ObjectManager.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  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 "ConnectionsPlacer.h"
  19. #include "TownPlacer.h"
  20. #include "MinePlacer.h"
  21. #include "QuestArtifactPlacer.h"
  22. #include "../../CCreatureHandler.h"
  23. #include "../../mapObjectConstructors/AObjectTypeHandler.h"
  24. #include "../../mapObjectConstructors/CObjectClassesHandler.h"
  25. #include "../../mapObjects/CGCreature.h"
  26. #include "../../mapping/CMap.h"
  27. #include "../../mapping/CMapEditManager.h"
  28. #include "../Functions.h"
  29. #include "../RmgObject.h"
  30. #include <vstd/RNG.h>
  31. VCMI_LIB_NAMESPACE_BEGIN
  32. void ObjectManager::process()
  33. {
  34. zone.fractalize();
  35. createRequiredObjects();
  36. }
  37. void ObjectManager::init()
  38. {
  39. DEPENDENCY(WaterAdopter);
  40. //Monoliths can be placed by other zone, too
  41. // Consider only connected zones
  42. auto id = zone.getId();
  43. std::set<TRmgTemplateZoneId> connectedZones;
  44. for(const auto & c : map.getMapGenOptions().getMapTemplate()->getConnectedZoneIds())
  45. {
  46. // Only consider connected zones
  47. if (c.getZoneA() == id || c.getZoneB() == id)
  48. {
  49. connectedZones.insert(c.getZoneA());
  50. connectedZones.insert(c.getZoneB());
  51. }
  52. }
  53. auto zones = map.getZones();
  54. for (auto zoneId : connectedZones)
  55. {
  56. auto * cp = zones.at(zoneId)->getModificator<ConnectionsPlacer>();
  57. if (cp)
  58. {
  59. dependency(cp);
  60. }
  61. }
  62. DEPENDENCY(TownPlacer); //Only secondary towns
  63. DEPENDENCY(MinePlacer);
  64. POSTFUNCTION(RoadPlacer);
  65. createDistancesPriorityQueue();
  66. }
  67. void ObjectManager::createDistancesPriorityQueue()
  68. {
  69. const auto tiles = zone.areaPossible()->getTilesVector();
  70. RecursiveLock lock(externalAccessMutex);
  71. tilesByDistance.clear();
  72. for(const auto & tile : tiles)
  73. {
  74. tilesByDistance.push(std::make_pair(tile, map.getNearestObjectDistance(tile)));
  75. }
  76. }
  77. void ObjectManager::addRequiredObject(const RequiredObjectInfo & info)
  78. {
  79. RecursiveLock lock(externalAccessMutex);
  80. requiredObjects.emplace_back(info);
  81. }
  82. void ObjectManager::addCloseObject(const RequiredObjectInfo & info)
  83. {
  84. RecursiveLock lock(externalAccessMutex);
  85. closeObjects.emplace_back(info);
  86. }
  87. void ObjectManager::addNearbyObject(const RequiredObjectInfo & info)
  88. {
  89. RecursiveLock lock(externalAccessMutex);
  90. nearbyObjects.emplace_back(info);
  91. }
  92. void ObjectManager::updateDistances(const rmg::Object & obj)
  93. {
  94. updateDistances([obj](const int3& tile) -> ui32
  95. {
  96. return obj.getArea().distanceSqr(tile); //optimization, only relative distance is interesting
  97. });
  98. }
  99. void ObjectManager::updateDistances(const int3 & pos)
  100. {
  101. updateDistances([pos](const int3& tile) -> ui32
  102. {
  103. return pos.dist2dSQ(tile); //optimization, only relative distance is interesting
  104. });
  105. }
  106. void ObjectManager::updateDistances(std::function<ui32(const int3 & tile)> distanceFunction)
  107. {
  108. // Workaround to avoid deadlock when accessed from other zone
  109. RecursiveLock lock(zone.areaMutex, std::try_to_lock);
  110. if (!lock.owns_lock())
  111. {
  112. // Unsolvable problem of mutual access
  113. return;
  114. }
  115. const auto tiles = zone.areaPossible()->getTilesVector();
  116. //RecursiveLock lock(externalAccessMutex);
  117. tilesByDistance.clear();
  118. for (const auto & tile : tiles) //don't need to mark distance for not possible tiles
  119. {
  120. ui32 d = distanceFunction(tile);
  121. map.setNearestObjectDistance(tile, std::min(static_cast<float>(d), map.getNearestObjectDistance(tile)));
  122. tilesByDistance.push(std::make_pair(tile, map.getNearestObjectDistance(tile)));
  123. }
  124. }
  125. const rmg::Area & ObjectManager::getVisitableArea() const
  126. {
  127. RecursiveLock lock(externalAccessMutex);
  128. return objectsVisitableArea;
  129. }
  130. std::vector<CGObjectInstance*> ObjectManager::getMines() const
  131. {
  132. std::vector<CGObjectInstance*> mines;
  133. RecursiveLock lock(externalAccessMutex);
  134. for(auto * object : objects)
  135. {
  136. if (object->ID == Obj::MINE)
  137. {
  138. mines.push_back(object);
  139. }
  140. }
  141. return mines;
  142. }
  143. int3 ObjectManager::findPlaceForObject(const rmg::Area & searchArea, rmg::Object & obj, const std::function<float(const int3)> & weightFunction, OptimizeType optimizer) const
  144. {
  145. float bestWeight = 0.f;
  146. int3 result(-1, -1, -1);
  147. //Blocked area might not cover object position if it has an offset from (0,0)
  148. auto outsideTheMap = [this, &obj]() -> bool
  149. {
  150. for (const auto& oi : obj.instances())
  151. {
  152. if (!map.isOnMap(oi->getPosition(true)))
  153. {
  154. return true;
  155. }
  156. }
  157. return false;
  158. };
  159. if(optimizer & OptimizeType::DISTANCE)
  160. {
  161. // Do not add or remove tiles while we iterate on them
  162. //RecursiveLock lock(externalAccessMutex);
  163. auto open = tilesByDistance;
  164. while(!open.empty())
  165. {
  166. auto node = open.top();
  167. open.pop();
  168. int3 tile = node.first;
  169. if(!searchArea.contains(tile))
  170. continue;
  171. obj.setPosition(tile);
  172. if (obj.getVisibleTop().y < 0)
  173. continue;
  174. if(!searchArea.contains(obj.getArea()) || !searchArea.overlap(obj.getAccessibleArea()))
  175. continue;
  176. if (outsideTheMap())
  177. continue;
  178. float weight = weightFunction(tile);
  179. if(weight > bestWeight)
  180. {
  181. bestWeight = weight;
  182. result = tile;
  183. if(!(optimizer & OptimizeType::WEIGHT))
  184. break;
  185. }
  186. }
  187. }
  188. else
  189. {
  190. for(const auto & tile : searchArea.getTilesVector())
  191. {
  192. obj.setPosition(tile);
  193. if (obj.getVisibleTop().y < 0)
  194. continue;
  195. if(!searchArea.contains(obj.getArea()) || !searchArea.overlap(obj.getAccessibleArea()))
  196. continue;
  197. if (outsideTheMap())
  198. continue;
  199. float weight = weightFunction(tile);
  200. if(weight > bestWeight)
  201. {
  202. bestWeight = weight;
  203. result = tile;
  204. if(!(optimizer & OptimizeType::WEIGHT))
  205. break;
  206. }
  207. }
  208. }
  209. if(result.isValid())
  210. obj.setPosition(result);
  211. return result;
  212. }
  213. int3 ObjectManager::findPlaceForObject(const rmg::Area & searchArea, rmg::Object & obj, si32 min_dist, OptimizeType optimizer) const
  214. {
  215. return findPlaceForObject(searchArea, obj, [this, min_dist, &obj](const int3 & tile)
  216. {
  217. auto ti = map.getTileInfo(tile);
  218. float dist = ti.getNearestObjectDistance();
  219. if(dist < min_dist)
  220. return -1.f;
  221. for(const auto & t : obj.getArea().getTilesVector())
  222. {
  223. auto localDist = map.getTileInfo(t).getNearestObjectDistance();
  224. if (localDist < min_dist)
  225. {
  226. return -1.f;
  227. }
  228. else
  229. {
  230. vstd::amin(dist, localDist); //Evaluate object tile which will be closest to another object
  231. }
  232. }
  233. return dist;
  234. }, optimizer);
  235. }
  236. rmg::Path ObjectManager::placeAndConnectObject(const rmg::Area & searchArea, rmg::Object & obj, si32 min_dist, bool isGuarded, bool onlyStraight, OptimizeType optimizer) const
  237. {
  238. return placeAndConnectObject(searchArea, obj, [this, min_dist, &obj](const int3 & tile)
  239. {
  240. float bestDistance = 10e9;
  241. for(const auto & t : obj.getArea().getTilesVector())
  242. {
  243. float distance = map.getTileInfo(t).getNearestObjectDistance();
  244. if(distance < min_dist)
  245. return -1.f;
  246. else
  247. vstd::amin(bestDistance, distance);
  248. }
  249. rmg::Area perimeter;
  250. rmg::Area areaToBlock;
  251. if (obj.isGuarded())
  252. {
  253. auto guardedArea = obj.instances().back()->getAccessibleArea();
  254. guardedArea.add(obj.instances().back()->getVisitablePosition());
  255. areaToBlock = obj.getAccessibleArea(true);
  256. areaToBlock.subtract(guardedArea);
  257. if (!areaToBlock.empty())
  258. {
  259. perimeter = areaToBlock;
  260. perimeter.unite(areaToBlock.getBorderOutside());
  261. //We could have added border around guard
  262. perimeter.subtract(guardedArea);
  263. }
  264. }
  265. else
  266. {
  267. perimeter = obj.getArea();
  268. perimeter.subtract(obj.getAccessibleArea());
  269. if (!perimeter.empty())
  270. {
  271. perimeter.unite(perimeter.getBorderOutside());
  272. perimeter.subtract(obj.getAccessibleArea());
  273. }
  274. }
  275. //Check if perimeter of the object intersects with more than one blocked areas
  276. auto tiles = perimeter.getTiles();
  277. vstd::erase_if(tiles, [this](const int3& tile) -> bool
  278. {
  279. //Out-of-map area also is an obstacle
  280. if (!map.isOnMap(tile))
  281. return false;
  282. return !(map.isBlocked(tile) || map.isUsed(tile));
  283. });
  284. if (!tiles.empty())
  285. {
  286. rmg::Area border(tiles);
  287. border.subtract(areaToBlock);
  288. if (!border.connected())
  289. {
  290. //We don't want to connect two blocked areas to create impassable obstacle
  291. return -1.f;
  292. }
  293. }
  294. return bestDistance;
  295. }, isGuarded, onlyStraight, optimizer);
  296. }
  297. 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
  298. {
  299. int3 pos;
  300. auto possibleArea = searchArea;
  301. auto cachedArea = zone.areaForRoads();
  302. while(true)
  303. {
  304. pos = findPlaceForObject(possibleArea, obj, weightFunction, optimizer);
  305. if(!pos.isValid())
  306. {
  307. return rmg::Path::invalid();
  308. }
  309. possibleArea.erase(pos); //do not place again at this point
  310. auto accessibleArea = obj.getAccessibleArea(isGuarded) * cachedArea;
  311. //we should exclude tiles which will be covered
  312. if(isGuarded)
  313. {
  314. const auto & guardedArea = obj.instances().back()->getAccessibleArea();
  315. accessibleArea.intersect(guardedArea);
  316. accessibleArea.add(obj.instances().back()->getPosition(true));
  317. }
  318. rmg::Area subArea;
  319. if (isGuarded)
  320. {
  321. const auto & guardedArea = obj.instances().back()->getAccessibleArea();
  322. const auto & unguardedArea = obj.getAccessibleArea(isGuarded);
  323. subArea = cachedArea.getSubarea([guardedArea, unguardedArea, obj](const int3 & t)
  324. {
  325. if(unguardedArea.contains(t) && !guardedArea.contains(t))
  326. return false;
  327. //guard position is always target
  328. if(obj.instances().back()->getPosition(true) == t)
  329. return true;
  330. return !obj.getArea().contains(t);
  331. });
  332. }
  333. else
  334. {
  335. subArea = cachedArea.getSubarea([obj](const int3 & t)
  336. {
  337. return !obj.getArea().contains(t);
  338. });
  339. }
  340. auto path = zone.searchPath(accessibleArea, onlyStraight, subArea);
  341. if(path.valid())
  342. {
  343. return path;
  344. }
  345. }
  346. }
  347. bool ObjectManager::createMonoliths()
  348. {
  349. // Special case for Junction zone only
  350. logGlobal->trace("Creating Monoliths");
  351. for(const auto & objInfo : requiredObjects)
  352. {
  353. if (objInfo.obj->ID != Obj::MONOLITH_TWO_WAY)
  354. {
  355. continue;
  356. }
  357. rmg::Object rmgObject(objInfo.obj);
  358. rmgObject.setTemplate(zone.getTerrainType(), zone.getRand());
  359. bool guarded = addGuard(rmgObject, objInfo.guardStrength, true);
  360. Zone::Lock lock(zone.areaMutex);
  361. auto path = placeAndConnectObject(zone.areaPossible().get(), rmgObject, 3, guarded, false, OptimizeType::DISTANCE);
  362. if(!path.valid())
  363. {
  364. logGlobal->error("Failed to fill zone %d due to lack of space", zone.getId());
  365. return false;
  366. }
  367. // Object must be placed first so that curved path won't go through occupied tiles
  368. placeObject(rmgObject, guarded, true, objInfo.createRoad);
  369. // Once it can be created, replace with curved path.
  370. replaceWithCurvedPath(path, zone, rmgObject.getVisitablePosition());
  371. zone.connectPath(path);
  372. }
  373. vstd::erase_if(requiredObjects, [](const auto & objInfo)
  374. {
  375. return objInfo.obj->ID == Obj::MONOLITH_TWO_WAY;
  376. });
  377. return true;
  378. }
  379. bool ObjectManager::createRequiredObjects()
  380. {
  381. logGlobal->trace("Creating required objects");
  382. RecursiveLock lock(externalAccessMutex); //In case someone adds more objects
  383. for(const auto & objInfo : requiredObjects)
  384. {
  385. rmg::Object rmgObject(objInfo.obj);
  386. rmgObject.setTemplate(zone.getTerrainType(), zone.getRand());
  387. bool guarded = addGuard(rmgObject, objInfo.guardStrength, (objInfo.obj->ID == Obj::MONOLITH_TWO_WAY));
  388. Zone::Lock lock(zone.areaMutex);
  389. auto path = placeAndConnectObject(zone.areaPossible().get(), rmgObject, 3, guarded, false, OptimizeType::DISTANCE);
  390. if(!path.valid())
  391. {
  392. logGlobal->error("Failed to fill zone %d due to lack of space", zone.getId());
  393. return false;
  394. }
  395. placeObject(rmgObject, guarded, true, objInfo.createRoad);
  396. if (objInfo.createRoad)
  397. {
  398. // Once valid path can be created, replace with curved path
  399. replaceWithCurvedPath(path, zone, rmgObject.getVisitablePosition());
  400. }
  401. zone.connectPath(path);
  402. for(const auto & nearby : nearbyObjects)
  403. {
  404. if(nearby.nearbyTarget != nearby.obj.get())
  405. continue;
  406. rmg::Object rmgNearObject(nearby.obj);
  407. rmg::Area possibleArea(rmgObject.instances().front()->getBlockedArea().getBorderOutside());
  408. possibleArea.intersect(zone.areaPossible().get());
  409. if(possibleArea.empty())
  410. {
  411. rmgNearObject.clear();
  412. continue;
  413. }
  414. rmgNearObject.setPosition(*RandomGeneratorUtil::nextItem(possibleArea.getTiles(), zone.getRand()));
  415. placeObject(rmgNearObject, false, false, nearby.createRoad);
  416. }
  417. }
  418. for(const auto & objInfo : closeObjects)
  419. {
  420. Zone::Lock lock(zone.areaMutex);
  421. rmg::Object rmgObject(objInfo.obj);
  422. rmgObject.setTemplate(zone.getTerrainType(), zone.getRand());
  423. bool guarded = addGuard(rmgObject, objInfo.guardStrength, (objInfo.obj->ID == Obj::MONOLITH_TWO_WAY));
  424. auto path = placeAndConnectObject(zone.areaPossible().get(), rmgObject,
  425. [this, &rmgObject](const int3 & tile)
  426. {
  427. float dist = rmgObject.getArea().distanceSqr(zone.getPos());
  428. dist *= (dist > 12.f * 12.f) ? 10.f : 1.f; //tiles closer 12 are preferable
  429. dist = 1000000.f - dist; //some big number
  430. return dist + map.getNearestObjectDistance(tile);
  431. }, guarded, false, OptimizeType::WEIGHT);
  432. if(!path.valid())
  433. {
  434. logGlobal->error("Failed to fill zone %d due to lack of space", zone.getId());
  435. return false;
  436. }
  437. zone.connectPath(path);
  438. placeObject(rmgObject, guarded, true);
  439. }
  440. for(const auto & nearby : nearbyObjects)
  441. {
  442. auto * targetObject = nearby.nearbyTarget;
  443. if (!targetObject || !targetObject->appearance)
  444. {
  445. continue;
  446. }
  447. rmg::Object rmgNearObject(nearby.obj);
  448. std::set<int3> blockedArea = targetObject->getBlockedPos();
  449. rmg::Area areaForObject(rmg::Area(rmg::Tileset(blockedArea.begin(), blockedArea.end())).getBorderOutside());
  450. areaForObject.intersect(zone.areaPossible().get());
  451. if(areaForObject.empty())
  452. {
  453. rmgNearObject.clear();
  454. continue;
  455. }
  456. rmgNearObject.setPosition(*RandomGeneratorUtil::nextItem(areaForObject.getTiles(), zone.getRand()));
  457. placeObject(rmgNearObject, false, false);
  458. auto path = zone.searchPath(rmgNearObject.getVisitablePosition(), false);
  459. if (path.valid())
  460. {
  461. zone.connectPath(path);
  462. }
  463. else
  464. {
  465. for (auto* instance : rmgNearObject.instances())
  466. {
  467. logGlobal->error("Failed to connect nearby object %s at %s",
  468. instance->object().getObjectName(), instance->getPosition(true).toString());
  469. mapProxy->removeObject(&instance->object());
  470. }
  471. }
  472. }
  473. //create object on specific positions
  474. //TODO: implement guards
  475. for (const auto &objInfo : instantObjects) //Unused ATM
  476. {
  477. rmg::Object rmgObject(objInfo.obj);
  478. rmgObject.setPosition(objInfo.pos);
  479. placeObject(rmgObject, false, false);
  480. }
  481. requiredObjects.clear();
  482. closeObjects.clear();
  483. nearbyObjects.clear();
  484. instantObjects.clear();
  485. return true;
  486. }
  487. void ObjectManager::placeObject(rmg::Object & object, bool guarded, bool updateDistance, bool createRoad/* = false*/)
  488. {
  489. if (object.instances().size() == 1 && object.instances().front()->object().ID == Obj::MONSTER)
  490. {
  491. //Fix for HoTA offset - lonely guards
  492. auto monster = object.instances().front();
  493. if (!monster->object().appearance)
  494. {
  495. //Needed to determine visitable offset
  496. monster->setAnyTemplate(zone.getRand());
  497. }
  498. object.getPosition();
  499. auto visitableOffset = monster->object().getVisitableOffset();
  500. auto fixedPos = monster->getPosition(true) + visitableOffset;
  501. //Do not place guard outside the map
  502. vstd::abetween(fixedPos.x, visitableOffset.x, map.width() - 1);
  503. vstd::abetween(fixedPos.y, visitableOffset.y, map.height() - 1);
  504. int3 parentOffset = monster->getPosition(true) - monster->getPosition(false);
  505. monster->setPosition(fixedPos - parentOffset);
  506. }
  507. object.finalize(map, zone.getRand());
  508. {
  509. Zone::Lock lock(zone.areaMutex);
  510. zone.areaPossible()->subtract(object.getArea());
  511. bool keepVisitable = object.isVisitable() && zone.freePaths()->contains(object.getVisitablePosition());
  512. zone.freePaths()->subtract(object.getArea()); //just to avoid areas overlapping
  513. zone.areaUsed()->unite(object.getArea());
  514. if (keepVisitable)
  515. {
  516. zone.freePaths()->add(object.getVisitablePosition());
  517. zone.areaUsed()->erase(object.getVisitablePosition());
  518. }
  519. if(guarded) //We assume the monster won't be guarded
  520. {
  521. auto guardedArea = object.instances().back()->getAccessibleArea();
  522. if (object.isVisitable())
  523. {
  524. guardedArea.add(object.instances().back()->getVisitablePosition());
  525. }
  526. auto areaToBlock = object.getAccessibleArea(true);
  527. areaToBlock.subtract(guardedArea);
  528. zone.areaPossible()->subtract(areaToBlock);
  529. for(const auto & i : areaToBlock.getTilesVector())
  530. if(map.isOnMap(i) && map.isPossible(i))
  531. map.setOccupied(i, ETileType::BLOCKED);
  532. }
  533. }
  534. if (updateDistance)
  535. {
  536. //Update distances in every adjacent zone (including this one) in case of wide connection
  537. std::set<TRmgTemplateZoneId> adjacentZones;
  538. auto objectArea = object.getArea();
  539. objectArea.unite(objectArea.getBorderOutside());
  540. for (auto tile : objectArea.getTilesVector())
  541. {
  542. if (map.isOnMap(tile))
  543. {
  544. adjacentZones.insert(map.getZoneID(tile));
  545. }
  546. }
  547. for (auto id : adjacentZones)
  548. {
  549. auto otherZone = map.getZones().at(id);
  550. if ((otherZone->getType() == ETemplateZoneType::WATER) == (zone.getType() == ETemplateZoneType::WATER))
  551. {
  552. // Do not update other zone if only one is water
  553. auto manager = otherZone->getModificator<ObjectManager>();
  554. if (manager)
  555. {
  556. manager->updateDistances(object);
  557. }
  558. }
  559. }
  560. }
  561. // TODO: Add multiple tiles in one operation to avoid multiple invalidation
  562. for(auto * instance : object.instances())
  563. {
  564. if (instance->object().isVisitable())
  565. {
  566. objectsVisitableArea.add(instance->getVisitablePosition());
  567. }
  568. objects.push_back(&instance->object());
  569. if(auto * rp = zone.getModificator<RoadPlacer>())
  570. {
  571. if (instance->object().blockVisit && !instance->object().removable)
  572. {
  573. //Cannot be trespassed (Corpse)
  574. continue;
  575. }
  576. else if(instance->object().appearance->isVisitableFromTop())
  577. {
  578. //Passable objects
  579. rp->areaForRoads().add(instance->getVisitablePosition());
  580. }
  581. else if(!instance->object().appearance->isVisitableFromTop())
  582. {
  583. // Do not route road behind visitable tile
  584. auto borderAbove = instance->getBorderAbove();
  585. rp->areaIsolated().unite(borderAbove);
  586. }
  587. if (object.isGuarded())
  588. {
  589. // Do not route roads through guarded objects
  590. rp->areaVisitable().add(instance->getVisitablePosition());
  591. }
  592. }
  593. switch (instance->object().ID.toEnum())
  594. {
  595. case Obj::RANDOM_TREASURE_ART:
  596. case Obj::RANDOM_MINOR_ART: //In OH3 quest artifacts have higher value than normal arts
  597. case Obj::RANDOM_RESOURCE:
  598. {
  599. if (auto * qap = zone.getModificator<QuestArtifactPlacer>())
  600. {
  601. qap->rememberPotentialArtifactToReplace(&instance->object());
  602. }
  603. break;
  604. }
  605. default:
  606. break;
  607. }
  608. }
  609. if (createRoad)
  610. {
  611. if (auto* m = zone.getModificator<RoadPlacer>())
  612. m->addRoadNode(object.instances().front()->getVisitablePosition());
  613. }
  614. //TODO: Add road node to these objects:
  615. /*
  616. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  617. case Obj::RANDOM_TOWN:
  618. case Obj::MONOLITH_ONE_WAY_EXIT:
  619. */
  620. switch(object.instances().front()->object().ID.toEnum())
  621. {
  622. case Obj::WATER_WHEEL:
  623. if (auto* m = zone.getModificator<RiverPlacer>())
  624. m->addRiverNode(object.instances().front()->getVisitablePosition());
  625. break;
  626. default:
  627. break;
  628. }
  629. }
  630. std::shared_ptr<CGCreature> ObjectManager::chooseGuard(si32 strength, bool zoneGuard)
  631. {
  632. //precalculate actual (randomized) monster strength based on this post
  633. //http://forum.vcmi.eu/viewtopic.php?p=12426#12426
  634. if(!zoneGuard && zone.monsterStrength == EMonsterStrength::ZONE_NONE)
  635. return nullptr; //no guards inside this zone except for zone guards
  636. int mapMonsterStrength = map.getMapGenOptions().getMonsterStrength();
  637. int monsterStrength = (zoneGuard ? 0 : zone.monsterStrength - EMonsterStrength::ZONE_NORMAL) + mapMonsterStrength - 1; //array index from 0 to 4
  638. static const std::array<int, 5> value1{2500, 1500, 1000, 500, 0};
  639. static const std::array<int, 5> value2{7500, 7500, 7500, 5000, 5000};
  640. static const std::array<float, 5> multiplier1{0.5, 0.75, 1.0, 1.5, 1.5};
  641. static const std::array<float, 5> multiplier2{0.5, 0.75, 1.0, 1.0, 1.5};
  642. int strength1 = static_cast<int>(std::max(0.f, (strength - value1.at(monsterStrength)) * multiplier1.at(monsterStrength)));
  643. int strength2 = static_cast<int>(std::max(0.f, (strength - value2.at(monsterStrength)) * multiplier2.at(monsterStrength)));
  644. strength = strength1 + strength2;
  645. if (strength < generator.getConfig().minGuardStrength)
  646. return nullptr; //no guard at all
  647. CreatureID creId = CreatureID::NONE;
  648. int amount = 0;
  649. std::vector<CreatureID> possibleCreatures;
  650. for(auto const & cre : LIBRARY->creh->objects)
  651. {
  652. if(cre->special)
  653. continue;
  654. if(!cre->getAIValue()) //bug #2681
  655. continue;
  656. if(!vstd::contains(zone.getMonsterTypes(), cre->getFactionID()))
  657. continue;
  658. 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
  659. {
  660. possibleCreatures.push_back(cre->getId());
  661. }
  662. }
  663. if(!possibleCreatures.empty())
  664. {
  665. creId = *RandomGeneratorUtil::nextItem(possibleCreatures, zone.getRand());
  666. amount = strength / creId.toEntity(LIBRARY)->getAIValue();
  667. if (amount >= 4)
  668. amount = static_cast<int>(amount * zone.getRand().nextDouble(0.75, 1.25));
  669. }
  670. else //just pick any available creature
  671. {
  672. creId = CreatureID::AZURE_DRAGON; //Azure Dragon
  673. amount = strength / creId.toEntity(LIBRARY)->getAIValue();
  674. }
  675. auto guardFactory = LIBRARY->objtypeh->getHandlerFor(Obj::MONSTER, creId);
  676. auto guard = std::dynamic_pointer_cast<CGCreature>(guardFactory->create(map.mapInstance->cb, nullptr));
  677. guard->character = CGCreature::HOSTILE;
  678. auto hlp = std::make_unique<CStackInstance>(creId, amount);
  679. //will be set during initialization
  680. guard->putStack(SlotID(0), std::move(hlp));
  681. return guard;
  682. }
  683. bool ObjectManager::addGuard(rmg::Object & object, si32 strength, bool zoneGuard)
  684. {
  685. auto guard = chooseGuard(strength, zoneGuard);
  686. if(!guard)
  687. return false;
  688. // Prefer non-blocking tiles, if any
  689. auto entrableArea = object.getEntrableArea();
  690. if (entrableArea.empty())
  691. {
  692. entrableArea.add(object.getVisitablePosition());
  693. }
  694. rmg::Area entrableBorder = entrableArea.getBorderOutside();
  695. auto accessibleArea = object.getAccessibleArea();
  696. accessibleArea.erase_if([&](const int3 & tile)
  697. {
  698. return !entrableBorder.contains(tile);
  699. });
  700. if(accessibleArea.empty())
  701. return false;
  702. auto guardTiles = accessibleArea.getTilesVector();
  703. auto guardPos = *std::min_element(guardTiles.begin(), guardTiles.end(), [&object](const int3 & l, const int3 & r)
  704. {
  705. auto p = object.getVisitablePosition();
  706. if(l.y > r.y)
  707. return true;
  708. if(l.y == r.y)
  709. return abs(l.x - p.x) < abs(r.x - p.x);
  710. return false;
  711. });
  712. auto & instance = object.addInstance(guard);
  713. instance.setAnyTemplate(zone.getRand()); //terrain is irrelevant for monsters, but monsters need some template now
  714. //Fix HoTA monsters with offset template
  715. auto visitableOffset = instance.object().getVisitableOffset();
  716. auto fixedPos = guardPos - object.getPosition() + visitableOffset;
  717. instance.setPosition(fixedPos);
  718. return true;
  719. }
  720. RequiredObjectInfo::RequiredObjectInfo():
  721. obj(nullptr),
  722. nearbyTarget(nullptr),
  723. guardStrength(0),
  724. createRoad(true)
  725. {}
  726. RequiredObjectInfo::RequiredObjectInfo(std::shared_ptr<CGObjectInstance> obj, ui32 guardStrength, bool createRoad, CGObjectInstance* nearbyTarget):
  727. obj(obj),
  728. nearbyTarget(nearbyTarget),
  729. guardStrength(guardStrength),
  730. createRoad(createRoad)
  731. {}
  732. VCMI_LIB_NAMESPACE_END