MapFormatH3M.cpp 63 KB

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