MapFormatH3M.cpp 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268
  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. const bool CMapLoaderH3M::IS_PROFILING_ENABLED = false;
  26. CMapLoaderH3M::CMapLoaderH3M(CInputStream * stream) : map(nullptr), reader(stream),inputStream(stream)
  27. {
  28. }
  29. CMapLoaderH3M::~CMapLoaderH3M()
  30. {
  31. }
  32. std::unique_ptr<CMap> CMapLoaderH3M::loadMap()
  33. {
  34. // Init map object by parsing the input buffer
  35. map = new CMap();
  36. mapHeader = std::unique_ptr<CMapHeader>(dynamic_cast<CMapHeader *>(map));
  37. init();
  38. return std::unique_ptr<CMap>(dynamic_cast<CMap *>(mapHeader.release()));
  39. }
  40. std::unique_ptr<CMapHeader> CMapLoaderH3M::loadMapHeader()
  41. {
  42. // Read header
  43. mapHeader = make_unique<CMapHeader>();
  44. readHeader();
  45. return std::move(mapHeader);
  46. }
  47. void CMapLoaderH3M::init()
  48. {
  49. //FIXME: get rid of double input process
  50. si64 temp_size = inputStream->getSize();
  51. inputStream->seek(0);
  52. auto temp_buffer = new ui8[temp_size];
  53. inputStream->read(temp_buffer,temp_size);
  54. // Compute checksum
  55. boost::crc_32_type result;
  56. result.process_bytes(temp_buffer, temp_size);
  57. map->checksum = result.checksum();
  58. delete [] temp_buffer;
  59. inputStream->seek(0);
  60. CStopWatch sw;
  61. struct MapLoadingTime
  62. {
  63. std::string name;
  64. si64 time;
  65. MapLoadingTime(std::string name, si64 time) : name(name),
  66. time(time)
  67. {
  68. }
  69. };
  70. std::vector<MapLoadingTime> times;
  71. readHeader();
  72. times.push_back(MapLoadingTime("header", sw.getDiff()));
  73. map->allHeroes.resize(map->allowedHeroes.size());
  74. readDisposedHeroes();
  75. times.push_back(MapLoadingTime("disposed heroes", sw.getDiff()));
  76. readAllowedArtifacts();
  77. times.push_back(MapLoadingTime("allowed artifacts", sw.getDiff()));
  78. readAllowedSpellsAbilities();
  79. times.push_back(MapLoadingTime("allowed spells and abilities", sw.getDiff()));
  80. readRumors();
  81. times.push_back(MapLoadingTime("rumors", sw.getDiff()));
  82. readPredefinedHeroes();
  83. times.push_back(MapLoadingTime("predefined heroes", sw.getDiff()));
  84. readTerrain();
  85. times.push_back(MapLoadingTime("terrain", sw.getDiff()));
  86. readDefInfo();
  87. times.push_back(MapLoadingTime("def info", sw.getDiff()));
  88. readObjects();
  89. times.push_back(MapLoadingTime("objects", sw.getDiff()));
  90. readEvents();
  91. times.push_back(MapLoadingTime("events", sw.getDiff()));
  92. times.push_back(MapLoadingTime("blocked/visitable tiles", sw.getDiff()));
  93. // Print profiling times
  94. if(IS_PROFILING_ENABLED)
  95. {
  96. for(MapLoadingTime & mlt : times)
  97. {
  98. logGlobal->debug("\tReading %s took %d ms", mlt.name, mlt.time);
  99. }
  100. }
  101. map->calculateGuardingGreaturePositions();
  102. afterRead();
  103. }
  104. void CMapLoaderH3M::readHeader()
  105. {
  106. // Check map for validity
  107. // Note: disabled, causes decompression of the entire file ( = SLOW)
  108. //if(inputStream->getSize() < 50)
  109. //{
  110. // throw std::runtime_error("Corrupted map file.");
  111. //}
  112. // Map version
  113. mapHeader->version = (EMapFormat::EMapFormat)(reader.readUInt32());
  114. if(mapHeader->version != EMapFormat::ROE && mapHeader->version != EMapFormat::AB && mapHeader->version != EMapFormat::SOD
  115. && mapHeader->version != EMapFormat::WOG)
  116. {
  117. throw std::runtime_error("Invalid map format!");
  118. }
  119. // Read map name, description, dimensions,...
  120. mapHeader->areAnyPlayers = reader.readBool();
  121. mapHeader->height = mapHeader->width = reader.readUInt32();
  122. mapHeader->twoLevel = reader.readBool();
  123. mapHeader->name = reader.readString();
  124. mapHeader->description = reader.readString();
  125. mapHeader->difficulty = reader.readInt8();
  126. if(mapHeader->version != EMapFormat::ROE)
  127. {
  128. mapHeader->levelLimit = reader.readUInt8();
  129. }
  130. else
  131. {
  132. mapHeader->levelLimit = 0;
  133. }
  134. readPlayerInfo();
  135. readVictoryLossConditions();
  136. readTeamInfo();
  137. readAllowedHeroes();
  138. }
  139. void CMapLoaderH3M::readPlayerInfo()
  140. {
  141. for(int i = 0; i < mapHeader->players.size(); ++i)
  142. {
  143. mapHeader->players[i].canHumanPlay = reader.readBool();
  144. mapHeader->players[i].canComputerPlay = reader.readBool();
  145. // If nobody can play with this player
  146. if((!(mapHeader->players[i].canHumanPlay || mapHeader->players[i].canComputerPlay)))
  147. {
  148. switch(mapHeader->version)
  149. {
  150. case EMapFormat::SOD:
  151. case EMapFormat::WOG:
  152. reader.skip(13);
  153. break;
  154. case EMapFormat::AB:
  155. reader.skip(12);
  156. break;
  157. case EMapFormat::ROE:
  158. reader.skip(6);
  159. break;
  160. }
  161. continue;
  162. }
  163. mapHeader->players[i].aiTactic = static_cast<EAiTactic::EAiTactic>(reader.readUInt8());
  164. if(mapHeader->version == EMapFormat::SOD || mapHeader->version == EMapFormat::WOG)
  165. {
  166. mapHeader->players[i].p7 = reader.readUInt8();
  167. }
  168. else
  169. {
  170. mapHeader->players[i].p7 = -1;
  171. }
  172. // Factions this player can choose
  173. ui16 allowedFactions = reader.readUInt8();
  174. // How many factions will be read from map
  175. ui16 totalFactions = GameConstants::F_NUMBER;
  176. if(mapHeader->version != EMapFormat::ROE)
  177. allowedFactions += reader.readUInt8() * 256; // 256 = 2^8 = 0b100000000
  178. else
  179. totalFactions--; //exclude conflux for ROE
  180. const bool isFactionRandom = mapHeader->players[i].isFactionRandom = reader.readBool();
  181. const ui16 allFactionsMask = (mapHeader->version == EMapFormat::ROE)
  182. ? 0b11111111 // 8 towns for ROE
  183. : 0b111111111; // 8 towns + Conflux
  184. const bool allFactionsAllowed = mapHeader->version == EMapFormat::VCMI
  185. || (isFactionRandom && ((allowedFactions & allFactionsMask) == allFactionsMask));
  186. if(!allFactionsAllowed)
  187. {
  188. mapHeader->players[i].allowedFactions.clear();
  189. for(int fact = 0; fact < totalFactions; ++fact)
  190. {
  191. if(allowedFactions & (1 << fact))
  192. mapHeader->players[i].allowedFactions.insert(fact);
  193. }
  194. }
  195. mapHeader->players[i].hasMainTown = reader.readBool();
  196. if(mapHeader->players[i].hasMainTown)
  197. {
  198. if(mapHeader->version != EMapFormat::ROE)
  199. {
  200. mapHeader->players[i].generateHeroAtMainTown = reader.readBool();
  201. mapHeader->players[i].generateHero = reader.readBool();
  202. }
  203. else
  204. {
  205. mapHeader->players[i].generateHeroAtMainTown = true;
  206. mapHeader->players[i].generateHero = false;
  207. }
  208. mapHeader->players[i].posOfMainTown = readInt3();
  209. }
  210. mapHeader->players[i].hasRandomHero = reader.readBool();
  211. mapHeader->players[i].mainCustomHeroId = reader.readUInt8();
  212. if(mapHeader->players[i].mainCustomHeroId != 0xff)
  213. {
  214. mapHeader->players[i].mainCustomHeroPortrait = reader.readUInt8();
  215. if (mapHeader->players[i].mainCustomHeroPortrait == 0xff)
  216. mapHeader->players[i].mainCustomHeroPortrait = -1; //correct 1-byte -1 (0xff) into 4-byte -1
  217. mapHeader->players[i].mainCustomHeroName = reader.readString();
  218. }
  219. else
  220. mapHeader->players[i].mainCustomHeroId = -1; //correct 1-byte -1 (0xff) into 4-byte -1
  221. if(mapHeader->version != EMapFormat::ROE)
  222. {
  223. mapHeader->players[i].powerPlaceholders = reader.readUInt8(); //unknown byte
  224. int heroCount = reader.readUInt8();
  225. reader.skip(3);
  226. for(int pp = 0; pp < heroCount; ++pp)
  227. {
  228. SHeroName vv;
  229. vv.heroId = reader.readUInt8();
  230. vv.heroName = reader.readString();
  231. mapHeader->players[i].heroesNames.push_back(vv);
  232. }
  233. }
  234. }
  235. }
  236. namespace EVictoryConditionType
  237. {
  238. enum EVictoryConditionType { ARTIFACT, GATHERTROOP, GATHERRESOURCE, BUILDCITY, BUILDGRAIL, BEATHERO,
  239. CAPTURECITY, BEATMONSTER, TAKEDWELLINGS, TAKEMINES, TRANSPORTITEM, WINSTANDARD = 255 };
  240. }
  241. namespace ELossConditionType
  242. {
  243. enum ELossConditionType { LOSSCASTLE, LOSSHERO, TIMEEXPIRES, LOSSSTANDARD = 255 };
  244. }
  245. void CMapLoaderH3M::readVictoryLossConditions()
  246. {
  247. mapHeader->triggeredEvents.clear();
  248. auto vicCondition = (EVictoryConditionType::EVictoryConditionType)reader.readUInt8();
  249. EventCondition victoryCondition(EventCondition::STANDARD_WIN);
  250. EventCondition defeatCondition(EventCondition::DAYS_WITHOUT_TOWN);
  251. defeatCondition.value = 7;
  252. TriggeredEvent standardVictory;
  253. standardVictory.effect.type = EventEffect::VICTORY;
  254. standardVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[5];
  255. standardVictory.identifier = "standardVictory";
  256. standardVictory.description = ""; // TODO: display in quest window
  257. standardVictory.onFulfill = VLC->generaltexth->allTexts[659];
  258. standardVictory.trigger = EventExpression(victoryCondition);
  259. TriggeredEvent standardDefeat;
  260. standardDefeat.effect.type = EventEffect::DEFEAT;
  261. standardDefeat.effect.toOtherMessage = VLC->generaltexth->allTexts[8];
  262. standardDefeat.identifier = "standardDefeat";
  263. standardDefeat.description = ""; // TODO: display in quest window
  264. standardDefeat.onFulfill = VLC->generaltexth->allTexts[7];
  265. standardDefeat.trigger = EventExpression(defeatCondition);
  266. // Specific victory conditions
  267. if(vicCondition == EVictoryConditionType::WINSTANDARD)
  268. {
  269. // create normal condition
  270. mapHeader->triggeredEvents.push_back(standardVictory);
  271. mapHeader->victoryIconIndex = 11;
  272. mapHeader->victoryMessage = VLC->generaltexth->victoryConditions[0];
  273. }
  274. else
  275. {
  276. TriggeredEvent specialVictory;
  277. specialVictory.effect.type = EventEffect::VICTORY;
  278. specialVictory.identifier = "specialVictory";
  279. specialVictory.description = ""; // TODO: display in quest window
  280. mapHeader->victoryIconIndex = ui16(vicCondition);
  281. mapHeader->victoryMessage = VLC->generaltexth->victoryConditions[size_t(vicCondition) + 1];
  282. bool allowNormalVictory = reader.readBool();
  283. bool appliesToAI = reader.readBool();
  284. if (allowNormalVictory)
  285. {
  286. size_t playersOnMap = boost::range::count_if(mapHeader->players,[](const PlayerInfo & info) { return info.canAnyonePlay();});
  287. if (playersOnMap == 1)
  288. {
  289. logGlobal->warn("Map %s has only one player but allows normal victory?", mapHeader->name);
  290. allowNormalVictory = false; // makes sense? Not much. Works as H3? Yes!
  291. }
  292. }
  293. switch(vicCondition)
  294. {
  295. case EVictoryConditionType::ARTIFACT:
  296. {
  297. EventCondition cond(EventCondition::HAVE_ARTIFACT);
  298. cond.objectType = reader.readUInt8();
  299. if (mapHeader->version != EMapFormat::ROE)
  300. reader.skip(1);
  301. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[281];
  302. specialVictory.onFulfill = VLC->generaltexth->allTexts[280];
  303. specialVictory.trigger = EventExpression(cond);
  304. break;
  305. }
  306. case EVictoryConditionType::GATHERTROOP:
  307. {
  308. EventCondition cond(EventCondition::HAVE_CREATURES);
  309. cond.objectType = reader.readUInt8();
  310. if (mapHeader->version != EMapFormat::ROE)
  311. reader.skip(1);
  312. cond.value = reader.readUInt32();
  313. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[277];
  314. specialVictory.onFulfill = VLC->generaltexth->allTexts[276];
  315. specialVictory.trigger = EventExpression(cond);
  316. break;
  317. }
  318. case EVictoryConditionType::GATHERRESOURCE:
  319. {
  320. EventCondition cond(EventCondition::HAVE_RESOURCES);
  321. cond.objectType = reader.readUInt8();
  322. cond.value = reader.readUInt32();
  323. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[279];
  324. specialVictory.onFulfill = VLC->generaltexth->allTexts[278];
  325. specialVictory.trigger = EventExpression(cond);
  326. break;
  327. }
  328. case EVictoryConditionType::BUILDCITY:
  329. {
  330. EventExpression::OperatorAll oper;
  331. EventCondition cond(EventCondition::HAVE_BUILDING);
  332. cond.position = readInt3();
  333. cond.objectType = BuildingID::VILLAGE_HALL + reader.readUInt8();
  334. oper.expressions.push_back(cond);
  335. cond.objectType = BuildingID::FORT + reader.readUInt8();
  336. oper.expressions.push_back(cond);
  337. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[283];
  338. specialVictory.onFulfill = VLC->generaltexth->allTexts[282];
  339. specialVictory.trigger = EventExpression(oper);
  340. break;
  341. }
  342. case EVictoryConditionType::BUILDGRAIL:
  343. {
  344. EventCondition cond(EventCondition::HAVE_BUILDING);
  345. cond.objectType = BuildingID::GRAIL;
  346. cond.position = readInt3();
  347. if(cond.position.z > 2)
  348. cond.position = int3(-1,-1,-1);
  349. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[285];
  350. specialVictory.onFulfill = VLC->generaltexth->allTexts[284];
  351. specialVictory.trigger = EventExpression(cond);
  352. break;
  353. }
  354. case EVictoryConditionType::BEATHERO:
  355. {
  356. EventCondition cond(EventCondition::DESTROY);
  357. cond.objectType = Obj::HERO;
  358. cond.position = readInt3();
  359. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[253];
  360. specialVictory.onFulfill = VLC->generaltexth->allTexts[252];
  361. specialVictory.trigger = EventExpression(cond);
  362. break;
  363. }
  364. case EVictoryConditionType::CAPTURECITY:
  365. {
  366. EventCondition cond(EventCondition::CONTROL);
  367. cond.objectType = Obj::TOWN;
  368. cond.position = readInt3();
  369. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[250];
  370. specialVictory.onFulfill = VLC->generaltexth->allTexts[249];
  371. specialVictory.trigger = EventExpression(cond);
  372. break;
  373. }
  374. case EVictoryConditionType::BEATMONSTER:
  375. {
  376. EventCondition cond(EventCondition::DESTROY);
  377. cond.objectType = Obj::MONSTER;
  378. cond.position = readInt3();
  379. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[287];
  380. specialVictory.onFulfill = VLC->generaltexth->allTexts[286];
  381. specialVictory.trigger = EventExpression(cond);
  382. break;
  383. }
  384. case EVictoryConditionType::TAKEDWELLINGS:
  385. {
  386. EventExpression::OperatorAll oper;
  387. oper.expressions.push_back(EventCondition(EventCondition::CONTROL, 0, Obj::CREATURE_GENERATOR1));
  388. oper.expressions.push_back(EventCondition(EventCondition::CONTROL, 0, Obj::CREATURE_GENERATOR4));
  389. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[289];
  390. specialVictory.onFulfill = VLC->generaltexth->allTexts[288];
  391. specialVictory.trigger = EventExpression(oper);
  392. break;
  393. }
  394. case EVictoryConditionType::TAKEMINES:
  395. {
  396. EventCondition cond(EventCondition::CONTROL);
  397. cond.objectType = Obj::MINE;
  398. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[291];
  399. specialVictory.onFulfill = VLC->generaltexth->allTexts[290];
  400. specialVictory.trigger = EventExpression(cond);
  401. break;
  402. }
  403. case EVictoryConditionType::TRANSPORTITEM:
  404. {
  405. EventCondition cond(EventCondition::TRANSPORT);
  406. cond.objectType = reader.readUInt8();
  407. cond.position = readInt3();
  408. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[293];
  409. specialVictory.onFulfill = VLC->generaltexth->allTexts[292];
  410. specialVictory.trigger = EventExpression(cond);
  411. break;
  412. }
  413. default:
  414. assert(0);
  415. }
  416. // if condition is human-only turn it into following construction: AllOf(human, condition)
  417. if (!appliesToAI)
  418. {
  419. EventExpression::OperatorAll oper;
  420. EventCondition notAI(EventCondition::IS_HUMAN);
  421. notAI.value = 1;
  422. oper.expressions.push_back(notAI);
  423. oper.expressions.push_back(specialVictory.trigger.get());
  424. specialVictory.trigger = EventExpression(oper);
  425. }
  426. // if normal victory allowed - add one more quest
  427. if (allowNormalVictory)
  428. {
  429. mapHeader->victoryMessage += " / ";
  430. mapHeader->victoryMessage += VLC->generaltexth->victoryConditions[0];
  431. mapHeader->triggeredEvents.push_back(standardVictory);
  432. }
  433. mapHeader->triggeredEvents.push_back(specialVictory);
  434. }
  435. // Read loss conditions
  436. auto lossCond = (ELossConditionType::ELossConditionType)reader.readUInt8();
  437. if (lossCond == ELossConditionType::LOSSSTANDARD)
  438. {
  439. mapHeader->defeatIconIndex = 3;
  440. mapHeader->defeatMessage = VLC->generaltexth->lossCondtions[0];
  441. }
  442. else
  443. {
  444. TriggeredEvent specialDefeat;
  445. specialDefeat.effect.type = EventEffect::DEFEAT;
  446. specialDefeat.effect.toOtherMessage = VLC->generaltexth->allTexts[5];
  447. specialDefeat.identifier = "specialDefeat";
  448. specialDefeat.description = ""; // TODO: display in quest window
  449. mapHeader->defeatIconIndex = ui16(lossCond);
  450. mapHeader->defeatMessage = VLC->generaltexth->lossCondtions[size_t(lossCond) + 1];
  451. switch(lossCond)
  452. {
  453. case ELossConditionType::LOSSCASTLE:
  454. {
  455. EventExpression::OperatorNone noneOf;
  456. EventCondition cond(EventCondition::CONTROL);
  457. cond.objectType = Obj::TOWN;
  458. cond.position = readInt3();
  459. noneOf.expressions.push_back(cond);
  460. specialDefeat.onFulfill = VLC->generaltexth->allTexts[251];
  461. specialDefeat.trigger = EventExpression(noneOf);
  462. break;
  463. }
  464. case ELossConditionType::LOSSHERO:
  465. {
  466. EventExpression::OperatorNone noneOf;
  467. EventCondition cond(EventCondition::CONTROL);
  468. cond.objectType = Obj::HERO;
  469. cond.position = readInt3();
  470. noneOf.expressions.push_back(cond);
  471. specialDefeat.onFulfill = VLC->generaltexth->allTexts[253];
  472. specialDefeat.trigger = EventExpression(noneOf);
  473. break;
  474. }
  475. case ELossConditionType::TIMEEXPIRES:
  476. {
  477. EventCondition cond(EventCondition::DAYS_PASSED);
  478. cond.value = reader.readUInt16();
  479. specialDefeat.onFulfill = VLC->generaltexth->allTexts[254];
  480. specialDefeat.trigger = EventExpression(cond);
  481. break;
  482. }
  483. }
  484. // turn simple loss condition into complete one that can be evaluated later:
  485. // - any of :
  486. // - days without town: 7
  487. // - all of:
  488. // - is human
  489. // - (expression)
  490. EventExpression::OperatorAll allOf;
  491. EventCondition isHuman(EventCondition::IS_HUMAN);
  492. isHuman.value = 1;
  493. allOf.expressions.push_back(isHuman);
  494. allOf.expressions.push_back(specialDefeat.trigger.get());
  495. specialDefeat.trigger = EventExpression(allOf);
  496. mapHeader->triggeredEvents.push_back(specialDefeat);
  497. }
  498. mapHeader->triggeredEvents.push_back(standardDefeat);
  499. }
  500. void CMapLoaderH3M::readTeamInfo()
  501. {
  502. mapHeader->howManyTeams = reader.readUInt8();
  503. if(mapHeader->howManyTeams > 0)
  504. {
  505. // Teams
  506. for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; ++i)
  507. {
  508. mapHeader->players[i].team = TeamID(reader.readUInt8());
  509. }
  510. }
  511. else
  512. {
  513. // No alliances
  514. for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
  515. {
  516. if(mapHeader->players[i].canComputerPlay || mapHeader->players[i].canHumanPlay)
  517. {
  518. mapHeader->players[i].team = TeamID(mapHeader->howManyTeams++);
  519. }
  520. }
  521. }
  522. }
  523. void CMapLoaderH3M::readAllowedHeroes()
  524. {
  525. mapHeader->allowedHeroes.resize(VLC->heroh->size(), true);
  526. const int bytes = mapHeader->version == EMapFormat::ROE ? 16 : 20;
  527. readBitmask(mapHeader->allowedHeroes,bytes,GameConstants::HEROES_QUANTITY, false);
  528. // Probably reserved for further heroes
  529. if(mapHeader->version > EMapFormat::ROE)
  530. {
  531. int placeholdersQty = reader.readUInt32();
  532. reader.skip(placeholdersQty * 1);
  533. // std::vector<ui16> placeholdedHeroes;
  534. //
  535. // for(int p = 0; p < placeholdersQty; ++p)
  536. // {
  537. // placeholdedHeroes.push_back(reader.readUInt8());
  538. // }
  539. }
  540. }
  541. void CMapLoaderH3M::readDisposedHeroes()
  542. {
  543. // Reading disposed heroes (20 bytes)
  544. if(map->version >= EMapFormat::SOD)
  545. {
  546. ui8 disp = reader.readUInt8();
  547. map->disposedHeroes.resize(disp);
  548. for(int g = 0; g < disp; ++g)
  549. {
  550. map->disposedHeroes[g].heroId = reader.readUInt8();
  551. map->disposedHeroes[g].portrait = reader.readUInt8();
  552. map->disposedHeroes[g].name = reader.readString();
  553. map->disposedHeroes[g].players = reader.readUInt8();
  554. }
  555. }
  556. //omitting NULLS
  557. reader.skip(31);
  558. }
  559. void CMapLoaderH3M::readAllowedArtifacts()
  560. {
  561. map->allowedArtifact.resize (VLC->arth->objects.size(),true); //handle new artifacts, make them allowed by default
  562. // Reading allowed artifacts: 17 or 18 bytes
  563. if(map->version != EMapFormat::ROE)
  564. {
  565. const int bytes = map->version == EMapFormat::AB ? 17 : 18;
  566. readBitmask(map->allowedArtifact,bytes,GameConstants::ARTIFACTS_QUANTITY);
  567. }
  568. // ban combo artifacts
  569. if (map->version == EMapFormat::ROE || map->version == EMapFormat::AB)
  570. {
  571. for(CArtifact * artifact : VLC->arth->objects)
  572. {
  573. // combo
  574. if (artifact->constituents)
  575. {
  576. map->allowedArtifact[artifact->id] = false;
  577. }
  578. }
  579. if (map->version == EMapFormat::ROE)
  580. {
  581. map->allowedArtifact[ArtifactID::ARMAGEDDONS_BLADE] = false;
  582. }
  583. }
  584. // Messy, but needed
  585. for (TriggeredEvent & event : map->triggeredEvents)
  586. {
  587. auto patcher = [&](EventCondition cond) -> EventExpression::Variant
  588. {
  589. if (cond.condition == EventCondition::HAVE_ARTIFACT ||
  590. cond.condition == EventCondition::TRANSPORT)
  591. {
  592. map->allowedArtifact[cond.objectType] = false;
  593. }
  594. return cond;
  595. };
  596. event.trigger = event.trigger.morph(patcher);
  597. }
  598. }
  599. void CMapLoaderH3M::readAllowedSpellsAbilities()
  600. {
  601. // Read allowed spells, including new ones
  602. map->allowedSpell.resize(VLC->spellh->objects.size(), true);
  603. // Read allowed abilities
  604. map->allowedAbilities.resize(GameConstants::SKILL_QUANTITY, true);
  605. if(map->version >= EMapFormat::SOD)
  606. {
  607. // Reading allowed spells (9 bytes)
  608. const int spell_bytes = 9;
  609. readBitmask(map->allowedSpell, spell_bytes, GameConstants::SPELLS_QUANTITY);
  610. // Allowed hero's abilities (4 bytes)
  611. const int abil_bytes = 4;
  612. readBitmask(map->allowedAbilities, abil_bytes, GameConstants::SKILL_QUANTITY);
  613. }
  614. //do not generate special abilities and spells
  615. for (auto spell : VLC->spellh->objects)
  616. if (spell->isSpecial() || spell->isCreatureAbility())
  617. map->allowedSpell[spell->id] = false;
  618. }
  619. void CMapLoaderH3M::readRumors()
  620. {
  621. int rumNr = reader.readUInt32();
  622. for(int it = 0; it < rumNr; it++)
  623. {
  624. Rumor ourRumor;
  625. ourRumor.name = reader.readString();
  626. ourRumor.text = reader.readString();
  627. map->rumors.push_back(ourRumor);
  628. }
  629. }
  630. void CMapLoaderH3M::readPredefinedHeroes()
  631. {
  632. switch(map->version)
  633. {
  634. case EMapFormat::WOG:
  635. case EMapFormat::SOD:
  636. {
  637. // Disposed heroes
  638. for(int z = 0; z < GameConstants::HEROES_QUANTITY; z++)
  639. {
  640. int custom = reader.readUInt8();
  641. if(!custom) continue;
  642. auto hero = new CGHeroInstance();
  643. hero->ID = Obj::HERO;
  644. hero->subID = z;
  645. bool hasExp = reader.readBool();
  646. if(hasExp)
  647. {
  648. hero->exp = reader.readUInt32();
  649. }
  650. else
  651. {
  652. hero->exp = 0;
  653. }
  654. bool hasSecSkills = reader.readBool();
  655. if(hasSecSkills)
  656. {
  657. int howMany = reader.readUInt32();
  658. hero->secSkills.resize(howMany);
  659. for(int yy = 0; yy < howMany; ++yy)
  660. {
  661. hero->secSkills[yy].first = SecondarySkill(reader.readUInt8());
  662. hero->secSkills[yy].second = reader.readUInt8();
  663. }
  664. }
  665. loadArtifactsOfHero(hero);
  666. bool hasCustomBio = reader.readBool();
  667. if(hasCustomBio)
  668. {
  669. hero->biography = reader.readString();
  670. }
  671. // 0xFF is default, 00 male, 01 female
  672. hero->sex = reader.readUInt8();
  673. bool hasCustomSpells = reader.readBool();
  674. if(hasCustomSpells)
  675. {
  676. readSpells(hero->spells);
  677. }
  678. bool hasCustomPrimSkills = reader.readBool();
  679. if(hasCustomPrimSkills)
  680. {
  681. for(int xx = 0; xx < GameConstants::PRIMARY_SKILLS; xx++)
  682. {
  683. hero->pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(xx), reader.readUInt8());
  684. }
  685. }
  686. map->predefinedHeroes.push_back(hero);
  687. }
  688. break;
  689. }
  690. case EMapFormat::ROE:
  691. break;
  692. }
  693. }
  694. void CMapLoaderH3M::loadArtifactsOfHero(CGHeroInstance * hero)
  695. {
  696. bool artSet = reader.readBool();
  697. // True if artifact set is not default (hero has some artifacts)
  698. if(artSet)
  699. {
  700. if(hero->artifactsWorn.size() || hero->artifactsInBackpack.size())
  701. {
  702. 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());
  703. hero->artifactsInBackpack.clear();
  704. while(hero->artifactsWorn.size())
  705. hero->eraseArtSlot(hero->artifactsWorn.begin()->first);
  706. }
  707. for(int pom = 0; pom < 16; pom++)
  708. {
  709. loadArtifactToSlot(hero, pom);
  710. }
  711. // misc5 art //17
  712. if(map->version >= EMapFormat::SOD)
  713. {
  714. assert(!hero->getArt(ArtifactPosition::MACH4));
  715. if(!loadArtifactToSlot(hero, ArtifactPosition::MACH4))
  716. {
  717. // catapult by default
  718. assert(!hero->getArt(ArtifactPosition::MACH4));
  719. hero->putArtifact(ArtifactPosition::MACH4, CArtifactInstance::createArtifact(map, ArtifactID::CATAPULT));
  720. }
  721. }
  722. loadArtifactToSlot(hero, ArtifactPosition::SPELLBOOK);
  723. // 19 //???what is that? gap in file or what? - it's probably fifth slot..
  724. if(map->version > EMapFormat::ROE)
  725. {
  726. loadArtifactToSlot(hero, ArtifactPosition::MISC5);
  727. }
  728. else
  729. {
  730. reader.skip(1);
  731. }
  732. // bag artifacts //20
  733. // number of artifacts in hero's bag
  734. int amount = reader.readUInt16();
  735. for(int ss = 0; ss < amount; ++ss)
  736. {
  737. loadArtifactToSlot(hero, GameConstants::BACKPACK_START + (int)hero->artifactsInBackpack.size());
  738. }
  739. }
  740. }
  741. bool CMapLoaderH3M::loadArtifactToSlot(CGHeroInstance * hero, int slot)
  742. {
  743. const int artmask = map->version == EMapFormat::ROE ? 0xff : 0xffff;
  744. int aid;
  745. if(map->version == EMapFormat::ROE)
  746. {
  747. aid = reader.readUInt8();
  748. }
  749. else
  750. {
  751. aid = reader.readUInt16();
  752. }
  753. bool isArt = aid != artmask;
  754. if(isArt)
  755. {
  756. const Artifact * art = ArtifactID(aid).toArtifact(VLC->artifacts());
  757. if(nullptr == art)
  758. {
  759. logGlobal->warn("Invalid artifact in hero's backpack, ignoring...");
  760. return false;
  761. }
  762. if(art->isBig() && slot >= GameConstants::BACKPACK_START)
  763. {
  764. logGlobal->warn("A big artifact (war machine) in hero's backpack, ignoring...");
  765. return false;
  766. }
  767. if(aid == 0 && slot == ArtifactPosition::MISC5)
  768. {
  769. //TODO: check how H3 handles it -> art 0 in slot 18 in AB map
  770. logGlobal->warn("Spellbook to MISC5 slot? Putting it spellbook place. AB format peculiarity? (format %d)", static_cast<int>(map->version));
  771. slot = ArtifactPosition::SPELLBOOK;
  772. }
  773. // this is needed, because some H3M maps (last scenario of ROE map) contain invalid data like misplaced artifacts
  774. auto artifact = CArtifactInstance::createArtifact(map, aid);
  775. auto artifactPos = ArtifactPosition(slot);
  776. if (artifact->canBePutAt(ArtifactLocation(hero, artifactPos)))
  777. {
  778. hero->putArtifact(artifactPos, artifact);
  779. }
  780. else
  781. {
  782. logGlobal->debug("Artifact can't be put at the specified location."); //TODO add more debugging information
  783. }
  784. }
  785. return isArt;
  786. }
  787. void CMapLoaderH3M::readTerrain()
  788. {
  789. map->initTerrain();
  790. // Read terrain
  791. int3 pos;
  792. for(pos.z = 0; pos.z < 2; ++pos.z)
  793. {
  794. if(pos.z == 1 && !map->twoLevel)
  795. {
  796. break;
  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 = Terrain::createTerrainTypeH3M(reader.readUInt8());
  805. tile.terView = reader.readUInt8();
  806. tile.riverType = RIVER_NAMES[reader.readUInt8()];
  807. tile.riverDir = reader.readUInt8();
  808. tile.roadType = ROAD_NAMES[reader.readUInt8()];
  809. tile.roadDir = reader.readUInt8();
  810. tile.extTileFlags = reader.readUInt8();
  811. tile.blocked = ((!tile.terType.isPassable() || tile.terType == 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. int 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 = 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. if(nhi->patrol.patrolRadius == 0xff)
  1452. {
  1453. nhi->patrol.patrolling = false;
  1454. }
  1455. else
  1456. {
  1457. nhi->patrol.patrolling = true;
  1458. nhi->patrol.initialPos = CGHeroInstance::convertPosition(initialPos, false);
  1459. }
  1460. if(map->version > EMapFormat::ROE)
  1461. {
  1462. bool hasCustomBiography = reader.readBool();
  1463. if(hasCustomBiography)
  1464. {
  1465. nhi->biography = reader.readString();
  1466. }
  1467. nhi->sex = reader.readUInt8();
  1468. // Remove trash
  1469. if (nhi->sex != 0xFF)
  1470. {
  1471. nhi->sex &= 1;
  1472. }
  1473. }
  1474. else
  1475. {
  1476. nhi->sex = 0xFF;
  1477. }
  1478. // Spells
  1479. if(map->version > EMapFormat::AB)
  1480. {
  1481. bool hasCustomSpells = reader.readBool();
  1482. if(nhi->spells.size())
  1483. {
  1484. nhi->clear();
  1485. 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);
  1486. }
  1487. if(hasCustomSpells)
  1488. {
  1489. nhi->spells.insert(SpellID::PRESET); //placeholder "preset spells"
  1490. readSpells(nhi->spells);
  1491. }
  1492. }
  1493. else if(map->version == EMapFormat::AB)
  1494. {
  1495. //we can read one spell
  1496. ui8 buff = reader.readUInt8();
  1497. if(buff != 254)
  1498. {
  1499. nhi->spells.insert(SpellID::PRESET); //placeholder "preset spells"
  1500. if(buff < 254) //255 means no spells
  1501. {
  1502. nhi->spells.insert(SpellID(buff));
  1503. }
  1504. }
  1505. }
  1506. if(map->version > EMapFormat::AB)
  1507. {
  1508. bool hasCustomPrimSkills = reader.readBool();
  1509. if(hasCustomPrimSkills)
  1510. {
  1511. auto ps = nhi->getAllBonuses(Selector::type()(Bonus::PRIMARY_SKILL)
  1512. .And(Selector::sourceType()(Bonus::HERO_BASE_SKILL)), nullptr);
  1513. if(ps->size())
  1514. {
  1515. 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);
  1516. for(auto b : *ps)
  1517. nhi->removeBonus(b);
  1518. }
  1519. for(int xx = 0; xx < GameConstants::PRIMARY_SKILLS; ++xx)
  1520. {
  1521. nhi->pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(xx), reader.readUInt8());
  1522. }
  1523. }
  1524. }
  1525. reader.skip(16);
  1526. return nhi;
  1527. }
  1528. CGSeerHut * CMapLoaderH3M::readSeerHut()
  1529. {
  1530. auto hut = new CGSeerHut();
  1531. if(map->version > EMapFormat::ROE)
  1532. {
  1533. readQuest(hut);
  1534. }
  1535. else
  1536. {
  1537. //RoE
  1538. int artID = reader.readUInt8();
  1539. if (artID != 255)
  1540. {
  1541. //not none quest
  1542. hut->quest->m5arts.push_back (artID);
  1543. hut->quest->missionType = CQuest::MISSION_ART;
  1544. }
  1545. else
  1546. {
  1547. hut->quest->missionType = CQuest::MISSION_NONE;
  1548. }
  1549. hut->quest->lastDay = -1; //no timeout
  1550. hut->quest->isCustomFirst = hut->quest->isCustomNext = hut->quest->isCustomComplete = false;
  1551. }
  1552. if (hut->quest->missionType)
  1553. {
  1554. auto rewardType = static_cast<CGSeerHut::ERewardType>(reader.readUInt8());
  1555. hut->rewardType = rewardType;
  1556. switch(rewardType)
  1557. {
  1558. case CGSeerHut::EXPERIENCE:
  1559. {
  1560. hut->rVal = reader.readUInt32();
  1561. break;
  1562. }
  1563. case CGSeerHut::MANA_POINTS:
  1564. {
  1565. hut->rVal = reader.readUInt32();
  1566. break;
  1567. }
  1568. case CGSeerHut::MORALE_BONUS:
  1569. {
  1570. hut->rVal = reader.readUInt8();
  1571. break;
  1572. }
  1573. case CGSeerHut::LUCK_BONUS:
  1574. {
  1575. hut->rVal = reader.readUInt8();
  1576. break;
  1577. }
  1578. case CGSeerHut::RESOURCES:
  1579. {
  1580. hut->rID = reader.readUInt8();
  1581. // Only the first 3 bytes are used. Skip the 4th.
  1582. hut->rVal = reader.readUInt32() & 0x00ffffff;
  1583. break;
  1584. }
  1585. case CGSeerHut::PRIMARY_SKILL:
  1586. {
  1587. hut->rID = reader.readUInt8();
  1588. hut->rVal = reader.readUInt8();
  1589. break;
  1590. }
  1591. case CGSeerHut::SECONDARY_SKILL:
  1592. {
  1593. hut->rID = reader.readUInt8();
  1594. hut->rVal = reader.readUInt8();
  1595. break;
  1596. }
  1597. case CGSeerHut::ARTIFACT:
  1598. {
  1599. if (map->version == EMapFormat::ROE)
  1600. {
  1601. hut->rID = reader.readUInt8();
  1602. }
  1603. else
  1604. {
  1605. hut->rID = reader.readUInt16();
  1606. }
  1607. break;
  1608. }
  1609. case CGSeerHut::SPELL:
  1610. {
  1611. hut->rID = reader.readUInt8();
  1612. break;
  1613. }
  1614. case CGSeerHut::CREATURE:
  1615. {
  1616. if(map->version > EMapFormat::ROE)
  1617. {
  1618. hut->rID = reader.readUInt16();
  1619. hut->rVal = reader.readUInt16();
  1620. }
  1621. else
  1622. {
  1623. hut->rID = reader.readUInt8();
  1624. hut->rVal = reader.readUInt16();
  1625. }
  1626. break;
  1627. }
  1628. }
  1629. reader.skip(2);
  1630. }
  1631. else
  1632. {
  1633. // missionType==255
  1634. reader.skip(3);
  1635. }
  1636. return hut;
  1637. }
  1638. void CMapLoaderH3M::readQuest(IQuestObject * guard)
  1639. {
  1640. guard->quest->missionType = static_cast<CQuest::Emission>(reader.readUInt8());
  1641. switch(guard->quest->missionType)
  1642. {
  1643. case CQuest::MISSION_NONE:
  1644. return;
  1645. case CQuest::MISSION_PRIMARY_STAT:
  1646. {
  1647. guard->quest->m2stats.resize(4);
  1648. for(int x = 0; x < 4; ++x)
  1649. {
  1650. guard->quest->m2stats[x] = reader.readUInt8();
  1651. }
  1652. }
  1653. break;
  1654. case CQuest::MISSION_LEVEL:
  1655. case CQuest::MISSION_KILL_HERO:
  1656. case CQuest::MISSION_KILL_CREATURE:
  1657. {
  1658. guard->quest->m13489val = reader.readUInt32();
  1659. break;
  1660. }
  1661. case CQuest::MISSION_ART:
  1662. {
  1663. int artNumber = reader.readUInt8();
  1664. for(int yy = 0; yy < artNumber; ++yy)
  1665. {
  1666. int artid = reader.readUInt16();
  1667. guard->quest->m5arts.push_back(artid);
  1668. map->allowedArtifact[artid] = false; //these are unavailable for random generation
  1669. }
  1670. break;
  1671. }
  1672. case CQuest::MISSION_ARMY:
  1673. {
  1674. int typeNumber = reader.readUInt8();
  1675. guard->quest->m6creatures.resize(typeNumber);
  1676. for(int hh = 0; hh < typeNumber; ++hh)
  1677. {
  1678. guard->quest->m6creatures[hh].type = VLC->creh->objects[reader.readUInt16()];
  1679. guard->quest->m6creatures[hh].count = reader.readUInt16();
  1680. }
  1681. break;
  1682. }
  1683. case CQuest::MISSION_RESOURCES:
  1684. {
  1685. guard->quest->m7resources.resize(7);
  1686. for(int x = 0; x < 7; ++x)
  1687. {
  1688. guard->quest->m7resources[x] = reader.readUInt32();
  1689. }
  1690. break;
  1691. }
  1692. case CQuest::MISSION_HERO:
  1693. case CQuest::MISSION_PLAYER:
  1694. {
  1695. guard->quest->m13489val = reader.readUInt8();
  1696. break;
  1697. }
  1698. }
  1699. int limit = reader.readUInt32();
  1700. if(limit == (static_cast<int>(0xffffffff)))
  1701. {
  1702. guard->quest->lastDay = -1;
  1703. }
  1704. else
  1705. {
  1706. guard->quest->lastDay = limit;
  1707. }
  1708. guard->quest->firstVisitText = reader.readString();
  1709. guard->quest->nextVisitText = reader.readString();
  1710. guard->quest->completedText = reader.readString();
  1711. guard->quest->isCustomFirst = guard->quest->firstVisitText.size() > 0;
  1712. guard->quest->isCustomNext = guard->quest->nextVisitText.size() > 0;
  1713. guard->quest->isCustomComplete = guard->quest->completedText.size() > 0;
  1714. }
  1715. CGTownInstance * CMapLoaderH3M::readTown(int castleID)
  1716. {
  1717. auto nt = new CGTownInstance();
  1718. if(map->version > EMapFormat::ROE)
  1719. {
  1720. nt->identifier = reader.readUInt32();
  1721. }
  1722. nt->tempOwner = PlayerColor(reader.readUInt8());
  1723. bool hasName = reader.readBool();
  1724. if(hasName)
  1725. {
  1726. nt->name = reader.readString();
  1727. }
  1728. bool hasGarrison = reader.readBool();
  1729. if(hasGarrison)
  1730. {
  1731. readCreatureSet(nt, 7);
  1732. }
  1733. nt->formation = reader.readUInt8();
  1734. bool hasCustomBuildings = reader.readBool();
  1735. if(hasCustomBuildings)
  1736. {
  1737. readBitmask(nt->builtBuildings,6,48,false);
  1738. readBitmask(nt->forbiddenBuildings,6,48,false);
  1739. nt->builtBuildings = convertBuildings(nt->builtBuildings, castleID);
  1740. nt->forbiddenBuildings = convertBuildings(nt->forbiddenBuildings, castleID);
  1741. }
  1742. // Standard buildings
  1743. else
  1744. {
  1745. bool hasFort = reader.readBool();
  1746. if(hasFort)
  1747. {
  1748. nt->builtBuildings.insert(BuildingID::FORT);
  1749. }
  1750. //means that set of standard building should be included
  1751. nt->builtBuildings.insert(BuildingID::DEFAULT);
  1752. }
  1753. if(map->version > EMapFormat::ROE)
  1754. {
  1755. for(int i = 0; i < 9; ++i)
  1756. {
  1757. ui8 c = reader.readUInt8();
  1758. for(int yy = 0; yy < 8; ++yy)
  1759. {
  1760. if(i * 8 + yy < GameConstants::SPELLS_QUANTITY)
  1761. {
  1762. if(c == (c | static_cast<ui8>(std::pow(2., yy)))) //add obligatory spell even if it's banned on a map (?)
  1763. {
  1764. nt->obligatorySpells.push_back(SpellID(i * 8 + yy));
  1765. }
  1766. }
  1767. }
  1768. }
  1769. }
  1770. for(int i = 0; i < 9; ++i)
  1771. {
  1772. ui8 c = reader.readUInt8();
  1773. for(int yy = 0; yy < 8; ++yy)
  1774. {
  1775. int spellid = i * 8 + yy;
  1776. if(spellid < GameConstants::SPELLS_QUANTITY)
  1777. {
  1778. if(c != (c | static_cast<ui8>(std::pow(2., yy))) && map->allowedSpell[spellid]) //add random spell only if it's allowed on entire map
  1779. {
  1780. nt->possibleSpells.push_back(SpellID(spellid));
  1781. }
  1782. }
  1783. }
  1784. }
  1785. //add all spells from mods
  1786. //TODO: allow customize new spells in towns
  1787. for (int i = SpellID::AFTER_LAST; i < VLC->spellh->objects.size(); ++i)
  1788. {
  1789. nt->possibleSpells.push_back(SpellID(i));
  1790. }
  1791. // Read castle events
  1792. int numberOfEvent = reader.readUInt32();
  1793. for(int gh = 0; gh < numberOfEvent; ++gh)
  1794. {
  1795. CCastleEvent nce;
  1796. nce.town = nt;
  1797. nce.name = reader.readString();
  1798. nce.message = reader.readString();
  1799. readResourses(nce.resources);
  1800. nce.players = reader.readUInt8();
  1801. if(map->version > EMapFormat::AB)
  1802. {
  1803. nce.humanAffected = reader.readUInt8();
  1804. }
  1805. else
  1806. {
  1807. nce.humanAffected = true;
  1808. }
  1809. nce.computerAffected = reader.readUInt8();
  1810. nce.firstOccurence = reader.readUInt16();
  1811. nce.nextOccurence = reader.readUInt8();
  1812. reader.skip(17);
  1813. // New buildings
  1814. readBitmask(nce.buildings,6,48,false);
  1815. nce.buildings = convertBuildings(nce.buildings, castleID, false);
  1816. nce.creatures.resize(7);
  1817. for(int vv = 0; vv < 7; ++vv)
  1818. {
  1819. nce.creatures[vv] = reader.readUInt16();
  1820. }
  1821. reader.skip(4);
  1822. nt->events.push_back(nce);
  1823. }
  1824. if(map->version > EMapFormat::AB)
  1825. {
  1826. nt->alignment = reader.readUInt8();
  1827. }
  1828. reader.skip(3);
  1829. return nt;
  1830. }
  1831. std::set<BuildingID> CMapLoaderH3M::convertBuildings(const std::set<BuildingID> h3m, int castleID, bool addAuxiliary)
  1832. {
  1833. std::map<int, BuildingID> mapa;
  1834. std::set<BuildingID> ret;
  1835. // Note: this file is parsed many times.
  1836. const JsonNode config(ResourceID("config/buildings5.json"));
  1837. for(const JsonNode & entry : config["table"].Vector())
  1838. {
  1839. int town = static_cast<int>(entry["town"].Float());
  1840. if (town == castleID || town == -1)
  1841. {
  1842. mapa[(int)entry["h3"].Float()] = BuildingID((si32)entry["vcmi"].Float());
  1843. }
  1844. }
  1845. for(auto & elem : h3m)
  1846. {
  1847. if(mapa[elem] >= 0)
  1848. {
  1849. ret.insert(mapa[elem]);
  1850. }
  1851. // horde buildings
  1852. else if(mapa[elem] >= (-GameConstants::CREATURES_PER_TOWN))
  1853. {
  1854. int level = (mapa[elem]);
  1855. //(-30)..(-36) - horde buildings (for game loading only), don't see other way to handle hordes in random towns
  1856. ret.insert(BuildingID(level - 30));
  1857. }
  1858. else
  1859. {
  1860. logGlobal->warn("Conversion warning: unknown building %d in castle %d", elem.num, castleID);
  1861. }
  1862. }
  1863. if(addAuxiliary)
  1864. {
  1865. //village hall is always present
  1866. ret.insert(BuildingID::VILLAGE_HALL);
  1867. if(ret.find(BuildingID::CITY_HALL) != ret.end())
  1868. {
  1869. ret.insert(BuildingID::EXTRA_CITY_HALL);
  1870. }
  1871. if(ret.find(BuildingID::TOWN_HALL) != ret.end())
  1872. {
  1873. ret.insert(BuildingID::EXTRA_TOWN_HALL);
  1874. }
  1875. if(ret.find(BuildingID::CAPITOL) != ret.end())
  1876. {
  1877. ret.insert(BuildingID::EXTRA_CAPITOL);
  1878. }
  1879. }
  1880. return ret;
  1881. }
  1882. void CMapLoaderH3M::readEvents()
  1883. {
  1884. int numberOfEvents = reader.readUInt32();
  1885. for(int yyoo = 0; yyoo < numberOfEvents; ++yyoo)
  1886. {
  1887. CMapEvent ne;
  1888. ne.name = reader.readString();
  1889. ne.message = reader.readString();
  1890. readResourses(ne.resources);
  1891. ne.players = reader.readUInt8();
  1892. if(map->version > EMapFormat::AB)
  1893. {
  1894. ne.humanAffected = reader.readUInt8();
  1895. }
  1896. else
  1897. {
  1898. ne.humanAffected = true;
  1899. }
  1900. ne.computerAffected = reader.readUInt8();
  1901. ne.firstOccurence = reader.readUInt16();
  1902. ne.nextOccurence = reader.readUInt8();
  1903. reader.skip(17);
  1904. map->events.push_back(ne);
  1905. }
  1906. }
  1907. void CMapLoaderH3M::readMessageAndGuards(std::string& message, CCreatureSet* guards)
  1908. {
  1909. bool hasMessage = reader.readBool();
  1910. if(hasMessage)
  1911. {
  1912. message = reader.readString();
  1913. bool hasGuards = reader.readBool();
  1914. if(hasGuards)
  1915. {
  1916. readCreatureSet(guards, 7);
  1917. }
  1918. reader.skip(4);
  1919. }
  1920. }
  1921. void CMapLoaderH3M::readSpells(std::set<SpellID>& dest)
  1922. {
  1923. readBitmask(dest,9,GameConstants::SPELLS_QUANTITY,false);
  1924. }
  1925. void CMapLoaderH3M::readResourses(TResources& resources)
  1926. {
  1927. resources.resize(GameConstants::RESOURCE_QUANTITY); //needed?
  1928. for(int x = 0; x < 7; ++x)
  1929. {
  1930. resources[x] = reader.readUInt32();
  1931. }
  1932. }
  1933. template <class Indentifier>
  1934. void CMapLoaderH3M::readBitmask(std::set<Indentifier>& dest, const int byteCount, const int limit, bool negate)
  1935. {
  1936. std::vector<bool> temp;
  1937. temp.resize(limit,true);
  1938. readBitmask(temp, byteCount, limit, negate);
  1939. for(int i = 0; i< std::min(temp.size(), static_cast<size_t>(limit)); i++)
  1940. {
  1941. if(temp[i])
  1942. {
  1943. dest.insert(static_cast<Indentifier>(i));
  1944. }
  1945. }
  1946. }
  1947. void CMapLoaderH3M::readBitmask(std::vector<bool>& dest, const int byteCount, const int limit, bool negate)
  1948. {
  1949. for(int byte = 0; byte < byteCount; ++byte)
  1950. {
  1951. const ui8 mask = reader.readUInt8();
  1952. for(int bit = 0; bit < 8; ++bit)
  1953. {
  1954. if(byte * 8 + bit < limit)
  1955. {
  1956. const bool flag = mask & (1 << bit);
  1957. if((negate && flag) || (!negate && !flag)) // FIXME: check PR388
  1958. dest[byte * 8 + bit] = false;
  1959. }
  1960. }
  1961. }
  1962. }
  1963. ui8 CMapLoaderH3M::reverse(ui8 arg)
  1964. {
  1965. ui8 ret = 0;
  1966. for(int i = 0; i < 8; ++i)
  1967. {
  1968. if((arg & (1 << i)) >> i)
  1969. {
  1970. ret |= (128 >> i);
  1971. }
  1972. }
  1973. return ret;
  1974. }
  1975. void CMapLoaderH3M::afterRead()
  1976. {
  1977. //convert main town positions for all players to actual object position, in H3M it is position of active tile
  1978. for(auto & p : map->players)
  1979. {
  1980. int3 posOfMainTown = p.posOfMainTown;
  1981. if(posOfMainTown.valid() && map->isInTheMap(posOfMainTown))
  1982. {
  1983. const TerrainTile & t = map->getTile(posOfMainTown);
  1984. const CGObjectInstance * mainTown = nullptr;
  1985. for(auto obj : t.visitableObjects)
  1986. {
  1987. if(obj->ID == Obj::TOWN || obj->ID == Obj::RANDOM_TOWN)
  1988. {
  1989. mainTown = obj;
  1990. break;
  1991. }
  1992. }
  1993. if(mainTown == nullptr)
  1994. continue;
  1995. p.posOfMainTown = posOfMainTown + mainTown->getVisitableOffset();
  1996. }
  1997. }
  1998. }