MapFormatH3M.cpp 57 KB

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