CRmgTemplateZone.cpp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769
  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. #include "../CSpellHandler.h" //for choosing random spells
  18. #include "../mapObjects/CommonConstructors.h"
  19. #include "../mapObjects/MapObjects.h" //needed to resolve templates for CommonConstructors.h
  20. #include "../mapObjects/CGPandoraBox.h"
  21. #include "../mapObjects/CRewardableObject.h"
  22. class CMap;
  23. class CMapEditManager;
  24. //class CGObjectInstance;
  25. CRmgTemplateZone::CTownInfo::CTownInfo() : townCount(0), castleCount(0), townDensity(0), castleDensity(0)
  26. {
  27. }
  28. int CRmgTemplateZone::CTownInfo::getTownCount() const
  29. {
  30. return townCount;
  31. }
  32. void CRmgTemplateZone::CTownInfo::setTownCount(int value)
  33. {
  34. if(value < 0)
  35. throw rmgException("Negative value for town count not allowed.");
  36. townCount = value;
  37. }
  38. int CRmgTemplateZone::CTownInfo::getCastleCount() const
  39. {
  40. return castleCount;
  41. }
  42. void CRmgTemplateZone::CTownInfo::setCastleCount(int value)
  43. {
  44. if(value < 0)
  45. throw rmgException("Negative value for castle count not allowed.");
  46. castleCount = value;
  47. }
  48. int CRmgTemplateZone::CTownInfo::getTownDensity() const
  49. {
  50. return townDensity;
  51. }
  52. void CRmgTemplateZone::CTownInfo::setTownDensity(int value)
  53. {
  54. if(value < 0)
  55. throw rmgException("Negative value for town density not allowed.");
  56. townDensity = value;
  57. }
  58. int CRmgTemplateZone::CTownInfo::getCastleDensity() const
  59. {
  60. return castleDensity;
  61. }
  62. void CRmgTemplateZone::CTownInfo::setCastleDensity(int value)
  63. {
  64. if(value < 0)
  65. throw rmgException("Negative value for castle density not allowed.");
  66. castleDensity = value;
  67. }
  68. CTileInfo::CTileInfo():nearestObjectDistance(INT_MAX), terrain(ETerrainType::WRONG)
  69. {
  70. occupied = ETileType::POSSIBLE; //all tiles are initially possible to place objects or passages
  71. }
  72. int CTileInfo::getNearestObjectDistance() const
  73. {
  74. return nearestObjectDistance;
  75. }
  76. void CTileInfo::setNearestObjectDistance(int value)
  77. {
  78. nearestObjectDistance = std::max(0, value); //never negative (or unitialized)
  79. }
  80. bool CTileInfo::shouldBeBlocked() const
  81. {
  82. return occupied == ETileType::BLOCKED;
  83. }
  84. bool CTileInfo::isBlocked() const
  85. {
  86. return occupied == ETileType::BLOCKED || occupied == ETileType::USED;
  87. }
  88. bool CTileInfo::isPossible() const
  89. {
  90. return occupied == ETileType::POSSIBLE;
  91. }
  92. bool CTileInfo::isFree() const
  93. {
  94. return occupied == ETileType::FREE;
  95. }
  96. bool CTileInfo::isUsed() const
  97. {
  98. return occupied == ETileType::USED;
  99. }
  100. void CTileInfo::setOccupied(ETileType::ETileType value)
  101. {
  102. occupied = value;
  103. }
  104. ETerrainType CTileInfo::getTerrainType() const
  105. {
  106. return terrain;
  107. }
  108. void CTileInfo::setTerrainType(ETerrainType value)
  109. {
  110. terrain = value;
  111. }
  112. CRmgTemplateZone::CRmgTemplateZone() :
  113. id(0),
  114. type(ETemplateZoneType::PLAYER_START),
  115. size(1),
  116. townsAreSameType(false),
  117. matchTerrainToTown(true),
  118. townType(0),
  119. terrainType (ETerrainType::GRASS),
  120. zoneMonsterStrength(EMonsterStrength::ZONE_NORMAL),
  121. totalDensity(0)
  122. {
  123. townTypes = getDefaultTownTypes();
  124. terrainTypes = getDefaultTerrainTypes();
  125. }
  126. TRmgTemplateZoneId CRmgTemplateZone::getId() const
  127. {
  128. return id;
  129. }
  130. void CRmgTemplateZone::setId(TRmgTemplateZoneId value)
  131. {
  132. if(value <= 0)
  133. throw rmgException(boost::to_string(boost::format("Zone %d id should be greater than 0.") %id));
  134. id = value;
  135. }
  136. ETemplateZoneType::ETemplateZoneType CRmgTemplateZone::getType() const
  137. {
  138. return type;
  139. }
  140. void CRmgTemplateZone::setType(ETemplateZoneType::ETemplateZoneType value)
  141. {
  142. type = value;
  143. }
  144. int CRmgTemplateZone::getSize() const
  145. {
  146. return size;
  147. }
  148. void CRmgTemplateZone::setSize(int value)
  149. {
  150. if(value <= 0)
  151. throw rmgException(boost::to_string(boost::format("Zone %d size needs to be greater than 0.") % id));
  152. size = value;
  153. }
  154. boost::optional<int> CRmgTemplateZone::getOwner() const
  155. {
  156. return owner;
  157. }
  158. void CRmgTemplateZone::setOwner(boost::optional<int> value)
  159. {
  160. if(!(*value >= 0 && *value <= PlayerColor::PLAYER_LIMIT_I))
  161. throw rmgException(boost::to_string(boost::format ("Owner of zone %d has to be in range 0 to max player count.") %id));
  162. owner = value;
  163. }
  164. const CRmgTemplateZone::CTownInfo & CRmgTemplateZone::getPlayerTowns() const
  165. {
  166. return playerTowns;
  167. }
  168. void CRmgTemplateZone::setPlayerTowns(const CTownInfo & value)
  169. {
  170. playerTowns = value;
  171. }
  172. const CRmgTemplateZone::CTownInfo & CRmgTemplateZone::getNeutralTowns() const
  173. {
  174. return neutralTowns;
  175. }
  176. void CRmgTemplateZone::setNeutralTowns(const CTownInfo & value)
  177. {
  178. neutralTowns = value;
  179. }
  180. bool CRmgTemplateZone::getTownsAreSameType() const
  181. {
  182. return townsAreSameType;
  183. }
  184. void CRmgTemplateZone::setTownsAreSameType(bool value)
  185. {
  186. townsAreSameType = value;
  187. }
  188. const std::set<TFaction> & CRmgTemplateZone::getTownTypes() const
  189. {
  190. return townTypes;
  191. }
  192. void CRmgTemplateZone::setTownTypes(const std::set<TFaction> & value)
  193. {
  194. townTypes = value;
  195. }
  196. std::set<TFaction> CRmgTemplateZone::getDefaultTownTypes() const
  197. {
  198. std::set<TFaction> defaultTowns;
  199. auto towns = VLC->townh->getDefaultAllowed();
  200. for(int i = 0; i < towns.size(); ++i)
  201. {
  202. if(towns[i]) defaultTowns.insert(i);
  203. }
  204. return defaultTowns;
  205. }
  206. bool CRmgTemplateZone::getMatchTerrainToTown() const
  207. {
  208. return matchTerrainToTown;
  209. }
  210. void CRmgTemplateZone::setMatchTerrainToTown(bool value)
  211. {
  212. matchTerrainToTown = value;
  213. }
  214. const std::set<ETerrainType> & CRmgTemplateZone::getTerrainTypes() const
  215. {
  216. return terrainTypes;
  217. }
  218. void CRmgTemplateZone::setTerrainTypes(const std::set<ETerrainType> & value)
  219. {
  220. assert(value.find(ETerrainType::WRONG) == value.end() && value.find(ETerrainType::BORDER) == value.end() &&
  221. value.find(ETerrainType::WATER) == value.end() && value.find(ETerrainType::ROCK) == value.end());
  222. terrainTypes = value;
  223. }
  224. std::set<ETerrainType> CRmgTemplateZone::getDefaultTerrainTypes() const
  225. {
  226. std::set<ETerrainType> terTypes;
  227. static const ETerrainType::EETerrainType allowedTerTypes[] = {ETerrainType::DIRT, ETerrainType::SAND, ETerrainType::GRASS, ETerrainType::SNOW,
  228. ETerrainType::SWAMP, ETerrainType::ROUGH, ETerrainType::SUBTERRANEAN, ETerrainType::LAVA};
  229. for (auto & allowedTerType : allowedTerTypes)
  230. terTypes.insert(allowedTerType);
  231. return terTypes;
  232. }
  233. void CRmgTemplateZone::setMinesAmount (TResource res, ui16 amount)
  234. {
  235. mines[res] = amount;
  236. }
  237. std::map<TResource, ui16> CRmgTemplateZone::getMinesInfo() const
  238. {
  239. return mines;
  240. }
  241. void CRmgTemplateZone::addConnection(TRmgTemplateZoneId otherZone)
  242. {
  243. connections.push_back (otherZone);
  244. }
  245. std::vector<TRmgTemplateZoneId> CRmgTemplateZone::getConnections() const
  246. {
  247. return connections;
  248. }
  249. void CRmgTemplateZone::setMonsterStrength (EMonsterStrength::EMonsterStrength val)
  250. {
  251. assert (vstd::iswithin(val, EMonsterStrength::ZONE_WEAK, EMonsterStrength::ZONE_STRONG));
  252. zoneMonsterStrength = val;
  253. }
  254. void CRmgTemplateZone::setTotalDensity (ui16 val)
  255. {
  256. totalDensity = val;
  257. }
  258. ui16 CRmgTemplateZone::getTotalDensity () const
  259. {
  260. return totalDensity;
  261. }
  262. void CRmgTemplateZone::addTreasureInfo(CTreasureInfo & info)
  263. {
  264. treasureInfo.push_back(info);
  265. }
  266. std::vector<CTreasureInfo> CRmgTemplateZone::getTreasureInfo()
  267. {
  268. return treasureInfo;
  269. }
  270. std::set<int3>* CRmgTemplateZone::getFreePaths()
  271. {
  272. return &freePaths;
  273. }
  274. float3 CRmgTemplateZone::getCenter() const
  275. {
  276. return center;
  277. }
  278. void CRmgTemplateZone::setCenter(const float3 &f)
  279. {
  280. //limit boundaries to (0,1) square
  281. center = float3 (std::min(std::max(f.x, 0.f), 1.f), std::min(std::max(f.y, 0.f), 1.f), f.z);
  282. }
  283. bool CRmgTemplateZone::pointIsIn(int x, int y)
  284. {
  285. return true;
  286. }
  287. int3 CRmgTemplateZone::getPos() const
  288. {
  289. return pos;
  290. }
  291. void CRmgTemplateZone::setPos(const int3 &Pos)
  292. {
  293. pos = Pos;
  294. }
  295. void CRmgTemplateZone::addTile (const int3 &pos)
  296. {
  297. tileinfo.insert(pos);
  298. }
  299. std::set<int3> CRmgTemplateZone::getTileInfo () const
  300. {
  301. return tileinfo;
  302. }
  303. void CRmgTemplateZone::discardDistantTiles (CMapGenerator* gen, float distance)
  304. {
  305. //TODO: mark tiles beyond zone as unavailable, but allow to connect with adjacent zones
  306. //for (auto tile : tileinfo)
  307. //{
  308. // if (tile.dist2d(this->pos) > distance)
  309. // {
  310. // gen->setOccupied(tile, ETileType::USED);
  311. // //gen->setOccupied(tile, ETileType::BLOCKED); //fixme: crash at rendering?
  312. // }
  313. //}
  314. vstd::erase_if (tileinfo, [distance, this](const int3 &tile) -> bool
  315. {
  316. return tile.dist2d(this->pos) > distance;
  317. });
  318. }
  319. void CRmgTemplateZone::createBorder(CMapGenerator* gen)
  320. {
  321. for (auto tile : tileinfo)
  322. {
  323. gen->foreach_neighbour (tile, [this, gen](int3 &pos)
  324. {
  325. if (!vstd::contains(this->tileinfo, pos))
  326. {
  327. gen->foreach_neighbour (pos, [this, gen](int3 &pos)
  328. {
  329. if (gen->isPossible(pos))
  330. gen->setOccupied (pos, ETileType::BLOCKED);
  331. });
  332. }
  333. });
  334. }
  335. }
  336. void CRmgTemplateZone::fractalize(CMapGenerator* gen)
  337. {
  338. std::vector<int3> clearedTiles (freePaths.begin(), freePaths.end());
  339. std::set<int3> possibleTiles;
  340. std::set<int3> tilesToClear; //will be set clear
  341. std::set<int3> tilesToIgnore; //will be erased in this iteration
  342. //the more treasure density, the greater distance between paths. Scaling is experimental.
  343. const float minDistance = std::sqrt(totalDensity * 3);
  344. for (auto tile : tileinfo)
  345. {
  346. if (gen->isFree(tile))
  347. clearedTiles.push_back(tile);
  348. else if (gen->isPossible(tile))
  349. possibleTiles.insert(tile);
  350. }
  351. if (clearedTiles.empty()) //this should come from zone connections
  352. {
  353. clearedTiles.push_back(pos); //zone center should be always clear
  354. }
  355. while (possibleTiles.size())
  356. {
  357. for (auto tileToMakePath : possibleTiles)
  358. {
  359. //find closest free tile
  360. float currentDistance = 1e10;
  361. int3 closestTile (-1,-1,-1);
  362. for (auto clearTile : clearedTiles)
  363. {
  364. float distance = tileToMakePath.dist2d(clearTile);
  365. if (distance < currentDistance)
  366. {
  367. currentDistance = distance;
  368. closestTile = clearTile;
  369. }
  370. if (currentDistance <= minDistance)
  371. {
  372. //this tile is close enough. Forget about it and check next one
  373. tilesToIgnore.insert (tileToMakePath);
  374. break;
  375. }
  376. }
  377. //if tiles is not close enough, make path to it
  378. if (currentDistance > minDistance)
  379. {
  380. crunchPath (gen, tileToMakePath, closestTile, id, &tilesToClear);
  381. break; //next iteration - use already cleared tiles
  382. }
  383. }
  384. for (auto tileToClear : tilesToClear)
  385. {
  386. //move cleared tiles from one set to another
  387. clearedTiles.push_back(tileToClear);
  388. vstd::erase_if_present(possibleTiles, tileToClear);
  389. }
  390. for (auto tileToClear : tilesToIgnore)
  391. {
  392. //these tiles are already connected, ignore them
  393. vstd::erase_if_present(possibleTiles, tileToClear);
  394. }
  395. if (tilesToClear.empty()) //nothing else can be done (?)
  396. break;
  397. tilesToClear.clear(); //empty this container
  398. tilesToIgnore.clear();
  399. }
  400. for (auto tile : clearedTiles)
  401. {
  402. freePaths.insert(tile);
  403. }
  404. if (0) //enable to debug
  405. {
  406. std::ofstream out(boost::to_string(boost::format("zone %d") % id));
  407. int levels = gen->map->twoLevel ? 2 : 1;
  408. int width = gen->map->width;
  409. int height = gen->map->height;
  410. for (int k = 0; k < levels; k++)
  411. {
  412. for(int j=0; j<height; j++)
  413. {
  414. for (int i=0; i<width; i++)
  415. {
  416. out << (int)vstd::contains(freePaths, int3(i,j,k));
  417. }
  418. out << std::endl;
  419. }
  420. out << std::endl;
  421. }
  422. }
  423. logGlobal->infoStream() << boost::format ("Zone %d subdivided fractally") %id;
  424. }
  425. bool CRmgTemplateZone::crunchPath (CMapGenerator* gen, const int3 &src, const int3 &dst, TRmgTemplateZoneId zone, std::set<int3>* clearedTiles)
  426. {
  427. /*
  428. make shortest path with free tiles, reachning dst or closest already free tile. Avoid blocks.
  429. do not leave zone border
  430. */
  431. bool result = false;
  432. bool end = false;
  433. int3 currentPos = src;
  434. float distance = currentPos.dist2dSQ (dst);
  435. while (!end)
  436. {
  437. if (currentPos == dst)
  438. {
  439. result = true;
  440. break;
  441. }
  442. auto lastDistance = distance;
  443. gen->foreach_neighbour (currentPos, [this, gen, &currentPos, dst, &distance, &result, &end, clearedTiles](int3 &pos)
  444. {
  445. if (!result) //not sure if lambda is worth it...
  446. {
  447. if (pos == dst)
  448. {
  449. result = true;
  450. end = true;
  451. }
  452. if (pos.dist2dSQ (dst) < distance)
  453. {
  454. if (!gen->isBlocked(pos))
  455. {
  456. if (vstd::contains (tileinfo, pos))
  457. {
  458. if (gen->isPossible(pos))
  459. {
  460. gen->setOccupied (pos, ETileType::FREE);
  461. if (clearedTiles)
  462. clearedTiles->insert(pos);
  463. currentPos = pos;
  464. distance = currentPos.dist2dSQ (dst);
  465. }
  466. else if (gen->isFree(pos))
  467. {
  468. end = true;
  469. result = true;
  470. }
  471. else
  472. throw rmgException(boost::to_string(boost::format("Tile %s of uknown type found on path") % pos()));
  473. }
  474. }
  475. }
  476. }
  477. });
  478. if (!(result || distance < lastDistance)) //we do not advance, use more avdnaced pathfinding algorithm?
  479. {
  480. logGlobal->warnStream() << boost::format ("No tile closer than %s found on path from %s to %s") %currentPos %src %dst;
  481. break;
  482. }
  483. }
  484. return result;
  485. }
  486. void CRmgTemplateZone::addRequiredObject(CGObjectInstance * obj, si32 strength)
  487. {
  488. requiredObjects.push_back(std::make_pair(obj, strength));
  489. }
  490. bool CRmgTemplateZone::addMonster(CMapGenerator* gen, int3 &pos, si32 strength)
  491. {
  492. //precalculate actual (randomized) monster strength based on this post
  493. //http://forum.vcmi.eu/viewtopic.php?p=12426#12426
  494. int mapMonsterStrength = gen->mapGenOptions->getMonsterStrength();
  495. int monsterStrength = zoneMonsterStrength + mapMonsterStrength - 1; //array index from 0 to 4
  496. static const int value1[] = {2500, 1500, 1000, 500, 0};
  497. static const int value2[] = {7500, 7500, 7500, 5000, 5000};
  498. static const float multiplier1[] = {0.5, 0.75, 1.0, 1.5, 1.5};
  499. static const float multiplier2[] = {0.5, 0.75, 1.0, 1.0, 1.5};
  500. int strength1 = std::max(0.f, (strength - value1[monsterStrength]) * multiplier1[monsterStrength]);
  501. int strength2 = std::max(0.f, (strength - value2[monsterStrength]) * multiplier2[monsterStrength]);
  502. strength = strength1 + strength2;
  503. if (strength < 2000)
  504. return false; //no guard at all
  505. CreatureID creId = CreatureID::NONE;
  506. int amount = 0;
  507. std::vector<CreatureID> possibleCreatures;
  508. for (auto cre : VLC->creh->creatures)
  509. {
  510. if (cre->special)
  511. continue;
  512. if ((cre->AIValue * (cre->ammMin + cre->ammMax) / 2 < strength) && (strength < cre->AIValue * 100)) //at least one full monster. size between minimum size of given stack and 100
  513. {
  514. possibleCreatures.push_back(cre->idNumber);
  515. }
  516. }
  517. if (possibleCreatures.size())
  518. {
  519. creId = *RandomGeneratorUtil::nextItem(possibleCreatures, gen->rand);
  520. amount = strength / VLC->creh->creatures[creId]->AIValue;
  521. if (amount >= 4)
  522. amount *= gen->rand.nextDouble(0.75, 1.25);
  523. }
  524. else //just pick any available creature
  525. {
  526. creId = CreatureID(132); //Azure Dragon
  527. amount = strength / VLC->creh->creatures[creId]->AIValue;
  528. }
  529. auto guard = new CGCreature();
  530. guard->ID = Obj::MONSTER;
  531. guard->subID = creId;
  532. auto hlp = new CStackInstance(creId, amount);
  533. //will be set during initialization
  534. guard->putStack(SlotID(0), hlp);
  535. placeObject(gen, guard, pos);
  536. return true;
  537. }
  538. bool CRmgTemplateZone::createTreasurePile (CMapGenerator* gen, int3 &pos)
  539. {
  540. CTreasurePileInfo info;
  541. std::map<int3, CGObjectInstance *> treasures;
  542. std::set<int3> boundary;
  543. int3 guardPos (-1,-1,-1);
  544. info.nextTreasurePos = pos;
  545. //default values
  546. int maxValue = 5000;
  547. int minValue = 1500;
  548. if (treasureInfo.size())
  549. {
  550. //roulette wheel
  551. int r = gen->rand.nextInt (1, totalDensity);
  552. for (auto t : treasureInfo)
  553. {
  554. if (r <= t.threshold)
  555. {
  556. maxValue = t.max;
  557. minValue = t.min;
  558. break;
  559. }
  560. }
  561. }
  562. int currentValue = 0;
  563. CGObjectInstance * object = nullptr;
  564. while (currentValue < minValue)
  565. {
  566. //make sure our shape is consistent
  567. treasures[info.nextTreasurePos] = nullptr;
  568. for (auto treasurePos : treasures)
  569. {
  570. gen->foreach_neighbour (treasurePos.first, [gen, &boundary](int3 pos)
  571. {
  572. boundary.insert(pos);
  573. });
  574. }
  575. for (auto treasurePos : treasures)
  576. {
  577. //leaving only boundary around objects
  578. vstd::erase_if_present (boundary, treasurePos.first);
  579. }
  580. for (auto tile : boundary)
  581. {
  582. //we can't extend boundary anymore
  583. if (!(gen->isBlocked(tile) || gen->isPossible(tile)))
  584. break;
  585. }
  586. int remaining = maxValue - currentValue;
  587. ObjectInfo oi = getRandomObject(gen, info, remaining);
  588. object = oi.generateObject();
  589. if (!object)
  590. {
  591. vstd::erase_if_present(treasures, info.nextTreasurePos);
  592. break;
  593. }
  594. else
  595. {
  596. //update treasure pile area
  597. int3 visitablePos = oi.templ.getVisitableOffset() + info.nextTreasurePos;
  598. info.visitablePositions.insert(visitablePos); //can be accessed only from bottom or side
  599. if (oi.templ.isVisitableFromTop())
  600. info.visitableFromTopPositions.insert(visitablePos); //can be accessed from any direction
  601. for (auto blockedOffset : oi.templ.getBlockedOffsets())
  602. info.occupiedPositions.insert(info.nextTreasurePos + blockedOffset);
  603. info.occupiedPositions.insert(visitablePos);
  604. }
  605. currentValue += oi.value;
  606. treasures[info.nextTreasurePos] = object;
  607. //now find place for next object
  608. int3 placeFound(-1,-1,-1);
  609. //FIXME: find out why teh following code causes crashes
  610. //std::vector<int3> boundaryVec(boundary.begin(), boundary.end());
  611. //RandomGeneratorUtil::randomShuffle(boundaryVec, gen->rand);
  612. //for (auto tile : boundaryVec)
  613. for (auto tile : boundary)
  614. {
  615. if (gen->isPossible(tile)) //we can place new treasure only on possible tile
  616. {
  617. bool here = true;
  618. gen->foreach_neighbour (tile, [gen, &here](int3 pos)
  619. {
  620. if (!(gen->isBlocked(pos) || gen->isPossible(pos)))
  621. here = false;
  622. });
  623. if (here)
  624. {
  625. placeFound = tile;
  626. break;
  627. }
  628. }
  629. }
  630. if (placeFound.valid())
  631. info.nextTreasurePos = placeFound;
  632. }
  633. if (treasures.size())
  634. {
  635. //find object closest to zone center, then con nect it to the middle of the zone
  636. int3 zoneCenter = getPos();
  637. int3 closestTile = int3(-1,-1,-1);
  638. float minDistance = 1e10;
  639. for (auto treasure : treasures)
  640. {
  641. if (zoneCenter.dist2d(treasure.first) < minDistance)
  642. {
  643. closestTile = treasure.first;
  644. minDistance = zoneCenter.dist2d(treasure.first);
  645. }
  646. }
  647. assert (closestTile.valid());
  648. if (!crunchPath (gen, closestTile, findClosestTile(freePaths, closestTile), id)) //make sure pile is connected to the middle of zone
  649. {
  650. for (auto treasure : treasures)
  651. {
  652. if (gen->isPossible(treasure.first))
  653. gen->setOccupied (treasure.first, ETileType::BLOCKED);
  654. }
  655. return true;
  656. }
  657. for (auto tile : boundary) //guard must be standing there
  658. {
  659. if (gen->isFree(tile)) //this tile could be already blocked, don't place a monster here
  660. {
  661. guardPos = tile;
  662. break;
  663. }
  664. }
  665. if (guardPos.valid())
  666. {
  667. for (auto treasure : treasures)
  668. {
  669. int3 visitableOffset = treasure.second->getVisitableOffset();
  670. placeObject(gen, treasure.second, treasure.first + visitableOffset);
  671. }
  672. if (addMonster(gen, guardPos, currentValue))
  673. {//block only if the object is guarded
  674. for (auto tile : boundary)
  675. {
  676. if (gen->isPossible(tile))
  677. gen->setOccupied (tile, ETileType::BLOCKED);
  678. }
  679. }
  680. }
  681. else //we couldn't make a connection to this location, block it
  682. {
  683. for (auto treasure : treasures)
  684. {
  685. if (gen->isPossible(treasure.first))
  686. gen->setOccupied (treasure.first, ETileType::BLOCKED);
  687. }
  688. }
  689. return true;
  690. }
  691. else //we did not place eveyrthing successfully
  692. return false;
  693. }
  694. void CRmgTemplateZone::initTownType (CMapGenerator* gen)
  695. {
  696. //FIXME: handle case that this player is not present -> towns should be set to neutral
  697. int totalTowns = 0;
  698. auto addNewTowns = [&totalTowns, gen, this](int count, bool hasFort, PlayerColor player)
  699. {
  700. for (int i = 0; i < count; i++)
  701. {
  702. auto town = new CGTownInstance();
  703. town->ID = Obj::TOWN;
  704. if (this->townsAreSameType)
  705. town->subID = townType;
  706. else
  707. town->subID = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand); //TODO: check allowed town types for this zone
  708. town->tempOwner = player;
  709. if (hasFort)
  710. town->builtBuildings.insert(BuildingID::FORT);
  711. town->builtBuildings.insert(BuildingID::DEFAULT);
  712. if (!totalTowns)
  713. {
  714. //first town in zone sets the facton of entire zone
  715. town->subID = townType;
  716. //register MAIN town of zone
  717. gen->registerZone(town->subID);
  718. //first town in zone goes in the middle
  719. placeAndGuardObject(gen, town, getPos() + town->getVisitableOffset(), 0);
  720. }
  721. else
  722. addRequiredObject (town);
  723. totalTowns++;
  724. }
  725. };
  726. if ((type == ETemplateZoneType::CPU_START) || (type == ETemplateZoneType::PLAYER_START))
  727. {
  728. //set zone types to player faction, generate main town
  729. logGlobal->infoStream() << "Preparing playing zone";
  730. int player_id = *owner - 1;
  731. auto & playerInfo = gen->map->players[player_id];
  732. if (playerInfo.canAnyonePlay())
  733. {
  734. PlayerColor player(player_id);
  735. townType = gen->mapGenOptions->getPlayersSettings().find(player)->second.getStartingTown();
  736. if(townType == CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  737. townType = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand); // all possible towns, skip neutral
  738. auto town = new CGTownInstance();
  739. town->ID = Obj::TOWN;
  740. town->subID = townType;
  741. town->tempOwner = player;
  742. town->builtBuildings.insert(BuildingID::FORT);
  743. town->builtBuildings.insert(BuildingID::DEFAULT);
  744. //towns are big objects and should be centered around visitable position
  745. placeAndGuardObject(gen, town, getPos() + town->getVisitableOffset(), 0); //generate no guards, but free path to entrance
  746. totalTowns++;
  747. //register MAIN town of zone only
  748. gen->registerZone (town->subID);
  749. logGlobal->traceStream() << "Fill player info " << player_id;
  750. // Update player info
  751. playerInfo.allowedFactions.clear();
  752. playerInfo.allowedFactions.insert (townType);
  753. playerInfo.hasMainTown = true;
  754. playerInfo.posOfMainTown = town->pos - town->getVisitableOffset();
  755. playerInfo.generateHeroAtMainTown = true;
  756. //now create actual towns
  757. addNewTowns (playerTowns.getCastleCount() - 1, true, player);
  758. addNewTowns (playerTowns.getTownCount(), false, player);
  759. //requiredObjects.push_back(town);
  760. }
  761. else
  762. {
  763. type = ETemplateZoneType::TREASURE;
  764. townType = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  765. logGlobal->infoStream() << "Skipping this zone cause no player";
  766. }
  767. }
  768. else //no player
  769. {
  770. townType = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  771. }
  772. addNewTowns (neutralTowns.getCastleCount(), true, PlayerColor::NEUTRAL);
  773. addNewTowns (neutralTowns.getTownCount(), false, PlayerColor::NEUTRAL);
  774. }
  775. void CRmgTemplateZone::initTerrainType (CMapGenerator* gen)
  776. {
  777. if (matchTerrainToTown)
  778. terrainType = VLC->townh->factions[townType]->nativeTerrain;
  779. else
  780. terrainType = *RandomGeneratorUtil::nextItem(terrainTypes, gen->rand);
  781. //TODO: allow new types of terrain?
  782. if (pos.z)
  783. {
  784. if (terrainType != ETerrainType::LAVA)
  785. terrainType = ETerrainType::SUBTERRANEAN;
  786. }
  787. else
  788. {
  789. if (terrainType == ETerrainType::SUBTERRANEAN)
  790. terrainType = ETerrainType::DIRT;
  791. }
  792. paintZoneTerrain (gen, terrainType);
  793. }
  794. void CRmgTemplateZone::paintZoneTerrain (CMapGenerator* gen, ETerrainType terrainType)
  795. {
  796. std::vector<int3> tiles;
  797. for (auto tile : tileinfo)
  798. {
  799. tiles.push_back (tile);
  800. }
  801. gen->editManager->getTerrainSelection().setSelection(tiles);
  802. gen->editManager->drawTerrain(terrainType, &gen->rand);
  803. }
  804. bool CRmgTemplateZone::placeMines (CMapGenerator* gen)
  805. {
  806. std::vector<Res::ERes> required_mines;
  807. required_mines.push_back(Res::ERes::WOOD);
  808. required_mines.push_back(Res::ERes::ORE);
  809. static const Res::ERes woodOre[] = {Res::ERes::WOOD, Res::ERes::ORE};
  810. static const Res::ERes preciousResources[] = {Res::ERes::GEMS, Res::ERes::CRYSTAL, Res::ERes::MERCURY, Res::ERes::SULFUR};
  811. //TODO: factory / copy constructor?
  812. for (const auto & res : woodOre)
  813. {
  814. //TODO: these 2 should be close to town (within 12 tiles radius)
  815. for (int i = 0; i < mines[res]; i++)
  816. {
  817. auto mine = new CGMine();
  818. mine->ID = Obj::MINE;
  819. mine->subID = static_cast<si32>(res);
  820. mine->producedResource = res;
  821. mine->producedQuantity = mine->defaultResProduction();
  822. addRequiredObject(mine, 1500);
  823. }
  824. }
  825. for (const auto & res : preciousResources)
  826. {
  827. for (int i = 0; i < mines[res]; i++)
  828. {
  829. auto mine = new CGMine();
  830. mine->ID = Obj::MINE;
  831. mine->subID = static_cast<si32>(res);
  832. mine->producedResource = res;
  833. mine->producedQuantity = mine->defaultResProduction();
  834. addRequiredObject(mine, 3500);
  835. }
  836. }
  837. for (int i = 0; i < mines[Res::GOLD]; i++)
  838. {
  839. auto mine = new CGMine();
  840. mine->ID = Obj::MINE;
  841. mine->subID = static_cast<si32>(Res::GOLD);
  842. mine->producedResource = Res::GOLD;
  843. mine->producedQuantity = mine->defaultResProduction();
  844. addRequiredObject(mine, 7000);
  845. }
  846. return true;
  847. }
  848. bool CRmgTemplateZone::createRequiredObjects(CMapGenerator* gen)
  849. {
  850. logGlobal->infoStream() << "Creating required objects";
  851. for(const auto &obj : requiredObjects)
  852. {
  853. int3 pos;
  854. logGlobal->traceStream() << "Looking for place";
  855. if ( ! findPlaceForObject(gen, obj.first, 3, pos))
  856. {
  857. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") %id;
  858. //TODO CLEANUP!
  859. return false;
  860. }
  861. logGlobal->traceStream() << "Place found";
  862. placeObject(gen, obj.first, pos);
  863. guardObject (gen, obj.first, obj.second);
  864. }
  865. return true;
  866. }
  867. void CRmgTemplateZone::createTreasures(CMapGenerator* gen)
  868. {
  869. const double minDistance = 3;
  870. do {
  871. int3 pos;
  872. if ( ! findPlaceForTreasurePile(gen, minDistance, pos))
  873. {
  874. break;
  875. }
  876. createTreasurePile (gen, pos);
  877. } while(true);
  878. }
  879. void CRmgTemplateZone::createObstacles(CMapGenerator* gen)
  880. {
  881. if (pos.z) //underground
  882. {
  883. std::vector<int3> rockTiles;
  884. for (auto tile : tileinfo)
  885. {
  886. if (gen->shouldBeBlocked(tile))
  887. {
  888. bool placeRock = true;
  889. gen->foreach_neighbour (tile, [gen, &placeRock](int3 &pos)
  890. {
  891. if (!(gen->shouldBeBlocked(pos) || gen->isPossible(pos)))
  892. placeRock = false;
  893. });
  894. if (placeRock)
  895. {
  896. rockTiles.push_back(tile);
  897. }
  898. }
  899. }
  900. gen->editManager->getTerrainSelection().setSelection(rockTiles);
  901. gen->editManager->drawTerrain(ETerrainType::ROCK, &gen->rand);
  902. //for (auto tile : rockTiles)
  903. //{
  904. // gen->setOccupied (tile, ETileType::USED);
  905. // gen->foreach_neighbour (tile, [gen](int3 &pos)
  906. // {
  907. // if (!gen->isUsed(pos))
  908. // gen->setOccupied (pos, ETileType::BLOCKED);
  909. // });
  910. //}
  911. }
  912. //get all possible obstacles for this terrain
  913. for (auto primaryID : VLC->objtypeh->knownObjects())
  914. {
  915. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  916. {
  917. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  918. if (handler->isStaticObject())
  919. {
  920. for (auto temp : handler->getTemplates())
  921. {
  922. if (temp.canBePlacedAt(terrainType) && temp.getBlockMapOffset().valid())
  923. possibleObstacles.push_back(temp);
  924. }
  925. }
  926. }
  927. }
  928. auto sel = gen->editManager->getTerrainSelection();
  929. sel.clearSelection();
  930. auto tryToPlaceObstacleHere = [this, gen](int3& tile)-> bool
  931. {
  932. auto temp = *RandomGeneratorUtil::nextItem(possibleObstacles, gen->rand);
  933. int3 obstaclePos = tile - temp.getBlockMapOffset();
  934. if (canObstacleBePlacedHere(gen, temp, obstaclePos)) //can be placed here
  935. {
  936. auto obj = VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  937. placeObject(gen, obj, obstaclePos);
  938. return true;
  939. }
  940. return false;
  941. };
  942. for (auto tile : tileinfo)
  943. {
  944. if (gen->shouldBeBlocked(tile)) //fill tiles that should be blocked with obstacles
  945. {
  946. while (!tryToPlaceObstacleHere(tile));
  947. }
  948. else if (gen->isPossible(tile))
  949. {
  950. //try to place random obstacle once - if not possible, leave it clear
  951. tryToPlaceObstacleHere(tile);
  952. }
  953. }
  954. }
  955. bool CRmgTemplateZone::fill(CMapGenerator* gen)
  956. {
  957. initTownType(gen);
  958. initTerrainType(gen);
  959. addAllPossibleObjects (gen);
  960. placeMines(gen);
  961. createRequiredObjects(gen);
  962. fractalize(gen); //after required objects are created and linked with their own paths
  963. createTreasures(gen);
  964. createObstacles(gen);
  965. logGlobal->infoStream() << boost::format ("Zone %d filled successfully") %id;
  966. return true;
  967. }
  968. bool CRmgTemplateZone::findPlaceForTreasurePile(CMapGenerator* gen, si32 min_dist, int3 &pos)
  969. {
  970. //si32 min_dist = sqrt(tileinfo.size()/density);
  971. int best_distance = 0;
  972. bool result = false;
  973. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  974. for(auto tile : tileinfo)
  975. {
  976. auto dist = gen->getTile(tile).getNearestObjectDistance();
  977. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  978. {
  979. bool allTilesAvailable = true;
  980. gen->foreach_neighbour (tile, [&gen, &allTilesAvailable](int3 neighbour)
  981. {
  982. if (!(gen->isPossible(neighbour) || gen->isBlocked(neighbour)))
  983. {
  984. allTilesAvailable = false; //all present tiles must be already blocked or ready for new objects
  985. }
  986. });
  987. if (allTilesAvailable)
  988. {
  989. best_distance = dist;
  990. pos = tile;
  991. result = true;
  992. }
  993. }
  994. }
  995. if (result)
  996. {
  997. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  998. }
  999. return result;
  1000. }
  1001. bool CRmgTemplateZone::canObstacleBePlacedHere(CMapGenerator* gen, ObjectTemplate &temp, int3 &pos)
  1002. {
  1003. if (!gen->map->isInTheMap(pos)) //blockmap may fit in the map, but botom-right corner does not
  1004. return false;
  1005. auto tilesBlockedByObject = temp.getBlockedOffsets();
  1006. for (auto blockingTile : tilesBlockedByObject)
  1007. {
  1008. int3 t = pos + blockingTile;
  1009. if (!gen->map->isInTheMap(t) || !(gen->isPossible(t) || gen->shouldBeBlocked(t)))
  1010. {
  1011. return false; //if at least one tile is not possible, object can't be placed here
  1012. }
  1013. }
  1014. return true;
  1015. }
  1016. bool CRmgTemplateZone::findPlaceForObject(CMapGenerator* gen, CGObjectInstance* obj, si32 min_dist, int3 &pos)
  1017. {
  1018. //we need object apperance to deduce free tiles
  1019. if (obj->appearance.id == Obj::NO_OBJ)
  1020. {
  1021. auto templates = VLC->objtypeh->getHandlerFor(obj->ID, obj->subID)->getTemplates(gen->map->getTile(getPos()).terType);
  1022. if (templates.empty())
  1023. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") %obj->ID %obj->subID %pos));
  1024. obj->appearance = templates.front();
  1025. }
  1026. //si32 min_dist = sqrt(tileinfo.size()/density);
  1027. int best_distance = 0;
  1028. bool result = false;
  1029. //si32 w = gen->map->width;
  1030. //si32 h = gen->map->height;
  1031. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  1032. auto tilesBlockedByObject = obj->getBlockedOffsets();
  1033. for (auto tile : tileinfo)
  1034. {
  1035. //object must be accessible from at least one surounding tile
  1036. bool accessible = false;
  1037. for (int x = -1; x < 2; x++)
  1038. for (int y = -1; y <2; y++)
  1039. {
  1040. if (x && y) //check only if object is visitable from another tile
  1041. {
  1042. int3 offset = obj->getVisitableOffset() + int3(x, y, 0);
  1043. if (!vstd::contains(tilesBlockedByObject, offset))
  1044. {
  1045. int3 nearbyPos = tile + offset;
  1046. if (gen->map->isInTheMap(nearbyPos))
  1047. {
  1048. if (obj->appearance.isVisitableFrom(x, y) && !gen->isBlocked(nearbyPos))
  1049. accessible = true;
  1050. }
  1051. }
  1052. }
  1053. };
  1054. if (!accessible)
  1055. continue;
  1056. auto ti = gen->getTile(tile);
  1057. auto dist = ti.getNearestObjectDistance();
  1058. //avoid borders
  1059. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  1060. {
  1061. bool allTilesAvailable = true;
  1062. for (auto blockingTile : tilesBlockedByObject)
  1063. {
  1064. int3 t = tile + blockingTile;
  1065. if (!gen->map->isInTheMap(t) || !gen->isPossible(t))
  1066. {
  1067. allTilesAvailable = false; //if at least one tile is not possible, object can't be placed here
  1068. break;
  1069. }
  1070. }
  1071. if (allTilesAvailable)
  1072. {
  1073. best_distance = dist;
  1074. pos = tile;
  1075. result = true;
  1076. }
  1077. }
  1078. }
  1079. if (result)
  1080. {
  1081. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  1082. }
  1083. return result;
  1084. }
  1085. void CRmgTemplateZone::checkAndPlaceObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  1086. {
  1087. if (!gen->map->isInTheMap(pos))
  1088. throw rmgException(boost::to_string(boost::format("Position of object %d at %s is outside the map") % object->id % pos));
  1089. object->pos = pos;
  1090. if (object->isVisitable() && !gen->map->isInTheMap(object->visitablePos()))
  1091. 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()));
  1092. for (auto tile : object->getBlockedPos())
  1093. {
  1094. if (!gen->map->isInTheMap(tile))
  1095. throw rmgException(boost::to_string(boost::format("Tile %s of object %d at %s is outside the map") % tile() % object->id % object->pos()));
  1096. }
  1097. if (object->appearance.id == Obj::NO_OBJ)
  1098. {
  1099. auto terrainType = gen->map->getTile(pos).terType;
  1100. auto templates = VLC->objtypeh->getHandlerFor(object->ID, object->subID)->getTemplates(terrainType);
  1101. if (templates.empty())
  1102. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s (terrain %d)") %object->ID %object->subID %pos %terrainType));
  1103. object->appearance = templates.front();
  1104. }
  1105. gen->map->addBlockVisTiles(object);
  1106. gen->editManager->insertObject(object, pos);
  1107. //logGlobal->traceStream() << boost::format ("Successfully inserted object (%d,%d) at pos %s") %object->ID %object->subID %pos();
  1108. }
  1109. void CRmgTemplateZone::placeObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  1110. {
  1111. //logGlobal->traceStream() << boost::format("Inserting object at %d %d") % pos.x % pos.y;
  1112. checkAndPlaceObject (gen, object, pos);
  1113. auto points = object->getBlockedPos();
  1114. if (object->isVisitable())
  1115. points.insert(pos + object->getVisitableOffset());
  1116. points.insert(pos);
  1117. for(auto p : points)
  1118. {
  1119. if (gen->map->isInTheMap(p))
  1120. {
  1121. gen->setOccupied(p, ETileType::USED);
  1122. }
  1123. }
  1124. for(auto tile : tileinfo)
  1125. {
  1126. si32 d = pos.dist2dSQ(tile); //optimization, only relative distance is interesting
  1127. gen->setNearestObjectDistance(tile, std::min(d, gen->getNearestObjectDistance(tile)));
  1128. }
  1129. }
  1130. void CRmgTemplateZone::placeAndGuardObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, si32 str)
  1131. {
  1132. placeObject(gen, object, pos);
  1133. guardObject(gen, object, str);
  1134. }
  1135. std::vector<int3> CRmgTemplateZone::getAccessibleOffsets (CMapGenerator* gen, CGObjectInstance* object)
  1136. {
  1137. //get all tiles from which this object can be accessed
  1138. int3 visitable = object->visitablePos();
  1139. std::vector<int3> tiles;
  1140. auto tilesBlockedByObject = object->getBlockedPos(); //absolue value, as object is already placed
  1141. gen->foreach_neighbour(visitable, [&](int3& pos)
  1142. {
  1143. if (gen->isPossible(pos))
  1144. {
  1145. if (!vstd::contains(tilesBlockedByObject, pos))
  1146. {
  1147. if (object->appearance.isVisitableFrom(pos.x - visitable.x, pos.y - visitable.y) && !gen->isBlocked(pos)) //TODO: refactor - info about visitability from absolute coordinates
  1148. {
  1149. tiles.push_back(pos);
  1150. }
  1151. }
  1152. };
  1153. });
  1154. return tiles;
  1155. }
  1156. bool CRmgTemplateZone::guardObject(CMapGenerator* gen, CGObjectInstance* object, si32 str)
  1157. {
  1158. logGlobal->traceStream() << boost::format("Guard object at %s") % object->pos();
  1159. std::vector<int3> tiles = getAccessibleOffsets (gen, object);
  1160. int3 guardTile(-1,-1,-1);
  1161. for (auto tile : tiles)
  1162. {
  1163. //crunching path may fail if center of teh zone is dirrectly over wide object
  1164. if (crunchPath (gen, tile, findClosestTile(freePaths, tile), id)) //make sure object is accessible before surrounding it with blocked tiles
  1165. {
  1166. guardTile = tile;
  1167. break;
  1168. }
  1169. }
  1170. if (!guardTile.valid())
  1171. {
  1172. logGlobal->errorStream() << boost::format("Failed to crunch path to object at %s") % object->pos();
  1173. return false;
  1174. }
  1175. if (addMonster (gen, guardTile, str)) //do not place obstacles around unguarded object
  1176. {
  1177. for (auto pos : tiles)
  1178. {
  1179. if (!gen->isFree(pos))
  1180. gen->setOccupied(pos, ETileType::BLOCKED);
  1181. }
  1182. gen->setOccupied (guardTile, ETileType::USED);
  1183. }
  1184. else //allow no guard or other object in front of this object
  1185. {
  1186. for (auto tile : tiles)
  1187. gen->setOccupied (tile, ETileType::FREE);
  1188. }
  1189. return true;
  1190. }
  1191. ObjectInfo CRmgTemplateZone::getRandomObject (CMapGenerator* gen, CTreasurePileInfo &info, ui32 value)
  1192. {
  1193. std::vector<std::pair<ui32, ObjectInfo>> tresholds;
  1194. ui32 total = 0;
  1195. ui32 minValue = 0.25f * value;
  1196. //roulette wheel
  1197. for (auto oi : possibleObjects)
  1198. {
  1199. if (oi.value >= minValue && oi.value <= value)
  1200. {
  1201. int3 visitableOffset = oi.templ.getVisitableOffset(); //visitablePos assumes object will be shifter by visitableOffset
  1202. if (info.visitablePositions.size()) //do not try to match first object in zone
  1203. {
  1204. bool fitsHere = false;
  1205. int3 visitablePos = info.nextTreasurePos;
  1206. if (oi.templ.isVisitableFromTop())
  1207. {
  1208. for (auto tile : info.visitablePositions)
  1209. {
  1210. int3 actualTile = tile + visitableOffset;
  1211. if (visitablePos.areNeighbours(actualTile)) //we access object from any position
  1212. {
  1213. fitsHere = true;
  1214. break;
  1215. }
  1216. }
  1217. }
  1218. else
  1219. {
  1220. //if object is not visitable from top, it must be accessible from below or side
  1221. for (auto tile : info.visitableFromTopPositions)
  1222. {
  1223. int3 actualTile = tile + visitableOffset;
  1224. if (visitablePos.areNeighbours(actualTile) && visitablePos.y >= actualTile.y) //we access object from below or side
  1225. {
  1226. fitsHere = true;
  1227. break;
  1228. }
  1229. }
  1230. }
  1231. if (!fitsHere)
  1232. continue;
  1233. }
  1234. //now check blockmap, including our already reserved pile area
  1235. bool fitsBlockmap = true;
  1236. std::set<int3> blockedOffsets = oi.templ.getBlockedOffsets();
  1237. blockedOffsets.insert (visitableOffset);
  1238. for (auto blockingTile : blockedOffsets)
  1239. {
  1240. int3 t = info.nextTreasurePos + visitableOffset + blockingTile;
  1241. if (!gen->map->isInTheMap(t) || vstd::contains(info.occupiedPositions, t))
  1242. {
  1243. fitsBlockmap = false; //if at least one tile is not possible, object can't be placed here
  1244. break;
  1245. }
  1246. if (!(gen->isPossible(t) || gen->isBlocked(t))) //blocked tiles of object may cover blocked tiles, but not used or free tiles
  1247. {
  1248. fitsBlockmap = false;
  1249. break;
  1250. }
  1251. }
  1252. if (!fitsBlockmap)
  1253. continue;
  1254. total += oi.probability;
  1255. tresholds.push_back (std::make_pair (total, oi));
  1256. }
  1257. }
  1258. //Generate pandora Box with gold if the value is extremely high
  1259. ObjectInfo oi;
  1260. if (tresholds.empty())
  1261. {
  1262. if (minValue > 20000) //we don't have object valuable enough
  1263. {
  1264. oi.generateObject = [minValue]() -> CGObjectInstance *
  1265. {
  1266. auto obj = new CGPandoraBox();
  1267. obj->ID = Obj::PANDORAS_BOX;
  1268. obj->subID = 0;
  1269. obj->resources[Res::GOLD] = minValue;
  1270. return obj;
  1271. };
  1272. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1273. oi.value = minValue;
  1274. oi.probability = 0;
  1275. }
  1276. else
  1277. {
  1278. oi.generateObject = [gen]() -> CGObjectInstance *
  1279. {
  1280. return nullptr;
  1281. };
  1282. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType); //TODO: null template or something? should be never used, but hell knows
  1283. oi.value = 0;
  1284. oi.probability = 0;
  1285. }
  1286. return oi;
  1287. }
  1288. int r = gen->rand.nextInt (1, total);
  1289. for (auto t : tresholds)
  1290. {
  1291. if (r <= t.first)
  1292. return t.second;
  1293. }
  1294. //FIXME: control reaches end of non-void function. Missing return?
  1295. }
  1296. void CRmgTemplateZone::addAllPossibleObjects (CMapGenerator* gen)
  1297. {
  1298. ObjectInfo oi;
  1299. for (auto primaryID : VLC->objtypeh->knownObjects())
  1300. {
  1301. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  1302. {
  1303. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  1304. if (!handler->isStaticObject() && handler->getRMGInfo().value)
  1305. {
  1306. for (auto temp : handler->getTemplates())
  1307. {
  1308. if (temp.canBePlacedAt(terrainType))
  1309. {
  1310. oi.generateObject = [gen, temp]() -> CGObjectInstance *
  1311. {
  1312. return VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  1313. };
  1314. oi.value = handler->getRMGInfo().value;
  1315. oi.probability = handler->getRMGInfo().rarity;
  1316. oi.templ = temp;
  1317. possibleObjects.push_back (oi);
  1318. }
  1319. }
  1320. }
  1321. }
  1322. }
  1323. //dwellings
  1324. auto subObjects = VLC->objtypeh->knownSubObjects(Obj::CREATURE_GENERATOR1);
  1325. //don't spawn original "neutral" dwellings that got replaced by Conflux dwellings in AB
  1326. static int elementalConfluxROE[] = {7, 13, 16, 47};
  1327. for (int i = 0; i < 4; i++)
  1328. vstd::erase_if_present(subObjects, elementalConfluxROE[i]);
  1329. for (auto secondaryID : subObjects)
  1330. {
  1331. auto dwellingHandler = dynamic_cast<const CDwellingInstanceConstructor*>(VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID).get());
  1332. auto creatures = dwellingHandler->getProducedCreatures();
  1333. if (creatures.empty())
  1334. continue;
  1335. auto cre = creatures.front();
  1336. if (cre->faction == townType)
  1337. {
  1338. oi.value = cre->AIValue * cre->growth * (1 + (float)(gen->getZoneCount(cre->faction)) / gen->getTotalZoneCount() + (float)(gen->getZoneCount(cre->faction) / 2)); //TODO: include town count in formula
  1339. oi.probability = 40;
  1340. for (auto temp : dwellingHandler->getTemplates())
  1341. {
  1342. if (temp.canBePlacedAt(terrainType))
  1343. {
  1344. oi.generateObject = [gen, temp, secondaryID, dwellingHandler]() -> CGObjectInstance *
  1345. {
  1346. auto obj = VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID)->create(temp);
  1347. //dwellingHandler->configureObject(obj, gen->rand);
  1348. obj->tempOwner = PlayerColor::NEUTRAL;
  1349. return obj;
  1350. };
  1351. oi.templ = temp;
  1352. possibleObjects.push_back (oi);
  1353. }
  1354. }
  1355. }
  1356. }
  1357. static const int scrollValues[] = {500, 2000, 3000, 4000, 5000};
  1358. for (int i = 0; i < 5; i++)
  1359. {
  1360. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1361. {
  1362. auto obj = new CGArtifact();
  1363. obj->ID = Obj::SPELL_SCROLL;
  1364. obj->subID = 0;
  1365. std::vector<SpellID> out;
  1366. //TODO: unify with cb->getAllowedSpells?
  1367. for (ui32 i = 0; i < gen->map->allowedSpell.size(); i++) //spellh size appears to be greater (?)
  1368. {
  1369. const CSpell *spell = SpellID(i).toSpell();
  1370. if (gen->map->allowedSpell[spell->id] && spell->level == i+1)
  1371. {
  1372. out.push_back(spell->id);
  1373. }
  1374. }
  1375. auto a = CArtifactInstance::createScroll(RandomGeneratorUtil::nextItem(out, gen->rand)->toSpell());
  1376. gen->map->addNewArtifactInstance(a);
  1377. obj->storedArtifact = a;
  1378. return obj;
  1379. };
  1380. oi.setTemplate (Obj::SPELL_SCROLL, 0, terrainType);
  1381. oi.value = scrollValues[i];
  1382. oi.probability = 30;
  1383. possibleObjects.push_back (oi);
  1384. }
  1385. //pandora box with gold
  1386. for (int i = 1; i < 5; i++)
  1387. {
  1388. oi.generateObject = [i]() -> CGObjectInstance *
  1389. {
  1390. auto obj = new CGPandoraBox();
  1391. obj->ID = Obj::PANDORAS_BOX;
  1392. obj->subID = 0;
  1393. obj->resources[Res::GOLD] = i * 5000;
  1394. return obj;
  1395. };
  1396. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1397. oi.value = i * 5000;;
  1398. oi.probability = 5;
  1399. possibleObjects.push_back (oi);
  1400. }
  1401. //pandora box with experience
  1402. for (int i = 1; i < 5; i++)
  1403. {
  1404. oi.generateObject = [i]() -> CGObjectInstance *
  1405. {
  1406. auto obj = new CGPandoraBox();
  1407. obj->ID = Obj::PANDORAS_BOX;
  1408. obj->subID = 0;
  1409. obj->gainedExp = i * 5000;
  1410. return obj;
  1411. };
  1412. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1413. oi.value = i * 6000;;
  1414. oi.probability = 20;
  1415. possibleObjects.push_back (oi);
  1416. }
  1417. //pandora box with creatures
  1418. static const int tierValues[] = {5000, 7000, 9000, 12000, 16000, 21000, 27000};
  1419. for (auto creature : VLC->creh->creatures)
  1420. {
  1421. if (!creature->special && VLC->townh->factions[creature->faction]->nativeTerrain == terrainType)
  1422. {
  1423. int actualTier = creature->level > 7 ? 6 : creature->level-1;
  1424. int creaturesAmount = tierValues[actualTier] / creature->AIValue;
  1425. if (creaturesAmount <= 5)
  1426. {
  1427. }
  1428. else if (creaturesAmount <= 12)
  1429. {
  1430. (creaturesAmount /= 2) *= 2;
  1431. }
  1432. else if (creaturesAmount <= 50)
  1433. {
  1434. creaturesAmount = boost::math::round((float)creaturesAmount / 5) * 5;
  1435. }
  1436. else if (creaturesAmount <= 12)
  1437. {
  1438. creaturesAmount = boost::math::round((float)creaturesAmount / 10) * 10;
  1439. }
  1440. oi.generateObject = [creature, creaturesAmount]() -> CGObjectInstance *
  1441. {
  1442. auto obj = new CGPandoraBox();
  1443. obj->ID = Obj::PANDORAS_BOX;
  1444. obj->subID = 0;
  1445. auto stack = new CStackInstance(creature, creaturesAmount);
  1446. obj->creatures.putStack(SlotID(0), stack);
  1447. return obj;
  1448. };
  1449. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1450. oi.value = (2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount()))/3; //TODO: count number of towns on the map
  1451. oi.probability = 3;
  1452. possibleObjects.push_back (oi);
  1453. }
  1454. }
  1455. //Pandora with 12 spells of certain level
  1456. for (int i = 1; i <= GameConstants::SPELL_LEVELS; i++)
  1457. {
  1458. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1459. {
  1460. auto obj = new CGPandoraBox();
  1461. obj->ID = Obj::PANDORAS_BOX;
  1462. obj->subID = 0;
  1463. std::vector <CSpell *> spells;
  1464. for (auto spell : VLC->spellh->objects)
  1465. {
  1466. if (!spell->isSpecialSpell() && spell->level == i)
  1467. spells.push_back(spell);
  1468. }
  1469. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1470. for (int j = 0; j < std::min<int>(12, spells.size()); j++)
  1471. {
  1472. obj->spells.push_back (spells[j]->id);
  1473. }
  1474. return obj;
  1475. };
  1476. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1477. oi.value = (i + 1) * 2500; //5000 - 15000
  1478. oi.probability = 2;
  1479. possibleObjects.push_back (oi);
  1480. }
  1481. //Pandora with 15 spells of certain school
  1482. for (int i = 1; i <= 4; i++)
  1483. {
  1484. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1485. {
  1486. auto obj = new CGPandoraBox();
  1487. obj->ID = Obj::PANDORAS_BOX;
  1488. obj->subID = 0;
  1489. std::vector <CSpell *> spells;
  1490. for (auto spell : VLC->spellh->objects)
  1491. {
  1492. if (!spell->isSpecialSpell())
  1493. {
  1494. bool school = false; //TODO: we could have better interface for iterating schools
  1495. switch (i)
  1496. {
  1497. case 1:
  1498. school = spell->air;
  1499. case 2:
  1500. school = spell->earth;
  1501. case 3:
  1502. school = spell->fire;
  1503. case 4:
  1504. school = spell->water;
  1505. }
  1506. if (school)
  1507. spells.push_back(spell);
  1508. }
  1509. }
  1510. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1511. for (int j = 0; j < std::min<int>(15, spells.size()); j++)
  1512. {
  1513. obj->spells.push_back (spells[j]->id);
  1514. }
  1515. return obj;
  1516. };
  1517. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1518. oi.value = 15000;
  1519. oi.probability = 2;
  1520. possibleObjects.push_back (oi);
  1521. }
  1522. // Pandora box with 60 random spells
  1523. oi.generateObject = [gen]() -> CGObjectInstance *
  1524. {
  1525. auto obj = new CGPandoraBox();
  1526. obj->ID = Obj::PANDORAS_BOX;
  1527. obj->subID = 0;
  1528. std::vector <CSpell *> spells;
  1529. for (auto spell : VLC->spellh->objects)
  1530. {
  1531. if (!spell->isSpecialSpell())
  1532. spells.push_back(spell);
  1533. }
  1534. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1535. for (int j = 0; j < std::min<int>(60, spells.size()); j++)
  1536. {
  1537. obj->spells.push_back (spells[j]->id);
  1538. }
  1539. return obj;
  1540. };
  1541. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1542. oi.value = 3000;
  1543. oi.probability = 2;
  1544. possibleObjects.push_back (oi);
  1545. }
  1546. void ObjectInfo::setTemplate (si32 type, si32 subtype, ETerrainType terrainType)
  1547. {
  1548. templ = VLC->objtypeh->getHandlerFor(type, subtype)->getTemplates(terrainType).front();
  1549. }