CMap.cpp 20 KB

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