CMap.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. /*
  2. * CMap.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 "CMap.h"
  12. #include "../CArtHandler.h"
  13. #include "../VCMI_Lib.h"
  14. #include "../CCreatureHandler.h"
  15. #include "../CHeroHandler.h"
  16. #include "../GameSettings.h"
  17. #include "../RiverHandler.h"
  18. #include "../RoadHandler.h"
  19. #include "../TerrainHandler.h"
  20. #include "../mapObjects/CGHeroInstance.h"
  21. #include "../mapObjects/CGTownInstance.h"
  22. #include "../mapObjects/CQuest.h"
  23. #include "../mapObjects/ObjectTemplate.h"
  24. #include "../texts/CGeneralTextHandler.h"
  25. #include "../spells/CSpellHandler.h"
  26. #include "../CSkillHandler.h"
  27. #include "CMapEditManager.h"
  28. #include "CMapOperation.h"
  29. #include "../serializer/JsonSerializeFormat.h"
  30. #include <vstd/RNG.h>
  31. VCMI_LIB_NAMESPACE_BEGIN
  32. void Rumor::serializeJson(JsonSerializeFormat & handler)
  33. {
  34. handler.serializeString("name", name);
  35. handler.serializeStruct("text", text);
  36. }
  37. DisposedHero::DisposedHero() : heroId(0), portrait(255)
  38. {
  39. }
  40. CMapEvent::CMapEvent()
  41. : humanAffected(false)
  42. , computerAffected(false)
  43. , firstOccurrence(0)
  44. , nextOccurrence(0)
  45. {
  46. }
  47. bool CMapEvent::occursToday(int currentDay) const
  48. {
  49. if (currentDay == firstOccurrence + 1)
  50. return true;
  51. if (nextOccurrence == 0)
  52. return false;
  53. if (currentDay < firstOccurrence)
  54. return false;
  55. return (currentDay - firstOccurrence - 1) % nextOccurrence == 0;
  56. }
  57. bool CMapEvent::affectsPlayer(PlayerColor color, bool isHuman) const
  58. {
  59. if (players.count(color) == 0)
  60. return false;
  61. if (!isHuman && !computerAffected)
  62. return false;
  63. if (isHuman && !humanAffected)
  64. return false;
  65. return true;
  66. }
  67. void CMapEvent::serializeJson(JsonSerializeFormat & handler)
  68. {
  69. handler.serializeString("name", name);
  70. handler.serializeStruct("message", message);
  71. if (!handler.saving && handler.getCurrent()["players"].isNumber())
  72. {
  73. // compatibility for old maps
  74. int playersMask = 0;
  75. handler.serializeInt("players", playersMask);
  76. for (int i = 0; i < 8; ++i)
  77. if ((playersMask & (1 << i)) != 0)
  78. players.insert(PlayerColor(i));
  79. }
  80. else
  81. {
  82. handler.serializeIdArray("players", players);
  83. }
  84. handler.serializeInt("humanAffected", humanAffected);
  85. handler.serializeInt("computerAffected", computerAffected);
  86. handler.serializeInt("firstOccurrence", firstOccurrence);
  87. handler.serializeInt("nextOccurrence", nextOccurrence);
  88. resources.serializeJson(handler, "resources");
  89. JsonNode deletedObjectsJson;
  90. for (const auto & entry : deletedObjectsCoordinates)
  91. {
  92. JsonNode values;
  93. JsonNode valueX;
  94. JsonNode valueY;
  95. JsonNode valueZ;
  96. valueX.Float() = static_cast<int>(entry.x);
  97. valueY.Float() = static_cast<int>(entry.y);
  98. valueZ.Float() = static_cast<int>(entry.z);
  99. values.Vector().push_back(valueX);
  100. values.Vector().push_back(valueY);
  101. values.Vector().push_back(valueZ);
  102. deletedObjectsJson.Vector().push_back(values);
  103. }
  104. handler.serializeRaw("deletedObjectsCoordinates", deletedObjectsJson, std::nullopt);
  105. }
  106. void CCastleEvent::serializeJson(JsonSerializeFormat & handler)
  107. {
  108. CMapEvent::serializeJson(handler);
  109. // TODO: handler.serializeIdArray("buildings", buildings);
  110. {
  111. std::vector<BuildingID> temp(buildings.begin(), buildings.end());
  112. auto a = handler.enterArray("buildings");
  113. a.syncSize(temp);
  114. for(int i = 0; i < temp.size(); ++i)
  115. {
  116. int buildingID = temp[i].getNum();
  117. a.serializeInt(i, buildingID);
  118. buildings.insert(buildingID);
  119. }
  120. }
  121. {
  122. auto a = handler.enterArray("creatures");
  123. a.syncSize(creatures);
  124. for(int i = 0; i < creatures.size(); ++i)
  125. a.serializeInt(i, creatures[i]);
  126. }
  127. }
  128. TerrainTile::TerrainTile():
  129. terType(nullptr),
  130. riverType(VLC->riverTypeHandler->getById(River::NO_RIVER)),
  131. roadType(VLC->roadTypeHandler->getById(Road::NO_ROAD)),
  132. terView(0),
  133. riverDir(0),
  134. roadDir(0),
  135. extTileFlags(0),
  136. visitable(false),
  137. blocked(false)
  138. {
  139. }
  140. bool TerrainTile::entrableTerrain(const TerrainTile * from) const
  141. {
  142. return entrableTerrain(from ? from->terType->isLand() : true, from ? from->terType->isWater() : true);
  143. }
  144. bool TerrainTile::entrableTerrain(bool allowLand, bool allowSea) const
  145. {
  146. return terType->isPassable()
  147. && ((allowSea && terType->isWater()) || (allowLand && terType->isLand()));
  148. }
  149. bool TerrainTile::isClear(const TerrainTile * from) const
  150. {
  151. return entrableTerrain(from) && !blocked;
  152. }
  153. Obj TerrainTile::topVisitableId(bool excludeTop) const
  154. {
  155. return topVisitableObj(excludeTop) ? topVisitableObj(excludeTop)->ID : Obj(Obj::NO_OBJ);
  156. }
  157. CGObjectInstance * TerrainTile::topVisitableObj(bool excludeTop) const
  158. {
  159. if(visitableObjects.empty() || (excludeTop && visitableObjects.size() == 1))
  160. return nullptr;
  161. if(excludeTop)
  162. return visitableObjects[visitableObjects.size()-2];
  163. return visitableObjects.back();
  164. }
  165. EDiggingStatus TerrainTile::getDiggingStatus(const bool excludeTop) const
  166. {
  167. if(terType->isWater() || !terType->isPassable())
  168. return EDiggingStatus::WRONG_TERRAIN;
  169. int allowedBlocked = excludeTop ? 1 : 0;
  170. if(blockingObjects.size() > allowedBlocked || topVisitableObj(excludeTop))
  171. return EDiggingStatus::TILE_OCCUPIED;
  172. else
  173. return EDiggingStatus::CAN_DIG;
  174. }
  175. bool TerrainTile::hasFavorableWinds() const
  176. {
  177. return extTileFlags & 128;
  178. }
  179. bool TerrainTile::isWater() const
  180. {
  181. return terType->isWater();
  182. }
  183. CMap::CMap(IGameCallback * cb)
  184. : GameCallbackHolder(cb)
  185. , checksum(0)
  186. , grailPos(-1, -1, -1)
  187. , grailRadius(0)
  188. , waterMap(false)
  189. , uidCounter(0)
  190. {
  191. allHeroes.resize(VLC->heroh->size());
  192. allowedAbilities = VLC->skillh->getDefaultAllowed();
  193. allowedArtifact = VLC->arth->getDefaultAllowed();
  194. allowedSpells = VLC->spellh->getDefaultAllowed();
  195. gameSettings = std::make_unique<GameSettings>();
  196. gameSettings->loadBase(VLC->settingsHandler->getFullConfig());
  197. }
  198. CMap::~CMap()
  199. {
  200. getEditManager()->getUndoManager().clearAll();
  201. for(auto obj : objects)
  202. obj.dellNull();
  203. for(auto quest : quests)
  204. quest.dellNull();
  205. for(auto artInstance : artInstances)
  206. artInstance.dellNull();
  207. resetStaticData();
  208. }
  209. void CMap::removeBlockVisTiles(CGObjectInstance * obj, bool total)
  210. {
  211. const int zVal = obj->pos.z;
  212. for(int fx = 0; fx < obj->getWidth(); ++fx)
  213. {
  214. int xVal = obj->pos.x - fx;
  215. for(int fy = 0; fy < obj->getHeight(); ++fy)
  216. {
  217. int yVal = obj->pos.y - fy;
  218. if(xVal>=0 && xVal < width && yVal>=0 && yVal < height)
  219. {
  220. TerrainTile & curt = terrain[zVal][xVal][yVal];
  221. if(total || obj->visitableAt(xVal, yVal))
  222. {
  223. curt.visitableObjects -= obj;
  224. curt.visitable = curt.visitableObjects.size();
  225. }
  226. if(total || obj->blockingAt(xVal, yVal))
  227. {
  228. curt.blockingObjects -= obj;
  229. curt.blocked = curt.blockingObjects.size();
  230. }
  231. }
  232. }
  233. }
  234. }
  235. void CMap::addBlockVisTiles(CGObjectInstance * obj)
  236. {
  237. const int zVal = obj->pos.z;
  238. for(int fx = 0; fx < obj->getWidth(); ++fx)
  239. {
  240. int xVal = obj->pos.x - fx;
  241. for(int fy = 0; fy < obj->getHeight(); ++fy)
  242. {
  243. int yVal = obj->pos.y - fy;
  244. if(xVal>=0 && xVal < width && yVal >= 0 && yVal < height)
  245. {
  246. TerrainTile & curt = terrain[zVal][xVal][yVal];
  247. if(obj->visitableAt(xVal, yVal))
  248. {
  249. curt.visitableObjects.push_back(obj);
  250. curt.visitable = true;
  251. }
  252. if(obj->blockingAt(xVal, yVal))
  253. {
  254. curt.blockingObjects.push_back(obj);
  255. curt.blocked = true;
  256. }
  257. }
  258. }
  259. }
  260. }
  261. void CMap::calculateGuardingGreaturePositions()
  262. {
  263. int levels = twoLevel ? 2 : 1;
  264. for(int z = 0; z < levels; z++)
  265. {
  266. for(int x = 0; x < width; x++)
  267. {
  268. for(int y = 0; y < height; y++)
  269. {
  270. guardingCreaturePositions[z][x][y] = guardingCreaturePosition(int3(x, y, z));
  271. }
  272. }
  273. }
  274. }
  275. CGHeroInstance * CMap::getHero(HeroTypeID heroID)
  276. {
  277. for(auto & elem : heroesOnMap)
  278. if(elem->getHeroType() == heroID)
  279. return elem;
  280. return nullptr;
  281. }
  282. bool CMap::isCoastalTile(const int3 & pos) const
  283. {
  284. //todo: refactoring: extract neighbor tile iterator and use it in GameState
  285. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  286. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  287. if(!isInTheMap(pos))
  288. {
  289. logGlobal->error("Coastal check outside of map: %s", pos.toString());
  290. return false;
  291. }
  292. if(isWaterTile(pos))
  293. return false;
  294. for(const auto & dir : dirs)
  295. {
  296. const int3 hlp = pos + dir;
  297. if(!isInTheMap(hlp))
  298. continue;
  299. const TerrainTile &hlpt = getTile(hlp);
  300. if(hlpt.isWater())
  301. return true;
  302. }
  303. return false;
  304. }
  305. TerrainTile & CMap::getTile(const int3 & tile)
  306. {
  307. assert(isInTheMap(tile));
  308. return terrain[tile.z][tile.x][tile.y];
  309. }
  310. const TerrainTile & CMap::getTile(const int3 & tile) const
  311. {
  312. assert(isInTheMap(tile));
  313. return terrain[tile.z][tile.x][tile.y];
  314. }
  315. bool CMap::isWaterTile(const int3 &pos) const
  316. {
  317. return isInTheMap(pos) && getTile(pos).isWater();
  318. }
  319. bool CMap::canMoveBetween(const int3 &src, const int3 &dst) const
  320. {
  321. const TerrainTile * dstTile = &getTile(dst);
  322. const TerrainTile * srcTile = &getTile(src);
  323. return checkForVisitableDir(src, dstTile, dst) && checkForVisitableDir(dst, srcTile, src);
  324. }
  325. bool CMap::checkForVisitableDir(const int3 & src, const TerrainTile * pom, const int3 & dst) const
  326. {
  327. if (!pom->entrableTerrain()) //rock is never accessible
  328. return false;
  329. for(auto * obj : pom->visitableObjects) //checking destination tile
  330. {
  331. if(!vstd::contains(pom->blockingObjects, obj)) //this visitable object is not blocking, ignore
  332. continue;
  333. if (!obj->appearance->isVisitableFrom(src.x - dst.x, src.y - dst.y))
  334. return false;
  335. }
  336. return true;
  337. }
  338. int3 CMap::guardingCreaturePosition (int3 pos) const
  339. {
  340. const int3 originalPos = pos;
  341. // Give monster at position priority.
  342. if (!isInTheMap(pos))
  343. return int3(-1, -1, -1);
  344. const TerrainTile &posTile = getTile(pos);
  345. if (posTile.visitable)
  346. {
  347. for (CGObjectInstance* obj : posTile.visitableObjects)
  348. {
  349. if (obj->ID == Obj::MONSTER)
  350. return pos;
  351. }
  352. }
  353. // See if there are any monsters adjacent.
  354. bool water = posTile.isWater();
  355. pos -= int3(1, 1, 0); // Start with top left.
  356. for (int dx = 0; dx < 3; dx++)
  357. {
  358. for (int dy = 0; dy < 3; dy++)
  359. {
  360. if (isInTheMap(pos))
  361. {
  362. const auto & tile = getTile(pos);
  363. if (tile.visitable && (tile.isWater() == water))
  364. {
  365. for (CGObjectInstance* obj : tile.visitableObjects)
  366. {
  367. if (obj->ID == Obj::MONSTER && checkForVisitableDir(pos, &posTile, originalPos)) // Monster being able to attack investigated tile
  368. {
  369. return pos;
  370. }
  371. }
  372. }
  373. }
  374. pos.y++;
  375. }
  376. pos.y -= 3;
  377. pos.x++;
  378. }
  379. return int3(-1, -1, -1);
  380. }
  381. const CGObjectInstance * CMap::getObjectiveObjectFrom(const int3 & pos, Obj type)
  382. {
  383. for (CGObjectInstance * object : getTile(pos).visitableObjects)
  384. {
  385. if (object->ID == type)
  386. return object;
  387. }
  388. // There is weird bug because of which sometimes heroes will not be found properly despite having correct position
  389. // Try to workaround that and find closest object that we can use
  390. logGlobal->error("Failed to find object of type %d at %s", type.getNum(), pos.toString());
  391. logGlobal->error("Will try to find closest matching object");
  392. CGObjectInstance * bestMatch = nullptr;
  393. for (CGObjectInstance * object : objects)
  394. {
  395. if (object && object->ID == type)
  396. {
  397. if (bestMatch == nullptr)
  398. bestMatch = object;
  399. else
  400. {
  401. if (object->pos.dist2dSQ(pos) < bestMatch->pos.dist2dSQ(pos))
  402. bestMatch = object;// closer than one we already found
  403. }
  404. }
  405. }
  406. assert(bestMatch != nullptr); // if this happens - victory conditions or map itself is very, very broken
  407. logGlobal->error("Will use %s from %s", bestMatch->getObjectName(), bestMatch->pos.toString());
  408. return bestMatch;
  409. }
  410. void CMap::checkForObjectives()
  411. {
  412. // NOTE: probably should be moved to MapFormatH3M.cpp
  413. for (TriggeredEvent & event : triggeredEvents)
  414. {
  415. auto patcher = [&](EventCondition cond) -> EventExpression::Variant
  416. {
  417. switch (cond.condition)
  418. {
  419. case EventCondition::HAVE_ARTIFACT:
  420. event.onFulfill.replaceTextID(cond.objectType.as<ArtifactID>().toEntity(VLC)->getNameTextID());
  421. break;
  422. case EventCondition::HAVE_CREATURES:
  423. event.onFulfill.replaceTextID(cond.objectType.as<CreatureID>().toEntity(VLC)->getNameSingularTextID());
  424. event.onFulfill.replaceNumber(cond.value);
  425. break;
  426. case EventCondition::HAVE_RESOURCES:
  427. event.onFulfill.replaceName(cond.objectType.as<GameResID>());
  428. event.onFulfill.replaceNumber(cond.value);
  429. break;
  430. case EventCondition::HAVE_BUILDING:
  431. if (isInTheMap(cond.position))
  432. cond.objectID = getObjectiveObjectFrom(cond.position, Obj::TOWN)->id;
  433. break;
  434. case EventCondition::CONTROL:
  435. if (isInTheMap(cond.position))
  436. cond.objectID = getObjectiveObjectFrom(cond.position, cond.objectType.as<MapObjectID>())->id;
  437. if (cond.objectID != ObjectInstanceID::NONE)
  438. {
  439. const auto * town = dynamic_cast<const CGTownInstance *>(objects[cond.objectID].get());
  440. if (town)
  441. event.onFulfill.replaceRawString(town->getNameTranslated());
  442. const auto * hero = dynamic_cast<const CGHeroInstance *>(objects[cond.objectID].get());
  443. if (hero)
  444. event.onFulfill.replaceRawString(hero->getNameTranslated());
  445. }
  446. break;
  447. case EventCondition::DESTROY:
  448. if (isInTheMap(cond.position))
  449. cond.objectID = getObjectiveObjectFrom(cond.position, cond.objectType.as<MapObjectID>())->id;
  450. if (cond.objectID != ObjectInstanceID::NONE)
  451. {
  452. const auto * hero = dynamic_cast<const CGHeroInstance *>(objects[cond.objectID].get());
  453. if (hero)
  454. event.onFulfill.replaceRawString(hero->getNameTranslated());
  455. }
  456. break;
  457. case EventCondition::TRANSPORT:
  458. cond.objectID = getObjectiveObjectFrom(cond.position, Obj::TOWN)->id;
  459. break;
  460. //break; case EventCondition::DAYS_PASSED:
  461. //break; case EventCondition::IS_HUMAN:
  462. //break; case EventCondition::DAYS_WITHOUT_TOWN:
  463. //break; case EventCondition::STANDARD_WIN:
  464. }
  465. return cond;
  466. };
  467. event.trigger = event.trigger.morph(patcher);
  468. }
  469. }
  470. void CMap::addNewArtifactInstance(CArtifactSet & artSet)
  471. {
  472. for(const auto & [slot, slotInfo] : artSet.artifactsWorn)
  473. {
  474. if(!slotInfo.locked && slotInfo.getArt())
  475. addNewArtifactInstance(slotInfo.artifact);
  476. }
  477. for(const auto & slotInfo : artSet.artifactsInBackpack)
  478. addNewArtifactInstance(slotInfo.artifact);
  479. }
  480. void CMap::addNewArtifactInstance(ConstTransitivePtr<CArtifactInstance> art)
  481. {
  482. assert(art);
  483. assert(art->getId() == -1);
  484. art->setId(static_cast<ArtifactInstanceID>(artInstances.size()));
  485. artInstances.emplace_back(art);
  486. for(const auto & partInfo : art->getPartsInfo())
  487. addNewArtifactInstance(partInfo.art);
  488. }
  489. void CMap::eraseArtifactInstance(CArtifactInstance * art)
  490. {
  491. //TODO: handle for artifacts removed in map editor
  492. assert(artInstances[art->getId().getNum()] == art);
  493. artInstances[art->getId().getNum()].dellNull();
  494. }
  495. void CMap::addNewQuestInstance(CQuest* quest)
  496. {
  497. quest->qid = static_cast<si32>(quests.size());
  498. quests.emplace_back(quest);
  499. }
  500. void CMap::removeQuestInstance(CQuest * quest)
  501. {
  502. //TODO: should be called only by map editor.
  503. //During game, completed quests or quests from removed objects stay forever
  504. //Shift indexes
  505. auto iter = std::next(quests.begin(), quest->qid);
  506. iter = quests.erase(iter);
  507. for (int i = quest->qid; iter != quests.end(); ++i, ++iter)
  508. {
  509. (*iter)->qid = i;
  510. }
  511. }
  512. void CMap::setUniqueInstanceName(CGObjectInstance * obj)
  513. {
  514. //this gives object unique name even if objects are removed later
  515. auto uid = uidCounter++;
  516. boost::format fmt("%s_%d");
  517. fmt % obj->typeName % uid;
  518. obj->instanceName = fmt.str();
  519. }
  520. void CMap::addNewObject(CGObjectInstance * obj)
  521. {
  522. if(obj->id != ObjectInstanceID(static_cast<si32>(objects.size())))
  523. throw std::runtime_error("Invalid object instance id");
  524. if(obj->instanceName.empty())
  525. throw std::runtime_error("Object instance name missing");
  526. if (vstd::contains(instanceNames, obj->instanceName))
  527. throw std::runtime_error("Object instance name duplicated: "+obj->instanceName);
  528. objects.emplace_back(obj);
  529. instanceNames[obj->instanceName] = obj;
  530. addBlockVisTiles(obj);
  531. //TODO: how about defeated heroes recruited again?
  532. obj->afterAddToMap(this);
  533. }
  534. void CMap::moveObject(CGObjectInstance * obj, const int3 & pos)
  535. {
  536. removeBlockVisTiles(obj);
  537. obj->pos = pos;
  538. addBlockVisTiles(obj);
  539. }
  540. void CMap::removeObject(CGObjectInstance * obj)
  541. {
  542. removeBlockVisTiles(obj);
  543. instanceNames.erase(obj->instanceName);
  544. //update indices
  545. auto iter = std::next(objects.begin(), obj->id.getNum());
  546. iter = objects.erase(iter);
  547. for(int i = obj->id.getNum(); iter != objects.end(); ++i, ++iter)
  548. {
  549. (*iter)->id = ObjectInstanceID(i);
  550. }
  551. obj->afterRemoveFromMap(this);
  552. //TODO: Clean artifact instances (mostly worn by hero?) and quests related to this object
  553. //This causes crash with undo/redo in editor
  554. }
  555. bool CMap::isWaterMap() const
  556. {
  557. return waterMap;
  558. }
  559. bool CMap::calculateWaterContent()
  560. {
  561. size_t totalTiles = height * width * levels();
  562. size_t waterTiles = 0;
  563. for(auto tile = terrain.origin(); tile < (terrain.origin() + terrain.num_elements()); ++tile)
  564. {
  565. if (tile->isWater())
  566. {
  567. waterTiles++;
  568. }
  569. }
  570. if (waterTiles >= totalTiles / 100) //At least 1% of area is water
  571. {
  572. waterMap = true;
  573. }
  574. else
  575. {
  576. waterMap = false;
  577. }
  578. return waterMap;
  579. }
  580. void CMap::banWaterContent()
  581. {
  582. banWaterHeroes();
  583. banWaterArtifacts();
  584. banWaterSpells();
  585. banWaterSkills();
  586. }
  587. void CMap::banWaterSpells()
  588. {
  589. vstd::erase_if(allowedSpells, [&](SpellID spell)
  590. {
  591. return spell.toSpell()->onlyOnWaterMap && !isWaterMap();
  592. });
  593. }
  594. void CMap::banWaterArtifacts()
  595. {
  596. vstd::erase_if(allowedArtifact, [&](ArtifactID artifact)
  597. {
  598. return artifact.toArtifact()->onlyOnWaterMap && !isWaterMap();
  599. });
  600. }
  601. void CMap::banWaterSkills()
  602. {
  603. vstd::erase_if(allowedAbilities, [&](SecondarySkill skill)
  604. {
  605. return skill.toSkill()->onlyOnWaterMap && !isWaterMap();
  606. });
  607. }
  608. void CMap::banWaterHeroes()
  609. {
  610. vstd::erase_if(allowedHeroes, [&](HeroTypeID hero)
  611. {
  612. return hero.toHeroType()->onlyOnWaterMap && !isWaterMap();
  613. });
  614. vstd::erase_if(allowedHeroes, [&](HeroTypeID hero)
  615. {
  616. return hero.toHeroType()->onlyOnMapWithoutWater && isWaterMap();
  617. });
  618. }
  619. void CMap::banHero(const HeroTypeID & id)
  620. {
  621. if (!vstd::contains(allowedHeroes, id))
  622. logGlobal->warn("Attempt to ban hero %s, who is already not allowed", id.encode(id));
  623. allowedHeroes.erase(id);
  624. }
  625. void CMap::unbanHero(const HeroTypeID & id)
  626. {
  627. if (vstd::contains(allowedHeroes, id))
  628. logGlobal->warn("Attempt to unban hero %s, who is already allowed", id.encode(id));
  629. allowedHeroes.insert(id);
  630. }
  631. void CMap::initTerrain()
  632. {
  633. terrain.resize(boost::extents[levels()][width][height]);
  634. guardingCreaturePositions.resize(boost::extents[levels()][width][height]);
  635. }
  636. CMapEditManager * CMap::getEditManager()
  637. {
  638. if(!editManager) editManager = std::make_unique<CMapEditManager>(this);
  639. return editManager.get();
  640. }
  641. void CMap::resetStaticData()
  642. {
  643. obeliskCount = 0;
  644. obelisksVisited.clear();
  645. townMerchantArtifacts.clear();
  646. townUniversitySkills.clear();
  647. }
  648. void CMap::resolveQuestIdentifiers()
  649. {
  650. //FIXME: move to CMapLoaderH3M
  651. for (auto & quest : quests)
  652. {
  653. if (quest && quest->killTarget != ObjectInstanceID::NONE)
  654. quest->killTarget = questIdentifierToId[quest->killTarget.getNum()];
  655. }
  656. questIdentifierToId.clear();
  657. }
  658. void CMap::reindexObjects()
  659. {
  660. // Only reindex at editor / RMG operations
  661. std::sort(objects.begin(), objects.end(), [](const CGObjectInstance * lhs, const CGObjectInstance * rhs)
  662. {
  663. // Obstacles first, then visitable, at the end - removable
  664. if (!lhs->isVisitable() && rhs->isVisitable())
  665. return true;
  666. if (lhs->isVisitable() && !rhs->isVisitable())
  667. return false;
  668. // Special case for Windomill - draw on top of other objects
  669. if (lhs->ID != Obj::WINDMILL && rhs->ID == Obj::WINDMILL)
  670. return true;
  671. if (lhs->ID == Obj::WINDMILL && rhs->ID != Obj::WINDMILL)
  672. return false;
  673. if (!lhs->isRemovable() && rhs->isRemovable())
  674. return true;
  675. if (lhs->isRemovable() && !rhs->isRemovable())
  676. return false;
  677. return lhs->pos.y < rhs->pos.y;
  678. });
  679. // instanceNames don't change
  680. for (size_t i = 0; i < objects.size(); ++i)
  681. {
  682. objects[i]->id = ObjectInstanceID(i);
  683. }
  684. }
  685. const IGameSettings & CMap::getSettings() const
  686. {
  687. return *gameSettings;
  688. }
  689. void CMap::overrideGameSetting(EGameSettings option, const JsonNode & input)
  690. {
  691. return gameSettings->addOverride(option, input);
  692. }
  693. void CMap::overrideGameSettings(const JsonNode & input)
  694. {
  695. return gameSettings->loadOverrides(input);
  696. }
  697. VCMI_LIB_NAMESPACE_END