CMap.cpp 17 KB

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