CMap.cpp 16 KB

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