ObjectManager.cpp 24 KB

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