MapFormatH3M.cpp 65 KB

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