CMap.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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 "../mapObjects/CObjectClassesHandler.h"
  18. #include "../mapObjects/CGHeroInstance.h"
  19. #include "../CGeneralTextHandler.h"
  20. #include "../spells/CSpellHandler.h"
  21. #include "CMapEditManager.h"
  22. #include "../serializer/JsonSerializeFormat.h"
  23. SHeroName::SHeroName() : heroId(-1)
  24. {
  25. }
  26. PlayerInfo::PlayerInfo(): canHumanPlay(false), canComputerPlay(false),
  27. aiTactic(EAiTactic::RANDOM), isFactionRandom(false), hasRandomHero(false), mainCustomHeroPortrait(-1), mainCustomHeroId(-1), hasMainTown(false),
  28. generateHeroAtMainTown(false), team(TeamID::NO_TEAM), /* following are unused */ generateHero(false), p7(0), powerPlaceholders(-1)
  29. {
  30. allowedFactions = VLC->townh->getAllowedFactions();
  31. }
  32. si8 PlayerInfo::defaultCastle() const
  33. {
  34. if(allowedFactions.size() == 1 || !isFactionRandom)
  35. {
  36. // faction can't be chosen - set to first that is marked as allowed
  37. assert(!allowedFactions.empty());
  38. return *allowedFactions.begin();
  39. }
  40. // set to random
  41. return -1;
  42. }
  43. si8 PlayerInfo::defaultHero() const
  44. {
  45. // we will generate hero in front of main town
  46. if((generateHeroAtMainTown && hasMainTown) || hasRandomHero)
  47. {
  48. //random hero
  49. return -1;
  50. }
  51. return -2;
  52. }
  53. bool PlayerInfo::canAnyonePlay() const
  54. {
  55. return canHumanPlay || canComputerPlay;
  56. }
  57. bool PlayerInfo::hasCustomMainHero() const
  58. {
  59. return !mainCustomHeroName.empty() && mainCustomHeroPortrait != -1;
  60. }
  61. EventCondition::EventCondition(EWinLoseType condition):
  62. object(nullptr),
  63. metaType(EMetaclass::INVALID),
  64. value(-1),
  65. objectType(-1),
  66. objectSubtype(-1),
  67. position(-1, -1, -1),
  68. condition(condition)
  69. {
  70. }
  71. EventCondition::EventCondition(EWinLoseType condition, si32 value, si32 objectType, int3 position):
  72. object(nullptr),
  73. metaType(EMetaclass::INVALID),
  74. value(value),
  75. objectType(objectType),
  76. objectSubtype(-1),
  77. position(position),
  78. condition(condition)
  79. {}
  80. void Rumor::serializeJson(JsonSerializeFormat & handler)
  81. {
  82. handler.serializeString("name", name);
  83. handler.serializeString("text", text);
  84. }
  85. DisposedHero::DisposedHero() : heroId(0), portrait(255), players(0)
  86. {
  87. }
  88. CMapEvent::CMapEvent() : players(0), humanAffected(0), computerAffected(0),
  89. firstOccurence(0), nextOccurence(0)
  90. {
  91. }
  92. bool CMapEvent::earlierThan(const CMapEvent & other) const
  93. {
  94. return firstOccurence < other.firstOccurence;
  95. }
  96. bool CMapEvent::earlierThanOrEqual(const CMapEvent & other) const
  97. {
  98. return firstOccurence <= other.firstOccurence;
  99. }
  100. CCastleEvent::CCastleEvent() : town(nullptr)
  101. {
  102. }
  103. TerrainTile::TerrainTile() : terType(ETerrainType::BORDER), terView(0), riverType(ERiverType::NO_RIVER),
  104. riverDir(0), roadType(ERoadType::NO_ROAD), roadDir(0), extTileFlags(0), visitable(false),
  105. blocked(false)
  106. {
  107. }
  108. bool TerrainTile::entrableTerrain(const TerrainTile * from) const
  109. {
  110. return entrableTerrain(from ? from->terType != ETerrainType::WATER : true, from ? from->terType == ETerrainType::WATER : true);
  111. }
  112. bool TerrainTile::entrableTerrain(bool allowLand, bool allowSea) const
  113. {
  114. return terType != ETerrainType::ROCK
  115. && ((allowSea && terType == ETerrainType::WATER) || (allowLand && terType != ETerrainType::WATER));
  116. }
  117. bool TerrainTile::isClear(const TerrainTile * from) const
  118. {
  119. return entrableTerrain(from) && !blocked;
  120. }
  121. Obj TerrainTile::topVisitableId(bool excludeTop) const
  122. {
  123. return topVisitableObj(excludeTop) ? topVisitableObj(excludeTop)->ID : Obj(Obj::NO_OBJ);
  124. }
  125. CGObjectInstance * TerrainTile::topVisitableObj(bool excludeTop) const
  126. {
  127. if(visitableObjects.empty() || (excludeTop && visitableObjects.size() == 1))
  128. return nullptr;
  129. if(excludeTop)
  130. return visitableObjects[visitableObjects.size()-2];
  131. return visitableObjects.back();
  132. }
  133. EDiggingStatus TerrainTile::getDiggingStatus(const bool excludeTop) const
  134. {
  135. if(terType == ETerrainType::WATER || terType == ETerrainType::ROCK)
  136. return EDiggingStatus::WRONG_TERRAIN;
  137. int allowedBlocked = excludeTop ? 1 : 0;
  138. if(blockingObjects.size() > allowedBlocked || topVisitableObj(excludeTop))
  139. return EDiggingStatus::TILE_OCCUPIED;
  140. else
  141. return EDiggingStatus::CAN_DIG;
  142. }
  143. bool TerrainTile::hasFavorableWinds() const
  144. {
  145. return extTileFlags & 128;
  146. }
  147. bool TerrainTile::isWater() const
  148. {
  149. return terType == ETerrainType::WATER;
  150. }
  151. const int CMapHeader::MAP_SIZE_SMALL = 36;
  152. const int CMapHeader::MAP_SIZE_MIDDLE = 72;
  153. const int CMapHeader::MAP_SIZE_LARGE = 108;
  154. const int CMapHeader::MAP_SIZE_XLARGE = 144;
  155. void CMapHeader::setupEvents()
  156. {
  157. EventCondition victoryCondition(EventCondition::STANDARD_WIN);
  158. EventCondition defeatCondition(EventCondition::DAYS_WITHOUT_TOWN);
  159. defeatCondition.value = 7;
  160. //Victory condition - defeat all
  161. TriggeredEvent standardVictory;
  162. standardVictory.effect.type = EventEffect::VICTORY;
  163. standardVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[5];
  164. standardVictory.identifier = "standardVictory";
  165. standardVictory.description = ""; // TODO: display in quest window
  166. standardVictory.onFulfill = VLC->generaltexth->allTexts[659];
  167. standardVictory.trigger = EventExpression(victoryCondition);
  168. //Loss condition - 7 days without town
  169. TriggeredEvent standardDefeat;
  170. standardDefeat.effect.type = EventEffect::DEFEAT;
  171. standardDefeat.effect.toOtherMessage = VLC->generaltexth->allTexts[8];
  172. standardDefeat.identifier = "standardDefeat";
  173. standardDefeat.description = ""; // TODO: display in quest window
  174. standardDefeat.onFulfill = VLC->generaltexth->allTexts[7];
  175. standardDefeat.trigger = EventExpression(defeatCondition);
  176. triggeredEvents.push_back(standardVictory);
  177. triggeredEvents.push_back(standardDefeat);
  178. victoryIconIndex = 11;
  179. victoryMessage = VLC->generaltexth->victoryConditions[0];
  180. defeatIconIndex = 3;
  181. defeatMessage = VLC->generaltexth->lossCondtions[0];
  182. }
  183. CMapHeader::CMapHeader() : version(EMapFormat::SOD), height(72), width(72),
  184. twoLevel(true), difficulty(1), levelLimit(0), howManyTeams(0), areAnyPlayers(false)
  185. {
  186. setupEvents();
  187. allowedHeroes = VLC->heroh->getDefaultAllowed();
  188. players.resize(PlayerColor::PLAYER_LIMIT_I);
  189. }
  190. CMapHeader::~CMapHeader()
  191. {
  192. }
  193. CMap::CMap()
  194. : checksum(0), grailPos(-1, -1, -1), grailRadius(0), terrain(nullptr),
  195. guardingCreaturePositions(nullptr)
  196. {
  197. allHeroes.resize(allowedHeroes.size());
  198. allowedAbilities = VLC->heroh->getDefaultAllowedAbilities();
  199. allowedArtifact = VLC->arth->getDefaultAllowed();
  200. allowedSpell = VLC->spellh->getDefaultAllowed();
  201. }
  202. CMap::~CMap()
  203. {
  204. if(terrain)
  205. {
  206. for (int i=0; i<width; i++)
  207. {
  208. for(int j=0; j<height; j++)
  209. {
  210. delete [] terrain[i][j];
  211. delete [] guardingCreaturePositions[i][j];
  212. }
  213. delete [] terrain[i];
  214. delete [] guardingCreaturePositions[i];
  215. }
  216. delete [] terrain;
  217. delete [] guardingCreaturePositions;
  218. }
  219. for(auto obj : objects)
  220. obj.dellNull();
  221. for(auto quest : quests)
  222. quest.dellNull();
  223. }
  224. void CMap::removeBlockVisTiles(CGObjectInstance * obj, bool total)
  225. {
  226. for(int fx=0; fx<obj->getWidth(); ++fx)
  227. {
  228. for(int fy=0; fy<obj->getHeight(); ++fy)
  229. {
  230. int xVal = obj->pos.x - fx;
  231. int yVal = obj->pos.y - fy;
  232. int zVal = obj->pos.z;
  233. if(xVal>=0 && xVal<width && yVal>=0 && yVal<height)
  234. {
  235. TerrainTile & curt = terrain[xVal][yVal][zVal];
  236. if(total || obj->visitableAt(xVal, yVal))
  237. {
  238. curt.visitableObjects -= obj;
  239. curt.visitable = curt.visitableObjects.size();
  240. }
  241. if(total || obj->blockingAt(xVal, yVal))
  242. {
  243. curt.blockingObjects -= obj;
  244. curt.blocked = curt.blockingObjects.size();
  245. }
  246. }
  247. }
  248. }
  249. }
  250. void CMap::addBlockVisTiles(CGObjectInstance * obj)
  251. {
  252. for(int fx=0; fx<obj->getWidth(); ++fx)
  253. {
  254. for(int fy=0; fy<obj->getHeight(); ++fy)
  255. {
  256. int xVal = obj->pos.x - fx;
  257. int yVal = obj->pos.y - fy;
  258. int zVal = obj->pos.z;
  259. if(xVal>=0 && xVal<width && yVal>=0 && yVal<height)
  260. {
  261. TerrainTile & curt = terrain[xVal][yVal][zVal];
  262. if( obj->visitableAt(xVal, yVal))
  263. {
  264. curt.visitableObjects.push_back(obj);
  265. curt.visitable = true;
  266. }
  267. if( obj->blockingAt(xVal, yVal))
  268. {
  269. curt.blockingObjects.push_back(obj);
  270. curt.blocked = true;
  271. }
  272. }
  273. }
  274. }
  275. }
  276. void CMap::calculateGuardingGreaturePositions()
  277. {
  278. int levels = twoLevel ? 2 : 1;
  279. for (int i=0; i<width; i++)
  280. {
  281. for(int j=0; j<height; j++)
  282. {
  283. for (int k = 0; k < levels; k++)
  284. guardingCreaturePositions[i][j][k] = guardingCreaturePosition(int3(i,j,k));
  285. }
  286. }
  287. }
  288. CGHeroInstance * CMap::getHero(int heroID)
  289. {
  290. for(auto & elem : heroesOnMap)
  291. if(elem->subID == heroID)
  292. return elem;
  293. return nullptr;
  294. }
  295. bool CMap::isCoastalTile(const int3 & pos) const
  296. {
  297. //todo: refactoring: extract neighbor tile iterator and use it in GameState
  298. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  299. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  300. if(!isInTheMap(pos))
  301. {
  302. logGlobal->errorStream() << "Coastal check outside of map :"<<pos;
  303. return false;
  304. }
  305. if(isWaterTile(pos))
  306. return false;
  307. for (auto & dir : dirs)
  308. {
  309. const int3 hlp = pos + dir;
  310. if(!isInTheMap(hlp))
  311. continue;
  312. const TerrainTile &hlpt = getTile(hlp);
  313. if(hlpt.isWater())
  314. return true;
  315. }
  316. return false;
  317. }
  318. bool CMap::isInTheMap(const int3 & pos) const
  319. {
  320. if(pos.x < 0 || pos.y < 0 || pos.z < 0 || pos.x >= width || pos.y >= height
  321. || pos.z > (twoLevel ? 1 : 0))
  322. {
  323. return false;
  324. }
  325. else
  326. {
  327. return true;
  328. }
  329. }
  330. TerrainTile & CMap::getTile(const int3 & tile)
  331. {
  332. assert(isInTheMap(tile));
  333. return terrain[tile.x][tile.y][tile.z];
  334. }
  335. const TerrainTile & CMap::getTile(const int3 & tile) const
  336. {
  337. assert(isInTheMap(tile));
  338. return terrain[tile.x][tile.y][tile.z];
  339. }
  340. bool CMap::isWaterTile(const int3 &pos) const
  341. {
  342. return isInTheMap(pos) && getTile(pos).isWater();
  343. }
  344. bool CMap::canMoveBetween(const int3 &src, const int3 &dst) const
  345. {
  346. const TerrainTile * dstTile = &getTile(dst);
  347. const TerrainTile * srcTile = &getTile(src);
  348. return checkForVisitableDir(src, dstTile, dst) && checkForVisitableDir(dst, srcTile, src);
  349. }
  350. bool CMap::checkForVisitableDir(const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  351. {
  352. if (!pom->entrableTerrain()) //rock is never accessible
  353. return false;
  354. for (auto obj : pom->visitableObjects) //checking destination tile
  355. {
  356. if(!vstd::contains(pom->blockingObjects, obj)) //this visitable object is not blocking, ignore
  357. continue;
  358. if (!obj->appearance.isVisitableFrom(src.x - dst.x, src.y - dst.y))
  359. return false;
  360. }
  361. return true;
  362. }
  363. int3 CMap::guardingCreaturePosition (int3 pos) const
  364. {
  365. const int3 originalPos = pos;
  366. // Give monster at position priority.
  367. if (!isInTheMap(pos))
  368. return int3(-1, -1, -1);
  369. const TerrainTile &posTile = getTile(pos);
  370. if (posTile.visitable)
  371. {
  372. for (CGObjectInstance* obj : posTile.visitableObjects)
  373. {
  374. if(obj->blockVisit)
  375. {
  376. if (obj->ID == Obj::MONSTER) // Monster
  377. return pos;
  378. else
  379. return int3(-1, -1, -1); //blockvis objects are not guarded by neighbouring creatures
  380. }
  381. }
  382. }
  383. // See if there are any monsters adjacent.
  384. bool water = posTile.isWater();
  385. pos -= int3(1, 1, 0); // Start with top left.
  386. for (int dx = 0; dx < 3; dx++)
  387. {
  388. for (int dy = 0; dy < 3; dy++)
  389. {
  390. if (isInTheMap(pos))
  391. {
  392. const auto & tile = getTile(pos);
  393. if (tile.visitable && (tile.isWater() == water))
  394. {
  395. for (CGObjectInstance* obj : tile.visitableObjects)
  396. {
  397. if (obj->ID == Obj::MONSTER && checkForVisitableDir(pos, &posTile, originalPos)) // Monster being able to attack investigated tile
  398. {
  399. return pos;
  400. }
  401. }
  402. }
  403. }
  404. pos.y++;
  405. }
  406. pos.y -= 3;
  407. pos.x++;
  408. }
  409. return int3(-1, -1, -1);
  410. }
  411. const CGObjectInstance * CMap::getObjectiveObjectFrom(int3 pos, Obj::EObj type)
  412. {
  413. for (CGObjectInstance * object : getTile(pos).visitableObjects)
  414. {
  415. if (object->ID == type)
  416. return object;
  417. }
  418. // There is weird bug because of which sometimes heroes will not be found properly despite having correct position
  419. // Try to workaround that and find closest object that we can use
  420. logGlobal->errorStream() << "Failed to find object of type " << int(type) << " at " << pos;
  421. logGlobal->errorStream() << "Will try to find closest matching object";
  422. CGObjectInstance * bestMatch = nullptr;
  423. for (CGObjectInstance * object : objects)
  424. {
  425. if (object && object->ID == type)
  426. {
  427. if (bestMatch == nullptr)
  428. bestMatch = object;
  429. else
  430. {
  431. if (object->pos.dist2dSQ(pos) < bestMatch->pos.dist2dSQ(pos))
  432. bestMatch = object;// closer than one we already found
  433. }
  434. }
  435. }
  436. assert(bestMatch != nullptr); // if this happens - victory conditions or map itself is very, very broken
  437. logGlobal->errorStream() << "Will use " << bestMatch->getObjectName() << " from " << bestMatch->pos;
  438. return bestMatch;
  439. }
  440. void CMap::checkForObjectives()
  441. {
  442. // NOTE: probably should be moved to MapFormatH3M.cpp
  443. for (TriggeredEvent & event : triggeredEvents)
  444. {
  445. auto patcher = [&](EventCondition cond) -> EventExpression::Variant
  446. {
  447. switch (cond.condition)
  448. {
  449. case EventCondition::HAVE_ARTIFACT:
  450. boost::algorithm::replace_first(event.onFulfill, "%s", VLC->arth->artifacts[cond.objectType]->Name());
  451. break;
  452. case EventCondition::HAVE_CREATURES:
  453. boost::algorithm::replace_first(event.onFulfill, "%s", VLC->creh->creatures[cond.objectType]->nameSing);
  454. boost::algorithm::replace_first(event.onFulfill, "%d", boost::lexical_cast<std::string>(cond.value));
  455. break;
  456. case EventCondition::HAVE_RESOURCES:
  457. boost::algorithm::replace_first(event.onFulfill, "%s", VLC->generaltexth->restypes[cond.objectType]);
  458. boost::algorithm::replace_first(event.onFulfill, "%d", boost::lexical_cast<std::string>(cond.value));
  459. break;
  460. case EventCondition::HAVE_BUILDING:
  461. if (isInTheMap(cond.position))
  462. cond.object = getObjectiveObjectFrom(cond.position, Obj::TOWN);
  463. break;
  464. case EventCondition::CONTROL:
  465. if (isInTheMap(cond.position))
  466. cond.object = getObjectiveObjectFrom(cond.position, Obj::EObj(cond.objectType));
  467. if (cond.object)
  468. {
  469. const CGTownInstance *town = dynamic_cast<const CGTownInstance*>(cond.object);
  470. if (town)
  471. boost::algorithm::replace_first(event.onFulfill, "%s", town->name);
  472. const CGHeroInstance *hero = dynamic_cast<const CGHeroInstance*>(cond.object);
  473. if (hero)
  474. boost::algorithm::replace_first(event.onFulfill, "%s", hero->name);
  475. }
  476. break;
  477. case EventCondition::DESTROY:
  478. if (isInTheMap(cond.position))
  479. cond.object = getObjectiveObjectFrom(cond.position, Obj::EObj(cond.objectType));
  480. if (cond.object)
  481. {
  482. const CGHeroInstance *hero = dynamic_cast<const CGHeroInstance*>(cond.object);
  483. if (hero)
  484. boost::algorithm::replace_first(event.onFulfill, "%s", hero->name);
  485. }
  486. break;
  487. case EventCondition::TRANSPORT:
  488. cond.object = getObjectiveObjectFrom(cond.position, Obj::TOWN);
  489. break;
  490. //break; case EventCondition::DAYS_PASSED:
  491. //break; case EventCondition::IS_HUMAN:
  492. //break; case EventCondition::DAYS_WITHOUT_TOWN:
  493. //break; case EventCondition::STANDARD_WIN:
  494. //TODO: support new condition format
  495. case EventCondition::HAVE_0:
  496. break;
  497. case EventCondition::DESTROY_0:
  498. break;
  499. case EventCondition::HAVE_BUILDING_0:
  500. break;
  501. }
  502. return cond;
  503. };
  504. event.trigger = event.trigger.morph(patcher);
  505. }
  506. }
  507. void CMap::addNewArtifactInstance(CArtifactInstance * art)
  508. {
  509. art->id = ArtifactInstanceID(artInstances.size());
  510. artInstances.push_back(art);
  511. }
  512. void CMap::eraseArtifactInstance(CArtifactInstance * art)
  513. {
  514. assert(artInstances[art->id.getNum()] == art);
  515. artInstances[art->id.getNum()].dellNull();
  516. }
  517. void CMap::addNewQuestInstance(CQuest* quest)
  518. {
  519. quest->qid = quests.size();
  520. quests.push_back(quest);
  521. }
  522. void CMap::addNewObject(CGObjectInstance * obj)
  523. {
  524. if(obj->id != ObjectInstanceID(objects.size()))
  525. throw std::runtime_error("Invalid object instance id");
  526. if(obj->instanceName == "")
  527. throw std::runtime_error("Object instance name missing");
  528. auto it = instanceNames.find(obj->instanceName);
  529. if(it != instanceNames.end())
  530. throw std::runtime_error("Object instance name duplicated: "+obj->instanceName);
  531. objects.push_back(obj);
  532. instanceNames[obj->instanceName] = obj;
  533. addBlockVisTiles(obj);
  534. obj->afterAddToMap(this);
  535. }
  536. void CMap::initTerrain()
  537. {
  538. int level = twoLevel ? 2 : 1;
  539. terrain = new TerrainTile**[width];
  540. guardingCreaturePositions = new int3**[width];
  541. for (int i = 0; i < width; ++i)
  542. {
  543. terrain[i] = new TerrainTile*[height];
  544. guardingCreaturePositions[i] = new int3*[height];
  545. for (int j = 0; j < height; ++j)
  546. {
  547. terrain[i][j] = new TerrainTile[level];
  548. guardingCreaturePositions[i][j] = new int3[level];
  549. }
  550. }
  551. }
  552. CMapEditManager * CMap::getEditManager()
  553. {
  554. if(!editManager) editManager = make_unique<CMapEditManager>(this);
  555. return editManager.get();
  556. }