2
0

CMap.cpp 21 KB

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