CMap.cpp 22 KB

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