CMap.cpp 16 KB

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