MapFormatH3M.cpp 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259
  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. // Read terrain
  792. int3 pos;
  793. for(pos.z = 0; pos.z < map->levels(); ++pos.z)
  794. {
  795. //OH3 format is [z][y][x]
  796. for(pos.y = 0; pos.y < map->height; pos.y++)
  797. {
  798. for(pos.x = 0; pos.x < map->width; pos.x++)
  799. {
  800. auto & tile = map->getTile(pos);
  801. tile.terType = const_cast<TerrainType*>(VLC->terrainTypeHandler->getByIndex(reader.readUInt8()));
  802. tile.terView = reader.readUInt8();
  803. tile.riverType = const_cast<RiverType*>(VLC->riverTypeHandler->getByIndex(reader.readUInt8()));
  804. tile.riverDir = reader.readUInt8();
  805. tile.roadType = const_cast<RoadType*>(VLC->roadTypeHandler->getByIndex(reader.readUInt8()));
  806. tile.roadDir = reader.readUInt8();
  807. tile.extTileFlags = reader.readUInt8();
  808. tile.blocked = ((!tile.terType->isPassable() || tile.terType->id == ETerrainId::BORDER ) ? true : false); //underground tiles are always blocked
  809. tile.visitable = 0;
  810. }
  811. }
  812. }
  813. }
  814. void CMapLoaderH3M::readDefInfo()
  815. {
  816. int defAmount = reader.readUInt32();
  817. templates.reserve(defAmount);
  818. // Read custom defs
  819. for(int idd = 0; idd < defAmount; ++idd)
  820. {
  821. auto tmpl = new ObjectTemplate;
  822. tmpl->readMap(reader);
  823. templates.push_back(std::shared_ptr<const ObjectTemplate>(tmpl));
  824. }
  825. }
  826. void CMapLoaderH3M::readObjects()
  827. {
  828. int howManyObjs = reader.readUInt32();
  829. for(int ww = 0; ww < howManyObjs; ++ww)
  830. {
  831. CGObjectInstance * nobj = nullptr;
  832. int3 objPos = readInt3();
  833. int defnum = reader.readUInt32();
  834. ObjectInstanceID idToBeGiven = ObjectInstanceID((si32)map->objects.size());
  835. std::shared_ptr<const ObjectTemplate> objTempl = templates.at(defnum);
  836. reader.skip(5);
  837. switch(objTempl->id)
  838. {
  839. case Obj::EVENT:
  840. {
  841. auto evnt = new CGEvent();
  842. nobj = evnt;
  843. readMessageAndGuards(evnt->message, evnt);
  844. evnt->gainedExp = reader.readUInt32();
  845. evnt->manaDiff = reader.readUInt32();
  846. evnt->moraleDiff = reader.readInt8();
  847. evnt->luckDiff = reader.readInt8();
  848. readResourses(evnt->resources);
  849. evnt->primskills.resize(GameConstants::PRIMARY_SKILLS);
  850. for(int x = 0; x < 4; ++x)
  851. {
  852. evnt->primskills[x] = static_cast<PrimarySkill::PrimarySkill>(reader.readUInt8());
  853. }
  854. int gabn = reader.readUInt8(); // Number of gained abilities
  855. for(int oo = 0; oo < gabn; ++oo)
  856. {
  857. evnt->abilities.push_back(SecondarySkill(reader.readUInt8()));
  858. evnt->abilityLevels.push_back(reader.readUInt8());
  859. }
  860. int gart = reader.readUInt8(); // Number of gained artifacts
  861. for(int oo = 0; oo < gart; ++oo)
  862. {
  863. if(map->version == EMapFormat::ROE)
  864. {
  865. evnt->artifacts.push_back(ArtifactID(reader.readUInt8()));
  866. }
  867. else
  868. {
  869. evnt->artifacts.push_back(ArtifactID(reader.readUInt16()));
  870. }
  871. }
  872. int gspel = reader.readUInt8(); // Number of gained spells
  873. for(int oo = 0; oo < gspel; ++oo)
  874. {
  875. evnt->spells.push_back(SpellID(reader.readUInt8()));
  876. }
  877. int gcre = reader.readUInt8(); //number of gained creatures
  878. readCreatureSet(&evnt->creatures, gcre);
  879. reader.skip(8);
  880. evnt->availableFor = reader.readUInt8();
  881. evnt->computerActivate = reader.readUInt8();
  882. evnt->removeAfterVisit = reader.readUInt8();
  883. evnt->humanActivate = true;
  884. reader.skip(4);
  885. break;
  886. }
  887. case Obj::HERO:
  888. case Obj::RANDOM_HERO:
  889. case Obj::PRISON:
  890. {
  891. nobj = readHero(idToBeGiven, objPos);
  892. break;
  893. }
  894. case Obj::MONSTER: //Monster
  895. case Obj::RANDOM_MONSTER:
  896. case Obj::RANDOM_MONSTER_L1:
  897. case Obj::RANDOM_MONSTER_L2:
  898. case Obj::RANDOM_MONSTER_L3:
  899. case Obj::RANDOM_MONSTER_L4:
  900. case Obj::RANDOM_MONSTER_L5:
  901. case Obj::RANDOM_MONSTER_L6:
  902. case Obj::RANDOM_MONSTER_L7:
  903. {
  904. auto cre = new CGCreature();
  905. nobj = cre;
  906. if(map->version > EMapFormat::ROE)
  907. {
  908. cre->identifier = reader.readUInt32();
  909. map->questIdentifierToId[cre->identifier] = idToBeGiven;
  910. }
  911. auto hlp = new CStackInstance();
  912. hlp->count = reader.readUInt16();
  913. //type will be set during initialization
  914. cre->putStack(SlotID(0), hlp);
  915. cre->character = reader.readUInt8();
  916. bool hasMessage = reader.readBool();
  917. if(hasMessage)
  918. {
  919. cre->message = reader.readString();
  920. readResourses(cre->resources);
  921. int artID;
  922. if (map->version == EMapFormat::ROE)
  923. {
  924. artID = reader.readUInt8();
  925. }
  926. else
  927. {
  928. artID = reader.readUInt16();
  929. }
  930. if(map->version == EMapFormat::ROE)
  931. {
  932. if(artID != 0xff)
  933. {
  934. cre->gainedArtifact = ArtifactID(artID);
  935. }
  936. else
  937. {
  938. cre->gainedArtifact = ArtifactID::NONE;
  939. }
  940. }
  941. else
  942. {
  943. if(artID != 0xffff)
  944. {
  945. cre->gainedArtifact = ArtifactID(artID);
  946. }
  947. else
  948. {
  949. cre->gainedArtifact = ArtifactID::NONE;
  950. }
  951. }
  952. }
  953. cre->neverFlees = reader.readUInt8();
  954. cre->notGrowingTeam =reader.readUInt8();
  955. reader.skip(2);
  956. break;
  957. }
  958. case Obj::OCEAN_BOTTLE:
  959. case Obj::SIGN:
  960. {
  961. auto sb = new CGSignBottle();
  962. nobj = sb;
  963. sb->message = reader.readString();
  964. reader.skip(4);
  965. break;
  966. }
  967. case Obj::SEER_HUT:
  968. {
  969. nobj = readSeerHut();
  970. break;
  971. }
  972. case Obj::WITCH_HUT:
  973. {
  974. auto wh = new CGWitchHut();
  975. nobj = wh;
  976. // in RoE we cannot specify it - all are allowed (I hope)
  977. if(map->version > EMapFormat::ROE)
  978. {
  979. for(int i = 0 ; i < 4; ++i)
  980. {
  981. ui8 c = reader.readUInt8();
  982. for(int yy = 0; yy < 8; ++yy)
  983. {
  984. if(i * 8 + yy < GameConstants::SKILL_QUANTITY)
  985. {
  986. if(c == (c | static_cast<ui8>(std::pow(2., yy))))
  987. {
  988. wh->allowedAbilities.push_back(i * 8 + yy);
  989. }
  990. }
  991. }
  992. }
  993. // enable new (modded) skills
  994. if(wh->allowedAbilities.size() != 1)
  995. {
  996. for(int skillID = GameConstants::SKILL_QUANTITY; skillID < VLC->skillh->size(); ++skillID)
  997. wh->allowedAbilities.push_back(skillID);
  998. }
  999. }
  1000. else
  1001. {
  1002. // RoE map
  1003. for(int skillID = 0; skillID < VLC->skillh->size(); ++skillID)
  1004. wh->allowedAbilities.push_back(skillID);
  1005. }
  1006. break;
  1007. }
  1008. case Obj::SCHOLAR:
  1009. {
  1010. auto sch = new CGScholar();
  1011. nobj = sch;
  1012. sch->bonusType = static_cast<CGScholar::EBonusType>(reader.readUInt8());
  1013. sch->bonusID = reader.readUInt8();
  1014. reader.skip(6);
  1015. break;
  1016. }
  1017. case Obj::GARRISON:
  1018. case Obj::GARRISON2:
  1019. {
  1020. auto gar = new CGGarrison();
  1021. nobj = gar;
  1022. nobj->setOwner(PlayerColor(reader.readUInt8()));
  1023. reader.skip(3);
  1024. readCreatureSet(gar, 7);
  1025. if(map->version > EMapFormat::ROE)
  1026. {
  1027. gar->removableUnits = reader.readBool();
  1028. }
  1029. else
  1030. {
  1031. gar->removableUnits = true;
  1032. }
  1033. reader.skip(8);
  1034. break;
  1035. }
  1036. case Obj::ARTIFACT:
  1037. case Obj::RANDOM_ART:
  1038. case Obj::RANDOM_TREASURE_ART:
  1039. case Obj::RANDOM_MINOR_ART:
  1040. case Obj::RANDOM_MAJOR_ART:
  1041. case Obj::RANDOM_RELIC_ART:
  1042. case Obj::SPELL_SCROLL:
  1043. {
  1044. auto artID = ArtifactID::NONE; //random, set later
  1045. int spellID = -1;
  1046. auto art = new CGArtifact();
  1047. nobj = art;
  1048. readMessageAndGuards(art->message, art);
  1049. if(objTempl->id == Obj::SPELL_SCROLL)
  1050. {
  1051. spellID = reader.readUInt32();
  1052. artID = ArtifactID::SPELL_SCROLL;
  1053. }
  1054. else if(objTempl->id == Obj::ARTIFACT)
  1055. {
  1056. //specific artifact
  1057. artID = ArtifactID(objTempl->subid);
  1058. }
  1059. art->storedArtifact = CArtifactInstance::createArtifact(map, artID, spellID);
  1060. break;
  1061. }
  1062. case Obj::RANDOM_RESOURCE:
  1063. case Obj::RESOURCE:
  1064. {
  1065. auto res = new CGResource();
  1066. nobj = res;
  1067. readMessageAndGuards(res->message, res);
  1068. res->amount = reader.readUInt32();
  1069. if(objTempl->subid == Res::GOLD)
  1070. {
  1071. // Gold is multiplied by 100.
  1072. res->amount *= 100;
  1073. }
  1074. reader.skip(4);
  1075. break;
  1076. }
  1077. case Obj::RANDOM_TOWN:
  1078. case Obj::TOWN:
  1079. {
  1080. nobj = readTown(objTempl->subid);
  1081. break;
  1082. }
  1083. case Obj::MINE:
  1084. case Obj::ABANDONED_MINE:
  1085. {
  1086. nobj = new CGMine();
  1087. nobj->setOwner(PlayerColor(reader.readUInt8()));
  1088. reader.skip(3);
  1089. break;
  1090. }
  1091. case Obj::CREATURE_GENERATOR1:
  1092. case Obj::CREATURE_GENERATOR2:
  1093. case Obj::CREATURE_GENERATOR3:
  1094. case Obj::CREATURE_GENERATOR4:
  1095. {
  1096. nobj = new CGDwelling();
  1097. nobj->setOwner(PlayerColor(reader.readUInt8()));
  1098. reader.skip(3);
  1099. break;
  1100. }
  1101. case Obj::SHRINE_OF_MAGIC_INCANTATION:
  1102. case Obj::SHRINE_OF_MAGIC_GESTURE:
  1103. case Obj::SHRINE_OF_MAGIC_THOUGHT:
  1104. {
  1105. auto shr = new CGShrine();
  1106. nobj = shr;
  1107. ui8 raw_id = reader.readUInt8();
  1108. if (255 == raw_id)
  1109. {
  1110. shr->spell = SpellID(SpellID::NONE);
  1111. }
  1112. else
  1113. {
  1114. shr->spell = SpellID(raw_id);
  1115. }
  1116. reader.skip(3);
  1117. break;
  1118. }
  1119. case Obj::PANDORAS_BOX:
  1120. {
  1121. auto box = new CGPandoraBox();
  1122. nobj = box;
  1123. readMessageAndGuards(box->message, box);
  1124. box->gainedExp = reader.readUInt32();
  1125. box->manaDiff = reader.readUInt32();
  1126. box->moraleDiff = reader.readInt8();
  1127. box->luckDiff = reader.readInt8();
  1128. readResourses(box->resources);
  1129. box->primskills.resize(GameConstants::PRIMARY_SKILLS);
  1130. for(int x = 0; x < 4; ++x)
  1131. {
  1132. box->primskills[x] = static_cast<PrimarySkill::PrimarySkill>(reader.readUInt8());
  1133. }
  1134. int gabn = reader.readUInt8();//number of gained abilities
  1135. for(int oo = 0; oo < gabn; ++oo)
  1136. {
  1137. box->abilities.push_back(SecondarySkill(reader.readUInt8()));
  1138. box->abilityLevels.push_back(reader.readUInt8());
  1139. }
  1140. int gart = reader.readUInt8(); //number of gained artifacts
  1141. for(int oo = 0; oo < gart; ++oo)
  1142. {
  1143. if(map->version > EMapFormat::ROE)
  1144. {
  1145. box->artifacts.push_back(ArtifactID(reader.readUInt16()));
  1146. }
  1147. else
  1148. {
  1149. box->artifacts.push_back(ArtifactID(reader.readUInt8()));
  1150. }
  1151. }
  1152. int gspel = reader.readUInt8(); //number of gained spells
  1153. for(int oo = 0; oo < gspel; ++oo)
  1154. {
  1155. box->spells.push_back(SpellID(reader.readUInt8()));
  1156. }
  1157. int gcre = reader.readUInt8(); //number of gained creatures
  1158. readCreatureSet(&box->creatures, gcre);
  1159. reader.skip(8);
  1160. break;
  1161. }
  1162. case Obj::GRAIL:
  1163. {
  1164. map->grailPos = objPos;
  1165. map->grailRadius = reader.readUInt32();
  1166. continue;
  1167. }
  1168. case Obj::RANDOM_DWELLING: //same as castle + level range
  1169. case Obj::RANDOM_DWELLING_LVL: //same as castle, fixed level
  1170. case Obj::RANDOM_DWELLING_FACTION: //level range, fixed faction
  1171. {
  1172. auto dwelling = new CGDwelling();
  1173. nobj = dwelling;
  1174. CSpecObjInfo * spec = nullptr;
  1175. switch(objTempl->id)
  1176. {
  1177. case Obj::RANDOM_DWELLING:
  1178. spec = new CCreGenLeveledCastleInfo();
  1179. break;
  1180. case Obj::RANDOM_DWELLING_LVL:
  1181. spec = new CCreGenAsCastleInfo();
  1182. break;
  1183. case Obj::RANDOM_DWELLING_FACTION:
  1184. spec = new CCreGenLeveledInfo();
  1185. break;
  1186. default:
  1187. throw std::runtime_error("Invalid random dwelling format");
  1188. }
  1189. spec->owner = dwelling;
  1190. nobj->setOwner(PlayerColor(reader.readUInt32()));
  1191. //216 and 217
  1192. if (auto castleSpec = dynamic_cast<CCreGenAsCastleInfo *>(spec))
  1193. {
  1194. castleSpec->instanceId = "";
  1195. castleSpec->identifier = reader.readUInt32();
  1196. if(!castleSpec->identifier)
  1197. {
  1198. castleSpec->asCastle = false;
  1199. const int MASK_SIZE = 8;
  1200. ui8 mask[2];
  1201. mask[0] = reader.readUInt8();
  1202. mask[1] = reader.readUInt8();
  1203. castleSpec->allowedFactions.clear();
  1204. castleSpec->allowedFactions.resize(VLC->townh->size(), false);
  1205. for(int i = 0; i < MASK_SIZE; i++)
  1206. castleSpec->allowedFactions[i] = ((mask[0] & (1 << i))>0);
  1207. for(int i = 0; i < (GameConstants::F_NUMBER-MASK_SIZE); i++)
  1208. castleSpec->allowedFactions[i+MASK_SIZE] = ((mask[1] & (1 << i))>0);
  1209. }
  1210. else
  1211. {
  1212. castleSpec->asCastle = true;
  1213. }
  1214. }
  1215. //216 and 218
  1216. if (auto lvlSpec = dynamic_cast<CCreGenLeveledInfo *>(spec))
  1217. {
  1218. lvlSpec->minLevel = std::max(reader.readUInt8(), ui8(1));
  1219. lvlSpec->maxLevel = std::min(reader.readUInt8(), ui8(7));
  1220. }
  1221. dwelling->info = spec;
  1222. break;
  1223. }
  1224. case Obj::QUEST_GUARD:
  1225. {
  1226. auto guard = new CGQuestGuard();
  1227. readQuest(guard);
  1228. nobj = guard;
  1229. break;
  1230. }
  1231. case Obj::SHIPYARD:
  1232. {
  1233. nobj = new CGShipyard();
  1234. nobj->setOwner(PlayerColor(reader.readUInt32()));
  1235. break;
  1236. }
  1237. case Obj::HERO_PLACEHOLDER: //hero placeholder
  1238. {
  1239. auto hp = new CGHeroPlaceholder();
  1240. nobj = hp;
  1241. hp->setOwner(PlayerColor(reader.readUInt8()));
  1242. int htid = reader.readUInt8(); //hero type id
  1243. nobj->subID = htid;
  1244. if(htid == 0xff)
  1245. {
  1246. hp->power = reader.readUInt8();
  1247. logGlobal->info("Hero placeholder: by power at %s", objPos.toString());
  1248. }
  1249. else
  1250. {
  1251. logGlobal->info("Hero placeholder: %s at %s", VLC->heroh->objects[htid]->name, objPos.toString());
  1252. hp->power = 0;
  1253. }
  1254. break;
  1255. }
  1256. case Obj::BORDERGUARD:
  1257. {
  1258. nobj = new CGBorderGuard();
  1259. break;
  1260. }
  1261. case Obj::BORDER_GATE:
  1262. {
  1263. nobj = new CGBorderGate();
  1264. break;
  1265. }
  1266. case Obj::PYRAMID: //Pyramid of WoG object
  1267. {
  1268. if(objTempl->subid == 0)
  1269. {
  1270. nobj = new CBank();
  1271. }
  1272. else
  1273. {
  1274. //WoG object
  1275. //TODO: possible special handling
  1276. nobj = new CGObjectInstance();
  1277. }
  1278. break;
  1279. }
  1280. case Obj::LIGHTHOUSE: //Lighthouse
  1281. {
  1282. nobj = new CGLighthouse();
  1283. nobj->tempOwner = PlayerColor(reader.readUInt32());
  1284. break;
  1285. }
  1286. default: //any other object
  1287. {
  1288. if (VLC->objtypeh->knownSubObjects(objTempl->id).count(objTempl->subid))
  1289. {
  1290. nobj = VLC->objtypeh->getHandlerFor(objTempl->id, objTempl->subid)->create(objTempl);
  1291. }
  1292. else
  1293. {
  1294. logGlobal->warn("Unrecognized object: %d:%d at %s on map %s", objTempl->id.toEnum(), objTempl->subid, objPos.toString(), map->name);
  1295. nobj = new CGObjectInstance();
  1296. }
  1297. break;
  1298. }
  1299. }
  1300. nobj->pos = objPos;
  1301. nobj->ID = objTempl->id;
  1302. nobj->id = idToBeGiven;
  1303. if(nobj->ID != Obj::HERO && nobj->ID != Obj::HERO_PLACEHOLDER && nobj->ID != Obj::PRISON)
  1304. {
  1305. nobj->subID = objTempl->subid;
  1306. }
  1307. nobj->appearance = objTempl;
  1308. assert(idToBeGiven == ObjectInstanceID((si32)map->objects.size()));
  1309. {
  1310. //TODO: define valid typeName and subtypeName fro H3M maps
  1311. //boost::format fmt("%s_%d");
  1312. //fmt % nobj->typeName % nobj->id.getNum();
  1313. boost::format fmt("obj_%d");
  1314. fmt % nobj->id.getNum();
  1315. nobj->instanceName = fmt.str();
  1316. }
  1317. map->addNewObject(nobj);
  1318. }
  1319. std::sort(map->heroesOnMap.begin(), map->heroesOnMap.end(), [](const ConstTransitivePtr<CGHeroInstance> & a, const ConstTransitivePtr<CGHeroInstance> & b)
  1320. {
  1321. return a->subID < b->subID;
  1322. });
  1323. }
  1324. void CMapLoaderH3M::readCreatureSet(CCreatureSet * out, int number)
  1325. {
  1326. const bool version = (map->version > EMapFormat::ROE);
  1327. const int maxID = version ? 0xffff : 0xff;
  1328. for(int ir = 0; ir < number; ++ir)
  1329. {
  1330. CreatureID creID;
  1331. int count;
  1332. if (version)
  1333. {
  1334. creID = CreatureID(reader.readUInt16());
  1335. }
  1336. else
  1337. {
  1338. creID = CreatureID(reader.readUInt8());
  1339. }
  1340. count = reader.readUInt16();
  1341. // Empty slot
  1342. if(creID == maxID)
  1343. continue;
  1344. auto hlp = new CStackInstance();
  1345. hlp->count = count;
  1346. if(creID > maxID - 0xf)
  1347. {
  1348. //this will happen when random object has random army
  1349. hlp->idRand = maxID - creID - 1;
  1350. }
  1351. else
  1352. {
  1353. hlp->setType(creID);
  1354. }
  1355. out->putStack(SlotID(ir), hlp);
  1356. }
  1357. out->validTypes(true);
  1358. }
  1359. CGObjectInstance * CMapLoaderH3M::readHero(ObjectInstanceID idToBeGiven, const int3 & initialPos)
  1360. {
  1361. auto nhi = new CGHeroInstance();
  1362. if(map->version > EMapFormat::ROE)
  1363. {
  1364. unsigned int identifier = reader.readUInt32();
  1365. map->questIdentifierToId[identifier] = idToBeGiven;
  1366. }
  1367. PlayerColor owner = PlayerColor(reader.readUInt8());
  1368. nhi->subID = reader.readUInt8();
  1369. assert(!nhi->getArt(ArtifactPosition::MACH4));
  1370. //If hero of this type has been predefined, use that as a base.
  1371. //Instance data will overwrite the predefined values where appropriate.
  1372. for(auto & elem : map->predefinedHeroes)
  1373. {
  1374. if(elem->subID == nhi->subID)
  1375. {
  1376. logGlobal->debug("Hero %d will be taken from the predefined heroes list.", nhi->subID);
  1377. delete nhi;
  1378. nhi = elem;
  1379. break;
  1380. }
  1381. }
  1382. nhi->setOwner(owner);
  1383. nhi->portrait = nhi->subID;
  1384. for(auto & elem : map->disposedHeroes)
  1385. {
  1386. if(elem.heroId == nhi->subID)
  1387. {
  1388. nhi->name = elem.name;
  1389. nhi->portrait = elem.portrait;
  1390. break;
  1391. }
  1392. }
  1393. bool hasName = reader.readBool();
  1394. if(hasName)
  1395. {
  1396. nhi->name = reader.readString();
  1397. }
  1398. if(map->version > EMapFormat::AB)
  1399. {
  1400. bool hasExp = reader.readBool();
  1401. if(hasExp)
  1402. {
  1403. nhi->exp = reader.readUInt32();
  1404. }
  1405. else
  1406. {
  1407. nhi->exp = 0xffffffff;
  1408. }
  1409. }
  1410. else
  1411. {
  1412. nhi->exp = reader.readUInt32();
  1413. //0 means "not set" in <=AB maps
  1414. if(!nhi->exp)
  1415. {
  1416. nhi->exp = 0xffffffff;
  1417. }
  1418. }
  1419. bool hasPortrait = reader.readBool();
  1420. if(hasPortrait)
  1421. {
  1422. nhi->portrait = reader.readUInt8();
  1423. }
  1424. bool hasSecSkills = reader.readBool();
  1425. if(hasSecSkills)
  1426. {
  1427. if(nhi->secSkills.size())
  1428. {
  1429. nhi->secSkills.clear();
  1430. //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);
  1431. }
  1432. int howMany = reader.readUInt32();
  1433. nhi->secSkills.resize(howMany);
  1434. for(int yy = 0; yy < howMany; ++yy)
  1435. {
  1436. nhi->secSkills[yy].first = SecondarySkill(reader.readUInt8());
  1437. nhi->secSkills[yy].second = reader.readUInt8();
  1438. }
  1439. }
  1440. bool hasGarison = reader.readBool();
  1441. if(hasGarison)
  1442. {
  1443. readCreatureSet(nhi, 7);
  1444. }
  1445. nhi->formation = reader.readUInt8();
  1446. loadArtifactsOfHero(nhi);
  1447. nhi->patrol.patrolRadius = reader.readUInt8();
  1448. nhi->patrol.patrolling = (nhi->patrol.patrolRadius != 0xff);
  1449. if(map->version > EMapFormat::ROE)
  1450. {
  1451. bool hasCustomBiography = reader.readBool();
  1452. if(hasCustomBiography)
  1453. {
  1454. nhi->biography = reader.readString();
  1455. }
  1456. nhi->sex = reader.readUInt8();
  1457. // Remove trash
  1458. if (nhi->sex != 0xFF)
  1459. {
  1460. nhi->sex &= 1;
  1461. }
  1462. }
  1463. else
  1464. {
  1465. nhi->sex = 0xFF;
  1466. }
  1467. // Spells
  1468. if(map->version > EMapFormat::AB)
  1469. {
  1470. bool hasCustomSpells = reader.readBool();
  1471. if(nhi->spells.size())
  1472. {
  1473. nhi->clear();
  1474. 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);
  1475. }
  1476. if(hasCustomSpells)
  1477. {
  1478. nhi->spells.insert(SpellID::PRESET); //placeholder "preset spells"
  1479. readSpells(nhi->spells);
  1480. }
  1481. }
  1482. else if(map->version == EMapFormat::AB)
  1483. {
  1484. //we can read one spell
  1485. ui8 buff = reader.readUInt8();
  1486. if(buff != 254)
  1487. {
  1488. nhi->spells.insert(SpellID::PRESET); //placeholder "preset spells"
  1489. if(buff < 254) //255 means no spells
  1490. {
  1491. nhi->spells.insert(SpellID(buff));
  1492. }
  1493. }
  1494. }
  1495. if(map->version > EMapFormat::AB)
  1496. {
  1497. bool hasCustomPrimSkills = reader.readBool();
  1498. if(hasCustomPrimSkills)
  1499. {
  1500. auto ps = nhi->getAllBonuses(Selector::type()(Bonus::PRIMARY_SKILL)
  1501. .And(Selector::sourceType()(Bonus::HERO_BASE_SKILL)), nullptr);
  1502. if(ps->size())
  1503. {
  1504. 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);
  1505. for(auto b : *ps)
  1506. nhi->removeBonus(b);
  1507. }
  1508. for(int xx = 0; xx < GameConstants::PRIMARY_SKILLS; ++xx)
  1509. {
  1510. nhi->pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(xx), reader.readUInt8());
  1511. }
  1512. }
  1513. }
  1514. reader.skip(16);
  1515. return nhi;
  1516. }
  1517. CGSeerHut * CMapLoaderH3M::readSeerHut()
  1518. {
  1519. auto hut = new CGSeerHut();
  1520. if(map->version > EMapFormat::ROE)
  1521. {
  1522. readQuest(hut);
  1523. }
  1524. else
  1525. {
  1526. //RoE
  1527. auto artID = ArtifactID(reader.readUInt8());
  1528. if (artID != 255)
  1529. {
  1530. //not none quest
  1531. hut->quest->addArtifactID(artID);
  1532. hut->quest->missionType = CQuest::MISSION_ART;
  1533. }
  1534. else
  1535. {
  1536. hut->quest->missionType = CQuest::MISSION_NONE;
  1537. }
  1538. hut->quest->lastDay = -1; //no timeout
  1539. hut->quest->isCustomFirst = hut->quest->isCustomNext = hut->quest->isCustomComplete = false;
  1540. }
  1541. if (hut->quest->missionType)
  1542. {
  1543. auto rewardType = static_cast<CGSeerHut::ERewardType>(reader.readUInt8());
  1544. hut->rewardType = rewardType;
  1545. switch(rewardType)
  1546. {
  1547. case CGSeerHut::EXPERIENCE:
  1548. {
  1549. hut->rVal = reader.readUInt32();
  1550. break;
  1551. }
  1552. case CGSeerHut::MANA_POINTS:
  1553. {
  1554. hut->rVal = reader.readUInt32();
  1555. break;
  1556. }
  1557. case CGSeerHut::MORALE_BONUS:
  1558. {
  1559. hut->rVal = reader.readUInt8();
  1560. break;
  1561. }
  1562. case CGSeerHut::LUCK_BONUS:
  1563. {
  1564. hut->rVal = reader.readUInt8();
  1565. break;
  1566. }
  1567. case CGSeerHut::RESOURCES:
  1568. {
  1569. hut->rID = reader.readUInt8();
  1570. // Only the first 3 bytes are used. Skip the 4th.
  1571. hut->rVal = reader.readUInt32() & 0x00ffffff;
  1572. break;
  1573. }
  1574. case CGSeerHut::PRIMARY_SKILL:
  1575. {
  1576. hut->rID = reader.readUInt8();
  1577. hut->rVal = reader.readUInt8();
  1578. break;
  1579. }
  1580. case CGSeerHut::SECONDARY_SKILL:
  1581. {
  1582. hut->rID = reader.readUInt8();
  1583. hut->rVal = reader.readUInt8();
  1584. break;
  1585. }
  1586. case CGSeerHut::ARTIFACT:
  1587. {
  1588. if (map->version == EMapFormat::ROE)
  1589. {
  1590. hut->rID = reader.readUInt8();
  1591. }
  1592. else
  1593. {
  1594. hut->rID = reader.readUInt16();
  1595. }
  1596. break;
  1597. }
  1598. case CGSeerHut::SPELL:
  1599. {
  1600. hut->rID = reader.readUInt8();
  1601. break;
  1602. }
  1603. case CGSeerHut::CREATURE:
  1604. {
  1605. if(map->version > EMapFormat::ROE)
  1606. {
  1607. hut->rID = reader.readUInt16();
  1608. hut->rVal = reader.readUInt16();
  1609. }
  1610. else
  1611. {
  1612. hut->rID = reader.readUInt8();
  1613. hut->rVal = reader.readUInt16();
  1614. }
  1615. break;
  1616. }
  1617. }
  1618. reader.skip(2);
  1619. }
  1620. else
  1621. {
  1622. // missionType==255
  1623. reader.skip(3);
  1624. }
  1625. return hut;
  1626. }
  1627. void CMapLoaderH3M::readQuest(IQuestObject * guard)
  1628. {
  1629. guard->quest->missionType = static_cast<CQuest::Emission>(reader.readUInt8());
  1630. switch(guard->quest->missionType)
  1631. {
  1632. case CQuest::MISSION_NONE:
  1633. return;
  1634. case CQuest::MISSION_PRIMARY_STAT:
  1635. {
  1636. guard->quest->m2stats.resize(4);
  1637. for(int x = 0; x < 4; ++x)
  1638. {
  1639. guard->quest->m2stats[x] = reader.readUInt8();
  1640. }
  1641. }
  1642. break;
  1643. case CQuest::MISSION_LEVEL:
  1644. case CQuest::MISSION_KILL_HERO:
  1645. case CQuest::MISSION_KILL_CREATURE:
  1646. {
  1647. guard->quest->m13489val = reader.readUInt32();
  1648. break;
  1649. }
  1650. case CQuest::MISSION_ART:
  1651. {
  1652. int artNumber = reader.readUInt8();
  1653. for(int yy = 0; yy < artNumber; ++yy)
  1654. {
  1655. auto artid = ArtifactID(reader.readUInt16());
  1656. guard->quest->addArtifactID(artid);
  1657. map->allowedArtifact[artid] = false; //these are unavailable for random generation
  1658. }
  1659. break;
  1660. }
  1661. case CQuest::MISSION_ARMY:
  1662. {
  1663. int typeNumber = reader.readUInt8();
  1664. guard->quest->m6creatures.resize(typeNumber);
  1665. for(int hh = 0; hh < typeNumber; ++hh)
  1666. {
  1667. guard->quest->m6creatures[hh].type = VLC->creh->objects[reader.readUInt16()];
  1668. guard->quest->m6creatures[hh].count = reader.readUInt16();
  1669. }
  1670. break;
  1671. }
  1672. case CQuest::MISSION_RESOURCES:
  1673. {
  1674. guard->quest->m7resources.resize(7);
  1675. for(int x = 0; x < 7; ++x)
  1676. {
  1677. guard->quest->m7resources[x] = reader.readUInt32();
  1678. }
  1679. break;
  1680. }
  1681. case CQuest::MISSION_HERO:
  1682. case CQuest::MISSION_PLAYER:
  1683. {
  1684. guard->quest->m13489val = reader.readUInt8();
  1685. break;
  1686. }
  1687. }
  1688. int limit = reader.readUInt32();
  1689. if(limit == (static_cast<int>(0xffffffff)))
  1690. {
  1691. guard->quest->lastDay = -1;
  1692. }
  1693. else
  1694. {
  1695. guard->quest->lastDay = limit;
  1696. }
  1697. guard->quest->firstVisitText = reader.readString();
  1698. guard->quest->nextVisitText = reader.readString();
  1699. guard->quest->completedText = reader.readString();
  1700. guard->quest->isCustomFirst = guard->quest->firstVisitText.size() > 0;
  1701. guard->quest->isCustomNext = guard->quest->nextVisitText.size() > 0;
  1702. guard->quest->isCustomComplete = guard->quest->completedText.size() > 0;
  1703. }
  1704. CGTownInstance * CMapLoaderH3M::readTown(int castleID)
  1705. {
  1706. auto nt = new CGTownInstance();
  1707. if(map->version > EMapFormat::ROE)
  1708. {
  1709. nt->identifier = reader.readUInt32();
  1710. }
  1711. nt->tempOwner = PlayerColor(reader.readUInt8());
  1712. bool hasName = reader.readBool();
  1713. if(hasName)
  1714. {
  1715. nt->name = reader.readString();
  1716. }
  1717. bool hasGarrison = reader.readBool();
  1718. if(hasGarrison)
  1719. {
  1720. readCreatureSet(nt, 7);
  1721. }
  1722. nt->formation = reader.readUInt8();
  1723. bool hasCustomBuildings = reader.readBool();
  1724. if(hasCustomBuildings)
  1725. {
  1726. readBitmask(nt->builtBuildings,6,48,false);
  1727. readBitmask(nt->forbiddenBuildings,6,48,false);
  1728. nt->builtBuildings = convertBuildings(nt->builtBuildings, castleID);
  1729. nt->forbiddenBuildings = convertBuildings(nt->forbiddenBuildings, castleID);
  1730. }
  1731. // Standard buildings
  1732. else
  1733. {
  1734. bool hasFort = reader.readBool();
  1735. if(hasFort)
  1736. {
  1737. nt->builtBuildings.insert(BuildingID::FORT);
  1738. }
  1739. //means that set of standard building should be included
  1740. nt->builtBuildings.insert(BuildingID::DEFAULT);
  1741. }
  1742. if(map->version > EMapFormat::ROE)
  1743. {
  1744. for(int i = 0; i < 9; ++i)
  1745. {
  1746. ui8 c = reader.readUInt8();
  1747. for(int yy = 0; yy < 8; ++yy)
  1748. {
  1749. if(i * 8 + yy < GameConstants::SPELLS_QUANTITY)
  1750. {
  1751. if(c == (c | static_cast<ui8>(std::pow(2., yy)))) //add obligatory spell even if it's banned on a map (?)
  1752. {
  1753. nt->obligatorySpells.push_back(SpellID(i * 8 + yy));
  1754. }
  1755. }
  1756. }
  1757. }
  1758. }
  1759. for(int i = 0; i < 9; ++i)
  1760. {
  1761. ui8 c = reader.readUInt8();
  1762. for(int yy = 0; yy < 8; ++yy)
  1763. {
  1764. int spellid = i * 8 + yy;
  1765. if(spellid < GameConstants::SPELLS_QUANTITY)
  1766. {
  1767. if(c != (c | static_cast<ui8>(std::pow(2., yy))) && map->allowedSpell[spellid]) //add random spell only if it's allowed on entire map
  1768. {
  1769. nt->possibleSpells.push_back(SpellID(spellid));
  1770. }
  1771. }
  1772. }
  1773. }
  1774. //add all spells from mods
  1775. //TODO: allow customize new spells in towns
  1776. for (int i = SpellID::AFTER_LAST; i < VLC->spellh->objects.size(); ++i)
  1777. {
  1778. nt->possibleSpells.push_back(SpellID(i));
  1779. }
  1780. // Read castle events
  1781. int numberOfEvent = reader.readUInt32();
  1782. for(int gh = 0; gh < numberOfEvent; ++gh)
  1783. {
  1784. CCastleEvent nce;
  1785. nce.town = nt;
  1786. nce.name = reader.readString();
  1787. nce.message = reader.readString();
  1788. readResourses(nce.resources);
  1789. nce.players = reader.readUInt8();
  1790. if(map->version > EMapFormat::AB)
  1791. {
  1792. nce.humanAffected = reader.readUInt8();
  1793. }
  1794. else
  1795. {
  1796. nce.humanAffected = true;
  1797. }
  1798. nce.computerAffected = reader.readUInt8();
  1799. nce.firstOccurence = reader.readUInt16();
  1800. nce.nextOccurence = reader.readUInt8();
  1801. reader.skip(17);
  1802. // New buildings
  1803. readBitmask(nce.buildings,6,48,false);
  1804. nce.buildings = convertBuildings(nce.buildings, castleID, false);
  1805. nce.creatures.resize(7);
  1806. for(int vv = 0; vv < 7; ++vv)
  1807. {
  1808. nce.creatures[vv] = reader.readUInt16();
  1809. }
  1810. reader.skip(4);
  1811. nt->events.push_back(nce);
  1812. }
  1813. if(map->version > EMapFormat::AB)
  1814. {
  1815. nt->alignment = reader.readUInt8();
  1816. }
  1817. reader.skip(3);
  1818. return nt;
  1819. }
  1820. std::set<BuildingID> CMapLoaderH3M::convertBuildings(const std::set<BuildingID> h3m, int castleID, bool addAuxiliary)
  1821. {
  1822. std::map<int, BuildingID> mapa;
  1823. std::set<BuildingID> ret;
  1824. // Note: this file is parsed many times.
  1825. const JsonNode config(ResourceID("config/buildings5.json"));
  1826. for(const JsonNode & entry : config["table"].Vector())
  1827. {
  1828. int town = static_cast<int>(entry["town"].Float());
  1829. if (town == castleID || town == -1)
  1830. {
  1831. mapa[(int)entry["h3"].Float()] = BuildingID((si32)entry["vcmi"].Float());
  1832. }
  1833. }
  1834. for(auto & elem : h3m)
  1835. {
  1836. if(mapa[elem] >= 0)
  1837. {
  1838. ret.insert(mapa[elem]);
  1839. }
  1840. // horde buildings
  1841. else if(mapa[elem] >= (-GameConstants::CREATURES_PER_TOWN))
  1842. {
  1843. int level = (mapa[elem]);
  1844. //(-30)..(-36) - horde buildings (for game loading only), don't see other way to handle hordes in random towns
  1845. ret.insert(BuildingID(level - 30));
  1846. }
  1847. else
  1848. {
  1849. logGlobal->warn("Conversion warning: unknown building %d in castle %d", elem.num, castleID);
  1850. }
  1851. }
  1852. if(addAuxiliary)
  1853. {
  1854. //village hall is always present
  1855. ret.insert(BuildingID::VILLAGE_HALL);
  1856. if(ret.find(BuildingID::CITY_HALL) != ret.end())
  1857. {
  1858. ret.insert(BuildingID::EXTRA_CITY_HALL);
  1859. }
  1860. if(ret.find(BuildingID::TOWN_HALL) != ret.end())
  1861. {
  1862. ret.insert(BuildingID::EXTRA_TOWN_HALL);
  1863. }
  1864. if(ret.find(BuildingID::CAPITOL) != ret.end())
  1865. {
  1866. ret.insert(BuildingID::EXTRA_CAPITOL);
  1867. }
  1868. }
  1869. return ret;
  1870. }
  1871. void CMapLoaderH3M::readEvents()
  1872. {
  1873. int numberOfEvents = reader.readUInt32();
  1874. for(int yyoo = 0; yyoo < numberOfEvents; ++yyoo)
  1875. {
  1876. CMapEvent ne;
  1877. ne.name = reader.readString();
  1878. ne.message = reader.readString();
  1879. readResourses(ne.resources);
  1880. ne.players = reader.readUInt8();
  1881. if(map->version > EMapFormat::AB)
  1882. {
  1883. ne.humanAffected = reader.readUInt8();
  1884. }
  1885. else
  1886. {
  1887. ne.humanAffected = true;
  1888. }
  1889. ne.computerAffected = reader.readUInt8();
  1890. ne.firstOccurence = reader.readUInt16();
  1891. ne.nextOccurence = reader.readUInt8();
  1892. reader.skip(17);
  1893. map->events.push_back(ne);
  1894. }
  1895. }
  1896. void CMapLoaderH3M::readMessageAndGuards(std::string& message, CCreatureSet* guards)
  1897. {
  1898. bool hasMessage = reader.readBool();
  1899. if(hasMessage)
  1900. {
  1901. message = reader.readString();
  1902. bool hasGuards = reader.readBool();
  1903. if(hasGuards)
  1904. {
  1905. readCreatureSet(guards, 7);
  1906. }
  1907. reader.skip(4);
  1908. }
  1909. }
  1910. void CMapLoaderH3M::readSpells(std::set<SpellID>& dest)
  1911. {
  1912. readBitmask(dest,9,GameConstants::SPELLS_QUANTITY,false);
  1913. }
  1914. void CMapLoaderH3M::readResourses(TResources& resources)
  1915. {
  1916. resources.resize(GameConstants::RESOURCE_QUANTITY); //needed?
  1917. for(int x = 0; x < 7; ++x)
  1918. {
  1919. resources[x] = reader.readUInt32();
  1920. }
  1921. }
  1922. template <class Indentifier>
  1923. void CMapLoaderH3M::readBitmask(std::set<Indentifier>& dest, const int byteCount, const int limit, bool negate)
  1924. {
  1925. std::vector<bool> temp;
  1926. temp.resize(limit,true);
  1927. readBitmask(temp, byteCount, limit, negate);
  1928. for(int i = 0; i< std::min(temp.size(), static_cast<size_t>(limit)); i++)
  1929. {
  1930. if(temp[i])
  1931. {
  1932. dest.insert(static_cast<Indentifier>(i));
  1933. }
  1934. }
  1935. }
  1936. void CMapLoaderH3M::readBitmask(std::vector<bool>& dest, const int byteCount, const int limit, bool negate)
  1937. {
  1938. for(int byte = 0; byte < byteCount; ++byte)
  1939. {
  1940. const ui8 mask = reader.readUInt8();
  1941. for(int bit = 0; bit < 8; ++bit)
  1942. {
  1943. if(byte * 8 + bit < limit)
  1944. {
  1945. const bool flag = mask & (1 << bit);
  1946. if((negate && flag) || (!negate && !flag)) // FIXME: check PR388
  1947. dest[byte * 8 + bit] = false;
  1948. }
  1949. }
  1950. }
  1951. }
  1952. ui8 CMapLoaderH3M::reverse(ui8 arg)
  1953. {
  1954. ui8 ret = 0;
  1955. for(int i = 0; i < 8; ++i)
  1956. {
  1957. if((arg & (1 << i)) >> i)
  1958. {
  1959. ret |= (128 >> i);
  1960. }
  1961. }
  1962. return ret;
  1963. }
  1964. void CMapLoaderH3M::afterRead()
  1965. {
  1966. //convert main town positions for all players to actual object position, in H3M it is position of active tile
  1967. for(auto & p : map->players)
  1968. {
  1969. int3 posOfMainTown = p.posOfMainTown;
  1970. if(posOfMainTown.valid() && map->isInTheMap(posOfMainTown))
  1971. {
  1972. const TerrainTile & t = map->getTile(posOfMainTown);
  1973. const CGObjectInstance * mainTown = nullptr;
  1974. for(auto obj : t.visitableObjects)
  1975. {
  1976. if(obj->ID == Obj::TOWN || obj->ID == Obj::RANDOM_TOWN)
  1977. {
  1978. mainTown = obj;
  1979. break;
  1980. }
  1981. }
  1982. if(mainTown == nullptr)
  1983. continue;
  1984. p.posOfMainTown = posOfMainTown + mainTown->getVisitableOffset();
  1985. }
  1986. }
  1987. }
  1988. VCMI_LIB_NAMESPACE_END