MapFormatH3M.cpp 57 KB

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