CMap.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  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.getArtifact(), 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.hasValue())
  439. obj->id = ObjectInstanceID(objects.size());
  440. if(obj->id != ObjectInstanceID(objects.size()) && objects.at(obj->id.getNum()) != nullptr)
  441. throw std::runtime_error("Invalid object instance id");
  442. if(obj->instanceName.empty())
  443. throw std::runtime_error("Object instance name missing");
  444. if (vstd::contains(instanceNames, obj->instanceName))
  445. throw std::runtime_error("Object instance name duplicated: "+obj->instanceName);
  446. objects.emplace_back(obj);
  447. instanceNames[obj->instanceName] = obj;
  448. addBlockVisTiles(obj.get());
  449. //TODO: how about defeated heroes recruited again?
  450. obj->afterAddToMap(this);
  451. }
  452. void CMap::moveObject(ObjectInstanceID target, const int3 & dst)
  453. {
  454. auto obj = objects.at(target).get();
  455. removeBlockVisTiles(obj);
  456. obj->setAnchorPos(dst);
  457. addBlockVisTiles(obj);
  458. }
  459. std::shared_ptr<CGObjectInstance> CMap::removeObject(ObjectInstanceID oldObject)
  460. {
  461. auto obj = objects.at(oldObject);
  462. removeBlockVisTiles(obj.get());
  463. instanceNames.erase(obj->instanceName);
  464. //update indices
  465. auto iter = std::next(objects.begin(), obj->id.getNum());
  466. iter = objects.erase(iter);
  467. for(int i = obj->id.getNum(); iter != objects.end(); ++i, ++iter)
  468. {
  469. (*iter)->id = ObjectInstanceID(i);
  470. }
  471. obj->afterRemoveFromMap(this);
  472. //TODO: Clean artifact instances (mostly worn by hero?) and quests related to this object
  473. //This causes crash with undo/redo in editor
  474. return obj;
  475. }
  476. std::shared_ptr<CGObjectInstance> CMap::replaceObject(ObjectInstanceID oldObjectID, const std::shared_ptr<CGObjectInstance> & newObject)
  477. {
  478. auto oldObject = objects.at(oldObjectID.getNum());
  479. newObject->id = oldObjectID;
  480. removeBlockVisTiles(oldObject.get(), true);
  481. instanceNames.erase(oldObject->instanceName);
  482. objects.at(oldObjectID.getNum()) = newObject;
  483. addBlockVisTiles(newObject.get());
  484. instanceNames[newObject->instanceName] = newObject;
  485. oldObject->afterRemoveFromMap(this);
  486. newObject->afterAddToMap(this);
  487. return oldObject;
  488. }
  489. std::shared_ptr<CGObjectInstance> CMap::eraseObject(ObjectInstanceID oldObjectID)
  490. {
  491. auto oldObject = objects.at(oldObjectID.getNum());
  492. instanceNames.erase(oldObject->instanceName);
  493. objects.at(oldObjectID) = nullptr;
  494. removeBlockVisTiles(oldObject.get(), true);
  495. oldObject->afterRemoveFromMap(this);
  496. return oldObject;
  497. }
  498. void CMap::heroAddedToMap(const CGHeroInstance * hero)
  499. {
  500. assert(!vstd::contains(heroesOnMap, hero->id));
  501. heroesOnMap.push_back(hero->id);
  502. }
  503. void CMap::heroRemovedFromMap(const CGHeroInstance * hero)
  504. {
  505. assert(vstd::contains(heroesOnMap, hero->id));
  506. vstd::erase(heroesOnMap, hero->id);
  507. }
  508. void CMap::townAddedToMap(const CGTownInstance * town)
  509. {
  510. assert(!vstd::contains(towns, town->id));
  511. towns.push_back(town->id);
  512. }
  513. void CMap::townRemovedFromMap(const CGTownInstance * town)
  514. {
  515. assert(vstd::contains(towns, town->id));
  516. vstd::erase(towns, town->id);
  517. }
  518. bool CMap::isWaterMap() const
  519. {
  520. return waterMap;
  521. }
  522. bool CMap::calculateWaterContent()
  523. {
  524. size_t totalTiles = height * width * levels();
  525. size_t waterTiles = 0;
  526. for(auto tile = terrain.origin(); tile < (terrain.origin() + terrain.num_elements()); ++tile)
  527. {
  528. if (tile->isWater())
  529. {
  530. waterTiles++;
  531. }
  532. }
  533. if (waterTiles >= totalTiles / 100) //At least 1% of area is water
  534. {
  535. waterMap = true;
  536. }
  537. else
  538. {
  539. waterMap = false;
  540. }
  541. return waterMap;
  542. }
  543. void CMap::banWaterContent()
  544. {
  545. banWaterHeroes();
  546. banWaterArtifacts();
  547. banWaterSpells();
  548. banWaterSkills();
  549. }
  550. void CMap::banWaterSpells()
  551. {
  552. vstd::erase_if(allowedSpells, [&](SpellID spell)
  553. {
  554. return spell.toSpell()->onlyOnWaterMap && !isWaterMap();
  555. });
  556. }
  557. void CMap::banWaterArtifacts()
  558. {
  559. vstd::erase_if(allowedArtifact, [&](ArtifactID artifact)
  560. {
  561. return artifact.toArtifact()->onlyOnWaterMap && !isWaterMap();
  562. });
  563. }
  564. void CMap::banWaterSkills()
  565. {
  566. vstd::erase_if(allowedAbilities, [&](SecondarySkill skill)
  567. {
  568. return skill.toSkill()->onlyOnWaterMap && !isWaterMap();
  569. });
  570. }
  571. void CMap::banWaterHeroes()
  572. {
  573. vstd::erase_if(allowedHeroes, [&](HeroTypeID hero)
  574. {
  575. return hero.toHeroType()->onlyOnWaterMap && !isWaterMap();
  576. });
  577. vstd::erase_if(allowedHeroes, [&](HeroTypeID hero)
  578. {
  579. return hero.toHeroType()->onlyOnMapWithoutWater && isWaterMap();
  580. });
  581. }
  582. void CMap::banHero(const HeroTypeID & id)
  583. {
  584. if (!vstd::contains(allowedHeroes, id))
  585. logGlobal->warn("Attempt to ban hero %s, who is already not allowed", id.encode(id));
  586. allowedHeroes.erase(id);
  587. }
  588. void CMap::unbanHero(const HeroTypeID & id)
  589. {
  590. if (vstd::contains(allowedHeroes, id))
  591. logGlobal->warn("Attempt to unban hero %s, who is already allowed", id.encode(id));
  592. allowedHeroes.insert(id);
  593. }
  594. void CMap::initTerrain()
  595. {
  596. terrain.resize(boost::extents[levels()][width][height]);
  597. guardingCreaturePositions.resize(boost::extents[levels()][width][height]);
  598. }
  599. CMapEditManager * CMap::getEditManager()
  600. {
  601. if(!editManager) editManager = std::make_unique<CMapEditManager>(this);
  602. return editManager.get();
  603. }
  604. void CMap::reindexObjects()
  605. {
  606. // Only reindex at editor / RMG operations
  607. std::sort(objects.begin(), objects.end(), [](const auto & lhs, const auto & rhs)
  608. {
  609. // Obstacles first, then visitable, at the end - removable
  610. if (!lhs->isVisitable() && rhs->isVisitable())
  611. return true;
  612. if (lhs->isVisitable() && !rhs->isVisitable())
  613. return false;
  614. // Special case for Windomill - draw on top of other objects
  615. if (lhs->ID != Obj::WINDMILL && rhs->ID == Obj::WINDMILL)
  616. return true;
  617. if (lhs->ID == Obj::WINDMILL && rhs->ID != Obj::WINDMILL)
  618. return false;
  619. if (!lhs->isRemovable() && rhs->isRemovable())
  620. return true;
  621. if (lhs->isRemovable() && !rhs->isRemovable())
  622. return false;
  623. return lhs->anchorPos().y < rhs->anchorPos().y;
  624. });
  625. // instanceNames don't change
  626. for (size_t i = 0; i < objects.size(); ++i)
  627. {
  628. objects[i]->id = ObjectInstanceID(i);
  629. }
  630. }
  631. const IGameSettings & CMap::getSettings() const
  632. {
  633. return *gameSettings;
  634. }
  635. void CMap::overrideGameSetting(EGameSettings option, const JsonNode & input)
  636. {
  637. return gameSettings->addOverride(option, input);
  638. }
  639. void CMap::overrideGameSettings(const JsonNode & input)
  640. {
  641. return gameSettings->loadOverrides(input);
  642. }
  643. CArtifactInstance * CMap::createScroll(const SpellID & spellId)
  644. {
  645. return createArtifact(ArtifactID::SPELL_SCROLL, spellId);
  646. }
  647. CArtifactInstance * CMap::createSingleArtifact(const ArtifactID & artId, const SpellID & spellId)
  648. {
  649. auto newArtifact = artId.hasValue() ?
  650. std::make_shared<CArtifactInstance>(cb, artId.toArtifact()):
  651. std::make_shared<CArtifactInstance>(cb);
  652. newArtifact->setId(ArtifactInstanceID(artInstances.size()));
  653. artInstances.push_back(newArtifact);
  654. return newArtifact.get();
  655. }
  656. CArtifactInstance * CMap::createArtifact(const ArtifactID & artID, const SpellID & spellId)
  657. {
  658. if(!artID.hasValue())
  659. {
  660. // random, empty
  661. // TODO: make this illegal & remove? Such artifact can't be randomized as combined artifact later
  662. return createSingleArtifact(artID, spellId);
  663. }
  664. auto art = artID.toArtifact();
  665. auto artInst = createSingleArtifact(artID, spellId);
  666. if(art->isCombined() && !art->isFused())
  667. {
  668. for(const auto & part : art->getConstituents())
  669. artInst->addPart(createArtifact(part->getId(), spellId), ArtifactPosition::PRE_FIRST);
  670. }
  671. if(art->isGrowing())
  672. {
  673. auto bonus = std::make_shared<Bonus>();
  674. bonus->type = BonusType::LEVEL_COUNTER;
  675. bonus->val = 0;
  676. artInst->addNewBonus(bonus);
  677. }
  678. if(art->isScroll())
  679. {
  680. artInst->addNewBonus(std::make_shared<Bonus>(BonusDuration::PERMANENT, BonusType::SPELL,
  681. BonusSource::ARTIFACT_INSTANCE, -1, BonusSourceID(ArtifactID(ArtifactID::SPELL_SCROLL)), BonusSubtypeID(spellId)));
  682. }
  683. return artInst;
  684. }
  685. CArtifactInstance * CMap::getArtifactInstance(const ArtifactInstanceID & artifactID)
  686. {
  687. return artInstances.at(artifactID.getNum()).get();
  688. }
  689. const CArtifactInstance * CMap::getArtifactInstance(const ArtifactInstanceID & artifactID) const
  690. {
  691. return artInstances.at(artifactID.getNum()).get();
  692. }
  693. const std::vector<ObjectInstanceID> & CMap::getAllTowns()
  694. {
  695. return towns;
  696. }
  697. const std::vector<ObjectInstanceID> & CMap::getHeroesOnMap()
  698. {
  699. return heroesOnMap;
  700. }
  701. void CMap::postInitialize()
  702. {
  703. //TODO: check whether this is actually needed
  704. boost::range::sort(heroesOnMap, [this](const ObjectInstanceID & a, const ObjectInstanceID & b)
  705. {
  706. const auto aHero = std::dynamic_pointer_cast<const CGHeroInstance>(objects.at(a.getNum()));
  707. const auto bHero = std::dynamic_pointer_cast<const CGHeroInstance>(objects.at(b.getNum()));
  708. return aHero->getHeroTypeID() < bHero->getHeroTypeID();
  709. });
  710. }
  711. void CMap::addToHeroPool(std::shared_ptr<CGHeroInstance> hero)
  712. {
  713. assert(hero->getHeroTypeID().isValid());
  714. assert(!vstd::contains(heroesOnMap, hero->getHeroTypeID()));
  715. assert(heroesPool.at(hero->getHeroTypeID().getNum()) == nullptr);
  716. heroesPool.at(hero->getHeroTypeID().getNum()) = hero;
  717. if (!hero->id.hasValue())
  718. {
  719. // reserve ID for this new hero, if needed (but don't actually add it since hero is not present on map)
  720. hero->id = ObjectInstanceID(objects.size());
  721. objects.push_back(nullptr);
  722. }
  723. }
  724. CGHeroInstance * CMap::tryGetFromHeroPool(HeroTypeID hero)
  725. {
  726. return heroesPool.at(hero.getNum()).get();
  727. }
  728. std::shared_ptr<CGHeroInstance> CMap::tryTakeFromHeroPool(HeroTypeID hero)
  729. {
  730. auto result = heroesPool.at(hero.getNum());
  731. heroesPool.at(hero.getNum()) = nullptr;
  732. return result;
  733. }
  734. std::vector<HeroTypeID> CMap::getHeroesInPool() const
  735. {
  736. std::vector<HeroTypeID> result;
  737. for (const auto & hero : heroesPool)
  738. if (hero)
  739. result.push_back(hero->getHeroTypeID());
  740. return result;
  741. }
  742. CGObjectInstance * CMap::getObject(ObjectInstanceID obj)
  743. {
  744. return objects.at(obj).get();
  745. }
  746. const CGObjectInstance * CMap::getObject(ObjectInstanceID obj) const
  747. {
  748. return objects.at(obj).get();
  749. }
  750. VCMI_LIB_NAMESPACE_END