MapFormatH3M.cpp 58 KB

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