CMap.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  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. for(auto obj : objects)
  201. obj.dellNull();
  202. }
  203. void CMap::removeBlockVisTiles(CGObjectInstance * obj, bool total)
  204. {
  205. for(int fx=0; fx<obj->getWidth(); ++fx)
  206. {
  207. for(int fy=0; fy<obj->getHeight(); ++fy)
  208. {
  209. int xVal = obj->pos.x - fx;
  210. int yVal = obj->pos.y - fy;
  211. int zVal = obj->pos.z;
  212. if(xVal>=0 && xVal<width && yVal>=0 && yVal<height)
  213. {
  214. TerrainTile & curt = terrain[xVal][yVal][zVal];
  215. if(total || obj->visitableAt(xVal, yVal))
  216. {
  217. curt.visitableObjects -= obj;
  218. curt.visitable = curt.visitableObjects.size();
  219. }
  220. if(total || obj->blockingAt(xVal, yVal))
  221. {
  222. curt.blockingObjects -= obj;
  223. curt.blocked = curt.blockingObjects.size();
  224. }
  225. }
  226. }
  227. }
  228. }
  229. void CMap::addBlockVisTiles(CGObjectInstance * obj)
  230. {
  231. for(int fx=0; fx<obj->getWidth(); ++fx)
  232. {
  233. for(int fy=0; fy<obj->getHeight(); ++fy)
  234. {
  235. int xVal = obj->pos.x - fx;
  236. int yVal = obj->pos.y - fy;
  237. int zVal = obj->pos.z;
  238. if(xVal>=0 && xVal<width && yVal>=0 && yVal<height)
  239. {
  240. TerrainTile & curt = terrain[xVal][yVal][zVal];
  241. if( obj->visitableAt(xVal, yVal))
  242. {
  243. curt.visitableObjects.push_back(obj);
  244. curt.visitable = true;
  245. }
  246. if( obj->blockingAt(xVal, yVal))
  247. {
  248. curt.blockingObjects.push_back(obj);
  249. curt.blocked = true;
  250. }
  251. }
  252. }
  253. }
  254. }
  255. void CMap::calculateGuardingGreaturePositions()
  256. {
  257. int levels = twoLevel ? 2 : 1;
  258. for (int i=0; i<width; i++)
  259. {
  260. for(int j=0; j<height; j++)
  261. {
  262. for (int k = 0; k < levels; k++)
  263. guardingCreaturePositions[i][j][k] = guardingCreaturePosition(int3(i,j,k));
  264. }
  265. }
  266. }
  267. CGHeroInstance * CMap::getHero(int heroID)
  268. {
  269. for(auto & elem : heroesOnMap)
  270. if(elem->subID == heroID)
  271. return elem;
  272. return nullptr;
  273. }
  274. bool CMap::isCoastalTile(const int3 & pos) const
  275. {
  276. //todo: refactoring: extract neighbor tile iterator and use it in GameState
  277. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  278. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  279. if(!isInTheMap(pos))
  280. {
  281. logGlobal->errorStream() << "Coastal check outside of map :"<<pos;
  282. return false;
  283. }
  284. if(isWaterTile(pos))
  285. return false;
  286. for (auto & dir : dirs)
  287. {
  288. const int3 hlp = pos + dir;
  289. if(!isInTheMap(hlp))
  290. continue;
  291. const TerrainTile &hlpt = getTile(hlp);
  292. if(hlpt.isWater())
  293. return true;
  294. }
  295. return false;
  296. }
  297. bool CMap::isInTheMap(const int3 & pos) const
  298. {
  299. if(pos.x < 0 || pos.y < 0 || pos.z < 0 || pos.x >= width || pos.y >= height
  300. || pos.z > (twoLevel ? 1 : 0))
  301. {
  302. return false;
  303. }
  304. else
  305. {
  306. return true;
  307. }
  308. }
  309. TerrainTile & CMap::getTile(const int3 & tile)
  310. {
  311. assert(isInTheMap(tile));
  312. return terrain[tile.x][tile.y][tile.z];
  313. }
  314. const TerrainTile & CMap::getTile(const int3 & tile) const
  315. {
  316. assert(isInTheMap(tile));
  317. return terrain[tile.x][tile.y][tile.z];
  318. }
  319. bool CMap::isWaterTile(const int3 &pos) const
  320. {
  321. return isInTheMap(pos) && getTile(pos).isWater();
  322. }
  323. bool CMap::checkForVisitableDir(const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  324. {
  325. if (!pom->entrableTerrain()) //rock is never accessible
  326. return false;
  327. for (auto obj : pom->visitableObjects) //checking destination tile
  328. {
  329. if(!vstd::contains(pom->blockingObjects, obj)) //this visitable object is not blocking, ignore
  330. continue;
  331. if (!obj->appearance.isVisitableFrom(src.x - dst.x, src.y - dst.y))
  332. return false;
  333. }
  334. return true;
  335. }
  336. int3 CMap::guardingCreaturePosition (int3 pos) const
  337. {
  338. const int3 originalPos = pos;
  339. // Give monster at position priority.
  340. if (!isInTheMap(pos))
  341. return int3(-1, -1, -1);
  342. const TerrainTile &posTile = getTile(pos);
  343. if (posTile.visitable)
  344. {
  345. for (CGObjectInstance* obj : posTile.visitableObjects)
  346. {
  347. if(obj->blockVisit)
  348. {
  349. if (obj->ID == Obj::MONSTER) // Monster
  350. return pos;
  351. else
  352. return int3(-1, -1, -1); //blockvis objects are not guarded by neighbouring creatures
  353. }
  354. }
  355. }
  356. // See if there are any monsters adjacent.
  357. bool water = posTile.isWater();
  358. pos -= int3(1, 1, 0); // Start with top left.
  359. for (int dx = 0; dx < 3; dx++)
  360. {
  361. for (int dy = 0; dy < 3; dy++)
  362. {
  363. if (isInTheMap(pos))
  364. {
  365. const auto & tile = getTile(pos);
  366. if (tile.visitable && (tile.isWater() == water))
  367. {
  368. for (CGObjectInstance* obj : tile.visitableObjects)
  369. {
  370. if (obj->ID == Obj::MONSTER && checkForVisitableDir(pos, &posTile, originalPos)) // Monster being able to attack investigated tile
  371. {
  372. return pos;
  373. }
  374. }
  375. }
  376. }
  377. pos.y++;
  378. }
  379. pos.y -= 3;
  380. pos.x++;
  381. }
  382. return int3(-1, -1, -1);
  383. }
  384. const CGObjectInstance * CMap::getObjectiveObjectFrom(int3 pos, Obj::EObj type)
  385. {
  386. for (CGObjectInstance * object : getTile(pos).visitableObjects)
  387. {
  388. if (object->ID == type)
  389. return object;
  390. }
  391. // There is weird bug because of which sometimes heroes will not be found properly despite having correct position
  392. // Try to workaround that and find closest object that we can use
  393. logGlobal->errorStream() << "Failed to find object of type " << int(type) << " at " << pos;
  394. logGlobal->errorStream() << "Will try to find closest matching object";
  395. CGObjectInstance * bestMatch = nullptr;
  396. for (CGObjectInstance * object : objects)
  397. {
  398. if (object && object->ID == type)
  399. {
  400. if (bestMatch == nullptr)
  401. bestMatch = object;
  402. else
  403. {
  404. if (object->pos.dist2dSQ(pos) < bestMatch->pos.dist2dSQ(pos))
  405. bestMatch = object;// closer than one we already found
  406. }
  407. }
  408. }
  409. assert(bestMatch != nullptr); // if this happens - victory conditions or map itself is very, very broken
  410. logGlobal->errorStream() << "Will use " << bestMatch->getObjectName() << " from " << bestMatch->pos;
  411. return bestMatch;
  412. }
  413. void CMap::checkForObjectives()
  414. {
  415. // NOTE: probably should be moved to MapFormatH3M.cpp
  416. for (TriggeredEvent & event : triggeredEvents)
  417. {
  418. auto patcher = [&](EventCondition cond) -> EventExpression::Variant
  419. {
  420. switch (cond.condition)
  421. {
  422. break; case EventCondition::HAVE_ARTIFACT:
  423. boost::algorithm::replace_first(event.onFulfill, "%s", VLC->arth->artifacts[cond.objectType]->Name());
  424. break; case EventCondition::HAVE_CREATURES:
  425. boost::algorithm::replace_first(event.onFulfill, "%s", VLC->creh->creatures[cond.objectType]->nameSing);
  426. boost::algorithm::replace_first(event.onFulfill, "%d", boost::lexical_cast<std::string>(cond.value));
  427. break; case EventCondition::HAVE_RESOURCES:
  428. boost::algorithm::replace_first(event.onFulfill, "%s", VLC->generaltexth->restypes[cond.objectType]);
  429. boost::algorithm::replace_first(event.onFulfill, "%d", boost::lexical_cast<std::string>(cond.value));
  430. break; case EventCondition::HAVE_BUILDING:
  431. if (isInTheMap(cond.position))
  432. cond.object = getObjectiveObjectFrom(cond.position, Obj::TOWN);
  433. break; case EventCondition::CONTROL:
  434. if (isInTheMap(cond.position))
  435. cond.object = getObjectiveObjectFrom(cond.position, Obj::EObj(cond.objectType));
  436. if (cond.object)
  437. {
  438. const CGTownInstance *town = dynamic_cast<const CGTownInstance*>(cond.object);
  439. if (town)
  440. boost::algorithm::replace_first(event.onFulfill, "%s", town->name);
  441. const CGHeroInstance *hero = dynamic_cast<const CGHeroInstance*>(cond.object);
  442. if (hero)
  443. boost::algorithm::replace_first(event.onFulfill, "%s", hero->name);
  444. }
  445. break; case EventCondition::DESTROY:
  446. if (isInTheMap(cond.position))
  447. cond.object = getObjectiveObjectFrom(cond.position, Obj::EObj(cond.objectType));
  448. if (cond.object)
  449. {
  450. const CGHeroInstance *hero = dynamic_cast<const CGHeroInstance*>(cond.object);
  451. if (hero)
  452. boost::algorithm::replace_first(event.onFulfill, "%s", hero->name);
  453. }
  454. break; case EventCondition::TRANSPORT:
  455. cond.object = getObjectiveObjectFrom(cond.position, Obj::TOWN);
  456. //break; case EventCondition::DAYS_PASSED:
  457. //break; case EventCondition::IS_HUMAN:
  458. //break; case EventCondition::DAYS_WITHOUT_TOWN:
  459. //break; case EventCondition::STANDARD_WIN:
  460. }
  461. return cond;
  462. };
  463. event.trigger = event.trigger.morph(patcher);
  464. }
  465. }
  466. void CMap::addNewArtifactInstance(CArtifactInstance * art)
  467. {
  468. art->id = ArtifactInstanceID(artInstances.size());
  469. artInstances.push_back(art);
  470. }
  471. void CMap::eraseArtifactInstance(CArtifactInstance * art)
  472. {
  473. assert(artInstances[art->id.getNum()] == art);
  474. artInstances[art->id.getNum()].dellNull();
  475. }
  476. void CMap::addQuest(CGObjectInstance * quest)
  477. {
  478. auto q = dynamic_cast<IQuestObject *>(quest);
  479. q->quest->qid = quests.size();
  480. quests.push_back(q->quest);
  481. }
  482. void CMap::addNewObject(CGObjectInstance * obj)
  483. {
  484. if(obj->id != ObjectInstanceID(objects.size()))
  485. throw std::runtime_error("Invalid object instance id");
  486. if(obj->instanceName == "")
  487. throw std::runtime_error("Object instance name missing");
  488. auto it = instanceNames.find(obj->instanceName);
  489. if(it != instanceNames.end())
  490. throw std::runtime_error("Object instance name duplicated:"+obj->instanceName);
  491. objects.push_back(obj);
  492. instanceNames[obj->instanceName] = obj;
  493. addBlockVisTiles(obj);
  494. if(obj->ID == Obj::TOWN)
  495. {
  496. towns.push_back(static_cast<CGTownInstance *>(obj));
  497. }
  498. if(obj->ID == Obj::HERO)
  499. {
  500. heroesOnMap.push_back(static_cast<CGHeroInstance*>(obj));
  501. }
  502. }
  503. void CMap::initTerrain()
  504. {
  505. int level = twoLevel ? 2 : 1;
  506. terrain = new TerrainTile**[width];
  507. guardingCreaturePositions = new int3**[width];
  508. for (int i = 0; i < width; ++i)
  509. {
  510. terrain[i] = new TerrainTile*[height];
  511. guardingCreaturePositions[i] = new int3*[height];
  512. for (int j = 0; j < height; ++j)
  513. {
  514. terrain[i][j] = new TerrainTile[level];
  515. guardingCreaturePositions[i][j] = new int3[level];
  516. }
  517. }
  518. }
  519. CMapEditManager * CMap::getEditManager()
  520. {
  521. if(!editManager) editManager = make_unique<CMapEditManager>(this);
  522. return editManager.get();
  523. }