MapFormatH3M.cpp 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308
  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 <boost/crc.hpp>
  12. #include "MapFormatH3M.h"
  13. #include "CMap.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 "../NetPacksBase.h"
  30. VCMI_LIB_NAMESPACE_BEGIN
  31. const bool CMapLoaderH3M::IS_PROFILING_ENABLED = false;
  32. static std::string convertMapName(std::string input)
  33. {
  34. boost::algorithm::to_lower(input);
  35. boost::algorithm::trim(input);
  36. size_t slashPos = input.find_last_of("/");
  37. if (slashPos != std::string::npos)
  38. return input.substr(slashPos + 1);
  39. return input;
  40. }
  41. CMapLoaderH3M::CMapLoaderH3M(const std::string & mapName, const std::string & modName, const std::string & encodingName, CInputStream * stream)
  42. : map(nullptr)
  43. , reader(new CBinaryReader(stream))
  44. , inputStream(stream)
  45. , mapName(convertMapName(mapName))
  46. , modName(modName)
  47. , fileEncoding(encodingName)
  48. {
  49. }
  50. //must be instantiated in .cpp file for access to complete types of all member fields
  51. CMapLoaderH3M::~CMapLoaderH3M() = default;
  52. std::unique_ptr<CMap> CMapLoaderH3M::loadMap()
  53. {
  54. // Init map object by parsing the input buffer
  55. map = new CMap();
  56. mapHeader = std::unique_ptr<CMapHeader>(dynamic_cast<CMapHeader *>(map));
  57. init();
  58. return std::unique_ptr<CMap>(dynamic_cast<CMap *>(mapHeader.release()));
  59. }
  60. std::unique_ptr<CMapHeader> CMapLoaderH3M::loadMapHeader()
  61. {
  62. // Read header
  63. mapHeader = std::make_unique<CMapHeader>();
  64. readHeader();
  65. return std::move(mapHeader);
  66. }
  67. void CMapLoaderH3M::init()
  68. {
  69. //FIXME: get rid of double input process
  70. si64 temp_size = inputStream->getSize();
  71. inputStream->seek(0);
  72. auto * temp_buffer = new ui8[temp_size];
  73. inputStream->read(temp_buffer,temp_size);
  74. // Compute checksum
  75. boost::crc_32_type result;
  76. result.process_bytes(temp_buffer, temp_size);
  77. map->checksum = result.checksum();
  78. delete [] temp_buffer;
  79. inputStream->seek(0);
  80. CStopWatch sw;
  81. struct MapLoadingTime
  82. {
  83. std::string name;
  84. si64 time;
  85. MapLoadingTime(std::string name, si64 time): name(std::move(name)), time(time) {}
  86. };
  87. std::vector<MapLoadingTime> times;
  88. readHeader();
  89. times.emplace_back("header", sw.getDiff());
  90. map->allHeroes.resize(map->allowedHeroes.size());
  91. readDisposedHeroes();
  92. times.emplace_back("disposed heroes", sw.getDiff());
  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. // Print profiling times
  111. if(IS_PROFILING_ENABLED)
  112. {
  113. for(MapLoadingTime & mlt : times)
  114. {
  115. logGlobal->debug("\tReading %s took %d ms", mlt.name, mlt.time);
  116. }
  117. }
  118. map->calculateGuardingGreaturePositions();
  119. afterRead();
  120. }
  121. void CMapLoaderH3M::readHeader()
  122. {
  123. // Check map for validity
  124. // Note: disabled, causes decompression of the entire file ( = SLOW)
  125. //if(inputStream->getSize() < 50)
  126. //{
  127. // throw std::runtime_error("Corrupted map file.");
  128. //}
  129. // Map version
  130. mapHeader->version = static_cast<EMapFormat::EMapFormat>(reader->readUInt32());
  131. if(mapHeader->version != EMapFormat::ROE && mapHeader->version != EMapFormat::AB && mapHeader->version != EMapFormat::SOD
  132. && mapHeader->version != EMapFormat::WOG)
  133. {
  134. throw std::runtime_error("Invalid map format!");
  135. }
  136. // Read map name, description, dimensions,...
  137. mapHeader->areAnyPlayers = reader->readBool();
  138. mapHeader->height = mapHeader->width = reader->readUInt32();
  139. mapHeader->twoLevel = reader->readBool();
  140. mapHeader->name = readLocalizedString("header.name");
  141. mapHeader->description = readLocalizedString("header.description");
  142. mapHeader->difficulty = reader->readInt8();
  143. if(mapHeader->version != EMapFormat::ROE)
  144. {
  145. mapHeader->levelLimit = reader->readUInt8();
  146. }
  147. else
  148. {
  149. mapHeader->levelLimit = 0;
  150. }
  151. readPlayerInfo();
  152. readVictoryLossConditions();
  153. readTeamInfo();
  154. readAllowedHeroes();
  155. }
  156. void CMapLoaderH3M::readPlayerInfo()
  157. {
  158. for(int i = 0; i < mapHeader->players.size(); ++i)
  159. {
  160. mapHeader->players[i].canHumanPlay = reader->readBool();
  161. mapHeader->players[i].canComputerPlay = reader->readBool();
  162. // If nobody can play with this player
  163. if((!(mapHeader->players[i].canHumanPlay || mapHeader->players[i].canComputerPlay)))
  164. {
  165. switch(mapHeader->version)
  166. {
  167. case EMapFormat::SOD:
  168. case EMapFormat::WOG:
  169. reader->skip(13);
  170. break;
  171. case EMapFormat::AB:
  172. reader->skip(12);
  173. break;
  174. case EMapFormat::ROE:
  175. reader->skip(6);
  176. break;
  177. }
  178. continue;
  179. }
  180. mapHeader->players[i].aiTactic = static_cast<EAiTactic::EAiTactic>(reader->readUInt8());
  181. if(mapHeader->version == EMapFormat::SOD || mapHeader->version == EMapFormat::WOG)
  182. {
  183. mapHeader->players[i].p7 = reader->readUInt8();
  184. }
  185. else
  186. {
  187. mapHeader->players[i].p7 = -1;
  188. }
  189. // Factions this player can choose
  190. ui16 allowedFactions = reader->readUInt8();
  191. // How many factions will be read from map
  192. ui16 totalFactions = GameConstants::F_NUMBER;
  193. if(mapHeader->version != EMapFormat::ROE)
  194. allowedFactions += reader->readUInt8() * 256; // 256 = 2^8 = 0b100000000
  195. else
  196. totalFactions--; //exclude conflux for ROE
  197. const bool isFactionRandom = mapHeader->players[i].isFactionRandom = reader->readBool();
  198. const ui16 allFactionsMask = (mapHeader->version == EMapFormat::ROE)
  199. ? 0b11111111 // 8 towns for ROE
  200. : 0b111111111; // 8 towns + Conflux
  201. const bool allFactionsAllowed = mapHeader->version == EMapFormat::VCMI
  202. || (isFactionRandom && ((allowedFactions & allFactionsMask) == allFactionsMask));
  203. if(!allFactionsAllowed)
  204. {
  205. mapHeader->players[i].allowedFactions.clear();
  206. for(int fact = 0; fact < totalFactions; ++fact)
  207. {
  208. if(allowedFactions & (1 << fact))
  209. mapHeader->players[i].allowedFactions.insert(fact);
  210. }
  211. }
  212. mapHeader->players[i].hasMainTown = reader->readBool();
  213. if(mapHeader->players[i].hasMainTown)
  214. {
  215. if(mapHeader->version != EMapFormat::ROE)
  216. {
  217. mapHeader->players[i].generateHeroAtMainTown = reader->readBool();
  218. mapHeader->players[i].generateHero = reader->readBool();
  219. }
  220. else
  221. {
  222. mapHeader->players[i].generateHeroAtMainTown = true;
  223. mapHeader->players[i].generateHero = false;
  224. }
  225. mapHeader->players[i].posOfMainTown = readInt3();
  226. }
  227. mapHeader->players[i].hasRandomHero = reader->readBool();
  228. mapHeader->players[i].mainCustomHeroId = reader->readUInt8();
  229. if(mapHeader->players[i].mainCustomHeroId != 0xff)
  230. {
  231. mapHeader->players[i].mainCustomHeroPortrait = reader->readUInt8();
  232. if (mapHeader->players[i].mainCustomHeroPortrait == 0xff)
  233. mapHeader->players[i].mainCustomHeroPortrait = -1; //correct 1-byte -1 (0xff) into 4-byte -1
  234. mapHeader->players[i].mainCustomHeroName = readLocalizedString(TextIdentifier("header", "player", i, "mainHeroName"));
  235. }
  236. else
  237. mapHeader->players[i].mainCustomHeroId = -1; //correct 1-byte -1 (0xff) into 4-byte -1
  238. if(mapHeader->version != EMapFormat::ROE)
  239. {
  240. mapHeader->players[i].powerPlaceholders = reader->readUInt8(); //unknown byte
  241. int heroCount = reader->readUInt8();
  242. reader->skip(3);
  243. for(int pp = 0; pp < heroCount; ++pp)
  244. {
  245. SHeroName vv;
  246. vv.heroId = reader->readUInt8();
  247. vv.heroName = readLocalizedString( TextIdentifier("header", "heroNames", vv.heroId));
  248. mapHeader->players[i].heroesNames.push_back(vv);
  249. }
  250. }
  251. }
  252. }
  253. namespace EVictoryConditionType
  254. {
  255. enum EVictoryConditionType { ARTIFACT, GATHERTROOP, GATHERRESOURCE, BUILDCITY, BUILDGRAIL, BEATHERO,
  256. CAPTURECITY, BEATMONSTER, TAKEDWELLINGS, TAKEMINES, TRANSPORTITEM, WINSTANDARD = 255 };
  257. }
  258. namespace ELossConditionType
  259. {
  260. enum ELossConditionType { LOSSCASTLE, LOSSHERO, TIMEEXPIRES, LOSSSTANDARD = 255 };
  261. }
  262. void CMapLoaderH3M::readVictoryLossConditions()
  263. {
  264. mapHeader->triggeredEvents.clear();
  265. auto vicCondition = static_cast<EVictoryConditionType::EVictoryConditionType>(reader->readUInt8());
  266. EventCondition victoryCondition(EventCondition::STANDARD_WIN);
  267. EventCondition defeatCondition(EventCondition::DAYS_WITHOUT_TOWN);
  268. defeatCondition.value = 7;
  269. TriggeredEvent standardVictory;
  270. standardVictory.effect.type = EventEffect::VICTORY;
  271. standardVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[5];
  272. standardVictory.identifier = "standardVictory";
  273. standardVictory.description.clear(); // TODO: display in quest window
  274. standardVictory.onFulfill = VLC->generaltexth->allTexts[659];
  275. standardVictory.trigger = EventExpression(victoryCondition);
  276. TriggeredEvent standardDefeat;
  277. standardDefeat.effect.type = EventEffect::DEFEAT;
  278. standardDefeat.effect.toOtherMessage = VLC->generaltexth->allTexts[8];
  279. standardDefeat.identifier = "standardDefeat";
  280. standardDefeat.description.clear(); // TODO: display in quest window
  281. standardDefeat.onFulfill = VLC->generaltexth->allTexts[7];
  282. standardDefeat.trigger = EventExpression(defeatCondition);
  283. // Specific victory conditions
  284. if(vicCondition == EVictoryConditionType::WINSTANDARD)
  285. {
  286. // create normal condition
  287. mapHeader->triggeredEvents.push_back(standardVictory);
  288. mapHeader->victoryIconIndex = 11;
  289. mapHeader->victoryMessage = VLC->generaltexth->victoryConditions[0];
  290. }
  291. else
  292. {
  293. TriggeredEvent specialVictory;
  294. specialVictory.effect.type = EventEffect::VICTORY;
  295. specialVictory.identifier = "specialVictory";
  296. specialVictory.description.clear(); // TODO: display in quest window
  297. mapHeader->victoryIconIndex = static_cast<ui16>(vicCondition);
  298. mapHeader->victoryMessage = VLC->generaltexth->victoryConditions[static_cast<size_t>(vicCondition) + 1];
  299. bool allowNormalVictory = reader->readBool();
  300. bool appliesToAI = reader->readBool();
  301. if (allowNormalVictory)
  302. {
  303. size_t playersOnMap = boost::range::count_if(mapHeader->players,[](const PlayerInfo & info) { return info.canAnyonePlay();});
  304. if (playersOnMap == 1)
  305. {
  306. logGlobal->warn("Map %s has only one player but allows normal victory?", mapHeader->name);
  307. allowNormalVictory = false; // makes sense? Not much. Works as H3? Yes!
  308. }
  309. }
  310. switch(vicCondition)
  311. {
  312. case EVictoryConditionType::ARTIFACT:
  313. {
  314. EventCondition cond(EventCondition::HAVE_ARTIFACT);
  315. cond.objectType = reader->readUInt8();
  316. if (mapHeader->version != EMapFormat::ROE)
  317. reader->skip(1);
  318. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[281];
  319. specialVictory.onFulfill = VLC->generaltexth->allTexts[280];
  320. specialVictory.trigger = EventExpression(cond);
  321. break;
  322. }
  323. case EVictoryConditionType::GATHERTROOP:
  324. {
  325. EventCondition cond(EventCondition::HAVE_CREATURES);
  326. cond.objectType = reader->readUInt8();
  327. if (mapHeader->version != EMapFormat::ROE)
  328. reader->skip(1);
  329. cond.value = reader->readUInt32();
  330. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[277];
  331. specialVictory.onFulfill = VLC->generaltexth->allTexts[276];
  332. specialVictory.trigger = EventExpression(cond);
  333. break;
  334. }
  335. case EVictoryConditionType::GATHERRESOURCE:
  336. {
  337. EventCondition cond(EventCondition::HAVE_RESOURCES);
  338. cond.objectType = reader->readUInt8();
  339. cond.value = reader->readUInt32();
  340. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[279];
  341. specialVictory.onFulfill = VLC->generaltexth->allTexts[278];
  342. specialVictory.trigger = EventExpression(cond);
  343. break;
  344. }
  345. case EVictoryConditionType::BUILDCITY:
  346. {
  347. EventExpression::OperatorAll oper;
  348. EventCondition cond(EventCondition::HAVE_BUILDING);
  349. cond.position = readInt3();
  350. cond.objectType = BuildingID::TOWN_HALL + reader->readUInt8();
  351. oper.expressions.emplace_back(cond);
  352. cond.objectType = BuildingID::FORT + reader->readUInt8();
  353. oper.expressions.emplace_back(cond);
  354. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[283];
  355. specialVictory.onFulfill = VLC->generaltexth->allTexts[282];
  356. specialVictory.trigger = EventExpression(oper);
  357. break;
  358. }
  359. case EVictoryConditionType::BUILDGRAIL:
  360. {
  361. EventCondition cond(EventCondition::HAVE_BUILDING);
  362. cond.objectType = BuildingID::GRAIL;
  363. cond.position = readInt3();
  364. if(cond.position.z > 2)
  365. cond.position = int3(-1,-1,-1);
  366. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[285];
  367. specialVictory.onFulfill = VLC->generaltexth->allTexts[284];
  368. specialVictory.trigger = EventExpression(cond);
  369. break;
  370. }
  371. case EVictoryConditionType::BEATHERO:
  372. {
  373. EventCondition cond(EventCondition::DESTROY);
  374. cond.objectType = Obj::HERO;
  375. cond.position = readInt3();
  376. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[253];
  377. specialVictory.onFulfill = VLC->generaltexth->allTexts[252];
  378. specialVictory.trigger = EventExpression(cond);
  379. break;
  380. }
  381. case EVictoryConditionType::CAPTURECITY:
  382. {
  383. EventCondition cond(EventCondition::CONTROL);
  384. cond.objectType = Obj::TOWN;
  385. cond.position = readInt3();
  386. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[250];
  387. specialVictory.onFulfill = VLC->generaltexth->allTexts[249];
  388. specialVictory.trigger = EventExpression(cond);
  389. break;
  390. }
  391. case EVictoryConditionType::BEATMONSTER:
  392. {
  393. EventCondition cond(EventCondition::DESTROY);
  394. cond.objectType = Obj::MONSTER;
  395. cond.position = readInt3();
  396. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[287];
  397. specialVictory.onFulfill = VLC->generaltexth->allTexts[286];
  398. specialVictory.trigger = EventExpression(cond);
  399. break;
  400. }
  401. case EVictoryConditionType::TAKEDWELLINGS:
  402. {
  403. EventExpression::OperatorAll oper;
  404. oper.expressions.emplace_back(EventCondition(EventCondition::CONTROL, 0, Obj::CREATURE_GENERATOR1));
  405. oper.expressions.emplace_back(EventCondition(EventCondition::CONTROL, 0, Obj::CREATURE_GENERATOR4));
  406. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[289];
  407. specialVictory.onFulfill = VLC->generaltexth->allTexts[288];
  408. specialVictory.trigger = EventExpression(oper);
  409. break;
  410. }
  411. case EVictoryConditionType::TAKEMINES:
  412. {
  413. EventCondition cond(EventCondition::CONTROL);
  414. cond.objectType = Obj::MINE;
  415. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[291];
  416. specialVictory.onFulfill = VLC->generaltexth->allTexts[290];
  417. specialVictory.trigger = EventExpression(cond);
  418. break;
  419. }
  420. case EVictoryConditionType::TRANSPORTITEM:
  421. {
  422. EventCondition cond(EventCondition::TRANSPORT);
  423. cond.objectType = reader->readUInt8();
  424. cond.position = readInt3();
  425. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[293];
  426. specialVictory.onFulfill = VLC->generaltexth->allTexts[292];
  427. specialVictory.trigger = EventExpression(cond);
  428. break;
  429. }
  430. default:
  431. assert(0);
  432. }
  433. // if condition is human-only turn it into following construction: AllOf(human, condition)
  434. if (!appliesToAI)
  435. {
  436. EventExpression::OperatorAll oper;
  437. EventCondition notAI(EventCondition::IS_HUMAN);
  438. notAI.value = 1;
  439. oper.expressions.emplace_back(notAI);
  440. oper.expressions.push_back(specialVictory.trigger.get());
  441. specialVictory.trigger = EventExpression(oper);
  442. }
  443. // if normal victory allowed - add one more quest
  444. if (allowNormalVictory)
  445. {
  446. mapHeader->victoryMessage += " / ";
  447. mapHeader->victoryMessage += VLC->generaltexth->victoryConditions[0];
  448. mapHeader->triggeredEvents.push_back(standardVictory);
  449. }
  450. mapHeader->triggeredEvents.push_back(specialVictory);
  451. }
  452. // Read loss conditions
  453. auto lossCond = static_cast<ELossConditionType::ELossConditionType>(reader->readUInt8());
  454. if (lossCond == ELossConditionType::LOSSSTANDARD)
  455. {
  456. mapHeader->defeatIconIndex = 3;
  457. mapHeader->defeatMessage = VLC->generaltexth->lossCondtions[0];
  458. }
  459. else
  460. {
  461. TriggeredEvent specialDefeat;
  462. specialDefeat.effect.type = EventEffect::DEFEAT;
  463. specialDefeat.effect.toOtherMessage = VLC->generaltexth->allTexts[5];
  464. specialDefeat.identifier = "specialDefeat";
  465. specialDefeat.description.clear(); // TODO: display in quest window
  466. mapHeader->defeatIconIndex = static_cast<ui16>(lossCond);
  467. mapHeader->defeatMessage = VLC->generaltexth->lossCondtions[static_cast<size_t>(lossCond) + 1];
  468. switch(lossCond)
  469. {
  470. case ELossConditionType::LOSSCASTLE:
  471. {
  472. EventExpression::OperatorNone noneOf;
  473. EventCondition cond(EventCondition::CONTROL);
  474. cond.objectType = Obj::TOWN;
  475. cond.position = readInt3();
  476. noneOf.expressions.emplace_back(cond);
  477. specialDefeat.onFulfill = VLC->generaltexth->allTexts[251];
  478. specialDefeat.trigger = EventExpression(noneOf);
  479. break;
  480. }
  481. case ELossConditionType::LOSSHERO:
  482. {
  483. EventExpression::OperatorNone noneOf;
  484. EventCondition cond(EventCondition::CONTROL);
  485. cond.objectType = Obj::HERO;
  486. cond.position = readInt3();
  487. noneOf.expressions.emplace_back(cond);
  488. specialDefeat.onFulfill = VLC->generaltexth->allTexts[253];
  489. specialDefeat.trigger = EventExpression(noneOf);
  490. break;
  491. }
  492. case ELossConditionType::TIMEEXPIRES:
  493. {
  494. EventCondition cond(EventCondition::DAYS_PASSED);
  495. cond.value = reader->readUInt16();
  496. specialDefeat.onFulfill = VLC->generaltexth->allTexts[254];
  497. specialDefeat.trigger = EventExpression(cond);
  498. break;
  499. }
  500. }
  501. // turn simple loss condition into complete one that can be evaluated later:
  502. // - any of :
  503. // - days without town: 7
  504. // - all of:
  505. // - is human
  506. // - (expression)
  507. EventExpression::OperatorAll allOf;
  508. EventCondition isHuman(EventCondition::IS_HUMAN);
  509. isHuman.value = 1;
  510. allOf.expressions.emplace_back(isHuman);
  511. allOf.expressions.push_back(specialDefeat.trigger.get());
  512. specialDefeat.trigger = EventExpression(allOf);
  513. mapHeader->triggeredEvents.push_back(specialDefeat);
  514. }
  515. mapHeader->triggeredEvents.push_back(standardDefeat);
  516. }
  517. void CMapLoaderH3M::readTeamInfo()
  518. {
  519. mapHeader->howManyTeams = reader->readUInt8();
  520. if(mapHeader->howManyTeams > 0)
  521. {
  522. // Teams
  523. for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; ++i)
  524. {
  525. mapHeader->players[i].team = TeamID(reader->readUInt8());
  526. }
  527. }
  528. else
  529. {
  530. // No alliances
  531. for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
  532. {
  533. if(mapHeader->players[i].canComputerPlay || mapHeader->players[i].canHumanPlay)
  534. {
  535. mapHeader->players[i].team = TeamID(mapHeader->howManyTeams++);
  536. }
  537. }
  538. }
  539. }
  540. void CMapLoaderH3M::readAllowedHeroes()
  541. {
  542. mapHeader->allowedHeroes.resize(VLC->heroh->size(), true);
  543. const int bytes = mapHeader->version == EMapFormat::ROE ? 16 : 20;
  544. readBitmask(mapHeader->allowedHeroes,bytes,GameConstants::HEROES_QUANTITY, false);
  545. // Probably reserved for further heroes
  546. if(mapHeader->version > EMapFormat::ROE)
  547. {
  548. int placeholdersQty = reader->readUInt32();
  549. reader->skip(placeholdersQty * 1);
  550. // std::vector<ui16> placeholdedHeroes;
  551. //
  552. // for(int p = 0; p < placeholdersQty; ++p)
  553. // {
  554. // placeholdedHeroes.push_back(reader->readUInt8());
  555. // }
  556. }
  557. }
  558. void CMapLoaderH3M::readDisposedHeroes()
  559. {
  560. // Reading disposed heroes (20 bytes)
  561. if(map->version >= EMapFormat::SOD)
  562. {
  563. ui8 disp = reader->readUInt8();
  564. map->disposedHeroes.resize(disp);
  565. for(int g = 0; g < disp; ++g)
  566. {
  567. map->disposedHeroes[g].heroId = reader->readUInt8();
  568. map->disposedHeroes[g].portrait = reader->readUInt8();
  569. map->disposedHeroes[g].name = readLocalizedString(TextIdentifier("header", "heroes", map->disposedHeroes[g].heroId));
  570. map->disposedHeroes[g].players = reader->readUInt8();
  571. }
  572. }
  573. //omitting NULLS
  574. reader->skip(31);
  575. }
  576. void CMapLoaderH3M::readAllowedArtifacts()
  577. {
  578. map->allowedArtifact.resize (VLC->arth->objects.size(),true); //handle new artifacts, make them allowed by default
  579. // Reading allowed artifacts: 17 or 18 bytes
  580. if(map->version != EMapFormat::ROE)
  581. {
  582. const int bytes = map->version == EMapFormat::AB ? 17 : 18;
  583. readBitmask(map->allowedArtifact,bytes,GameConstants::ARTIFACTS_QUANTITY);
  584. }
  585. // ban combo artifacts
  586. if (map->version == EMapFormat::ROE || map->version == EMapFormat::AB)
  587. {
  588. for(CArtifact * artifact : VLC->arth->objects)
  589. {
  590. // combo
  591. if (artifact->constituents)
  592. {
  593. map->allowedArtifact[artifact->getId()] = false;
  594. }
  595. }
  596. if (map->version == EMapFormat::ROE)
  597. {
  598. map->allowedArtifact[ArtifactID::ARMAGEDDONS_BLADE] = false;
  599. }
  600. }
  601. // Messy, but needed
  602. for (TriggeredEvent & event : map->triggeredEvents)
  603. {
  604. auto patcher = [&](EventCondition cond) -> EventExpression::Variant
  605. {
  606. if (cond.condition == EventCondition::HAVE_ARTIFACT ||
  607. cond.condition == EventCondition::TRANSPORT)
  608. {
  609. map->allowedArtifact[cond.objectType] = false;
  610. }
  611. return cond;
  612. };
  613. event.trigger = event.trigger.morph(patcher);
  614. }
  615. }
  616. void CMapLoaderH3M::readAllowedSpellsAbilities()
  617. {
  618. // Read allowed spells, including new ones
  619. map->allowedSpell.resize(VLC->spellh->objects.size(), true);
  620. // Read allowed abilities
  621. map->allowedAbilities.resize(VLC->skillh->objects.size(), true);
  622. if(map->version >= EMapFormat::SOD)
  623. {
  624. // Reading allowed spells (9 bytes)
  625. const int spell_bytes = 9;
  626. readBitmask(map->allowedSpell, spell_bytes, GameConstants::SPELLS_QUANTITY);
  627. // Allowed hero's abilities (4 bytes)
  628. const int abil_bytes = 4;
  629. readBitmask(map->allowedAbilities, abil_bytes, GameConstants::SKILL_QUANTITY);
  630. }
  631. //do not generate special abilities and spells
  632. for (auto spell : VLC->spellh->objects)
  633. if (spell->isSpecial() || spell->isCreatureAbility())
  634. map->allowedSpell[spell->id] = false;
  635. }
  636. void CMapLoaderH3M::readRumors()
  637. {
  638. int rumNr = reader->readUInt32();
  639. for(int it = 0; it < rumNr; it++)
  640. {
  641. Rumor ourRumor;
  642. ourRumor.name = readBasicString();
  643. ourRumor.text = readLocalizedString(TextIdentifier("header", "rumor", it, "text"));
  644. map->rumors.push_back(ourRumor);
  645. }
  646. }
  647. void CMapLoaderH3M::readPredefinedHeroes()
  648. {
  649. switch(map->version)
  650. {
  651. case EMapFormat::WOG:
  652. case EMapFormat::SOD:
  653. {
  654. // Disposed heroes
  655. for(int z = 0; z < GameConstants::HEROES_QUANTITY; z++)
  656. {
  657. int custom = reader->readUInt8();
  658. if(!custom) continue;
  659. auto * hero = new CGHeroInstance();
  660. hero->ID = Obj::HERO;
  661. hero->subID = z;
  662. bool hasExp = reader->readBool();
  663. if(hasExp)
  664. {
  665. hero->exp = reader->readUInt32();
  666. }
  667. else
  668. {
  669. hero->exp = 0;
  670. }
  671. bool hasSecSkills = reader->readBool();
  672. if(hasSecSkills)
  673. {
  674. int howMany = reader->readUInt32();
  675. hero->secSkills.resize(howMany);
  676. for(int yy = 0; yy < howMany; ++yy)
  677. {
  678. hero->secSkills[yy].first = SecondarySkill(reader->readUInt8());
  679. hero->secSkills[yy].second = reader->readUInt8();
  680. }
  681. }
  682. loadArtifactsOfHero(hero);
  683. bool hasCustomBio = reader->readBool();
  684. if(hasCustomBio)
  685. {
  686. hero->biographyCustom = readLocalizedString(TextIdentifier("heroes", z, "biography"));
  687. }
  688. // 0xFF is default, 00 male, 01 female
  689. hero->sex = reader->readUInt8();
  690. bool hasCustomSpells = reader->readBool();
  691. if(hasCustomSpells)
  692. {
  693. readSpells(hero->spells);
  694. }
  695. bool hasCustomPrimSkills = reader->readBool();
  696. if(hasCustomPrimSkills)
  697. {
  698. for(int xx = 0; xx < GameConstants::PRIMARY_SKILLS; xx++)
  699. {
  700. hero->pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(xx), reader->readUInt8());
  701. }
  702. }
  703. map->predefinedHeroes.emplace_back(hero);
  704. }
  705. break;
  706. }
  707. case EMapFormat::ROE:
  708. break;
  709. }
  710. }
  711. void CMapLoaderH3M::loadArtifactsOfHero(CGHeroInstance * hero)
  712. {
  713. bool artSet = reader->readBool();
  714. // True if artifact set is not default (hero has some artifacts)
  715. if(artSet)
  716. {
  717. if(!hero->artifactsWorn.empty() || !hero->artifactsInBackpack.empty())
  718. {
  719. logGlobal->warn("Hero %s at %s has set artifacts twice (in map properties and on adventure map instance). Using the latter set...",
  720. hero->getNameTranslated(),
  721. hero->pos.toString());
  722. hero->artifactsInBackpack.clear();
  723. while(!hero->artifactsWorn.empty())
  724. hero->eraseArtSlot(hero->artifactsWorn.begin()->first);
  725. }
  726. for(int pom = 0; pom < 16; pom++)
  727. {
  728. loadArtifactToSlot(hero, pom);
  729. }
  730. // misc5 art //17
  731. if(map->version >= EMapFormat::SOD)
  732. {
  733. assert(!hero->getArt(ArtifactPosition::MACH4));
  734. if(!loadArtifactToSlot(hero, ArtifactPosition::MACH4))
  735. {
  736. // catapult by default
  737. assert(!hero->getArt(ArtifactPosition::MACH4));
  738. hero->putArtifact(ArtifactPosition::MACH4, CArtifactInstance::createArtifact(map, ArtifactID::CATAPULT));
  739. }
  740. }
  741. loadArtifactToSlot(hero, ArtifactPosition::SPELLBOOK);
  742. // 19 //???what is that? gap in file or what? - it's probably fifth slot..
  743. if(map->version > EMapFormat::ROE)
  744. {
  745. loadArtifactToSlot(hero, ArtifactPosition::MISC5);
  746. }
  747. else
  748. {
  749. reader->skip(1);
  750. }
  751. // bag artifacts //20
  752. // number of artifacts in hero's bag
  753. int amount = reader->readUInt16();
  754. for(int ss = 0; ss < amount; ++ss)
  755. {
  756. loadArtifactToSlot(hero, GameConstants::BACKPACK_START + static_cast<int>(hero->artifactsInBackpack.size()));
  757. }
  758. }
  759. }
  760. bool CMapLoaderH3M::loadArtifactToSlot(CGHeroInstance * hero, int slot)
  761. {
  762. const int artmask = map->version == EMapFormat::ROE ? 0xff : 0xffff;
  763. ArtifactID aid;
  764. if(map->version == EMapFormat::ROE)
  765. {
  766. aid = ArtifactID(reader->readUInt8());
  767. }
  768. else
  769. {
  770. aid = ArtifactID(reader->readUInt16());
  771. }
  772. bool isArt = aid != artmask;
  773. if(isArt)
  774. {
  775. const Artifact * art = ArtifactID(aid).toArtifact(VLC->artifacts());
  776. if(nullptr == art)
  777. {
  778. logGlobal->warn("Invalid artifact in hero's backpack, ignoring...");
  779. return false;
  780. }
  781. if(art->isBig() && slot >= GameConstants::BACKPACK_START)
  782. {
  783. logGlobal->warn("A big artifact (war machine) in hero's backpack, ignoring...");
  784. return false;
  785. }
  786. if(aid == 0 && slot == ArtifactPosition::MISC5)
  787. {
  788. //TODO: check how H3 handles it -> art 0 in slot 18 in AB map
  789. logGlobal->warn("Spellbook to MISC5 slot? Putting it spellbook place. AB format peculiarity? (format %d)", static_cast<int>(map->version));
  790. slot = ArtifactPosition::SPELLBOOK;
  791. }
  792. // this is needed, because some H3M maps (last scenario of ROE map) contain invalid data like misplaced artifacts
  793. auto * artifact = CArtifactInstance::createArtifact(map, aid);
  794. auto artifactPos = ArtifactPosition(slot);
  795. if (artifact->canBePutAt(ArtifactLocation(hero, artifactPos)))
  796. {
  797. hero->putArtifact(artifactPos, artifact);
  798. }
  799. else
  800. {
  801. logGlobal->debug("Artifact can't be put at the specified location."); //TODO add more debugging information
  802. }
  803. }
  804. return isArt;
  805. }
  806. void CMapLoaderH3M::readTerrain()
  807. {
  808. map->initTerrain();
  809. // Read terrain
  810. int3 pos;
  811. for(pos.z = 0; pos.z < map->levels(); ++pos.z)
  812. {
  813. //OH3 format is [z][y][x]
  814. for(pos.y = 0; pos.y < map->height; pos.y++)
  815. {
  816. for(pos.x = 0; pos.x < map->width; pos.x++)
  817. {
  818. auto & tile = map->getTile(pos);
  819. tile.terType = const_cast<TerrainType*>(VLC->terrainTypeHandler->getByIndex(reader->readUInt8()));
  820. tile.terView = reader->readUInt8();
  821. tile.riverType = const_cast<RiverType*>(VLC->riverTypeHandler->getByIndex(reader->readUInt8()));
  822. tile.riverDir = reader->readUInt8();
  823. tile.roadType = const_cast<RoadType*>(VLC->roadTypeHandler->getByIndex(reader->readUInt8()));
  824. tile.roadDir = reader->readUInt8();
  825. tile.extTileFlags = reader->readUInt8();
  826. tile.blocked = !tile.terType->isPassable();
  827. tile.visitable = false;
  828. assert(tile.terType->getId() != ETerrainId::NONE);
  829. }
  830. }
  831. }
  832. }
  833. void CMapLoaderH3M::readDefInfo()
  834. {
  835. int defAmount = reader->readUInt32();
  836. templates.reserve(defAmount);
  837. // Read custom defs
  838. for(int idd = 0; idd < defAmount; ++idd)
  839. {
  840. auto * tmpl = new ObjectTemplate;
  841. tmpl->readMap(*reader);
  842. templates.push_back(std::shared_ptr<const ObjectTemplate>(tmpl));
  843. }
  844. }
  845. void CMapLoaderH3M::readObjects()
  846. {
  847. int howManyObjs = reader->readUInt32();
  848. for(int ww = 0; ww < howManyObjs; ++ww)
  849. {
  850. CGObjectInstance * nobj = nullptr;
  851. int3 objPos = readInt3();
  852. int defnum = reader->readUInt32();
  853. ObjectInstanceID idToBeGiven = ObjectInstanceID(static_cast<si32>(map->objects.size()));
  854. std::shared_ptr<const ObjectTemplate> objTempl = templates.at(defnum);
  855. reader->skip(5);
  856. switch(objTempl->id)
  857. {
  858. case Obj::EVENT:
  859. {
  860. auto * evnt = new CGEvent();
  861. nobj = evnt;
  862. readMessageAndGuards(evnt->message, evnt, objPos);
  863. evnt->gainedExp = reader->readUInt32();
  864. evnt->manaDiff = reader->readUInt32();
  865. evnt->moraleDiff = reader->readInt8();
  866. evnt->luckDiff = reader->readInt8();
  867. readResourses(evnt->resources);
  868. evnt->primskills.resize(GameConstants::PRIMARY_SKILLS);
  869. for(int x = 0; x < 4; ++x)
  870. {
  871. evnt->primskills[x] = static_cast<PrimarySkill::PrimarySkill>(reader->readUInt8());
  872. }
  873. int gabn = reader->readUInt8(); // Number of gained abilities
  874. for(int oo = 0; oo < gabn; ++oo)
  875. {
  876. evnt->abilities.emplace_back(reader->readUInt8());
  877. evnt->abilityLevels.push_back(reader->readUInt8());
  878. }
  879. int gart = reader->readUInt8(); // Number of gained artifacts
  880. for(int oo = 0; oo < gart; ++oo)
  881. {
  882. if(map->version == EMapFormat::ROE)
  883. {
  884. evnt->artifacts.emplace_back(reader->readUInt8());
  885. }
  886. else
  887. {
  888. evnt->artifacts.emplace_back(reader->readUInt16());
  889. }
  890. }
  891. int gspel = reader->readUInt8(); // Number of gained spells
  892. for(int oo = 0; oo < gspel; ++oo)
  893. {
  894. evnt->spells.emplace_back(reader->readUInt8());
  895. }
  896. int gcre = reader->readUInt8(); //number of gained creatures
  897. readCreatureSet(&evnt->creatures, gcre);
  898. reader->skip(8);
  899. evnt->availableFor = reader->readUInt8();
  900. evnt->computerActivate = reader->readUInt8();
  901. evnt->removeAfterVisit = reader->readUInt8();
  902. evnt->humanActivate = true;
  903. reader->skip(4);
  904. break;
  905. }
  906. case Obj::HERO:
  907. case Obj::RANDOM_HERO:
  908. case Obj::PRISON:
  909. {
  910. nobj = readHero(idToBeGiven, objPos);
  911. break;
  912. }
  913. case Obj::MONSTER: //Monster
  914. case Obj::RANDOM_MONSTER:
  915. case Obj::RANDOM_MONSTER_L1:
  916. case Obj::RANDOM_MONSTER_L2:
  917. case Obj::RANDOM_MONSTER_L3:
  918. case Obj::RANDOM_MONSTER_L4:
  919. case Obj::RANDOM_MONSTER_L5:
  920. case Obj::RANDOM_MONSTER_L6:
  921. case Obj::RANDOM_MONSTER_L7:
  922. {
  923. auto * cre = new CGCreature();
  924. nobj = cre;
  925. if(map->version > EMapFormat::ROE)
  926. {
  927. cre->identifier = reader->readUInt32();
  928. map->questIdentifierToId[cre->identifier] = idToBeGiven;
  929. }
  930. auto * hlp = new CStackInstance();
  931. hlp->count = reader->readUInt16();
  932. //type will be set during initialization
  933. cre->putStack(SlotID(0), hlp);
  934. cre->character = reader->readUInt8();
  935. bool hasMessage = reader->readBool();
  936. if(hasMessage)
  937. {
  938. cre->message = readLocalizedString(TextIdentifier("monster", objPos.x, objPos.y, objPos.z, "message"));
  939. readResourses(cre->resources);
  940. int artID = 0;
  941. if (map->version == EMapFormat::ROE)
  942. {
  943. artID = reader->readUInt8();
  944. }
  945. else
  946. {
  947. artID = reader->readUInt16();
  948. }
  949. if(map->version == EMapFormat::ROE)
  950. {
  951. if(artID != 0xff)
  952. {
  953. cre->gainedArtifact = ArtifactID(artID);
  954. }
  955. else
  956. {
  957. cre->gainedArtifact = ArtifactID::NONE;
  958. }
  959. }
  960. else
  961. {
  962. if(artID != 0xffff)
  963. {
  964. cre->gainedArtifact = ArtifactID(artID);
  965. }
  966. else
  967. {
  968. cre->gainedArtifact = ArtifactID::NONE;
  969. }
  970. }
  971. }
  972. cre->neverFlees = reader->readUInt8();
  973. cre->notGrowingTeam =reader->readUInt8();
  974. reader->skip(2);
  975. break;
  976. }
  977. case Obj::OCEAN_BOTTLE:
  978. case Obj::SIGN:
  979. {
  980. auto * sb = new CGSignBottle();
  981. nobj = sb;
  982. sb->message = readLocalizedString(TextIdentifier("sign", objPos.x, objPos.y, objPos.z, "message"));
  983. reader->skip(4);
  984. break;
  985. }
  986. case Obj::SEER_HUT:
  987. {
  988. nobj = readSeerHut(objPos);
  989. break;
  990. }
  991. case Obj::WITCH_HUT:
  992. {
  993. auto * wh = new CGWitchHut();
  994. nobj = wh;
  995. // in RoE we cannot specify it - all are allowed (I hope)
  996. if(map->version > EMapFormat::ROE)
  997. {
  998. for(int i = 0 ; i < 4; ++i)
  999. {
  1000. ui8 c = reader->readUInt8();
  1001. for(int yy = 0; yy < 8; ++yy)
  1002. {
  1003. if(i * 8 + yy < GameConstants::SKILL_QUANTITY)
  1004. {
  1005. if(c == (c | static_cast<ui8>(std::pow(2., yy))))
  1006. {
  1007. wh->allowedAbilities.push_back(i * 8 + yy);
  1008. }
  1009. }
  1010. }
  1011. }
  1012. // enable new (modded) skills
  1013. if(wh->allowedAbilities.size() != 1)
  1014. {
  1015. for(int skillID = GameConstants::SKILL_QUANTITY; skillID < VLC->skillh->size(); ++skillID)
  1016. wh->allowedAbilities.push_back(skillID);
  1017. }
  1018. }
  1019. else
  1020. {
  1021. // RoE map
  1022. for(int skillID = 0; skillID < VLC->skillh->size(); ++skillID)
  1023. wh->allowedAbilities.push_back(skillID);
  1024. }
  1025. break;
  1026. }
  1027. case Obj::SCHOLAR:
  1028. {
  1029. auto * sch = new CGScholar();
  1030. nobj = sch;
  1031. sch->bonusType = static_cast<CGScholar::EBonusType>(reader->readUInt8());
  1032. sch->bonusID = reader->readUInt8();
  1033. reader->skip(6);
  1034. break;
  1035. }
  1036. case Obj::GARRISON:
  1037. case Obj::GARRISON2:
  1038. {
  1039. auto * gar = new CGGarrison();
  1040. nobj = gar;
  1041. nobj->setOwner(PlayerColor(reader->readUInt8()));
  1042. reader->skip(3);
  1043. readCreatureSet(gar, 7);
  1044. if(map->version > EMapFormat::ROE)
  1045. {
  1046. gar->removableUnits = reader->readBool();
  1047. }
  1048. else
  1049. {
  1050. gar->removableUnits = true;
  1051. }
  1052. reader->skip(8);
  1053. break;
  1054. }
  1055. case Obj::ARTIFACT:
  1056. case Obj::RANDOM_ART:
  1057. case Obj::RANDOM_TREASURE_ART:
  1058. case Obj::RANDOM_MINOR_ART:
  1059. case Obj::RANDOM_MAJOR_ART:
  1060. case Obj::RANDOM_RELIC_ART:
  1061. case Obj::SPELL_SCROLL:
  1062. {
  1063. auto artID = ArtifactID::NONE; //random, set later
  1064. int spellID = -1;
  1065. auto * art = new CGArtifact();
  1066. nobj = art;
  1067. readMessageAndGuards(art->message, art, objPos);
  1068. if(objTempl->id == Obj::SPELL_SCROLL)
  1069. {
  1070. spellID = reader->readUInt32();
  1071. artID = ArtifactID::SPELL_SCROLL;
  1072. }
  1073. else if(objTempl->id == Obj::ARTIFACT)
  1074. {
  1075. //specific artifact
  1076. artID = ArtifactID(objTempl->subid);
  1077. }
  1078. art->storedArtifact = CArtifactInstance::createArtifact(map, artID, spellID);
  1079. break;
  1080. }
  1081. case Obj::RANDOM_RESOURCE:
  1082. case Obj::RESOURCE:
  1083. {
  1084. auto * res = new CGResource();
  1085. nobj = res;
  1086. readMessageAndGuards(res->message, res, objPos);
  1087. res->amount = reader->readUInt32();
  1088. if(objTempl->subid == Res::GOLD)
  1089. {
  1090. // Gold is multiplied by 100.
  1091. res->amount *= 100;
  1092. }
  1093. reader->skip(4);
  1094. break;
  1095. }
  1096. case Obj::RANDOM_TOWN:
  1097. case Obj::TOWN:
  1098. {
  1099. nobj = readTown(objTempl->subid, objPos);
  1100. break;
  1101. }
  1102. case Obj::MINE:
  1103. case Obj::ABANDONED_MINE:
  1104. {
  1105. nobj = new CGMine();
  1106. nobj->setOwner(PlayerColor(reader->readUInt8()));
  1107. reader->skip(3);
  1108. break;
  1109. }
  1110. case Obj::CREATURE_GENERATOR1:
  1111. case Obj::CREATURE_GENERATOR2:
  1112. case Obj::CREATURE_GENERATOR3:
  1113. case Obj::CREATURE_GENERATOR4:
  1114. {
  1115. nobj = new CGDwelling();
  1116. nobj->setOwner(PlayerColor(reader->readUInt8()));
  1117. reader->skip(3);
  1118. break;
  1119. }
  1120. case Obj::SHRINE_OF_MAGIC_INCANTATION:
  1121. case Obj::SHRINE_OF_MAGIC_GESTURE:
  1122. case Obj::SHRINE_OF_MAGIC_THOUGHT:
  1123. {
  1124. auto * shr = new CGShrine();
  1125. nobj = shr;
  1126. ui8 raw_id = reader->readUInt8();
  1127. if (255 == raw_id)
  1128. {
  1129. shr->spell = SpellID(SpellID::NONE);
  1130. }
  1131. else
  1132. {
  1133. shr->spell = SpellID(raw_id);
  1134. }
  1135. reader->skip(3);
  1136. break;
  1137. }
  1138. case Obj::PANDORAS_BOX:
  1139. {
  1140. auto * box = new CGPandoraBox();
  1141. nobj = box;
  1142. readMessageAndGuards(box->message, box, objPos);
  1143. box->gainedExp = reader->readUInt32();
  1144. box->manaDiff = reader->readUInt32();
  1145. box->moraleDiff = reader->readInt8();
  1146. box->luckDiff = reader->readInt8();
  1147. readResourses(box->resources);
  1148. box->primskills.resize(GameConstants::PRIMARY_SKILLS);
  1149. for(int x = 0; x < 4; ++x)
  1150. {
  1151. box->primskills[x] = static_cast<PrimarySkill::PrimarySkill>(reader->readUInt8());
  1152. }
  1153. int gabn = reader->readUInt8();//number of gained abilities
  1154. for(int oo = 0; oo < gabn; ++oo)
  1155. {
  1156. box->abilities.emplace_back(reader->readUInt8());
  1157. box->abilityLevels.push_back(reader->readUInt8());
  1158. }
  1159. int gart = reader->readUInt8(); //number of gained artifacts
  1160. for(int oo = 0; oo < gart; ++oo)
  1161. {
  1162. if(map->version > EMapFormat::ROE)
  1163. {
  1164. box->artifacts.emplace_back(reader->readUInt16());
  1165. }
  1166. else
  1167. {
  1168. box->artifacts.emplace_back(reader->readUInt8());
  1169. }
  1170. }
  1171. int gspel = reader->readUInt8(); //number of gained spells
  1172. for(int oo = 0; oo < gspel; ++oo)
  1173. {
  1174. box->spells.emplace_back(reader->readUInt8());
  1175. }
  1176. int gcre = reader->readUInt8(); //number of gained creatures
  1177. readCreatureSet(&box->creatures, gcre);
  1178. reader->skip(8);
  1179. break;
  1180. }
  1181. case Obj::GRAIL:
  1182. {
  1183. map->grailPos = objPos;
  1184. map->grailRadius = reader->readUInt32();
  1185. continue;
  1186. }
  1187. case Obj::RANDOM_DWELLING: //same as castle + level range
  1188. case Obj::RANDOM_DWELLING_LVL: //same as castle, fixed level
  1189. case Obj::RANDOM_DWELLING_FACTION: //level range, fixed faction
  1190. {
  1191. auto * dwelling = new CGDwelling();
  1192. nobj = dwelling;
  1193. CSpecObjInfo * spec = nullptr;
  1194. switch(objTempl->id)
  1195. {
  1196. case Obj::RANDOM_DWELLING:
  1197. spec = new CCreGenLeveledCastleInfo();
  1198. break;
  1199. case Obj::RANDOM_DWELLING_LVL:
  1200. spec = new CCreGenAsCastleInfo();
  1201. break;
  1202. case Obj::RANDOM_DWELLING_FACTION:
  1203. spec = new CCreGenLeveledInfo();
  1204. break;
  1205. default:
  1206. throw std::runtime_error("Invalid random dwelling format");
  1207. }
  1208. spec->owner = dwelling;
  1209. nobj->setOwner(PlayerColor(reader->readUInt32()));
  1210. //216 and 217
  1211. if(auto * castleSpec = dynamic_cast<CCreGenAsCastleInfo *>(spec))
  1212. {
  1213. castleSpec->instanceId = "";
  1214. castleSpec->identifier = reader->readUInt32();
  1215. if(!castleSpec->identifier)
  1216. {
  1217. castleSpec->asCastle = false;
  1218. const int MASK_SIZE = 8;
  1219. ui8 mask[2];
  1220. mask[0] = reader->readUInt8();
  1221. mask[1] = reader->readUInt8();
  1222. castleSpec->allowedFactions.clear();
  1223. castleSpec->allowedFactions.resize(VLC->townh->size(), false);
  1224. for(int i = 0; i < MASK_SIZE; i++)
  1225. castleSpec->allowedFactions[i] = ((mask[0] & (1 << i))>0);
  1226. for(int i = 0; i < (GameConstants::F_NUMBER-MASK_SIZE); i++)
  1227. castleSpec->allowedFactions[i+MASK_SIZE] = ((mask[1] & (1 << i))>0);
  1228. }
  1229. else
  1230. {
  1231. castleSpec->asCastle = true;
  1232. }
  1233. }
  1234. //216 and 218
  1235. if(auto * lvlSpec = dynamic_cast<CCreGenLeveledInfo *>(spec))
  1236. {
  1237. lvlSpec->minLevel = std::max(reader->readUInt8(), static_cast<ui8>(1));
  1238. lvlSpec->maxLevel = std::min(reader->readUInt8(), static_cast<ui8>(7));
  1239. }
  1240. dwelling->info = spec;
  1241. break;
  1242. }
  1243. case Obj::QUEST_GUARD:
  1244. {
  1245. auto * guard = new CGQuestGuard();
  1246. readQuest(guard, objPos);
  1247. nobj = guard;
  1248. break;
  1249. }
  1250. case Obj::SHIPYARD:
  1251. {
  1252. nobj = new CGShipyard();
  1253. nobj->setOwner(PlayerColor(reader->readUInt32()));
  1254. break;
  1255. }
  1256. case Obj::HERO_PLACEHOLDER: //hero placeholder
  1257. {
  1258. auto * hp = new CGHeroPlaceholder();
  1259. nobj = hp;
  1260. hp->setOwner(PlayerColor(reader->readUInt8()));
  1261. int htid = reader->readUInt8(); //hero type id
  1262. nobj->subID = htid;
  1263. if(htid == 0xff)
  1264. {
  1265. hp->power = reader->readUInt8();
  1266. logGlobal->debug("Hero placeholder: by power at %s", objPos.toString());
  1267. }
  1268. else
  1269. {
  1270. logGlobal->debug("Hero placeholder: %s at %s", VLC->heroh->objects[htid]->getNameTranslated(), objPos.toString());
  1271. hp->power = 0;
  1272. }
  1273. break;
  1274. }
  1275. case Obj::BORDERGUARD:
  1276. {
  1277. nobj = new CGBorderGuard();
  1278. break;
  1279. }
  1280. case Obj::BORDER_GATE:
  1281. {
  1282. nobj = new CGBorderGate();
  1283. break;
  1284. }
  1285. case Obj::PYRAMID: //Pyramid of WoG object
  1286. {
  1287. if(objTempl->subid == 0)
  1288. {
  1289. nobj = new CBank();
  1290. }
  1291. else
  1292. {
  1293. //WoG object
  1294. //TODO: possible special handling
  1295. nobj = new CGObjectInstance();
  1296. }
  1297. break;
  1298. }
  1299. case Obj::LIGHTHOUSE: //Lighthouse
  1300. {
  1301. nobj = new CGLighthouse();
  1302. nobj->tempOwner = PlayerColor(reader->readUInt32());
  1303. break;
  1304. }
  1305. default: //any other object
  1306. {
  1307. if (VLC->objtypeh->knownSubObjects(objTempl->id).count(objTempl->subid))
  1308. {
  1309. nobj = VLC->objtypeh->getHandlerFor(objTempl->id, objTempl->subid)->create(objTempl);
  1310. }
  1311. else
  1312. {
  1313. logGlobal->warn("Unrecognized object: %d:%d at %s on map %s", objTempl->id.toEnum(), objTempl->subid, objPos.toString(), map->name);
  1314. nobj = new CGObjectInstance();
  1315. }
  1316. break;
  1317. }
  1318. }
  1319. nobj->pos = objPos;
  1320. nobj->ID = objTempl->id;
  1321. nobj->id = idToBeGiven;
  1322. if(nobj->ID != Obj::HERO && nobj->ID != Obj::HERO_PLACEHOLDER && nobj->ID != Obj::PRISON)
  1323. {
  1324. nobj->subID = objTempl->subid;
  1325. }
  1326. nobj->appearance = objTempl;
  1327. assert(idToBeGiven == ObjectInstanceID((si32)map->objects.size()));
  1328. {
  1329. //TODO: define valid typeName and subtypeName fro H3M maps
  1330. //boost::format fmt("%s_%d");
  1331. //fmt % nobj->typeName % nobj->id.getNum();
  1332. boost::format fmt("obj_%d");
  1333. fmt % nobj->id.getNum();
  1334. nobj->instanceName = fmt.str();
  1335. }
  1336. map->addNewObject(nobj);
  1337. }
  1338. std::sort(map->heroesOnMap.begin(), map->heroesOnMap.end(), [](const ConstTransitivePtr<CGHeroInstance> & a, const ConstTransitivePtr<CGHeroInstance> & b)
  1339. {
  1340. return a->subID < b->subID;
  1341. });
  1342. }
  1343. void CMapLoaderH3M::readCreatureSet(CCreatureSet * out, int number)
  1344. {
  1345. const bool version = (map->version > EMapFormat::ROE);
  1346. const int maxID = version ? 0xffff : 0xff;
  1347. for(int ir = 0; ir < number; ++ir)
  1348. {
  1349. CreatureID creID;
  1350. int count = 0;
  1351. if (version)
  1352. {
  1353. creID = CreatureID(reader->readUInt16());
  1354. }
  1355. else
  1356. {
  1357. creID = CreatureID(reader->readUInt8());
  1358. }
  1359. count = reader->readUInt16();
  1360. // Empty slot
  1361. if(creID == maxID)
  1362. continue;
  1363. auto * hlp = new CStackInstance();
  1364. hlp->count = count;
  1365. if(creID > maxID - 0xf)
  1366. {
  1367. //this will happen when random object has random army
  1368. hlp->idRand = maxID - creID - 1;
  1369. }
  1370. else
  1371. {
  1372. hlp->setType(creID);
  1373. }
  1374. out->putStack(SlotID(ir), hlp);
  1375. }
  1376. out->validTypes(true);
  1377. }
  1378. CGObjectInstance * CMapLoaderH3M::readHero(const ObjectInstanceID & idToBeGiven, const int3 & initialPos)
  1379. {
  1380. auto * nhi = new CGHeroInstance();
  1381. if(map->version > EMapFormat::ROE)
  1382. {
  1383. unsigned int identifier = reader->readUInt32();
  1384. map->questIdentifierToId[identifier] = idToBeGiven;
  1385. }
  1386. PlayerColor owner = PlayerColor(reader->readUInt8());
  1387. nhi->subID = reader->readUInt8();
  1388. assert(!nhi->getArt(ArtifactPosition::MACH4));
  1389. //If hero of this type has been predefined, use that as a base.
  1390. //Instance data will overwrite the predefined values where appropriate.
  1391. for(auto & elem : map->predefinedHeroes)
  1392. {
  1393. if(elem->subID == nhi->subID)
  1394. {
  1395. logGlobal->debug("Hero %d will be taken from the predefined heroes list.", nhi->subID);
  1396. delete nhi;
  1397. nhi = elem;
  1398. break;
  1399. }
  1400. }
  1401. nhi->setOwner(owner);
  1402. nhi->portrait = nhi->subID;
  1403. for(auto & elem : map->disposedHeroes)
  1404. {
  1405. if(elem.heroId == nhi->subID)
  1406. {
  1407. nhi->nameCustom = elem.name;
  1408. nhi->portrait = elem.portrait;
  1409. break;
  1410. }
  1411. }
  1412. bool hasName = reader->readBool();
  1413. if(hasName)
  1414. {
  1415. nhi->nameCustom = readLocalizedString(TextIdentifier("heroes", nhi->subID, "name"));
  1416. }
  1417. if(map->version > EMapFormat::AB)
  1418. {
  1419. bool hasExp = reader->readBool();
  1420. if(hasExp)
  1421. {
  1422. nhi->exp = reader->readUInt32();
  1423. }
  1424. else
  1425. {
  1426. nhi->exp = CGHeroInstance::UNINITIALIZED_EXPERIENCE;
  1427. }
  1428. }
  1429. else
  1430. {
  1431. nhi->exp = reader->readUInt32();
  1432. //0 means "not set" in <=AB maps
  1433. if(!nhi->exp)
  1434. {
  1435. nhi->exp = CGHeroInstance::UNINITIALIZED_EXPERIENCE;
  1436. }
  1437. }
  1438. bool hasPortrait = reader->readBool();
  1439. if(hasPortrait)
  1440. {
  1441. nhi->portrait = reader->readUInt8();
  1442. }
  1443. bool hasSecSkills = reader->readBool();
  1444. if(hasSecSkills)
  1445. {
  1446. if(!nhi->secSkills.empty())
  1447. {
  1448. nhi->secSkills.clear();
  1449. //logGlobal->warn("Hero %s subID=%d has set secondary skills twice (in map properties and on adventure map instance). Using the latter set...", nhi->name, nhi->subID);
  1450. }
  1451. int howMany = reader->readUInt32();
  1452. nhi->secSkills.resize(howMany);
  1453. for(int yy = 0; yy < howMany; ++yy)
  1454. {
  1455. nhi->secSkills[yy].first = SecondarySkill(reader->readUInt8());
  1456. nhi->secSkills[yy].second = reader->readUInt8();
  1457. }
  1458. }
  1459. bool hasGarison = reader->readBool();
  1460. if(hasGarison)
  1461. {
  1462. readCreatureSet(nhi, 7);
  1463. }
  1464. nhi->formation = reader->readUInt8();
  1465. loadArtifactsOfHero(nhi);
  1466. nhi->patrol.patrolRadius = reader->readUInt8();
  1467. nhi->patrol.patrolling = (nhi->patrol.patrolRadius != 0xff);
  1468. if(map->version > EMapFormat::ROE)
  1469. {
  1470. bool hasCustomBiography = reader->readBool();
  1471. if(hasCustomBiography)
  1472. {
  1473. nhi->biographyCustom = readLocalizedString(TextIdentifier("heroes", nhi->subID, "biography"));
  1474. }
  1475. nhi->sex = reader->readUInt8();
  1476. // Remove trash
  1477. if (nhi->sex != 0xFF)
  1478. {
  1479. nhi->sex &= 1;
  1480. }
  1481. }
  1482. else
  1483. {
  1484. nhi->sex = 0xFF;
  1485. }
  1486. // Spells
  1487. if(map->version > EMapFormat::AB)
  1488. {
  1489. bool hasCustomSpells = reader->readBool();
  1490. if(!nhi->spells.empty())
  1491. {
  1492. nhi->clear();
  1493. 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);
  1494. }
  1495. if(hasCustomSpells)
  1496. {
  1497. nhi->spells.insert(SpellID::PRESET); //placeholder "preset spells"
  1498. readSpells(nhi->spells);
  1499. }
  1500. }
  1501. else if(map->version == EMapFormat::AB)
  1502. {
  1503. //we can read one spell
  1504. ui8 buff = reader->readUInt8();
  1505. if(buff != 254)
  1506. {
  1507. nhi->spells.insert(SpellID::PRESET); //placeholder "preset spells"
  1508. if(buff < 254) //255 means no spells
  1509. {
  1510. nhi->spells.insert(SpellID(buff));
  1511. }
  1512. }
  1513. }
  1514. if(map->version > EMapFormat::AB)
  1515. {
  1516. bool hasCustomPrimSkills = reader->readBool();
  1517. if(hasCustomPrimSkills)
  1518. {
  1519. auto ps = nhi->getAllBonuses(Selector::type()(Bonus::PRIMARY_SKILL)
  1520. .And(Selector::sourceType()(Bonus::HERO_BASE_SKILL)), nullptr);
  1521. if(ps->size())
  1522. {
  1523. 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);
  1524. for(const auto & b : *ps)
  1525. nhi->removeBonus(b);
  1526. }
  1527. for(int xx = 0; xx < GameConstants::PRIMARY_SKILLS; ++xx)
  1528. {
  1529. nhi->pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(xx), reader->readUInt8());
  1530. }
  1531. }
  1532. }
  1533. reader->skip(16);
  1534. return nhi;
  1535. }
  1536. CGSeerHut * CMapLoaderH3M::readSeerHut(const int3 & position)
  1537. {
  1538. auto * hut = new CGSeerHut();
  1539. if(map->version > EMapFormat::ROE)
  1540. {
  1541. readQuest(hut, position);
  1542. }
  1543. else
  1544. {
  1545. //RoE
  1546. auto artID = ArtifactID(reader->readUInt8());
  1547. if (artID != 255)
  1548. {
  1549. //not none quest
  1550. hut->quest->addArtifactID(artID);
  1551. hut->quest->missionType = CQuest::MISSION_ART;
  1552. }
  1553. else
  1554. {
  1555. hut->quest->missionType = CQuest::MISSION_NONE;
  1556. }
  1557. hut->quest->lastDay = -1; //no timeout
  1558. hut->quest->isCustomFirst = hut->quest->isCustomNext = hut->quest->isCustomComplete = false;
  1559. }
  1560. if (hut->quest->missionType)
  1561. {
  1562. auto rewardType = static_cast<CGSeerHut::ERewardType>(reader->readUInt8());
  1563. hut->rewardType = rewardType;
  1564. switch(rewardType)
  1565. {
  1566. case CGSeerHut::EXPERIENCE:
  1567. {
  1568. hut->rVal = reader->readUInt32();
  1569. break;
  1570. }
  1571. case CGSeerHut::MANA_POINTS:
  1572. {
  1573. hut->rVal = reader->readUInt32();
  1574. break;
  1575. }
  1576. case CGSeerHut::MORALE_BONUS:
  1577. {
  1578. hut->rVal = reader->readUInt8();
  1579. break;
  1580. }
  1581. case CGSeerHut::LUCK_BONUS:
  1582. {
  1583. hut->rVal = reader->readUInt8();
  1584. break;
  1585. }
  1586. case CGSeerHut::RESOURCES:
  1587. {
  1588. hut->rID = reader->readUInt8();
  1589. // Only the first 3 bytes are used. Skip the 4th.
  1590. hut->rVal = reader->readUInt32() & 0x00ffffff;
  1591. break;
  1592. }
  1593. case CGSeerHut::PRIMARY_SKILL:
  1594. {
  1595. hut->rID = reader->readUInt8();
  1596. hut->rVal = reader->readUInt8();
  1597. break;
  1598. }
  1599. case CGSeerHut::SECONDARY_SKILL:
  1600. {
  1601. hut->rID = reader->readUInt8();
  1602. hut->rVal = reader->readUInt8();
  1603. break;
  1604. }
  1605. case CGSeerHut::ARTIFACT:
  1606. {
  1607. if (map->version == EMapFormat::ROE)
  1608. {
  1609. hut->rID = reader->readUInt8();
  1610. }
  1611. else
  1612. {
  1613. hut->rID = reader->readUInt16();
  1614. }
  1615. break;
  1616. }
  1617. case CGSeerHut::SPELL:
  1618. {
  1619. hut->rID = reader->readUInt8();
  1620. break;
  1621. }
  1622. case CGSeerHut::CREATURE:
  1623. {
  1624. if(map->version > EMapFormat::ROE)
  1625. {
  1626. hut->rID = reader->readUInt16();
  1627. hut->rVal = reader->readUInt16();
  1628. }
  1629. else
  1630. {
  1631. hut->rID = reader->readUInt8();
  1632. hut->rVal = reader->readUInt16();
  1633. }
  1634. break;
  1635. }
  1636. }
  1637. reader->skip(2);
  1638. }
  1639. else
  1640. {
  1641. // missionType==255
  1642. reader->skip(3);
  1643. }
  1644. return hut;
  1645. }
  1646. void CMapLoaderH3M::readQuest(IQuestObject * guard, const int3 & position)
  1647. {
  1648. guard->quest->missionType = static_cast<CQuest::Emission>(reader->readUInt8());
  1649. switch(guard->quest->missionType)
  1650. {
  1651. case CQuest::MISSION_NONE:
  1652. return;
  1653. case CQuest::MISSION_PRIMARY_STAT:
  1654. {
  1655. guard->quest->m2stats.resize(4);
  1656. for(int x = 0; x < 4; ++x)
  1657. {
  1658. guard->quest->m2stats[x] = reader->readUInt8();
  1659. }
  1660. }
  1661. break;
  1662. case CQuest::MISSION_LEVEL:
  1663. case CQuest::MISSION_KILL_HERO:
  1664. case CQuest::MISSION_KILL_CREATURE:
  1665. {
  1666. guard->quest->m13489val = reader->readUInt32();
  1667. break;
  1668. }
  1669. case CQuest::MISSION_ART:
  1670. {
  1671. int artNumber = reader->readUInt8();
  1672. for(int yy = 0; yy < artNumber; ++yy)
  1673. {
  1674. auto artid = ArtifactID(reader->readUInt16());
  1675. guard->quest->addArtifactID(artid);
  1676. map->allowedArtifact[artid] = false; //these are unavailable for random generation
  1677. }
  1678. break;
  1679. }
  1680. case CQuest::MISSION_ARMY:
  1681. {
  1682. int typeNumber = reader->readUInt8();
  1683. guard->quest->m6creatures.resize(typeNumber);
  1684. for(int hh = 0; hh < typeNumber; ++hh)
  1685. {
  1686. guard->quest->m6creatures[hh].type = VLC->creh->objects[reader->readUInt16()];
  1687. guard->quest->m6creatures[hh].count = reader->readUInt16();
  1688. }
  1689. break;
  1690. }
  1691. case CQuest::MISSION_RESOURCES:
  1692. {
  1693. guard->quest->m7resources.resize(7);
  1694. for(int x = 0; x < 7; ++x)
  1695. {
  1696. guard->quest->m7resources[x] = reader->readUInt32();
  1697. }
  1698. break;
  1699. }
  1700. case CQuest::MISSION_HERO:
  1701. case CQuest::MISSION_PLAYER:
  1702. {
  1703. guard->quest->m13489val = reader->readUInt8();
  1704. break;
  1705. }
  1706. }
  1707. int limit = reader->readUInt32();
  1708. if(limit == (static_cast<int>(0xffffffff)))
  1709. {
  1710. guard->quest->lastDay = -1;
  1711. }
  1712. else
  1713. {
  1714. guard->quest->lastDay = limit;
  1715. }
  1716. guard->quest->firstVisitText = readLocalizedString(TextIdentifier("quest", position.x, position.y, position.z, "firstVisit"));
  1717. guard->quest->nextVisitText = readLocalizedString(TextIdentifier("quest", position.x, position.y, position.z, "nextVisit"));
  1718. guard->quest->completedText = readLocalizedString(TextIdentifier("quest", position.x, position.y, position.z, "completed"));
  1719. guard->quest->isCustomFirst = !guard->quest->firstVisitText.empty();
  1720. guard->quest->isCustomNext = !guard->quest->nextVisitText.empty();
  1721. guard->quest->isCustomComplete = !guard->quest->completedText.empty();
  1722. }
  1723. CGTownInstance * CMapLoaderH3M::readTown(int castleID, const int3 & position)
  1724. {
  1725. auto * nt = new CGTownInstance();
  1726. if(map->version > EMapFormat::ROE)
  1727. {
  1728. nt->identifier = reader->readUInt32();
  1729. }
  1730. nt->tempOwner = PlayerColor(reader->readUInt8());
  1731. bool hasName = reader->readBool();
  1732. if(hasName)
  1733. {
  1734. nt->setNameTranslated(readLocalizedString(TextIdentifier("town", position.x, position.y, position.z, "name")));
  1735. }
  1736. bool hasGarrison = reader->readBool();
  1737. if(hasGarrison)
  1738. {
  1739. readCreatureSet(nt, 7);
  1740. }
  1741. nt->formation = reader->readUInt8();
  1742. bool hasCustomBuildings = reader->readBool();
  1743. if(hasCustomBuildings)
  1744. {
  1745. readBitmask(nt->builtBuildings,6,48,false);
  1746. readBitmask(nt->forbiddenBuildings,6,48,false);
  1747. nt->builtBuildings = convertBuildings(nt->builtBuildings, castleID);
  1748. nt->forbiddenBuildings = convertBuildings(nt->forbiddenBuildings, castleID);
  1749. }
  1750. // Standard buildings
  1751. else
  1752. {
  1753. bool hasFort = reader->readBool();
  1754. if(hasFort)
  1755. {
  1756. nt->builtBuildings.insert(BuildingID::FORT);
  1757. }
  1758. //means that set of standard building should be included
  1759. nt->builtBuildings.insert(BuildingID::DEFAULT);
  1760. }
  1761. if(map->version > EMapFormat::ROE)
  1762. {
  1763. for(int i = 0; i < 9; ++i)
  1764. {
  1765. ui8 c = reader->readUInt8();
  1766. for(int yy = 0; yy < 8; ++yy)
  1767. {
  1768. if(i * 8 + yy < GameConstants::SPELLS_QUANTITY)
  1769. {
  1770. if(c == (c | static_cast<ui8>(std::pow(2., yy)))) //add obligatory spell even if it's banned on a map (?)
  1771. {
  1772. nt->obligatorySpells.emplace_back(i * 8 + yy);
  1773. }
  1774. }
  1775. }
  1776. }
  1777. }
  1778. for(int i = 0; i < 9; ++i)
  1779. {
  1780. ui8 c = reader->readUInt8();
  1781. for(int yy = 0; yy < 8; ++yy)
  1782. {
  1783. int spellid = i * 8 + yy;
  1784. if(spellid < GameConstants::SPELLS_QUANTITY)
  1785. {
  1786. if(c != (c | static_cast<ui8>(std::pow(2., yy))) && map->allowedSpell[spellid]) //add random spell only if it's allowed on entire map
  1787. {
  1788. nt->possibleSpells.emplace_back(spellid);
  1789. }
  1790. }
  1791. }
  1792. }
  1793. //add all spells from mods
  1794. //TODO: allow customize new spells in towns
  1795. for (int i = SpellID::AFTER_LAST; i < VLC->spellh->objects.size(); ++i)
  1796. {
  1797. nt->possibleSpells.emplace_back(i);
  1798. }
  1799. // Read castle events
  1800. int numberOfEvent = reader->readUInt32();
  1801. for(int gh = 0; gh < numberOfEvent; ++gh)
  1802. {
  1803. CCastleEvent nce;
  1804. nce.town = nt;
  1805. nce.name = readBasicString();
  1806. nce.message = readLocalizedString(TextIdentifier("town", position.x, position.y, position.z, "event", gh, "description"));
  1807. readResourses(nce.resources);
  1808. nce.players = reader->readUInt8();
  1809. if(map->version > EMapFormat::AB)
  1810. {
  1811. nce.humanAffected = reader->readUInt8();
  1812. }
  1813. else
  1814. {
  1815. nce.humanAffected = true;
  1816. }
  1817. nce.computerAffected = reader->readUInt8();
  1818. nce.firstOccurence = reader->readUInt16();
  1819. nce.nextOccurence = reader->readUInt8();
  1820. reader->skip(17);
  1821. // New buildings
  1822. readBitmask(nce.buildings,6,48,false);
  1823. nce.buildings = convertBuildings(nce.buildings, castleID, false);
  1824. nce.creatures.resize(7);
  1825. for(int vv = 0; vv < 7; ++vv)
  1826. {
  1827. nce.creatures[vv] = reader->readUInt16();
  1828. }
  1829. reader->skip(4);
  1830. nt->events.push_back(nce);
  1831. }
  1832. if(map->version > EMapFormat::AB)
  1833. {
  1834. nt->alignment = reader->readUInt8();
  1835. }
  1836. reader->skip(3);
  1837. return nt;
  1838. }
  1839. std::set<BuildingID> CMapLoaderH3M::convertBuildings(const std::set<BuildingID> & h3m, int castleID, bool addAuxiliary) const
  1840. {
  1841. std::map<int, BuildingID> helperMap;
  1842. std::set<BuildingID> ret;
  1843. // Note: this file is parsed many times.
  1844. const JsonNode config(ResourceID("config/buildings5.json"));
  1845. for(const JsonNode & entry : config["table"].Vector())
  1846. {
  1847. int town = static_cast<int>(entry["town"].Float());
  1848. if (town == castleID || town == -1)
  1849. {
  1850. helperMap[static_cast<int>(entry["h3"].Float())] = BuildingID(static_cast<si32>(entry["vcmi"].Float()));
  1851. }
  1852. }
  1853. for(const auto & elem : h3m)
  1854. {
  1855. if(helperMap[elem] >= BuildingID::FIRST_REGULAR_ID)
  1856. {
  1857. ret.insert(helperMap[elem]);
  1858. }
  1859. // horde buildings use indexes from -1 to -5, where creature level is 1 to 5
  1860. else if(helperMap[elem] >= (-GameConstants::CREATURES_PER_TOWN))
  1861. {
  1862. int level = (helperMap[elem]);
  1863. //(-30)..(-36) - horde buildings (for game loading only)
  1864. //They will be replaced in CGameState::initTowns()
  1865. ret.insert(BuildingID(level + BuildingID::HORDE_BUILDING_CONVERTER)); //-1 => -30
  1866. }
  1867. else
  1868. {
  1869. logGlobal->warn("Conversion warning: unknown building %d in castle %d", elem.num, castleID);
  1870. }
  1871. }
  1872. if(addAuxiliary)
  1873. {
  1874. //village hall is always present
  1875. ret.insert(BuildingID::VILLAGE_HALL);
  1876. if(ret.find(BuildingID::CITY_HALL) != ret.end())
  1877. {
  1878. ret.insert(BuildingID::EXTRA_CITY_HALL);
  1879. }
  1880. if(ret.find(BuildingID::TOWN_HALL) != ret.end())
  1881. {
  1882. ret.insert(BuildingID::EXTRA_TOWN_HALL);
  1883. }
  1884. if(ret.find(BuildingID::CAPITOL) != ret.end())
  1885. {
  1886. ret.insert(BuildingID::EXTRA_CAPITOL);
  1887. }
  1888. }
  1889. return ret;
  1890. }
  1891. void CMapLoaderH3M::readEvents()
  1892. {
  1893. int numberOfEvents = reader->readUInt32();
  1894. for(int yyoo = 0; yyoo < numberOfEvents; ++yyoo)
  1895. {
  1896. CMapEvent ne;
  1897. ne.name = readBasicString();
  1898. ne.message = readLocalizedString(TextIdentifier("event", yyoo, "description"));
  1899. readResourses(ne.resources);
  1900. ne.players = reader->readUInt8();
  1901. if(map->version > EMapFormat::AB)
  1902. {
  1903. ne.humanAffected = reader->readUInt8();
  1904. }
  1905. else
  1906. {
  1907. ne.humanAffected = true;
  1908. }
  1909. ne.computerAffected = reader->readUInt8();
  1910. ne.firstOccurence = reader->readUInt16();
  1911. ne.nextOccurence = reader->readUInt8();
  1912. reader->skip(17);
  1913. map->events.push_back(ne);
  1914. }
  1915. }
  1916. void CMapLoaderH3M::readMessageAndGuards(std::string& message, CCreatureSet* guards, const int3 & position)
  1917. {
  1918. bool hasMessage = reader->readBool();
  1919. if(hasMessage)
  1920. {
  1921. message = readLocalizedString(TextIdentifier("guards", position.x, position.y, position.z, "message"));
  1922. bool hasGuards = reader->readBool();
  1923. if(hasGuards)
  1924. {
  1925. readCreatureSet(guards, 7);
  1926. }
  1927. reader->skip(4);
  1928. }
  1929. }
  1930. void CMapLoaderH3M::readSpells(std::set<SpellID>& dest)
  1931. {
  1932. readBitmask(dest,9,GameConstants::SPELLS_QUANTITY,false);
  1933. }
  1934. void CMapLoaderH3M::readResourses(TResources& resources)
  1935. {
  1936. resources.resize(GameConstants::RESOURCE_QUANTITY); //needed?
  1937. for(int x = 0; x < 7; ++x)
  1938. {
  1939. resources[x] = reader->readUInt32();
  1940. }
  1941. }
  1942. template <class Indentifier>
  1943. void CMapLoaderH3M::readBitmask(std::set<Indentifier>& dest, const int byteCount, const int limit, bool negate)
  1944. {
  1945. std::vector<bool> temp;
  1946. temp.resize(limit,true);
  1947. readBitmask(temp, byteCount, limit, negate);
  1948. for(int i = 0; i< std::min(temp.size(), static_cast<size_t>(limit)); i++)
  1949. {
  1950. if(temp[i])
  1951. {
  1952. dest.insert(static_cast<Indentifier>(i));
  1953. }
  1954. }
  1955. }
  1956. void CMapLoaderH3M::readBitmask(std::vector<bool>& dest, const int byteCount, const int limit, bool negate)
  1957. {
  1958. for(int byte = 0; byte < byteCount; ++byte)
  1959. {
  1960. const ui8 mask = reader->readUInt8();
  1961. for(int bit = 0; bit < 8; ++bit)
  1962. {
  1963. if(byte * 8 + bit < limit)
  1964. {
  1965. const bool flag = mask & (1 << bit);
  1966. if((negate && flag) || (!negate && !flag)) // FIXME: check PR388
  1967. dest[byte * 8 + bit] = false;
  1968. }
  1969. }
  1970. }
  1971. }
  1972. ui8 CMapLoaderH3M::reverse(ui8 arg) const
  1973. {
  1974. ui8 ret = 0;
  1975. for(int i = 0; i < 8; ++i)
  1976. {
  1977. if((arg & (1 << i)) >> i)
  1978. {
  1979. ret |= (128 >> i);
  1980. }
  1981. }
  1982. return ret;
  1983. }
  1984. int3 CMapLoaderH3M::readInt3()
  1985. {
  1986. int3 p;
  1987. p.x = reader->readUInt8();
  1988. p.y = reader->readUInt8();
  1989. p.z = reader->readUInt8();
  1990. return p;
  1991. }
  1992. std::string CMapLoaderH3M::readBasicString()
  1993. {
  1994. return TextOperations::toUnicode(reader->readBaseString(), fileEncoding);
  1995. }
  1996. std::string CMapLoaderH3M::readLocalizedString(const TextIdentifier & stringIdentifier)
  1997. {
  1998. std::string mapString = TextOperations::toUnicode(reader->readBaseString(), fileEncoding);
  1999. TextIdentifier fullIdentifier("map", mapName, stringIdentifier.get());
  2000. if (mapString.empty())
  2001. return "";
  2002. VLC->generaltexth->registerString(modName, fullIdentifier, mapString);
  2003. return VLC->generaltexth->translate(fullIdentifier.get());
  2004. }
  2005. void CMapLoaderH3M::afterRead()
  2006. {
  2007. //convert main town positions for all players to actual object position, in H3M it is position of active tile
  2008. for(auto & p : map->players)
  2009. {
  2010. int3 posOfMainTown = p.posOfMainTown;
  2011. if(posOfMainTown.valid() && map->isInTheMap(posOfMainTown))
  2012. {
  2013. const TerrainTile & t = map->getTile(posOfMainTown);
  2014. const CGObjectInstance * mainTown = nullptr;
  2015. for(auto * obj : t.visitableObjects)
  2016. {
  2017. if(obj->ID == Obj::TOWN || obj->ID == Obj::RANDOM_TOWN)
  2018. {
  2019. mainTown = obj;
  2020. break;
  2021. }
  2022. }
  2023. if(mainTown == nullptr)
  2024. continue;
  2025. p.posOfMainTown = posOfMainTown + mainTown->getVisitableOffset();
  2026. }
  2027. }
  2028. }
  2029. VCMI_LIB_NAMESPACE_END