CMap.cpp 21 KB

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