CRmgTemplateZone.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  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. bool 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 false; //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. return true;
  390. }
  391. bool CRmgTemplateZone::createTreasurePile (CMapGenerator* gen, int3 &pos)
  392. {
  393. std::map<int3, CGObjectInstance *> treasures;
  394. std::set<int3> boundary;
  395. int3 guardPos;
  396. int3 nextTreasurePos = pos;
  397. //default values
  398. int maxValue = 5000;
  399. int minValue = 1500;
  400. //TODO: choose random treasure info based on density
  401. if (treasureInfo.size())
  402. {
  403. maxValue = treasureInfo.front().max;
  404. minValue = treasureInfo.front().min;
  405. }
  406. int currentValue = 0;
  407. CGObjectInstance * object = nullptr;
  408. while (currentValue < minValue)
  409. {
  410. //TODO: this works only for 1-tile objects
  411. //make sure our shape is consistent
  412. treasures[nextTreasurePos] = nullptr;
  413. for (auto treasurePos : treasures)
  414. {
  415. gen->foreach_neighbour (treasurePos.first, [gen, &boundary](int3 pos)
  416. {
  417. boundary.insert(pos);
  418. });
  419. }
  420. for (auto treasurePos : treasures)
  421. {
  422. //leaving only boundary around objects
  423. vstd::erase_if_present (boundary, treasurePos.first);
  424. }
  425. for (auto tile : boundary)
  426. {
  427. //we can't extend boundary anymore
  428. if (!(gen->isBlocked(tile) || gen->isPossible(tile)))
  429. break;
  430. }
  431. int remaining = maxValue - currentValue;
  432. auto oi = getRandomObject(gen, remaining);
  433. object = oi.generateObject();
  434. if (!object)
  435. break;
  436. currentValue += oi.value;
  437. treasures[nextTreasurePos] = object;
  438. //now find place for next object
  439. int3 placeFound(-1,-1,-1);
  440. for (auto tile : boundary)
  441. {
  442. if (gen->isPossible(tile)) //we can place new treasure only on possible tile
  443. {
  444. bool here = true;
  445. gen->foreach_neighbour (tile, [gen, &here](int3 pos)
  446. {
  447. if (!(gen->isBlocked(pos) || gen->isPossible(pos)))
  448. here = false;
  449. });
  450. if (here)
  451. {
  452. placeFound = tile;
  453. break;
  454. }
  455. }
  456. }
  457. if (placeFound.valid())
  458. nextTreasurePos = placeFound;
  459. }
  460. if (treasures.size())
  461. {
  462. for (auto treasure : treasures)
  463. {
  464. placeObject(gen, treasure.second, treasure.first);
  465. }
  466. guardPos = *RandomGeneratorUtil::nextItem(boundary, gen->rand);
  467. if (addMonster(gen, guardPos, currentValue))
  468. {//block only if object is guarded
  469. for (auto tile : boundary)
  470. {
  471. if (gen->isPossible(tile))
  472. gen->setOccupied (tile, ETileType::BLOCKED);
  473. }
  474. }
  475. return true;
  476. }
  477. else //we did not place eveyrthing successfully
  478. return false;
  479. }
  480. ObjectInfo CRmgTemplateZone::getRandomObject (CMapGenerator* gen, ui32 value)
  481. {
  482. std::vector<std::pair<ui32, ObjectInfo>> tresholds;
  483. ui32 total = 0;
  484. ui32 minValue = 0.25f * value;
  485. //roulette wheel
  486. for (auto oi : possibleObjects)
  487. {
  488. if (oi.value >= minValue && oi.value <= value)
  489. {
  490. total += oi.probability;
  491. tresholds.push_back (std::make_pair (total, oi));
  492. }
  493. }
  494. //TODO: generate pandora box with gold if the value is very high
  495. if (tresholds.empty())
  496. {
  497. ObjectInfo oi;
  498. oi.generateObject = [gen]() -> CGObjectInstance *
  499. {
  500. return nullptr;
  501. };
  502. oi.value = 0;
  503. oi.probability = 0;
  504. }
  505. int r = gen->rand.nextInt (1, total);
  506. for (auto t : tresholds)
  507. {
  508. if (r <= t.first)
  509. return t.second;
  510. }
  511. }
  512. void CRmgTemplateZone::addAllPossibleObjects (CMapGenerator* gen)
  513. {
  514. //TODO: move typical objects to config
  515. ObjectInfo oi;
  516. static const Res::ERes preciousRes[] = {Res::ERes::CRYSTAL, Res::ERes::GEMS, Res::ERes::MERCURY, Res::ERes::SULFUR};
  517. for (int i = 0; i < 4; i++)
  518. {
  519. oi.generateObject = [i, gen]() -> CGObjectInstance *
  520. {
  521. auto obj = new CGResource();
  522. obj->ID = Obj::RESOURCE;
  523. obj->subID = static_cast<si32>(preciousRes[i]);
  524. obj->amount = 0;
  525. return obj;
  526. };
  527. oi.value = 1400;
  528. oi.probability = 300;
  529. possibleObjects.push_back (oi);
  530. }
  531. static const Res::ERes woodOre[] = {Res::ERes::WOOD, Res::ERes::ORE};
  532. for (int i = 0; i < 2; i++)
  533. {
  534. oi.generateObject = [i, gen]() -> CGObjectInstance *
  535. {
  536. auto obj = new CGResource();
  537. obj->ID = Obj::RESOURCE;
  538. obj->subID = static_cast<si32>(woodOre[i]);
  539. obj->amount = 0;
  540. return obj;
  541. };
  542. oi.value = 1400;
  543. oi.probability = 300;
  544. possibleObjects.push_back (oi);
  545. }
  546. oi.generateObject = [gen]() -> CGObjectInstance *
  547. {
  548. auto obj = new CGResource();
  549. obj->ID = Obj::RESOURCE;
  550. obj->subID = static_cast<si32>(Res::ERes::GOLD);
  551. obj->amount = 0;
  552. return obj;
  553. };
  554. oi.value = 750;
  555. oi.probability = 300;
  556. possibleObjects.push_back (oi);
  557. oi.generateObject = [gen]() -> CGObjectInstance *
  558. {
  559. auto obj = new CGPickable();
  560. obj->ID = Obj::TREASURE_CHEST;
  561. obj->subID = 0;
  562. return obj;
  563. };
  564. oi.value = 1500;
  565. oi.probability = 1000;
  566. possibleObjects.push_back (oi);
  567. oi.generateObject = [gen]() -> CGObjectInstance *
  568. {
  569. auto obj = new CGArtifact();
  570. obj->ID = Obj::RANDOM_TREASURE_ART;
  571. obj->subID = 0;
  572. auto a = new CArtifactInstance();
  573. gen->map->addNewArtifactInstance(a);
  574. obj->storedArtifact = a;
  575. return obj;
  576. };
  577. oi.value = 2000;
  578. oi.probability = 150;
  579. possibleObjects.push_back (oi);
  580. oi.generateObject = [gen]() -> CGObjectInstance *
  581. {
  582. auto obj = new CGArtifact();
  583. obj->ID = Obj::RANDOM_MINOR_ART;
  584. obj->subID = 0;
  585. auto a = new CArtifactInstance();
  586. gen->map->addNewArtifactInstance(a);
  587. obj->storedArtifact = a;
  588. return obj;
  589. };
  590. oi.value = 5000;
  591. oi.probability = 150;
  592. possibleObjects.push_back (oi);
  593. oi.generateObject = [gen]() -> CGObjectInstance *
  594. {
  595. auto obj = new CGArtifact();
  596. obj->ID = Obj::RANDOM_MAJOR_ART;
  597. obj->subID = 0;
  598. auto a = new CArtifactInstance();
  599. gen->map->addNewArtifactInstance(a);
  600. obj->storedArtifact = a;
  601. return obj;
  602. };
  603. oi.value = 10000;
  604. oi.probability = 150;
  605. possibleObjects.push_back (oi);
  606. oi.generateObject = [gen]() -> CGObjectInstance *
  607. {
  608. auto obj = new CGArtifact();
  609. obj->ID = Obj::RANDOM_RELIC_ART;
  610. obj->subID = 0;
  611. auto a = new CArtifactInstance();
  612. gen->map->addNewArtifactInstance(a);
  613. obj->storedArtifact = a;
  614. return obj;
  615. };
  616. oi.value = 20000;
  617. oi.probability = 150;
  618. possibleObjects.push_back (oi);
  619. }
  620. bool CRmgTemplateZone::fill(CMapGenerator* gen)
  621. {
  622. addAllPossibleObjects (gen);
  623. int townId = 0;
  624. if ((type == ETemplateZoneType::CPU_START) || (type == ETemplateZoneType::PLAYER_START))
  625. {
  626. logGlobal->infoStream() << "Preparing playing zone";
  627. int player_id = *owner - 1;
  628. auto & playerInfo = gen->map->players[player_id];
  629. if (playerInfo.canAnyonePlay())
  630. {
  631. PlayerColor player(player_id);
  632. auto town = new CGTownInstance();
  633. town->ID = Obj::TOWN;
  634. townId = gen->mapGenOptions->getPlayersSettings().find(player)->second.getStartingTown();
  635. if(townId == CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  636. townId = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand); // all possible towns, skip neutral
  637. town->subID = townId;
  638. town->tempOwner = player;
  639. town->builtBuildings.insert(BuildingID::FORT);
  640. town->builtBuildings.insert(BuildingID::DEFAULT);
  641. placeObject(gen, town, getPos() + town->getVisitableOffset()); //towns are big objects and should be centered around visitable position
  642. logGlobal->traceStream() << "Fill player info " << player_id;
  643. // Update player info
  644. playerInfo.allowedFactions.clear();
  645. playerInfo.allowedFactions.insert(townId);
  646. playerInfo.hasMainTown = true;
  647. playerInfo.posOfMainTown = town->pos - int3(2, 0, 0);
  648. playerInfo.generateHeroAtMainTown = true;
  649. //requiredObjects.push_back(town);
  650. std::vector<Res::ERes> required_mines;
  651. required_mines.push_back(Res::ERes::WOOD);
  652. required_mines.push_back(Res::ERes::ORE);
  653. for(const auto res : required_mines)
  654. {
  655. auto mine = new CGMine();
  656. mine->ID = Obj::MINE;
  657. mine->subID = static_cast<si32>(res);
  658. mine->producedResource = res;
  659. mine->producedQuantity = mine->defaultResProduction();
  660. addRequiredObject(mine);
  661. }
  662. }
  663. else
  664. {
  665. type = ETemplateZoneType::TREASURE;
  666. townId = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  667. logGlobal->infoStream() << "Skipping this zone cause no player";
  668. }
  669. }
  670. else //no player
  671. {
  672. townId = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  673. }
  674. //paint zone with matching terrain
  675. std::vector<int3> tiles;
  676. for (auto tile : tileinfo)
  677. {
  678. tiles.push_back (tile);
  679. }
  680. gen->editManager->getTerrainSelection().setSelection(tiles);
  681. gen->editManager->drawTerrain(VLC->townh->factions[townId]->nativeTerrain, &gen->rand);
  682. logGlobal->infoStream() << "Creating required objects";
  683. for(const auto &obj : requiredObjects)
  684. {
  685. int3 pos;
  686. logGlobal->traceStream() << "Looking for place";
  687. if ( ! findPlaceForObject(gen, obj.first, 3, pos))
  688. {
  689. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") %id;
  690. //TODO CLEANUP!
  691. return false;
  692. }
  693. logGlobal->traceStream() << "Place found";
  694. placeObject(gen, obj.first, pos);
  695. if (obj.second)
  696. {
  697. guardObject (gen, obj.first, obj.second);
  698. }
  699. }
  700. const double res_mindist = 5;
  701. //TODO: just placeholder to chekc for possible locations
  702. auto obj = new CGResource();
  703. obj->ID = Obj::RESOURCE;
  704. obj->subID = static_cast<si32>(Res::ERes::GOLD);
  705. obj->amount = 0;
  706. do {
  707. int3 pos;
  708. if ( ! findPlaceForObject(gen, obj, res_mindist, pos))
  709. {
  710. delete obj;
  711. break;
  712. }
  713. createTreasurePile (gen, pos);
  714. } while(true);
  715. auto sel = gen->editManager->getTerrainSelection();
  716. sel.clearSelection();
  717. for (auto tile : tileinfo)
  718. {
  719. //test code - block all the map to show paths clearly
  720. //if (gen->isPossible(tile))
  721. // gen->setOccupied(tile, ETileType::BLOCKED);
  722. if (gen->shouldBeBlocked(tile)) //fill tiles that should be blocked with obstacles
  723. {
  724. auto obj = new CGObjectInstance();
  725. obj->ID = static_cast<Obj>(130);
  726. obj->subID = 0;
  727. placeObject(gen, obj, tile);
  728. }
  729. }
  730. //logGlobal->infoStream() << boost::format("Filling %d with ROCK") % sel.getSelectedItems().size();
  731. //gen->editManager->drawTerrain(ETerrainType::ROCK, &gen->gen);
  732. logGlobal->infoStream() << boost::format ("Zone %d filled successfully") %id;
  733. return true;
  734. }
  735. bool CRmgTemplateZone::findPlaceForObject(CMapGenerator* gen, CGObjectInstance* obj, si32 min_dist, int3 &pos)
  736. {
  737. //we need object apperance to deduce free tiles
  738. if (obj->appearance.id == Obj::NO_OBJ)
  739. {
  740. auto templates = VLC->dobjinfo->pickCandidates(obj->ID, obj->subID, gen->map->getTile(getPos()).terType);
  741. if (templates.empty())
  742. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") %obj->ID %obj->subID %pos));
  743. obj->appearance = templates.front();
  744. }
  745. //si32 min_dist = sqrt(tileinfo.size()/density);
  746. int best_distance = 0;
  747. bool result = false;
  748. si32 w = gen->map->width;
  749. si32 h = gen->map->height;
  750. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  751. for(auto tile : tileinfo)
  752. {
  753. auto ti = gen->getTile(tile);
  754. auto dist = ti.getNearestObjectDistance();
  755. //avoid borders
  756. if ((tile.x < 3) || (w - tile.x < 3) || (tile.y < 3) || (h - tile.y < 3))
  757. continue;
  758. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  759. {
  760. bool allTilesAvailable = true;
  761. for (auto blockingTile : obj->getBlockedOffsets())
  762. {
  763. int3 t = tile + blockingTile;
  764. if (!gen->map->isInTheMap(t) || !gen->isPossible(t))
  765. {
  766. allTilesAvailable = false; //if at least one tile is not possible, object can't be placed here
  767. break;
  768. }
  769. }
  770. if (allTilesAvailable)
  771. {
  772. best_distance = dist;
  773. pos = tile;
  774. result = true;
  775. }
  776. }
  777. }
  778. if (result)
  779. {
  780. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  781. }
  782. return result;
  783. }
  784. void CRmgTemplateZone::checkAndPlaceObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  785. {
  786. if (!gen->map->isInTheMap(pos))
  787. throw rmgException(boost::to_string(boost::format("Position of object %d at %s is outside the map") % object->id % object->pos()));
  788. object->pos = pos;
  789. if (object->isVisitable() && !gen->map->isInTheMap(object->visitablePos()))
  790. 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()));
  791. for (auto tile : object->getBlockedPos())
  792. {
  793. if (!gen->map->isInTheMap(tile))
  794. throw rmgException(boost::to_string(boost::format("Tile %s of object %d at %s is outside the map") % tile() % object->id % object->pos()));
  795. }
  796. if (object->appearance.id == Obj::NO_OBJ)
  797. {
  798. auto templates = VLC->dobjinfo->pickCandidates(object->ID, object->subID, gen->map->getTile(pos).terType);
  799. if (templates.empty())
  800. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") %object->ID %object->subID %pos));
  801. object->appearance = templates.front();
  802. }
  803. gen->map->addBlockVisTiles(object);
  804. gen->editManager->insertObject(object, pos);
  805. logGlobal->traceStream() << boost::format ("Successfully inserted object (%d,%d) at pos %s") %object->ID %object->subID %pos();
  806. }
  807. void CRmgTemplateZone::placeObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  808. {
  809. logGlobal->traceStream() << boost::format("Inserting object at %d %d") % pos.x % pos.y;
  810. checkAndPlaceObject (gen, object, pos);
  811. auto points = object->getBlockedPos();
  812. if (object->isVisitable())
  813. points.insert(pos + object->getVisitableOffset());
  814. points.insert(pos);
  815. for(auto p : points)
  816. {
  817. if (gen->map->isInTheMap(p))
  818. {
  819. gen->setOccupied(p, ETileType::USED);
  820. }
  821. }
  822. for(auto tile : tileinfo)
  823. {
  824. si32 d = pos.dist2d(tile);
  825. gen->setNearestObjectDistance(tile, std::min(d, gen->getNearestObjectDistance(tile)));
  826. }
  827. }
  828. bool CRmgTemplateZone::guardObject(CMapGenerator* gen, CGObjectInstance* object, si32 str)
  829. {
  830. logGlobal->traceStream() << boost::format("Guard object at %d %d") % object->pos.x % object->pos.y;
  831. int3 visitable = object->visitablePos();
  832. std::vector<int3> tiles;
  833. gen->foreach_neighbour(visitable, [&](int3& pos)
  834. {
  835. logGlobal->traceStream() << boost::format("Block at %d %d") % pos.x % pos.y;
  836. if (gen->isPossible(pos))
  837. {
  838. tiles.push_back(pos);
  839. };
  840. });
  841. if ( ! tiles.size())
  842. {
  843. logGlobal->infoStream() << "Failed";
  844. return false;
  845. }
  846. auto guard_tile = *RandomGeneratorUtil::nextItem(tiles, gen->rand);
  847. if (addMonster (gen, guard_tile, str)) //do not place obstacles around unguarded object
  848. {
  849. for (auto pos : tiles)
  850. gen->setOccupied(pos, ETileType::BLOCKED);
  851. gen->setOccupied (guard_tile, ETileType::USED);
  852. }
  853. else
  854. gen->setOccupied (guard_tile, ETileType::FREE);
  855. return true;
  856. }