CMap.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  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 "CMapEditManager.h"
  13. #include "CMapOperation.h"
  14. #include "../CCreatureHandler.h"
  15. #include "../CSkillHandler.h"
  16. #include "../GameLibrary.h"
  17. #include "../GameSettings.h"
  18. #include "../RiverHandler.h"
  19. #include "../RoadHandler.h"
  20. #include "../TerrainHandler.h"
  21. #include "../callback/IGameInfoCallback.h"
  22. #include "../entities/artifact/CArtHandler.h"
  23. #include "../entities/hero/CHeroHandler.h"
  24. #include "../gameState/CGameState.h"
  25. #include "../mapObjects/CGHeroInstance.h"
  26. #include "../mapObjects/CGTownInstance.h"
  27. #include "../mapObjects/CQuest.h"
  28. #include "../mapObjects/ObjectTemplate.h"
  29. #include "../serializer/JsonSerializeFormat.h"
  30. #include "../spells/CSpellHandler.h"
  31. #include "../texts/CGeneralTextHandler.h"
  32. #include <vstd/RNG.h>
  33. VCMI_LIB_NAMESPACE_BEGIN
  34. void Rumor::serializeJson(JsonSerializeFormat & handler)
  35. {
  36. handler.serializeString("name", name);
  37. handler.serializeStruct("text", text);
  38. }
  39. CMapEvent::CMapEvent()
  40. : humanAffected(false)
  41. , computerAffected(false)
  42. , firstOccurrence(0)
  43. , nextOccurrence(0)
  44. {
  45. }
  46. bool CMapEvent::occursToday(int currentDay) const
  47. {
  48. if (currentDay == firstOccurrence + 1)
  49. return true;
  50. if (nextOccurrence == 0)
  51. return false;
  52. if (currentDay < firstOccurrence)
  53. return false;
  54. return (currentDay - firstOccurrence - 1) % nextOccurrence == 0;
  55. }
  56. bool CMapEvent::affectsPlayer(PlayerColor color, bool isHuman) const
  57. {
  58. if (players.count(color) == 0)
  59. return false;
  60. if (!isHuman && !computerAffected)
  61. return false;
  62. if (isHuman && !humanAffected)
  63. return false;
  64. return true;
  65. }
  66. void CMapEvent::serializeJson(JsonSerializeFormat & handler)
  67. {
  68. handler.serializeString("name", name);
  69. handler.serializeStruct("message", message);
  70. if (!handler.saving && handler.getCurrent()["players"].isNumber())
  71. {
  72. // compatibility for old maps
  73. int playersMask = 0;
  74. handler.serializeInt("players", playersMask);
  75. for (int i = 0; i < 8; ++i)
  76. if ((playersMask & (1 << i)) != 0)
  77. players.insert(PlayerColor(i));
  78. }
  79. else
  80. {
  81. handler.serializeIdArray("players", players);
  82. }
  83. handler.serializeInt("humanAffected", humanAffected);
  84. handler.serializeInt("computerAffected", computerAffected);
  85. handler.serializeInt("firstOccurrence", firstOccurrence);
  86. handler.serializeInt("nextOccurrence", nextOccurrence);
  87. resources.serializeJson(handler, "resources");
  88. auto deletedObjects = handler.enterArray("deletedObjectsInstances");
  89. deletedObjects.serializeArray(deletedObjectsInstances);
  90. }
  91. void CCastleEvent::serializeJson(JsonSerializeFormat & handler)
  92. {
  93. CMapEvent::serializeJson(handler);
  94. // TODO: handler.serializeIdArray("buildings", buildings);
  95. {
  96. std::vector<BuildingID> temp(buildings.begin(), buildings.end());
  97. auto a = handler.enterArray("buildings");
  98. a.syncSize(temp);
  99. for(int i = 0; i < temp.size(); ++i)
  100. {
  101. int buildingID = temp[i].getNum();
  102. a.serializeInt(i, buildingID);
  103. buildings.insert(buildingID);
  104. }
  105. }
  106. {
  107. auto a = handler.enterArray("creatures");
  108. a.syncSize(creatures);
  109. for(int i = 0; i < creatures.size(); ++i)
  110. a.serializeInt(i, creatures[i]);
  111. }
  112. }
  113. TerrainTile::TerrainTile():
  114. riverType(River::NO_RIVER),
  115. roadType(Road::NO_ROAD),
  116. terView(0),
  117. riverDir(0),
  118. roadDir(0),
  119. extTileFlags(0)
  120. {
  121. }
  122. bool TerrainTile::isClear(const TerrainTile * from) const
  123. {
  124. return entrableTerrain(from) && !blocked();
  125. }
  126. ObjectInstanceID TerrainTile::topVisitableObj(bool excludeTop) const
  127. {
  128. if(visitableObjects.empty() || (excludeTop && visitableObjects.size() == 1))
  129. return {};
  130. if(excludeTop)
  131. return visitableObjects[visitableObjects.size()-2];
  132. return visitableObjects.back();
  133. }
  134. EDiggingStatus TerrainTile::getDiggingStatus(const bool excludeTop) const
  135. {
  136. if(isWater() || !getTerrain()->isPassable())
  137. return EDiggingStatus::WRONG_TERRAIN;
  138. int allowedBlocked = excludeTop ? 1 : 0;
  139. if(blockingObjects.size() > allowedBlocked || topVisitableObj(excludeTop).hasValue())
  140. return EDiggingStatus::TILE_OCCUPIED;
  141. else
  142. return EDiggingStatus::CAN_DIG;
  143. }
  144. CMap::CMap(IGameInfoCallback * cb)
  145. : GameCallbackHolder(cb)
  146. , grailPos(-1, -1, -1)
  147. , grailRadius(0)
  148. , waterMap(false)
  149. , uidCounter(0)
  150. {
  151. heroesPool.resize(LIBRARY->heroh->size());
  152. allowedAbilities = LIBRARY->skillh->getDefaultAllowed();
  153. allowedArtifact = LIBRARY->arth->getDefaultAllowed();
  154. allowedSpells = LIBRARY->spellh->getDefaultAllowed();
  155. gameSettings = std::make_unique<GameSettings>();
  156. gameSettings->loadBase(LIBRARY->settingsHandler->getFullConfig());
  157. }
  158. CMap::~CMap() = default;
  159. void CMap::hideObject(CGObjectInstance * obj)
  160. {
  161. const int zVal = obj->anchorPos().z;
  162. for(int fx = 0; fx < obj->getWidth(); ++fx)
  163. {
  164. int xVal = obj->anchorPos().x - fx;
  165. for(int fy = 0; fy < obj->getHeight(); ++fy)
  166. {
  167. int yVal = obj->anchorPos().y - fy;
  168. if(xVal>=0 && xVal < width && yVal>=0 && yVal < height)
  169. {
  170. TerrainTile & curt = terrain[zVal][xVal][yVal];
  171. curt.visitableObjects -= obj->id;
  172. curt.blockingObjects -= obj->id;
  173. }
  174. }
  175. }
  176. }
  177. void CMap::showObject(CGObjectInstance * obj)
  178. {
  179. const int zVal = obj->anchorPos().z;
  180. for(int fx = 0; fx < obj->getWidth(); ++fx)
  181. {
  182. int xVal = obj->anchorPos().x - fx;
  183. for(int fy = 0; fy < obj->getHeight(); ++fy)
  184. {
  185. int yVal = obj->anchorPos().y - fy;
  186. if(xVal>=0 && xVal < width && yVal >= 0 && yVal < height)
  187. {
  188. TerrainTile & curt = terrain[zVal][xVal][yVal];
  189. if(obj->visitableAt(int3(xVal, yVal, zVal)))
  190. {
  191. assert(!vstd::contains(curt.visitableObjects, obj->id));
  192. curt.visitableObjects.push_back(obj->id);
  193. }
  194. if(obj->blockingAt(int3(xVal, yVal, zVal)))
  195. {
  196. assert(!vstd::contains(curt.blockingObjects, obj->id));
  197. curt.blockingObjects.push_back(obj->id);
  198. }
  199. }
  200. }
  201. }
  202. }
  203. void CMap::calculateGuardingGreaturePositions()
  204. {
  205. int levels = twoLevel ? 2 : 1;
  206. for(int z = 0; z < levels; z++)
  207. {
  208. for(int x = 0; x < width; x++)
  209. {
  210. for(int y = 0; y < height; y++)
  211. {
  212. guardingCreaturePositions[z][x][y] = guardingCreaturePosition(int3(x, y, z));
  213. }
  214. }
  215. }
  216. }
  217. CGHeroInstance * CMap::getHero(HeroTypeID heroID)
  218. {
  219. for (const auto & objectID : heroesOnMap)
  220. {
  221. const auto hero = std::dynamic_pointer_cast<CGHeroInstance>(objects.at(objectID.getNum()));
  222. if (hero->getHeroTypeID() == heroID)
  223. return hero.get();
  224. }
  225. return nullptr;
  226. }
  227. const CGHeroInstance * CMap::getHero(HeroTypeID heroID) const
  228. {
  229. for (const auto & objectID : heroesOnMap)
  230. {
  231. const auto hero = std::dynamic_pointer_cast<CGHeroInstance>(objects.at(objectID.getNum()));
  232. if (hero->getHeroTypeID() == heroID)
  233. return hero.get();
  234. }
  235. return nullptr;
  236. }
  237. bool CMap::isCoastalTile(const int3 & pos) const
  238. {
  239. //todo: refactoring: extract neighbour tile iterator and use it in GameState
  240. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  241. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  242. if(!isInTheMap(pos))
  243. {
  244. logGlobal->error("Coastal check outside of map: %s", pos.toString());
  245. return false;
  246. }
  247. if(getTile(pos).isWater())
  248. return false;
  249. for(const auto & dir : dirs)
  250. {
  251. const int3 hlp = pos + dir;
  252. if(!isInTheMap(hlp))
  253. continue;
  254. const TerrainTile &hlpt = getTile(hlp);
  255. if(hlpt.isWater())
  256. return true;
  257. }
  258. return false;
  259. }
  260. bool CMap::canMoveBetween(const int3 &src, const int3 &dst) const
  261. {
  262. const TerrainTile * dstTile = &getTile(dst);
  263. const TerrainTile * srcTile = &getTile(src);
  264. return checkForVisitableDir(src, dstTile, dst) && checkForVisitableDir(dst, srcTile, src);
  265. }
  266. bool CMap::checkForVisitableDir(const int3 & src, const TerrainTile * pom, const int3 & dst) const
  267. {
  268. if (!pom->entrableTerrain()) //rock is never accessible
  269. return false;
  270. for(const auto & objID : pom->visitableObjects) //checking destination tile
  271. {
  272. if(!vstd::contains(pom->blockingObjects, objID)) //this visitable object is not blocking, ignore
  273. continue;
  274. if (!getObject(objID)->appearance->isVisitableFrom(src.x - dst.x, src.y - dst.y))
  275. return false;
  276. }
  277. return true;
  278. }
  279. int3 CMap::guardingCreaturePosition (int3 pos) const
  280. {
  281. const int3 originalPos = pos;
  282. // Give monster at position priority.
  283. if (!isInTheMap(pos))
  284. return int3(-1, -1, -1);
  285. const TerrainTile &posTile = getTile(pos);
  286. if (posTile.visitable())
  287. {
  288. for (const auto & objID : posTile.visitableObjects)
  289. {
  290. const auto * object = getObject(objID);
  291. if (object->ID == Obj::MONSTER)
  292. return pos;
  293. }
  294. }
  295. // See if there are any monsters adjacent.
  296. bool water = posTile.isWater();
  297. pos -= int3(1, 1, 0); // Start with top left.
  298. for (int dx = 0; dx < 3; dx++)
  299. {
  300. for (int dy = 0; dy < 3; dy++)
  301. {
  302. if (isInTheMap(pos))
  303. {
  304. const auto & tile = getTile(pos);
  305. if (tile.visitable() && (tile.isWater() == water))
  306. {
  307. for (const auto & objID : tile.visitableObjects)
  308. {
  309. const auto * object = getObject(objID);
  310. if (object->ID == Obj::MONSTER && checkForVisitableDir(pos, &posTile, originalPos)) // Monster being able to attack investigated tile
  311. return pos;
  312. }
  313. }
  314. }
  315. pos.y++;
  316. }
  317. pos.y -= 3;
  318. pos.x++;
  319. }
  320. return int3(-1, -1, -1);
  321. }
  322. const CGObjectInstance * CMap::getObjectiveObjectFrom(const int3 & pos, Obj type)
  323. {
  324. for(const auto & objID : getTile(pos).visitableObjects)
  325. {
  326. const auto * object = getObject(objID);
  327. if (object->ID == type)
  328. return object;
  329. }
  330. // There is weird bug because of which sometimes heroes will not be found properly despite having correct position
  331. // Try to workaround that and find closest object that we can use
  332. logGlobal->error("Failed to find object of type %d at %s", type.getNum(), pos.toString());
  333. logGlobal->error("Will try to find closest matching object");
  334. CGObjectInstance * bestMatch = nullptr;
  335. for (const auto & object : objects)
  336. {
  337. if (object && object->ID == type)
  338. {
  339. if (bestMatch == nullptr)
  340. bestMatch = object.get();
  341. else
  342. {
  343. if (object->anchorPos().dist2dSQ(pos) < bestMatch->anchorPos().dist2dSQ(pos))
  344. bestMatch = object.get();// closer than one we already found
  345. }
  346. }
  347. }
  348. assert(bestMatch != nullptr); // if this happens - victory conditions or map itself is very, very broken
  349. logGlobal->error("Will use %s from %s", bestMatch->getObjectName(), bestMatch->anchorPos().toString());
  350. return bestMatch;
  351. }
  352. void CMap::checkForObjectives()
  353. {
  354. // NOTE: probably should be moved to MapFormatH3M.cpp
  355. for (TriggeredEvent & event : triggeredEvents)
  356. {
  357. auto patcher = [&](EventCondition cond) -> EventExpression::Variant
  358. {
  359. switch (cond.condition)
  360. {
  361. case EventCondition::HAVE_ARTIFACT:
  362. event.onFulfill.replaceTextID(cond.objectType.as<ArtifactID>().toEntity(LIBRARY)->getNameTextID());
  363. break;
  364. case EventCondition::HAVE_CREATURES:
  365. event.onFulfill.replaceTextID(cond.objectType.as<CreatureID>().toEntity(LIBRARY)->getNameSingularTextID());
  366. event.onFulfill.replaceNumber(cond.value);
  367. break;
  368. case EventCondition::HAVE_RESOURCES:
  369. event.onFulfill.replaceName(cond.objectType.as<GameResID>());
  370. event.onFulfill.replaceNumber(cond.value);
  371. break;
  372. case EventCondition::HAVE_BUILDING:
  373. if (isInTheMap(cond.position))
  374. cond.objectID = getObjectiveObjectFrom(cond.position, Obj::TOWN)->id;
  375. break;
  376. case EventCondition::CONTROL:
  377. if (isInTheMap(cond.position))
  378. cond.objectID = getObjectiveObjectFrom(cond.position, cond.objectType.as<MapObjectID>())->id;
  379. if (cond.objectID != ObjectInstanceID::NONE)
  380. {
  381. const auto * town = dynamic_cast<const CGTownInstance *>(objects[cond.objectID].get());
  382. if (town)
  383. event.onFulfill.replaceRawString(town->getNameTranslated());
  384. const auto * hero = dynamic_cast<const CGHeroInstance *>(objects[cond.objectID].get());
  385. if (hero)
  386. event.onFulfill.replaceRawString(hero->getNameTranslated());
  387. }
  388. break;
  389. case EventCondition::DESTROY:
  390. if (isInTheMap(cond.position))
  391. cond.objectID = getObjectiveObjectFrom(cond.position, cond.objectType.as<MapObjectID>())->id;
  392. if (cond.objectID != ObjectInstanceID::NONE)
  393. {
  394. const auto * hero = dynamic_cast<const CGHeroInstance *>(objects[cond.objectID].get());
  395. if (hero)
  396. event.onFulfill.replaceRawString(hero->getNameTranslated());
  397. }
  398. break;
  399. case EventCondition::TRANSPORT:
  400. cond.objectID = getObjectiveObjectFrom(cond.position, Obj::TOWN)->id;
  401. break;
  402. //break; case EventCondition::DAYS_PASSED:
  403. //break; case EventCondition::IS_HUMAN:
  404. //break; case EventCondition::DAYS_WITHOUT_TOWN:
  405. //break; case EventCondition::STANDARD_WIN:
  406. }
  407. return cond;
  408. };
  409. event.trigger = event.trigger.morph(patcher);
  410. }
  411. }
  412. void CMap::eraseArtifactInstance(ArtifactInstanceID art)
  413. {
  414. //TODO: handle for artifacts removed in map editor
  415. artInstances[art.getNum()] = nullptr;
  416. }
  417. void CMap::moveArtifactInstance(
  418. CArtifactSet & srcSet, const ArtifactPosition & srcSlot,
  419. CArtifactSet & dstSet, const ArtifactPosition & dstSlot)
  420. {
  421. auto art = srcSet.getArt(srcSlot);
  422. removeArtifactInstance(srcSet, srcSlot);
  423. putArtifactInstance(dstSet, art->getId(), dstSlot);
  424. }
  425. void CMap::putArtifactInstance(CArtifactSet & set, ArtifactInstanceID artID, const ArtifactPosition & slot)
  426. {
  427. auto artifact = artInstances.at(artID.getNum());
  428. artifact->addPlacementMap(set.putArtifact(slot, artifact.get()));
  429. }
  430. void CMap::removeArtifactInstance(CArtifactSet & set, const ArtifactPosition & slot)
  431. {
  432. ArtifactInstanceID artID = set.getArtID(slot);
  433. auto artifact = artInstances.at(artID.getNum());
  434. assert(artifact);
  435. set.removeArtifact(slot);
  436. CArtifactSet::ArtPlacementMap partsMap;
  437. for(auto & part : artifact->getPartsInfo())
  438. {
  439. if(part.slot != ArtifactPosition::PRE_FIRST)
  440. partsMap.try_emplace(part.getArtifact(), ArtifactPosition::PRE_FIRST);
  441. }
  442. artifact->addPlacementMap(partsMap);
  443. }
  444. void CMap::generateUniqueInstanceName(CGObjectInstance * target)
  445. {
  446. //this gives object unique name even if objects are removed later
  447. auto uid = uidCounter++;
  448. boost::format fmt("%s_%d");
  449. fmt % target->getTypeName() % uid;
  450. target->instanceName = fmt.str();
  451. }
  452. void CMap::addNewObject(std::shared_ptr<CGObjectInstance> obj)
  453. {
  454. if (!obj->id.hasValue())
  455. obj->id = ObjectInstanceID(objects.size());
  456. if(obj->id != ObjectInstanceID(objects.size()) && objects.at(obj->id.getNum()) != nullptr)
  457. throw std::runtime_error("Invalid object instance id");
  458. if(obj->instanceName.empty())
  459. throw std::runtime_error("Object instance name missing");
  460. if (vstd::contains(instanceNames, obj->instanceName))
  461. throw std::runtime_error("Object instance name duplicated: "+obj->instanceName);
  462. if (obj->id == ObjectInstanceID(objects.size()))
  463. objects.emplace_back(obj);
  464. else
  465. objects[obj->id.getNum()] = obj;
  466. instanceNames[obj->instanceName] = obj;
  467. showObject(obj.get());
  468. //TODO: how about defeated heroes recruited again?
  469. obj->afterAddToMap(this);
  470. }
  471. void CMap::moveObject(ObjectInstanceID target, const int3 & dst)
  472. {
  473. auto obj = objects.at(target).get();
  474. hideObject(obj);
  475. obj->setAnchorPos(dst);
  476. showObject(obj);
  477. }
  478. std::shared_ptr<CGObjectInstance> CMap::removeObject(ObjectInstanceID oldObject)
  479. {
  480. auto obj = objects.at(oldObject);
  481. hideObject(obj.get());
  482. instanceNames.erase(obj->instanceName);
  483. obj->afterRemoveFromMap(this);
  484. //update indices
  485. auto iter = std::next(objects.begin(), obj->id.getNum());
  486. iter = objects.erase(iter);
  487. for(int i = obj->id.getNum(); iter != objects.end(); ++i, ++iter)
  488. (*iter)->id = ObjectInstanceID(i);
  489. for (auto & town : towns)
  490. if (town.getNum() >= obj->id)
  491. town = ObjectInstanceID(town.getNum()-1);
  492. for (auto & hero : heroesOnMap)
  493. if (hero.getNum() >= obj->id)
  494. hero = ObjectInstanceID(hero.getNum()-1);
  495. for(auto tile = terrain.origin(); tile < (terrain.origin() + terrain.num_elements()); ++tile)
  496. {
  497. for (auto & objectID : tile->blockingObjects)
  498. if (objectID.getNum() >= obj->id)
  499. objectID = ObjectInstanceID(objectID.getNum()-1);
  500. for (auto & objectID : tile->visitableObjects)
  501. if (objectID.getNum() >= obj->id)
  502. objectID = ObjectInstanceID(objectID.getNum()-1);
  503. }
  504. //TODO: Clean artifact instances (mostly worn by hero?) and quests related to this object
  505. //This causes crash with undo/redo in editor
  506. return obj;
  507. }
  508. std::shared_ptr<CGObjectInstance> CMap::replaceObject(ObjectInstanceID oldObjectID, const std::shared_ptr<CGObjectInstance> & newObject)
  509. {
  510. auto oldObject = objects.at(oldObjectID.getNum());
  511. newObject->id = oldObjectID;
  512. hideObject(oldObject.get());
  513. instanceNames.erase(oldObject->instanceName);
  514. objects.at(oldObjectID.getNum()) = newObject;
  515. showObject(newObject.get());
  516. instanceNames[newObject->instanceName] = newObject;
  517. oldObject->afterRemoveFromMap(this);
  518. newObject->afterAddToMap(this);
  519. return oldObject;
  520. }
  521. std::shared_ptr<CGObjectInstance> CMap::eraseObject(ObjectInstanceID oldObjectID)
  522. {
  523. auto oldObject = objects.at(oldObjectID.getNum());
  524. instanceNames.erase(oldObject->instanceName);
  525. objects.at(oldObjectID) = nullptr;
  526. hideObject(oldObject.get());
  527. oldObject->afterRemoveFromMap(this);
  528. return oldObject;
  529. }
  530. void CMap::heroAddedToMap(const CGHeroInstance * hero)
  531. {
  532. assert(!vstd::contains(heroesOnMap, hero->id));
  533. heroesOnMap.push_back(hero->id);
  534. }
  535. void CMap::heroRemovedFromMap(const CGHeroInstance * hero)
  536. {
  537. assert(vstd::contains(heroesOnMap, hero->id));
  538. vstd::erase(heroesOnMap, hero->id);
  539. }
  540. void CMap::townAddedToMap(const CGTownInstance * town)
  541. {
  542. assert(!vstd::contains(towns, town->id));
  543. towns.push_back(town->id);
  544. }
  545. void CMap::townRemovedFromMap(const CGTownInstance * town)
  546. {
  547. assert(vstd::contains(towns, town->id));
  548. vstd::erase(towns, town->id);
  549. }
  550. bool CMap::isWaterMap() const
  551. {
  552. return waterMap;
  553. }
  554. bool CMap::calculateWaterContent()
  555. {
  556. size_t totalTiles = height * width * levels();
  557. size_t waterTiles = 0;
  558. for(auto tile = terrain.origin(); tile < (terrain.origin() + terrain.num_elements()); ++tile)
  559. {
  560. if (tile->isWater())
  561. {
  562. waterTiles++;
  563. }
  564. }
  565. if (waterTiles >= totalTiles / 100) //At least 1% of area is water
  566. {
  567. waterMap = true;
  568. }
  569. else
  570. {
  571. waterMap = false;
  572. }
  573. return waterMap;
  574. }
  575. void CMap::banWaterContent()
  576. {
  577. banWaterHeroes();
  578. banWaterArtifacts();
  579. banWaterSpells();
  580. banWaterSkills();
  581. }
  582. void CMap::banWaterSpells()
  583. {
  584. vstd::erase_if(allowedSpells, [&](SpellID spell)
  585. {
  586. return spell.toSpell()->onlyOnWaterMap && !isWaterMap();
  587. });
  588. }
  589. void CMap::banWaterArtifacts()
  590. {
  591. vstd::erase_if(allowedArtifact, [&](ArtifactID artifact)
  592. {
  593. return artifact.toArtifact()->onlyOnWaterMap && !isWaterMap();
  594. });
  595. }
  596. void CMap::banWaterSkills()
  597. {
  598. vstd::erase_if(allowedAbilities, [&](SecondarySkill skill)
  599. {
  600. return skill.toSkill()->onlyOnWaterMap && !isWaterMap();
  601. });
  602. }
  603. void CMap::banWaterHeroes()
  604. {
  605. vstd::erase_if(allowedHeroes, [&](HeroTypeID hero)
  606. {
  607. return hero.toHeroType()->onlyOnWaterMap && !isWaterMap();
  608. });
  609. vstd::erase_if(allowedHeroes, [&](HeroTypeID hero)
  610. {
  611. return hero.toHeroType()->onlyOnMapWithoutWater && isWaterMap();
  612. });
  613. }
  614. void CMap::banHero(const HeroTypeID & id)
  615. {
  616. if (!vstd::contains(allowedHeroes, id))
  617. logGlobal->warn("Attempt to ban hero %s, who is already not allowed", id.encode(id));
  618. allowedHeroes.erase(id);
  619. }
  620. void CMap::unbanHero(const HeroTypeID & id)
  621. {
  622. if (vstd::contains(allowedHeroes, id))
  623. logGlobal->warn("Attempt to unban hero %s, who is already allowed", id.encode(id));
  624. allowedHeroes.insert(id);
  625. }
  626. void CMap::initTerrain()
  627. {
  628. terrain.resize(boost::extents[levels()][width][height]);
  629. guardingCreaturePositions.resize(boost::extents[levels()][width][height]);
  630. }
  631. CMapEditManager * CMap::getEditManager()
  632. {
  633. if(!editManager) editManager = std::make_unique<CMapEditManager>(this);
  634. return editManager.get();
  635. }
  636. void CMap::reindexObjects()
  637. {
  638. // Only reindex at editor / RMG operations
  639. auto oldIndex = objects;
  640. std::sort(objects.begin(), objects.end(), [](const auto & lhs, const auto & rhs)
  641. {
  642. // Obstacles first, then visitable, at the end - removable
  643. if (!lhs->isVisitable() && rhs->isVisitable())
  644. return true;
  645. if (lhs->isVisitable() && !rhs->isVisitable())
  646. return false;
  647. // Special case for Windomill - draw on top of other objects
  648. if (lhs->ID != Obj::WINDMILL && rhs->ID == Obj::WINDMILL)
  649. return true;
  650. if (lhs->ID == Obj::WINDMILL && rhs->ID != Obj::WINDMILL)
  651. return false;
  652. if (!lhs->isRemovable() && rhs->isRemovable())
  653. return true;
  654. if (lhs->isRemovable() && !rhs->isRemovable())
  655. return false;
  656. return lhs->anchorPos().y < rhs->anchorPos().y;
  657. });
  658. // instanceNames don't change
  659. for (size_t i = 0; i < objects.size(); ++i)
  660. objects[i]->id = ObjectInstanceID(i);
  661. for (auto & town : towns)
  662. town = oldIndex.at(town.getNum())->id;
  663. for (auto & hero : heroesOnMap)
  664. hero = oldIndex.at(hero.getNum())->id;
  665. for(auto tile = terrain.origin(); tile < (terrain.origin() + terrain.num_elements()); ++tile)
  666. {
  667. for (auto & objectID : tile->blockingObjects)
  668. objectID = oldIndex.at(objectID.getNum())->id;
  669. for (auto & objectID : tile->visitableObjects)
  670. objectID = oldIndex.at(objectID.getNum())->id;
  671. }
  672. }
  673. const IGameSettings & CMap::getSettings() const
  674. {
  675. return *gameSettings;
  676. }
  677. void CMap::overrideGameSetting(EGameSettings option, const JsonNode & input)
  678. {
  679. return gameSettings->addOverride(option, input);
  680. }
  681. void CMap::overrideGameSettings(const JsonNode & input)
  682. {
  683. return gameSettings->loadOverrides(input);
  684. }
  685. CArtifactInstance * CMap::createScroll(const SpellID & spellId)
  686. {
  687. return createArtifact(ArtifactID::SPELL_SCROLL, spellId);
  688. }
  689. CArtifactInstance * CMap::createArtifactComponent(const ArtifactID & artId)
  690. {
  691. auto newArtifact = artId.hasValue() ?
  692. std::make_shared<CArtifactInstance>(cb, artId.toArtifact()):
  693. std::make_shared<CArtifactInstance>(cb);
  694. newArtifact->setId(ArtifactInstanceID(artInstances.size()));
  695. artInstances.push_back(newArtifact);
  696. return newArtifact.get();
  697. }
  698. CArtifactInstance * CMap::createArtifact(const ArtifactID & artID, const SpellID & spellId)
  699. {
  700. if(!artID.hasValue())
  701. throw std::runtime_error("Can't create empty artifact!");
  702. auto art = artID.toArtifact();
  703. auto artInst = createArtifactComponent(artID);
  704. if(art->isCombined() && !art->isFused())
  705. {
  706. for(const auto & part : art->getConstituents())
  707. artInst->addPart(createArtifact(part->getId(), spellId), ArtifactPosition::PRE_FIRST);
  708. }
  709. if(art->isGrowing())
  710. {
  711. auto bonus = std::make_shared<Bonus>();
  712. bonus->type = BonusType::ARTIFACT_GROWING;
  713. bonus->val = 0;
  714. artInst->addNewBonus(bonus);
  715. }
  716. if(art->isScroll())
  717. {
  718. artInst->addNewBonus(std::make_shared<Bonus>(BonusDuration::PERMANENT, BonusType::SPELL,
  719. BonusSource::ARTIFACT_INSTANCE, -1, BonusSourceID(ArtifactID(ArtifactID::SPELL_SCROLL)), BonusSubtypeID(spellId)));
  720. }
  721. if(art->isCharged())
  722. {
  723. auto bonus = std::make_shared<Bonus>();
  724. bonus->type = BonusType::ARTIFACT_CHARGE;
  725. bonus->val = 0;
  726. artInst->addNewBonus(bonus);
  727. artInst->addCharges(art->getDefaultStartCharges());
  728. }
  729. return artInst;
  730. }
  731. CArtifactInstance * CMap::getArtifactInstance(const ArtifactInstanceID & artifactID)
  732. {
  733. return artInstances.at(artifactID.getNum()).get();
  734. }
  735. const CArtifactInstance * CMap::getArtifactInstance(const ArtifactInstanceID & artifactID) const
  736. {
  737. return artInstances.at(artifactID.getNum()).get();
  738. }
  739. const std::vector<ObjectInstanceID> & CMap::getAllTowns() const
  740. {
  741. return towns;
  742. }
  743. const std::vector<ObjectInstanceID> & CMap::getHeroesOnMap() const
  744. {
  745. return heroesOnMap;
  746. }
  747. void CMap::addToHeroPool(std::shared_ptr<CGHeroInstance> hero)
  748. {
  749. assert(hero->getHeroTypeID().isValid());
  750. assert(!vstd::contains(heroesOnMap, hero->id));
  751. assert(heroesPool.at(hero->getHeroTypeID().getNum()) == nullptr);
  752. heroesPool.at(hero->getHeroTypeID().getNum()) = hero;
  753. if (!hero->id.hasValue())
  754. {
  755. // reserve ID for this new hero, if needed (but don't actually add it since hero is not present on map)
  756. hero->id = ObjectInstanceID(objects.size());
  757. objects.push_back(nullptr);
  758. }
  759. }
  760. CGHeroInstance * CMap::tryGetFromHeroPool(HeroTypeID hero)
  761. {
  762. return heroesPool.at(hero.getNum()).get();
  763. }
  764. std::shared_ptr<CGHeroInstance> CMap::tryTakeFromHeroPool(HeroTypeID hero)
  765. {
  766. auto result = heroesPool.at(hero.getNum());
  767. heroesPool.at(hero.getNum()) = nullptr;
  768. return result;
  769. }
  770. std::vector<HeroTypeID> CMap::getHeroesInPool() const
  771. {
  772. std::vector<HeroTypeID> result;
  773. for (const auto & hero : heroesPool)
  774. if (hero)
  775. result.push_back(hero->getHeroTypeID());
  776. return result;
  777. }
  778. CGObjectInstance * CMap::getObject(ObjectInstanceID obj)
  779. {
  780. return objects.at(obj).get();
  781. }
  782. const CGObjectInstance * CMap::getObject(ObjectInstanceID obj) const
  783. {
  784. return objects.at(obj).get();
  785. }
  786. void CMap::saveCompatibilityStoreAllocatedArtifactID()
  787. {
  788. if (!artInstances.empty())
  789. cb->gameState().saveCompatibilityLastAllocatedArtifactID = artInstances.back()->getId();
  790. }
  791. void CMap::saveCompatibilityAddMissingArtifact(std::shared_ptr<CArtifactInstance> artifact)
  792. {
  793. assert(artifact->getId().getNum() == artInstances.size());
  794. artInstances.push_back(artifact);
  795. }
  796. ObjectInstanceID CMap::allocateUniqueInstanceID()
  797. {
  798. objects.push_back(nullptr);
  799. return ObjectInstanceID(objects.size() - 1);
  800. }
  801. void CMap::parseUidCounter()
  802. {
  803. int max_index = -1;
  804. for (const auto& entry : instanceNames) {
  805. const std::string& key = entry.first;
  806. const size_t pos = key.find_last_of('_');
  807. // Validate underscore position
  808. if (pos == std::string::npos || pos + 1 >= key.size()) {
  809. logGlobal->error("Instance name '%s' is not valid.", key);
  810. continue;
  811. }
  812. const std::string index_part = key.substr(pos + 1);
  813. try {
  814. const int current_index = std::stoi(index_part);
  815. max_index = std::max(max_index, current_index);
  816. }
  817. catch (const std::invalid_argument&) {
  818. logGlobal->error("Instance name %s contains non-numeric index part: %s", key, index_part);
  819. }
  820. catch (const std::out_of_range&) {
  821. logGlobal->error("Instance name %s index part is overflow.", key);
  822. }
  823. }
  824. // Directly set uidCounter using simplified logic
  825. uidCounter = max_index + 1; // Automatically 0 when max_index = -1
  826. }
  827. VCMI_LIB_NAMESPACE_END