MapFormatH3M.cpp 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217
  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 "MapFormat.h"
  15. #include "../CCreatureHandler.h"
  16. #include "../CGeneralTextHandler.h"
  17. #include "../CHeroHandler.h"
  18. #include "../CSkillHandler.h"
  19. #include "../CStopWatch.h"
  20. #include "../CModHandler.h"
  21. #include "../GameSettings.h"
  22. #include "../RiverHandler.h"
  23. #include "../RoadHandler.h"
  24. #include "../TerrainHandler.h"
  25. #include "../TextOperations.h"
  26. #include "../VCMI_Lib.h"
  27. #include "../filesystem/CBinaryReader.h"
  28. #include "../filesystem/Filesystem.h"
  29. #include "../mapObjects/CObjectClassesHandler.h"
  30. #include "../mapObjects/MapObjects.h"
  31. #include "../spells/CSpellHandler.h"
  32. #include <boost/crc.hpp>
  33. VCMI_LIB_NAMESPACE_BEGIN
  34. static std::string convertMapName(std::string input)
  35. {
  36. boost::algorithm::to_lower(input);
  37. boost::algorithm::trim(input);
  38. size_t slashPos = input.find_last_of('/');
  39. if(slashPos != std::string::npos)
  40. return input.substr(slashPos + 1);
  41. return input;
  42. }
  43. CMapLoaderH3M::CMapLoaderH3M(const std::string & mapName, const std::string & modName, const std::string & encodingName, CInputStream * stream)
  44. : map(nullptr)
  45. , reader(new MapReaderH3M(stream))
  46. , inputStream(stream)
  47. , mapName(convertMapName(mapName))
  48. , modName(modName)
  49. , fileEncoding(encodingName)
  50. {
  51. }
  52. //must be instantiated in .cpp file for access to complete types of all member fields
  53. CMapLoaderH3M::~CMapLoaderH3M() = default;
  54. std::unique_ptr<CMap> CMapLoaderH3M::loadMap()
  55. {
  56. // Init map object by parsing the input buffer
  57. map = new CMap();
  58. mapHeader = std::unique_ptr<CMapHeader>(dynamic_cast<CMapHeader *>(map));
  59. init();
  60. return std::unique_ptr<CMap>(dynamic_cast<CMap *>(mapHeader.release()));
  61. }
  62. std::unique_ptr<CMapHeader> CMapLoaderH3M::loadMapHeader()
  63. {
  64. // Read header
  65. mapHeader = std::make_unique<CMapHeader>();
  66. readHeader();
  67. return std::move(mapHeader);
  68. }
  69. void CMapLoaderH3M::init()
  70. {
  71. //TODO: get rid of double input process
  72. si64 temp_size = inputStream->getSize();
  73. inputStream->seek(0);
  74. auto * temp_buffer = new ui8[temp_size];
  75. inputStream->read(temp_buffer, temp_size);
  76. // Compute checksum
  77. boost::crc_32_type result;
  78. result.process_bytes(temp_buffer, temp_size);
  79. map->checksum = result.checksum();
  80. delete[] temp_buffer;
  81. inputStream->seek(0);
  82. readHeader();
  83. map->allHeroes.resize(map->allowedHeroes.size());
  84. readDisposedHeroes();
  85. readMapOptions();
  86. readAllowedArtifacts();
  87. readAllowedSpellsAbilities();
  88. readRumors();
  89. readPredefinedHeroes();
  90. readTerrain();
  91. readObjectTemplates();
  92. readObjects();
  93. readEvents();
  94. map->calculateGuardingGreaturePositions();
  95. afterRead();
  96. }
  97. void CMapLoaderH3M::readHeader()
  98. {
  99. // Map version
  100. mapHeader->version = static_cast<EMapFormat>(reader->readUInt32());
  101. if(mapHeader->version == EMapFormat::HOTA)
  102. {
  103. uint32_t hotaVersion = reader->readUInt32();
  104. features = MapFormatFeaturesH3M::find(mapHeader->version, hotaVersion);
  105. reader->setFormatLevel(features);
  106. if(hotaVersion > 0)
  107. {
  108. reader->skipZero(1);
  109. //TODO: HotA
  110. bool isArenaMap = reader->readBool();
  111. if (isArenaMap)
  112. {
  113. logGlobal->warn("Map '%s': Arena maps are not supported!", mapName);
  114. }
  115. }
  116. if(hotaVersion > 1)
  117. {
  118. [[maybe_unused]] uint8_t unknown = reader->readUInt32();
  119. assert(unknown == 12);
  120. }
  121. }
  122. else
  123. {
  124. features = MapFormatFeaturesH3M::find(mapHeader->version, 0);
  125. reader->setFormatLevel(features);
  126. }
  127. MapIdentifiersH3M identifierMapper;
  128. if (features.levelROE)
  129. identifierMapper.loadMapping(VLC->settings()->getValue(EGameSettings::MAP_FORMAT_RESTORATION_OF_ERATHIA));
  130. if (features.levelAB)
  131. identifierMapper.loadMapping(VLC->settings()->getValue(EGameSettings::MAP_FORMAT_ARMAGEDDONS_BLADE));
  132. if (features.levelSOD)
  133. identifierMapper.loadMapping(VLC->settings()->getValue(EGameSettings::MAP_FORMAT_SHADOW_OF_DEATH));
  134. if (features.levelWOG)
  135. identifierMapper.loadMapping(VLC->settings()->getValue(EGameSettings::MAP_FORMAT_IN_THE_WAKE_OF_GODS));
  136. if (features.levelHOTA0)
  137. identifierMapper.loadMapping(VLC->settings()->getValue(EGameSettings::MAP_FORMAT_HORN_OF_THE_ABYSS));
  138. reader->setIdentifierRemapper(identifierMapper);
  139. // include basic mod
  140. if(mapHeader->version == EMapFormat::WOG)
  141. mapHeader->mods["wake-of-gods"];
  142. // Read map name, description, dimensions,...
  143. mapHeader->areAnyPlayers = reader->readBool();
  144. mapHeader->height = mapHeader->width = reader->readInt32();
  145. mapHeader->twoLevel = reader->readBool();
  146. mapHeader->name = readLocalizedString("header.name");
  147. mapHeader->description = readLocalizedString("header.description");
  148. mapHeader->difficulty = reader->readInt8();
  149. if(features.levelAB)
  150. mapHeader->levelLimit = reader->readUInt8();
  151. else
  152. mapHeader->levelLimit = 0;
  153. readPlayerInfo();
  154. readVictoryLossConditions();
  155. readTeamInfo();
  156. readAllowedHeroes();
  157. }
  158. void CMapLoaderH3M::readPlayerInfo()
  159. {
  160. for(int i = 0; i < mapHeader->players.size(); ++i)
  161. {
  162. auto & playerInfo = mapHeader->players[i];
  163. playerInfo.canHumanPlay = reader->readBool();
  164. playerInfo.canComputerPlay = reader->readBool();
  165. // If nobody can play with this player - skip loading of these properties
  166. if((!(playerInfo.canHumanPlay || playerInfo.canComputerPlay)))
  167. {
  168. if(features.levelROE)
  169. reader->skipUnused(6);
  170. if(features.levelAB)
  171. reader->skipUnused(6);
  172. if(features.levelSOD)
  173. reader->skipUnused(1);
  174. continue;
  175. }
  176. playerInfo.aiTactic = static_cast<EAiTactic::EAiTactic>(reader->readUInt8());
  177. if(features.levelSOD)
  178. reader->skipUnused(1); //TODO: check meaning?
  179. std::set<FactionID> allowedFactions;
  180. reader->readBitmaskFactions(allowedFactions, false);
  181. const bool isFactionRandom = playerInfo.isFactionRandom = reader->readBool();
  182. const bool allFactionsAllowed = isFactionRandom && allowedFactions.size() == features.factionsCount;
  183. if(!allFactionsAllowed)
  184. playerInfo.allowedFactions = allowedFactions;
  185. playerInfo.hasMainTown = reader->readBool();
  186. if(playerInfo.hasMainTown)
  187. {
  188. if(features.levelAB)
  189. {
  190. playerInfo.generateHeroAtMainTown = reader->readBool();
  191. reader->skipUnused(1); //TODO: check meaning?
  192. }
  193. else
  194. {
  195. playerInfo.generateHeroAtMainTown = true;
  196. }
  197. playerInfo.posOfMainTown = reader->readInt3();
  198. }
  199. playerInfo.hasRandomHero = reader->readBool();
  200. playerInfo.mainCustomHeroId = reader->readHero().getNum();
  201. if(playerInfo.mainCustomHeroId != -1)
  202. {
  203. playerInfo.mainCustomHeroPortrait = reader->readHero().getNum();
  204. playerInfo.mainCustomHeroName = readLocalizedString(TextIdentifier("header", "player", i, "mainHeroName"));
  205. }
  206. if(features.levelAB)
  207. {
  208. reader->skipUnused(1); //TODO: check meaning?
  209. uint32_t heroCount = reader->readUInt32();
  210. for(int pp = 0; pp < heroCount; ++pp)
  211. {
  212. SHeroName vv;
  213. vv.heroId = reader->readUInt8();
  214. vv.heroName = readLocalizedString(TextIdentifier("header", "heroNames", vv.heroId));
  215. playerInfo.heroesNames.push_back(vv);
  216. }
  217. }
  218. }
  219. }
  220. enum class EVictoryConditionType : uint8_t
  221. {
  222. ARTIFACT = 0,
  223. GATHERTROOP = 1,
  224. GATHERRESOURCE = 2,
  225. BUILDCITY = 3,
  226. BUILDGRAIL = 4,
  227. BEATHERO = 5,
  228. CAPTURECITY = 6,
  229. BEATMONSTER = 7,
  230. TAKEDWELLINGS = 8,
  231. TAKEMINES = 9,
  232. TRANSPORTITEM = 10,
  233. HOTA_ELIMINATE_ALL_MONSTERS = 11,
  234. HOTA_SURVIVE_FOR_DAYS = 12,
  235. WINSTANDARD = 255
  236. };
  237. enum class ELossConditionType : uint8_t
  238. {
  239. LOSSCASTLE = 0,
  240. LOSSHERO = 1,
  241. TIMEEXPIRES = 2,
  242. LOSSSTANDARD = 255
  243. };
  244. void CMapLoaderH3M::readVictoryLossConditions()
  245. {
  246. mapHeader->triggeredEvents.clear();
  247. auto vicCondition = static_cast<EVictoryConditionType>(reader->readUInt8());
  248. EventCondition victoryCondition(EventCondition::STANDARD_WIN);
  249. EventCondition defeatCondition(EventCondition::DAYS_WITHOUT_TOWN);
  250. defeatCondition.value = 7;
  251. TriggeredEvent standardVictory;
  252. standardVictory.effect.type = EventEffect::VICTORY;
  253. standardVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[5];
  254. standardVictory.identifier = "standardVictory";
  255. standardVictory.description.clear(); // TODO: display in quest window
  256. standardVictory.onFulfill = VLC->generaltexth->allTexts[659];
  257. standardVictory.trigger = EventExpression(victoryCondition);
  258. TriggeredEvent standardDefeat;
  259. standardDefeat.effect.type = EventEffect::DEFEAT;
  260. standardDefeat.effect.toOtherMessage = VLC->generaltexth->allTexts[8];
  261. standardDefeat.identifier = "standardDefeat";
  262. standardDefeat.description.clear(); // TODO: display in quest window
  263. standardDefeat.onFulfill = VLC->generaltexth->allTexts[7];
  264. standardDefeat.trigger = EventExpression(defeatCondition);
  265. // Specific victory conditions
  266. if(vicCondition == EVictoryConditionType::WINSTANDARD)
  267. {
  268. // create normal condition
  269. mapHeader->triggeredEvents.push_back(standardVictory);
  270. mapHeader->victoryIconIndex = 11;
  271. mapHeader->victoryMessage = VLC->generaltexth->victoryConditions[0];
  272. }
  273. else
  274. {
  275. TriggeredEvent specialVictory;
  276. specialVictory.effect.type = EventEffect::VICTORY;
  277. specialVictory.identifier = "specialVictory";
  278. specialVictory.description.clear(); // TODO: display in quest window
  279. mapHeader->victoryIconIndex = static_cast<ui16>(vicCondition);
  280. mapHeader->victoryMessage = VLC->generaltexth->victoryConditions[static_cast<size_t>(vicCondition) + 1];
  281. bool allowNormalVictory = reader->readBool();
  282. bool appliesToAI = reader->readBool();
  283. if(allowNormalVictory)
  284. {
  285. size_t playersOnMap = boost::range::count_if(
  286. mapHeader->players,
  287. [](const PlayerInfo & info)
  288. {
  289. return info.canAnyonePlay();
  290. }
  291. );
  292. if(playersOnMap == 1)
  293. {
  294. logGlobal->warn("Map %s: Only one player exists, but normal victory allowed!", mapName);
  295. allowNormalVictory = false; // makes sense? Not much. Works as H3? Yes!
  296. }
  297. }
  298. switch(vicCondition)
  299. {
  300. case EVictoryConditionType::ARTIFACT:
  301. {
  302. EventCondition cond(EventCondition::HAVE_ARTIFACT);
  303. cond.objectType = reader->readArtifact();
  304. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[281];
  305. specialVictory.onFulfill = VLC->generaltexth->allTexts[280];
  306. specialVictory.trigger = EventExpression(cond);
  307. break;
  308. }
  309. case EVictoryConditionType::GATHERTROOP:
  310. {
  311. EventCondition cond(EventCondition::HAVE_CREATURES);
  312. cond.objectType = reader->readCreature();
  313. cond.value = reader->readInt32();
  314. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[277];
  315. specialVictory.onFulfill = VLC->generaltexth->allTexts[276];
  316. specialVictory.trigger = EventExpression(cond);
  317. break;
  318. }
  319. case EVictoryConditionType::GATHERRESOURCE:
  320. {
  321. EventCondition cond(EventCondition::HAVE_RESOURCES);
  322. cond.objectType = reader->readUInt8();
  323. cond.value = reader->readInt32();
  324. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[279];
  325. specialVictory.onFulfill = VLC->generaltexth->allTexts[278];
  326. specialVictory.trigger = EventExpression(cond);
  327. break;
  328. }
  329. case EVictoryConditionType::BUILDCITY:
  330. {
  331. EventExpression::OperatorAll oper;
  332. EventCondition cond(EventCondition::HAVE_BUILDING);
  333. cond.position = reader->readInt3();
  334. cond.objectType = BuildingID::TOWN_HALL + reader->readUInt8();
  335. oper.expressions.emplace_back(cond);
  336. cond.objectType = BuildingID::FORT + reader->readUInt8();
  337. oper.expressions.emplace_back(cond);
  338. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[283];
  339. specialVictory.onFulfill = VLC->generaltexth->allTexts[282];
  340. specialVictory.trigger = EventExpression(oper);
  341. break;
  342. }
  343. case EVictoryConditionType::BUILDGRAIL:
  344. {
  345. EventCondition cond(EventCondition::HAVE_BUILDING);
  346. cond.objectType = BuildingID::GRAIL;
  347. cond.position = reader->readInt3();
  348. if(cond.position.z > 2)
  349. cond.position = int3(-1, -1, -1);
  350. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[285];
  351. specialVictory.onFulfill = VLC->generaltexth->allTexts[284];
  352. specialVictory.trigger = EventExpression(cond);
  353. break;
  354. }
  355. case EVictoryConditionType::BEATHERO:
  356. {
  357. EventCondition cond(EventCondition::DESTROY);
  358. cond.objectType = Obj::HERO;
  359. cond.position = reader->readInt3();
  360. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[253];
  361. specialVictory.onFulfill = VLC->generaltexth->allTexts[252];
  362. specialVictory.trigger = EventExpression(cond);
  363. break;
  364. }
  365. case EVictoryConditionType::CAPTURECITY:
  366. {
  367. EventCondition cond(EventCondition::CONTROL);
  368. cond.objectType = Obj::TOWN;
  369. cond.position = reader->readInt3();
  370. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[250];
  371. specialVictory.onFulfill = VLC->generaltexth->allTexts[249];
  372. specialVictory.trigger = EventExpression(cond);
  373. break;
  374. }
  375. case EVictoryConditionType::BEATMONSTER:
  376. {
  377. EventCondition cond(EventCondition::DESTROY);
  378. cond.objectType = Obj::MONSTER;
  379. cond.position = reader->readInt3();
  380. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[287];
  381. specialVictory.onFulfill = VLC->generaltexth->allTexts[286];
  382. specialVictory.trigger = EventExpression(cond);
  383. break;
  384. }
  385. case EVictoryConditionType::TAKEDWELLINGS:
  386. {
  387. EventExpression::OperatorAll oper;
  388. oper.expressions.emplace_back(EventCondition(EventCondition::CONTROL, 0, Obj::CREATURE_GENERATOR1));
  389. oper.expressions.emplace_back(EventCondition(EventCondition::CONTROL, 0, Obj::CREATURE_GENERATOR4));
  390. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[289];
  391. specialVictory.onFulfill = VLC->generaltexth->allTexts[288];
  392. specialVictory.trigger = EventExpression(oper);
  393. break;
  394. }
  395. case EVictoryConditionType::TAKEMINES:
  396. {
  397. EventCondition cond(EventCondition::CONTROL);
  398. cond.objectType = Obj::MINE;
  399. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[291];
  400. specialVictory.onFulfill = VLC->generaltexth->allTexts[290];
  401. specialVictory.trigger = EventExpression(cond);
  402. break;
  403. }
  404. case EVictoryConditionType::TRANSPORTITEM:
  405. {
  406. EventCondition cond(EventCondition::TRANSPORT);
  407. cond.objectType = reader->readUInt8();
  408. cond.position = reader->readInt3();
  409. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[293];
  410. specialVictory.onFulfill = VLC->generaltexth->allTexts[292];
  411. specialVictory.trigger = EventExpression(cond);
  412. break;
  413. }
  414. case EVictoryConditionType::HOTA_ELIMINATE_ALL_MONSTERS:
  415. //TODO: HOTA
  416. logGlobal->warn("Map '%s': Victory condition 'Eliminate all monsters' is not implemented!", mapName);
  417. break;
  418. case EVictoryConditionType::HOTA_SURVIVE_FOR_DAYS:
  419. {
  420. //TODO: HOTA
  421. uint32_t daysToSurvive = reader->readUInt32(); // Number of days
  422. logGlobal->warn("Map '%s': Victory condition 'Survive for %d days' is not implemented!", mapName, daysToSurvive);
  423. break;
  424. }
  425. default:
  426. assert(0);
  427. }
  428. // if condition is human-only turn it into following construction: AllOf(human, condition)
  429. if(!appliesToAI)
  430. {
  431. EventExpression::OperatorAll oper;
  432. EventCondition notAI(EventCondition::IS_HUMAN);
  433. notAI.value = 1;
  434. oper.expressions.emplace_back(notAI);
  435. oper.expressions.push_back(specialVictory.trigger.get());
  436. specialVictory.trigger = EventExpression(oper);
  437. }
  438. // if normal victory allowed - add one more quest
  439. if(allowNormalVictory)
  440. {
  441. mapHeader->victoryMessage += " / ";
  442. mapHeader->victoryMessage += VLC->generaltexth->victoryConditions[0];
  443. mapHeader->triggeredEvents.push_back(standardVictory);
  444. }
  445. mapHeader->triggeredEvents.push_back(specialVictory);
  446. }
  447. // Read loss conditions
  448. auto lossCond = static_cast<ELossConditionType>(reader->readUInt8());
  449. if(lossCond == ELossConditionType::LOSSSTANDARD)
  450. {
  451. mapHeader->defeatIconIndex = 3;
  452. mapHeader->defeatMessage = VLC->generaltexth->lossCondtions[0];
  453. }
  454. else
  455. {
  456. TriggeredEvent specialDefeat;
  457. specialDefeat.effect.type = EventEffect::DEFEAT;
  458. specialDefeat.effect.toOtherMessage = VLC->generaltexth->allTexts[5];
  459. specialDefeat.identifier = "specialDefeat";
  460. specialDefeat.description.clear(); // TODO: display in quest window
  461. mapHeader->defeatIconIndex = static_cast<ui16>(lossCond);
  462. mapHeader->defeatMessage = VLC->generaltexth->lossCondtions[static_cast<size_t>(lossCond) + 1];
  463. switch(lossCond)
  464. {
  465. case ELossConditionType::LOSSCASTLE:
  466. {
  467. EventExpression::OperatorNone noneOf;
  468. EventCondition cond(EventCondition::CONTROL);
  469. cond.objectType = Obj::TOWN;
  470. cond.position = reader->readInt3();
  471. noneOf.expressions.emplace_back(cond);
  472. specialDefeat.onFulfill = VLC->generaltexth->allTexts[251];
  473. specialDefeat.trigger = EventExpression(noneOf);
  474. break;
  475. }
  476. case ELossConditionType::LOSSHERO:
  477. {
  478. EventExpression::OperatorNone noneOf;
  479. EventCondition cond(EventCondition::CONTROL);
  480. cond.objectType = Obj::HERO;
  481. cond.position = reader->readInt3();
  482. noneOf.expressions.emplace_back(cond);
  483. specialDefeat.onFulfill = VLC->generaltexth->allTexts[253];
  484. specialDefeat.trigger = EventExpression(noneOf);
  485. break;
  486. }
  487. case ELossConditionType::TIMEEXPIRES:
  488. {
  489. EventCondition cond(EventCondition::DAYS_PASSED);
  490. cond.value = reader->readUInt16();
  491. specialDefeat.onFulfill = VLC->generaltexth->allTexts[254];
  492. specialDefeat.trigger = EventExpression(cond);
  493. break;
  494. }
  495. }
  496. // turn simple loss condition into complete one that can be evaluated later:
  497. // - any of :
  498. // - days without town: 7
  499. // - all of:
  500. // - is human
  501. // - (expression)
  502. EventExpression::OperatorAll allOf;
  503. EventCondition isHuman(EventCondition::IS_HUMAN);
  504. isHuman.value = 1;
  505. allOf.expressions.emplace_back(isHuman);
  506. allOf.expressions.push_back(specialDefeat.trigger.get());
  507. specialDefeat.trigger = EventExpression(allOf);
  508. mapHeader->triggeredEvents.push_back(specialDefeat);
  509. }
  510. mapHeader->triggeredEvents.push_back(standardDefeat);
  511. }
  512. void CMapLoaderH3M::readTeamInfo()
  513. {
  514. mapHeader->howManyTeams = reader->readUInt8();
  515. if(mapHeader->howManyTeams > 0)
  516. {
  517. // Teams
  518. for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; ++i)
  519. mapHeader->players[i].team = TeamID(reader->readUInt8());
  520. }
  521. else
  522. {
  523. // No alliances
  524. for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
  525. if(mapHeader->players[i].canComputerPlay || mapHeader->players[i].canHumanPlay)
  526. mapHeader->players[i].team = TeamID(mapHeader->howManyTeams++);
  527. }
  528. }
  529. void CMapLoaderH3M::readAllowedHeroes()
  530. {
  531. mapHeader->allowedHeroes = VLC->heroh->getDefaultAllowed();
  532. if(features.levelHOTA0)
  533. reader->readBitmaskHeroesSized(mapHeader->allowedHeroes, false);
  534. else
  535. reader->readBitmaskHeroes(mapHeader->allowedHeroes, false);
  536. //TODO: unknown value. Check meaning? Only present in campaign maps.
  537. if(features.levelAB)
  538. {
  539. uint32_t placeholdersQty = reader->readUInt32();
  540. reader->skipUnused(placeholdersQty * 1);
  541. }
  542. }
  543. void CMapLoaderH3M::readDisposedHeroes()
  544. {
  545. // Reading disposed heroes (20 bytes)
  546. if(features.levelSOD)
  547. {
  548. ui8 disp = reader->readUInt8();
  549. map->disposedHeroes.resize(disp);
  550. for(int g = 0; g < disp; ++g)
  551. {
  552. map->disposedHeroes[g].heroId = reader->readHero().getNum();
  553. map->disposedHeroes[g].portrait = reader->readHero().getNum();
  554. map->disposedHeroes[g].name = readLocalizedString(TextIdentifier("header", "heroes", map->disposedHeroes[g].heroId));
  555. map->disposedHeroes[g].players = reader->readUInt8();
  556. }
  557. }
  558. }
  559. void CMapLoaderH3M::readMapOptions()
  560. {
  561. //omitting NULLS
  562. reader->skipZero(31);
  563. if(features.levelHOTA0)
  564. {
  565. //TODO: HotA
  566. bool allowSpecialMonths = reader->readBool();
  567. if(!allowSpecialMonths)
  568. logGlobal->warn("Map '%s': Option 'allow special months' is not implemented!", mapName);
  569. reader->skipZero(3);
  570. }
  571. if(features.levelHOTA1)
  572. {
  573. // Unknown, may be another "sized bitmap", e.g
  574. // 4 bytes - size of bitmap (16)
  575. // 2 bytes - bitmap data (16 bits / 2 bytes)
  576. [[maybe_unused]] uint8_t unknownConstant = reader->readUInt8();
  577. assert(unknownConstant == 16);
  578. reader->skipZero(5);
  579. }
  580. if(features.levelHOTA3)
  581. {
  582. //TODO: HotA
  583. int32_t roundLimit = reader->readInt32();
  584. if(roundLimit != -1)
  585. logGlobal->warn("Map '%s': roundLimit of %d is not implemented!", mapName, roundLimit);
  586. }
  587. }
  588. void CMapLoaderH3M::readAllowedArtifacts()
  589. {
  590. map->allowedArtifact = VLC->arth->getDefaultAllowed();
  591. if(features.levelAB)
  592. {
  593. if(features.levelHOTA0)
  594. reader->readBitmaskArtifactsSized(map->allowedArtifact, true);
  595. else
  596. reader->readBitmaskArtifacts(map->allowedArtifact, true);
  597. }
  598. // ban combo artifacts
  599. if(!features.levelSOD)
  600. {
  601. for(CArtifact * artifact : VLC->arth->objects)
  602. if(artifact->constituents)
  603. map->allowedArtifact[artifact->getId()] = false;
  604. }
  605. if(!features.levelAB)
  606. {
  607. map->allowedArtifact[ArtifactID::VIAL_OF_DRAGON_BLOOD] = false;
  608. map->allowedArtifact[ArtifactID::ARMAGEDDONS_BLADE] = false;
  609. }
  610. // Messy, but needed
  611. for(TriggeredEvent & event : map->triggeredEvents)
  612. {
  613. auto patcher = [&](EventCondition cond) -> EventExpression::Variant
  614. {
  615. if(cond.condition == EventCondition::HAVE_ARTIFACT || cond.condition == EventCondition::TRANSPORT)
  616. {
  617. map->allowedArtifact[cond.objectType] = false;
  618. }
  619. return cond;
  620. };
  621. event.trigger = event.trigger.morph(patcher);
  622. }
  623. }
  624. void CMapLoaderH3M::readAllowedSpellsAbilities()
  625. {
  626. map->allowedSpell = VLC->spellh->getDefaultAllowed();
  627. map->allowedAbilities = VLC->skillh->getDefaultAllowed();
  628. if(features.levelSOD)
  629. {
  630. reader->readBitmaskSpells(map->allowedSpell, true);
  631. reader->readBitmaskSkills(map->allowedAbilities, true);
  632. }
  633. }
  634. void CMapLoaderH3M::readRumors()
  635. {
  636. uint32_t rumorsCount = reader->readUInt32();
  637. assert(rumorsCount < 1000); // sanity check
  638. for(int it = 0; it < rumorsCount; it++)
  639. {
  640. Rumor ourRumor;
  641. ourRumor.name = readBasicString();
  642. ourRumor.text = readLocalizedString(TextIdentifier("header", "rumor", it, "text"));
  643. map->rumors.push_back(ourRumor);
  644. }
  645. }
  646. void CMapLoaderH3M::readPredefinedHeroes()
  647. {
  648. if(!features.levelSOD)
  649. return;
  650. uint32_t heroesCount = features.heroesCount;
  651. if(features.levelHOTA0)
  652. heroesCount = reader->readUInt32();
  653. assert(heroesCount <= features.heroesCount);
  654. for(int heroID = 0; heroID < heroesCount; heroID++)
  655. {
  656. bool custom = reader->readBool();
  657. if(!custom)
  658. continue;
  659. auto * hero = new CGHeroInstance();
  660. hero->ID = Obj::HERO;
  661. hero->subID = heroID;
  662. bool hasExp = reader->readBool();
  663. if(hasExp)
  664. {
  665. hero->exp = reader->readUInt32();
  666. }
  667. else
  668. {
  669. hero->exp = 0;
  670. }
  671. bool hasSecSkills = reader->readBool();
  672. if(hasSecSkills)
  673. {
  674. uint32_t howMany = reader->readUInt32();
  675. hero->secSkills.resize(howMany);
  676. for(int yy = 0; yy < howMany; ++yy)
  677. {
  678. hero->secSkills[yy].first = reader->readSkill();
  679. hero->secSkills[yy].second = reader->readUInt8();
  680. }
  681. }
  682. loadArtifactsOfHero(hero);
  683. bool hasCustomBio = reader->readBool();
  684. if(hasCustomBio)
  685. hero->biographyCustom = readLocalizedString(TextIdentifier("heroes", heroID, "biography"));
  686. // 0xFF is default, 00 male, 01 female
  687. hero->gender = static_cast<EHeroGender>(reader->readUInt8());
  688. assert(hero->gender == EHeroGender::MALE || hero->gender == EHeroGender::FEMALE || hero->gender == EHeroGender::DEFAULT);
  689. bool hasCustomSpells = reader->readBool();
  690. if(hasCustomSpells)
  691. reader->readBitmaskSpells(hero->spells, false);
  692. bool hasCustomPrimSkills = reader->readBool();
  693. if(hasCustomPrimSkills)
  694. {
  695. for(int skillID = 0; skillID < GameConstants::PRIMARY_SKILLS; skillID++)
  696. {
  697. hero->pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(skillID), reader->readUInt8());
  698. }
  699. }
  700. map->predefinedHeroes.emplace_back(hero);
  701. }
  702. }
  703. void CMapLoaderH3M::loadArtifactsOfHero(CGHeroInstance * hero)
  704. {
  705. bool hasArtSet = reader->readBool();
  706. // True if artifact set is not default (hero has some artifacts)
  707. if(!hasArtSet)
  708. return;
  709. if(!hero->artifactsWorn.empty() || !hero->artifactsInBackpack.empty())
  710. {
  711. logGlobal->warn("Hero %s at %s has set artifacts twice (in map properties and on adventure map instance). Using the latter set...", hero->getNameTranslated(), hero->pos.toString());
  712. hero->artifactsInBackpack.clear();
  713. while(!hero->artifactsWorn.empty())
  714. hero->eraseArtSlot(hero->artifactsWorn.begin()->first);
  715. }
  716. for(int i = 0; i < features.artifactSlotsCount; i++)
  717. loadArtifactToSlot(hero, i);
  718. // bag artifacts
  719. // number of artifacts in hero's bag
  720. int amount = reader->readUInt16();
  721. for(int i = 0; i < amount; ++i)
  722. {
  723. loadArtifactToSlot(hero, GameConstants::BACKPACK_START + static_cast<int>(hero->artifactsInBackpack.size()));
  724. }
  725. }
  726. bool CMapLoaderH3M::loadArtifactToSlot(CGHeroInstance * hero, int slot)
  727. {
  728. ArtifactID artifactID = reader->readArtifact();
  729. if(artifactID == ArtifactID::NONE)
  730. return false;
  731. const Artifact * art = artifactID.toArtifact(VLC->artifacts());
  732. if(!art)
  733. {
  734. logGlobal->warn("Map '%s': Invalid artifact in hero's backpack, ignoring...", mapName);
  735. return false;
  736. }
  737. if(art->isBig() && slot >= GameConstants::BACKPACK_START)
  738. {
  739. logGlobal->warn("Map '%s': A big artifact (war machine) in hero's backpack, ignoring...", mapName);
  740. return false;
  741. }
  742. // H3 bug workaround - Enemy hero on 3rd scenario of Good1.h3c campaign ("Long Live The Queen")
  743. // He has Shackles of War (normally - MISC slot artifact) in LEFT_HAND slot set in editor
  744. // Artifact seems to be missing in game, so skip artifacts that don't fit target slot
  745. auto * artifact = CArtifactInstance::createArtifact(map, artifactID);
  746. auto artifactPos = ArtifactPosition(slot);
  747. if(artifact->canBePutAt(ArtifactLocation(hero, artifactPos)))
  748. {
  749. hero->putArtifact(artifactPos, artifact);
  750. }
  751. else
  752. {
  753. logGlobal->warn("Map '%s': Artifact '%s' can't be put at the slot %d", mapName, artifact->artType->getNameTranslated(), slot);
  754. return false;
  755. }
  756. return true;
  757. }
  758. void CMapLoaderH3M::readTerrain()
  759. {
  760. map->initTerrain();
  761. // Read terrain
  762. int3 pos;
  763. for(pos.z = 0; pos.z < map->levels(); ++pos.z)
  764. {
  765. //OH3 format is [z][y][x]
  766. for(pos.y = 0; pos.y < map->height; pos.y++)
  767. {
  768. for(pos.x = 0; pos.x < map->width; pos.x++)
  769. {
  770. auto & tile = map->getTile(pos);
  771. tile.terType = VLC->terrainTypeHandler->getById(reader->readTerrain());
  772. tile.terView = reader->readUInt8();
  773. tile.riverType = VLC->riverTypeHandler->getById(reader->readRiver());
  774. tile.riverDir = reader->readUInt8();
  775. tile.roadType = VLC->roadTypeHandler->getById(reader->readRoad());
  776. tile.roadDir = reader->readUInt8();
  777. tile.extTileFlags = reader->readUInt8();
  778. tile.blocked = !tile.terType->isPassable();
  779. tile.visitable = false;
  780. assert(tile.terType->getId() != ETerrainId::NONE);
  781. }
  782. }
  783. }
  784. }
  785. void CMapLoaderH3M::readObjectTemplates()
  786. {
  787. uint32_t defAmount = reader->readUInt32();
  788. templates.reserve(defAmount);
  789. // Read custom defs
  790. for(int defID = 0; defID < defAmount; ++defID)
  791. {
  792. auto tmpl = reader->readObjectTemplate();
  793. templates.push_back(tmpl);
  794. if (!CResourceHandler::get()->existsResource(ResourceID( "SPRITES/" + tmpl->animationFile, EResType::ANIMATION)))
  795. logMod->warn("Template animation %s of type (%d %d) is missing!", tmpl->animationFile, tmpl->id, tmpl->subid );
  796. }
  797. }
  798. CGObjectInstance * CMapLoaderH3M::readEvent(const int3 & mapPosition)
  799. {
  800. auto * object = new CGEvent();
  801. readBoxContent(object, mapPosition);
  802. object->availableFor = reader->readUInt8();
  803. object->computerActivate = reader->readBool();
  804. object->removeAfterVisit = reader->readBool();
  805. reader->skipZero(4);
  806. if(features.levelHOTA3)
  807. object->humanActivate = reader->readBool();
  808. else
  809. object->humanActivate = true;
  810. return object;
  811. }
  812. CGObjectInstance * CMapLoaderH3M::readPandora(const int3 & mapPosition)
  813. {
  814. auto * object = new CGPandoraBox();
  815. readBoxContent(object, mapPosition);
  816. return object;
  817. }
  818. void CMapLoaderH3M::readBoxContent(CGPandoraBox * object, const int3 & mapPosition)
  819. {
  820. readMessageAndGuards(object->message, object, mapPosition);
  821. object->gainedExp = reader->readUInt32();
  822. object->manaDiff = reader->readInt32();
  823. object->moraleDiff = reader->readInt8();
  824. object->luckDiff = reader->readInt8();
  825. reader->readResourses(object->resources);
  826. object->primskills.resize(GameConstants::PRIMARY_SKILLS);
  827. for(int x = 0; x < GameConstants::PRIMARY_SKILLS; ++x)
  828. object->primskills[x] = static_cast<PrimarySkill::PrimarySkill>(reader->readUInt8());
  829. int gabn = reader->readUInt8(); //number of gained abilities
  830. for(int oo = 0; oo < gabn; ++oo)
  831. {
  832. object->abilities.emplace_back(reader->readSkill());
  833. object->abilityLevels.push_back(reader->readUInt8());
  834. }
  835. int gart = reader->readUInt8(); //number of gained artifacts
  836. for(int oo = 0; oo < gart; ++oo)
  837. object->artifacts.emplace_back(reader->readArtifact());
  838. int gspel = reader->readUInt8(); //number of gained spells
  839. for(int oo = 0; oo < gspel; ++oo)
  840. object->spells.emplace_back(reader->readSpell());
  841. int gcre = reader->readUInt8(); //number of gained creatures
  842. readCreatureSet(&object->creatures, gcre);
  843. reader->skipZero(8);
  844. }
  845. CGObjectInstance * CMapLoaderH3M::readMonster(const int3 & mapPosition, const ObjectInstanceID & objectInstanceID)
  846. {
  847. auto * object = new CGCreature();
  848. if(features.levelAB)
  849. {
  850. object->identifier = reader->readUInt32();
  851. map->questIdentifierToId[object->identifier] = objectInstanceID;
  852. }
  853. auto * hlp = new CStackInstance();
  854. hlp->count = reader->readUInt16();
  855. //type will be set during initialization
  856. object->putStack(SlotID(0), hlp);
  857. object->character = reader->readInt8();
  858. bool hasMessage = reader->readBool();
  859. if(hasMessage)
  860. {
  861. object->message = readLocalizedString(TextIdentifier("monster", mapPosition.x, mapPosition.y, mapPosition.z, "message"));
  862. reader->readResourses(object->resources);
  863. object->gainedArtifact = reader->readArtifact();
  864. }
  865. object->neverFlees = reader->readBool();
  866. object->notGrowingTeam = reader->readBool();
  867. reader->skipZero(2);
  868. if(features.levelHOTA3)
  869. {
  870. //TODO: HotA
  871. int32_t agressionExact = reader->readInt32(); // -1 = default, 1-10 = possible values range
  872. bool joinOnlyForMoney = reader->readBool(); // if true, monsters will only join for money
  873. int32_t joinPercent = reader->readInt32(); // 100 = default, percent of monsters that will join on succesfull agression check
  874. int32_t upgradedStack = reader->readInt32(); // Presence of upgraded stack, -1 = random, 0 = never, 1 = always
  875. int32_t stacksCount = reader->readInt32(); // TODO: check possible values. How many creature stacks will be present on battlefield, -1 = default
  876. if(agressionExact != -1 || joinOnlyForMoney || joinPercent != 100 || upgradedStack != -1 || stacksCount != -1)
  877. logGlobal->warn(
  878. "Map '%s': Wandering monsters %s settings %d %d %d %d %d are not implemeted!",
  879. mapName,
  880. mapPosition.toString(),
  881. agressionExact,
  882. int(joinOnlyForMoney),
  883. joinPercent,
  884. upgradedStack,
  885. stacksCount
  886. );
  887. }
  888. return object;
  889. }
  890. CGObjectInstance * CMapLoaderH3M::readSign(const int3 & mapPosition)
  891. {
  892. auto * object = new CGSignBottle();
  893. object->message = readLocalizedString(TextIdentifier("sign", mapPosition.x, mapPosition.y, mapPosition.z, "message"));
  894. reader->skipZero(4);
  895. return object;
  896. }
  897. CGObjectInstance * CMapLoaderH3M::readWitchHut()
  898. {
  899. auto * object = new CGWitchHut();
  900. // AB and later maps have allowed abilities defined in H3M
  901. if(features.levelAB)
  902. {
  903. reader->readBitmaskSkills(object->allowedAbilities, false);
  904. if(object->allowedAbilities.size() != 1)
  905. {
  906. auto defaultAllowed = VLC->skillh->getDefaultAllowed();
  907. for(int skillID = 0; skillID < VLC->skillh->size(); ++skillID)
  908. if(defaultAllowed[skillID])
  909. object->allowedAbilities.insert(SecondarySkill(skillID));
  910. }
  911. }
  912. return object;
  913. }
  914. CGObjectInstance * CMapLoaderH3M::readScholar()
  915. {
  916. auto * object = new CGScholar();
  917. object->bonusType = static_cast<CGScholar::EBonusType>(reader->readUInt8());
  918. object->bonusID = reader->readUInt8();
  919. reader->skipZero(6);
  920. return object;
  921. }
  922. CGObjectInstance * CMapLoaderH3M::readGarrison(const int3 & mapPosition)
  923. {
  924. auto * object = new CGGarrison();
  925. setOwnerAndValidate(mapPosition, object, reader->readPlayer32());
  926. readCreatureSet(object, 7);
  927. if(features.levelAB)
  928. object->removableUnits = reader->readBool();
  929. else
  930. object->removableUnits = true;
  931. reader->skipZero(8);
  932. return object;
  933. }
  934. CGObjectInstance * CMapLoaderH3M::readArtifact(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  935. {
  936. auto artID = ArtifactID::NONE; //random, set later
  937. int spellID = -1;
  938. auto * object = new CGArtifact();
  939. readMessageAndGuards(object->message, object, mapPosition);
  940. if(objectTemplate->id == Obj::SPELL_SCROLL)
  941. {
  942. spellID = reader->readSpell32();
  943. artID = ArtifactID::SPELL_SCROLL;
  944. }
  945. else if(objectTemplate->id == Obj::ARTIFACT)
  946. {
  947. //specific artifact
  948. artID = ArtifactID(objectTemplate->subid);
  949. }
  950. object->storedArtifact = CArtifactInstance::createArtifact(map, artID, spellID);
  951. return object;
  952. }
  953. CGObjectInstance * CMapLoaderH3M::readResource(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  954. {
  955. auto * object = new CGResource();
  956. readMessageAndGuards(object->message, object, mapPosition);
  957. object->amount = reader->readUInt32();
  958. if(objectTemplate->subid == GameResID(EGameResID::GOLD))
  959. {
  960. // Gold is multiplied by 100.
  961. object->amount *= 100;
  962. }
  963. reader->skipZero(4);
  964. return object;
  965. }
  966. CGObjectInstance * CMapLoaderH3M::readMine(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  967. {
  968. auto * object = new CGMine();
  969. if(objectTemplate->subid < 7)
  970. {
  971. setOwnerAndValidate(mapPosition, object, reader->readPlayer32());
  972. }
  973. else
  974. {
  975. object->setOwner(PlayerColor::NEUTRAL);
  976. reader->readBitmaskResources(object->abandonedMineResources, false);
  977. }
  978. return object;
  979. }
  980. CGObjectInstance * CMapLoaderH3M::readDwelling(const int3 & position)
  981. {
  982. auto * object = new CGDwelling();
  983. setOwnerAndValidate(position, object, reader->readPlayer32());
  984. return object;
  985. }
  986. CGObjectInstance * CMapLoaderH3M::readDwellingRandom(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  987. {
  988. auto * object = new CGDwelling();
  989. CSpecObjInfo * spec = nullptr;
  990. switch(objectTemplate->id)
  991. {
  992. case Obj::RANDOM_DWELLING:
  993. spec = new CCreGenLeveledCastleInfo();
  994. break;
  995. case Obj::RANDOM_DWELLING_LVL:
  996. spec = new CCreGenAsCastleInfo();
  997. break;
  998. case Obj::RANDOM_DWELLING_FACTION:
  999. spec = new CCreGenLeveledInfo();
  1000. break;
  1001. default:
  1002. throw std::runtime_error("Invalid random dwelling format");
  1003. }
  1004. spec->owner = object;
  1005. setOwnerAndValidate(mapPosition, object, reader->readPlayer32());
  1006. //216 and 217
  1007. if(auto * castleSpec = dynamic_cast<CCreGenAsCastleInfo *>(spec))
  1008. {
  1009. castleSpec->instanceId = "";
  1010. castleSpec->identifier = reader->readUInt32();
  1011. if(!castleSpec->identifier)
  1012. {
  1013. castleSpec->asCastle = false;
  1014. const int MASK_SIZE = 8;
  1015. ui8 mask[2];
  1016. mask[0] = reader->readUInt8();
  1017. mask[1] = reader->readUInt8();
  1018. castleSpec->allowedFactions.clear();
  1019. castleSpec->allowedFactions.resize(VLC->townh->size(), false);
  1020. for(int i = 0; i < MASK_SIZE; i++)
  1021. castleSpec->allowedFactions[i] = ((mask[0] & (1 << i)) > 0);
  1022. for(int i = 0; i < (GameConstants::F_NUMBER - MASK_SIZE); i++)
  1023. castleSpec->allowedFactions[i + MASK_SIZE] = ((mask[1] & (1 << i)) > 0);
  1024. }
  1025. else
  1026. {
  1027. castleSpec->asCastle = true;
  1028. }
  1029. }
  1030. //216 and 218
  1031. if(auto * lvlSpec = dynamic_cast<CCreGenLeveledInfo *>(spec))
  1032. {
  1033. lvlSpec->minLevel = std::max(reader->readUInt8(), static_cast<ui8>(1));
  1034. lvlSpec->maxLevel = std::min(reader->readUInt8(), static_cast<ui8>(7));
  1035. }
  1036. object->info = spec;
  1037. return object;
  1038. }
  1039. CGObjectInstance * CMapLoaderH3M::readShrine()
  1040. {
  1041. auto * object = new CGShrine();
  1042. object->spell = reader->readSpell32();
  1043. return object;
  1044. }
  1045. CGObjectInstance * CMapLoaderH3M::readHeroPlaceholder(const int3 & mapPosition)
  1046. {
  1047. auto * object = new CGHeroPlaceholder();
  1048. setOwnerAndValidate(mapPosition, object, reader->readPlayer());
  1049. HeroTypeID htid = reader->readHero(); //hero type id
  1050. object->subID = htid.getNum();
  1051. if(htid.getNum() == -1)
  1052. {
  1053. object->power = reader->readUInt8();
  1054. logGlobal->debug("Hero placeholder: by power at %s", mapPosition.toString());
  1055. }
  1056. else
  1057. {
  1058. object->power = 0;
  1059. logGlobal->debug("Hero placeholder: %s at %s", VLC->heroh->getById(htid)->getNameTranslated(), mapPosition.toString());
  1060. }
  1061. return object;
  1062. }
  1063. CGObjectInstance * CMapLoaderH3M::readGrail(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1064. {
  1065. if (objectTemplate->subid < 1000)
  1066. {
  1067. map->grailPos = mapPosition;
  1068. map->grailRadius = reader->readInt32();
  1069. }
  1070. else
  1071. {
  1072. // Battle location for arena mode in HotA
  1073. logGlobal->warn("Map '%s': Arena mode is not supported!", mapName);
  1074. }
  1075. return nullptr;
  1076. }
  1077. CGObjectInstance * CMapLoaderH3M::readGeneric(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1078. {
  1079. if(VLC->objtypeh->knownSubObjects(objectTemplate->id).count(objectTemplate->subid))
  1080. return VLC->objtypeh->getHandlerFor(objectTemplate->id, objectTemplate->subid)->create(objectTemplate);
  1081. logGlobal->warn("Map '%s': Unrecognized object %d:%d ('%s') at %s found!", mapName, objectTemplate->id.toEnum(), objectTemplate->subid, objectTemplate->animationFile, mapPosition.toString());
  1082. return new CGObjectInstance();
  1083. }
  1084. CGObjectInstance * CMapLoaderH3M::readPyramid(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1085. {
  1086. if(objectTemplate->subid == 0)
  1087. return new CBank();
  1088. return new CGObjectInstance();
  1089. }
  1090. CGObjectInstance * CMapLoaderH3M::readQuestGuard(const int3 & mapPosition)
  1091. {
  1092. auto * guard = new CGQuestGuard();
  1093. readQuest(guard, mapPosition);
  1094. return guard;
  1095. }
  1096. CGObjectInstance * CMapLoaderH3M::readShipyard(const int3 & mapPosition)
  1097. {
  1098. auto * object = new CGShipyard();
  1099. setOwnerAndValidate(mapPosition, object, reader->readPlayer32());
  1100. return object;
  1101. }
  1102. CGObjectInstance * CMapLoaderH3M::readBorderGuard()
  1103. {
  1104. return new CGBorderGuard();
  1105. }
  1106. CGObjectInstance * CMapLoaderH3M::readBorderGate(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1107. {
  1108. if(objectTemplate->subid < 1000)
  1109. return new CGBorderGate();
  1110. //TODO: HotA - grave has same ID as border gate? WTF?
  1111. if(objectTemplate->subid == 1001)
  1112. return new CGObjectInstance();
  1113. logGlobal->warn("Map '%s: Quest gates at %s are not implemented!", mapName, mapPosition.toString());
  1114. return readQuestGuard(mapPosition);
  1115. }
  1116. CGObjectInstance * CMapLoaderH3M::readLighthouse(const int3 & mapPosition)
  1117. {
  1118. auto * object = new CGLighthouse();
  1119. setOwnerAndValidate(mapPosition, object, reader->readPlayer32());
  1120. return object;
  1121. }
  1122. CGObjectInstance * CMapLoaderH3M::readBank(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1123. {
  1124. if(features.levelHOTA3)
  1125. {
  1126. //TODO: HotA
  1127. // index of guards preset. -1 = random, 0-4 = index of possible guards settings
  1128. int32_t guardsPresetIndex = reader->readInt32();
  1129. // presence of upgraded stack: -1 = random, 0 = never, 1 = always
  1130. int8_t upgradedStackPresence = reader->readInt8();
  1131. assert(vstd::iswithin(guardsPresetIndex, -1, 4));
  1132. assert(vstd::iswithin(upgradedStackPresence, -1, 1));
  1133. // list of possible artifacts in reward
  1134. // - if list is empty, artifacts are either not present in reward or random
  1135. // - if non-empty, then list always have same number of elements as number of artifacts in bank
  1136. // - ArtifactID::NONE indictates random artifact, other values indicate artifact that should be used as reward
  1137. std::vector<ArtifactID> artifacts;
  1138. int artNumber = reader->readUInt32();
  1139. for(int yy = 0; yy < artNumber; ++yy)
  1140. {
  1141. artifacts.push_back(reader->readArtifact32());
  1142. }
  1143. if(guardsPresetIndex != -1 || upgradedStackPresence != -1 || !artifacts.empty())
  1144. logGlobal->warn(
  1145. "Map '%s: creature bank at %s settings %d %d %d are not implemented!",
  1146. mapName,
  1147. mapPosition.toString(),
  1148. guardsPresetIndex,
  1149. int(upgradedStackPresence),
  1150. artifacts.size()
  1151. );
  1152. }
  1153. return readGeneric(mapPosition, objectTemplate);
  1154. }
  1155. CGObjectInstance * CMapLoaderH3M::readObject(std::shared_ptr<const ObjectTemplate> objectTemplate, const int3 & mapPosition, const ObjectInstanceID & objectInstanceID)
  1156. {
  1157. switch(objectTemplate->id)
  1158. {
  1159. case Obj::EVENT:
  1160. return readEvent(mapPosition);
  1161. case Obj::HERO:
  1162. case Obj::RANDOM_HERO:
  1163. case Obj::PRISON:
  1164. return readHero(mapPosition, objectInstanceID);
  1165. case Obj::MONSTER:
  1166. case Obj::RANDOM_MONSTER:
  1167. case Obj::RANDOM_MONSTER_L1:
  1168. case Obj::RANDOM_MONSTER_L2:
  1169. case Obj::RANDOM_MONSTER_L3:
  1170. case Obj::RANDOM_MONSTER_L4:
  1171. case Obj::RANDOM_MONSTER_L5:
  1172. case Obj::RANDOM_MONSTER_L6:
  1173. case Obj::RANDOM_MONSTER_L7:
  1174. return readMonster(mapPosition, objectInstanceID);
  1175. case Obj::OCEAN_BOTTLE:
  1176. case Obj::SIGN:
  1177. return readSign(mapPosition);
  1178. case Obj::SEER_HUT:
  1179. return readSeerHut(mapPosition);
  1180. case Obj::WITCH_HUT:
  1181. return readWitchHut();
  1182. case Obj::SCHOLAR:
  1183. return readScholar();
  1184. case Obj::GARRISON:
  1185. case Obj::GARRISON2:
  1186. return readGarrison(mapPosition);
  1187. case Obj::ARTIFACT:
  1188. case Obj::RANDOM_ART:
  1189. case Obj::RANDOM_TREASURE_ART:
  1190. case Obj::RANDOM_MINOR_ART:
  1191. case Obj::RANDOM_MAJOR_ART:
  1192. case Obj::RANDOM_RELIC_ART:
  1193. case Obj::SPELL_SCROLL:
  1194. return readArtifact(mapPosition, objectTemplate);
  1195. case Obj::RANDOM_RESOURCE:
  1196. case Obj::RESOURCE:
  1197. return readResource(mapPosition, objectTemplate);
  1198. case Obj::RANDOM_TOWN:
  1199. case Obj::TOWN:
  1200. return readTown(mapPosition, objectTemplate);
  1201. case Obj::MINE:
  1202. case Obj::ABANDONED_MINE:
  1203. return readMine(mapPosition, objectTemplate);
  1204. case Obj::CREATURE_GENERATOR1:
  1205. case Obj::CREATURE_GENERATOR2:
  1206. case Obj::CREATURE_GENERATOR3:
  1207. case Obj::CREATURE_GENERATOR4:
  1208. return readDwelling(mapPosition);
  1209. case Obj::SHRINE_OF_MAGIC_INCANTATION:
  1210. case Obj::SHRINE_OF_MAGIC_GESTURE:
  1211. case Obj::SHRINE_OF_MAGIC_THOUGHT:
  1212. return readShrine();
  1213. case Obj::PANDORAS_BOX:
  1214. return readPandora(mapPosition);
  1215. case Obj::GRAIL:
  1216. return readGrail(mapPosition, objectTemplate);
  1217. case Obj::RANDOM_DWELLING:
  1218. case Obj::RANDOM_DWELLING_LVL:
  1219. case Obj::RANDOM_DWELLING_FACTION:
  1220. return readDwellingRandom(mapPosition, objectTemplate);
  1221. case Obj::QUEST_GUARD:
  1222. return readQuestGuard(mapPosition);
  1223. case Obj::SHIPYARD:
  1224. return readShipyard(mapPosition);
  1225. case Obj::HERO_PLACEHOLDER:
  1226. return readHeroPlaceholder(mapPosition);
  1227. case Obj::BORDERGUARD:
  1228. return readBorderGuard();
  1229. case Obj::BORDER_GATE:
  1230. return readBorderGate(mapPosition, objectTemplate);
  1231. case Obj::PYRAMID:
  1232. return readPyramid(mapPosition, objectTemplate);
  1233. case Obj::LIGHTHOUSE:
  1234. return readLighthouse(mapPosition);
  1235. case Obj::CREATURE_BANK:
  1236. case Obj::DERELICT_SHIP:
  1237. case Obj::DRAGON_UTOPIA:
  1238. case Obj::CRYPT:
  1239. case Obj::SHIPWRECK:
  1240. return readBank(mapPosition, objectTemplate);
  1241. default: //any other object
  1242. return readGeneric(mapPosition, objectTemplate);
  1243. }
  1244. }
  1245. void CMapLoaderH3M::readObjects()
  1246. {
  1247. uint32_t objectsCount = reader->readUInt32();
  1248. for(uint32_t i = 0; i < objectsCount; ++i)
  1249. {
  1250. int3 mapPosition = reader->readInt3();
  1251. uint32_t defIndex = reader->readUInt32();
  1252. ObjectInstanceID objectInstanceID = ObjectInstanceID(static_cast<si32>(map->objects.size()));
  1253. std::shared_ptr<const ObjectTemplate> objectTemplate = templates.at(defIndex);
  1254. reader->skipZero(5);
  1255. CGObjectInstance * newObject = readObject(objectTemplate, mapPosition, objectInstanceID);
  1256. if(!newObject)
  1257. continue;
  1258. newObject->pos = mapPosition;
  1259. newObject->ID = objectTemplate->id;
  1260. newObject->id = objectInstanceID;
  1261. if(newObject->ID != Obj::HERO && newObject->ID != Obj::HERO_PLACEHOLDER && newObject->ID != Obj::PRISON)
  1262. {
  1263. newObject->subID = objectTemplate->subid;
  1264. }
  1265. newObject->appearance = objectTemplate;
  1266. assert(objectInstanceID == ObjectInstanceID((si32)map->objects.size()));
  1267. {
  1268. //TODO: define valid typeName and subtypeName for H3M maps
  1269. //boost::format fmt("%s_%d");
  1270. //fmt % nobj->typeName % nobj->id.getNum();
  1271. boost::format fmt("obj_%d");
  1272. fmt % newObject->id.getNum();
  1273. newObject->instanceName = fmt.str();
  1274. }
  1275. map->addNewObject(newObject);
  1276. }
  1277. std::sort(
  1278. map->heroesOnMap.begin(),
  1279. map->heroesOnMap.end(),
  1280. [](const ConstTransitivePtr<CGHeroInstance> & a, const ConstTransitivePtr<CGHeroInstance> & b)
  1281. {
  1282. return a->subID < b->subID;
  1283. }
  1284. );
  1285. }
  1286. void CMapLoaderH3M::readCreatureSet(CCreatureSet * out, int number)
  1287. {
  1288. for(int index = 0; index < number; ++index)
  1289. {
  1290. CreatureID creatureID = reader->readCreature();
  1291. int count = reader->readUInt16();
  1292. // Empty slot
  1293. if(creatureID == CreatureID::NONE)
  1294. continue;
  1295. auto * result = new CStackInstance();
  1296. result->count = count;
  1297. if(creatureID < CreatureID::NONE)
  1298. {
  1299. int value = -creatureID.getNum() - 2;
  1300. assert(value >= 0 && value < 14);
  1301. uint8_t level = value / 2;
  1302. uint8_t upgrade = value % 2;
  1303. //this will happen when random object has random army
  1304. result->randomStack = CStackInstance::RandomStackInfo{level, upgrade};
  1305. }
  1306. else
  1307. {
  1308. result->setType(creatureID);
  1309. }
  1310. out->putStack(SlotID(index), result);
  1311. }
  1312. out->validTypes(true);
  1313. }
  1314. void CMapLoaderH3M::setOwnerAndValidate(const int3 & mapPosition, CGObjectInstance * object, const PlayerColor & owner)
  1315. {
  1316. assert(owner.isValidPlayer() || owner == PlayerColor::NEUTRAL);
  1317. if(owner == PlayerColor::NEUTRAL)
  1318. {
  1319. object->setOwner(PlayerColor::NEUTRAL);
  1320. return;
  1321. }
  1322. if(!owner.isValidPlayer())
  1323. {
  1324. object->setOwner(PlayerColor::NEUTRAL);
  1325. logGlobal->warn("Map '%s': Object at %s - owned by invalid player %d! Will be set to neutral!", mapName, mapPosition.toString(), int(owner.getNum()));
  1326. return;
  1327. }
  1328. if(!mapHeader->players[owner.getNum()].canAnyonePlay())
  1329. {
  1330. object->setOwner(PlayerColor::NEUTRAL);
  1331. logGlobal->warn("Map '%s': Object at %s - owned by non-existing player %d! Will be set to neutral!", mapName, mapPosition.toString(), int(owner.getNum())
  1332. );
  1333. return;
  1334. }
  1335. object->setOwner(owner);
  1336. }
  1337. CGObjectInstance * CMapLoaderH3M::readHero(const int3 & mapPosition, const ObjectInstanceID & objectInstanceID)
  1338. {
  1339. auto * object = new CGHeroInstance();
  1340. if(features.levelAB)
  1341. {
  1342. unsigned int identifier = reader->readUInt32();
  1343. map->questIdentifierToId[identifier] = objectInstanceID;
  1344. }
  1345. PlayerColor owner = reader->readPlayer();
  1346. object->subID = reader->readUInt8();
  1347. //If hero of this type has been predefined, use that as a base.
  1348. //Instance data will overwrite the predefined values where appropriate.
  1349. for(auto & elem : map->predefinedHeroes)
  1350. {
  1351. if(elem->subID == object->subID)
  1352. {
  1353. logGlobal->debug("Hero %d will be taken from the predefined heroes list.", object->subID);
  1354. delete object;
  1355. object = elem;
  1356. break;
  1357. }
  1358. }
  1359. setOwnerAndValidate(mapPosition, object, owner);
  1360. object->portrait = object->subID;
  1361. for(auto & elem : map->disposedHeroes)
  1362. {
  1363. if(elem.heroId == object->subID)
  1364. {
  1365. object->nameCustom = elem.name;
  1366. object->portrait = elem.portrait;
  1367. break;
  1368. }
  1369. }
  1370. bool hasName = reader->readBool();
  1371. if(hasName)
  1372. object->nameCustom = readLocalizedString(TextIdentifier("heroes", object->subID, "name"));
  1373. if(features.levelSOD)
  1374. {
  1375. bool hasCustomExperience = reader->readBool();
  1376. if(hasCustomExperience)
  1377. object->exp = reader->readUInt32();
  1378. else
  1379. object->exp = CGHeroInstance::UNINITIALIZED_EXPERIENCE;
  1380. }
  1381. else
  1382. {
  1383. object->exp = reader->readUInt32();
  1384. //0 means "not set" in <=AB maps
  1385. if(!object->exp)
  1386. object->exp = CGHeroInstance::UNINITIALIZED_EXPERIENCE;
  1387. }
  1388. bool hasPortrait = reader->readBool();
  1389. if(hasPortrait)
  1390. object->portrait = reader->readHero().getNum();
  1391. bool hasSecSkills = reader->readBool();
  1392. if(hasSecSkills)
  1393. {
  1394. if(!object->secSkills.empty())
  1395. {
  1396. if(object->secSkills[0].first != SecondarySkill::DEFAULT)
  1397. logGlobal->warn("Hero %s subID=%d has set secondary skills twice (in map properties and on adventure map instance). Using the latter set...", object->getNameTextID(), object->subID);
  1398. object->secSkills.clear();
  1399. }
  1400. uint32_t skillsCount = reader->readUInt32();
  1401. object->secSkills.resize(skillsCount);
  1402. for(int i = 0; i < skillsCount; ++i)
  1403. {
  1404. object->secSkills[i].first = reader->readSkill();
  1405. object->secSkills[i].second = reader->readUInt8();
  1406. }
  1407. }
  1408. bool hasGarison = reader->readBool();
  1409. if(hasGarison)
  1410. readCreatureSet(object, 7);
  1411. object->formation = static_cast<EArmyFormation>(reader->readUInt8());
  1412. assert(object->formation == EArmyFormation::LOOSE || object->formation == EArmyFormation::TIGHT);
  1413. loadArtifactsOfHero(object);
  1414. object->patrol.patrolRadius = reader->readUInt8();
  1415. object->patrol.patrolling = (object->patrol.patrolRadius != 0xff);
  1416. if(features.levelAB)
  1417. {
  1418. bool hasCustomBiography = reader->readBool();
  1419. if(hasCustomBiography)
  1420. object->biographyCustom = readLocalizedString(TextIdentifier("heroes", object->subID, "biography"));
  1421. object->gender = static_cast<EHeroGender>(reader->readUInt8());
  1422. assert(object->gender == EHeroGender::MALE || object->gender == EHeroGender::FEMALE || object->gender == EHeroGender::DEFAULT);
  1423. }
  1424. else
  1425. {
  1426. object->gender = EHeroGender::DEFAULT;
  1427. }
  1428. // Spells
  1429. if(features.levelSOD)
  1430. {
  1431. bool hasCustomSpells = reader->readBool();
  1432. if(hasCustomSpells)
  1433. {
  1434. if(!object->spells.empty())
  1435. {
  1436. object->clear();
  1437. logGlobal->warn("Hero %s subID=%d has spells set twice (in map properties and on adventure map instance). Using the latter set...", object->getNameTextID(), object->subID);
  1438. }
  1439. object->spells.insert(SpellID::PRESET); //placeholder "preset spells"
  1440. reader->readBitmaskSpells(object->spells, false);
  1441. }
  1442. }
  1443. else if(features.levelAB)
  1444. {
  1445. //we can read one spell
  1446. SpellID spell = reader->readSpell();
  1447. if(spell != SpellID::NONE)
  1448. object->spells.insert(spell);
  1449. }
  1450. if(features.levelSOD)
  1451. {
  1452. bool hasCustomPrimSkills = reader->readBool();
  1453. if(hasCustomPrimSkills)
  1454. {
  1455. auto ps = object->getAllBonuses(Selector::type()(BonusType::PRIMARY_SKILL).And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL)), nullptr);
  1456. if(ps->size())
  1457. {
  1458. logGlobal->warn("Hero %s subID=%d has set primary skills twice (in map properties and on adventure map instance). Using the latter set...", object->getNameTranslated(), object->subID );
  1459. for(const auto & b : *ps)
  1460. object->removeBonus(b);
  1461. }
  1462. for(int xx = 0; xx < GameConstants::PRIMARY_SKILLS; ++xx)
  1463. {
  1464. object->pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(xx), reader->readUInt8());
  1465. }
  1466. }
  1467. }
  1468. reader->skipZero(16);
  1469. return object;
  1470. }
  1471. CGObjectInstance * CMapLoaderH3M::readSeerHut(const int3 & position)
  1472. {
  1473. auto * hut = new CGSeerHut();
  1474. uint32_t questsCount = 1;
  1475. if(features.levelHOTA3)
  1476. questsCount = reader->readUInt32();
  1477. //TODO: HotA
  1478. if(questsCount > 1)
  1479. logGlobal->warn("Map '%s': Seer Hut at %s - %d quests are not implemented!", mapName, position.toString(), questsCount);
  1480. for(size_t i = 0; i < questsCount; ++i)
  1481. readSeerHutQuest(hut, position);
  1482. if(features.levelHOTA3)
  1483. {
  1484. uint32_t repeateableQuestsCount = reader->readUInt32();
  1485. if(repeateableQuestsCount != 0)
  1486. logGlobal->warn("Map '%s': Seer Hut at %s - %d repeatable quests are not implemented!", mapName, position.toString(), repeateableQuestsCount);
  1487. for(size_t i = 0; i < repeateableQuestsCount; ++i)
  1488. readSeerHutQuest(hut, position);
  1489. }
  1490. reader->skipZero(2);
  1491. return hut;
  1492. }
  1493. void CMapLoaderH3M::readSeerHutQuest(CGSeerHut * hut, const int3 & position)
  1494. {
  1495. if(features.levelAB)
  1496. {
  1497. readQuest(hut, position);
  1498. }
  1499. else
  1500. {
  1501. //RoE
  1502. auto artID = reader->readArtifact();
  1503. if(artID != ArtifactID::NONE)
  1504. {
  1505. //not none quest
  1506. hut->quest->addArtifactID(artID);
  1507. hut->quest->missionType = CQuest::MISSION_ART;
  1508. }
  1509. else
  1510. {
  1511. hut->quest->missionType = CQuest::MISSION_NONE;
  1512. }
  1513. hut->quest->lastDay = -1; //no timeout
  1514. hut->quest->isCustomFirst = false;
  1515. hut->quest->isCustomNext = false;
  1516. hut->quest->isCustomComplete = false;
  1517. }
  1518. if(hut->quest->missionType)
  1519. {
  1520. auto rewardType = static_cast<CGSeerHut::ERewardType>(reader->readUInt8());
  1521. hut->rewardType = rewardType;
  1522. switch(rewardType)
  1523. {
  1524. case CGSeerHut::EXPERIENCE:
  1525. {
  1526. hut->rVal = reader->readUInt32();
  1527. break;
  1528. }
  1529. case CGSeerHut::MANA_POINTS:
  1530. {
  1531. hut->rVal = reader->readUInt32();
  1532. break;
  1533. }
  1534. case CGSeerHut::MORALE_BONUS:
  1535. {
  1536. hut->rVal = reader->readUInt8();
  1537. break;
  1538. }
  1539. case CGSeerHut::LUCK_BONUS:
  1540. {
  1541. hut->rVal = reader->readUInt8();
  1542. break;
  1543. }
  1544. case CGSeerHut::RESOURCES:
  1545. {
  1546. hut->rID = reader->readUInt8();
  1547. hut->rVal = reader->readUInt32();
  1548. assert(hut->rID < features.resourcesCount);
  1549. assert((hut->rVal & 0x00ffffff) == hut->rVal);
  1550. break;
  1551. }
  1552. case CGSeerHut::PRIMARY_SKILL:
  1553. {
  1554. hut->rID = reader->readUInt8();
  1555. hut->rVal = reader->readUInt8();
  1556. break;
  1557. }
  1558. case CGSeerHut::SECONDARY_SKILL:
  1559. {
  1560. hut->rID = reader->readSkill();
  1561. hut->rVal = reader->readUInt8();
  1562. break;
  1563. }
  1564. case CGSeerHut::ARTIFACT:
  1565. {
  1566. hut->rID = reader->readArtifact();
  1567. break;
  1568. }
  1569. case CGSeerHut::SPELL:
  1570. {
  1571. hut->rID = reader->readSpell();
  1572. break;
  1573. }
  1574. case CGSeerHut::CREATURE:
  1575. {
  1576. hut->rID = reader->readCreature();
  1577. hut->rVal = reader->readUInt16();
  1578. break;
  1579. }
  1580. case CGSeerHut::NOTHING:
  1581. {
  1582. // no-op
  1583. break;
  1584. }
  1585. default:
  1586. {
  1587. assert(0);
  1588. }
  1589. }
  1590. }
  1591. else
  1592. {
  1593. // missionType==255
  1594. reader->skipZero(1);
  1595. }
  1596. }
  1597. void CMapLoaderH3M::readQuest(IQuestObject * guard, const int3 & position)
  1598. {
  1599. guard->quest->missionType = static_cast<CQuest::Emission>(reader->readUInt8());
  1600. switch(guard->quest->missionType)
  1601. {
  1602. case CQuest::MISSION_NONE:
  1603. return;
  1604. case CQuest::MISSION_PRIMARY_STAT:
  1605. {
  1606. guard->quest->m2stats.resize(4);
  1607. for(int x = 0; x < 4; ++x)
  1608. {
  1609. guard->quest->m2stats[x] = reader->readUInt8();
  1610. }
  1611. }
  1612. break;
  1613. case CQuest::MISSION_LEVEL:
  1614. case CQuest::MISSION_KILL_HERO:
  1615. case CQuest::MISSION_KILL_CREATURE:
  1616. {
  1617. guard->quest->m13489val = reader->readUInt32();
  1618. break;
  1619. }
  1620. case CQuest::MISSION_ART:
  1621. {
  1622. int artNumber = reader->readUInt8();
  1623. for(int yy = 0; yy < artNumber; ++yy)
  1624. {
  1625. auto artid = reader->readArtifact();
  1626. guard->quest->addArtifactID(artid);
  1627. map->allowedArtifact[artid] = false; //these are unavailable for random generation
  1628. }
  1629. break;
  1630. }
  1631. case CQuest::MISSION_ARMY:
  1632. {
  1633. int typeNumber = reader->readUInt8();
  1634. guard->quest->m6creatures.resize(typeNumber);
  1635. for(int hh = 0; hh < typeNumber; ++hh)
  1636. {
  1637. guard->quest->m6creatures[hh].type = VLC->creh->objects[reader->readCreature()];
  1638. guard->quest->m6creatures[hh].count = reader->readUInt16();
  1639. }
  1640. break;
  1641. }
  1642. case CQuest::MISSION_RESOURCES:
  1643. {
  1644. for(int x = 0; x < 7; ++x)
  1645. guard->quest->m7resources[x] = reader->readUInt32();
  1646. break;
  1647. }
  1648. case CQuest::MISSION_HERO:
  1649. {
  1650. guard->quest->m13489val = reader->readHero().getNum();
  1651. break;
  1652. }
  1653. case CQuest::MISSION_PLAYER:
  1654. {
  1655. guard->quest->m13489val = reader->readPlayer().getNum();
  1656. break;
  1657. }
  1658. case CQuest::MISSION_HOTA_MULTI:
  1659. {
  1660. uint32_t missionSubID = reader->readUInt32();
  1661. if(missionSubID == 0)
  1662. {
  1663. guard->quest->missionType = CQuest::MISSION_HOTA_HERO_CLASS;
  1664. std::set<HeroClassID> heroClasses;
  1665. reader->readBitmaskHeroClassesSized(heroClasses, false);
  1666. logGlobal->warn("Map '%s': Quest at %s 'Belong to one of %d classes' is not implemented!", mapName, position.toString(), heroClasses.size());
  1667. break;
  1668. }
  1669. if(missionSubID == 1)
  1670. {
  1671. guard->quest->missionType = CQuest::MISSION_HOTA_REACH_DATE;
  1672. uint32_t daysPassed = reader->readUInt32();
  1673. logGlobal->warn("Map '%s': Quest at %s 'Wait till %d days passed' is not implemented!", mapName, position.toString(), daysPassed);
  1674. break;
  1675. }
  1676. assert(0);
  1677. break;
  1678. }
  1679. default:
  1680. {
  1681. assert(0);
  1682. }
  1683. }
  1684. guard->quest->lastDay = reader->readInt32();
  1685. guard->quest->firstVisitText = readLocalizedString(TextIdentifier("quest", position.x, position.y, position.z, "firstVisit"));
  1686. guard->quest->nextVisitText = readLocalizedString(TextIdentifier("quest", position.x, position.y, position.z, "nextVisit"));
  1687. guard->quest->completedText = readLocalizedString(TextIdentifier("quest", position.x, position.y, position.z, "completed"));
  1688. guard->quest->isCustomFirst = !guard->quest->firstVisitText.empty();
  1689. guard->quest->isCustomNext = !guard->quest->nextVisitText.empty();
  1690. guard->quest->isCustomComplete = !guard->quest->completedText.empty();
  1691. }
  1692. CGObjectInstance * CMapLoaderH3M::readTown(const int3 & position, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1693. {
  1694. auto * object = new CGTownInstance();
  1695. if(features.levelAB)
  1696. object->identifier = reader->readUInt32();
  1697. setOwnerAndValidate(position, object, reader->readPlayer());
  1698. std::optional<FactionID> faction;
  1699. if (objectTemplate->id == Obj::TOWN)
  1700. faction = FactionID(objectTemplate->subid);
  1701. bool hasName = reader->readBool();
  1702. if(hasName)
  1703. object->setNameTranslated(readLocalizedString(TextIdentifier("town", position.x, position.y, position.z, "name")));
  1704. bool hasGarrison = reader->readBool();
  1705. if(hasGarrison)
  1706. readCreatureSet(object, 7);
  1707. object->formation = static_cast<EArmyFormation>(reader->readUInt8());
  1708. assert(object->formation == EArmyFormation::LOOSE || object->formation == EArmyFormation::TIGHT);
  1709. bool hasCustomBuildings = reader->readBool();
  1710. if(hasCustomBuildings)
  1711. {
  1712. reader->readBitmaskBuildings(object->builtBuildings, faction);
  1713. reader->readBitmaskBuildings(object->forbiddenBuildings, faction);
  1714. }
  1715. // Standard buildings
  1716. else
  1717. {
  1718. bool hasFort = reader->readBool();
  1719. if(hasFort)
  1720. object->builtBuildings.insert(BuildingID::FORT);
  1721. //means that set of standard building should be included
  1722. object->builtBuildings.insert(BuildingID::DEFAULT);
  1723. }
  1724. if(features.levelAB)
  1725. {
  1726. std::set<SpellID> spellsMask;
  1727. reader->readBitmaskSpells(spellsMask, false);
  1728. std::copy(spellsMask.begin(), spellsMask.end(), std::back_inserter(object->obligatorySpells));
  1729. }
  1730. {
  1731. std::set<SpellID> spellsMask;
  1732. reader->readBitmaskSpells(spellsMask, true);
  1733. std::copy(spellsMask.begin(), spellsMask.end(), std::back_inserter(object->possibleSpells));
  1734. auto defaultAllowed = VLC->spellh->getDefaultAllowed();
  1735. //add all spells from mods
  1736. for(int i = features.spellsCount; i < defaultAllowed.size(); ++i)
  1737. if(defaultAllowed[i])
  1738. object->possibleSpells.emplace_back(i);
  1739. }
  1740. if(features.levelHOTA1)
  1741. {
  1742. // TODO: HOTA support
  1743. [[maybe_unused]] bool spellResearchAvailable = reader->readBool();
  1744. }
  1745. // Read castle events
  1746. uint32_t eventsCount = reader->readUInt32();
  1747. for(int eventID = 0; eventID < eventsCount; ++eventID)
  1748. {
  1749. CCastleEvent event;
  1750. event.town = object;
  1751. event.name = readBasicString();
  1752. event.message = readLocalizedString(TextIdentifier("town", position.x, position.y, position.z, "event", eventID, "description"));
  1753. reader->readResourses(event.resources);
  1754. event.players = reader->readUInt8();
  1755. if(features.levelSOD)
  1756. event.humanAffected = reader->readBool();
  1757. else
  1758. event.humanAffected = true;
  1759. event.computerAffected = reader->readUInt8();
  1760. event.firstOccurence = reader->readUInt16();
  1761. event.nextOccurence = reader->readUInt8();
  1762. reader->skipZero(17);
  1763. // New buildings
  1764. reader->readBitmaskBuildings(event.buildings, faction);
  1765. event.creatures.resize(7);
  1766. for(int i = 0; i < 7; ++i)
  1767. event.creatures[i] = reader->readUInt16();
  1768. reader->skipZero(4);
  1769. object->events.push_back(event);
  1770. }
  1771. if(features.levelSOD)
  1772. {
  1773. object->alignmentToPlayer = PlayerColor::NEUTRAL; // "same as owner or random"
  1774. uint8_t alignment = reader->readUInt8();
  1775. if(alignment != PlayerColor::NEUTRAL.getNum())
  1776. {
  1777. if(alignment < PlayerColor::PLAYER_LIMIT.getNum())
  1778. {
  1779. if (mapHeader->players[alignment].canAnyonePlay())
  1780. object->alignmentToPlayer = PlayerColor(alignment);
  1781. else
  1782. logGlobal->warn("%s - Aligment of town at %s is invalid! Player %d is not present on map!", mapName, position.toString(), int(alignment));
  1783. }
  1784. else
  1785. {
  1786. // TODO: HOTA support
  1787. uint8_t invertedAlignment = alignment - PlayerColor::PLAYER_LIMIT.getNum();
  1788. if(invertedAlignment < PlayerColor::PLAYER_LIMIT.getNum())
  1789. {
  1790. logGlobal->warn("%s - Aligment of town at %s 'not as player %d' is not implemented!", mapName, position.toString(), alignment - PlayerColor::PLAYER_LIMIT.getNum());
  1791. }
  1792. else
  1793. {
  1794. logGlobal->warn("%s - Aligment of town at %s is corrupted!!", mapName, position.toString());
  1795. }
  1796. }
  1797. }
  1798. }
  1799. reader->skipZero(3);
  1800. return object;
  1801. }
  1802. void CMapLoaderH3M::readEvents()
  1803. {
  1804. uint32_t eventsCount = reader->readUInt32();
  1805. for(int eventID = 0; eventID < eventsCount; ++eventID)
  1806. {
  1807. CMapEvent event;
  1808. event.name = readBasicString();
  1809. event.message = readLocalizedString(TextIdentifier("event", eventID, "description"));
  1810. reader->readResourses(event.resources);
  1811. event.players = reader->readUInt8();
  1812. if(features.levelSOD)
  1813. {
  1814. event.humanAffected = reader->readBool();
  1815. }
  1816. else
  1817. {
  1818. event.humanAffected = true;
  1819. }
  1820. event.computerAffected = reader->readBool();
  1821. event.firstOccurence = reader->readUInt16();
  1822. event.nextOccurence = reader->readUInt8();
  1823. reader->skipZero(17);
  1824. map->events.push_back(event);
  1825. }
  1826. }
  1827. void CMapLoaderH3M::readMessageAndGuards(std::string & message, CCreatureSet * guards, const int3 & position)
  1828. {
  1829. bool hasMessage = reader->readBool();
  1830. if(hasMessage)
  1831. {
  1832. message = readLocalizedString(TextIdentifier("guards", position.x, position.y, position.z, "message"));
  1833. bool hasGuards = reader->readBool();
  1834. if(hasGuards)
  1835. readCreatureSet(guards, 7);
  1836. reader->skipZero(4);
  1837. }
  1838. }
  1839. std::string CMapLoaderH3M::readBasicString()
  1840. {
  1841. return TextOperations::toUnicode(reader->readBaseString(), fileEncoding);
  1842. }
  1843. std::string CMapLoaderH3M::readLocalizedString(const TextIdentifier & stringIdentifier)
  1844. {
  1845. std::string mapString = TextOperations::toUnicode(reader->readBaseString(), fileEncoding);
  1846. TextIdentifier fullIdentifier("map", mapName, stringIdentifier.get());
  1847. if(mapString.empty())
  1848. return "";
  1849. VLC->generaltexth->registerString(modName, fullIdentifier, mapString);
  1850. return VLC->generaltexth->translate(fullIdentifier.get());
  1851. }
  1852. void CMapLoaderH3M::afterRead()
  1853. {
  1854. //convert main town positions for all players to actual object position, in H3M it is position of active tile
  1855. for(auto & p : map->players)
  1856. {
  1857. int3 posOfMainTown = p.posOfMainTown;
  1858. if(posOfMainTown.valid() && map->isInTheMap(posOfMainTown))
  1859. {
  1860. const TerrainTile & t = map->getTile(posOfMainTown);
  1861. const CGObjectInstance * mainTown = nullptr;
  1862. for(auto * obj : t.visitableObjects)
  1863. {
  1864. if(obj->ID == Obj::TOWN || obj->ID == Obj::RANDOM_TOWN)
  1865. {
  1866. mainTown = obj;
  1867. break;
  1868. }
  1869. }
  1870. if(mainTown == nullptr)
  1871. continue;
  1872. p.posOfMainTown = posOfMainTown + mainTown->getVisitableOffset();
  1873. }
  1874. }
  1875. }
  1876. VCMI_LIB_NAMESPACE_END