CRmgTemplateZone.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  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. void CRmgTemplateZone::addTreasureInfo(CTreasureInfo & info)
  239. {
  240. treasureInfo.push_back(info);
  241. }
  242. std::vector<CTreasureInfo> CRmgTemplateZone::getTreasureInfo()
  243. {
  244. return treasureInfo;
  245. }
  246. float3 CRmgTemplateZone::getCenter() const
  247. {
  248. return center;
  249. }
  250. void CRmgTemplateZone::setCenter(const float3 &f)
  251. {
  252. //limit boundaries to (0,1) square
  253. center = float3 (std::min(std::max(f.x, 0.f), 1.f), std::min(std::max(f.y, 0.f), 1.f), f.z);
  254. }
  255. bool CRmgTemplateZone::pointIsIn(int x, int y)
  256. {
  257. return true;
  258. }
  259. int3 CRmgTemplateZone::getPos() const
  260. {
  261. return pos;
  262. }
  263. void CRmgTemplateZone::setPos(const int3 &Pos)
  264. {
  265. pos = Pos;
  266. }
  267. void CRmgTemplateZone::addTile (const int3 &pos)
  268. {
  269. tileinfo.insert(pos);
  270. }
  271. std::set<int3> CRmgTemplateZone::getTileInfo () const
  272. {
  273. return tileinfo;
  274. }
  275. void CRmgTemplateZone::createBorder(CMapGenerator* gen)
  276. {
  277. for (auto tile : tileinfo)
  278. {
  279. gen->foreach_neighbour (tile, [this, gen](int3 &pos)
  280. {
  281. if (!vstd::contains(this->tileinfo, pos))
  282. {
  283. gen->foreach_neighbour (pos, [this, gen](int3 &pos)
  284. {
  285. if (gen->isPossible(pos))
  286. gen->setOccupied (pos, ETileType::BLOCKED);
  287. });
  288. }
  289. });
  290. }
  291. }
  292. bool CRmgTemplateZone::crunchPath (CMapGenerator* gen, const int3 &src, const int3 &dst, TRmgTemplateZoneId zone)
  293. {
  294. /*
  295. make shortest path with free tiles, reachning dst or closest already free tile. Avoid blocks.
  296. do not leave zone border
  297. */
  298. bool result = false;
  299. bool end = false;
  300. int3 currentPos = src;
  301. float distance = currentPos.dist2dSQ (dst);
  302. while (!end)
  303. {
  304. if (currentPos == dst)
  305. break;
  306. auto lastDistance = distance;
  307. gen->foreach_neighbour (currentPos, [this, gen, &currentPos, dst, &distance, &result, &end](int3 &pos)
  308. {
  309. if (!result) //not sure if lambda is worth it...
  310. {
  311. if (pos == dst)
  312. {
  313. result = true;
  314. end = true;
  315. }
  316. if (pos.dist2dSQ (dst) < distance)
  317. {
  318. if (!gen->isBlocked(pos))
  319. {
  320. if (vstd::contains (tileinfo, pos))
  321. {
  322. if (gen->isPossible(pos))
  323. {
  324. gen->setOccupied (pos, ETileType::FREE);
  325. currentPos = pos;
  326. distance = currentPos.dist2dSQ (dst);
  327. }
  328. else if (gen->isFree(pos))
  329. {
  330. end = true;
  331. result = true;
  332. }
  333. else
  334. throw rmgException(boost::to_string(boost::format("Tile %s of uknown type found on path") % pos()));
  335. }
  336. }
  337. }
  338. }
  339. });
  340. if (!(result || distance < lastDistance)) //we do not advance, use more avdnaced pathfinding algorithm?
  341. {
  342. logGlobal->warnStream() << boost::format ("No tile closer than %s found on path from %s to %s") %currentPos %src %dst;
  343. break;
  344. }
  345. }
  346. return result;
  347. }
  348. void CRmgTemplateZone::addRequiredObject(CGObjectInstance * obj, si32 strength)
  349. {
  350. requiredObjects.push_back(std::make_pair(obj, strength));
  351. }
  352. void CRmgTemplateZone::addMonster(CMapGenerator* gen, int3 &pos, si32 strength)
  353. {
  354. //precalculate actual (randomized) monster strength based on this post
  355. //http://forum.vcmi.eu/viewtopic.php?p=12426#12426
  356. int zoneMonsterStrength = 0; //TODO: range -1..1 based on template settings
  357. int mapMonsterStrength = gen->mapGenOptions->getMonsterStrength();
  358. int monsterStrength = zoneMonsterStrength + mapMonsterStrength - 1; //array index from 0 to 4
  359. static const int value1[] = {2500, 1500, 1000, 500, 0};
  360. static const int value2[] = {7500, 7500, 7500, 5000, 5000};
  361. static const float multiplier1[] = {0.5, 0.75, 1.0, 1.5, 1.5};
  362. static const float multiplier2[] = {0.5, 0.75, 1.0, 1.0, 1.5};
  363. int strength1 = std::max(0.f, (strength - value1[monsterStrength]) * multiplier1[monsterStrength]);
  364. int strength2 = std::max(0.f, (strength - value2[monsterStrength]) * multiplier2[monsterStrength]);
  365. strength = strength1 + strength2;
  366. if (strength < 2000)
  367. return; //no guard at all
  368. CreatureID creId = CreatureID::NONE;
  369. int amount = 0;
  370. while (true)
  371. {
  372. creId = VLC->creh->pickRandomMonster(gen->rand);
  373. auto cre = VLC->creh->creatures[creId];
  374. 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
  375. {
  376. amount = strength / cre->AIValue;
  377. if (amount >= 4)
  378. amount *= gen->rand.nextDouble(0.75, 1.25);
  379. break;
  380. }
  381. }
  382. auto guard = new CGCreature();
  383. guard->ID = Obj::MONSTER;
  384. guard->subID = creId;
  385. auto hlp = new CStackInstance(creId, amount);
  386. //will be set during initialization
  387. guard->putStack(SlotID(0), hlp);
  388. placeObject(gen, guard, pos);
  389. }
  390. bool CRmgTemplateZone::createTreasurePile (CMapGenerator* gen, int3 &pos)
  391. {
  392. //TODO: read treasure values from template
  393. //default values
  394. int maxValue = 5000;
  395. int minValue = 1500;
  396. //TODO: choose random treasure info based on density
  397. if (treasureInfo.size())
  398. {
  399. maxValue = treasureInfo.front().max;
  400. minValue = treasureInfo.front().min;
  401. }
  402. static const Res::ERes woodOre[] = {Res::ERes::WOOD, Res::ERes::ORE};
  403. static const Res::ERes preciousRes[] = {Res::ERes::CRYSTAL, Res::ERes::GEMS, Res::ERes::MERCURY, Res::ERes::SULFUR};
  404. static auto res_gen = gen->rand.getIntRange(Res::ERes::WOOD, Res::ERes::GOLD);
  405. int currentValue = 0;
  406. CGObjectInstance * object = nullptr;
  407. while (currentValue < minValue)
  408. {
  409. int remaining = maxValue - currentValue;
  410. int nextValue = gen->rand.nextInt (0.25f * remaining, remaining);
  411. if (nextValue >= 20000)
  412. {
  413. auto obj = new CGArtifact();
  414. obj->ID = Obj::RANDOM_RELIC_ART;
  415. obj->subID = 0;
  416. auto a = new CArtifactInstance(); //TODO: probably some refactoring could help here
  417. gen->map->addNewArtifactInstance(a);
  418. obj->storedArtifact = a;
  419. object = obj;
  420. currentValue += 20000;
  421. }
  422. else if (nextValue >= 10000)
  423. {
  424. auto obj = new CGArtifact();
  425. obj->ID = Obj::RANDOM_MAJOR_ART;
  426. obj->subID = 0;
  427. auto a = new CArtifactInstance();
  428. gen->map->addNewArtifactInstance(a);
  429. obj->storedArtifact = a;
  430. object = obj;
  431. currentValue += 10000;
  432. }
  433. else if (nextValue >= 5000)
  434. {
  435. auto obj = new CGArtifact();
  436. obj->ID = Obj::RANDOM_MINOR_ART;
  437. obj->subID = 0;
  438. auto a = new CArtifactInstance();
  439. gen->map->addNewArtifactInstance(a);
  440. obj->storedArtifact = a;
  441. object = obj;
  442. currentValue += 5000;
  443. }
  444. else if (nextValue >= 2000)
  445. {
  446. auto obj = new CGArtifact();
  447. obj->ID = Obj::RANDOM_TREASURE_ART;
  448. obj->subID = 0;
  449. auto a = new CArtifactInstance();
  450. gen->map->addNewArtifactInstance(a);
  451. obj->storedArtifact = a;
  452. object = obj;
  453. currentValue += 2000;
  454. }
  455. else if (nextValue >= 1500)
  456. {
  457. auto obj = new CGPickable();
  458. obj->ID = Obj::TREASURE_CHEST;
  459. obj->subID = 0;
  460. object = obj;
  461. currentValue += 1500;
  462. }
  463. else if (nextValue >= 1400)
  464. {
  465. auto obj = new CGResource();
  466. auto restype = static_cast<Res::ERes>(preciousRes[gen->rand.nextInt (0,3)]); //TODO: how about dedicated function to pick random element of array?
  467. obj->ID = Obj::RESOURCE;
  468. obj->subID = static_cast<si32>(restype);
  469. obj->amount = 0;
  470. object = obj;
  471. currentValue += 1400;
  472. }
  473. else if (nextValue >= 1000)
  474. {
  475. auto obj = new CGResource();
  476. auto restype = static_cast<Res::ERes>(woodOre[gen->rand.nextInt (0,1)]);
  477. obj->ID = Obj::RESOURCE;
  478. obj->subID = static_cast<si32>(restype);
  479. obj->amount = 0;
  480. object = obj;
  481. currentValue += 1000;
  482. }
  483. else if (nextValue >= 750)
  484. {
  485. auto obj = new CGResource();
  486. obj->ID = Obj::RESOURCE;
  487. obj->subID = static_cast<si32>(Res::ERes::GOLD);
  488. obj->amount = 0;
  489. object = obj;
  490. currentValue += 750;
  491. }
  492. else //no possible treasure left (should not happen)
  493. break;
  494. //TODO: generate actual zone and not just all objects on a pile
  495. placeObject(gen, object, pos);
  496. }
  497. if (object)
  498. {
  499. guardObject (gen, object, currentValue);
  500. return true;
  501. }
  502. else //we did not place eveyrthing successfully
  503. return false;
  504. }
  505. bool CRmgTemplateZone::fill(CMapGenerator* gen)
  506. {
  507. int townId = 0;
  508. if ((type == ETemplateZoneType::CPU_START) || (type == ETemplateZoneType::PLAYER_START))
  509. {
  510. logGlobal->infoStream() << "Preparing playing zone";
  511. int player_id = *owner - 1;
  512. auto & playerInfo = gen->map->players[player_id];
  513. if (playerInfo.canAnyonePlay())
  514. {
  515. PlayerColor player(player_id);
  516. auto town = new CGTownInstance();
  517. town->ID = Obj::TOWN;
  518. townId = gen->mapGenOptions->getPlayersSettings().find(player)->second.getStartingTown();
  519. if(townId == CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  520. townId = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand); // all possible towns, skip neutral
  521. town->subID = townId;
  522. town->tempOwner = player;
  523. town->builtBuildings.insert(BuildingID::FORT);
  524. town->builtBuildings.insert(BuildingID::DEFAULT);
  525. placeObject(gen, town, getPos() + town->getVisitableOffset()); //towns are big objects and should be centered around visitable position
  526. logGlobal->traceStream() << "Placed object";
  527. logGlobal->traceStream() << "Fill player info " << player_id;
  528. auto & playerInfo = gen->map->players[player_id];
  529. // Update player info
  530. playerInfo.allowedFactions.clear();
  531. playerInfo.allowedFactions.insert(town->subID);
  532. playerInfo.hasMainTown = true;
  533. playerInfo.posOfMainTown = town->pos - int3(2, 0, 0);
  534. playerInfo.generateHeroAtMainTown = true;
  535. //requiredObjects.push_back(town);
  536. std::vector<Res::ERes> required_mines;
  537. required_mines.push_back(Res::ERes::WOOD);
  538. required_mines.push_back(Res::ERes::ORE);
  539. for(const auto res : required_mines)
  540. {
  541. auto mine = new CGMine();
  542. mine->ID = Obj::MINE;
  543. mine->subID = static_cast<si32>(res);
  544. mine->producedResource = res;
  545. mine->producedQuantity = mine->defaultResProduction();
  546. addRequiredObject(mine);
  547. }
  548. }
  549. else
  550. {
  551. type = ETemplateZoneType::TREASURE;
  552. townId = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  553. logGlobal->infoStream() << "Skipping this zone cause no player";
  554. }
  555. }
  556. else //no player
  557. {
  558. townId = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  559. }
  560. //paint zone with matching terrain
  561. std::vector<int3> tiles;
  562. for (auto tile : tileinfo)
  563. {
  564. tiles.push_back (tile);
  565. }
  566. gen->editManager->getTerrainSelection().setSelection(tiles);
  567. gen->editManager->drawTerrain(VLC->townh->factions[townId]->nativeTerrain, &gen->rand);
  568. logGlobal->infoStream() << "Creating required objects";
  569. for(const auto &obj : requiredObjects)
  570. {
  571. int3 pos;
  572. logGlobal->traceStream() << "Looking for place";
  573. if ( ! findPlaceForObject(gen, obj.first, 3, pos))
  574. {
  575. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") %id;
  576. //TODO CLEANUP!
  577. return false;
  578. }
  579. logGlobal->traceStream() << "Place found";
  580. placeObject(gen, obj.first, pos);
  581. if (obj.second)
  582. {
  583. guardObject (gen, obj.first, obj.second);
  584. }
  585. }
  586. const double res_mindist = 5;
  587. //TODO: just placeholder to chekc for possible locations
  588. auto obj = new CGResource();
  589. obj->ID = Obj::RESOURCE;
  590. obj->subID = static_cast<si32>(Res::ERes::GOLD);
  591. obj->amount = 0;
  592. do {
  593. int3 pos;
  594. if ( ! findPlaceForObject(gen, obj, res_mindist, pos))
  595. {
  596. delete obj;
  597. break;
  598. }
  599. createTreasurePile (gen, pos);
  600. } while(true);
  601. auto sel = gen->editManager->getTerrainSelection();
  602. sel.clearSelection();
  603. for (auto tile : tileinfo)
  604. {
  605. //test code - block all the map to show paths clearly
  606. //if (gen->isPossible(tile))
  607. // gen->setOccupied(tile, ETileType::BLOCKED);
  608. if (gen->shouldBeBlocked(tile)) //fill tiles that should be blocked with obstacles
  609. {
  610. auto obj = new CGObjectInstance();
  611. obj->ID = static_cast<Obj>(130);
  612. obj->subID = 0;
  613. placeObject(gen, obj, tile);
  614. }
  615. }
  616. //logGlobal->infoStream() << boost::format("Filling %d with ROCK") % sel.getSelectedItems().size();
  617. //gen->editManager->drawTerrain(ETerrainType::ROCK, &gen->gen);
  618. logGlobal->infoStream() << boost::format ("Zone %d filled successfully") %id;
  619. return true;
  620. }
  621. bool CRmgTemplateZone::findPlaceForObject(CMapGenerator* gen, CGObjectInstance* obj, si32 min_dist, int3 &pos)
  622. {
  623. //we need object apperance to deduce free tiles
  624. if (obj->appearance.id == Obj::NO_OBJ)
  625. {
  626. auto templates = VLC->dobjinfo->pickCandidates(obj->ID, obj->subID, gen->map->getTile(getPos()).terType);
  627. if (templates.empty())
  628. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") %obj->ID %obj->subID %pos));
  629. obj->appearance = templates.front();
  630. }
  631. //si32 min_dist = sqrt(tileinfo.size()/density);
  632. int best_distance = 0;
  633. bool result = false;
  634. si32 w = gen->map->width;
  635. si32 h = gen->map->height;
  636. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  637. for(auto tile : tileinfo)
  638. {
  639. auto ti = gen->getTile(tile);
  640. auto dist = ti.getNearestObjectDistance();
  641. //avoid borders
  642. if ((tile.x < 3) || (w - tile.x < 3) || (tile.y < 3) || (h - tile.y < 3))
  643. continue;
  644. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  645. {
  646. bool allTilesAvailable = true;
  647. for (auto blockingTile : obj->getBlockedOffsets())
  648. {
  649. int3 t = tile + blockingTile;
  650. if (!gen->map->isInTheMap(t) || !gen->isPossible(t))
  651. {
  652. allTilesAvailable = false; //if at least one tile is not possible, object can't be placed here
  653. break;
  654. }
  655. }
  656. if (allTilesAvailable)
  657. {
  658. best_distance = dist;
  659. pos = tile;
  660. result = true;
  661. }
  662. }
  663. }
  664. if (result)
  665. {
  666. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  667. }
  668. return result;
  669. }
  670. void CRmgTemplateZone::checkAndPlaceObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  671. {
  672. if (!gen->map->isInTheMap(pos))
  673. throw rmgException(boost::to_string(boost::format("Position of object %d at %s is outside the map") % object->id % object->pos()));
  674. object->pos = pos;
  675. if (object->isVisitable() && !gen->map->isInTheMap(object->visitablePos()))
  676. 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()));
  677. for (auto tile : object->getBlockedPos())
  678. {
  679. if (!gen->map->isInTheMap(tile))
  680. throw rmgException(boost::to_string(boost::format("Tile %s of object %d at %s is outside the map") % tile() % object->id % object->pos()));
  681. }
  682. if (object->appearance.id == Obj::NO_OBJ)
  683. {
  684. auto templates = VLC->dobjinfo->pickCandidates(object->ID, object->subID, gen->map->getTile(pos).terType);
  685. if (templates.empty())
  686. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") %object->ID %object->subID %pos));
  687. object->appearance = templates.front();
  688. }
  689. gen->map->addBlockVisTiles(object);
  690. gen->editManager->insertObject(object, pos);
  691. logGlobal->traceStream() << boost::format ("Successfully inserted object (%d,%d) at pos %s") %object->ID %object->subID %pos();
  692. }
  693. void CRmgTemplateZone::placeObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  694. {
  695. logGlobal->traceStream() << boost::format("Inserting object at %d %d") % pos.x % pos.y;
  696. checkAndPlaceObject (gen, object, pos);
  697. auto points = object->getBlockedPos();
  698. if (object->isVisitable())
  699. points.insert(pos + object->getVisitableOffset());
  700. points.insert(pos);
  701. for(auto p : points)
  702. {
  703. if (gen->map->isInTheMap(p))
  704. {
  705. gen->setOccupied(p, ETileType::USED);
  706. }
  707. }
  708. for(auto tile : tileinfo)
  709. {
  710. si32 d = pos.dist2d(tile);
  711. gen->setNearestObjectDistance(tile, std::min(d, gen->getNearestObjectDistance(tile)));
  712. }
  713. }
  714. bool CRmgTemplateZone::guardObject(CMapGenerator* gen, CGObjectInstance* object, si32 str)
  715. {
  716. logGlobal->traceStream() << boost::format("Guard object at %d %d") % object->pos.x % object->pos.y;
  717. int3 visitable = object->visitablePos();
  718. std::vector<int3> tiles;
  719. gen->foreach_neighbour(visitable, [&](int3& pos)
  720. {
  721. logGlobal->traceStream() << boost::format("Block at %d %d") % pos.x % pos.y;
  722. if (gen->isPossible(pos))
  723. {
  724. tiles.push_back(pos);
  725. gen->setOccupied(pos, ETileType::BLOCKED);
  726. };
  727. });
  728. if ( ! tiles.size())
  729. {
  730. logGlobal->infoStream() << "Failed";
  731. return false;
  732. }
  733. auto guard_tile = *RandomGeneratorUtil::nextItem(tiles, gen->rand);
  734. gen->setOccupied (guard_tile, ETileType::USED);
  735. addMonster (gen, guard_tile, str);
  736. return true;
  737. }