ObjectManager.cpp 23 KB

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