CRmgTemplateZone.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  1. /*
  2. * CRmgTemplateZone.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 "CRmgTemplateZone.h"
  12. #include "../mapping/CMapEditManager.h"
  13. #include "../mapping/CMap.h"
  14. #include "../VCMI_Lib.h"
  15. #include "../CTownHandler.h"
  16. #include "../CCreatureHandler.h"
  17. class CMap;
  18. class CMapEditManager;
  19. CRmgTemplateZone::CTownInfo::CTownInfo() : townCount(0), castleCount(0), townDensity(0), castleDensity(0)
  20. {
  21. }
  22. int CRmgTemplateZone::CTownInfo::getTownCount() const
  23. {
  24. return townCount;
  25. }
  26. void CRmgTemplateZone::CTownInfo::setTownCount(int value)
  27. {
  28. if(value < 0)
  29. throw rmgException("Negative value for town count not allowed.");
  30. townCount = value;
  31. }
  32. int CRmgTemplateZone::CTownInfo::getCastleCount() const
  33. {
  34. return castleCount;
  35. }
  36. void CRmgTemplateZone::CTownInfo::setCastleCount(int value)
  37. {
  38. if(value < 0)
  39. throw rmgException("Negative value for castle count not allowed.");
  40. castleCount = value;
  41. }
  42. int CRmgTemplateZone::CTownInfo::getTownDensity() const
  43. {
  44. return townDensity;
  45. }
  46. void CRmgTemplateZone::CTownInfo::setTownDensity(int value)
  47. {
  48. if(value < 0)
  49. throw rmgException("Negative value for town density not allowed.");
  50. townDensity = value;
  51. }
  52. int CRmgTemplateZone::CTownInfo::getCastleDensity() const
  53. {
  54. return castleDensity;
  55. }
  56. void CRmgTemplateZone::CTownInfo::setCastleDensity(int value)
  57. {
  58. if(value < 0)
  59. throw rmgException("Negative value for castle density not allowed.");
  60. castleDensity = value;
  61. }
  62. CTileInfo::CTileInfo():nearestObjectDistance(INT_MAX), terrain(ETerrainType::WRONG)
  63. {
  64. occupied = ETileType::POSSIBLE; //all tiles are initially possible to place objects or passages
  65. }
  66. int CTileInfo::getNearestObjectDistance() const
  67. {
  68. return nearestObjectDistance;
  69. }
  70. void CTileInfo::setNearestObjectDistance(int value)
  71. {
  72. nearestObjectDistance = std::max(0, value); //never negative (or unitialized)
  73. }
  74. bool CTileInfo::shouldBeBlocked() const
  75. {
  76. return occupied == ETileType::BLOCKED;
  77. }
  78. bool CTileInfo::isBlocked() const
  79. {
  80. return occupied == ETileType::BLOCKED || occupied == ETileType::USED;
  81. }
  82. bool CTileInfo::isPossible() const
  83. {
  84. return occupied == ETileType::POSSIBLE;
  85. }
  86. bool CTileInfo::isFree() const
  87. {
  88. return occupied == ETileType::FREE;
  89. }
  90. void CTileInfo::setOccupied(ETileType::ETileType value)
  91. {
  92. occupied = value;
  93. }
  94. ETerrainType CTileInfo::getTerrainType() const
  95. {
  96. return terrain;
  97. }
  98. void CTileInfo::setTerrainType(ETerrainType value)
  99. {
  100. terrain = value;
  101. }
  102. CRmgTemplateZone::CRmgTemplateZone() : id(0), type(ETemplateZoneType::PLAYER_START), size(1),
  103. townsAreSameType(false), matchTerrainToTown(true)
  104. {
  105. townTypes = getDefaultTownTypes();
  106. terrainTypes = getDefaultTerrainTypes();
  107. }
  108. TRmgTemplateZoneId CRmgTemplateZone::getId() const
  109. {
  110. return id;
  111. }
  112. void CRmgTemplateZone::setId(TRmgTemplateZoneId value)
  113. {
  114. if(value <= 0)
  115. throw rmgException(boost::to_string(boost::format("Zone %d id should be greater than 0.") %id));
  116. id = value;
  117. }
  118. ETemplateZoneType::ETemplateZoneType CRmgTemplateZone::getType() const
  119. {
  120. return type;
  121. }
  122. void CRmgTemplateZone::setType(ETemplateZoneType::ETemplateZoneType value)
  123. {
  124. type = value;
  125. }
  126. int CRmgTemplateZone::getSize() const
  127. {
  128. return size;
  129. }
  130. void CRmgTemplateZone::setSize(int value)
  131. {
  132. if(value <= 0)
  133. throw rmgException(boost::to_string(boost::format("Zone %d size needs to be greater than 0.") % id));
  134. size = value;
  135. }
  136. boost::optional<int> CRmgTemplateZone::getOwner() const
  137. {
  138. return owner;
  139. }
  140. void CRmgTemplateZone::setOwner(boost::optional<int> value)
  141. {
  142. if(!(*value >= 0 && *value <= PlayerColor::PLAYER_LIMIT_I))
  143. throw rmgException(boost::to_string(boost::format ("Owner of zone %d has to be in range 0 to max player count.") %id));
  144. owner = value;
  145. }
  146. const CRmgTemplateZone::CTownInfo & CRmgTemplateZone::getPlayerTowns() const
  147. {
  148. return playerTowns;
  149. }
  150. void CRmgTemplateZone::setPlayerTowns(const CTownInfo & value)
  151. {
  152. playerTowns = value;
  153. }
  154. const CRmgTemplateZone::CTownInfo & CRmgTemplateZone::getNeutralTowns() const
  155. {
  156. return neutralTowns;
  157. }
  158. void CRmgTemplateZone::setNeutralTowns(const CTownInfo & value)
  159. {
  160. neutralTowns = value;
  161. }
  162. bool CRmgTemplateZone::getTownsAreSameType() const
  163. {
  164. return townsAreSameType;
  165. }
  166. void CRmgTemplateZone::setTownsAreSameType(bool value)
  167. {
  168. townsAreSameType = value;
  169. }
  170. const std::set<TFaction> & CRmgTemplateZone::getTownTypes() const
  171. {
  172. return townTypes;
  173. }
  174. void CRmgTemplateZone::setTownTypes(const std::set<TFaction> & value)
  175. {
  176. townTypes = value;
  177. }
  178. std::set<TFaction> CRmgTemplateZone::getDefaultTownTypes() const
  179. {
  180. std::set<TFaction> defaultTowns;
  181. auto towns = VLC->townh->getDefaultAllowed();
  182. for(int i = 0; i < towns.size(); ++i)
  183. {
  184. if(towns[i]) defaultTowns.insert(i);
  185. }
  186. return defaultTowns;
  187. }
  188. bool CRmgTemplateZone::getMatchTerrainToTown() const
  189. {
  190. return matchTerrainToTown;
  191. }
  192. void CRmgTemplateZone::setMatchTerrainToTown(bool value)
  193. {
  194. matchTerrainToTown = value;
  195. }
  196. const std::set<ETerrainType> & CRmgTemplateZone::getTerrainTypes() const
  197. {
  198. return terrainTypes;
  199. }
  200. void CRmgTemplateZone::setTerrainTypes(const std::set<ETerrainType> & value)
  201. {
  202. assert(value.find(ETerrainType::WRONG) == value.end() && value.find(ETerrainType::BORDER) == value.end() &&
  203. value.find(ETerrainType::WATER) == value.end() && value.find(ETerrainType::ROCK) == value.end());
  204. terrainTypes = value;
  205. }
  206. std::set<ETerrainType> CRmgTemplateZone::getDefaultTerrainTypes() const
  207. {
  208. std::set<ETerrainType> terTypes;
  209. static const ETerrainType::EETerrainType allowedTerTypes[] = { ETerrainType::DIRT, ETerrainType::SAND, ETerrainType::GRASS, ETerrainType::SNOW,
  210. ETerrainType::SWAMP, ETerrainType::ROUGH, ETerrainType::SUBTERRANEAN, ETerrainType::LAVA };
  211. for(auto & allowedTerType : allowedTerTypes) terTypes.insert(allowedTerType);
  212. return terTypes;
  213. }
  214. boost::optional<TRmgTemplateZoneId> CRmgTemplateZone::getTerrainTypeLikeZone() const
  215. {
  216. return terrainTypeLikeZone;
  217. }
  218. void CRmgTemplateZone::setTerrainTypeLikeZone(boost::optional<TRmgTemplateZoneId> value)
  219. {
  220. terrainTypeLikeZone = value;
  221. }
  222. boost::optional<TRmgTemplateZoneId> CRmgTemplateZone::getTownTypeLikeZone() const
  223. {
  224. return townTypeLikeZone;
  225. }
  226. void CRmgTemplateZone::setTownTypeLikeZone(boost::optional<TRmgTemplateZoneId> value)
  227. {
  228. townTypeLikeZone = value;
  229. }
  230. void CRmgTemplateZone::addConnection(TRmgTemplateZoneId otherZone)
  231. {
  232. connections.push_back (otherZone);
  233. }
  234. std::vector<TRmgTemplateZoneId> CRmgTemplateZone::getConnections() const
  235. {
  236. return connections;
  237. }
  238. float3 CRmgTemplateZone::getCenter() const
  239. {
  240. return center;
  241. }
  242. void CRmgTemplateZone::setCenter(const float3 &f)
  243. {
  244. //limit boundaries to (0,1) square
  245. center = float3 (std::min(std::max(f.x, 0.f), 1.f), std::min(std::max(f.y, 0.f), 1.f), f.z);
  246. }
  247. bool CRmgTemplateZone::pointIsIn(int x, int y)
  248. {
  249. return true;
  250. }
  251. int3 CRmgTemplateZone::getPos() const
  252. {
  253. return pos;
  254. }
  255. void CRmgTemplateZone::setPos(const int3 &Pos)
  256. {
  257. pos = Pos;
  258. }
  259. void CRmgTemplateZone::addTile (const int3 &pos)
  260. {
  261. tileinfo.insert(pos);
  262. }
  263. std::set<int3> CRmgTemplateZone::getTileInfo () const
  264. {
  265. return tileinfo;
  266. }
  267. void CRmgTemplateZone::createBorder(CMapGenerator* gen)
  268. {
  269. for (auto tile : tileinfo)
  270. {
  271. gen->foreach_neighbour (tile, [this, gen](int3 &pos)
  272. {
  273. if (!vstd::contains(this->tileinfo, pos))
  274. {
  275. gen->foreach_neighbour (pos, [this, gen](int3 &pos)
  276. {
  277. if (gen->isPossible(pos))
  278. gen->setOccupied (pos, ETileType::BLOCKED);
  279. });
  280. }
  281. });
  282. }
  283. }
  284. bool CRmgTemplateZone::crunchPath (CMapGenerator* gen, const int3 &src, const int3 &dst, TRmgTemplateZoneId zone)
  285. {
  286. /*
  287. make shortest path with free tiles, reachning dst or closest already free tile. Avoid blocks.
  288. do not leave zone border
  289. */
  290. bool result = false;
  291. bool end = false;
  292. int3 currentPos = src;
  293. float distance = currentPos.dist2dSQ (dst);
  294. while (!end)
  295. {
  296. if (currentPos == dst)
  297. break;
  298. auto lastDistance = distance;
  299. gen->foreach_neighbour (currentPos, [this, gen, &currentPos, dst, &distance, &result, &end](int3 &pos)
  300. {
  301. if (!result) //not sure if lambda is worth it...
  302. {
  303. if (pos == dst)
  304. {
  305. result = true;
  306. end = true;
  307. }
  308. if (pos.dist2dSQ (dst) < distance)
  309. {
  310. if (!gen->isBlocked(pos))
  311. {
  312. if (vstd::contains (tileinfo, pos))
  313. {
  314. if (gen->isPossible(pos))
  315. {
  316. gen->setOccupied (pos, ETileType::FREE);
  317. currentPos = pos;
  318. distance = currentPos.dist2dSQ (dst);
  319. }
  320. else if (gen->isFree(pos))
  321. {
  322. end = true;
  323. result = true;
  324. }
  325. else
  326. throw rmgException(boost::to_string(boost::format("Tile %s of uknown type found on path") % pos()));
  327. }
  328. }
  329. }
  330. }
  331. });
  332. if (!(result || distance < lastDistance)) //we do not advance, use more avdnaced pathfinding algorithm?
  333. {
  334. logGlobal->warnStream() << boost::format ("No tile closer than %s found on path from %s to %s") %currentPos %src %dst;
  335. break;
  336. }
  337. }
  338. return result;
  339. }
  340. void CRmgTemplateZone::addRequiredObject(CGObjectInstance * obj, si32 strength)
  341. {
  342. requiredObjects.push_back(std::make_pair(obj, strength));
  343. }
  344. void CRmgTemplateZone::addMonster(CMapGenerator* gen, int3 &pos, si32 strength)
  345. {
  346. //precalculate actual (randomized) monster strength based on this post
  347. //http://forum.vcmi.eu/viewtopic.php?p=12426#12426
  348. int zoneMonsterStrength = 0; //TODO: range -1..1 based on template settings
  349. int mapMonsterStrength = gen->mapGenOptions->getMonsterStrength();
  350. int monsterStrength = zoneMonsterStrength + mapMonsterStrength - 1; //array index from 0 to 4
  351. static const int value1[] = {2500, 1500, 1000, 500, 0};
  352. static const int value2[] = {7500, 7500, 7500, 5000, 5000};
  353. static const float multiplier1[] = {0.5, 0.75, 1.0, 1.5, 1.5};
  354. static const float multiplier2[] = {0.5, 0.75, 1.0, 1.0, 1.5};
  355. int strength1 = std::max(0.f, (strength - value1[monsterStrength]) * multiplier1[monsterStrength]);
  356. int strength2 = std::max(0.f, (strength - value2[monsterStrength]) * multiplier2[monsterStrength]);
  357. strength = strength1 + strength2;
  358. if (strength < 2000)
  359. return; //no guard at all
  360. CreatureID creId = CreatureID::NONE;
  361. int amount = 0;
  362. while (true)
  363. {
  364. creId = VLC->creh->pickRandomMonster(gen->rand);
  365. auto cre = VLC->creh->creatures[creId];
  366. if ((cre->AIValue * (cre->ammMin + cre->ammMax) / 2 < strength) && (strength < cre->AIValue * 100)) //at leats one full monster. size between minimum size of given stack and 100
  367. {
  368. amount = strength / cre->AIValue;
  369. if (amount >= 4)
  370. amount *= gen->rand.nextDouble(0.75, 1.25);
  371. break;
  372. }
  373. }
  374. auto guard = new CGCreature();
  375. guard->ID = Obj::MONSTER;
  376. guard->subID = creId;
  377. auto hlp = new CStackInstance(creId, amount);
  378. //will be set during initialization
  379. guard->putStack(SlotID(0), hlp);
  380. placeObject(gen, guard, pos);
  381. }
  382. bool CRmgTemplateZone::createTreasurePile (CMapGenerator* gen, int3 &pos)
  383. {
  384. //TODO: read treasure values from template
  385. const int maxValue = 5000;
  386. const int minValue = 1500;
  387. static const Res::ERes woodOre[] = {Res::ERes::WOOD, Res::ERes::ORE};
  388. static const Res::ERes preciousRes[] = {Res::ERes::CRYSTAL, Res::ERes::GEMS, Res::ERes::MERCURY, Res::ERes::SULFUR};
  389. static auto res_gen = gen->rand.getIntRange(Res::ERes::WOOD, Res::ERes::GOLD);
  390. int currentValue = 0;
  391. CGObjectInstance * object = nullptr;
  392. while (currentValue < minValue)
  393. {
  394. int remaining = maxValue - currentValue;
  395. int nextValue = gen->rand.nextInt (0.25f * remaining, remaining);
  396. if (nextValue >= 20000)
  397. {
  398. auto obj = new CGArtifact();
  399. obj->ID = Obj::RANDOM_RELIC_ART;
  400. obj->subID = 0;
  401. auto a = new CArtifactInstance(); //TODO: probably some refactoring could help here
  402. gen->map->addNewArtifactInstance(a);
  403. obj->storedArtifact = a;
  404. object = obj;
  405. currentValue += 20000;
  406. }
  407. else if (nextValue >= 10000)
  408. {
  409. auto obj = new CGArtifact();
  410. obj->ID = Obj::RANDOM_MAJOR_ART;
  411. obj->subID = 0;
  412. auto a = new CArtifactInstance();
  413. gen->map->addNewArtifactInstance(a);
  414. obj->storedArtifact = a;
  415. object = obj;
  416. currentValue += 10000;
  417. }
  418. else if (nextValue >= 5000)
  419. {
  420. auto obj = new CGArtifact();
  421. obj->ID = Obj::RANDOM_MINOR_ART;
  422. obj->subID = 0;
  423. auto a = new CArtifactInstance();
  424. gen->map->addNewArtifactInstance(a);
  425. obj->storedArtifact = a;
  426. object = obj;
  427. currentValue += 5000;
  428. }
  429. else if (nextValue >= 2000)
  430. {
  431. auto obj = new CGArtifact();
  432. obj->ID = Obj::RANDOM_TREASURE_ART;
  433. obj->subID = 0;
  434. auto a = new CArtifactInstance();
  435. gen->map->addNewArtifactInstance(a);
  436. obj->storedArtifact = a;
  437. object = obj;
  438. currentValue += 2000;
  439. }
  440. else if (nextValue >= 1500)
  441. {
  442. auto obj = new CGPickable();
  443. obj->ID = Obj::TREASURE_CHEST;
  444. obj->subID = 0;
  445. object = obj;
  446. currentValue += 1500;
  447. }
  448. else if (nextValue >= 1400)
  449. {
  450. auto obj = new CGResource();
  451. auto restype = static_cast<Res::ERes>(preciousRes[gen->rand.nextInt (0,3)]); //TODO: how about dedicated function to pick random element of array?
  452. obj->ID = Obj::RESOURCE;
  453. obj->subID = static_cast<si32>(restype);
  454. obj->amount = 0;
  455. object = obj;
  456. currentValue += 1400;
  457. }
  458. else if (nextValue >= 1000)
  459. {
  460. auto obj = new CGResource();
  461. auto restype = static_cast<Res::ERes>(woodOre[gen->rand.nextInt (0,1)]);
  462. obj->ID = Obj::RESOURCE;
  463. obj->subID = static_cast<si32>(restype);
  464. obj->amount = 0;
  465. object = obj;
  466. currentValue += 1000;
  467. }
  468. else if (nextValue >= 750)
  469. {
  470. auto obj = new CGResource();
  471. obj->ID = Obj::RESOURCE;
  472. obj->subID = static_cast<si32>(Res::ERes::GOLD);
  473. obj->amount = 0;
  474. object = obj;
  475. currentValue += 750;
  476. }
  477. else //no possible treasure left (should not happen)
  478. break;
  479. //TODO: generate actual zone and not just all objects on a pile
  480. placeObject(gen, object, pos);
  481. }
  482. if (object)
  483. {
  484. guardObject (gen, object, currentValue);
  485. return true;
  486. }
  487. else //we did not place eveyrthing successfully
  488. return false;
  489. }
  490. bool CRmgTemplateZone::fill(CMapGenerator* gen)
  491. {
  492. int townId = 0;
  493. if ((type == ETemplateZoneType::CPU_START) || (type == ETemplateZoneType::PLAYER_START))
  494. {
  495. logGlobal->infoStream() << "Preparing playing zone";
  496. int player_id = *owner - 1;
  497. auto & playerInfo = gen->map->players[player_id];
  498. if (playerInfo.canAnyonePlay())
  499. {
  500. PlayerColor player(player_id);
  501. auto town = new CGTownInstance();
  502. town->ID = Obj::TOWN;
  503. townId = gen->mapGenOptions->getPlayersSettings().find(player)->second.getStartingTown();
  504. if(townId == CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  505. townId = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand); // all possible towns, skip neutral
  506. town->subID = townId;
  507. town->tempOwner = player;
  508. town->builtBuildings.insert(BuildingID::FORT);
  509. town->builtBuildings.insert(BuildingID::DEFAULT);
  510. placeObject(gen, town, getPos() + town->getVisitableOffset()); //towns are big objects and should be centered around visitable position
  511. logGlobal->traceStream() << "Placed object";
  512. logGlobal->traceStream() << "Fill player info " << player_id;
  513. auto & playerInfo = gen->map->players[player_id];
  514. // Update player info
  515. playerInfo.allowedFactions.clear();
  516. playerInfo.allowedFactions.insert(town->subID);
  517. playerInfo.hasMainTown = true;
  518. playerInfo.posOfMainTown = town->pos - int3(2, 0, 0);
  519. playerInfo.generateHeroAtMainTown = true;
  520. //requiredObjects.push_back(town);
  521. std::vector<Res::ERes> required_mines;
  522. required_mines.push_back(Res::ERes::WOOD);
  523. required_mines.push_back(Res::ERes::ORE);
  524. for(const auto res : required_mines)
  525. {
  526. auto mine = new CGMine();
  527. mine->ID = Obj::MINE;
  528. mine->subID = static_cast<si32>(res);
  529. mine->producedResource = res;
  530. mine->producedQuantity = mine->defaultResProduction();
  531. addRequiredObject(mine);
  532. }
  533. }
  534. else
  535. {
  536. type = ETemplateZoneType::TREASURE;
  537. townId = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  538. logGlobal->infoStream() << "Skipping this zone cause no player";
  539. }
  540. }
  541. else //no player
  542. {
  543. townId = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  544. }
  545. //paint zone with matching terrain
  546. std::vector<int3> tiles;
  547. for (auto tile : tileinfo)
  548. {
  549. tiles.push_back (tile);
  550. }
  551. gen->editManager->getTerrainSelection().setSelection(tiles);
  552. gen->editManager->drawTerrain(VLC->townh->factions[townId]->nativeTerrain, &gen->rand);
  553. logGlobal->infoStream() << "Creating required objects";
  554. for(const auto &obj : requiredObjects)
  555. {
  556. int3 pos;
  557. logGlobal->traceStream() << "Looking for place";
  558. if ( ! findPlaceForObject(gen, obj.first, 3, pos))
  559. {
  560. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") %id;
  561. //TODO CLEANUP!
  562. return false;
  563. }
  564. logGlobal->traceStream() << "Place found";
  565. placeObject(gen, obj.first, pos);
  566. if (obj.second)
  567. {
  568. guardObject (gen, obj.first, obj.second);
  569. }
  570. }
  571. const double res_mindist = 5;
  572. //TODO: just placeholder to chekc for possible locations
  573. auto obj = new CGResource();
  574. obj->ID = Obj::RESOURCE;
  575. obj->subID = static_cast<si32>(Res::ERes::GOLD);
  576. obj->amount = 0;
  577. do {
  578. int3 pos;
  579. if ( ! findPlaceForObject(gen, obj, res_mindist, pos))
  580. {
  581. delete obj;
  582. break;
  583. }
  584. createTreasurePile (gen, pos);
  585. } while(true);
  586. auto sel = gen->editManager->getTerrainSelection();
  587. sel.clearSelection();
  588. for (auto tile : tileinfo)
  589. {
  590. //test code - block all the map to show paths clearly
  591. //if (gen->isPossible(tile))
  592. // gen->setOccupied(tile, ETileType::BLOCKED);
  593. if (gen->shouldBeBlocked(tile)) //fill tiles that should be blocked with obstacles
  594. {
  595. auto obj = new CGObjectInstance();
  596. obj->ID = static_cast<Obj>(130);
  597. obj->subID = 0;
  598. placeObject(gen, obj, tile);
  599. }
  600. }
  601. //logGlobal->infoStream() << boost::format("Filling %d with ROCK") % sel.getSelectedItems().size();
  602. //gen->editManager->drawTerrain(ETerrainType::ROCK, &gen->gen);
  603. logGlobal->infoStream() << boost::format ("Zone %d filled successfully") %id;
  604. return true;
  605. }
  606. bool CRmgTemplateZone::findPlaceForObject(CMapGenerator* gen, CGObjectInstance* obj, si32 min_dist, int3 &pos)
  607. {
  608. //we need object apperance to deduce free tiles
  609. if (obj->appearance.id == Obj::NO_OBJ)
  610. {
  611. auto templates = VLC->dobjinfo->pickCandidates(obj->ID, obj->subID, gen->map->getTile(getPos()).terType);
  612. if (templates.empty())
  613. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") %obj->ID %obj->subID %pos));
  614. obj->appearance = templates.front();
  615. }
  616. //si32 min_dist = sqrt(tileinfo.size()/density);
  617. int best_distance = 0;
  618. bool result = false;
  619. si32 w = gen->map->width;
  620. si32 h = gen->map->height;
  621. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  622. for(auto tile : tileinfo)
  623. {
  624. auto ti = gen->getTile(tile);
  625. auto dist = ti.getNearestObjectDistance();
  626. //avoid borders
  627. if ((tile.x < 3) || (w - tile.x < 3) || (tile.y < 3) || (h - tile.y < 3))
  628. continue;
  629. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  630. {
  631. bool allTilesAvailable = true;
  632. for (auto blockingTile : obj->getBlockedOffsets())
  633. {
  634. int3 t = tile + blockingTile;
  635. if (!gen->map->isInTheMap(t) || !gen->isPossible(t))
  636. {
  637. allTilesAvailable = false; //if at least one tile is not possible, object can't be placed here
  638. break;
  639. }
  640. }
  641. if (allTilesAvailable)
  642. {
  643. best_distance = dist;
  644. pos = tile;
  645. result = true;
  646. }
  647. }
  648. }
  649. if (result)
  650. {
  651. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  652. }
  653. return result;
  654. }
  655. void CRmgTemplateZone::checkAndPlaceObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  656. {
  657. if (!gen->map->isInTheMap(pos))
  658. throw rmgException(boost::to_string(boost::format("Position of object %d at %s is outside the map") % object->id % object->pos()));
  659. object->pos = pos;
  660. if (object->isVisitable() && !gen->map->isInTheMap(object->visitablePos()))
  661. throw rmgException(boost::to_string(boost::format("Visitable tile %s of object %d at %s is outside the map") % object->visitablePos() % object->id % object->pos()));
  662. for (auto tile : object->getBlockedPos())
  663. {
  664. if (!gen->map->isInTheMap(tile))
  665. throw rmgException(boost::to_string(boost::format("Tile %s of object %d at %s is outside the map") % tile() % object->id % object->pos()));
  666. }
  667. if (object->appearance.id == Obj::NO_OBJ)
  668. {
  669. auto templates = VLC->dobjinfo->pickCandidates(object->ID, object->subID, gen->map->getTile(pos).terType);
  670. if (templates.empty())
  671. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") %object->ID %object->subID %pos));
  672. object->appearance = templates.front();
  673. }
  674. gen->map->addBlockVisTiles(object);
  675. gen->editManager->insertObject(object, pos);
  676. logGlobal->traceStream() << boost::format ("Successfully inserted object (%d,%d) at pos %s") %object->ID %object->subID %pos();
  677. }
  678. void CRmgTemplateZone::placeObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  679. {
  680. logGlobal->traceStream() << boost::format("Inserting object at %d %d") % pos.x % pos.y;
  681. checkAndPlaceObject (gen, object, pos);
  682. auto points = object->getBlockedPos();
  683. if (object->isVisitable())
  684. points.insert(pos + object->getVisitableOffset());
  685. points.insert(pos);
  686. for(auto p : points)
  687. {
  688. if (gen->map->isInTheMap(p))
  689. {
  690. gen->setOccupied(p, ETileType::USED);
  691. }
  692. }
  693. for(auto tile : tileinfo)
  694. {
  695. si32 d = pos.dist2d(tile);
  696. gen->setNearestObjectDistance(tile, std::min(d, gen->getNearestObjectDistance(tile)));
  697. }
  698. }
  699. bool CRmgTemplateZone::guardObject(CMapGenerator* gen, CGObjectInstance* object, si32 str)
  700. {
  701. logGlobal->traceStream() << boost::format("Guard object at %d %d") % object->pos.x % object->pos.y;
  702. int3 visitable = object->visitablePos();
  703. std::vector<int3> tiles;
  704. gen->foreach_neighbour(visitable, [&](int3& pos)
  705. {
  706. logGlobal->traceStream() << boost::format("Block at %d %d") % pos.x % pos.y;
  707. if (gen->isPossible(pos))
  708. {
  709. tiles.push_back(pos);
  710. gen->setOccupied(pos, ETileType::BLOCKED);
  711. };
  712. });
  713. if ( ! tiles.size())
  714. {
  715. logGlobal->infoStream() << "Failed";
  716. return false;
  717. }
  718. auto guard_tile = *RandomGeneratorUtil::nextItem(tiles, gen->rand);
  719. gen->setOccupied (guard_tile, ETileType::USED);
  720. addMonster (gen, guard_tile, str);
  721. return true;
  722. }