MapFormatH3M.cpp 55 KB

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