MapFormatH3M.cpp 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239
  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. break; case Obj::RANDOM_DWELLING: spec = new CCreGenLeveledCastleInfo();
  1162. break; case Obj::RANDOM_DWELLING_LVL: spec = new CCreGenAsCastleInfo();
  1163. break; case Obj::RANDOM_DWELLING_FACTION: spec = new CCreGenLeveledInfo();
  1164. }
  1165. spec->owner = dwelling;
  1166. nobj->setOwner(PlayerColor(reader.readUInt32()));
  1167. //216 and 217
  1168. if (auto castleSpec = dynamic_cast<CCreGenAsCastleInfo *>(spec))
  1169. {
  1170. castleSpec->instanceId = "";
  1171. castleSpec->identifier = reader.readUInt32();
  1172. if(!castleSpec->identifier)
  1173. {
  1174. castleSpec->asCastle = false;
  1175. const int MASK_SIZE = 8;
  1176. ui8 mask[2];
  1177. mask[0] = reader.readUInt8();
  1178. mask[1] = reader.readUInt8();
  1179. castleSpec->allowedFactions.clear();
  1180. castleSpec->allowedFactions.resize(VLC->townh->factions.size(), false);
  1181. for(int i = 0; i < MASK_SIZE; i++)
  1182. castleSpec->allowedFactions[i] = ((mask[0] & (1 << i))>0);
  1183. for(int i = 0; i < (GameConstants::F_NUMBER-MASK_SIZE); i++)
  1184. castleSpec->allowedFactions[i+MASK_SIZE] = ((mask[1] & (1 << i))>0);
  1185. }
  1186. else
  1187. {
  1188. castleSpec->asCastle = true;
  1189. }
  1190. }
  1191. //216 and 218
  1192. if (auto lvlSpec = dynamic_cast<CCreGenLeveledInfo *>(spec))
  1193. {
  1194. lvlSpec->minLevel = std::max(reader.readUInt8(), ui8(1));
  1195. lvlSpec->maxLevel = std::min(reader.readUInt8(), ui8(7));
  1196. }
  1197. dwelling->info = spec;
  1198. break;
  1199. }
  1200. case Obj::QUEST_GUARD:
  1201. {
  1202. auto guard = new CGQuestGuard();
  1203. readQuest(guard);
  1204. nobj = guard;
  1205. break;
  1206. }
  1207. case Obj::SHIPYARD:
  1208. {
  1209. nobj = new CGShipyard();
  1210. nobj->setOwner(PlayerColor(reader.readUInt32()));
  1211. break;
  1212. }
  1213. case Obj::HERO_PLACEHOLDER: //hero placeholder
  1214. {
  1215. auto hp = new CGHeroPlaceholder();
  1216. nobj = hp;
  1217. hp->setOwner(PlayerColor(reader.readUInt8()));
  1218. int htid = reader.readUInt8();; //hero type id
  1219. nobj->subID = htid;
  1220. if(htid == 0xff)
  1221. {
  1222. hp->power = reader.readUInt8();
  1223. logGlobal->infoStream() << "Hero placeholder: by power at " << objPos;
  1224. }
  1225. else
  1226. {
  1227. logGlobal->infoStream() << "Hero placeholder: " << VLC->heroh->heroes[htid]->name << " at " << objPos;
  1228. hp->power = 0;
  1229. }
  1230. break;
  1231. }
  1232. case Obj::BORDERGUARD:
  1233. {
  1234. nobj = new CGBorderGuard();
  1235. break;
  1236. }
  1237. case Obj::BORDER_GATE:
  1238. {
  1239. nobj = new CGBorderGate();
  1240. break;
  1241. }
  1242. case Obj::PYRAMID: //Pyramid of WoG object
  1243. {
  1244. if(objTempl.subid == 0)
  1245. {
  1246. nobj = new CBank();
  1247. }
  1248. else
  1249. {
  1250. //WoG object
  1251. //TODO: possible special handling
  1252. nobj = new CGObjectInstance();
  1253. }
  1254. break;
  1255. }
  1256. case Obj::LIGHTHOUSE: //Lighthouse
  1257. {
  1258. nobj = new CGLighthouse();
  1259. nobj->tempOwner = PlayerColor(reader.readUInt32());
  1260. break;
  1261. }
  1262. default: //any other object
  1263. {
  1264. if (VLC->objtypeh->knownSubObjects(objTempl.id).count(objTempl.subid))
  1265. {
  1266. nobj = VLC->objtypeh->getHandlerFor(objTempl.id, objTempl.subid)->create(objTempl);
  1267. }
  1268. else
  1269. {
  1270. logGlobal->warnStream() << "Unrecognized object: " << objTempl.id << ":" << objTempl.subid << " at " << objPos
  1271. << " on map " << map->name;
  1272. nobj = new CGObjectInstance();
  1273. }
  1274. break;
  1275. }
  1276. }
  1277. nobj->pos = objPos;
  1278. nobj->ID = objTempl.id;
  1279. nobj->id = idToBeGiven;
  1280. if(nobj->ID != Obj::HERO && nobj->ID != Obj::HERO_PLACEHOLDER && nobj->ID != Obj::PRISON)
  1281. {
  1282. nobj->subID = objTempl.subid;
  1283. }
  1284. nobj->appearance = objTempl;
  1285. assert(idToBeGiven == ObjectInstanceID(map->objects.size()));
  1286. {
  1287. //TODO: define valid typeName and subtypeName fro H3M maps
  1288. //boost::format fmt("%s_%d");
  1289. //fmt % nobj->typeName % nobj->id.getNum();
  1290. boost::format fmt("obj_%d");
  1291. fmt % nobj->id.getNum();
  1292. nobj->instanceName = fmt.str();
  1293. }
  1294. map->addNewObject(nobj);
  1295. }
  1296. std::sort(map->heroesOnMap.begin(), map->heroesOnMap.end(), [](const ConstTransitivePtr<CGHeroInstance> & a, const ConstTransitivePtr<CGHeroInstance> & b)
  1297. {
  1298. return a->subID < b->subID;
  1299. });
  1300. }
  1301. void CMapLoaderH3M::readCreatureSet(CCreatureSet * out, int number)
  1302. {
  1303. const bool version = (map->version > EMapFormat::ROE);
  1304. const int maxID = version ? 0xffff : 0xff;
  1305. for(int ir = 0; ir < number; ++ir)
  1306. {
  1307. CreatureID creID;
  1308. int count;
  1309. if (version)
  1310. {
  1311. creID = CreatureID(reader.readUInt16());
  1312. }
  1313. else
  1314. {
  1315. creID = CreatureID(reader.readUInt8());
  1316. }
  1317. count = reader.readUInt16();
  1318. // Empty slot
  1319. if(creID == maxID)
  1320. continue;
  1321. auto hlp = new CStackInstance();
  1322. hlp->count = count;
  1323. if(creID > maxID - 0xf)
  1324. {
  1325. //this will happen when random object has random army
  1326. hlp->idRand = maxID - creID - 1;
  1327. }
  1328. else
  1329. {
  1330. hlp->setType(creID);
  1331. }
  1332. out->putStack(SlotID(ir), hlp);
  1333. }
  1334. out->validTypes(true);
  1335. }
  1336. CGObjectInstance * CMapLoaderH3M::readHero(ObjectInstanceID idToBeGiven, const int3 & initialPos)
  1337. {
  1338. auto nhi = new CGHeroInstance();
  1339. if(map->version > EMapFormat::ROE)
  1340. {
  1341. unsigned int identifier = reader.readUInt32();
  1342. map->questIdentifierToId[identifier] = idToBeGiven;
  1343. }
  1344. PlayerColor owner = PlayerColor(reader.readUInt8());
  1345. nhi->subID = reader.readUInt8();
  1346. assert(!nhi->getArt(ArtifactPosition::MACH4));
  1347. //If hero of this type has been predefined, use that as a base.
  1348. //Instance data will overwrite the predefined values where appropriate.
  1349. for(auto & elem : map->predefinedHeroes)
  1350. {
  1351. if(elem->subID == nhi->subID)
  1352. {
  1353. logGlobal->debugStream() << "Hero " << nhi->subID << " will be taken from the predefined heroes list.";
  1354. delete nhi;
  1355. nhi = elem;
  1356. break;
  1357. }
  1358. }
  1359. nhi->setOwner(owner);
  1360. nhi->portrait = nhi->subID;
  1361. for(auto & elem : map->disposedHeroes)
  1362. {
  1363. if(elem.heroId == nhi->subID)
  1364. {
  1365. nhi->name = elem.name;
  1366. nhi->portrait = elem.portrait;
  1367. break;
  1368. }
  1369. }
  1370. bool hasName = reader.readBool();
  1371. if(hasName)
  1372. {
  1373. nhi->name = reader.readString();
  1374. }
  1375. if(map->version > EMapFormat::AB)
  1376. {
  1377. bool hasExp = reader.readBool();
  1378. if(hasExp)
  1379. {
  1380. nhi->exp = reader.readUInt32();
  1381. }
  1382. else
  1383. {
  1384. nhi->exp = 0xffffffff;
  1385. }
  1386. }
  1387. else
  1388. {
  1389. nhi->exp = reader.readUInt32();
  1390. //0 means "not set" in <=AB maps
  1391. if(!nhi->exp)
  1392. {
  1393. nhi->exp = 0xffffffff;
  1394. }
  1395. }
  1396. bool hasPortrait = reader.readBool();
  1397. if(hasPortrait)
  1398. {
  1399. nhi->portrait = reader.readUInt8();
  1400. }
  1401. bool hasSecSkills = reader.readBool();
  1402. if(hasSecSkills)
  1403. {
  1404. if(nhi->secSkills.size())
  1405. {
  1406. nhi->secSkills.clear();
  1407. //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;
  1408. }
  1409. int howMany = reader.readUInt32();
  1410. nhi->secSkills.resize(howMany);
  1411. for(int yy = 0; yy < howMany; ++yy)
  1412. {
  1413. nhi->secSkills[yy].first = SecondarySkill(reader.readUInt8());
  1414. nhi->secSkills[yy].second = reader.readUInt8();
  1415. }
  1416. }
  1417. bool hasGarison = reader.readBool();
  1418. if(hasGarison)
  1419. {
  1420. readCreatureSet(nhi, 7);
  1421. }
  1422. nhi->formation = reader.readUInt8();
  1423. loadArtifactsOfHero(nhi);
  1424. nhi->patrol.patrolRadius = reader.readUInt8();
  1425. if(nhi->patrol.patrolRadius == 0xff)
  1426. {
  1427. nhi->patrol.patrolling = false;
  1428. }
  1429. else
  1430. {
  1431. nhi->patrol.patrolling = true;
  1432. nhi->patrol.initialPos = CGHeroInstance::convertPosition(initialPos, false);
  1433. }
  1434. if(map->version > EMapFormat::ROE)
  1435. {
  1436. bool hasCustomBiography = reader.readBool();
  1437. if(hasCustomBiography)
  1438. {
  1439. nhi->biography = reader.readString();
  1440. }
  1441. nhi->sex = reader.readUInt8();
  1442. // Remove trash
  1443. if (nhi->sex != 0xFF)
  1444. {
  1445. nhi->sex &= 1;
  1446. }
  1447. }
  1448. else
  1449. {
  1450. nhi->sex = 0xFF;
  1451. }
  1452. // Spells
  1453. if(map->version > EMapFormat::AB)
  1454. {
  1455. bool hasCustomSpells = reader.readBool();
  1456. if(nhi->spells.size())
  1457. {
  1458. nhi->clear();
  1459. 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;
  1460. }
  1461. if(hasCustomSpells)
  1462. {
  1463. nhi->spells.insert(SpellID::PRESET); //placeholder "preset spells"
  1464. readSpells(nhi->spells);
  1465. }
  1466. }
  1467. else if(map->version == EMapFormat::AB)
  1468. {
  1469. //we can read one spell
  1470. ui8 buff = reader.readUInt8();
  1471. if(buff != 254)
  1472. {
  1473. nhi->spells.insert(SpellID::PRESET); //placeholder "preset spells"
  1474. if(buff < 254) //255 means no spells
  1475. {
  1476. nhi->spells.insert(SpellID(buff));
  1477. }
  1478. }
  1479. }
  1480. if(map->version > EMapFormat::AB)
  1481. {
  1482. bool hasCustomPrimSkills = reader.readBool();
  1483. if(hasCustomPrimSkills)
  1484. {
  1485. auto ps = nhi->getAllBonuses(Selector::type(Bonus::PRIMARY_SKILL)
  1486. .And(Selector::sourceType(Bonus::HERO_BASE_SKILL)), nullptr);
  1487. if(ps->size())
  1488. {
  1489. 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;
  1490. for(auto b : *ps)
  1491. nhi->removeBonus(b);
  1492. }
  1493. for(int xx = 0; xx < GameConstants::PRIMARY_SKILLS; ++xx)
  1494. {
  1495. nhi->pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(xx), reader.readUInt8());
  1496. }
  1497. }
  1498. }
  1499. reader.skip(16);
  1500. return nhi;
  1501. }
  1502. CGSeerHut * CMapLoaderH3M::readSeerHut()
  1503. {
  1504. auto hut = new CGSeerHut();
  1505. if(map->version > EMapFormat::ROE)
  1506. {
  1507. readQuest(hut);
  1508. }
  1509. else
  1510. {
  1511. //RoE
  1512. int artID = reader.readUInt8();
  1513. if (artID != 255)
  1514. {
  1515. //not none quest
  1516. hut->quest->m5arts.push_back (artID);
  1517. hut->quest->missionType = CQuest::MISSION_ART;
  1518. }
  1519. else
  1520. {
  1521. hut->quest->missionType = CQuest::MISSION_NONE;
  1522. }
  1523. hut->quest->lastDay = -1; //no timeout
  1524. hut->quest->isCustomFirst = hut->quest->isCustomNext = hut->quest->isCustomComplete = false;
  1525. }
  1526. if (hut->quest->missionType)
  1527. {
  1528. auto rewardType = static_cast<CGSeerHut::ERewardType>(reader.readUInt8());
  1529. hut->rewardType = rewardType;
  1530. switch(rewardType)
  1531. {
  1532. case CGSeerHut::EXPERIENCE:
  1533. {
  1534. hut->rVal = reader.readUInt32();
  1535. break;
  1536. }
  1537. case CGSeerHut::MANA_POINTS:
  1538. {
  1539. hut->rVal = reader.readUInt32();
  1540. break;
  1541. }
  1542. case CGSeerHut::MORALE_BONUS:
  1543. {
  1544. hut->rVal = reader.readUInt8();
  1545. break;
  1546. }
  1547. case CGSeerHut::LUCK_BONUS:
  1548. {
  1549. hut->rVal = reader.readUInt8();
  1550. break;
  1551. }
  1552. case CGSeerHut::RESOURCES:
  1553. {
  1554. hut->rID = reader.readUInt8();
  1555. // Only the first 3 bytes are used. Skip the 4th.
  1556. hut->rVal = reader.readUInt32() & 0x00ffffff;
  1557. break;
  1558. }
  1559. case CGSeerHut::PRIMARY_SKILL:
  1560. {
  1561. hut->rID = reader.readUInt8();
  1562. hut->rVal = reader.readUInt8();
  1563. break;
  1564. }
  1565. case CGSeerHut::SECONDARY_SKILL:
  1566. {
  1567. hut->rID = reader.readUInt8();
  1568. hut->rVal = reader.readUInt8();
  1569. break;
  1570. }
  1571. case CGSeerHut::ARTIFACT:
  1572. {
  1573. if (map->version == EMapFormat::ROE)
  1574. {
  1575. hut->rID = reader.readUInt8();
  1576. }
  1577. else
  1578. {
  1579. hut->rID = reader.readUInt16();
  1580. }
  1581. break;
  1582. }
  1583. case CGSeerHut::SPELL:
  1584. {
  1585. hut->rID = reader.readUInt8();
  1586. break;
  1587. }
  1588. case CGSeerHut::CREATURE:
  1589. {
  1590. if(map->version > EMapFormat::ROE)
  1591. {
  1592. hut->rID = reader.readUInt16();
  1593. hut->rVal = reader.readUInt16();
  1594. }
  1595. else
  1596. {
  1597. hut->rID = reader.readUInt8();
  1598. hut->rVal = reader.readUInt16();
  1599. }
  1600. break;
  1601. }
  1602. }
  1603. reader.skip(2);
  1604. }
  1605. else
  1606. {
  1607. // missionType==255
  1608. reader.skip(3);
  1609. }
  1610. return hut;
  1611. }
  1612. void CMapLoaderH3M::readQuest(IQuestObject * guard)
  1613. {
  1614. guard->quest->missionType = static_cast<CQuest::Emission>(reader.readUInt8());
  1615. switch(guard->quest->missionType)
  1616. {
  1617. case CQuest::MISSION_NONE:
  1618. return;
  1619. case CQuest::MISSION_PRIMARY_STAT:
  1620. {
  1621. guard->quest->m2stats.resize(4);
  1622. for(int x = 0; x < 4; ++x)
  1623. {
  1624. guard->quest->m2stats[x] = reader.readUInt8();
  1625. }
  1626. }
  1627. break;
  1628. case CQuest::MISSION_LEVEL:
  1629. case CQuest::MISSION_KILL_HERO:
  1630. case CQuest::MISSION_KILL_CREATURE:
  1631. {
  1632. guard->quest->m13489val = reader.readUInt32();
  1633. break;
  1634. }
  1635. case CQuest::MISSION_ART:
  1636. {
  1637. int artNumber = reader.readUInt8();
  1638. for(int yy = 0; yy < artNumber; ++yy)
  1639. {
  1640. int artid = reader.readUInt16();
  1641. guard->quest->m5arts.push_back(artid);
  1642. map->allowedArtifact[artid] = false; //these are unavailable for random generation
  1643. }
  1644. break;
  1645. }
  1646. case CQuest::MISSION_ARMY:
  1647. {
  1648. int typeNumber = reader.readUInt8();
  1649. guard->quest->m6creatures.resize(typeNumber);
  1650. for(int hh = 0; hh < typeNumber; ++hh)
  1651. {
  1652. guard->quest->m6creatures[hh].type = VLC->creh->creatures[reader.readUInt16()];
  1653. guard->quest->m6creatures[hh].count = reader.readUInt16();
  1654. }
  1655. break;
  1656. }
  1657. case CQuest::MISSION_RESOURCES:
  1658. {
  1659. guard->quest->m7resources.resize(7);
  1660. for(int x = 0; x < 7; ++x)
  1661. {
  1662. guard->quest->m7resources[x] = reader.readUInt32();
  1663. }
  1664. break;
  1665. }
  1666. case CQuest::MISSION_HERO:
  1667. case CQuest::MISSION_PLAYER:
  1668. {
  1669. guard->quest->m13489val = reader.readUInt8();
  1670. break;
  1671. }
  1672. }
  1673. int limit = reader.readUInt32();
  1674. if(limit == (static_cast<int>(0xffffffff)))
  1675. {
  1676. guard->quest->lastDay = -1;
  1677. }
  1678. else
  1679. {
  1680. guard->quest->lastDay = limit;
  1681. }
  1682. guard->quest->firstVisitText = reader.readString();
  1683. guard->quest->nextVisitText = reader.readString();
  1684. guard->quest->completedText = reader.readString();
  1685. guard->quest->isCustomFirst = guard->quest->firstVisitText.size() > 0;
  1686. guard->quest->isCustomNext = guard->quest->nextVisitText.size() > 0;
  1687. guard->quest->isCustomComplete = guard->quest->completedText.size() > 0;
  1688. }
  1689. CGTownInstance * CMapLoaderH3M::readTown(int castleID)
  1690. {
  1691. auto nt = new CGTownInstance();
  1692. if(map->version > EMapFormat::ROE)
  1693. {
  1694. nt->identifier = reader.readUInt32();
  1695. }
  1696. nt->tempOwner = PlayerColor(reader.readUInt8());
  1697. bool hasName = reader.readBool();
  1698. if(hasName)
  1699. {
  1700. nt->name = reader.readString();
  1701. }
  1702. bool hasGarrison = reader.readBool();
  1703. if(hasGarrison)
  1704. {
  1705. readCreatureSet(nt, 7);
  1706. }
  1707. nt->formation = reader.readUInt8();
  1708. bool hasCustomBuildings = reader.readBool();
  1709. if(hasCustomBuildings)
  1710. {
  1711. readBitmask(nt->builtBuildings,6,48,false);
  1712. readBitmask(nt->forbiddenBuildings,6,48,false);
  1713. nt->builtBuildings = convertBuildings(nt->builtBuildings, castleID);
  1714. nt->forbiddenBuildings = convertBuildings(nt->forbiddenBuildings, castleID);
  1715. }
  1716. // Standard buildings
  1717. else
  1718. {
  1719. bool hasFort = reader.readBool();
  1720. if(hasFort)
  1721. {
  1722. nt->builtBuildings.insert(BuildingID::FORT);
  1723. }
  1724. //means that set of standard building should be included
  1725. nt->builtBuildings.insert(BuildingID::DEFAULT);
  1726. }
  1727. if(map->version > EMapFormat::ROE)
  1728. {
  1729. for(int i = 0; i < 9; ++i)
  1730. {
  1731. ui8 c = reader.readUInt8();
  1732. for(int yy = 0; yy < 8; ++yy)
  1733. {
  1734. if(i * 8 + yy < GameConstants::SPELLS_QUANTITY)
  1735. {
  1736. if(c == (c | static_cast<ui8>(std::pow(2., yy)))) //add obligatory spell even if it's banned on a map (?)
  1737. {
  1738. nt->obligatorySpells.push_back(SpellID(i * 8 + yy));
  1739. }
  1740. }
  1741. }
  1742. }
  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. int spellid = i * 8 + yy;
  1750. if(spellid < GameConstants::SPELLS_QUANTITY)
  1751. {
  1752. if(c != (c | static_cast<ui8>(std::pow(2., yy))) && map->allowedSpell[spellid]) //add random spell only if it's allowed on entire map
  1753. {
  1754. nt->possibleSpells.push_back(SpellID(spellid));
  1755. }
  1756. }
  1757. }
  1758. }
  1759. //add all spells from mods
  1760. //TODO: allow customize new spells in towns
  1761. for (int i = SpellID::AFTER_LAST; i < VLC->spellh->objects.size(); ++i)
  1762. {
  1763. nt->possibleSpells.push_back(SpellID(i));
  1764. }
  1765. // Read castle events
  1766. int numberOfEvent = reader.readUInt32();
  1767. for(int gh = 0; gh < numberOfEvent; ++gh)
  1768. {
  1769. CCastleEvent nce;
  1770. nce.town = nt;
  1771. nce.name = reader.readString();
  1772. nce.message = reader.readString();
  1773. readResourses(nce.resources);
  1774. nce.players = reader.readUInt8();
  1775. if(map->version > EMapFormat::AB)
  1776. {
  1777. nce.humanAffected = reader.readUInt8();
  1778. }
  1779. else
  1780. {
  1781. nce.humanAffected = true;
  1782. }
  1783. nce.computerAffected = reader.readUInt8();
  1784. nce.firstOccurence = reader.readUInt16();
  1785. nce.nextOccurence = reader.readUInt8();
  1786. reader.skip(17);
  1787. // New buildings
  1788. readBitmask(nce.buildings,6,48,false);
  1789. nce.buildings = convertBuildings(nce.buildings, castleID, false);
  1790. nce.creatures.resize(7);
  1791. for(int vv = 0; vv < 7; ++vv)
  1792. {
  1793. nce.creatures[vv] = reader.readUInt16();
  1794. }
  1795. reader.skip(4);
  1796. nt->events.push_back(nce);
  1797. }
  1798. if(map->version > EMapFormat::AB)
  1799. {
  1800. nt->alignment = reader.readUInt8();
  1801. }
  1802. reader.skip(3);
  1803. return nt;
  1804. }
  1805. std::set<BuildingID> CMapLoaderH3M::convertBuildings(const std::set<BuildingID> h3m, int castleID, bool addAuxiliary /*= true*/)
  1806. {
  1807. std::map<int, BuildingID> mapa;
  1808. std::set<BuildingID> ret;
  1809. // Note: this file is parsed many times.
  1810. const JsonNode config(ResourceID("config/buildings5.json"));
  1811. for(const JsonNode & entry : config["table"].Vector())
  1812. {
  1813. int town = entry["town"].Float();
  1814. if (town == castleID || town == -1)
  1815. {
  1816. mapa[entry["h3"].Float()] = BuildingID((si32)entry["vcmi"].Float());
  1817. }
  1818. }
  1819. for(auto & elem : h3m)
  1820. {
  1821. if(mapa[elem] >= 0)
  1822. {
  1823. ret.insert(mapa[elem]);
  1824. }
  1825. // horde buildings
  1826. else if(mapa[elem] >= (-GameConstants::CREATURES_PER_TOWN))
  1827. {
  1828. int level = (mapa[elem]);
  1829. //(-30)..(-36) - horde buildings (for game loading only), don't see other way to handle hordes in random towns
  1830. ret.insert(BuildingID(level - 30));
  1831. }
  1832. else
  1833. {
  1834. logGlobal->warnStream() << "Conversion warning: unknown building " << elem << " in castle "
  1835. << castleID;
  1836. }
  1837. }
  1838. if(addAuxiliary)
  1839. {
  1840. //village hall is always present
  1841. ret.insert(BuildingID::VILLAGE_HALL);
  1842. }
  1843. if(ret.find(BuildingID::CITY_HALL) != ret.end())
  1844. {
  1845. ret.insert(BuildingID::EXTRA_CITY_HALL);
  1846. }
  1847. if(ret.find(BuildingID::TOWN_HALL) != ret.end())
  1848. {
  1849. ret.insert(BuildingID::EXTRA_TOWN_HALL);
  1850. }
  1851. if(ret.find(BuildingID::CAPITOL) != ret.end())
  1852. {
  1853. ret.insert(BuildingID::EXTRA_CAPITOL);
  1854. }
  1855. return ret;
  1856. }
  1857. void CMapLoaderH3M::readEvents()
  1858. {
  1859. int numberOfEvents = reader.readUInt32();
  1860. for(int yyoo = 0; yyoo < numberOfEvents; ++yyoo)
  1861. {
  1862. CMapEvent ne;
  1863. ne.name = reader.readString();
  1864. ne.message = reader.readString();
  1865. readResourses(ne.resources);
  1866. ne.players = reader.readUInt8();
  1867. if(map->version > EMapFormat::AB)
  1868. {
  1869. ne.humanAffected = reader.readUInt8();
  1870. }
  1871. else
  1872. {
  1873. ne.humanAffected = true;
  1874. }
  1875. ne.computerAffected = reader.readUInt8();
  1876. ne.firstOccurence = reader.readUInt16();
  1877. ne.nextOccurence = reader.readUInt8();
  1878. reader.skip(17);
  1879. map->events.push_back(ne);
  1880. }
  1881. }
  1882. void CMapLoaderH3M::readMessageAndGuards(std::string& message, CCreatureSet* guards)
  1883. {
  1884. bool hasMessage = reader.readBool();
  1885. if(hasMessage)
  1886. {
  1887. message = reader.readString();
  1888. bool hasGuards = reader.readBool();
  1889. if(hasGuards)
  1890. {
  1891. readCreatureSet(guards, 7);
  1892. }
  1893. reader.skip(4);
  1894. }
  1895. }
  1896. void CMapLoaderH3M::readSpells(std::set<SpellID>& dest)
  1897. {
  1898. readBitmask(dest,9,GameConstants::SPELLS_QUANTITY,false);
  1899. }
  1900. void CMapLoaderH3M::readResourses(TResources& resources)
  1901. {
  1902. resources.resize(GameConstants::RESOURCE_QUANTITY); //needed?
  1903. for(int x = 0; x < 7; ++x)
  1904. {
  1905. resources[x] = reader.readUInt32();
  1906. }
  1907. }
  1908. template <class Indentifier>
  1909. void CMapLoaderH3M::readBitmask(std::set<Indentifier>& dest, const int byteCount, const int limit, bool negate)
  1910. {
  1911. std::vector<bool> temp;
  1912. temp.resize(limit,true);
  1913. readBitmask(temp, byteCount, limit, negate);
  1914. for(int i = 0; i< std::min(temp.size(), static_cast<size_t>(limit)); i++)
  1915. {
  1916. if(temp[i])
  1917. {
  1918. dest.insert(static_cast<Indentifier>(i));
  1919. }
  1920. }
  1921. }
  1922. void CMapLoaderH3M::readBitmask(std::vector<bool>& dest, const int byteCount, const int limit, bool negate)
  1923. {
  1924. for(int byte = 0; byte < byteCount; ++byte)
  1925. {
  1926. const ui8 mask = reader.readUInt8();
  1927. for(int bit = 0; bit < 8; ++bit)
  1928. {
  1929. if(byte * 8 + bit < limit)
  1930. {
  1931. const bool flag = mask & (1 << bit);
  1932. if((negate && flag) || (!negate && !flag))
  1933. dest[byte * 8 + bit] = false;
  1934. }
  1935. }
  1936. }
  1937. }
  1938. ui8 CMapLoaderH3M::reverse(ui8 arg)
  1939. {
  1940. ui8 ret = 0;
  1941. for(int i = 0; i < 8; ++i)
  1942. {
  1943. if((arg & (1 << i)) >> i)
  1944. {
  1945. ret |= (128 >> i);
  1946. }
  1947. }
  1948. return ret;
  1949. }
  1950. void CMapLoaderH3M::afterRead()
  1951. {
  1952. //convert main town positions for all players to actual object position, in H3M it is position of active tile
  1953. for(auto & p : map->players)
  1954. {
  1955. int3 posOfMainTown = p.posOfMainTown;
  1956. if(posOfMainTown.valid() && map->isInTheMap(posOfMainTown))
  1957. {
  1958. const TerrainTile & t = map->getTile(posOfMainTown);
  1959. const CGObjectInstance * mainTown = nullptr;
  1960. for(auto obj : t.visitableObjects)
  1961. {
  1962. if(obj->ID = Obj::TOWN)
  1963. {
  1964. mainTown = obj;
  1965. break;
  1966. }
  1967. }
  1968. if(mainTown == nullptr)
  1969. continue;
  1970. p.posOfMainTown = posOfMainTown + mainTown->getVisitableOffset();
  1971. }
  1972. }
  1973. }