MapFormatH3M.cpp 59 KB

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