CMap.cpp 15 KB

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