ObjectManager.cpp 22 KB

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