2
0

MapFormatH3M.cpp 58 KB

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