2
0

CMap.cpp 16 KB

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