2
0

MapFormatH3M.cpp 59 KB

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