CMap.cpp 23 KB

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