MapFormatH3M.cpp 63 KB

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