MapFormatH3M.cpp 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215
  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 = new ObjectTemplate;
  793. tmpl->readMap(reader->getInternalReader());
  794. templates.push_back(std::shared_ptr<const ObjectTemplate>(tmpl));
  795. }
  796. }
  797. CGObjectInstance * CMapLoaderH3M::readEvent(const int3 & mapPosition)
  798. {
  799. auto * object = new CGEvent();
  800. readBoxContent(object, mapPosition);
  801. object->availableFor = reader->readUInt8();
  802. object->computerActivate = reader->readBool();
  803. object->removeAfterVisit = reader->readBool();
  804. reader->skipZero(4);
  805. if(features.levelHOTA3)
  806. object->humanActivate = reader->readBool();
  807. else
  808. object->humanActivate = true;
  809. return object;
  810. }
  811. CGObjectInstance * CMapLoaderH3M::readPandora(const int3 & mapPosition)
  812. {
  813. auto * object = new CGPandoraBox();
  814. readBoxContent(object, mapPosition);
  815. return object;
  816. }
  817. void CMapLoaderH3M::readBoxContent(CGPandoraBox * object, const int3 & mapPosition)
  818. {
  819. readMessageAndGuards(object->message, object, mapPosition);
  820. object->gainedExp = reader->readUInt32();
  821. object->manaDiff = reader->readInt32();
  822. object->moraleDiff = reader->readInt8();
  823. object->luckDiff = reader->readInt8();
  824. reader->readResourses(object->resources);
  825. object->primskills.resize(GameConstants::PRIMARY_SKILLS);
  826. for(int x = 0; x < GameConstants::PRIMARY_SKILLS; ++x)
  827. object->primskills[x] = static_cast<PrimarySkill::PrimarySkill>(reader->readUInt8());
  828. int gabn = reader->readUInt8(); //number of gained abilities
  829. for(int oo = 0; oo < gabn; ++oo)
  830. {
  831. object->abilities.emplace_back(reader->readSkill());
  832. object->abilityLevels.push_back(reader->readUInt8());
  833. }
  834. int gart = reader->readUInt8(); //number of gained artifacts
  835. for(int oo = 0; oo < gart; ++oo)
  836. object->artifacts.emplace_back(reader->readArtifact());
  837. int gspel = reader->readUInt8(); //number of gained spells
  838. for(int oo = 0; oo < gspel; ++oo)
  839. object->spells.emplace_back(reader->readSpell());
  840. int gcre = reader->readUInt8(); //number of gained creatures
  841. readCreatureSet(&object->creatures, gcre);
  842. reader->skipZero(8);
  843. }
  844. CGObjectInstance * CMapLoaderH3M::readMonster(const int3 & mapPosition, const ObjectInstanceID & objectInstanceID)
  845. {
  846. auto * object = new CGCreature();
  847. if(features.levelAB)
  848. {
  849. object->identifier = reader->readUInt32();
  850. map->questIdentifierToId[object->identifier] = objectInstanceID;
  851. }
  852. auto * hlp = new CStackInstance();
  853. hlp->count = reader->readUInt16();
  854. //type will be set during initialization
  855. object->putStack(SlotID(0), hlp);
  856. object->character = reader->readInt8();
  857. bool hasMessage = reader->readBool();
  858. if(hasMessage)
  859. {
  860. object->message = readLocalizedString(TextIdentifier("monster", mapPosition.x, mapPosition.y, mapPosition.z, "message"));
  861. reader->readResourses(object->resources);
  862. object->gainedArtifact = reader->readArtifact();
  863. }
  864. object->neverFlees = reader->readBool();
  865. object->notGrowingTeam = reader->readBool();
  866. reader->skipZero(2);
  867. if(features.levelHOTA3)
  868. {
  869. //TODO: HotA
  870. int32_t agressionExact = reader->readInt32(); // -1 = default, 1-10 = possible values range
  871. bool joinOnlyForMoney = reader->readBool(); // if true, monsters will only join for money
  872. int32_t joinPercent = reader->readInt32(); // 100 = default, percent of monsters that will join on succesfull agression check
  873. int32_t upgradedStack = reader->readInt32(); // Presence of upgraded stack, -1 = random, 0 = never, 1 = always
  874. int32_t stacksCount = reader->readInt32(); // TODO: check possible values. How many creature stacks will be present on battlefield, -1 = default
  875. if(agressionExact != -1 || joinOnlyForMoney || joinPercent != 100 || upgradedStack != -1 || stacksCount != -1)
  876. logGlobal->warn(
  877. "Map '%s': Wandering monsters %s settings %d %d %d %d %d are not implemeted!",
  878. mapName,
  879. mapPosition.toString(),
  880. agressionExact,
  881. int(joinOnlyForMoney),
  882. joinPercent,
  883. upgradedStack,
  884. stacksCount
  885. );
  886. }
  887. return object;
  888. }
  889. CGObjectInstance * CMapLoaderH3M::readSign(const int3 & mapPosition)
  890. {
  891. auto * object = new CGSignBottle();
  892. object->message = readLocalizedString(TextIdentifier("sign", mapPosition.x, mapPosition.y, mapPosition.z, "message"));
  893. reader->skipZero(4);
  894. return object;
  895. }
  896. CGObjectInstance * CMapLoaderH3M::readWitchHut()
  897. {
  898. auto * object = new CGWitchHut();
  899. // AB and later maps have allowed abilities defined in H3M
  900. if(features.levelAB)
  901. {
  902. reader->readBitmaskSkills(object->allowedAbilities, false);
  903. if(object->allowedAbilities.size() != 1)
  904. {
  905. auto defaultAllowed = VLC->skillh->getDefaultAllowed();
  906. for(int skillID = 0; skillID < VLC->skillh->size(); ++skillID)
  907. if(defaultAllowed[skillID])
  908. object->allowedAbilities.insert(SecondarySkill(skillID));
  909. }
  910. }
  911. return object;
  912. }
  913. CGObjectInstance * CMapLoaderH3M::readScholar()
  914. {
  915. auto * object = new CGScholar();
  916. object->bonusType = static_cast<CGScholar::EBonusType>(reader->readUInt8());
  917. object->bonusID = reader->readUInt8();
  918. reader->skipZero(6);
  919. return object;
  920. }
  921. CGObjectInstance * CMapLoaderH3M::readGarrison(const int3 & mapPosition)
  922. {
  923. auto * object = new CGGarrison();
  924. setOwnerAndValidate(mapPosition, object, reader->readPlayer32());
  925. readCreatureSet(object, 7);
  926. if(features.levelAB)
  927. object->removableUnits = reader->readBool();
  928. else
  929. object->removableUnits = true;
  930. reader->skipZero(8);
  931. return object;
  932. }
  933. CGObjectInstance * CMapLoaderH3M::readArtifact(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  934. {
  935. auto artID = ArtifactID::NONE; //random, set later
  936. int spellID = -1;
  937. auto * object = new CGArtifact();
  938. readMessageAndGuards(object->message, object, mapPosition);
  939. if(objectTemplate->id == Obj::SPELL_SCROLL)
  940. {
  941. spellID = reader->readSpell32();
  942. artID = ArtifactID::SPELL_SCROLL;
  943. }
  944. else if(objectTemplate->id == Obj::ARTIFACT)
  945. {
  946. //specific artifact
  947. artID = ArtifactID(objectTemplate->subid);
  948. }
  949. object->storedArtifact = CArtifactInstance::createArtifact(map, artID, spellID);
  950. return object;
  951. }
  952. CGObjectInstance * CMapLoaderH3M::readResource(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  953. {
  954. auto * object = new CGResource();
  955. readMessageAndGuards(object->message, object, mapPosition);
  956. object->amount = reader->readUInt32();
  957. if(objectTemplate->subid == GameResID(EGameResID::GOLD))
  958. {
  959. // Gold is multiplied by 100.
  960. object->amount *= 100;
  961. }
  962. reader->skipZero(4);
  963. return object;
  964. }
  965. CGObjectInstance * CMapLoaderH3M::readMine(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  966. {
  967. auto * object = new CGMine();
  968. if(objectTemplate->subid < 7)
  969. {
  970. setOwnerAndValidate(mapPosition, object, reader->readPlayer32());
  971. }
  972. else
  973. {
  974. object->setOwner(PlayerColor::NEUTRAL);
  975. reader->readBitmaskResources(object->abandonedMineResources, false);
  976. }
  977. return object;
  978. }
  979. CGObjectInstance * CMapLoaderH3M::readDwelling(const int3 & position)
  980. {
  981. auto * object = new CGDwelling();
  982. setOwnerAndValidate(position, object, reader->readPlayer32());
  983. return object;
  984. }
  985. CGObjectInstance * CMapLoaderH3M::readDwellingRandom(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  986. {
  987. auto * object = new CGDwelling();
  988. CSpecObjInfo * spec = nullptr;
  989. switch(objectTemplate->id)
  990. {
  991. case Obj::RANDOM_DWELLING:
  992. spec = new CCreGenLeveledCastleInfo();
  993. break;
  994. case Obj::RANDOM_DWELLING_LVL:
  995. spec = new CCreGenAsCastleInfo();
  996. break;
  997. case Obj::RANDOM_DWELLING_FACTION:
  998. spec = new CCreGenLeveledInfo();
  999. break;
  1000. default:
  1001. throw std::runtime_error("Invalid random dwelling format");
  1002. }
  1003. spec->owner = object;
  1004. setOwnerAndValidate(mapPosition, object, reader->readPlayer32());
  1005. //216 and 217
  1006. if(auto * castleSpec = dynamic_cast<CCreGenAsCastleInfo *>(spec))
  1007. {
  1008. castleSpec->instanceId = "";
  1009. castleSpec->identifier = reader->readUInt32();
  1010. if(!castleSpec->identifier)
  1011. {
  1012. castleSpec->asCastle = false;
  1013. const int MASK_SIZE = 8;
  1014. ui8 mask[2];
  1015. mask[0] = reader->readUInt8();
  1016. mask[1] = reader->readUInt8();
  1017. castleSpec->allowedFactions.clear();
  1018. castleSpec->allowedFactions.resize(VLC->townh->size(), false);
  1019. for(int i = 0; i < MASK_SIZE; i++)
  1020. castleSpec->allowedFactions[i] = ((mask[0] & (1 << i)) > 0);
  1021. for(int i = 0; i < (GameConstants::F_NUMBER - MASK_SIZE); i++)
  1022. castleSpec->allowedFactions[i + MASK_SIZE] = ((mask[1] & (1 << i)) > 0);
  1023. }
  1024. else
  1025. {
  1026. castleSpec->asCastle = true;
  1027. }
  1028. }
  1029. //216 and 218
  1030. if(auto * lvlSpec = dynamic_cast<CCreGenLeveledInfo *>(spec))
  1031. {
  1032. lvlSpec->minLevel = std::max(reader->readUInt8(), static_cast<ui8>(1));
  1033. lvlSpec->maxLevel = std::min(reader->readUInt8(), static_cast<ui8>(7));
  1034. }
  1035. object->info = spec;
  1036. return object;
  1037. }
  1038. CGObjectInstance * CMapLoaderH3M::readShrine()
  1039. {
  1040. auto * object = new CGShrine();
  1041. object->spell = reader->readSpell32();
  1042. return object;
  1043. }
  1044. CGObjectInstance * CMapLoaderH3M::readHeroPlaceholder(const int3 & mapPosition)
  1045. {
  1046. auto * object = new CGHeroPlaceholder();
  1047. setOwnerAndValidate(mapPosition, object, reader->readPlayer());
  1048. HeroTypeID htid = reader->readHero(); //hero type id
  1049. object->subID = htid.getNum();
  1050. if(htid.getNum() == -1)
  1051. {
  1052. object->power = reader->readUInt8();
  1053. logGlobal->debug("Hero placeholder: by power at %s", mapPosition.toString());
  1054. }
  1055. else
  1056. {
  1057. object->power = 0;
  1058. logGlobal->debug("Hero placeholder: %s at %s", VLC->heroh->getById(htid)->getNameTranslated(), mapPosition.toString());
  1059. }
  1060. return object;
  1061. }
  1062. CGObjectInstance * CMapLoaderH3M::readGrail(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1063. {
  1064. if (objectTemplate->subid < 1000)
  1065. {
  1066. map->grailPos = mapPosition;
  1067. map->grailRadius = reader->readInt32();
  1068. }
  1069. else
  1070. {
  1071. // Battle location for arena mode in HotA
  1072. logGlobal->warn("Map '%s': Arena mode is not supported!", mapName);
  1073. }
  1074. return nullptr;
  1075. }
  1076. CGObjectInstance * CMapLoaderH3M::readGeneric(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1077. {
  1078. if(VLC->objtypeh->knownSubObjects(objectTemplate->id).count(objectTemplate->subid))
  1079. return VLC->objtypeh->getHandlerFor(objectTemplate->id, objectTemplate->subid)->create(objectTemplate);
  1080. logGlobal->warn("Map '%s': Unrecognized object %d:%d ('%s') at %s found!", mapName, objectTemplate->id.toEnum(), objectTemplate->subid, objectTemplate->animationFile, mapPosition.toString());
  1081. return new CGObjectInstance();
  1082. }
  1083. CGObjectInstance * CMapLoaderH3M::readPyramid(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1084. {
  1085. if(objectTemplate->subid == 0)
  1086. return new CBank();
  1087. return new CGObjectInstance();
  1088. }
  1089. CGObjectInstance * CMapLoaderH3M::readQuestGuard(const int3 & mapPosition)
  1090. {
  1091. auto * guard = new CGQuestGuard();
  1092. readQuest(guard, mapPosition);
  1093. return guard;
  1094. }
  1095. CGObjectInstance * CMapLoaderH3M::readShipyard(const int3 & mapPosition)
  1096. {
  1097. auto * object = new CGShipyard();
  1098. setOwnerAndValidate(mapPosition, object, reader->readPlayer32());
  1099. return object;
  1100. }
  1101. CGObjectInstance * CMapLoaderH3M::readBorderGuard()
  1102. {
  1103. return new CGBorderGuard();
  1104. }
  1105. CGObjectInstance * CMapLoaderH3M::readBorderGate(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1106. {
  1107. if(objectTemplate->subid < 1000)
  1108. return new CGBorderGate();
  1109. //TODO: HotA - grave has same ID as border gate? WTF?
  1110. if(objectTemplate->subid == 1001)
  1111. return new CGObjectInstance();
  1112. logGlobal->warn("Map '%s: Quest gates at %s are not implemented!", mapName, mapPosition.toString());
  1113. return readQuestGuard(mapPosition);
  1114. }
  1115. CGObjectInstance * CMapLoaderH3M::readLighthouse(const int3 & mapPosition)
  1116. {
  1117. auto * object = new CGLighthouse();
  1118. setOwnerAndValidate(mapPosition, object, reader->readPlayer32());
  1119. return object;
  1120. }
  1121. CGObjectInstance * CMapLoaderH3M::readBank(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1122. {
  1123. if(features.levelHOTA3)
  1124. {
  1125. //TODO: HotA
  1126. // index of guards preset. -1 = random, 0-4 = index of possible guards settings
  1127. int32_t guardsPresetIndex = reader->readInt32();
  1128. // presence of upgraded stack: -1 = random, 0 = never, 1 = always
  1129. int8_t upgradedStackPresence = reader->readInt8();
  1130. assert(vstd::iswithin(guardsPresetIndex, -1, 4));
  1131. assert(vstd::iswithin(upgradedStackPresence, -1, 1));
  1132. // list of possible artifacts in reward
  1133. // - if list is empty, artifacts are either not present in reward or random
  1134. // - if non-empty, then list always have same number of elements as number of artifacts in bank
  1135. // - ArtifactID::NONE indictates random artifact, other values indicate artifact that should be used as reward
  1136. std::vector<ArtifactID> artifacts;
  1137. int artNumber = reader->readUInt32();
  1138. for(int yy = 0; yy < artNumber; ++yy)
  1139. {
  1140. artifacts.push_back(reader->readArtifact32());
  1141. }
  1142. if(guardsPresetIndex != -1 || upgradedStackPresence != -1 || !artifacts.empty())
  1143. logGlobal->warn(
  1144. "Map '%s: creature bank at %s settings %d %d %d are not implemented!",
  1145. mapName,
  1146. mapPosition.toString(),
  1147. guardsPresetIndex,
  1148. int(upgradedStackPresence),
  1149. artifacts.size()
  1150. );
  1151. }
  1152. return readGeneric(mapPosition, objectTemplate);
  1153. }
  1154. CGObjectInstance * CMapLoaderH3M::readObject(std::shared_ptr<const ObjectTemplate> objectTemplate, const int3 & mapPosition, const ObjectInstanceID & objectInstanceID)
  1155. {
  1156. switch(objectTemplate->id)
  1157. {
  1158. case Obj::EVENT:
  1159. return readEvent(mapPosition);
  1160. case Obj::HERO:
  1161. case Obj::RANDOM_HERO:
  1162. case Obj::PRISON:
  1163. return readHero(mapPosition, objectInstanceID);
  1164. case Obj::MONSTER:
  1165. case Obj::RANDOM_MONSTER:
  1166. case Obj::RANDOM_MONSTER_L1:
  1167. case Obj::RANDOM_MONSTER_L2:
  1168. case Obj::RANDOM_MONSTER_L3:
  1169. case Obj::RANDOM_MONSTER_L4:
  1170. case Obj::RANDOM_MONSTER_L5:
  1171. case Obj::RANDOM_MONSTER_L6:
  1172. case Obj::RANDOM_MONSTER_L7:
  1173. return readMonster(mapPosition, objectInstanceID);
  1174. case Obj::OCEAN_BOTTLE:
  1175. case Obj::SIGN:
  1176. return readSign(mapPosition);
  1177. case Obj::SEER_HUT:
  1178. return readSeerHut(mapPosition);
  1179. case Obj::WITCH_HUT:
  1180. return readWitchHut();
  1181. case Obj::SCHOLAR:
  1182. return readScholar();
  1183. case Obj::GARRISON:
  1184. case Obj::GARRISON2:
  1185. return readGarrison(mapPosition);
  1186. case Obj::ARTIFACT:
  1187. case Obj::RANDOM_ART:
  1188. case Obj::RANDOM_TREASURE_ART:
  1189. case Obj::RANDOM_MINOR_ART:
  1190. case Obj::RANDOM_MAJOR_ART:
  1191. case Obj::RANDOM_RELIC_ART:
  1192. case Obj::SPELL_SCROLL:
  1193. return readArtifact(mapPosition, objectTemplate);
  1194. case Obj::RANDOM_RESOURCE:
  1195. case Obj::RESOURCE:
  1196. return readResource(mapPosition, objectTemplate);
  1197. case Obj::RANDOM_TOWN:
  1198. case Obj::TOWN:
  1199. return readTown(mapPosition, objectTemplate);
  1200. case Obj::MINE:
  1201. case Obj::ABANDONED_MINE:
  1202. return readMine(mapPosition, objectTemplate);
  1203. case Obj::CREATURE_GENERATOR1:
  1204. case Obj::CREATURE_GENERATOR2:
  1205. case Obj::CREATURE_GENERATOR3:
  1206. case Obj::CREATURE_GENERATOR4:
  1207. return readDwelling(mapPosition);
  1208. case Obj::SHRINE_OF_MAGIC_INCANTATION:
  1209. case Obj::SHRINE_OF_MAGIC_GESTURE:
  1210. case Obj::SHRINE_OF_MAGIC_THOUGHT:
  1211. return readShrine();
  1212. case Obj::PANDORAS_BOX:
  1213. return readPandora(mapPosition);
  1214. case Obj::GRAIL:
  1215. return readGrail(mapPosition, objectTemplate);
  1216. case Obj::RANDOM_DWELLING:
  1217. case Obj::RANDOM_DWELLING_LVL:
  1218. case Obj::RANDOM_DWELLING_FACTION:
  1219. return readDwellingRandom(mapPosition, objectTemplate);
  1220. case Obj::QUEST_GUARD:
  1221. return readQuestGuard(mapPosition);
  1222. case Obj::SHIPYARD:
  1223. return readShipyard(mapPosition);
  1224. case Obj::HERO_PLACEHOLDER:
  1225. return readHeroPlaceholder(mapPosition);
  1226. case Obj::BORDERGUARD:
  1227. return readBorderGuard();
  1228. case Obj::BORDER_GATE:
  1229. return readBorderGate(mapPosition, objectTemplate);
  1230. case Obj::PYRAMID:
  1231. return readPyramid(mapPosition, objectTemplate);
  1232. case Obj::LIGHTHOUSE:
  1233. return readLighthouse(mapPosition);
  1234. case Obj::CREATURE_BANK:
  1235. case Obj::DERELICT_SHIP:
  1236. case Obj::DRAGON_UTOPIA:
  1237. case Obj::CRYPT:
  1238. case Obj::SHIPWRECK:
  1239. return readBank(mapPosition, objectTemplate);
  1240. default: //any other object
  1241. return readGeneric(mapPosition, objectTemplate);
  1242. }
  1243. }
  1244. void CMapLoaderH3M::readObjects()
  1245. {
  1246. uint32_t objectsCount = reader->readUInt32();
  1247. for(uint32_t i = 0; i < objectsCount; ++i)
  1248. {
  1249. int3 mapPosition = reader->readInt3();
  1250. uint32_t defIndex = reader->readUInt32();
  1251. ObjectInstanceID objectInstanceID = ObjectInstanceID(static_cast<si32>(map->objects.size()));
  1252. std::shared_ptr<const ObjectTemplate> objectTemplate = templates.at(defIndex);
  1253. reader->skipZero(5);
  1254. CGObjectInstance * newObject = readObject(objectTemplate, mapPosition, objectInstanceID);
  1255. if(!newObject)
  1256. continue;
  1257. newObject->pos = mapPosition;
  1258. newObject->ID = objectTemplate->id;
  1259. newObject->id = objectInstanceID;
  1260. if(newObject->ID != Obj::HERO && newObject->ID != Obj::HERO_PLACEHOLDER && newObject->ID != Obj::PRISON)
  1261. {
  1262. newObject->subID = objectTemplate->subid;
  1263. }
  1264. newObject->appearance = objectTemplate;
  1265. assert(objectInstanceID == ObjectInstanceID((si32)map->objects.size()));
  1266. {
  1267. //TODO: define valid typeName and subtypeName for H3M maps
  1268. //boost::format fmt("%s_%d");
  1269. //fmt % nobj->typeName % nobj->id.getNum();
  1270. boost::format fmt("obj_%d");
  1271. fmt % newObject->id.getNum();
  1272. newObject->instanceName = fmt.str();
  1273. }
  1274. map->addNewObject(newObject);
  1275. }
  1276. std::sort(
  1277. map->heroesOnMap.begin(),
  1278. map->heroesOnMap.end(),
  1279. [](const ConstTransitivePtr<CGHeroInstance> & a, const ConstTransitivePtr<CGHeroInstance> & b)
  1280. {
  1281. return a->subID < b->subID;
  1282. }
  1283. );
  1284. }
  1285. void CMapLoaderH3M::readCreatureSet(CCreatureSet * out, int number)
  1286. {
  1287. for(int index = 0; index < number; ++index)
  1288. {
  1289. CreatureID creatureID = reader->readCreature();
  1290. int count = reader->readUInt16();
  1291. // Empty slot
  1292. if(creatureID == CreatureID::NONE)
  1293. continue;
  1294. auto * result = new CStackInstance();
  1295. result->count = count;
  1296. if(creatureID < CreatureID::NONE)
  1297. {
  1298. int value = -creatureID.getNum() - 2;
  1299. assert(value >= 0 && value < 14);
  1300. uint8_t level = value / 2;
  1301. uint8_t upgrade = value % 2;
  1302. //this will happen when random object has random army
  1303. result->randomStack = CStackInstance::RandomStackInfo{level, upgrade};
  1304. }
  1305. else
  1306. {
  1307. result->setType(creatureID);
  1308. }
  1309. out->putStack(SlotID(index), result);
  1310. }
  1311. out->validTypes(true);
  1312. }
  1313. void CMapLoaderH3M::setOwnerAndValidate(const int3 & mapPosition, CGObjectInstance * object, const PlayerColor & owner)
  1314. {
  1315. assert(owner.isValidPlayer() || owner == PlayerColor::NEUTRAL);
  1316. if(owner == PlayerColor::NEUTRAL)
  1317. {
  1318. object->setOwner(PlayerColor::NEUTRAL);
  1319. return;
  1320. }
  1321. if(!owner.isValidPlayer())
  1322. {
  1323. object->setOwner(PlayerColor::NEUTRAL);
  1324. logGlobal->warn("Map '%s': Object at %s - owned by invalid player %d! Will be set to neutral!", mapName, mapPosition.toString(), int(owner.getNum()));
  1325. return;
  1326. }
  1327. if(!mapHeader->players[owner.getNum()].canAnyonePlay())
  1328. {
  1329. object->setOwner(PlayerColor::NEUTRAL);
  1330. logGlobal->warn("Map '%s': Object at %s - owned by non-existing player %d! Will be set to neutral!", mapName, mapPosition.toString(), int(owner.getNum())
  1331. );
  1332. return;
  1333. }
  1334. object->setOwner(owner);
  1335. }
  1336. CGObjectInstance * CMapLoaderH3M::readHero(const int3 & mapPosition, const ObjectInstanceID & objectInstanceID)
  1337. {
  1338. auto * object = new CGHeroInstance();
  1339. if(features.levelAB)
  1340. {
  1341. unsigned int identifier = reader->readUInt32();
  1342. map->questIdentifierToId[identifier] = objectInstanceID;
  1343. }
  1344. PlayerColor owner = reader->readPlayer();
  1345. object->subID = reader->readUInt8();
  1346. //If hero of this type has been predefined, use that as a base.
  1347. //Instance data will overwrite the predefined values where appropriate.
  1348. for(auto & elem : map->predefinedHeroes)
  1349. {
  1350. if(elem->subID == object->subID)
  1351. {
  1352. logGlobal->debug("Hero %d will be taken from the predefined heroes list.", object->subID);
  1353. delete object;
  1354. object = elem;
  1355. break;
  1356. }
  1357. }
  1358. setOwnerAndValidate(mapPosition, object, owner);
  1359. object->portrait = object->subID;
  1360. for(auto & elem : map->disposedHeroes)
  1361. {
  1362. if(elem.heroId == object->subID)
  1363. {
  1364. object->nameCustom = elem.name;
  1365. object->portrait = elem.portrait;
  1366. break;
  1367. }
  1368. }
  1369. bool hasName = reader->readBool();
  1370. if(hasName)
  1371. object->nameCustom = readLocalizedString(TextIdentifier("heroes", object->subID, "name"));
  1372. if(features.levelSOD)
  1373. {
  1374. bool hasCustomExperience = reader->readBool();
  1375. if(hasCustomExperience)
  1376. object->exp = reader->readUInt32();
  1377. else
  1378. object->exp = CGHeroInstance::UNINITIALIZED_EXPERIENCE;
  1379. }
  1380. else
  1381. {
  1382. object->exp = reader->readUInt32();
  1383. //0 means "not set" in <=AB maps
  1384. if(!object->exp)
  1385. object->exp = CGHeroInstance::UNINITIALIZED_EXPERIENCE;
  1386. }
  1387. bool hasPortrait = reader->readBool();
  1388. if(hasPortrait)
  1389. object->portrait = reader->readHero().getNum();
  1390. bool hasSecSkills = reader->readBool();
  1391. if(hasSecSkills)
  1392. {
  1393. if(!object->secSkills.empty())
  1394. {
  1395. if(object->secSkills[0].first != SecondarySkill::DEFAULT)
  1396. 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);
  1397. object->secSkills.clear();
  1398. }
  1399. uint32_t skillsCount = reader->readUInt32();
  1400. object->secSkills.resize(skillsCount);
  1401. for(int i = 0; i < skillsCount; ++i)
  1402. {
  1403. object->secSkills[i].first = reader->readSkill();
  1404. object->secSkills[i].second = reader->readUInt8();
  1405. }
  1406. }
  1407. bool hasGarison = reader->readBool();
  1408. if(hasGarison)
  1409. readCreatureSet(object, 7);
  1410. object->formation = static_cast<EArmyFormation>(reader->readUInt8());
  1411. assert(object->formation == EArmyFormation::LOOSE || object->formation == EArmyFormation::TIGHT);
  1412. loadArtifactsOfHero(object);
  1413. object->patrol.patrolRadius = reader->readUInt8();
  1414. object->patrol.patrolling = (object->patrol.patrolRadius != 0xff);
  1415. if(features.levelAB)
  1416. {
  1417. bool hasCustomBiography = reader->readBool();
  1418. if(hasCustomBiography)
  1419. object->biographyCustom = readLocalizedString(TextIdentifier("heroes", object->subID, "biography"));
  1420. object->gender = static_cast<EHeroGender>(reader->readUInt8());
  1421. assert(object->gender == EHeroGender::MALE || object->gender == EHeroGender::FEMALE || object->gender == EHeroGender::DEFAULT);
  1422. }
  1423. else
  1424. {
  1425. object->gender = EHeroGender::DEFAULT;
  1426. }
  1427. // Spells
  1428. if(features.levelSOD)
  1429. {
  1430. bool hasCustomSpells = reader->readBool();
  1431. if(hasCustomSpells)
  1432. {
  1433. if(!object->spells.empty())
  1434. {
  1435. object->clear();
  1436. 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);
  1437. }
  1438. object->spells.insert(SpellID::PRESET); //placeholder "preset spells"
  1439. reader->readBitmaskSpells(object->spells, false);
  1440. }
  1441. }
  1442. else if(features.levelAB)
  1443. {
  1444. //we can read one spell
  1445. SpellID spell = reader->readSpell();
  1446. if(spell != SpellID::NONE)
  1447. object->spells.insert(spell);
  1448. }
  1449. if(features.levelSOD)
  1450. {
  1451. bool hasCustomPrimSkills = reader->readBool();
  1452. if(hasCustomPrimSkills)
  1453. {
  1454. auto ps = object->getAllBonuses(Selector::type()(BonusType::PRIMARY_SKILL).And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL)), nullptr);
  1455. if(ps->size())
  1456. {
  1457. 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 );
  1458. for(const auto & b : *ps)
  1459. object->removeBonus(b);
  1460. }
  1461. for(int xx = 0; xx < GameConstants::PRIMARY_SKILLS; ++xx)
  1462. {
  1463. object->pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(xx), reader->readUInt8());
  1464. }
  1465. }
  1466. }
  1467. reader->skipZero(16);
  1468. return object;
  1469. }
  1470. CGObjectInstance * CMapLoaderH3M::readSeerHut(const int3 & position)
  1471. {
  1472. auto * hut = new CGSeerHut();
  1473. uint32_t questsCount = 1;
  1474. if(features.levelHOTA3)
  1475. questsCount = reader->readUInt32();
  1476. //TODO: HotA
  1477. if(questsCount > 1)
  1478. logGlobal->warn("Map '%s': Seer Hut at %s - %d quests are not implemented!", mapName, position.toString(), questsCount);
  1479. for(size_t i = 0; i < questsCount; ++i)
  1480. readSeerHutQuest(hut, position);
  1481. if(features.levelHOTA3)
  1482. {
  1483. uint32_t repeateableQuestsCount = reader->readUInt32();
  1484. if(repeateableQuestsCount != 0)
  1485. logGlobal->warn("Map '%s': Seer Hut at %s - %d repeatable quests are not implemented!", mapName, position.toString(), repeateableQuestsCount);
  1486. for(size_t i = 0; i < repeateableQuestsCount; ++i)
  1487. readSeerHutQuest(hut, position);
  1488. }
  1489. reader->skipZero(2);
  1490. return hut;
  1491. }
  1492. void CMapLoaderH3M::readSeerHutQuest(CGSeerHut * hut, const int3 & position)
  1493. {
  1494. if(features.levelAB)
  1495. {
  1496. readQuest(hut, position);
  1497. }
  1498. else
  1499. {
  1500. //RoE
  1501. auto artID = reader->readArtifact();
  1502. if(artID != ArtifactID::NONE)
  1503. {
  1504. //not none quest
  1505. hut->quest->addArtifactID(artID);
  1506. hut->quest->missionType = CQuest::MISSION_ART;
  1507. }
  1508. else
  1509. {
  1510. hut->quest->missionType = CQuest::MISSION_NONE;
  1511. }
  1512. hut->quest->lastDay = -1; //no timeout
  1513. hut->quest->isCustomFirst = false;
  1514. hut->quest->isCustomNext = false;
  1515. hut->quest->isCustomComplete = false;
  1516. }
  1517. if(hut->quest->missionType)
  1518. {
  1519. auto rewardType = static_cast<CGSeerHut::ERewardType>(reader->readUInt8());
  1520. hut->rewardType = rewardType;
  1521. switch(rewardType)
  1522. {
  1523. case CGSeerHut::EXPERIENCE:
  1524. {
  1525. hut->rVal = reader->readUInt32();
  1526. break;
  1527. }
  1528. case CGSeerHut::MANA_POINTS:
  1529. {
  1530. hut->rVal = reader->readUInt32();
  1531. break;
  1532. }
  1533. case CGSeerHut::MORALE_BONUS:
  1534. {
  1535. hut->rVal = reader->readUInt8();
  1536. break;
  1537. }
  1538. case CGSeerHut::LUCK_BONUS:
  1539. {
  1540. hut->rVal = reader->readUInt8();
  1541. break;
  1542. }
  1543. case CGSeerHut::RESOURCES:
  1544. {
  1545. hut->rID = reader->readUInt8();
  1546. hut->rVal = reader->readUInt32();
  1547. assert(hut->rID < features.resourcesCount);
  1548. assert((hut->rVal & 0x00ffffff) == hut->rVal);
  1549. break;
  1550. }
  1551. case CGSeerHut::PRIMARY_SKILL:
  1552. {
  1553. hut->rID = reader->readUInt8();
  1554. hut->rVal = reader->readUInt8();
  1555. break;
  1556. }
  1557. case CGSeerHut::SECONDARY_SKILL:
  1558. {
  1559. hut->rID = reader->readSkill();
  1560. hut->rVal = reader->readUInt8();
  1561. break;
  1562. }
  1563. case CGSeerHut::ARTIFACT:
  1564. {
  1565. hut->rID = reader->readArtifact();
  1566. break;
  1567. }
  1568. case CGSeerHut::SPELL:
  1569. {
  1570. hut->rID = reader->readSpell();
  1571. break;
  1572. }
  1573. case CGSeerHut::CREATURE:
  1574. {
  1575. hut->rID = reader->readCreature();
  1576. hut->rVal = reader->readUInt16();
  1577. break;
  1578. }
  1579. case CGSeerHut::NOTHING:
  1580. {
  1581. // no-op
  1582. break;
  1583. }
  1584. default:
  1585. {
  1586. assert(0);
  1587. }
  1588. }
  1589. }
  1590. else
  1591. {
  1592. // missionType==255
  1593. reader->skipZero(1);
  1594. }
  1595. }
  1596. void CMapLoaderH3M::readQuest(IQuestObject * guard, const int3 & position)
  1597. {
  1598. guard->quest->missionType = static_cast<CQuest::Emission>(reader->readUInt8());
  1599. switch(guard->quest->missionType)
  1600. {
  1601. case CQuest::MISSION_NONE:
  1602. return;
  1603. case CQuest::MISSION_PRIMARY_STAT:
  1604. {
  1605. guard->quest->m2stats.resize(4);
  1606. for(int x = 0; x < 4; ++x)
  1607. {
  1608. guard->quest->m2stats[x] = reader->readUInt8();
  1609. }
  1610. }
  1611. break;
  1612. case CQuest::MISSION_LEVEL:
  1613. case CQuest::MISSION_KILL_HERO:
  1614. case CQuest::MISSION_KILL_CREATURE:
  1615. {
  1616. guard->quest->m13489val = reader->readUInt32();
  1617. break;
  1618. }
  1619. case CQuest::MISSION_ART:
  1620. {
  1621. int artNumber = reader->readUInt8();
  1622. for(int yy = 0; yy < artNumber; ++yy)
  1623. {
  1624. auto artid = reader->readArtifact();
  1625. guard->quest->addArtifactID(artid);
  1626. map->allowedArtifact[artid] = false; //these are unavailable for random generation
  1627. }
  1628. break;
  1629. }
  1630. case CQuest::MISSION_ARMY:
  1631. {
  1632. int typeNumber = reader->readUInt8();
  1633. guard->quest->m6creatures.resize(typeNumber);
  1634. for(int hh = 0; hh < typeNumber; ++hh)
  1635. {
  1636. guard->quest->m6creatures[hh].type = VLC->creh->objects[reader->readCreature()];
  1637. guard->quest->m6creatures[hh].count = reader->readUInt16();
  1638. }
  1639. break;
  1640. }
  1641. case CQuest::MISSION_RESOURCES:
  1642. {
  1643. for(int x = 0; x < 7; ++x)
  1644. guard->quest->m7resources[x] = reader->readUInt32();
  1645. break;
  1646. }
  1647. case CQuest::MISSION_HERO:
  1648. {
  1649. guard->quest->m13489val = reader->readHero().getNum();
  1650. break;
  1651. }
  1652. case CQuest::MISSION_PLAYER:
  1653. {
  1654. guard->quest->m13489val = reader->readPlayer().getNum();
  1655. break;
  1656. }
  1657. case CQuest::MISSION_HOTA_MULTI:
  1658. {
  1659. uint32_t missionSubID = reader->readUInt32();
  1660. if(missionSubID == 0)
  1661. {
  1662. guard->quest->missionType = CQuest::MISSION_HOTA_HERO_CLASS;
  1663. std::set<HeroClassID> heroClasses;
  1664. reader->readBitmaskHeroClassesSized(heroClasses, false);
  1665. logGlobal->warn("Map '%s': Quest at %s 'Belong to one of %d classes' is not implemented!", mapName, position.toString(), heroClasses.size());
  1666. break;
  1667. }
  1668. if(missionSubID == 1)
  1669. {
  1670. guard->quest->missionType = CQuest::MISSION_HOTA_REACH_DATE;
  1671. uint32_t daysPassed = reader->readUInt32();
  1672. logGlobal->warn("Map '%s': Quest at %s 'Wait till %d days passed' is not implemented!", mapName, position.toString(), daysPassed);
  1673. break;
  1674. }
  1675. assert(0);
  1676. break;
  1677. }
  1678. default:
  1679. {
  1680. assert(0);
  1681. }
  1682. }
  1683. guard->quest->lastDay = reader->readInt32();
  1684. guard->quest->firstVisitText = readLocalizedString(TextIdentifier("quest", position.x, position.y, position.z, "firstVisit"));
  1685. guard->quest->nextVisitText = readLocalizedString(TextIdentifier("quest", position.x, position.y, position.z, "nextVisit"));
  1686. guard->quest->completedText = readLocalizedString(TextIdentifier("quest", position.x, position.y, position.z, "completed"));
  1687. guard->quest->isCustomFirst = !guard->quest->firstVisitText.empty();
  1688. guard->quest->isCustomNext = !guard->quest->nextVisitText.empty();
  1689. guard->quest->isCustomComplete = !guard->quest->completedText.empty();
  1690. }
  1691. CGObjectInstance * CMapLoaderH3M::readTown(const int3 & position, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1692. {
  1693. auto * object = new CGTownInstance();
  1694. if(features.levelAB)
  1695. object->identifier = reader->readUInt32();
  1696. setOwnerAndValidate(position, object, reader->readPlayer());
  1697. std::optional<FactionID> faction;
  1698. if (objectTemplate->id == Obj::TOWN)
  1699. faction = FactionID(objectTemplate->subid);
  1700. bool hasName = reader->readBool();
  1701. if(hasName)
  1702. object->setNameTranslated(readLocalizedString(TextIdentifier("town", position.x, position.y, position.z, "name")));
  1703. bool hasGarrison = reader->readBool();
  1704. if(hasGarrison)
  1705. readCreatureSet(object, 7);
  1706. object->formation = static_cast<EArmyFormation>(reader->readUInt8());
  1707. assert(object->formation == EArmyFormation::LOOSE || object->formation == EArmyFormation::TIGHT);
  1708. bool hasCustomBuildings = reader->readBool();
  1709. if(hasCustomBuildings)
  1710. {
  1711. reader->readBitmaskBuildings(object->builtBuildings, faction);
  1712. reader->readBitmaskBuildings(object->forbiddenBuildings, faction);
  1713. }
  1714. // Standard buildings
  1715. else
  1716. {
  1717. bool hasFort = reader->readBool();
  1718. if(hasFort)
  1719. object->builtBuildings.insert(BuildingID::FORT);
  1720. //means that set of standard building should be included
  1721. object->builtBuildings.insert(BuildingID::DEFAULT);
  1722. }
  1723. if(features.levelAB)
  1724. {
  1725. std::set<SpellID> spellsMask;
  1726. reader->readBitmaskSpells(spellsMask, false);
  1727. std::copy(spellsMask.begin(), spellsMask.end(), std::back_inserter(object->obligatorySpells));
  1728. }
  1729. {
  1730. std::set<SpellID> spellsMask;
  1731. reader->readBitmaskSpells(spellsMask, true);
  1732. std::copy(spellsMask.begin(), spellsMask.end(), std::back_inserter(object->possibleSpells));
  1733. auto defaultAllowed = VLC->spellh->getDefaultAllowed();
  1734. //add all spells from mods
  1735. for(int i = features.spellsCount; i < defaultAllowed.size(); ++i)
  1736. if(defaultAllowed[i])
  1737. object->possibleSpells.emplace_back(i);
  1738. }
  1739. if(features.levelHOTA1)
  1740. {
  1741. // TODO: HOTA support
  1742. [[maybe_unused]] bool spellResearchAvailable = reader->readBool();
  1743. }
  1744. // Read castle events
  1745. uint32_t eventsCount = reader->readUInt32();
  1746. for(int eventID = 0; eventID < eventsCount; ++eventID)
  1747. {
  1748. CCastleEvent event;
  1749. event.town = object;
  1750. event.name = readBasicString();
  1751. event.message = readLocalizedString(TextIdentifier("town", position.x, position.y, position.z, "event", eventID, "description"));
  1752. reader->readResourses(event.resources);
  1753. event.players = reader->readUInt8();
  1754. if(features.levelSOD)
  1755. event.humanAffected = reader->readBool();
  1756. else
  1757. event.humanAffected = true;
  1758. event.computerAffected = reader->readUInt8();
  1759. event.firstOccurence = reader->readUInt16();
  1760. event.nextOccurence = reader->readUInt8();
  1761. reader->skipZero(17);
  1762. // New buildings
  1763. reader->readBitmaskBuildings(event.buildings, faction);
  1764. event.creatures.resize(7);
  1765. for(int i = 0; i < 7; ++i)
  1766. event.creatures[i] = reader->readUInt16();
  1767. reader->skipZero(4);
  1768. object->events.push_back(event);
  1769. }
  1770. if(features.levelSOD)
  1771. {
  1772. object->alignmentToPlayer = PlayerColor::NEUTRAL; // "same as owner or random"
  1773. uint8_t alignment = reader->readUInt8();
  1774. if(alignment != PlayerColor::NEUTRAL.getNum())
  1775. {
  1776. if(alignment < PlayerColor::PLAYER_LIMIT.getNum())
  1777. {
  1778. if (mapHeader->players[alignment].canAnyonePlay())
  1779. object->alignmentToPlayer = PlayerColor(alignment);
  1780. else
  1781. logGlobal->warn("%s - Aligment of town at %s is invalid! Player %d is not present on map!", mapName, position.toString(), int(alignment));
  1782. }
  1783. else
  1784. {
  1785. // TODO: HOTA support
  1786. uint8_t invertedAlignment = alignment - PlayerColor::PLAYER_LIMIT.getNum();
  1787. if(invertedAlignment < PlayerColor::PLAYER_LIMIT.getNum())
  1788. {
  1789. logGlobal->warn("%s - Aligment of town at %s 'not as player %d' is not implemented!", mapName, position.toString(), alignment - PlayerColor::PLAYER_LIMIT.getNum());
  1790. }
  1791. else
  1792. {
  1793. logGlobal->warn("%s - Aligment of town at %s is corrupted!!", mapName, position.toString());
  1794. }
  1795. }
  1796. }
  1797. }
  1798. reader->skipZero(3);
  1799. return object;
  1800. }
  1801. void CMapLoaderH3M::readEvents()
  1802. {
  1803. uint32_t eventsCount = reader->readUInt32();
  1804. for(int eventID = 0; eventID < eventsCount; ++eventID)
  1805. {
  1806. CMapEvent event;
  1807. event.name = readBasicString();
  1808. event.message = readLocalizedString(TextIdentifier("event", eventID, "description"));
  1809. reader->readResourses(event.resources);
  1810. event.players = reader->readUInt8();
  1811. if(features.levelSOD)
  1812. {
  1813. event.humanAffected = reader->readBool();
  1814. }
  1815. else
  1816. {
  1817. event.humanAffected = true;
  1818. }
  1819. event.computerAffected = reader->readBool();
  1820. event.firstOccurence = reader->readUInt16();
  1821. event.nextOccurence = reader->readUInt8();
  1822. reader->skipZero(17);
  1823. map->events.push_back(event);
  1824. }
  1825. }
  1826. void CMapLoaderH3M::readMessageAndGuards(std::string & message, CCreatureSet * guards, const int3 & position)
  1827. {
  1828. bool hasMessage = reader->readBool();
  1829. if(hasMessage)
  1830. {
  1831. message = readLocalizedString(TextIdentifier("guards", position.x, position.y, position.z, "message"));
  1832. bool hasGuards = reader->readBool();
  1833. if(hasGuards)
  1834. readCreatureSet(guards, 7);
  1835. reader->skipZero(4);
  1836. }
  1837. }
  1838. std::string CMapLoaderH3M::readBasicString()
  1839. {
  1840. return TextOperations::toUnicode(reader->readBaseString(), fileEncoding);
  1841. }
  1842. std::string CMapLoaderH3M::readLocalizedString(const TextIdentifier & stringIdentifier)
  1843. {
  1844. std::string mapString = TextOperations::toUnicode(reader->readBaseString(), fileEncoding);
  1845. TextIdentifier fullIdentifier("map", mapName, stringIdentifier.get());
  1846. if(mapString.empty())
  1847. return "";
  1848. VLC->generaltexth->registerString(modName, fullIdentifier, mapString);
  1849. return VLC->generaltexth->translate(fullIdentifier.get());
  1850. }
  1851. void CMapLoaderH3M::afterRead()
  1852. {
  1853. //convert main town positions for all players to actual object position, in H3M it is position of active tile
  1854. for(auto & p : map->players)
  1855. {
  1856. int3 posOfMainTown = p.posOfMainTown;
  1857. if(posOfMainTown.valid() && map->isInTheMap(posOfMainTown))
  1858. {
  1859. const TerrainTile & t = map->getTile(posOfMainTown);
  1860. const CGObjectInstance * mainTown = nullptr;
  1861. for(auto * obj : t.visitableObjects)
  1862. {
  1863. if(obj->ID == Obj::TOWN || obj->ID == Obj::RANDOM_TOWN)
  1864. {
  1865. mainTown = obj;
  1866. break;
  1867. }
  1868. }
  1869. if(mainTown == nullptr)
  1870. continue;
  1871. p.posOfMainTown = posOfMainTown + mainTown->getVisitableOffset();
  1872. }
  1873. }
  1874. }
  1875. VCMI_LIB_NAMESPACE_END