CMap.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  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 "../CTownHandler.h"
  16. #include "../CHeroHandler.h"
  17. #include "../RiverHandler.h"
  18. #include "../RoadHandler.h"
  19. #include "../TerrainHandler.h"
  20. #include "../mapObjects/CGHeroInstance.h"
  21. #include "../mapObjects/ObjectTemplate.h"
  22. #include "../CGeneralTextHandler.h"
  23. #include "../spells/CSpellHandler.h"
  24. #include "../CSkillHandler.h"
  25. #include "CMapEditManager.h"
  26. #include "CMapOperation.h"
  27. #include "../serializer/JsonSerializeFormat.h"
  28. VCMI_LIB_NAMESPACE_BEGIN
  29. void Rumor::serializeJson(JsonSerializeFormat & handler)
  30. {
  31. handler.serializeString("name", name);
  32. handler.serializeStruct("text", text);
  33. }
  34. DisposedHero::DisposedHero() : heroId(0), portrait(255)
  35. {
  36. }
  37. CMapEvent::CMapEvent() : players(0), humanAffected(0), computerAffected(0),
  38. firstOccurence(0), nextOccurence(0)
  39. {
  40. }
  41. bool CMapEvent::earlierThan(const CMapEvent & other) const
  42. {
  43. return firstOccurence < other.firstOccurence;
  44. }
  45. bool CMapEvent::earlierThanOrEqual(const CMapEvent & other) const
  46. {
  47. return firstOccurence <= other.firstOccurence;
  48. }
  49. void CMapEvent::serializeJson(JsonSerializeFormat & handler)
  50. {
  51. handler.serializeString("name", name);
  52. handler.serializeStruct("message", message);
  53. handler.serializeInt("players", players);
  54. handler.serializeInt("humanAffected", humanAffected);
  55. handler.serializeInt("computerAffected", computerAffected);
  56. handler.serializeInt("firstOccurence", firstOccurence);
  57. handler.serializeInt("nextOccurence", nextOccurence);
  58. resources.serializeJson(handler, "resources");
  59. }
  60. void CCastleEvent::serializeJson(JsonSerializeFormat & handler)
  61. {
  62. CMapEvent::serializeJson(handler);
  63. // TODO: handler.serializeIdArray("buildings", buildings);
  64. {
  65. std::vector<BuildingID> temp(buildings.begin(), buildings.end());
  66. auto a = handler.enterArray("buildings");
  67. a.syncSize(temp);
  68. for(int i = 0; i < temp.size(); ++i)
  69. {
  70. int buildingID = temp[i].getNum();
  71. a.serializeInt(i, buildingID);
  72. buildings.insert(buildingID);
  73. }
  74. }
  75. {
  76. auto a = handler.enterArray("creatures");
  77. a.syncSize(creatures);
  78. for(int i = 0; i < creatures.size(); ++i)
  79. a.serializeInt(i, creatures[i]);
  80. }
  81. }
  82. TerrainTile::TerrainTile():
  83. terType(nullptr),
  84. terView(0),
  85. riverType(VLC->riverTypeHandler->getById(River::NO_RIVER)),
  86. riverDir(0),
  87. roadType(VLC->roadTypeHandler->getById(Road::NO_ROAD)),
  88. roadDir(0),
  89. extTileFlags(0),
  90. visitable(false),
  91. blocked(false)
  92. {
  93. }
  94. bool TerrainTile::entrableTerrain(const TerrainTile * from) const
  95. {
  96. return entrableTerrain(from ? from->terType->isLand() : true, from ? from->terType->isWater() : true);
  97. }
  98. bool TerrainTile::entrableTerrain(bool allowLand, bool allowSea) const
  99. {
  100. return terType->isPassable()
  101. && ((allowSea && terType->isWater()) || (allowLand && terType->isLand()));
  102. }
  103. bool TerrainTile::isClear(const TerrainTile * from) const
  104. {
  105. return entrableTerrain(from) && !blocked;
  106. }
  107. Obj TerrainTile::topVisitableId(bool excludeTop) const
  108. {
  109. return topVisitableObj(excludeTop) ? topVisitableObj(excludeTop)->ID : Obj(Obj::NO_OBJ);
  110. }
  111. CGObjectInstance * TerrainTile::topVisitableObj(bool excludeTop) const
  112. {
  113. if(visitableObjects.empty() || (excludeTop && visitableObjects.size() == 1))
  114. return nullptr;
  115. if(excludeTop)
  116. return visitableObjects[visitableObjects.size()-2];
  117. return visitableObjects.back();
  118. }
  119. EDiggingStatus TerrainTile::getDiggingStatus(const bool excludeTop) const
  120. {
  121. if(terType->isWater() || !terType->isPassable())
  122. return EDiggingStatus::WRONG_TERRAIN;
  123. int allowedBlocked = excludeTop ? 1 : 0;
  124. if(blockingObjects.size() > allowedBlocked || topVisitableObj(excludeTop))
  125. return EDiggingStatus::TILE_OCCUPIED;
  126. else
  127. return EDiggingStatus::CAN_DIG;
  128. }
  129. bool TerrainTile::hasFavorableWinds() const
  130. {
  131. return extTileFlags & 128;
  132. }
  133. bool TerrainTile::isWater() const
  134. {
  135. return terType->isWater();
  136. }
  137. CMap::CMap()
  138. : checksum(0)
  139. , grailPos(-1, -1, -1)
  140. , grailRadius(0)
  141. , uidCounter(0)
  142. {
  143. allHeroes.resize(VLC->heroh->objects.size());
  144. allowedAbilities = VLC->skillh->getDefaultAllowed();
  145. allowedArtifact = VLC->arth->getDefaultAllowed();
  146. allowedSpells = VLC->spellh->getDefaultAllowed();
  147. }
  148. CMap::~CMap()
  149. {
  150. getEditManager()->getUndoManager().clearAll();
  151. for(auto obj : objects)
  152. obj.dellNull();
  153. for(auto quest : quests)
  154. quest.dellNull();
  155. for(auto artInstance : artInstances)
  156. artInstance.dellNull();
  157. resetStaticData();
  158. }
  159. void CMap::removeBlockVisTiles(CGObjectInstance * obj, bool total)
  160. {
  161. const int zVal = obj->pos.z;
  162. for(int fx = 0; fx < obj->getWidth(); ++fx)
  163. {
  164. int xVal = obj->pos.x - fx;
  165. for(int fy = 0; fy < obj->getHeight(); ++fy)
  166. {
  167. int yVal = obj->pos.y - fy;
  168. if(xVal>=0 && xVal < width && yVal>=0 && yVal < height)
  169. {
  170. TerrainTile & curt = terrain[zVal][xVal][yVal];
  171. if(total || obj->visitableAt(xVal, yVal))
  172. {
  173. curt.visitableObjects -= obj;
  174. curt.visitable = curt.visitableObjects.size();
  175. }
  176. if(total || obj->blockingAt(xVal, yVal))
  177. {
  178. curt.blockingObjects -= obj;
  179. curt.blocked = curt.blockingObjects.size();
  180. }
  181. }
  182. }
  183. }
  184. }
  185. void CMap::addBlockVisTiles(CGObjectInstance * obj)
  186. {
  187. const int zVal = obj->pos.z;
  188. for(int fx = 0; fx < obj->getWidth(); ++fx)
  189. {
  190. int xVal = obj->pos.x - fx;
  191. for(int fy = 0; fy < obj->getHeight(); ++fy)
  192. {
  193. int yVal = obj->pos.y - fy;
  194. if(xVal>=0 && xVal < width && yVal >= 0 && yVal < height)
  195. {
  196. TerrainTile & curt = terrain[zVal][xVal][yVal];
  197. if(obj->visitableAt(xVal, yVal))
  198. {
  199. curt.visitableObjects.push_back(obj);
  200. curt.visitable = true;
  201. }
  202. if(obj->blockingAt(xVal, yVal))
  203. {
  204. curt.blockingObjects.push_back(obj);
  205. curt.blocked = true;
  206. }
  207. }
  208. }
  209. }
  210. }
  211. void CMap::calculateGuardingGreaturePositions()
  212. {
  213. int levels = twoLevel ? 2 : 1;
  214. for(int z = 0; z < levels; z++)
  215. {
  216. for(int x = 0; x < width; x++)
  217. {
  218. for(int y = 0; y < height; y++)
  219. {
  220. guardingCreaturePositions[z][x][y] = guardingCreaturePosition(int3(x, y, z));
  221. }
  222. }
  223. }
  224. }
  225. CGHeroInstance * CMap::getHero(HeroTypeID heroID)
  226. {
  227. for(auto & elem : heroesOnMap)
  228. if(elem->getHeroType() == heroID)
  229. return elem;
  230. return nullptr;
  231. }
  232. bool CMap::isCoastalTile(const int3 & pos) const
  233. {
  234. //todo: refactoring: extract neighbor tile iterator and use it in GameState
  235. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  236. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  237. if(!isInTheMap(pos))
  238. {
  239. logGlobal->error("Coastal check outside of map: %s", pos.toString());
  240. return false;
  241. }
  242. if(isWaterTile(pos))
  243. return false;
  244. for(const auto & dir : dirs)
  245. {
  246. const int3 hlp = pos + dir;
  247. if(!isInTheMap(hlp))
  248. continue;
  249. const TerrainTile &hlpt = getTile(hlp);
  250. if(hlpt.isWater())
  251. return true;
  252. }
  253. return false;
  254. }
  255. bool CMap::isInTheMap(const int3 & pos) const
  256. {
  257. return pos.x >= 0 && pos.y >= 0 && pos.z >= 0 && pos.x < width && pos.y < height && pos.z <= (twoLevel ? 1 : 0);
  258. }
  259. TerrainTile & CMap::getTile(const int3 & tile)
  260. {
  261. assert(isInTheMap(tile));
  262. return terrain[tile.z][tile.x][tile.y];
  263. }
  264. const TerrainTile & CMap::getTile(const int3 & tile) const
  265. {
  266. assert(isInTheMap(tile));
  267. return terrain[tile.z][tile.x][tile.y];
  268. }
  269. bool CMap::isWaterTile(const int3 &pos) const
  270. {
  271. return isInTheMap(pos) && getTile(pos).isWater();
  272. }
  273. bool CMap::canMoveBetween(const int3 &src, const int3 &dst) const
  274. {
  275. const TerrainTile * dstTile = &getTile(dst);
  276. const TerrainTile * srcTile = &getTile(src);
  277. return checkForVisitableDir(src, dstTile, dst) && checkForVisitableDir(dst, srcTile, src);
  278. }
  279. bool CMap::checkForVisitableDir(const int3 & src, const TerrainTile * pom, const int3 & dst) const
  280. {
  281. if (!pom->entrableTerrain()) //rock is never accessible
  282. return false;
  283. for(auto * obj : pom->visitableObjects) //checking destination tile
  284. {
  285. if(!vstd::contains(pom->blockingObjects, obj)) //this visitable object is not blocking, ignore
  286. continue;
  287. if (!obj->appearance->isVisitableFrom(src.x - dst.x, src.y - dst.y))
  288. return false;
  289. }
  290. return true;
  291. }
  292. int3 CMap::guardingCreaturePosition (int3 pos) const
  293. {
  294. const int3 originalPos = pos;
  295. // Give monster at position priority.
  296. if (!isInTheMap(pos))
  297. return int3(-1, -1, -1);
  298. const TerrainTile &posTile = getTile(pos);
  299. if (posTile.visitable)
  300. {
  301. for (CGObjectInstance* obj : posTile.visitableObjects)
  302. {
  303. if (obj->ID == Obj::MONSTER)
  304. return pos;
  305. }
  306. }
  307. // See if there are any monsters adjacent.
  308. bool water = posTile.isWater();
  309. pos -= int3(1, 1, 0); // Start with top left.
  310. for (int dx = 0; dx < 3; dx++)
  311. {
  312. for (int dy = 0; dy < 3; dy++)
  313. {
  314. if (isInTheMap(pos))
  315. {
  316. const auto & tile = getTile(pos);
  317. if (tile.visitable && (tile.isWater() == water))
  318. {
  319. for (CGObjectInstance* obj : tile.visitableObjects)
  320. {
  321. if (obj->ID == Obj::MONSTER && checkForVisitableDir(pos, &posTile, originalPos)) // Monster being able to attack investigated tile
  322. {
  323. return pos;
  324. }
  325. }
  326. }
  327. }
  328. pos.y++;
  329. }
  330. pos.y -= 3;
  331. pos.x++;
  332. }
  333. return int3(-1, -1, -1);
  334. }
  335. const CGObjectInstance * CMap::getObjectiveObjectFrom(const int3 & pos, Obj type)
  336. {
  337. for (CGObjectInstance * object : getTile(pos).visitableObjects)
  338. {
  339. if (object->ID == type)
  340. return object;
  341. }
  342. // There is weird bug because of which sometimes heroes will not be found properly despite having correct position
  343. // Try to workaround that and find closest object that we can use
  344. logGlobal->error("Failed to find object of type %d at %s", type.getNum(), pos.toString());
  345. logGlobal->error("Will try to find closest matching object");
  346. CGObjectInstance * bestMatch = nullptr;
  347. for (CGObjectInstance * object : objects)
  348. {
  349. if (object && object->ID == type)
  350. {
  351. if (bestMatch == nullptr)
  352. bestMatch = object;
  353. else
  354. {
  355. if (object->pos.dist2dSQ(pos) < bestMatch->pos.dist2dSQ(pos))
  356. bestMatch = object;// closer than one we already found
  357. }
  358. }
  359. }
  360. assert(bestMatch != nullptr); // if this happens - victory conditions or map itself is very, very broken
  361. logGlobal->error("Will use %s from %s", bestMatch->getObjectName(), bestMatch->pos.toString());
  362. return bestMatch;
  363. }
  364. void CMap::checkForObjectives()
  365. {
  366. // NOTE: probably should be moved to MapFormatH3M.cpp
  367. for (TriggeredEvent & event : triggeredEvents)
  368. {
  369. auto patcher = [&](EventCondition cond) -> EventExpression::Variant
  370. {
  371. switch (cond.condition)
  372. {
  373. case EventCondition::HAVE_ARTIFACT:
  374. event.onFulfill.replaceTextID(cond.objectType.as<ArtifactID>().toEntity(VLC)->getNameTextID());
  375. break;
  376. case EventCondition::HAVE_CREATURES:
  377. event.onFulfill.replaceTextID(cond.objectType.as<CreatureID>().toEntity(VLC)->getNameSingularTextID());
  378. event.onFulfill.replaceNumber(cond.value);
  379. break;
  380. case EventCondition::HAVE_RESOURCES:
  381. event.onFulfill.replaceName(cond.objectType.as<GameResID>());
  382. event.onFulfill.replaceNumber(cond.value);
  383. break;
  384. case EventCondition::HAVE_BUILDING:
  385. if (isInTheMap(cond.position))
  386. cond.objectID = getObjectiveObjectFrom(cond.position, Obj::TOWN)->id;
  387. break;
  388. case EventCondition::CONTROL:
  389. if (isInTheMap(cond.position))
  390. cond.objectID = getObjectiveObjectFrom(cond.position, cond.objectType.as<MapObjectID>())->id;
  391. if (cond.objectID != ObjectInstanceID::NONE)
  392. {
  393. const auto * town = dynamic_cast<const CGTownInstance *>(objects[cond.objectID].get());
  394. if (town)
  395. event.onFulfill.replaceRawString(town->getNameTranslated());
  396. const auto * hero = dynamic_cast<const CGHeroInstance *>(objects[cond.objectID].get());
  397. if (hero)
  398. event.onFulfill.replaceRawString(hero->getNameTranslated());
  399. }
  400. break;
  401. case EventCondition::DESTROY:
  402. if (isInTheMap(cond.position))
  403. cond.objectID = getObjectiveObjectFrom(cond.position, cond.objectType.as<MapObjectID>())->id;
  404. if (cond.objectID != ObjectInstanceID::NONE)
  405. {
  406. const auto * hero = dynamic_cast<const CGHeroInstance *>(objects[cond.objectID].get());
  407. if (hero)
  408. event.onFulfill.replaceRawString(hero->getNameTranslated());
  409. }
  410. break;
  411. case EventCondition::TRANSPORT:
  412. cond.objectID = getObjectiveObjectFrom(cond.position, Obj::TOWN)->id;
  413. break;
  414. //break; case EventCondition::DAYS_PASSED:
  415. //break; case EventCondition::IS_HUMAN:
  416. //break; case EventCondition::DAYS_WITHOUT_TOWN:
  417. //break; case EventCondition::STANDARD_WIN:
  418. }
  419. return cond;
  420. };
  421. event.trigger = event.trigger.morph(patcher);
  422. }
  423. }
  424. void CMap::addNewArtifactInstance(ConstTransitivePtr<CArtifactInstance> art)
  425. {
  426. art->setId(static_cast<ArtifactInstanceID>(artInstances.size()));
  427. artInstances.emplace_back(art);
  428. }
  429. void CMap::eraseArtifactInstance(CArtifactInstance * art)
  430. {
  431. //TODO: handle for artifacts removed in map editor
  432. assert(artInstances[art->getId().getNum()] == art);
  433. artInstances[art->getId().getNum()].dellNull();
  434. }
  435. void CMap::addNewQuestInstance(CQuest* quest)
  436. {
  437. quest->qid = static_cast<si32>(quests.size());
  438. quests.emplace_back(quest);
  439. }
  440. void CMap::removeQuestInstance(CQuest * quest)
  441. {
  442. //TODO: should be called only by map editor.
  443. //During game, completed quests or quests from removed objects stay forever
  444. //Shift indexes
  445. auto iter = std::next(quests.begin(), quest->qid);
  446. iter = quests.erase(iter);
  447. for (int i = quest->qid; iter != quests.end(); ++i, ++iter)
  448. {
  449. (*iter)->qid = i;
  450. }
  451. }
  452. void CMap::setUniqueInstanceName(CGObjectInstance * obj)
  453. {
  454. //this gives object unique name even if objects are removed later
  455. auto uid = uidCounter++;
  456. boost::format fmt("%s_%d");
  457. fmt % obj->typeName % uid;
  458. obj->instanceName = fmt.str();
  459. }
  460. void CMap::addNewObject(CGObjectInstance * obj)
  461. {
  462. if(obj->id != ObjectInstanceID(static_cast<si32>(objects.size())))
  463. throw std::runtime_error("Invalid object instance id");
  464. if(obj->instanceName.empty())
  465. throw std::runtime_error("Object instance name missing");
  466. if (vstd::contains(instanceNames, obj->instanceName))
  467. throw std::runtime_error("Object instance name duplicated: "+obj->instanceName);
  468. objects.emplace_back(obj);
  469. instanceNames[obj->instanceName] = obj;
  470. addBlockVisTiles(obj);
  471. //TODO: how about defeated heroes recruited again?
  472. obj->afterAddToMap(this);
  473. }
  474. void CMap::moveObject(CGObjectInstance * obj, const int3 & pos)
  475. {
  476. removeBlockVisTiles(obj);
  477. obj->pos = pos;
  478. addBlockVisTiles(obj);
  479. }
  480. void CMap::removeObject(CGObjectInstance * obj)
  481. {
  482. removeBlockVisTiles(obj);
  483. instanceNames.erase(obj->instanceName);
  484. //update indeces
  485. auto iter = std::next(objects.begin(), obj->id.getNum());
  486. iter = objects.erase(iter);
  487. for(int i = obj->id.getNum(); iter != objects.end(); ++i, ++iter)
  488. {
  489. (*iter)->id = ObjectInstanceID(i);
  490. }
  491. obj->afterRemoveFromMap(this);
  492. //TOOD: Clean artifact instances (mostly worn by hero?) and quests related to this object
  493. }
  494. bool CMap::isWaterMap() const
  495. {
  496. return waterMap;
  497. }
  498. bool CMap::calculateWaterContent()
  499. {
  500. size_t totalTiles = height * width * levels();
  501. size_t waterTiles = 0;
  502. for(auto tile = terrain.origin(); tile < (terrain.origin() + terrain.num_elements()); ++tile)
  503. {
  504. if (tile->isWater())
  505. {
  506. waterTiles++;
  507. }
  508. }
  509. if (waterTiles >= totalTiles / 100) //At least 1% of area is water
  510. {
  511. waterMap = true;
  512. }
  513. return waterMap;
  514. }
  515. void CMap::banWaterContent()
  516. {
  517. banWaterHeroes();
  518. banWaterArtifacts();
  519. banWaterSpells();
  520. banWaterSkills();
  521. }
  522. void CMap::banWaterSpells()
  523. {
  524. vstd::erase_if(allowedSpells, [&](SpellID spell)
  525. {
  526. return spell.toSpell()->onlyOnWaterMap && !isWaterMap();
  527. });
  528. }
  529. void CMap::banWaterArtifacts()
  530. {
  531. vstd::erase_if(allowedArtifact, [&](ArtifactID artifact)
  532. {
  533. return artifact.toArtifact()->onlyOnWaterMap && !isWaterMap();
  534. });
  535. }
  536. void CMap::banWaterSkills()
  537. {
  538. vstd::erase_if(allowedAbilities, [&](SecondarySkill skill)
  539. {
  540. return skill.toSkill()->onlyOnWaterMap && !isWaterMap();
  541. });
  542. }
  543. void CMap::banWaterHeroes()
  544. {
  545. vstd::erase_if(allowedHeroes, [&](HeroTypeID hero)
  546. {
  547. return hero.toHeroType()->onlyOnWaterMap && !isWaterMap();
  548. });
  549. vstd::erase_if(allowedHeroes, [&](HeroTypeID hero)
  550. {
  551. return hero.toHeroType()->onlyOnMapWithoutWater && isWaterMap();
  552. });
  553. }
  554. void CMap::banHero(const HeroTypeID & id)
  555. {
  556. allowedHeroes.erase(id);
  557. }
  558. void CMap::initTerrain()
  559. {
  560. terrain.resize(boost::extents[levels()][width][height]);
  561. guardingCreaturePositions.resize(boost::extents[levels()][width][height]);
  562. }
  563. CMapEditManager * CMap::getEditManager()
  564. {
  565. if(!editManager) editManager = std::make_unique<CMapEditManager>(this);
  566. return editManager.get();
  567. }
  568. void CMap::resetStaticData()
  569. {
  570. CGObelisk::reset();
  571. CGTownInstance::reset();
  572. }
  573. VCMI_LIB_NAMESPACE_END