MapFormatH3M.cpp 60 KB

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