CMap.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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(255), 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. position(-1, -1, -1),
  56. condition(condition)
  57. {
  58. }
  59. EventCondition::EventCondition(EWinLoseType condition, si32 value, si32 objectType, int3 position):
  60. object(nullptr),
  61. value(value),
  62. objectType(objectType),
  63. position(position),
  64. condition(condition)
  65. {}
  66. DisposedHero::DisposedHero() : heroId(0), portrait(255), players(0)
  67. {
  68. }
  69. CMapEvent::CMapEvent() : players(0), humanAffected(0), computerAffected(0),
  70. firstOccurence(0), nextOccurence(0)
  71. {
  72. }
  73. bool CMapEvent::earlierThan(const CMapEvent & other) const
  74. {
  75. return firstOccurence < other.firstOccurence;
  76. }
  77. bool CMapEvent::earlierThanOrEqual(const CMapEvent & other) const
  78. {
  79. return firstOccurence <= other.firstOccurence;
  80. }
  81. CCastleEvent::CCastleEvent() : town(nullptr)
  82. {
  83. }
  84. TerrainTile::TerrainTile() : terType(ETerrainType::BORDER), terView(0), riverType(ERiverType::NO_RIVER),
  85. riverDir(0), roadType(ERoadType::NO_ROAD), roadDir(0), extTileFlags(0), visitable(false),
  86. blocked(false)
  87. {
  88. }
  89. bool TerrainTile::entrableTerrain(const TerrainTile * from /*= nullptr*/) const
  90. {
  91. return entrableTerrain(from ? from->terType != ETerrainType::WATER : true, from ? from->terType == ETerrainType::WATER : true);
  92. }
  93. bool TerrainTile::entrableTerrain(bool allowLand, bool allowSea) const
  94. {
  95. return terType != ETerrainType::ROCK
  96. && ((allowSea && terType == ETerrainType::WATER) || (allowLand && terType != ETerrainType::WATER));
  97. }
  98. bool TerrainTile::isClear(const TerrainTile *from /*= nullptr*/) const
  99. {
  100. return entrableTerrain(from) && !blocked;
  101. }
  102. Obj TerrainTile::topVisitableId(bool excludeTop) const
  103. {
  104. return topVisitableObj(excludeTop) ? topVisitableObj(excludeTop)->ID : Obj(Obj::NO_OBJ);
  105. }
  106. CGObjectInstance * TerrainTile::topVisitableObj(bool excludeTop) const
  107. {
  108. if(visitableObjects.empty() || (excludeTop && visitableObjects.size() == 1))
  109. return nullptr;
  110. if(excludeTop)
  111. return visitableObjects[visitableObjects.size()-2];
  112. return visitableObjects.back();
  113. }
  114. bool TerrainTile::isCoastal() const
  115. {
  116. return extTileFlags & 64;
  117. }
  118. bool TerrainTile::hasFavourableWinds() const
  119. {
  120. return extTileFlags & 128;
  121. }
  122. bool TerrainTile::isWater() const
  123. {
  124. return terType == ETerrainType::WATER;
  125. }
  126. const int CMapHeader::MAP_SIZE_SMALL = 36;
  127. const int CMapHeader::MAP_SIZE_MIDDLE = 72;
  128. const int CMapHeader::MAP_SIZE_LARGE = 108;
  129. const int CMapHeader::MAP_SIZE_XLARGE = 144;
  130. void CMapHeader::setupEvents()
  131. {
  132. EventCondition victoryCondition(EventCondition::STANDARD_WIN);
  133. EventCondition defeatCondition(EventCondition::DAYS_WITHOUT_TOWN);
  134. defeatCondition.value = 7;
  135. //Victory condition - defeat all
  136. TriggeredEvent standardVictory;
  137. standardVictory.effect.type = EventEffect::VICTORY;
  138. standardVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[5];
  139. standardVictory.identifier = "standardVictory";
  140. standardVictory.description = ""; // TODO: display in quest window
  141. standardVictory.onFulfill = VLC->generaltexth->allTexts[659];
  142. standardVictory.trigger = EventExpression(victoryCondition);
  143. //Loss condition - 7 days without town
  144. TriggeredEvent standardDefeat;
  145. standardDefeat.effect.type = EventEffect::DEFEAT;
  146. standardDefeat.effect.toOtherMessage = VLC->generaltexth->allTexts[8];
  147. standardDefeat.identifier = "standardDefeat";
  148. standardDefeat.description = ""; // TODO: display in quest window
  149. standardDefeat.onFulfill = VLC->generaltexth->allTexts[7];
  150. standardDefeat.trigger = EventExpression(defeatCondition);
  151. triggeredEvents.push_back(standardVictory);
  152. triggeredEvents.push_back(standardDefeat);
  153. victoryIconIndex = 11;
  154. victoryMessage = VLC->generaltexth->victoryConditions[0];
  155. defeatIconIndex = 3;
  156. defeatMessage = VLC->generaltexth->lossCondtions[0];
  157. }
  158. CMapHeader::CMapHeader() : version(EMapFormat::SOD), height(72), width(72),
  159. twoLevel(true), difficulty(1), levelLimit(0), howManyTeams(0), areAnyPlayers(false)
  160. {
  161. setupEvents();
  162. allowedHeroes = VLC->heroh->getDefaultAllowed();
  163. players.resize(PlayerColor::PLAYER_LIMIT_I);
  164. }
  165. CMapHeader::~CMapHeader()
  166. {
  167. }
  168. CMap::CMap() : checksum(0), grailPos(-1, -1, -1), grailRadious(0), terrain(nullptr)
  169. {
  170. allHeroes.resize(allowedHeroes.size());
  171. allowedAbilities = VLC->heroh->getDefaultAllowedAbilities();
  172. allowedArtifact = VLC->arth->getDefaultAllowed();
  173. allowedSpell = VLC->spellh->getDefaultAllowed();
  174. }
  175. CMap::~CMap()
  176. {
  177. if(terrain)
  178. {
  179. for (int i=0; i<width; i++)
  180. {
  181. for(int j=0; j<height; j++)
  182. {
  183. delete [] terrain[i][j];
  184. delete [] guardingCreaturePositions[i][j];
  185. }
  186. delete [] terrain[i];
  187. delete [] guardingCreaturePositions[i];
  188. }
  189. delete [] terrain;
  190. delete [] guardingCreaturePositions;
  191. }
  192. }
  193. void CMap::removeBlockVisTiles(CGObjectInstance * obj, bool total)
  194. {
  195. for(int fx=0; fx<obj->getWidth(); ++fx)
  196. {
  197. for(int fy=0; fy<obj->getHeight(); ++fy)
  198. {
  199. int xVal = obj->pos.x - fx;
  200. int yVal = obj->pos.y - fy;
  201. int zVal = obj->pos.z;
  202. if(xVal>=0 && xVal<width && yVal>=0 && yVal<height)
  203. {
  204. TerrainTile & curt = terrain[xVal][yVal][zVal];
  205. if(total || obj->visitableAt(xVal, yVal))
  206. {
  207. curt.visitableObjects -= obj;
  208. curt.visitable = curt.visitableObjects.size();
  209. }
  210. if(total || obj->blockingAt(xVal, yVal))
  211. {
  212. curt.blockingObjects -= obj;
  213. curt.blocked = curt.blockingObjects.size();
  214. }
  215. }
  216. }
  217. }
  218. }
  219. void CMap::addBlockVisTiles(CGObjectInstance * obj)
  220. {
  221. for(int fx=0; fx<obj->getWidth(); ++fx)
  222. {
  223. for(int fy=0; fy<obj->getHeight(); ++fy)
  224. {
  225. int xVal = obj->pos.x - fx;
  226. int yVal = obj->pos.y - fy;
  227. int zVal = obj->pos.z;
  228. if(xVal>=0 && xVal<width && yVal>=0 && yVal<height)
  229. {
  230. TerrainTile & curt = terrain[xVal][yVal][zVal];
  231. if( obj->visitableAt(xVal, yVal))
  232. {
  233. curt.visitableObjects.push_back(obj);
  234. curt.visitable = true;
  235. }
  236. if( obj->blockingAt(xVal, yVal))
  237. {
  238. curt.blockingObjects.push_back(obj);
  239. curt.blocked = true;
  240. }
  241. }
  242. }
  243. }
  244. }
  245. void CMap::calculateGuardingGreaturePositions()
  246. {
  247. int levels = twoLevel ? 2 : 1;
  248. for (int i=0; i<width; i++)
  249. {
  250. for(int j=0; j<height; j++)
  251. {
  252. for (int k = 0; k < levels; k++)
  253. guardingCreaturePositions[i][j][k] = guardingCreaturePosition(int3(i,j,k));
  254. }
  255. }
  256. }
  257. CGHeroInstance * CMap::getHero(int heroID)
  258. {
  259. for(auto & elem : heroesOnMap)
  260. if(elem->subID == heroID)
  261. return elem;
  262. return nullptr;
  263. }
  264. bool CMap::isInTheMap(const int3 & pos) const
  265. {
  266. if(pos.x < 0 || pos.y < 0 || pos.z < 0 || pos.x >= width || pos.y >= height
  267. || pos.z > (twoLevel ? 1 : 0))
  268. {
  269. return false;
  270. }
  271. else
  272. {
  273. return true;
  274. }
  275. }
  276. TerrainTile & CMap::getTile(const int3 & tile)
  277. {
  278. assert(isInTheMap(tile));
  279. return terrain[tile.x][tile.y][tile.z];
  280. }
  281. const TerrainTile & CMap::getTile(const int3 & tile) const
  282. {
  283. assert(isInTheMap(tile));
  284. return terrain[tile.x][tile.y][tile.z];
  285. }
  286. bool CMap::isWaterTile(const int3 &pos) const
  287. {
  288. return isInTheMap(pos) && getTile(pos).terType == ETerrainType::WATER;
  289. }
  290. bool CMap::checkForVisitableDir(const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  291. {
  292. if (!pom->entrableTerrain()) //rock is never accessible
  293. return false;
  294. for (auto obj : pom->visitableObjects) //checking destination tile
  295. {
  296. if(!vstd::contains(pom->blockingObjects, obj)) //this visitable object is not blocking, ignore
  297. continue;
  298. if (!obj->appearance.isVisitableFrom(src.x - dst.x, src.y - dst.y))
  299. return false;
  300. }
  301. return true;
  302. }
  303. int3 CMap::guardingCreaturePosition (int3 pos) const
  304. {
  305. const int3 originalPos = pos;
  306. // Give monster at position priority.
  307. if (!isInTheMap(pos))
  308. return int3(-1, -1, -1);
  309. const TerrainTile &posTile = getTile(pos);
  310. if (posTile.visitable)
  311. {
  312. for (CGObjectInstance* obj : posTile.visitableObjects)
  313. {
  314. if(obj->blockVisit)
  315. {
  316. if (obj->ID == Obj::MONSTER) // Monster
  317. return pos;
  318. else
  319. return int3(-1, -1, -1); //blockvis objects are not guarded by neighbouring creatures
  320. }
  321. }
  322. }
  323. // See if there are any monsters adjacent.
  324. bool water = posTile.isWater();
  325. pos -= int3(1, 1, 0); // Start with top left.
  326. for (int dx = 0; dx < 3; dx++)
  327. {
  328. for (int dy = 0; dy < 3; dy++)
  329. {
  330. if (isInTheMap(pos))
  331. {
  332. const auto & tile = getTile(pos);
  333. if (tile.visitable && (tile.isWater() == water))
  334. {
  335. for (CGObjectInstance* obj : tile.visitableObjects)
  336. {
  337. if (obj->ID == Obj::MONSTER && checkForVisitableDir(pos, &posTile, originalPos)) // Monster being able to attack investigated tile
  338. {
  339. return pos;
  340. }
  341. }
  342. }
  343. }
  344. pos.y++;
  345. }
  346. pos.y -= 3;
  347. pos.x++;
  348. }
  349. return int3(-1, -1, -1);
  350. }
  351. const CGObjectInstance * CMap::getObjectiveObjectFrom(int3 pos, Obj::EObj type)
  352. {
  353. for (CGObjectInstance * object : getTile(pos).visitableObjects)
  354. {
  355. if (object->ID == type)
  356. return object;
  357. }
  358. // There is weird bug because of which sometimes heroes will not be found properly despite having correct position
  359. // Try to workaround that and find closest object that we can use
  360. logGlobal->errorStream() << "Failed to find object of type " << int(type) << " at " << pos;
  361. logGlobal->errorStream() << "Will try to find closest matching object";
  362. CGObjectInstance * bestMatch = nullptr;
  363. for (CGObjectInstance * object : objects)
  364. {
  365. if (object && object->ID == type)
  366. {
  367. if (bestMatch == nullptr)
  368. bestMatch = object;
  369. else
  370. {
  371. if (object->pos.dist2dSQ(pos) < bestMatch->pos.dist2dSQ(pos))
  372. bestMatch = object;// closer than one we already found
  373. }
  374. }
  375. }
  376. assert(bestMatch != nullptr); // if this happens - victory conditions or map itself is very, very broken
  377. logGlobal->errorStream() << "Will use " << bestMatch->getObjectName() << " from " << bestMatch->pos;
  378. return bestMatch;
  379. }
  380. void CMap::checkForObjectives()
  381. {
  382. // NOTE: probably should be moved to MapFormatH3M.cpp
  383. for (TriggeredEvent & event : triggeredEvents)
  384. {
  385. auto patcher = [&](EventCondition cond) -> EventExpression::Variant
  386. {
  387. switch (cond.condition)
  388. {
  389. break; case EventCondition::HAVE_ARTIFACT:
  390. boost::algorithm::replace_first(event.onFulfill, "%s", VLC->arth->artifacts[cond.objectType]->Name());
  391. break; case EventCondition::HAVE_CREATURES:
  392. boost::algorithm::replace_first(event.onFulfill, "%s", VLC->creh->creatures[cond.objectType]->nameSing);
  393. boost::algorithm::replace_first(event.onFulfill, "%d", boost::lexical_cast<std::string>(cond.value));
  394. break; case EventCondition::HAVE_RESOURCES:
  395. boost::algorithm::replace_first(event.onFulfill, "%s", VLC->generaltexth->restypes[cond.objectType]);
  396. boost::algorithm::replace_first(event.onFulfill, "%d", boost::lexical_cast<std::string>(cond.value));
  397. break; case EventCondition::HAVE_BUILDING:
  398. if (isInTheMap(cond.position))
  399. cond.object = getObjectiveObjectFrom(cond.position, Obj::TOWN);
  400. break; case EventCondition::CONTROL:
  401. if (isInTheMap(cond.position))
  402. cond.object = getObjectiveObjectFrom(cond.position, Obj::EObj(cond.objectType));
  403. if (cond.object)
  404. {
  405. const CGTownInstance *town = dynamic_cast<const CGTownInstance*>(cond.object);
  406. if (town)
  407. boost::algorithm::replace_first(event.onFulfill, "%s", town->name);
  408. const CGHeroInstance *hero = dynamic_cast<const CGHeroInstance*>(cond.object);
  409. if (hero)
  410. boost::algorithm::replace_first(event.onFulfill, "%s", hero->name);
  411. }
  412. break; case EventCondition::DESTROY:
  413. if (isInTheMap(cond.position))
  414. cond.object = getObjectiveObjectFrom(cond.position, Obj::EObj(cond.objectType));
  415. if (cond.object)
  416. {
  417. const CGHeroInstance *hero = dynamic_cast<const CGHeroInstance*>(cond.object);
  418. if (hero)
  419. boost::algorithm::replace_first(event.onFulfill, "%s", hero->name);
  420. }
  421. break; case EventCondition::TRANSPORT:
  422. cond.object = getObjectiveObjectFrom(cond.position, Obj::TOWN);
  423. //break; case EventCondition::DAYS_PASSED:
  424. //break; case EventCondition::IS_HUMAN:
  425. //break; case EventCondition::DAYS_WITHOUT_TOWN:
  426. //break; case EventCondition::STANDARD_WIN:
  427. }
  428. return cond;
  429. };
  430. event.trigger = event.trigger.morph(patcher);
  431. }
  432. }
  433. void CMap::addNewArtifactInstance(CArtifactInstance * art)
  434. {
  435. art->id = ArtifactInstanceID(artInstances.size());
  436. artInstances.push_back(art);
  437. }
  438. void CMap::eraseArtifactInstance(CArtifactInstance * art)
  439. {
  440. assert(artInstances[art->id.getNum()] == art);
  441. artInstances[art->id.getNum()].dellNull();
  442. }
  443. void CMap::addQuest(CGObjectInstance * quest)
  444. {
  445. auto q = dynamic_cast<IQuestObject *>(quest);
  446. q->quest->qid = quests.size();
  447. quests.push_back(q->quest);
  448. }
  449. void CMap::initTerrain()
  450. {
  451. int level = twoLevel ? 2 : 1;
  452. terrain = new TerrainTile**[width];
  453. guardingCreaturePositions = new int3**[width];
  454. for (int i = 0; i < width; ++i)
  455. {
  456. terrain[i] = new TerrainTile*[height];
  457. guardingCreaturePositions[i] = new int3*[height];
  458. for (int j = 0; j < height; ++j)
  459. {
  460. terrain[i][j] = new TerrainTile[level];
  461. guardingCreaturePositions[i][j] = new int3[level];
  462. }
  463. }
  464. }
  465. CMapEditManager * CMap::getEditManager()
  466. {
  467. if(!editManager) editManager = make_unique<CMapEditManager>(this);
  468. return editManager.get();
  469. }