MapFormatH3M.cpp 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744
  1. /*
  2. * MapFormatH3M.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 "MapFormatH3M.h"
  12. #include "CMap.h"
  13. #include "MapReaderH3M.h"
  14. #include "MapFormatSettings.h"
  15. #include "../CCreatureHandler.h"
  16. #include "../texts/CGeneralTextHandler.h"
  17. #include "../CSkillHandler.h"
  18. #include "../CStopWatch.h"
  19. #include "../IGameSettings.h"
  20. #include "../RiverHandler.h"
  21. #include "../RoadHandler.h"
  22. #include "../TerrainHandler.h"
  23. #include "../GameLibrary.h"
  24. #include "../constants/StringConstants.h"
  25. #include "../entities/artifact/CArtHandler.h"
  26. #include "../entities/hero/CHeroHandler.h"
  27. #include "../filesystem/CBinaryReader.h"
  28. #include "../filesystem/Filesystem.h"
  29. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  30. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  31. #include "../mapObjectConstructors/CommonConstructors.h"
  32. #include "../mapObjects/CGCreature.h"
  33. #include "../mapObjects/CGResource.h"
  34. #include "../mapObjects/CQuest.h"
  35. #include "../mapObjects/MapObjects.h"
  36. #include "../mapObjects/ObjectTemplate.h"
  37. #include "../modding/ModScope.h"
  38. #include "../networkPacks/Component.h"
  39. #include "../networkPacks/ArtifactLocation.h"
  40. #include "../spells/CSpellHandler.h"
  41. #include "../texts/TextOperations.h"
  42. VCMI_LIB_NAMESPACE_BEGIN
  43. static std::string convertMapName(std::string input)
  44. {
  45. boost::algorithm::to_lower(input);
  46. boost::algorithm::trim(input);
  47. boost::algorithm::erase_all(input, ".");
  48. size_t slashPos = input.find_last_of('/');
  49. if(slashPos != std::string::npos)
  50. return input.substr(slashPos + 1);
  51. return input;
  52. }
  53. CMapLoaderH3M::CMapLoaderH3M(const std::string & mapName, const std::string & modName, const std::string & encodingName, CInputStream * stream)
  54. : map(nullptr)
  55. , reader(new MapReaderH3M(stream))
  56. , inputStream(stream)
  57. , mapName(convertMapName(mapName))
  58. , modName(modName)
  59. , fileEncoding(encodingName)
  60. {
  61. }
  62. //must be instantiated in .cpp file for access to complete types of all member fields
  63. CMapLoaderH3M::~CMapLoaderH3M() = default;
  64. std::unique_ptr<CMap> CMapLoaderH3M::loadMap(IGameInfoCallback * cb)
  65. {
  66. // Init map object by parsing the input buffer
  67. map = new CMap(cb);
  68. mapHeader = std::unique_ptr<CMapHeader>(dynamic_cast<CMapHeader *>(map));
  69. init();
  70. return std::unique_ptr<CMap>(dynamic_cast<CMap *>(mapHeader.release()));
  71. }
  72. std::unique_ptr<CMapHeader> CMapLoaderH3M::loadMapHeader()
  73. {
  74. // Read header
  75. mapHeader = std::make_unique<CMapHeader>();
  76. readHeader();
  77. return std::move(mapHeader);
  78. }
  79. void CMapLoaderH3M::init()
  80. {
  81. inputStream->seek(0);
  82. readHeader();
  83. readMapOptions();
  84. readAllowedArtifacts();
  85. readAllowedSpellsAbilities();
  86. readRumors();
  87. readPredefinedHeroes();
  88. readTerrain();
  89. readObjectTemplates();
  90. readObjects();
  91. readEvents();
  92. map->calculateGuardingGreaturePositions();
  93. afterRead();
  94. //map->banWaterContent(); //Not sure if force this for custom scenarios
  95. }
  96. void CMapLoaderH3M::readHeader()
  97. {
  98. // Map version
  99. mapHeader->version = static_cast<EMapFormat>(reader->readUInt32());
  100. if(mapHeader->version == EMapFormat::HOTA)
  101. {
  102. uint32_t hotaVersion = reader->readUInt32();
  103. features = MapFormatFeaturesH3M::find(mapHeader->version, hotaVersion);
  104. reader->setFormatLevel(features);
  105. if(features.levelHOTA8)
  106. {
  107. int hotaVersionMajor = reader->readUInt32();
  108. int hotaVersionMinor = reader->readUInt32();
  109. int hotaVersionPatch = reader->readUInt32();
  110. logGlobal->trace("Loading HotA map, version %d.%d.%d", hotaVersionMajor, hotaVersionMinor, hotaVersionPatch);
  111. }
  112. if(features.levelHOTA1)
  113. {
  114. bool isMirrorMap = reader->readBool();
  115. bool isArenaMap = reader->readBool();
  116. //TODO: HotA
  117. if (isMirrorMap)
  118. logGlobal->warn("Map '%s': Mirror maps are not yet supported!", mapName);
  119. if (isArenaMap)
  120. logGlobal->warn("Map '%s': Arena maps are not supported!", mapName);
  121. }
  122. if(features.levelHOTA2)
  123. {
  124. int32_t terrainTypesCount = reader->readUInt32();
  125. assert(features.terrainsCount == terrainTypesCount);
  126. if (features.terrainsCount != terrainTypesCount)
  127. logGlobal->warn("Map '%s': Expected %d terrains, but %d found!", mapName, features.terrainsCount, terrainTypesCount);
  128. }
  129. if(features.levelHOTA5)
  130. {
  131. int32_t townTypesCount = reader->readUInt32();
  132. int8_t allowedDifficultiesMask = reader->readInt8Checked(0, 31);
  133. assert(features.factionsCount == townTypesCount);
  134. if (features.factionsCount != townTypesCount)
  135. logGlobal->warn("Map '%s': Expected %d factions, but %d found!", mapName, features.factionsCount, townTypesCount);
  136. if (allowedDifficultiesMask != 0)
  137. logGlobal->warn("Map '%s': List of allowed difficulties (%d) is not implemented!", mapName, static_cast<int>(allowedDifficultiesMask));
  138. }
  139. if(features.levelHOTA7)
  140. {
  141. bool canHireDefeatedHeroes = reader->readBool();
  142. if (!canHireDefeatedHeroes)
  143. logGlobal->warn("Map '%s': Option to block hiring of defeated heroes is not implemented!", mapName);
  144. }
  145. if(features.levelHOTA8)
  146. {
  147. bool forceMatchingVersion = reader->readBool();
  148. if (forceMatchingVersion)
  149. logGlobal->warn("Map '%s': This map is forced to use specific hota version!", mapName);
  150. }
  151. }
  152. else
  153. {
  154. features = MapFormatFeaturesH3M::find(mapHeader->version, 0);
  155. reader->setFormatLevel(features);
  156. }
  157. if (!LIBRARY->mapFormat->isSupported(mapHeader->version))
  158. throw std::runtime_error("Unsupported map format! Format ID " + std::to_string(static_cast<int>(mapHeader->version)));
  159. const MapIdentifiersH3M & identifierMapper = LIBRARY->mapFormat->getMapping(mapHeader->version);
  160. reader->setIdentifierRemapper(identifierMapper);
  161. // Read map name, description, dimensions,...
  162. mapHeader->areAnyPlayers = reader->readBool();
  163. mapHeader->height = mapHeader->width = reader->readInt32();
  164. mapHeader->twoLevel = reader->readBool();
  165. mapHeader->name.appendTextID(readLocalizedString("header.name"));
  166. mapHeader->description.appendTextID(readLocalizedString("header.description"));
  167. mapHeader->author.appendRawString("");
  168. mapHeader->authorContact.appendRawString("");
  169. mapHeader->mapVersion.appendRawString("");
  170. mapHeader->creationDateTime = 0;
  171. mapHeader->difficulty = static_cast<EMapDifficulty>(reader->readInt8Checked(0, 4));
  172. if(features.levelAB)
  173. mapHeader->levelLimit = reader->readInt8Checked(0, std::min(100u, LIBRARY->heroh->maxSupportedLevel()));
  174. else
  175. mapHeader->levelLimit = 0;
  176. readPlayerInfo();
  177. readVictoryLossConditions();
  178. readTeamInfo();
  179. readAllowedHeroes();
  180. readDisposedHeroes();
  181. }
  182. void CMapLoaderH3M::readPlayerInfo()
  183. {
  184. for(int i = 0; i < mapHeader->players.size(); ++i)
  185. {
  186. auto & playerInfo = mapHeader->players[i];
  187. playerInfo.canHumanPlay = reader->readBool();
  188. playerInfo.canComputerPlay = reader->readBool();
  189. // If nobody can play with this player - skip loading of these properties
  190. if((!(playerInfo.canHumanPlay || playerInfo.canComputerPlay)))
  191. {
  192. if(features.levelROE)
  193. reader->skipUnused(6);
  194. if(features.levelAB)
  195. reader->skipUnused(6);
  196. if(features.levelSOD)
  197. reader->skipUnused(1);
  198. continue;
  199. }
  200. playerInfo.aiTactic = static_cast<EAiTactic>(reader->readInt8Checked(-1, 3));
  201. if(features.levelSOD)
  202. reader->skipUnused(1); //faction is selectable
  203. std::set<FactionID> allowedFactions;
  204. reader->readBitmaskFactions(allowedFactions, false);
  205. playerInfo.isFactionRandom = reader->readBool();
  206. const bool allFactionsAllowed = playerInfo.isFactionRandom && allowedFactions.size() == features.factionsCount;
  207. if(!allFactionsAllowed)
  208. {
  209. if (!allowedFactions.empty())
  210. playerInfo.allowedFactions = allowedFactions;
  211. else
  212. logGlobal->warn("Map '%s': Player %d has no allowed factions to play! Ignoring.", mapName, i);
  213. }
  214. playerInfo.hasMainTown = reader->readBool();
  215. if(playerInfo.hasMainTown)
  216. {
  217. if(features.levelAB)
  218. {
  219. playerInfo.generateHeroAtMainTown = reader->readBool();
  220. reader->skipUnused(1); // starting town type, unused
  221. }
  222. else
  223. {
  224. playerInfo.generateHeroAtMainTown = true;
  225. }
  226. playerInfo.posOfMainTown = reader->readInt3();
  227. }
  228. playerInfo.hasRandomHero = reader->readBool();
  229. playerInfo.mainCustomHeroId = reader->readHero();
  230. if(playerInfo.mainCustomHeroId != HeroTypeID::NONE)
  231. {
  232. playerInfo.mainCustomHeroPortrait = reader->readHeroPortrait();
  233. playerInfo.mainCustomHeroNameTextId = readLocalizedString(TextIdentifier("header", "player", i, "mainHeroName"));
  234. }
  235. if(features.levelAB)
  236. {
  237. reader->skipUnused(1); //TODO: check meaning?
  238. size_t heroCount = reader->readUInt32();
  239. for(size_t pp = 0; pp < heroCount; ++pp)
  240. {
  241. SHeroName vv;
  242. vv.heroId = reader->readHero();
  243. vv.heroName = readLocalizedString(TextIdentifier("header", "heroNames", vv.heroId.getNum()));
  244. playerInfo.heroesNames.push_back(vv);
  245. }
  246. }
  247. }
  248. }
  249. void CMapLoaderH3M::readVictoryLossConditions()
  250. {
  251. mapHeader->triggeredEvents.clear();
  252. mapHeader->victoryMessage.clear();
  253. mapHeader->defeatMessage.clear();
  254. auto vicCondition = static_cast<EVictoryConditionType>(reader->readInt8Checked(-1, 12));
  255. EventCondition victoryCondition(EventCondition::STANDARD_WIN);
  256. EventCondition defeatCondition(EventCondition::DAYS_WITHOUT_TOWN);
  257. defeatCondition.value = 7;
  258. TriggeredEvent standardVictory;
  259. standardVictory.effect.type = EventEffect::VICTORY;
  260. standardVictory.effect.toOtherMessage.appendTextID("core.genrltxt.5");
  261. standardVictory.identifier = "standardVictory";
  262. standardVictory.description.clear(); // TODO: display in quest window
  263. standardVictory.onFulfill.appendTextID("core.genrltxt.659");
  264. standardVictory.trigger = EventExpression(victoryCondition);
  265. TriggeredEvent standardDefeat;
  266. standardDefeat.effect.type = EventEffect::DEFEAT;
  267. standardDefeat.effect.toOtherMessage.appendTextID("core.genrltxt.8");
  268. standardDefeat.identifier = "standardDefeat";
  269. standardDefeat.description.clear(); // TODO: display in quest window
  270. standardDefeat.onFulfill.appendTextID("core.genrltxt.7");
  271. standardDefeat.trigger = EventExpression(defeatCondition);
  272. // Specific victory conditions
  273. if(vicCondition == EVictoryConditionType::WINSTANDARD)
  274. {
  275. // create normal condition
  276. mapHeader->triggeredEvents.push_back(standardVictory);
  277. mapHeader->victoryIconIndex = 11;
  278. mapHeader->victoryMessage.appendTextID("core.vcdesc.0");
  279. }
  280. else
  281. {
  282. TriggeredEvent specialVictory;
  283. specialVictory.effect.type = EventEffect::VICTORY;
  284. specialVictory.identifier = "specialVictory";
  285. specialVictory.description.clear(); // TODO: display in quest window
  286. mapHeader->victoryIconIndex = static_cast<ui16>(vicCondition);
  287. bool allowNormalVictory = reader->readBool();
  288. bool appliesToAI = reader->readBool();
  289. switch(vicCondition)
  290. {
  291. case EVictoryConditionType::ARTIFACT:
  292. {
  293. assert(allowNormalVictory == true); // not selectable in editor
  294. EventCondition cond(EventCondition::HAVE_ARTIFACT);
  295. cond.objectType = reader->readArtifact();
  296. specialVictory.effect.toOtherMessage.appendTextID("core.genrltxt.281");
  297. specialVictory.onFulfill.appendTextID("core.genrltxt.280");
  298. specialVictory.trigger = EventExpression(cond);
  299. mapHeader->victoryMessage.appendTextID("core.vcdesc.1");
  300. break;
  301. }
  302. case EVictoryConditionType::GATHERTROOP:
  303. {
  304. EventCondition cond(EventCondition::HAVE_CREATURES);
  305. cond.objectType = reader->readCreature();
  306. cond.value = reader->readInt32();
  307. specialVictory.effect.toOtherMessage.appendTextID("core.genrltxt.277");
  308. specialVictory.onFulfill.appendTextID("core.genrltxt.276");
  309. specialVictory.trigger = EventExpression(cond);
  310. mapHeader->victoryMessage.appendTextID("core.vcdesc.2");
  311. break;
  312. }
  313. case EVictoryConditionType::GATHERRESOURCE:
  314. {
  315. EventCondition cond(EventCondition::HAVE_RESOURCES);
  316. cond.objectType = reader->readGameResID();
  317. cond.value = reader->readInt32();
  318. specialVictory.effect.toOtherMessage.appendTextID("core.genrltxt.279");
  319. specialVictory.onFulfill.appendTextID("core.genrltxt.278");
  320. specialVictory.trigger = EventExpression(cond);
  321. mapHeader->victoryMessage.appendTextID("core.vcdesc.3");
  322. break;
  323. }
  324. case EVictoryConditionType::BUILDCITY:
  325. {
  326. assert(appliesToAI == true); // not selectable in editor
  327. EventExpression::OperatorAll oper;
  328. EventCondition cond(EventCondition::HAVE_BUILDING);
  329. cond.position = reader->readInt3();
  330. cond.objectType = BuildingID::HALL_LEVEL(reader->readInt8Checked(0,3) + 1);
  331. oper.expressions.emplace_back(cond);
  332. cond.objectType = BuildingID::FORT_LEVEL(reader->readInt8Checked(0, 2));
  333. oper.expressions.emplace_back(cond);
  334. specialVictory.effect.toOtherMessage.appendTextID("core.genrltxt.283");
  335. specialVictory.onFulfill.appendTextID("core.genrltxt.282");
  336. specialVictory.trigger = EventExpression(oper);
  337. mapHeader->victoryMessage.appendTextID("core.vcdesc.4");
  338. break;
  339. }
  340. case EVictoryConditionType::BUILDGRAIL:
  341. {
  342. assert(allowNormalVictory == true); // not selectable in editor
  343. assert(appliesToAI == true); // not selectable in editor
  344. EventCondition cond(EventCondition::HAVE_BUILDING);
  345. cond.objectType = BuildingID(BuildingID::GRAIL);
  346. cond.position = reader->readInt3();
  347. if(cond.position.z > 2)
  348. cond.position = int3(-1, -1, -1);
  349. specialVictory.effect.toOtherMessage.appendTextID("core.genrltxt.285");
  350. specialVictory.onFulfill.appendTextID("core.genrltxt.284");
  351. specialVictory.trigger = EventExpression(cond);
  352. mapHeader->victoryMessage.appendTextID("core.vcdesc.5");
  353. break;
  354. }
  355. case EVictoryConditionType::BEATHERO:
  356. {
  357. if (!allowNormalVictory)
  358. logGlobal->debug("Map %s: Has 'beat hero' as victory condition, but 'allow normal victory' not set. Ignoring", mapName);
  359. allowNormalVictory = true; // H3 behavior
  360. assert(appliesToAI == false); // not selectable in editor
  361. EventCondition cond(EventCondition::DESTROY);
  362. cond.objectType = MapObjectID(MapObjectID::HERO);
  363. cond.position = reader->readInt3();
  364. specialVictory.effect.toOtherMessage.appendTextID("core.genrltxt.253");
  365. specialVictory.onFulfill.appendTextID("core.genrltxt.252");
  366. specialVictory.trigger = EventExpression(cond);
  367. mapHeader->victoryMessage.appendTextID("core.vcdesc.6");
  368. break;
  369. }
  370. case EVictoryConditionType::CAPTURECITY:
  371. {
  372. EventCondition cond(EventCondition::CONTROL);
  373. cond.objectType = MapObjectID(MapObjectID::TOWN);
  374. cond.position = reader->readInt3();
  375. specialVictory.effect.toOtherMessage.appendTextID("core.genrltxt.250");
  376. specialVictory.onFulfill.appendTextID("core.genrltxt.249");
  377. specialVictory.trigger = EventExpression(cond);
  378. mapHeader->victoryMessage.appendTextID("core.vcdesc.7");
  379. break;
  380. }
  381. case EVictoryConditionType::BEATMONSTER:
  382. {
  383. assert(appliesToAI == true); // not selectable in editor
  384. EventCondition cond(EventCondition::DESTROY);
  385. cond.objectType = MapObjectID(MapObjectID::MONSTER);
  386. cond.position = reader->readInt3();
  387. specialVictory.effect.toOtherMessage.appendTextID("core.genrltxt.287");
  388. specialVictory.onFulfill.appendTextID("core.genrltxt.286");
  389. specialVictory.trigger = EventExpression(cond);
  390. mapHeader->victoryMessage.appendTextID("core.vcdesc.8");
  391. break;
  392. }
  393. case EVictoryConditionType::TAKEDWELLINGS:
  394. {
  395. EventExpression::OperatorAll oper;
  396. oper.expressions.emplace_back(EventCondition(EventCondition::CONTROL, 0, Obj(Obj::CREATURE_GENERATOR1)));
  397. oper.expressions.emplace_back(EventCondition(EventCondition::CONTROL, 0, Obj(Obj::CREATURE_GENERATOR4)));
  398. specialVictory.effect.toOtherMessage.appendTextID("core.genrltxt.289");
  399. specialVictory.onFulfill.appendTextID("core.genrltxt.288");
  400. specialVictory.trigger = EventExpression(oper);
  401. mapHeader->victoryMessage.appendTextID("core.vcdesc.9");
  402. break;
  403. }
  404. case EVictoryConditionType::TAKEMINES:
  405. {
  406. EventCondition cond(EventCondition::CONTROL);
  407. cond.objectType = MapObjectID(MapObjectID::MINE);
  408. specialVictory.effect.toOtherMessage.appendTextID("core.genrltxt.291");
  409. specialVictory.onFulfill.appendTextID("core.genrltxt.290");
  410. specialVictory.trigger = EventExpression(cond);
  411. mapHeader->victoryMessage.appendTextID("core.vcdesc.10");
  412. break;
  413. }
  414. case EVictoryConditionType::TRANSPORTITEM:
  415. {
  416. assert(allowNormalVictory == true); // not selectable in editor
  417. EventCondition cond(EventCondition::TRANSPORT);
  418. cond.objectType = reader->readArtifact8();
  419. cond.position = reader->readInt3();
  420. specialVictory.effect.toOtherMessage.appendTextID("core.genrltxt.293");
  421. specialVictory.onFulfill.appendTextID("core.genrltxt.292");
  422. specialVictory.trigger = EventExpression(cond);
  423. mapHeader->victoryMessage.appendTextID("core.vcdesc.11");
  424. break;
  425. }
  426. case EVictoryConditionType::HOTA_ELIMINATE_ALL_MONSTERS:
  427. {
  428. assert(appliesToAI == false); // not selectable in editor
  429. EventCondition cond(EventCondition::DESTROY);
  430. cond.objectType = MapObjectID(MapObjectID::MONSTER);
  431. specialVictory.effect.toOtherMessage.appendTextID("vcmi.map.victoryCondition.eliminateMonsters.toOthers");
  432. specialVictory.onFulfill.appendTextID("vcmi.map.victoryCondition.eliminateMonsters.toSelf");
  433. specialVictory.trigger = EventExpression(cond);
  434. mapHeader->victoryMessage.appendTextID("core.vcdesc.12");
  435. mapHeader->victoryIconIndex = 12;
  436. break;
  437. }
  438. case EVictoryConditionType::HOTA_SURVIVE_FOR_DAYS:
  439. {
  440. assert(appliesToAI == false); // not selectable in editor
  441. EventCondition cond(EventCondition::DAYS_PASSED);
  442. cond.value = reader->readUInt32();
  443. specialVictory.effect.toOtherMessage.appendTextID("vcmi.map.victoryCondition.daysPassed.toOthers");
  444. specialVictory.onFulfill.appendTextID("vcmi.map.victoryCondition.daysPassed.toSelf");
  445. specialVictory.trigger = EventExpression(cond);
  446. mapHeader->victoryMessage.appendTextID("core.vcdesc.13");
  447. mapHeader->victoryIconIndex = 13;
  448. break;
  449. }
  450. default:
  451. assert(0);
  452. }
  453. if(allowNormalVictory)
  454. {
  455. size_t playersOnMap = boost::range::count_if(
  456. mapHeader->players,
  457. [](const PlayerInfo & info)
  458. {
  459. return info.canAnyonePlay();
  460. }
  461. );
  462. if(playersOnMap == 1)
  463. {
  464. logGlobal->warn("Map %s: Only one player exists, but normal victory allowed!", mapName);
  465. allowNormalVictory = false; // makes sense? Not much. Works as H3? Yes!
  466. }
  467. }
  468. // if condition is human-only turn it into following construction: AllOf(human, condition)
  469. if(!appliesToAI)
  470. {
  471. EventExpression::OperatorAll oper;
  472. EventCondition notAI(EventCondition::IS_HUMAN);
  473. notAI.value = 1;
  474. oper.expressions.emplace_back(notAI);
  475. oper.expressions.push_back(specialVictory.trigger.get());
  476. specialVictory.trigger = EventExpression(oper);
  477. }
  478. // if normal victory allowed - add one more quest
  479. if(allowNormalVictory)
  480. {
  481. mapHeader->victoryMessage.appendRawString(" / ");
  482. mapHeader->victoryMessage.appendTextID("core.vcdesc.0");
  483. mapHeader->triggeredEvents.push_back(standardVictory);
  484. }
  485. mapHeader->triggeredEvents.push_back(specialVictory);
  486. }
  487. // Read loss conditions
  488. auto lossCond = static_cast<ELossConditionType>(reader->readInt8Checked(-1, 2));
  489. if(lossCond == ELossConditionType::LOSSSTANDARD)
  490. {
  491. mapHeader->defeatIconIndex = 3;
  492. mapHeader->defeatMessage.appendTextID("core.lcdesc.0");
  493. }
  494. else
  495. {
  496. TriggeredEvent specialDefeat;
  497. specialDefeat.effect.type = EventEffect::DEFEAT;
  498. specialDefeat.effect.toOtherMessage.appendTextID("core.genrltxt.5");
  499. specialDefeat.identifier = "specialDefeat";
  500. specialDefeat.description.clear(); // TODO: display in quest window
  501. mapHeader->defeatIconIndex = static_cast<ui16>(lossCond);
  502. switch(lossCond)
  503. {
  504. case ELossConditionType::LOSSCASTLE:
  505. {
  506. EventExpression::OperatorNone noneOf;
  507. EventCondition cond(EventCondition::CONTROL);
  508. cond.objectType = Obj(Obj::TOWN);
  509. cond.position = reader->readInt3();
  510. noneOf.expressions.emplace_back(cond);
  511. specialDefeat.onFulfill.appendTextID("core.genrltxt.251");
  512. specialDefeat.trigger = EventExpression(noneOf);
  513. mapHeader->defeatMessage.appendTextID("core.lcdesc.1");
  514. break;
  515. }
  516. case ELossConditionType::LOSSHERO:
  517. {
  518. EventExpression::OperatorNone noneOf;
  519. EventCondition cond(EventCondition::CONTROL);
  520. cond.objectType = Obj(Obj::HERO);
  521. cond.position = reader->readInt3();
  522. noneOf.expressions.emplace_back(cond);
  523. specialDefeat.onFulfill.appendTextID("core.genrltxt.253");
  524. specialDefeat.trigger = EventExpression(noneOf);
  525. mapHeader->defeatMessage.appendTextID("core.lcdesc.2");
  526. break;
  527. }
  528. case ELossConditionType::TIMEEXPIRES:
  529. {
  530. EventCondition cond(EventCondition::DAYS_PASSED);
  531. cond.value = reader->readUInt16();
  532. specialDefeat.onFulfill.appendTextID("core.genrltxt.254");
  533. specialDefeat.trigger = EventExpression(cond);
  534. mapHeader->defeatMessage.appendTextID("core.lcdesc.3");
  535. break;
  536. }
  537. }
  538. // turn simple loss condition into complete one that can be evaluated later:
  539. // - any of :
  540. // - days without town: 7
  541. // - all of:
  542. // - is human
  543. // - (expression)
  544. EventExpression::OperatorAll allOf;
  545. EventCondition isHuman(EventCondition::IS_HUMAN);
  546. isHuman.value = 1;
  547. allOf.expressions.emplace_back(isHuman);
  548. allOf.expressions.push_back(specialDefeat.trigger.get());
  549. specialDefeat.trigger = EventExpression(allOf);
  550. mapHeader->triggeredEvents.push_back(specialDefeat);
  551. }
  552. mapHeader->triggeredEvents.push_back(standardDefeat);
  553. }
  554. void CMapLoaderH3M::readTeamInfo()
  555. {
  556. mapHeader->howManyTeams = reader->readUInt8();
  557. if(mapHeader->howManyTeams > 0)
  558. {
  559. // Teams
  560. for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; ++i)
  561. mapHeader->players[i].team = TeamID(reader->readUInt8());
  562. }
  563. else
  564. {
  565. // No alliances
  566. for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
  567. if(mapHeader->players[i].canComputerPlay || mapHeader->players[i].canHumanPlay)
  568. mapHeader->players[i].team = TeamID(mapHeader->howManyTeams++);
  569. }
  570. }
  571. void CMapLoaderH3M::readAllowedHeroes()
  572. {
  573. mapHeader->allowedHeroes = LIBRARY->heroh->getDefaultAllowed();
  574. if(features.levelHOTA0)
  575. reader->readBitmaskHeroesSized(mapHeader->allowedHeroes, false);
  576. else
  577. reader->readBitmaskHeroes(mapHeader->allowedHeroes, false);
  578. if(features.levelAB)
  579. {
  580. size_t placeholdersQty = reader->readUInt32();
  581. for (size_t i = 0; i < placeholdersQty; ++i)
  582. {
  583. auto heroID = reader->readHero();
  584. mapHeader->reservedCampaignHeroes.insert(heroID);
  585. }
  586. }
  587. }
  588. void CMapLoaderH3M::readDisposedHeroes()
  589. {
  590. // Reading disposed heroes (20 bytes)
  591. if(features.levelSOD)
  592. {
  593. size_t disp = reader->readUInt8();
  594. mapHeader->disposedHeroes.resize(disp);
  595. for(size_t g = 0; g < disp; ++g)
  596. {
  597. mapHeader->disposedHeroes[g].heroId = reader->readHero();
  598. mapHeader->disposedHeroes[g].portrait = reader->readHeroPortrait();
  599. mapHeader->disposedHeroes[g].name = readLocalizedString(TextIdentifier("header", "heroes", mapHeader->disposedHeroes[g].heroId.getNum()));
  600. reader->readBitmaskPlayers(mapHeader->disposedHeroes[g].players, false);
  601. }
  602. }
  603. }
  604. void CMapLoaderH3M::readMapOptions()
  605. {
  606. //omitting NULLS
  607. reader->skipZero(31);
  608. if(features.levelHOTA0)
  609. {
  610. bool allowSpecialMonths = reader->readBool();
  611. map->overrideGameSetting(EGameSettings::CREATURES_ALLOW_RANDOM_SPECIAL_WEEKS, JsonNode(allowSpecialMonths));
  612. reader->skipZero(3);
  613. }
  614. if(features.levelHOTA1)
  615. {
  616. int32_t combinedArtifactsCount = reader->readInt32();
  617. int32_t combinedArtifactsBytes = (combinedArtifactsCount + 7) / 8;
  618. for (int i = 0; i < combinedArtifactsBytes; ++i)
  619. {
  620. uint8_t mask = reader->readUInt8();
  621. if (mask != 0)
  622. logGlobal->warn("Map '%s': Option to ban specific combined artifacts is not implemented!", mapName);
  623. }
  624. }
  625. if(features.levelHOTA3)
  626. {
  627. //TODO: HotA
  628. int32_t roundLimit = reader->readInt32();
  629. if(roundLimit != -1)
  630. logGlobal->warn("Map '%s': roundLimit of %d is not implemented!", mapName, roundLimit);
  631. }
  632. if(features.levelHOTA5)
  633. {
  634. for (int i = 0; i < PlayerColor::PLAYER_LIMIT_I; ++i)
  635. {
  636. // unconfirmed, but only remainig option according to changelog
  637. bool heroRecruitmentBlocked = reader->readBool();
  638. if (heroRecruitmentBlocked)
  639. logGlobal->warn("Map '%s': option to ban hero recruitment for %s is not implemented!!", mapName, PlayerColor(i).toString());
  640. }
  641. }
  642. }
  643. void CMapLoaderH3M::readAllowedArtifacts()
  644. {
  645. map->allowedArtifact = LIBRARY->arth->getDefaultAllowed();
  646. if(features.levelAB)
  647. {
  648. if(features.levelHOTA0)
  649. reader->readBitmaskArtifactsSized(map->allowedArtifact, true);
  650. else
  651. reader->readBitmaskArtifacts(map->allowedArtifact, true);
  652. }
  653. // ban combo artifacts
  654. if(!features.levelSOD)
  655. {
  656. for(auto const & artifact : LIBRARY->arth->objects)
  657. if(artifact->isCombined())
  658. map->allowedArtifact.erase(artifact->getId());
  659. }
  660. if(!features.levelAB)
  661. {
  662. map->allowedArtifact.erase(ArtifactID::VIAL_OF_DRAGON_BLOOD);
  663. map->allowedArtifact.erase(ArtifactID::ARMAGEDDONS_BLADE);
  664. }
  665. // Messy, but needed
  666. for(TriggeredEvent & event : map->triggeredEvents)
  667. {
  668. auto patcher = [&](EventCondition cond) -> EventExpression::Variant
  669. {
  670. if(cond.condition == EventCondition::HAVE_ARTIFACT || cond.condition == EventCondition::TRANSPORT)
  671. {
  672. map->allowedArtifact.erase(cond.objectType.as<ArtifactID>());
  673. }
  674. return cond;
  675. };
  676. event.trigger = event.trigger.morph(patcher);
  677. }
  678. }
  679. void CMapLoaderH3M::readAllowedSpellsAbilities()
  680. {
  681. map->allowedSpells = LIBRARY->spellh->getDefaultAllowed();
  682. map->allowedAbilities = LIBRARY->skillh->getDefaultAllowed();
  683. if(features.levelSOD)
  684. {
  685. reader->readBitmaskSpells(map->allowedSpells, true);
  686. reader->readBitmaskSkills(map->allowedAbilities, true);
  687. }
  688. }
  689. void CMapLoaderH3M::readRumors()
  690. {
  691. size_t rumorsCount = reader->readUInt32();
  692. assert(rumorsCount < 1000); // sanity check
  693. for(size_t it = 0; it < rumorsCount; it++)
  694. {
  695. Rumor ourRumor;
  696. ourRumor.name = readBasicString();
  697. ourRumor.text.appendTextID(readLocalizedString(TextIdentifier("header", "rumor", it, "text")));
  698. map->rumors.push_back(ourRumor);
  699. }
  700. }
  701. void CMapLoaderH3M::readPredefinedHeroes()
  702. {
  703. if(!features.levelSOD)
  704. return;
  705. uint32_t heroesCount = features.heroesCount;
  706. if(features.levelHOTA0)
  707. heroesCount = reader->readUInt32();
  708. assert(heroesCount <= features.heroesCount);
  709. for(int heroID = 0; heroID < heroesCount; heroID++)
  710. {
  711. bool custom = reader->readBool();
  712. if(!custom)
  713. continue;
  714. auto hero = std::make_shared<CGHeroInstance>(map->cb);
  715. hero->ID = Obj::HERO;
  716. hero->subID = heroID;
  717. bool hasExp = reader->readBool();
  718. if(hasExp)
  719. {
  720. hero->exp = reader->readUInt32();
  721. }
  722. else
  723. {
  724. hero->exp = 0;
  725. }
  726. bool hasSecSkills = reader->readBool();
  727. if(hasSecSkills)
  728. {
  729. uint32_t howMany = reader->readUInt32();
  730. hero->secSkills.resize(howMany);
  731. for(int yy = 0; yy < howMany; ++yy)
  732. {
  733. hero->secSkills[yy].first = reader->readSkill();
  734. hero->secSkills[yy].second = reader->readInt8Checked(1,3);
  735. }
  736. }
  737. loadArtifactsOfHero(hero.get());
  738. bool hasCustomBio = reader->readBool();
  739. if(hasCustomBio)
  740. hero->biographyCustomTextId = readLocalizedString(TextIdentifier("heroes", heroID, "biography"));
  741. // 0xFF is default, 00 male, 01 female
  742. hero->gender = static_cast<EHeroGender>(reader->readInt8Checked(-1, 1));
  743. assert(hero->gender == EHeroGender::MALE || hero->gender == EHeroGender::FEMALE || hero->gender == EHeroGender::DEFAULT);
  744. bool hasCustomSpells = reader->readBool();
  745. if(hasCustomSpells)
  746. reader->readBitmaskSpells(hero->spells, false);
  747. bool hasCustomPrimSkills = reader->readBool();
  748. if(hasCustomPrimSkills)
  749. {
  750. for(int skillID = 0; skillID < GameConstants::PRIMARY_SKILLS; skillID++)
  751. {
  752. hero->pushPrimSkill(static_cast<PrimarySkill>(skillID), reader->readUInt8());
  753. }
  754. }
  755. map->addToHeroPool(hero);
  756. logGlobal->debug("Map '%s': Hero predefined in map: %s", mapName, hero->getHeroType()->getJsonKey());
  757. }
  758. if(features.levelHOTA5)
  759. {
  760. for(int heroID = 0; heroID < heroesCount; heroID++)
  761. {
  762. bool alwaysAddSkills = reader->readBool(); // prevent heroes from receiving additional random secondary skills at the start of the map if they are not of the first level
  763. bool cannotGainXP = reader->readBool();
  764. int32_t level = reader->readInt32(); // Needs investigation how this interacts with usual setting of level via experience
  765. assert(level > 0);
  766. if (!alwaysAddSkills)
  767. logGlobal->warn("Map '%s': Option to prevent hero %d from gaining skills on map start is not implemented!", mapName, heroID);
  768. if (cannotGainXP)
  769. logGlobal->warn("Map '%s': Option to prevent hero %d from receiveing experience is not implemented!", mapName, heroID);
  770. if (level > 1)
  771. logGlobal->warn("Map '%s': Option to set level of hero %d to %d is not implemented!", mapName, heroID, level);
  772. }
  773. }
  774. }
  775. void CMapLoaderH3M::loadArtifactsOfHero(CGHeroInstance * hero)
  776. {
  777. bool hasArtSet = reader->readBool();
  778. // True if artifact set is not default (hero has some artifacts)
  779. if(!hasArtSet)
  780. return;
  781. // Workaround - if hero has customized artifacts game should not attempt to add spellbook based on hero type
  782. hero->spells.insert(SpellID::SPELLBOOK_PRESET);
  783. if(!hero->artifactsWorn.empty() || !hero->artifactsInBackpack.empty())
  784. {
  785. logGlobal->debug("Hero %d at %s has set artifacts twice (in map properties and on adventure map instance). Using the latter set...", hero->getHeroTypeID().getNum(), hero->anchorPos().toString());
  786. hero->artifactsInBackpack.clear();
  787. while(!hero->artifactsWorn.empty())
  788. hero->removeArtifact(hero->artifactsWorn.begin()->first);
  789. }
  790. for(int i = 0; i < features.artifactSlotsCount; i++)
  791. loadArtifactToSlot(hero, i);
  792. // bag artifacts
  793. // number of artifacts in hero's bag
  794. size_t amount = reader->readUInt16();
  795. for(size_t i = 0; i < amount; ++i)
  796. {
  797. loadArtifactToSlot(hero, ArtifactPosition::BACKPACK_START + static_cast<int>(hero->artifactsInBackpack.size()));
  798. }
  799. }
  800. bool CMapLoaderH3M::loadArtifactToSlot(CGHeroInstance * hero, int slot)
  801. {
  802. ArtifactID artifactID = reader->readArtifact();
  803. SpellID scrollSpell = SpellID::NONE;
  804. if (features.levelHOTA5)
  805. scrollSpell = reader->readSpell16();
  806. if(artifactID == ArtifactID::NONE)
  807. return false;
  808. const Artifact * art = artifactID.toEntity(LIBRARY);
  809. if(!art)
  810. {
  811. logGlobal->warn("Map '%s': Invalid artifact in hero's backpack, ignoring...", mapName);
  812. return false;
  813. }
  814. if(art->isBig() && slot >= ArtifactPosition::BACKPACK_START)
  815. {
  816. logGlobal->warn("Map '%s': A big artifact (war machine) in hero's backpack, ignoring...", mapName);
  817. return false;
  818. }
  819. // H3 bug workaround - Enemy hero on 3rd scenario of Good1.h3c campaign ("Long Live The Queen")
  820. // He has Shackles of War (normally - MISC slot artifact) in LEFT_HAND slot set in editor
  821. // Artifact seems to be missing in game, so skip artifacts that don't fit target slot
  822. if(ArtifactID(artifactID).toArtifact()->canBePutAt(hero, ArtifactPosition(slot)))
  823. {
  824. auto * artifact = map->createArtifact(artifactID, scrollSpell);
  825. map->putArtifactInstance(*hero, artifact->getId(), slot);
  826. }
  827. else
  828. {
  829. logGlobal->warn("Map '%s': Artifact '%s' can't be put at the slot %d", mapName, ArtifactID(artifactID).toArtifact()->getNameTranslated(), slot);
  830. return false;
  831. }
  832. return true;
  833. }
  834. void CMapLoaderH3M::readTerrain()
  835. {
  836. map->initTerrain();
  837. // Read terrain
  838. int3 pos;
  839. for(pos.z = 0; pos.z < map->levels(); ++pos.z)
  840. {
  841. //OH3 format is [z][y][x]
  842. for(pos.y = 0; pos.y < map->height; pos.y++)
  843. {
  844. for(pos.x = 0; pos.x < map->width; pos.x++)
  845. {
  846. auto & tile = map->getTile(pos);
  847. tile.terrainType = reader->readTerrain();
  848. tile.terView = reader->readUInt8();
  849. tile.riverType = reader->readRiver();
  850. tile.riverDir = reader->readUInt8();
  851. tile.roadType = reader->readRoad();
  852. tile.roadDir = reader->readUInt8();
  853. tile.extTileFlags = reader->readUInt8();
  854. }
  855. }
  856. }
  857. map->calculateWaterContent();
  858. }
  859. void CMapLoaderH3M::readObjectTemplates()
  860. {
  861. uint32_t defAmount = reader->readUInt32();
  862. originalTemplates.reserve(defAmount);
  863. remappedTemplates.reserve(defAmount);
  864. // Read custom defs
  865. for(int defID = 0; defID < defAmount; ++defID)
  866. {
  867. auto tmpl = reader->readObjectTemplate();
  868. originalTemplates.push_back(tmpl);
  869. auto remapped = std::make_shared<ObjectTemplate>(*tmpl);
  870. reader->remapTemplate(*remapped);
  871. remappedTemplates.push_back(remapped);
  872. if (!CResourceHandler::get()->existsResource(remapped->animationFile.addPrefix("SPRITES/")))
  873. logMod->warn("Template animation %s of type (%d %d) is missing!", remapped->animationFile.getOriginalName(), remapped->id, remapped->subid );
  874. }
  875. }
  876. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readEvent(const int3 & mapPosition, const ObjectInstanceID & idToBeGiven)
  877. {
  878. auto object = std::make_shared<CGEvent>(map->cb);
  879. readBoxContent(object.get(), mapPosition, idToBeGiven);
  880. reader->readBitmaskPlayers(object->availableFor, false);
  881. object->computerActivate = reader->readBool();
  882. object->removeAfterVisit = reader->readBool();
  883. reader->skipZero(4);
  884. if(features.levelHOTA3)
  885. object->humanActivate = reader->readBool();
  886. else
  887. object->humanActivate = true;
  888. readBoxHotaContent(object.get(), mapPosition, idToBeGiven);
  889. return object;
  890. }
  891. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readPandora(const int3 & mapPosition, const ObjectInstanceID & idToBeGiven)
  892. {
  893. auto object = std::make_shared<CGPandoraBox>(map->cb);
  894. readBoxContent(object.get(), mapPosition, idToBeGiven);
  895. if(features.levelHOTA5)
  896. reader->skipZero(1); // Unknown value, always 0 so far
  897. readBoxHotaContent(object.get(), mapPosition, idToBeGiven);
  898. return object;
  899. }
  900. void CMapLoaderH3M::readBoxContent(CGPandoraBox * object, const int3 & mapPosition, const ObjectInstanceID & idToBeGiven)
  901. {
  902. readMessageAndGuards(object->message, object, mapPosition, idToBeGiven);
  903. Rewardable::VisitInfo vinfo;
  904. auto & reward = vinfo.reward;
  905. reward.heroExperience = reader->readUInt32();
  906. reward.manaDiff = reader->readInt32();
  907. if(auto val = reader->readInt8Checked(-3, 3))
  908. reward.heroBonuses.push_back(std::make_shared<Bonus>(BonusDuration::ONE_BATTLE, BonusType::MORALE, BonusSource::OBJECT_INSTANCE, val, BonusSourceID(idToBeGiven)));
  909. if(auto val = reader->readInt8Checked(-3, 3))
  910. reward.heroBonuses.push_back(std::make_shared<Bonus>(BonusDuration::ONE_BATTLE, BonusType::LUCK, BonusSource::OBJECT_INSTANCE, val, BonusSourceID(idToBeGiven)));
  911. reader->readResources(reward.resources);
  912. for(int x = 0; x < GameConstants::PRIMARY_SKILLS; ++x)
  913. reward.primary.at(x) = reader->readUInt8();
  914. size_t gabn = reader->readUInt8(); //number of gained abilities
  915. for(size_t oo = 0; oo < gabn; ++oo)
  916. {
  917. auto rId = reader->readSkill();
  918. auto rVal = reader->readInt8Checked(1,3);
  919. reward.secondary[rId] = rVal;
  920. }
  921. size_t gart = reader->readUInt8(); //number of gained artifacts
  922. for(size_t oo = 0; oo < gart; ++oo)
  923. {
  924. ArtifactID grantedArtifact = reader->readArtifact();
  925. if (features.levelHOTA5)
  926. {
  927. SpellID scrollSpell = reader->readSpell16();
  928. if (grantedArtifact == ArtifactID::SPELL_SCROLL)
  929. reward.grantedScrolls.push_back(scrollSpell);
  930. }
  931. else
  932. reward.grantedArtifacts.push_back(grantedArtifact);
  933. }
  934. size_t gspel = reader->readUInt8(); //number of gained spells
  935. for(size_t oo = 0; oo < gspel; ++oo)
  936. reward.spells.push_back(reader->readSpell());
  937. size_t gcre = reader->readUInt8(); //number of gained creatures
  938. for(size_t oo = 0; oo < gcre; ++oo)
  939. {
  940. auto rId = reader->readCreature();
  941. auto rVal = reader->readUInt16();
  942. reward.creatures.emplace_back(rId, rVal);
  943. }
  944. vinfo.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  945. object->configuration.info.push_back(vinfo);
  946. reader->skipZero(8);
  947. }
  948. void CMapLoaderH3M::readBoxHotaContent(CGPandoraBox * object, const int3 & mapPosition, const ObjectInstanceID & idToBeGiven)
  949. {
  950. if(features.levelHOTA5)
  951. {
  952. int32_t movementMode = reader->readInt32(); // Give, Take, Nullify, Set, Replenish
  953. int32_t movementAmount = reader->readInt32();
  954. assert(movementMode >= 0 && movementMode <= 4);
  955. if (movementMode != 0 || movementAmount != 0)
  956. logGlobal->warn("Map '%s': Event/Pandora %s option to modify (mode %d) movement points by %d is not implemented!", mapName, mapPosition.toString(), movementMode, movementAmount);
  957. }
  958. if(features.levelHOTA6)
  959. {
  960. int32_t allowedDifficultiesMask = reader->readInt32();
  961. assert(allowedDifficultiesMask > 0 && allowedDifficultiesMask < 32);
  962. if (allowedDifficultiesMask != 31)
  963. logGlobal->warn("Map '%s': Event/Pandora %s availability by difficulty (mode %d) is not implemented!", mapName, mapPosition.toString(), allowedDifficultiesMask);
  964. }
  965. }
  966. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readMonster(const int3 & mapPosition, const ObjectInstanceID & objectInstanceID)
  967. {
  968. auto object = std::make_shared<CGCreature>(map->cb);
  969. object->id = objectInstanceID;
  970. if(features.levelAB)
  971. {
  972. object->identifier = reader->readUInt32();
  973. questIdentifierToId[object->identifier] = objectInstanceID;
  974. }
  975. auto hlp = std::make_unique<CStackInstance>(map->cb);
  976. hlp->setCount(reader->readUInt16());
  977. //type will be set during initialization
  978. object->putStack(SlotID(0), std::move(hlp));
  979. //TODO: 0-4 is h3 range. 5 is hota extension for exact aggression?
  980. object->character = reader->readInt8Checked(0, 5);
  981. bool hasMessage = reader->readBool();
  982. if(hasMessage)
  983. {
  984. object->message.appendTextID(readLocalizedString(TextIdentifier("monster", mapPosition.x, mapPosition.y, mapPosition.z, "message")));
  985. reader->readResources(object->resources);
  986. object->gainedArtifact = reader->readArtifact();
  987. }
  988. object->neverFlees = reader->readBool();
  989. object->notGrowingTeam = reader->readBool();
  990. reader->skipZero(2);
  991. if(features.levelHOTA3)
  992. {
  993. //TODO: HotA
  994. int32_t aggressionExact = reader->readInt32(); // -1 = default, 1-10 = possible values range
  995. bool joinOnlyForMoney = reader->readBool(); // if true, monsters will only join for money
  996. int32_t joinPercent = reader->readInt32(); // 100 = default, percent of monsters that will join on successful aggression check
  997. int32_t upgradedStack = reader->readInt32(); // Presence of upgraded stack, -1 = random, 0 = never, 1 = always
  998. int32_t stacksCount = reader->readInt32(); // TODO: check possible values. How many creature stacks will be present on battlefield, -1 = default
  999. if(aggressionExact != -1 || joinOnlyForMoney || joinPercent != 100 || upgradedStack != -1 || stacksCount != -1)
  1000. logGlobal->warn(
  1001. "Map '%s': Wandering monsters %s settings %d %d %d %d %d are not implemented!",
  1002. mapName,
  1003. mapPosition.toString(),
  1004. aggressionExact,
  1005. int(joinOnlyForMoney),
  1006. joinPercent,
  1007. upgradedStack,
  1008. stacksCount
  1009. );
  1010. }
  1011. if (features.levelHOTA5)
  1012. {
  1013. bool sizeByValue = reader->readBool();//FIXME: double-check this flag effect
  1014. int32_t targetValue = reader->readInt32();
  1015. if (sizeByValue || targetValue)
  1016. logGlobal->warn( "Map '%s': Wandering monsters %s option to set unit size to %d (%d) AI value is not implemented!", mapName, mapPosition.toString(), targetValue, sizeByValue);
  1017. }
  1018. return object;
  1019. }
  1020. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readSign(const int3 & mapPosition)
  1021. {
  1022. auto object = std::make_shared<CGSignBottle>(map->cb);
  1023. object->message.appendTextID(readLocalizedString(TextIdentifier("sign", mapPosition.x, mapPosition.y, mapPosition.z, "message")));
  1024. reader->skipZero(4);
  1025. return object;
  1026. }
  1027. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readWitchHut(const int3 & position, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1028. {
  1029. auto object = readGeneric(position, objectTemplate);
  1030. auto rewardable = std::dynamic_pointer_cast<CRewardableObject>(object);
  1031. // AB and later maps have allowed abilities defined in H3M
  1032. if(features.levelAB)
  1033. {
  1034. std::set<SecondarySkill> allowedAbilities;
  1035. reader->readBitmaskSkills(allowedAbilities, false);
  1036. if (rewardable)
  1037. {
  1038. if(allowedAbilities.size() != 1)
  1039. {
  1040. auto defaultAllowed = LIBRARY->skillh->getDefaultAllowed();
  1041. for(int skillID = features.skillsCount; skillID < defaultAllowed.size(); ++skillID)
  1042. if(defaultAllowed.count(skillID))
  1043. allowedAbilities.insert(SecondarySkill(skillID));
  1044. }
  1045. JsonNode variable;
  1046. if (allowedAbilities.size() == 1)
  1047. {
  1048. variable.String() = LIBRARY->skills()->getById(*allowedAbilities.begin())->getJsonKey();
  1049. }
  1050. else
  1051. {
  1052. JsonVector anyOfList;
  1053. for (auto const & skill : allowedAbilities)
  1054. {
  1055. JsonNode entry;
  1056. entry.String() = LIBRARY->skills()->getById(skill)->getJsonKey();
  1057. anyOfList.push_back(entry);
  1058. }
  1059. variable["anyOf"].Vector() = anyOfList;
  1060. }
  1061. variable.setModScope(ModScope::scopeGame()); // list may include skills from all mods
  1062. rewardable->configuration.presetVariable("secondarySkill", "gainedSkill", variable);
  1063. }
  1064. else
  1065. {
  1066. logGlobal->warn("Failed to set allowed secondary skills to a Witch Hut! Object is not rewardable!");
  1067. }
  1068. }
  1069. return object;
  1070. }
  1071. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readScholar(const int3 & position, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1072. {
  1073. enum class ScholarBonusType : int8_t {
  1074. RANDOM = -1,
  1075. PRIM_SKILL = 0,
  1076. SECONDARY_SKILL = 1,
  1077. SPELL = 2,
  1078. };
  1079. auto object = readGeneric(position, objectTemplate);
  1080. auto rewardable = std::dynamic_pointer_cast<CRewardableObject>(object);
  1081. uint8_t bonusTypeRaw = reader->readInt8Checked(-1, 2);
  1082. auto bonusType = static_cast<ScholarBonusType>(bonusTypeRaw);
  1083. auto bonusID = reader->readUInt8();
  1084. if (rewardable)
  1085. {
  1086. switch (bonusType)
  1087. {
  1088. case ScholarBonusType::PRIM_SKILL:
  1089. {
  1090. JsonNode variable;
  1091. JsonNode dice;
  1092. variable.String() = NPrimarySkill::names[bonusID];
  1093. variable.setModScope(ModScope::scopeGame());
  1094. dice.Integer() = 80;
  1095. rewardable->configuration.presetVariable("primarySkill", "gainedStat", variable);
  1096. rewardable->configuration.presetVariable("dice", "0", dice);
  1097. break;
  1098. }
  1099. case ScholarBonusType::SECONDARY_SKILL:
  1100. {
  1101. JsonNode variable;
  1102. JsonNode dice;
  1103. variable.String() = LIBRARY->skills()->getByIndex(bonusID)->getJsonKey();
  1104. variable.setModScope(ModScope::scopeGame());
  1105. dice.Integer() = 50;
  1106. rewardable->configuration.presetVariable("secondarySkill", "gainedSkill", variable);
  1107. rewardable->configuration.presetVariable("dice", "0", dice);
  1108. break;
  1109. }
  1110. case ScholarBonusType::SPELL:
  1111. {
  1112. JsonNode variable;
  1113. JsonNode dice;
  1114. variable.String() = LIBRARY->spells()->getByIndex(bonusID)->getJsonKey();
  1115. variable.setModScope(ModScope::scopeGame());
  1116. dice.Integer() = 20;
  1117. rewardable->configuration.presetVariable("spell", "gainedSpell", variable);
  1118. rewardable->configuration.presetVariable("dice", "0", dice);
  1119. break;
  1120. }
  1121. case ScholarBonusType::RANDOM:
  1122. break;// No-op
  1123. default:
  1124. logGlobal->warn("Map '%s': Invalid Scholar settings! Ignoring...", mapName);
  1125. }
  1126. }
  1127. else
  1128. {
  1129. logGlobal->warn("Failed to set reward parameters for a Scholar! Object is not rewardable!");
  1130. }
  1131. reader->skipZero(6);
  1132. return object;
  1133. }
  1134. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readGarrison(const int3 & mapPosition, const ObjectInstanceID & idToBeGiven)
  1135. {
  1136. auto object = std::make_shared<CGGarrison>(map->cb);
  1137. setOwnerAndValidate(mapPosition, object.get(), reader->readPlayer32());
  1138. readCreatureSet(object.get(), idToBeGiven);
  1139. if(features.levelAB)
  1140. object->removableUnits = reader->readBool();
  1141. else
  1142. object->removableUnits = true;
  1143. reader->skipZero(8);
  1144. return object;
  1145. }
  1146. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readArtifact(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate, const ObjectInstanceID & idToBeGiven)
  1147. {
  1148. ArtifactID artID = ArtifactID::NONE; //random, set later
  1149. auto object = std::make_shared<CGArtifact>(map->cb);
  1150. readMessageAndGuards(object->message, object.get(), mapPosition, idToBeGiven);
  1151. //specific artifact
  1152. if(objectTemplate->id == Obj::ARTIFACT)
  1153. artID = ArtifactID(objectTemplate->subid);
  1154. if(features.levelHOTA5)
  1155. {
  1156. uint32_t pickupMode = reader->readUInt32();
  1157. uint8_t pickupFlags = reader->readUInt8();
  1158. assert(pickupMode == 0 || pickupMode == 1 || pickupMode == 2); // DISABLED, RANDOM, CUSTOM
  1159. if (pickupMode != 0)
  1160. logGlobal->warn("Map '%s': Artifact %s: not implemented pickup mode %d (flags: %d)", mapName, mapPosition.toString(), pickupMode, static_cast<int>(pickupFlags));
  1161. }
  1162. if (artID.hasValue())
  1163. object->setArtifactInstance(map->createArtifact(artID, SpellID::NONE));
  1164. // else - random, will be initialized later
  1165. return object;
  1166. }
  1167. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readScroll(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate, const ObjectInstanceID & idToBeGiven)
  1168. {
  1169. auto object = std::make_shared<CGArtifact>(map->cb);
  1170. readMessageAndGuards(object->message, object.get(), mapPosition, idToBeGiven);
  1171. SpellID spellID = reader->readSpell32();
  1172. object->setArtifactInstance(map->createArtifact(ArtifactID::SPELL_SCROLL, spellID.getNum()));
  1173. return object;
  1174. }
  1175. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readResource(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate, const ObjectInstanceID & idToBeGiven)
  1176. {
  1177. auto object = std::make_shared<CGResource>(map->cb);
  1178. readMessageAndGuards(object->message, object.get(), mapPosition, idToBeGiven);
  1179. object->amount = reader->readUInt32();
  1180. if (objectTemplate->id != Obj::RANDOM_RESOURCE)
  1181. {
  1182. const auto & baseHandler = LIBRARY->objtypeh->getHandlerFor(objectTemplate->id, objectTemplate->subid);
  1183. const auto & ourHandler = std::dynamic_pointer_cast<ResourceInstanceConstructor>(baseHandler);
  1184. object->amount *= ourHandler->getAmountMultiplier();
  1185. }
  1186. reader->skipZero(4);
  1187. return object;
  1188. }
  1189. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readMine(const int3 & mapPosition)
  1190. {
  1191. auto object = std::make_shared<CGMine>(map->cb);
  1192. setOwnerAndValidate(mapPosition, object.get(), reader->readPlayer32());
  1193. return object;
  1194. }
  1195. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readAbandonedMine(const int3 & mapPosition)
  1196. {
  1197. auto object = std::make_shared<CGMine>(map->cb);
  1198. object->setOwner(PlayerColor::NEUTRAL);
  1199. reader->readBitmaskResources(object->abandonedMineResources, false);
  1200. if(features.levelHOTA5)
  1201. {
  1202. bool customGuards = reader->readBool();
  1203. CreatureID guardsUnit = reader->readCreature32();
  1204. int32_t guardsMin = reader->readInt32();
  1205. int32_t guardsMax = reader->readInt32();
  1206. if (customGuards)
  1207. {
  1208. assert(guardsMin <= guardsMax);
  1209. assert(guardsUnit.hasValue());
  1210. logGlobal->warn("Map '%s': Abandoned Mine %s: not implemented guards of %d-%d %s", mapName, mapPosition.toString(), guardsMin, guardsMax, guardsUnit.toEntity(LIBRARY)->getJsonKey());
  1211. }
  1212. }
  1213. return object;
  1214. }
  1215. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readDwelling(const int3 & position)
  1216. {
  1217. auto object = std::make_shared<CGDwelling>(map->cb);
  1218. setOwnerAndValidate(position, object.get(), reader->readPlayer32());
  1219. return object;
  1220. }
  1221. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readDwellingRandom(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1222. {
  1223. auto object = std::make_shared<CGDwelling>(map->cb);
  1224. setOwnerAndValidate(mapPosition, object.get(), reader->readPlayer32());
  1225. object->randomizationInfo = CGDwellingRandomizationInfo();
  1226. bool hasFactionInfo = objectTemplate->id == Obj::RANDOM_DWELLING || objectTemplate->id == Obj::RANDOM_DWELLING_LVL;
  1227. bool hasLevelInfo = objectTemplate->id == Obj::RANDOM_DWELLING || objectTemplate->id == Obj::RANDOM_DWELLING_FACTION;
  1228. if (hasFactionInfo)
  1229. {
  1230. object->randomizationInfo->identifier = reader->readUInt32();
  1231. if(object->randomizationInfo->identifier == 0)
  1232. reader->readBitmaskFactions(object->randomizationInfo->allowedFactions, false);
  1233. }
  1234. else
  1235. object->randomizationInfo->allowedFactions.insert(FactionID(objectTemplate->subid));
  1236. if(hasLevelInfo)
  1237. {
  1238. object->randomizationInfo->minLevel = std::max(reader->readUInt8(), static_cast<ui8>(0)) + 1;
  1239. object->randomizationInfo->maxLevel = std::min(reader->readUInt8(), static_cast<ui8>(6)) + 1;
  1240. }
  1241. else
  1242. {
  1243. object->randomizationInfo->minLevel = objectTemplate->subid;
  1244. object->randomizationInfo->maxLevel = objectTemplate->subid;
  1245. }
  1246. return object;
  1247. }
  1248. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readShrine(const int3 & position, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1249. {
  1250. auto object = readGeneric(position, objectTemplate);
  1251. auto rewardable = std::dynamic_pointer_cast<CRewardableObject>(object);
  1252. SpellID spell = reader->readSpell32();
  1253. if (rewardable)
  1254. {
  1255. if(spell != SpellID::NONE)
  1256. {
  1257. JsonNode variable;
  1258. variable.String() = LIBRARY->spells()->getById(spell)->getJsonKey();
  1259. variable.setModScope(ModScope::scopeGame()); // list may include spells from all mods
  1260. rewardable->configuration.presetVariable("spell", "gainedSpell", variable);
  1261. }
  1262. }
  1263. else
  1264. {
  1265. logGlobal->warn("Failed to set selected spell to a Shrine!. Object is not rewardable!");
  1266. }
  1267. return object;
  1268. }
  1269. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readHeroPlaceholder(const int3 & mapPosition)
  1270. {
  1271. auto object = std::make_shared<CGHeroPlaceholder>(map->cb);
  1272. setOwnerAndValidate(mapPosition, object.get(), reader->readPlayer());
  1273. HeroTypeID htid = reader->readHero(); //hero type id
  1274. if(htid.getNum() == -1)
  1275. {
  1276. object->powerRank = reader->readUInt8();
  1277. logGlobal->debug("Map '%s': Hero placeholder: by power at %s, owned by %s", mapName, mapPosition.toString(), object->getOwner().toString());
  1278. }
  1279. else
  1280. {
  1281. object->heroType = htid;
  1282. logGlobal->debug("Map '%s': Hero placeholder: %s at %s, owned by %s", mapName, LIBRARY->heroh->getById(htid)->getJsonKey(), mapPosition.toString(), object->getOwner().toString());
  1283. }
  1284. if(features.levelHOTA5)
  1285. {
  1286. bool customizedStatingUnits = reader->readBool();
  1287. if (customizedStatingUnits)
  1288. logGlobal->warn("Map '%s': Hero placeholder: not implemented option to customize starting units", mapName);
  1289. for (int i = 0; i < 7; ++i)
  1290. {
  1291. int32_t unitAmount = reader->readInt32();
  1292. CreatureID unitToGive = reader->readCreature32();
  1293. if (unitToGive.hasValue())
  1294. logGlobal->warn("Map '%s': Hero placeholder: not implemented option to give %d units of type %d on map start to slot %d is not implemented!", mapName, unitAmount, unitToGive.toEntity(LIBRARY)->getJsonKey(), i);
  1295. }
  1296. int32_t artifactsToGive = reader->readInt32();
  1297. assert(artifactsToGive >= 0);
  1298. assert(artifactsToGive < 100); // technically legal, but not possible in h3
  1299. for (int i = 0; i < artifactsToGive; ++i)
  1300. {
  1301. // NOTE: this might actually be 2 bytes for artifact ID + 2 bytes for spell scroll
  1302. ArtifactID startingArtifact = reader->readArtifact32();
  1303. logGlobal->warn("Map '%s': Hero placeholder: not implemented option to give hero artifact %d", mapName, startingArtifact.toEntity(LIBRARY)->getJsonKey());
  1304. }
  1305. }
  1306. return object;
  1307. }
  1308. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readGrail(const int3 & mapPosition)
  1309. {
  1310. map->grailPos = mapPosition;
  1311. map->grailRadius = reader->readInt32();
  1312. return nullptr;
  1313. }
  1314. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readHotaBattleLocation(const int3 & mapPosition)
  1315. {
  1316. // Battle location for arena mode in HotA
  1317. logGlobal->warn("Map '%s': Arena mode is not supported!", mapName);
  1318. return nullptr;
  1319. }
  1320. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readGeneric(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1321. {
  1322. if(LIBRARY->objtypeh->knownSubObjects(objectTemplate->id).count(objectTemplate->subid))
  1323. return LIBRARY->objtypeh->getHandlerFor(objectTemplate->id, objectTemplate->subid)->create(map->cb, objectTemplate);
  1324. logGlobal->warn("Map '%s': Unrecognized object %d:%d ('%s') at %s found!", mapName, objectTemplate->id.toEnum(), objectTemplate->subid, objectTemplate->animationFile.getOriginalName(), mapPosition.toString());
  1325. return std::make_shared<CGObjectInstance>(map->cb);
  1326. }
  1327. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readQuestGuard(const int3 & mapPosition)
  1328. {
  1329. auto guard = std::make_shared<CGQuestGuard>(map->cb);
  1330. readQuest(guard.get(), mapPosition);
  1331. return guard;
  1332. }
  1333. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readShipyard(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1334. {
  1335. auto object = readGeneric(mapPosition, objectTemplate);
  1336. setOwnerAndValidate(mapPosition, object.get(), reader->readPlayer32());
  1337. return object;
  1338. }
  1339. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readLighthouse(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1340. {
  1341. auto object = readGeneric(mapPosition, objectTemplate);
  1342. setOwnerAndValidate(mapPosition, object.get(), reader->readPlayer32());
  1343. return object;
  1344. }
  1345. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readBank(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1346. {
  1347. if(features.levelHOTA3)
  1348. {
  1349. //TODO: HotA
  1350. // index of guards preset. -1 = random, 0-4 = index of possible guards settings
  1351. int32_t guardsPresetIndex = reader->readInt32();
  1352. // presence of upgraded stack: -1 = random, 0 = never, 1 = always
  1353. int8_t upgradedStackPresence = reader->readInt8Checked(-1, 1);
  1354. assert(vstd::iswithin(guardsPresetIndex, -1, 4));
  1355. assert(vstd::iswithin(upgradedStackPresence, -1, 1));
  1356. // list of possible artifacts in reward
  1357. // - if list is empty, artifacts are either not present in reward or random
  1358. // - if non-empty, then list always have same number of elements as number of artifacts in bank
  1359. // - ArtifactID::NONE indictates random artifact, other values indicate artifact that should be used as reward
  1360. std::vector<ArtifactID> artifacts;
  1361. int artNumber = reader->readUInt32();
  1362. for(int yy = 0; yy < artNumber; ++yy)
  1363. {
  1364. artifacts.push_back(reader->readArtifact32());
  1365. }
  1366. if(guardsPresetIndex != -1 || upgradedStackPresence != -1 || !artifacts.empty())
  1367. logGlobal->warn(
  1368. "Map '%s': creature bank at %s settings %d %d %d are not implemented!",
  1369. mapName,
  1370. mapPosition.toString(),
  1371. guardsPresetIndex,
  1372. int(upgradedStackPresence),
  1373. artifacts.size()
  1374. );
  1375. }
  1376. return readGeneric(mapPosition, objectTemplate);
  1377. }
  1378. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readRewardWithArtifact(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1379. {
  1380. if(features.levelHOTA5)
  1381. {
  1382. // TREASURE_CHEST - rewards index, if 3 - then 2nd value is artifact
  1383. // CORPSE - rewards index, if 1 - then 2nd value is artifact
  1384. // SHIPWRECK_SURVIVOR - if content = 0 then 2nd value is granted artifact
  1385. // SEA_CHEST - rewards index, if 2 - then 2nd value is artifact
  1386. // FLOTSAM - rewards index (0-3) + -1
  1387. // TREE_OF_KNOWLEDGE - rewards index (0-2) + -1
  1388. // PYRAMID - if content = 0 then 2nd value is granted spell
  1389. // WARRIORS_TOMB - if content = 0 then 2nd value is granted artifact
  1390. // HOTA_JETSAM - rewards index (0-3) + -1
  1391. // HOTA_VIAL_OF_MANA - rewards index (0-3) + -1
  1392. int32_t content = reader->readInt32();
  1393. ArtifactID artifact;
  1394. if (content != -1)
  1395. {
  1396. artifact = reader->readArtifact32(); // NOTE: might be 2 byte artifact + 2 bytes scroll spell
  1397. logGlobal->warn("Map '%s': Object (%d) %s settings %d %d are not implemented!", mapName, objectTemplate->id, mapPosition.toString(), content, artifact);
  1398. }
  1399. else
  1400. reader->skipUnused(4); // garbage data, usually -1, but sometimes uninitialized
  1401. }
  1402. return readGeneric(mapPosition, objectTemplate);
  1403. }
  1404. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readBlackMarket(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1405. {
  1406. if(features.levelHOTA5)
  1407. {
  1408. for (int i = 0; i < 7; ++i)
  1409. {
  1410. ArtifactID artifact = reader->readArtifact();
  1411. SpellID spellID = reader->readSpell16();
  1412. if (artifact.hasValue())
  1413. {
  1414. if (artifact != ArtifactID::SPELL_SCROLL)
  1415. logGlobal->warn("Map '%s': Black Market at %s: option to sell artifact %s is not implemented", mapName, mapPosition.toString(), artifact.toEntity(LIBRARY)->getJsonKey());
  1416. else
  1417. logGlobal->warn("Map '%s': Black Market at %s: option to sell scroll %s is not implemented", mapName, mapPosition.toString(), spellID.toEntity(LIBRARY)->getJsonKey());
  1418. }
  1419. }
  1420. }
  1421. return readGeneric(mapPosition, objectTemplate);
  1422. }
  1423. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readUniversity(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1424. {
  1425. if(features.levelHOTA5)
  1426. {
  1427. int32_t customized = reader->readInt32();
  1428. std::set<SecondarySkill> allowedSkills;
  1429. reader->readBitmaskSkills(allowedSkills, false);
  1430. // NOTE: check how this interacts with hota Seafaring Academy that is guaranteed to give Navigation
  1431. assert(customized == -1 || customized == 0);
  1432. if (customized != -1)
  1433. logGlobal->warn("Map '%s': University at %s: option to give specific skills out of %d is not implemented", mapName, mapPosition.toString(), allowedSkills.size());
  1434. }
  1435. return readGeneric(mapPosition, objectTemplate);
  1436. }
  1437. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readRewardWithArtifactAndResources(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1438. {
  1439. if(features.levelHOTA5)
  1440. {
  1441. // Sea Barrel / 0 -> aID = -1, aA = resource amount, rA = resource type, aB = garbage, rB = 0
  1442. // Sea Barrel / 1 -> aID = -1, aA = 1, rA = 1, aB = garbage, rB = 0
  1443. // Ancient Lamp / 0 -> aID = -1, aA = amount to recruit, rA = 0, aB = 1, rB = 0
  1444. // Grave / 0 -> aID = artifact to give, aA = resource amount, rA = resource type, aB = 1, rB = garbage
  1445. // CAMPFIRE 12 / 0 -> aID = -1, aA = gold amount, rA = gold type, aB = resource amount, rB = resource type
  1446. // WAGON 105 / 0 -> aID = -1 or artifact, aA = resource amount, rA = resource type, aB = 1, rB = garbage?
  1447. // WAGON 105 / 1 -> empty / garbage?
  1448. // LEAN_TO / 39 / 0 -> aID = -1, aA = resource amount, rA = resource type, aB = garbage, rB = 0
  1449. int32_t content = reader->readInt32();
  1450. int32_t artifact = reader->readInt32();
  1451. int32_t amountA = reader->readInt32();
  1452. int8_t resourceA = reader->readInt8();
  1453. int32_t amountB = reader->readInt32();
  1454. int8_t resourceB = reader->readInt8();
  1455. if (content != -1)
  1456. logGlobal->warn("Map '%s': Object (%d) %s settings %d %d %d %d %d %d are not implemented!", mapName, objectTemplate->id, mapPosition.toString(), content, artifact, amountA, static_cast<int>(resourceA), amountB, static_cast<int>(resourceB));
  1457. }
  1458. return readGeneric(mapPosition, objectTemplate);
  1459. }
  1460. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readObject(MapObjectID id, MapObjectSubID subid, std::shared_ptr<const ObjectTemplate> objectTemplate, const int3 & mapPosition, const ObjectInstanceID & objectInstanceID)
  1461. {
  1462. switch(id.toEnum())
  1463. {
  1464. case Obj::EVENT:
  1465. return readEvent(mapPosition, objectInstanceID);
  1466. case Obj::HERO:
  1467. case Obj::RANDOM_HERO:
  1468. case Obj::PRISON:
  1469. return readHero(mapPosition, objectInstanceID);
  1470. case Obj::MONSTER:
  1471. case Obj::RANDOM_MONSTER:
  1472. case Obj::RANDOM_MONSTER_L1:
  1473. case Obj::RANDOM_MONSTER_L2:
  1474. case Obj::RANDOM_MONSTER_L3:
  1475. case Obj::RANDOM_MONSTER_L4:
  1476. case Obj::RANDOM_MONSTER_L5:
  1477. case Obj::RANDOM_MONSTER_L6:
  1478. case Obj::RANDOM_MONSTER_L7:
  1479. return readMonster(mapPosition, objectInstanceID);
  1480. case Obj::OCEAN_BOTTLE:
  1481. case Obj::SIGN:
  1482. return readSign(mapPosition);
  1483. case Obj::SEER_HUT:
  1484. return readSeerHut(mapPosition, objectInstanceID);
  1485. case Obj::WITCH_HUT:
  1486. return readWitchHut(mapPosition, objectTemplate);
  1487. case Obj::SCHOLAR:
  1488. return readScholar(mapPosition, objectTemplate);
  1489. case Obj::GARRISON:
  1490. case Obj::GARRISON2:
  1491. return readGarrison(mapPosition, objectInstanceID);
  1492. case Obj::ARTIFACT:
  1493. case Obj::RANDOM_ART:
  1494. case Obj::RANDOM_TREASURE_ART:
  1495. case Obj::RANDOM_MINOR_ART:
  1496. case Obj::RANDOM_MAJOR_ART:
  1497. case Obj::RANDOM_RELIC_ART:
  1498. return readArtifact(mapPosition, objectTemplate, objectInstanceID);
  1499. case Obj::SPELL_SCROLL:
  1500. return readScroll(mapPosition, objectTemplate, objectInstanceID);
  1501. case Obj::RANDOM_RESOURCE:
  1502. case Obj::RESOURCE:
  1503. return readResource(mapPosition, objectTemplate, objectInstanceID);
  1504. case Obj::RANDOM_TOWN:
  1505. case Obj::TOWN:
  1506. return readTown(mapPosition, objectTemplate, objectInstanceID);
  1507. case Obj::MINE:
  1508. case Obj::ABANDONED_MINE:
  1509. if (subid < 7)
  1510. return readMine(mapPosition);
  1511. else
  1512. return readAbandonedMine(mapPosition);
  1513. case Obj::CREATURE_GENERATOR1:
  1514. case Obj::CREATURE_GENERATOR2:
  1515. case Obj::CREATURE_GENERATOR3:
  1516. case Obj::CREATURE_GENERATOR4:
  1517. return readDwelling(mapPosition);
  1518. case Obj::SHRINE_OF_MAGIC_INCANTATION:
  1519. case Obj::SHRINE_OF_MAGIC_GESTURE:
  1520. case Obj::SHRINE_OF_MAGIC_THOUGHT:
  1521. return readShrine(mapPosition, objectTemplate);
  1522. case Obj::PANDORAS_BOX:
  1523. return readPandora(mapPosition, objectInstanceID);
  1524. case Obj::GRAIL:
  1525. if (subid < 1000)
  1526. return readGrail(mapPosition);
  1527. else
  1528. return readHotaBattleLocation(mapPosition);
  1529. case Obj::RANDOM_DWELLING:
  1530. case Obj::RANDOM_DWELLING_LVL:
  1531. case Obj::RANDOM_DWELLING_FACTION:
  1532. return readDwellingRandom(mapPosition, objectTemplate);
  1533. case Obj::QUEST_GUARD:
  1534. return readQuestGuard(mapPosition);
  1535. case Obj::SHIPYARD:
  1536. return readShipyard(mapPosition, objectTemplate);
  1537. case Obj::HERO_PLACEHOLDER:
  1538. return readHeroPlaceholder(mapPosition);
  1539. case Obj::LIGHTHOUSE:
  1540. return readLighthouse(mapPosition, objectTemplate);
  1541. case Obj::CREATURE_BANK:
  1542. case Obj::DERELICT_SHIP:
  1543. case Obj::DRAGON_UTOPIA:
  1544. case Obj::CRYPT:
  1545. case Obj::SHIPWRECK:
  1546. return readBank(mapPosition, objectTemplate);
  1547. case Obj::TREASURE_CHEST:
  1548. case Obj::CORPSE:
  1549. case Obj::SHIPWRECK_SURVIVOR:
  1550. case Obj::SEA_CHEST:
  1551. case Obj::FLOTSAM:
  1552. case Obj::TREE_OF_KNOWLEDGE:
  1553. case Obj::PYRAMID:
  1554. case Obj::WARRIORS_TOMB:
  1555. return readRewardWithArtifact(mapPosition, objectTemplate);
  1556. case Obj::CAMPFIRE:
  1557. case Obj::WAGON:
  1558. case Obj::LEAN_TO:
  1559. return readRewardWithArtifactAndResources(mapPosition, objectTemplate);
  1560. case Obj::BORDER_GATE:
  1561. if (subid == 1000) // HotA hacks - Quest Gate
  1562. return readQuestGuard(mapPosition);
  1563. if (subid == 1001) // HotA hacks - Grave
  1564. return readRewardWithArtifactAndResources(mapPosition, objectTemplate);
  1565. return readGeneric(mapPosition, objectTemplate);
  1566. case Obj::HOTA_CUSTOM_OBJECT_1:
  1567. // 0 -> Ancient Lamp
  1568. // 1 -> Sea Barrel
  1569. // 2 -> Jetsam
  1570. // 3 -> Vial of Mana
  1571. if (subid == 0 || subid == 1)
  1572. return readRewardWithArtifactAndResources(mapPosition, objectTemplate);
  1573. else
  1574. return readRewardWithArtifact(mapPosition, objectTemplate);
  1575. case Obj::HOTA_CUSTOM_OBJECT_2:
  1576. if (subid == 0) // Seafaring Academy
  1577. return readUniversity(mapPosition, objectTemplate);
  1578. else
  1579. return readGeneric(mapPosition, objectTemplate);
  1580. case Obj::BLACK_MARKET:
  1581. return readBlackMarket(mapPosition, objectTemplate);
  1582. case Obj::UNIVERSITY:
  1583. return readUniversity(mapPosition, objectTemplate);
  1584. default: //any other object
  1585. return readGeneric(mapPosition, objectTemplate);
  1586. }
  1587. }
  1588. void CMapLoaderH3M::readObjects()
  1589. {
  1590. uint32_t objectsCount = reader->readUInt32();
  1591. for(uint32_t i = 0; i < objectsCount; ++i)
  1592. {
  1593. int3 mapPosition = reader->readInt3();
  1594. assert(map->isInTheMap(mapPosition) || map->isInTheMap(mapPosition - int3(0,8,0)) || map->isInTheMap(mapPosition - int3(8,0,0)) || map->isInTheMap(mapPosition - int3(8,8,0)));
  1595. uint32_t defIndex = reader->readUInt32();
  1596. std::shared_ptr<ObjectTemplate> originalTemplate = originalTemplates.at(defIndex);
  1597. std::shared_ptr<ObjectTemplate> remappedTemplate = remappedTemplates.at(defIndex);
  1598. auto originalID = originalTemplate->id;
  1599. auto originalSubID = originalTemplate->subid;
  1600. reader->skipZero(5);
  1601. ObjectInstanceID newObjectID = map->allocateUniqueInstanceID();
  1602. auto newObject = readObject(originalID, originalSubID, remappedTemplate, mapPosition, newObjectID);
  1603. if(!newObject)
  1604. continue;
  1605. newObject->setAnchorPos(mapPosition);
  1606. newObject->ID = remappedTemplate->id;
  1607. newObject->id = newObjectID;
  1608. if(newObject->ID != Obj::HERO && newObject->ID != Obj::HERO_PLACEHOLDER && newObject->ID != Obj::PRISON)
  1609. {
  1610. newObject->subID = remappedTemplate->subid;
  1611. }
  1612. newObject->appearance = remappedTemplate;
  1613. if (newObject->isVisitable() && !map->isInTheMap(newObject->visitablePos()))
  1614. logGlobal->error("Map '%s': Object at %s - outside of map borders!", mapName, mapPosition.toString());
  1615. map->generateUniqueInstanceName(newObject.get());
  1616. map->addNewObject(newObject);
  1617. }
  1618. }
  1619. void CMapLoaderH3M::readCreatureSet(CArmedInstance * out, const ObjectInstanceID & idToBeGiven)
  1620. {
  1621. constexpr int unitsToRead = 7;
  1622. out->id = idToBeGiven;
  1623. for(int index = 0; index < unitsToRead; ++index)
  1624. {
  1625. CreatureID creatureID = reader->readCreature();
  1626. int count = reader->readUInt16();
  1627. // Empty slot
  1628. if(creatureID == CreatureID::NONE)
  1629. continue;
  1630. auto result = std::make_unique<CStackInstance>(map->cb);
  1631. result->setCount(count);
  1632. if(creatureID < CreatureID::NONE)
  1633. {
  1634. int value = -creatureID.getNum() - 2;
  1635. assert(value >= 0 && value < 14);
  1636. uint8_t level = value / 2;
  1637. uint8_t upgrade = value % 2;
  1638. //this will happen when random object has random army
  1639. result->randomStack = CStackInstance::RandomStackInfo{level, upgrade};
  1640. }
  1641. else
  1642. {
  1643. result->setType(creatureID);
  1644. }
  1645. out->putStack(SlotID(index), std::move(result));
  1646. }
  1647. out->validTypes(true);
  1648. }
  1649. void CMapLoaderH3M::setOwnerAndValidate(const int3 & mapPosition, CGObjectInstance * object, const PlayerColor & owner)
  1650. {
  1651. assert(owner.isValidPlayer() || owner == PlayerColor::NEUTRAL);
  1652. if(owner == PlayerColor::NEUTRAL)
  1653. {
  1654. object->setOwner(PlayerColor::NEUTRAL);
  1655. return;
  1656. }
  1657. if(!owner.isValidPlayer())
  1658. {
  1659. object->setOwner(PlayerColor::NEUTRAL);
  1660. logGlobal->warn("Map '%s': Object at %s - owned by invalid player %d! Will be set to neutral!", mapName, mapPosition.toString(), int(owner.getNum()));
  1661. return;
  1662. }
  1663. if(!mapHeader->players[owner.getNum()].canAnyonePlay())
  1664. {
  1665. object->setOwner(PlayerColor::NEUTRAL);
  1666. logGlobal->warn("Map '%s': Object at %s - owned by non-existing player %d! Will be set to neutral!", mapName, mapPosition.toString(), int(owner.getNum())
  1667. );
  1668. return;
  1669. }
  1670. object->setOwner(owner);
  1671. }
  1672. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readHero(const int3 & mapPosition, const ObjectInstanceID & objectInstanceID)
  1673. {
  1674. if(features.levelAB)
  1675. {
  1676. unsigned int identifier = reader->readUInt32();
  1677. questIdentifierToId[identifier] = objectInstanceID;
  1678. }
  1679. PlayerColor owner = reader->readPlayer();
  1680. HeroTypeID heroType = reader->readHero();
  1681. //If hero of this type has been predefined, use that as a base.
  1682. //Instance data will overwrite the predefined values where appropriate.
  1683. std::shared_ptr<CGHeroInstance> object;
  1684. if (heroType.hasValue())
  1685. object = map->tryTakeFromHeroPool(heroType);
  1686. if (!object)
  1687. {
  1688. object = std::make_shared<CGHeroInstance>(map->cb);
  1689. object->subID = heroType.getNum();
  1690. }
  1691. setOwnerAndValidate(mapPosition, object.get(), owner);
  1692. for(auto & elem : map->disposedHeroes)
  1693. {
  1694. if(elem.heroId == object->getHeroTypeID())
  1695. {
  1696. object->nameCustomTextId = elem.name;
  1697. object->customPortraitSource = elem.portrait;
  1698. break;
  1699. }
  1700. }
  1701. bool hasName = reader->readBool();
  1702. if(hasName)
  1703. object->nameCustomTextId = readLocalizedString(TextIdentifier("heroes", object->getHeroTypeID().getNum(), "name"));
  1704. if(features.levelSOD)
  1705. {
  1706. bool hasCustomExperience = reader->readBool();
  1707. if(hasCustomExperience)
  1708. object->exp = reader->readUInt32();
  1709. }
  1710. else
  1711. {
  1712. object->exp = reader->readUInt32();
  1713. //0 means "not set" in <=AB maps
  1714. if(!object->exp)
  1715. object->exp = CGHeroInstance::UNINITIALIZED_EXPERIENCE;
  1716. }
  1717. bool hasPortrait = reader->readBool();
  1718. if(hasPortrait)
  1719. object->customPortraitSource = reader->readHeroPortrait();
  1720. bool hasSecSkills = reader->readBool();
  1721. if(hasSecSkills)
  1722. {
  1723. if(!object->secSkills.empty())
  1724. {
  1725. if(object->secSkills[0].first != SecondarySkill::NONE)
  1726. logGlobal->debug("Map '%s': Hero %s subID=%d has set secondary skills twice (in map properties and on adventure map instance). Using the latter set...", mapName, object->getNameTextID(), object->subID);
  1727. object->secSkills.clear();
  1728. }
  1729. uint32_t skillsCount = reader->readUInt32();
  1730. object->secSkills.resize(skillsCount);
  1731. for(int i = 0; i < skillsCount; ++i)
  1732. {
  1733. object->secSkills[i].first = reader->readSkill();
  1734. object->secSkills[i].second = reader->readInt8Checked(1,3);
  1735. }
  1736. }
  1737. bool hasGarison = reader->readBool();
  1738. if(hasGarison)
  1739. readCreatureSet(object.get(), objectInstanceID);
  1740. object->formation = static_cast<EArmyFormation>(reader->readInt8Checked(0, 1));
  1741. assert(object->formation == EArmyFormation::LOOSE || object->formation == EArmyFormation::TIGHT);
  1742. loadArtifactsOfHero(object.get());
  1743. object->patrol.patrolRadius = reader->readUInt8();
  1744. object->patrol.patrolling = (object->patrol.patrolRadius != 0xff);
  1745. if(features.levelAB)
  1746. {
  1747. bool hasCustomBiography = reader->readBool();
  1748. if(hasCustomBiography)
  1749. object->biographyCustomTextId = readLocalizedString(TextIdentifier("heroes", object->subID, "biography"));
  1750. object->gender = static_cast<EHeroGender>(reader->readInt8Checked(-1, 1));
  1751. assert(object->gender == EHeroGender::MALE || object->gender == EHeroGender::FEMALE || object->gender == EHeroGender::DEFAULT);
  1752. }
  1753. else
  1754. {
  1755. object->gender = EHeroGender::DEFAULT;
  1756. }
  1757. // Spells
  1758. if(features.levelSOD)
  1759. {
  1760. bool hasCustomSpells = reader->readBool();
  1761. if(hasCustomSpells)
  1762. {
  1763. if(!object->spells.empty())
  1764. {
  1765. object->spells.clear();
  1766. logGlobal->debug("Hero %s subID=%d has spells set twice (in map properties and on adventure map instance). Using the latter set...", object->getNameTextID(), object->subID);
  1767. }
  1768. reader->readBitmaskSpells(object->spells, false);
  1769. object->spells.insert(SpellID::PRESET); //placeholder "preset spells"
  1770. }
  1771. }
  1772. else if(features.levelAB)
  1773. {
  1774. //we can read one spell
  1775. SpellID spell = reader->readSpell();
  1776. // workaround: VCMI uses 'PRESET' spell to indicate that spellbook has been preconfigured on map
  1777. // but H3 uses 'PRESET' spell (-2) to indicate that game should give standard spell to hero
  1778. if(spell == SpellID::NONE)
  1779. object->spells.insert(SpellID::PRESET); //spellbook is preconfigured to be empty
  1780. if (spell.hasValue())
  1781. object->spells.insert(spell);
  1782. }
  1783. if(features.levelSOD)
  1784. {
  1785. bool hasCustomPrimSkills = reader->readBool();
  1786. if(hasCustomPrimSkills)
  1787. {
  1788. auto ps = object->getAllBonuses(Selector::type()(BonusType::PRIMARY_SKILL).And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL)), nullptr);
  1789. if(ps->size())
  1790. {
  1791. logGlobal->debug("Hero %s has set primary skills twice (in map properties and on adventure map instance). Using the latter set...", object->getHeroTypeID().getNum() );
  1792. for(const auto & b : *ps)
  1793. object->removeBonus(b);
  1794. }
  1795. for(int xx = 0; xx < GameConstants::PRIMARY_SKILLS; ++xx)
  1796. {
  1797. object->pushPrimSkill(static_cast<PrimarySkill>(xx), reader->readUInt8());
  1798. }
  1799. }
  1800. }
  1801. if (object->subID != MapObjectSubID())
  1802. logGlobal->debug("Map '%s': Hero on map: %s at %s, owned by %s", mapName, object->getHeroType()->getJsonKey(), mapPosition.toString(), object->getOwner().toString());
  1803. else
  1804. logGlobal->debug("Map '%s': Hero on map: (random) at %s, owned by %s", mapName, mapPosition.toString(), object->getOwner().toString());
  1805. reader->skipZero(16);
  1806. if(features.levelHOTA5)
  1807. {
  1808. bool alwaysAddSkills = reader->readBool(); // prevent heroes from receiving additional random secondary skills at the start of the map if they are not of the first level
  1809. bool cannotGainXP = reader->readBool();
  1810. int32_t level = reader->readInt32(); // Needs investigation how this interacts with usual setting of level via experience
  1811. assert(level > 0);
  1812. if (!alwaysAddSkills)
  1813. logGlobal->warn("Map '%s': Option to prevent hero %d from gaining skills on map start is not implemented!", mapName, object->subID.num);
  1814. if (cannotGainXP)
  1815. logGlobal->warn("Map '%s': Option to prevent hero %d from receiveing experience is not implemented!", mapName, object->subID.num);
  1816. if (level > 1)
  1817. logGlobal->warn("Map '%s': Option to set level of hero %d to %d is not implemented!", mapName, object->subID.num, level);
  1818. }
  1819. return object;
  1820. }
  1821. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readSeerHut(const int3 & position, const ObjectInstanceID & idToBeGiven)
  1822. {
  1823. auto hut = std::make_shared<CGSeerHut>(map->cb);
  1824. uint32_t questsCount = 1;
  1825. if(features.levelHOTA3)
  1826. questsCount = reader->readUInt32();
  1827. //TODO: HotA
  1828. if(questsCount > 1)
  1829. logGlobal->warn("Map '%s': Seer Hut at %s - %d quests are not implemented!", mapName, position.toString(), questsCount);
  1830. for(size_t i = 0; i < questsCount; ++i)
  1831. readSeerHutQuest(hut.get(), position, idToBeGiven);
  1832. if(features.levelHOTA3)
  1833. {
  1834. uint32_t repeateableQuestsCount = reader->readUInt32();
  1835. hut->getQuest().repeatedQuest = repeateableQuestsCount != 0;
  1836. if(repeateableQuestsCount != 0)
  1837. logGlobal->warn("Map '%s': Seer Hut at %s - %d repeatable quests are not implemented!", mapName, position.toString(), repeateableQuestsCount);
  1838. for(size_t i = 0; i < repeateableQuestsCount; ++i)
  1839. readSeerHutQuest(hut.get(), position, idToBeGiven);
  1840. }
  1841. reader->skipZero(2);
  1842. return hut;
  1843. }
  1844. enum class ESeerHutRewardType : uint8_t
  1845. {
  1846. NOTHING = 0,
  1847. EXPERIENCE = 1,
  1848. MANA_POINTS = 2,
  1849. MORALE = 3,
  1850. LUCK = 4,
  1851. RESOURCES = 5,
  1852. PRIMARY_SKILL = 6,
  1853. SECONDARY_SKILL = 7,
  1854. ARTIFACT = 8,
  1855. SPELL = 9,
  1856. CREATURE = 10,
  1857. };
  1858. void CMapLoaderH3M::readSeerHutQuest(CGSeerHut * hut, const int3 & position, const ObjectInstanceID & idToBeGiven)
  1859. {
  1860. EQuestMission missionType = EQuestMission::NONE;
  1861. if(features.levelAB)
  1862. {
  1863. missionType = readQuest(hut, position);
  1864. }
  1865. else
  1866. {
  1867. //RoE
  1868. auto artID = reader->readArtifact();
  1869. if(artID != ArtifactID::NONE)
  1870. {
  1871. //not none quest
  1872. hut->getQuest().mission.artifacts.push_back(artID);
  1873. missionType = EQuestMission::ARTIFACT;
  1874. }
  1875. hut->getQuest().lastDay = -1; //no timeout
  1876. hut->getQuest().isCustomFirst = false;
  1877. hut->getQuest().isCustomNext = false;
  1878. hut->getQuest().isCustomComplete = false;
  1879. }
  1880. if(missionType != EQuestMission::NONE)
  1881. {
  1882. auto rewardType = static_cast<ESeerHutRewardType>(reader->readInt8Checked(0, 10));
  1883. Rewardable::VisitInfo vinfo;
  1884. auto & reward = vinfo.reward;
  1885. switch(rewardType)
  1886. {
  1887. case ESeerHutRewardType::NOTHING:
  1888. {
  1889. // no-op
  1890. break;
  1891. }
  1892. case ESeerHutRewardType::EXPERIENCE:
  1893. {
  1894. reward.heroExperience = reader->readUInt32();
  1895. break;
  1896. }
  1897. case ESeerHutRewardType::MANA_POINTS:
  1898. {
  1899. reward.manaDiff = reader->readUInt32();
  1900. break;
  1901. }
  1902. case ESeerHutRewardType::MORALE:
  1903. {
  1904. reward.heroBonuses.push_back(std::make_shared<Bonus>(BonusDuration::ONE_BATTLE, BonusType::MORALE, BonusSource::OBJECT_INSTANCE, reader->readInt8Checked(-3, 3), BonusSourceID(idToBeGiven)));
  1905. break;
  1906. }
  1907. case ESeerHutRewardType::LUCK:
  1908. {
  1909. reward.heroBonuses.push_back(std::make_shared<Bonus>(BonusDuration::ONE_BATTLE, BonusType::LUCK, BonusSource::OBJECT_INSTANCE, reader->readInt8Checked(-3, 3), BonusSourceID(idToBeGiven)));
  1910. break;
  1911. }
  1912. case ESeerHutRewardType::RESOURCES:
  1913. {
  1914. auto rId = reader->readGameResID();
  1915. auto rVal = reader->readUInt32();
  1916. reward.resources[rId] = rVal;
  1917. break;
  1918. }
  1919. case ESeerHutRewardType::PRIMARY_SKILL:
  1920. {
  1921. auto rId = reader->readPrimary();
  1922. auto rVal = reader->readUInt8();
  1923. reward.primary.at(rId.getNum()) = rVal;
  1924. break;
  1925. }
  1926. case ESeerHutRewardType::SECONDARY_SKILL:
  1927. {
  1928. auto rId = reader->readSkill();
  1929. auto rVal = reader->readInt8Checked(1,3);
  1930. reward.secondary[rId] = rVal;
  1931. break;
  1932. }
  1933. case ESeerHutRewardType::ARTIFACT:
  1934. {
  1935. ArtifactID grantedArtifact = reader->readArtifact();
  1936. if (features.levelHOTA5)
  1937. {
  1938. SpellID scrollSpell = reader->readSpell16();
  1939. if (grantedArtifact == ArtifactID::SPELL_SCROLL)
  1940. reward.grantedScrolls.push_back(scrollSpell);
  1941. }
  1942. else
  1943. reward.grantedArtifacts.push_back(grantedArtifact);
  1944. break;
  1945. }
  1946. case ESeerHutRewardType::SPELL:
  1947. {
  1948. reward.spells.push_back(reader->readSpell());
  1949. break;
  1950. }
  1951. case ESeerHutRewardType::CREATURE:
  1952. {
  1953. auto rId = reader->readCreature();
  1954. auto rVal = reader->readUInt16();
  1955. reward.creatures.emplace_back(rId, rVal);
  1956. break;
  1957. }
  1958. default:
  1959. {
  1960. assert(0);
  1961. }
  1962. }
  1963. vinfo.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  1964. hut->configuration.info.push_back(vinfo);
  1965. }
  1966. else
  1967. {
  1968. // missionType==255
  1969. reader->skipZero(1);
  1970. }
  1971. }
  1972. EQuestMission CMapLoaderH3M::readQuest(IQuestObject * guard, const int3 & position)
  1973. {
  1974. auto missionId = static_cast<EQuestMission>(reader->readInt8Checked(0, 10));
  1975. switch(missionId)
  1976. {
  1977. case EQuestMission::NONE:
  1978. return missionId;
  1979. case EQuestMission::PRIMARY_SKILL:
  1980. {
  1981. for(int x = 0; x < 4; ++x)
  1982. {
  1983. guard->getQuest().mission.primary[x] = reader->readUInt8();
  1984. }
  1985. break;
  1986. }
  1987. case EQuestMission::LEVEL:
  1988. {
  1989. guard->getQuest().mission.heroLevel = reader->readUInt32();
  1990. break;
  1991. }
  1992. case EQuestMission::KILL_HERO:
  1993. case EQuestMission::KILL_CREATURE:
  1994. {
  1995. // NOTE: assert might fail on multi-quest seers
  1996. //assert(questsToResolve.count(guard) == 0);
  1997. questsToResolve[guard] = reader->readUInt32();
  1998. break;
  1999. }
  2000. case EQuestMission::ARTIFACT:
  2001. {
  2002. size_t artNumber = reader->readUInt8();
  2003. for(size_t yy = 0; yy < artNumber; ++yy)
  2004. {
  2005. ArtifactID requiredArtifact = reader->readArtifact();
  2006. if (features.levelHOTA5)
  2007. {
  2008. SpellID scrollSpell = reader->readSpell16();
  2009. if (requiredArtifact == ArtifactID::SPELL_SCROLL)
  2010. guard->getQuest().mission.scrolls.push_back(scrollSpell);
  2011. }
  2012. else
  2013. guard->getQuest().mission.artifacts.push_back(requiredArtifact);
  2014. map->allowedArtifact.erase(requiredArtifact); //these are unavailable for random generation
  2015. }
  2016. break;
  2017. }
  2018. case EQuestMission::ARMY:
  2019. {
  2020. size_t typeNumber = reader->readUInt8();
  2021. guard->getQuest().mission.creatures.resize(typeNumber);
  2022. for(size_t hh = 0; hh < typeNumber; ++hh)
  2023. {
  2024. guard->getQuest().mission.creatures[hh].setType(reader->readCreature().toCreature());
  2025. guard->getQuest().mission.creatures[hh].setCount(reader->readUInt16());
  2026. }
  2027. break;
  2028. }
  2029. case EQuestMission::RESOURCES:
  2030. {
  2031. for(int x = 0; x < 7; ++x)
  2032. guard->getQuest().mission.resources[x] = reader->readUInt32();
  2033. break;
  2034. }
  2035. case EQuestMission::HERO:
  2036. {
  2037. guard->getQuest().mission.heroes.push_back(reader->readHero());
  2038. break;
  2039. }
  2040. case EQuestMission::PLAYER:
  2041. {
  2042. guard->getQuest().mission.players.push_back(reader->readPlayer());
  2043. break;
  2044. }
  2045. case EQuestMission::HOTA_MULTI:
  2046. {
  2047. uint32_t missionSubID = reader->readUInt32();
  2048. assert(missionSubID < 3);
  2049. if(missionSubID == 0)
  2050. {
  2051. missionId = EQuestMission::HOTA_HERO_CLASS;
  2052. std::set<HeroClassID> heroClasses;
  2053. reader->readBitmaskHeroClassesSized(heroClasses, false);
  2054. for(auto & hc : heroClasses)
  2055. guard->getQuest().mission.heroClasses.push_back(hc);
  2056. break;
  2057. }
  2058. if(missionSubID == 1)
  2059. {
  2060. missionId = EQuestMission::HOTA_REACH_DATE;
  2061. guard->getQuest().mission.daysPassed = reader->readUInt32() + 1;
  2062. break;
  2063. }
  2064. if(missionSubID == 2)
  2065. {
  2066. missionId = EQuestMission::HOTA_GAME_DIFFICULTY;
  2067. int32_t difficultyMask = reader->readUInt32();
  2068. assert(difficultyMask > 0 && difficultyMask < 32);
  2069. logGlobal->warn("Map '%s': Seer Hut at %s: Difficulty-specific quest (%d) is not implemented!", mapName, position.toString(), difficultyMask);
  2070. break;
  2071. }
  2072. break;
  2073. }
  2074. default:
  2075. {
  2076. assert(0);
  2077. }
  2078. }
  2079. guard->getQuest().lastDay = reader->readInt32();
  2080. guard->getQuest().firstVisitText.appendTextID(readLocalizedString(TextIdentifier("quest", position.x, position.y, position.z, "firstVisit")));
  2081. guard->getQuest().nextVisitText.appendTextID(readLocalizedString(TextIdentifier("quest", position.x, position.y, position.z, "nextVisit")));
  2082. guard->getQuest().completedText.appendTextID(readLocalizedString(TextIdentifier("quest", position.x, position.y, position.z, "completed")));
  2083. guard->getQuest().isCustomFirst = !guard->getQuest().firstVisitText.empty();
  2084. guard->getQuest().isCustomNext = !guard->getQuest().nextVisitText.empty();
  2085. guard->getQuest().isCustomComplete = !guard->getQuest().completedText.empty();
  2086. return missionId;
  2087. }
  2088. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readTown(const int3 & position, std::shared_ptr<const ObjectTemplate> objectTemplate, const ObjectInstanceID & idToBeGiven)
  2089. {
  2090. auto object = std::make_shared<CGTownInstance>(map->cb);
  2091. if(features.levelAB)
  2092. object->identifier = reader->readUInt32();
  2093. setOwnerAndValidate(position, object.get(), reader->readPlayer());
  2094. std::optional<FactionID> faction;
  2095. if (objectTemplate->id == Obj::TOWN)
  2096. faction = FactionID(objectTemplate->subid);
  2097. bool hasName = reader->readBool();
  2098. if(hasName)
  2099. object->setNameTextId(readLocalizedString(TextIdentifier("town", position.x, position.y, position.z, "name")));
  2100. bool hasGarrison = reader->readBool();
  2101. if(hasGarrison)
  2102. readCreatureSet(object.get(), idToBeGiven);
  2103. object->formation = static_cast<EArmyFormation>(reader->readInt8Checked(0, 1));
  2104. assert(object->formation == EArmyFormation::LOOSE || object->formation == EArmyFormation::TIGHT);
  2105. bool hasCustomBuildings = reader->readBool();
  2106. if(hasCustomBuildings)
  2107. {
  2108. std::set<BuildingID> builtBuildings;
  2109. reader->readBitmaskBuildings(builtBuildings, faction);
  2110. for(const auto & building : builtBuildings)
  2111. object->addBuilding(building);
  2112. reader->readBitmaskBuildings(object->forbiddenBuildings, faction);
  2113. }
  2114. // Standard buildings
  2115. else
  2116. {
  2117. bool hasFort = reader->readBool();
  2118. if(hasFort)
  2119. object->addBuilding(BuildingID::FORT);
  2120. //means that set of standard building should be included
  2121. object->addBuilding(BuildingID::DEFAULT);
  2122. }
  2123. if(features.levelAB)
  2124. {
  2125. std::set<SpellID> spellsMask;
  2126. reader->readBitmaskSpells(spellsMask, false);
  2127. std::copy(spellsMask.begin(), spellsMask.end(), std::back_inserter(object->obligatorySpells));
  2128. }
  2129. {
  2130. std::set<SpellID> spellsMask = LIBRARY->spellh->getDefaultAllowed(); // by default - include spells from mods
  2131. reader->readBitmaskSpells(spellsMask, true);
  2132. std::copy(spellsMask.begin(), spellsMask.end(), std::back_inserter(object->possibleSpells));
  2133. }
  2134. if(features.levelHOTA1)
  2135. object->spellResearchAllowed = reader->readBool();
  2136. if(features.levelHOTA5)
  2137. {
  2138. // Most likely customization of special buildings per faction -> 4x11 table
  2139. // presumably:
  2140. // 0 -> default / allowed
  2141. // 1 -> built?
  2142. // 2 -> banned?
  2143. uint32_t specialBuildingsSize = reader->readUInt32();
  2144. for (int i = 0; i < specialBuildingsSize; ++i)
  2145. {
  2146. int factionID = i / 4;
  2147. int buildingID = i % 4;
  2148. int8_t specialBuildingBuilt = reader->readInt8Checked(0, 2);
  2149. if (specialBuildingBuilt != 0)
  2150. logGlobal->warn("Map '%s': Town at %s: Constructing / banning town-specific special building %d in faction %d on start is not implemented!", mapName, position.toString(), buildingID, factionID);
  2151. }
  2152. }
  2153. // Read castle events
  2154. uint32_t eventsCount = reader->readUInt32();
  2155. for(int eventID = 0; eventID < eventsCount; ++eventID)
  2156. {
  2157. CCastleEvent event;
  2158. event.creatures.resize(7);
  2159. readEventCommon(event, TextIdentifier("town", position.x, position.y, position.z, "event", eventID, "description"));
  2160. if(features.levelHOTA5)
  2161. {
  2162. int32_t creatureGrowth8 = reader->readInt32();
  2163. // always 44
  2164. int32_t hotaAmount = reader->readInt32();
  2165. // contains bitmask on which town-specific buildings to build
  2166. // 4 bits / town, for each of special building in town (special 1 - special 4)
  2167. int32_t hotaSpecialA = reader->readInt32();
  2168. int16_t hotaSpecialB = reader->readInt16();
  2169. if (hotaSpecialA != 0 || hotaSpecialB != 0 || hotaAmount != 44)
  2170. logGlobal->warn("Map '%s': Town at %s: Constructing town-specific special buildings in event is not implemented!", mapName, position.toString());
  2171. event.creatures.push_back(creatureGrowth8);
  2172. }
  2173. if(features.levelHOTA7)
  2174. {
  2175. [[maybe_unused]] bool neutralAffected = reader->readBool();
  2176. }
  2177. // New buildings
  2178. reader->readBitmaskBuildings(event.buildings, faction);
  2179. for(int i = 0; i < 7; ++i)
  2180. event.creatures[i] = reader->readUInt16();
  2181. reader->skipZero(4);
  2182. object->events.push_back(event);
  2183. }
  2184. if(features.levelSOD)
  2185. {
  2186. object->alignmentToPlayer = PlayerColor::NEUTRAL; // "same as owner or random"
  2187. uint8_t alignment = reader->readUInt8();
  2188. if(alignment != 255)
  2189. {
  2190. if(alignment < PlayerColor::PLAYER_LIMIT.getNum())
  2191. {
  2192. if (mapHeader->players[alignment].canAnyonePlay())
  2193. object->alignmentToPlayer = PlayerColor(alignment);
  2194. else
  2195. logGlobal->warn("Map '%s': Alignment of town at %s is invalid! Player %d is not present on map!", mapName, position.toString(), static_cast<int>(alignment));
  2196. }
  2197. else
  2198. {
  2199. // TODO: HOTA support
  2200. uint8_t invertedAlignment = alignment - PlayerColor::PLAYER_LIMIT.getNum();
  2201. if(invertedAlignment < PlayerColor::PLAYER_LIMIT.getNum())
  2202. {
  2203. logGlobal->warn("Map '%s': Alignment of town at %s 'not as player %d' is not implemented!", mapName, position.toString(), alignment - PlayerColor::PLAYER_LIMIT.getNum());
  2204. }
  2205. else
  2206. {
  2207. logGlobal->warn("Map '%s': Alignment of town at %s is corrupted!!", mapName, position.toString());
  2208. }
  2209. }
  2210. }
  2211. }
  2212. reader->skipZero(3);
  2213. return object;
  2214. }
  2215. void CMapLoaderH3M::readEventCommon(CMapEvent & event, const TextIdentifier & messageID)
  2216. {
  2217. event.name = readBasicString();
  2218. event.message.appendTextID(readLocalizedString(messageID));
  2219. reader->readResources(event.resources);
  2220. reader->readBitmaskPlayers(event.players, false);
  2221. if(features.levelSOD)
  2222. event.humanAffected = reader->readBool();
  2223. else
  2224. event.humanAffected = true;
  2225. event.computerAffected = reader->readBool();
  2226. event.firstOccurrence = reader->readUInt16();
  2227. event.nextOccurrence = reader->readUInt16();
  2228. reader->skipZero(16);
  2229. if (features.levelHOTA7)
  2230. {
  2231. int32_t allowedDifficultiesMask = reader->readInt32();
  2232. assert(allowedDifficultiesMask > 0 && allowedDifficultiesMask < 32);
  2233. if (allowedDifficultiesMask != 31)
  2234. logGlobal->warn("Map '%s': Map event: availability by difficulty (mode %d) is not implemented!", mapName, allowedDifficultiesMask);
  2235. }
  2236. }
  2237. void CMapLoaderH3M::readEvents()
  2238. {
  2239. uint32_t eventsCount = reader->readUInt32();
  2240. for(int eventID = 0; eventID < eventsCount; ++eventID)
  2241. {
  2242. CMapEvent event;
  2243. readEventCommon(event, TextIdentifier("event", eventID, "description"));
  2244. // garbage bytes that were present in HOTA5 & HOTA6
  2245. if (features.levelHOTA5 && !features.levelHOTA7)
  2246. reader->skipUnused(14);
  2247. map->events.push_back(event);
  2248. }
  2249. }
  2250. void CMapLoaderH3M::readMessageAndGuards(MetaString & message, CArmedInstance * guards, const int3 & position, const ObjectInstanceID & idToBeGiven)
  2251. {
  2252. bool hasMessage = reader->readBool();
  2253. if(hasMessage)
  2254. {
  2255. message.appendTextID(readLocalizedString(TextIdentifier("guards", position.x, position.y, position.z, "message")));
  2256. bool hasGuards = reader->readBool();
  2257. if(hasGuards)
  2258. readCreatureSet(guards, idToBeGiven);
  2259. reader->skipZero(4);
  2260. }
  2261. }
  2262. std::string CMapLoaderH3M::readBasicString()
  2263. {
  2264. return TextOperations::toUnicode(reader->readBaseString(), fileEncoding);
  2265. }
  2266. std::string CMapLoaderH3M::readLocalizedString(const TextIdentifier & stringIdentifier)
  2267. {
  2268. std::string mapString = TextOperations::toUnicode(reader->readBaseString(), fileEncoding);
  2269. TextIdentifier fullIdentifier("map", mapName, stringIdentifier.get());
  2270. if(mapString.empty())
  2271. return "";
  2272. return mapRegisterLocalizedString(modName, *mapHeader, fullIdentifier, mapString);
  2273. }
  2274. void CMapLoaderH3M::afterRead()
  2275. {
  2276. //convert main town positions for all players to actual object position, in H3M it is position of active tile
  2277. for(auto & p : map->players)
  2278. {
  2279. int3 posOfMainTown = p.posOfMainTown;
  2280. if(posOfMainTown.isValid() && map->isInTheMap(posOfMainTown))
  2281. {
  2282. const TerrainTile & t = map->getTile(posOfMainTown);
  2283. const CGObjectInstance * mainTown = nullptr;
  2284. for(ObjectInstanceID objID : t.visitableObjects)
  2285. {
  2286. const CGObjectInstance * object = map->getObject(objID);
  2287. if(object->ID == Obj::TOWN || object->ID == Obj::RANDOM_TOWN)
  2288. {
  2289. mainTown = object;
  2290. break;
  2291. }
  2292. }
  2293. if(mainTown == nullptr)
  2294. continue;
  2295. p.posOfMainTown = posOfMainTown + mainTown->getVisitableOffset();
  2296. }
  2297. }
  2298. for (auto & quest : questsToResolve)
  2299. quest.first->getQuest().killTarget = questIdentifierToId.at(quest.second);
  2300. }
  2301. VCMI_LIB_NAMESPACE_END