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. auto visitableObj = visitableObjects;
  109. if(excludeTop && visitableObj.size())
  110. visitableObj.pop_back();
  111. return visitableObj.size() ? visitableObj.back() : nullptr;
  112. }
  113. bool TerrainTile::isCoastal() const
  114. {
  115. return extTileFlags & 64;
  116. }
  117. bool TerrainTile::hasFavourableWinds() const
  118. {
  119. return extTileFlags & 128;
  120. }
  121. bool TerrainTile::isWater() const
  122. {
  123. return terType == ETerrainType::WATER;
  124. }
  125. const int CMapHeader::MAP_SIZE_SMALL = 36;
  126. const int CMapHeader::MAP_SIZE_MIDDLE = 72;
  127. const int CMapHeader::MAP_SIZE_LARGE = 108;
  128. const int CMapHeader::MAP_SIZE_XLARGE = 144;
  129. void CMapHeader::setupEvents()
  130. {
  131. EventCondition victoryCondition(EventCondition::STANDARD_WIN);
  132. EventCondition defeatCondition(EventCondition::DAYS_WITHOUT_TOWN);
  133. defeatCondition.value = 7;
  134. //Victory condition - defeat all
  135. TriggeredEvent standardVictory;
  136. standardVictory.effect.type = EventEffect::VICTORY;
  137. standardVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[5];
  138. standardVictory.identifier = "standardVictory";
  139. standardVictory.description = ""; // TODO: display in quest window
  140. standardVictory.onFulfill = VLC->generaltexth->allTexts[659];
  141. standardVictory.trigger = EventExpression(victoryCondition);
  142. //Loss condition - 7 days without town
  143. TriggeredEvent standardDefeat;
  144. standardDefeat.effect.type = EventEffect::DEFEAT;
  145. standardDefeat.effect.toOtherMessage = VLC->generaltexth->allTexts[8];
  146. standardDefeat.identifier = "standardDefeat";
  147. standardDefeat.description = ""; // TODO: display in quest window
  148. standardDefeat.onFulfill = VLC->generaltexth->allTexts[7];
  149. standardDefeat.trigger = EventExpression(defeatCondition);
  150. triggeredEvents.push_back(standardVictory);
  151. triggeredEvents.push_back(standardDefeat);
  152. victoryIconIndex = 11;
  153. victoryMessage = VLC->generaltexth->victoryConditions[0];
  154. defeatIconIndex = 3;
  155. defeatMessage = VLC->generaltexth->lossCondtions[0];
  156. }
  157. CMapHeader::CMapHeader() : version(EMapFormat::SOD), height(72), width(72),
  158. twoLevel(true), difficulty(1), levelLimit(0), howManyTeams(0), areAnyPlayers(false)
  159. {
  160. setupEvents();
  161. allowedHeroes = VLC->heroh->getDefaultAllowed();
  162. players.resize(PlayerColor::PLAYER_LIMIT_I);
  163. }
  164. CMapHeader::~CMapHeader()
  165. {
  166. }
  167. CMap::CMap() : checksum(0), grailPos(-1, -1, -1), grailRadious(0), terrain(nullptr)
  168. {
  169. allHeroes.resize(allowedHeroes.size());
  170. allowedAbilities = VLC->heroh->getDefaultAllowedAbilities();
  171. allowedArtifact = VLC->arth->getDefaultAllowed();
  172. allowedSpell = VLC->spellh->getDefaultAllowed();
  173. }
  174. CMap::~CMap()
  175. {
  176. if(terrain)
  177. {
  178. for (int i=0; i<width; i++)
  179. {
  180. for(int j=0; j<height; j++)
  181. {
  182. delete [] terrain[i][j];
  183. delete [] guardingCreaturePositions[i][j];
  184. }
  185. delete [] terrain[i];
  186. delete [] guardingCreaturePositions[i];
  187. }
  188. delete [] terrain;
  189. delete [] guardingCreaturePositions;
  190. }
  191. }
  192. void CMap::removeBlockVisTiles(CGObjectInstance * obj, bool total)
  193. {
  194. for(int fx=0; fx<obj->getWidth(); ++fx)
  195. {
  196. for(int fy=0; fy<obj->getHeight(); ++fy)
  197. {
  198. int xVal = obj->pos.x - fx;
  199. int yVal = obj->pos.y - fy;
  200. int zVal = obj->pos.z;
  201. if(xVal>=0 && xVal<width && yVal>=0 && yVal<height)
  202. {
  203. TerrainTile & curt = terrain[xVal][yVal][zVal];
  204. if(total || obj->visitableAt(xVal, yVal))
  205. {
  206. curt.visitableObjects -= obj;
  207. curt.visitable = curt.visitableObjects.size();
  208. }
  209. if(total || obj->blockingAt(xVal, yVal))
  210. {
  211. curt.blockingObjects -= obj;
  212. curt.blocked = curt.blockingObjects.size();
  213. }
  214. }
  215. }
  216. }
  217. }
  218. void CMap::addBlockVisTiles(CGObjectInstance * obj)
  219. {
  220. for(int fx=0; fx<obj->getWidth(); ++fx)
  221. {
  222. for(int fy=0; fy<obj->getHeight(); ++fy)
  223. {
  224. int xVal = obj->pos.x - fx;
  225. int yVal = obj->pos.y - fy;
  226. int zVal = obj->pos.z;
  227. if(xVal>=0 && xVal<width && yVal>=0 && yVal<height)
  228. {
  229. TerrainTile & curt = terrain[xVal][yVal][zVal];
  230. if( obj->visitableAt(xVal, yVal))
  231. {
  232. curt.visitableObjects.push_back(obj);
  233. curt.visitable = true;
  234. }
  235. if( obj->blockingAt(xVal, yVal))
  236. {
  237. curt.blockingObjects.push_back(obj);
  238. curt.blocked = true;
  239. }
  240. }
  241. }
  242. }
  243. }
  244. void CMap::calculateGuardingGreaturePositions()
  245. {
  246. int levels = twoLevel ? 2 : 1;
  247. for (int i=0; i<width; i++)
  248. {
  249. for(int j=0; j<height; j++)
  250. {
  251. for (int k = 0; k < levels; k++)
  252. guardingCreaturePositions[i][j][k] = guardingCreaturePosition(int3(i,j,k));
  253. }
  254. }
  255. }
  256. CGHeroInstance * CMap::getHero(int heroID)
  257. {
  258. for(auto & elem : heroesOnMap)
  259. if(elem->subID == heroID)
  260. return elem;
  261. return nullptr;
  262. }
  263. bool CMap::isInTheMap(const int3 & pos) const
  264. {
  265. if(pos.x < 0 || pos.y < 0 || pos.z < 0 || pos.x >= width || pos.y >= height
  266. || pos.z > (twoLevel ? 1 : 0))
  267. {
  268. return false;
  269. }
  270. else
  271. {
  272. return true;
  273. }
  274. }
  275. TerrainTile & CMap::getTile(const int3 & tile)
  276. {
  277. assert(isInTheMap(tile));
  278. return terrain[tile.x][tile.y][tile.z];
  279. }
  280. const TerrainTile & CMap::getTile(const int3 & tile) const
  281. {
  282. assert(isInTheMap(tile));
  283. return terrain[tile.x][tile.y][tile.z];
  284. }
  285. bool CMap::isWaterTile(const int3 &pos) const
  286. {
  287. return isInTheMap(pos) && getTile(pos).terType == ETerrainType::WATER;
  288. }
  289. bool CMap::checkForVisitableDir(const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  290. {
  291. if (!pom->entrableTerrain()) //rock is never accessible
  292. return false;
  293. for(ui32 b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  294. {
  295. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  296. continue;
  297. const CGObjectInstance * obj = pom->visitableObjects[b];
  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. }