CMap.cpp 14 KB

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