123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217 |
- /*
- * MapFormatH3M.cpp, part of VCMI engine
- *
- * Authors: listed in file AUTHORS in main folder
- *
- * License: GNU General Public License v2.0 or later
- * Full text of license available in license.txt file, in main folder
- *
- */
- #include "StdInc.h"
- #include "MapFormatH3M.h"
- #include "CMap.h"
- #include "MapReaderH3M.h"
- #include "../CStopWatch.h"
- #include "../filesystem/Filesystem.h"
- #include "../filesystem/CBinaryReader.h"
- #include "../spells/CSpellHandler.h"
- #include "../CSkillHandler.h"
- #include "../CCreatureHandler.h"
- #include "../CGeneralTextHandler.h"
- #include "../CHeroHandler.h"
- #include "../mapObjects/CObjectClassesHandler.h"
- #include "../mapObjects/MapObjects.h"
- #include "../VCMI_Lib.h"
- #include "../TextOperations.h"
- #include "../TerrainHandler.h"
- #include "../RoadHandler.h"
- #include "../RiverHandler.h"
- #include <boost/crc.hpp>
- VCMI_LIB_NAMESPACE_BEGIN
- static std::string convertMapName(std::string input)
- {
- boost::algorithm::to_lower(input);
- boost::algorithm::trim(input);
- size_t slashPos = input.find_last_of('/');
- if (slashPos != std::string::npos)
- return input.substr(slashPos + 1);
- return input;
- }
- CMapLoaderH3M::CMapLoaderH3M(const std::string & mapName, const std::string & modName, const std::string & encodingName, CInputStream * stream)
- : map(nullptr)
- , reader(new MapReaderH3M(stream))
- , inputStream(stream)
- , mapName(convertMapName(mapName))
- , modName(modName)
- , fileEncoding(encodingName)
- {
- }
- //must be instantiated in .cpp file for access to complete types of all member fields
- CMapLoaderH3M::~CMapLoaderH3M() = default;
- std::unique_ptr<CMap> CMapLoaderH3M::loadMap()
- {
- // Init map object by parsing the input buffer
- map = new CMap();
- mapHeader = std::unique_ptr<CMapHeader>(dynamic_cast<CMapHeader *>(map));
- init();
- return std::unique_ptr<CMap>(dynamic_cast<CMap *>(mapHeader.release()));
- }
- std::unique_ptr<CMapHeader> CMapLoaderH3M::loadMapHeader()
- {
- // Read header
- mapHeader = std::make_unique<CMapHeader>();
- readHeader();
- return std::move(mapHeader);
- }
- void CMapLoaderH3M::init()
- {
- //TODO: get rid of double input process
- si64 temp_size = inputStream->getSize();
- inputStream->seek(0);
- auto * temp_buffer = new ui8[temp_size];
- inputStream->read(temp_buffer,temp_size);
- // Compute checksum
- boost::crc_32_type result;
- result.process_bytes(temp_buffer, temp_size);
- map->checksum = result.checksum();
- delete [] temp_buffer;
- inputStream->seek(0);
- CStopWatch sw;
- struct MapLoadingTime
- {
- std::string name;
- si64 time;
- MapLoadingTime(std::string name, si64 time): name(std::move(name)), time(time) {}
- };
- std::vector<MapLoadingTime> times;
- readHeader();
- times.emplace_back("header", sw.getDiff());
- map->allHeroes.resize(map->allowedHeroes.size());
- readDisposedHeroes();
- times.emplace_back("disposed heroes", sw.getDiff());
- readMapOptions();
- readAllowedArtifacts();
- times.emplace_back("allowed artifacts", sw.getDiff());
- readAllowedSpellsAbilities();
- times.emplace_back("allowed spells and abilities", sw.getDiff());
- readRumors();
- times.emplace_back("rumors", sw.getDiff());
- readPredefinedHeroes();
- times.emplace_back("predefined heroes", sw.getDiff());
- readTerrain();
- times.emplace_back("terrain", sw.getDiff());
- readDefInfo();
- times.emplace_back("def info", sw.getDiff());
- readObjects();
- times.emplace_back("objects", sw.getDiff());
- readEvents();
- times.emplace_back("events", sw.getDiff());
- times.emplace_back("blocked/visitable tiles", sw.getDiff());
- map->calculateGuardingGreaturePositions();
- afterRead();
- }
- void CMapLoaderH3M::readHeader()
- {
- // Map version
- mapHeader->version = static_cast<EMapFormat>(reader->readUInt32());
- if(mapHeader->version == EMapFormat::HOTA1 || mapHeader->version == EMapFormat::HOTA2 || mapHeader->version == EMapFormat::HOTA3)
- {
- uint32_t hotaVersion = reader->readUInt32();
- features = MapFormatFeaturesH3M::find(mapHeader->version, hotaVersion);
- reader->setFormatLevel(mapHeader->version, hotaVersion);
- reader->skipZero(2);
- if (hotaVersion > 1)
- {
- uint8_t unknown = reader->readUInt32();
- assert(unknown == 12);
- MAYBE_UNUSED(unknown);
- }
- }
- else
- {
- features = MapFormatFeaturesH3M::find(mapHeader->version, 0);
- reader->setFormatLevel(mapHeader->version, 0);
- }
- // Read map name, description, dimensions,...
- mapHeader->areAnyPlayers = reader->readBool();
- mapHeader->height = mapHeader->width = reader->readInt32();
- mapHeader->twoLevel = reader->readBool();
- mapHeader->name = readLocalizedString("header.name");
- mapHeader->description = readLocalizedString("header.description");
- mapHeader->difficulty = reader->readInt8();
- if(features.levelAB)
- mapHeader->levelLimit = reader->readUInt8();
- else
- mapHeader->levelLimit = 0;
- readPlayerInfo();
- readVictoryLossConditions();
- readTeamInfo();
- readAllowedHeroes();
- }
- void CMapLoaderH3M::readPlayerInfo()
- {
- for(int i = 0; i < mapHeader->players.size(); ++i)
- {
- auto & playerInfo = mapHeader->players[i];
- playerInfo.canHumanPlay = reader->readBool();
- playerInfo.canComputerPlay = reader->readBool();
- // If nobody can play with this player - skip loading of these properties
- if((!(playerInfo.canHumanPlay || playerInfo.canComputerPlay)))
- {
- if (features.levelROE)
- reader->skipUnused(6);
- if (features.levelAB)
- reader->skipUnused(6);
- if (features.levelSOD)
- reader->skipUnused(1);
- continue;
- }
- playerInfo.aiTactic = static_cast<EAiTactic::EAiTactic>(reader->readUInt8());
- if(features.levelSOD)
- reader->skipUnused(1); //TODO: check meaning?
- std::set<TFaction> allowedFactions;
- reader->readBitmask(allowedFactions, features.factionsBytes, features.factionsCount, false);
- const bool isFactionRandom = playerInfo.isFactionRandom = reader->readBool();
- const bool allFactionsAllowed = isFactionRandom && allowedFactions.size() == features.factionsCount;
- if(!allFactionsAllowed)
- playerInfo.allowedFactions = allowedFactions;
- playerInfo.hasMainTown = reader->readBool();
- if(playerInfo.hasMainTown)
- {
- if(features.levelAB)
- {
- playerInfo.generateHeroAtMainTown = reader->readBool();
- reader->skipUnused(1); //TODO: check meaning?
- }
- else
- {
- playerInfo.generateHeroAtMainTown = true;
- }
- playerInfo.posOfMainTown = reader->readInt3();
- }
- playerInfo.hasRandomHero = reader->readBool();
- playerInfo.mainCustomHeroId = reader->readHero().getNum();
- if(playerInfo.mainCustomHeroId != -1)
- {
- playerInfo.mainCustomHeroPortrait = reader->readHero().getNum();
- playerInfo.mainCustomHeroName = readLocalizedString(TextIdentifier("header", "player", i, "mainHeroName"));
- }
- if(features.levelAB)
- {
- reader->skipUnused(1); //TODO: check meaning?
- uint32_t heroCount = reader->readUInt32();
- for(int pp = 0; pp < heroCount; ++pp)
- {
- SHeroName vv;
- vv.heroId = reader->readUInt8();
- vv.heroName = readLocalizedString( TextIdentifier("header", "heroNames", vv.heroId));
- playerInfo.heroesNames.push_back(vv);
- }
- }
- }
- }
- enum class EVictoryConditionType : uint8_t
- {
- ARTIFACT = 0,
- GATHERTROOP = 1,
- GATHERRESOURCE = 2,
- BUILDCITY = 3,
- BUILDGRAIL = 4,
- BEATHERO = 5,
- CAPTURECITY = 6,
- BEATMONSTER = 7,
- TAKEDWELLINGS = 8,
- TAKEMINES = 9,
- TRANSPORTITEM = 10,
- HOTA_ELIMINATE_ALL_MONSTERS = 11,
- HOTA_SURVIVE_FOR_DAYS = 12,
- WINSTANDARD = 255
- };
- enum class ELossConditionType : uint8_t
- {
- LOSSCASTLE,
- LOSSHERO,
- TIMEEXPIRES,
- LOSSSTANDARD = 255
- };
- void CMapLoaderH3M::readVictoryLossConditions()
- {
- mapHeader->triggeredEvents.clear();
- auto vicCondition = static_cast<EVictoryConditionType>(reader->readUInt8());
- EventCondition victoryCondition(EventCondition::STANDARD_WIN);
- EventCondition defeatCondition(EventCondition::DAYS_WITHOUT_TOWN);
- defeatCondition.value = 7;
- TriggeredEvent standardVictory;
- standardVictory.effect.type = EventEffect::VICTORY;
- standardVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[5];
- standardVictory.identifier = "standardVictory";
- standardVictory.description.clear(); // TODO: display in quest window
- standardVictory.onFulfill = VLC->generaltexth->allTexts[659];
- standardVictory.trigger = EventExpression(victoryCondition);
- TriggeredEvent standardDefeat;
- standardDefeat.effect.type = EventEffect::DEFEAT;
- standardDefeat.effect.toOtherMessage = VLC->generaltexth->allTexts[8];
- standardDefeat.identifier = "standardDefeat";
- standardDefeat.description.clear(); // TODO: display in quest window
- standardDefeat.onFulfill = VLC->generaltexth->allTexts[7];
- standardDefeat.trigger = EventExpression(defeatCondition);
- // Specific victory conditions
- if(vicCondition == EVictoryConditionType::WINSTANDARD)
- {
- // create normal condition
- mapHeader->triggeredEvents.push_back(standardVictory);
- mapHeader->victoryIconIndex = 11;
- mapHeader->victoryMessage = VLC->generaltexth->victoryConditions[0];
- }
- else
- {
- TriggeredEvent specialVictory;
- specialVictory.effect.type = EventEffect::VICTORY;
- specialVictory.identifier = "specialVictory";
- specialVictory.description.clear(); // TODO: display in quest window
- mapHeader->victoryIconIndex = static_cast<ui16>(vicCondition);
- mapHeader->victoryMessage = VLC->generaltexth->victoryConditions[static_cast<size_t>(vicCondition) + 1];
- bool allowNormalVictory = reader->readBool();
- bool appliesToAI = reader->readBool();
- if (allowNormalVictory)
- {
- size_t playersOnMap = boost::range::count_if(mapHeader->players,[](const PlayerInfo & info) { return info.canAnyonePlay();});
- if (playersOnMap == 1)
- {
- logGlobal->warn("Map %s has only one player but allows normal victory?", mapHeader->name);
- allowNormalVictory = false; // makes sense? Not much. Works as H3? Yes!
- }
- }
- switch(vicCondition)
- {
- case EVictoryConditionType::ARTIFACT:
- {
- EventCondition cond(EventCondition::HAVE_ARTIFACT);
- cond.objectType = reader->readArtifact();
- specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[281];
- specialVictory.onFulfill = VLC->generaltexth->allTexts[280];
- specialVictory.trigger = EventExpression(cond);
- break;
- }
- case EVictoryConditionType::GATHERTROOP:
- {
- EventCondition cond(EventCondition::HAVE_CREATURES);
- cond.objectType = reader->readCreature();
- cond.value = reader->readInt32();
- specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[277];
- specialVictory.onFulfill = VLC->generaltexth->allTexts[276];
- specialVictory.trigger = EventExpression(cond);
- break;
- }
- case EVictoryConditionType::GATHERRESOURCE:
- {
- EventCondition cond(EventCondition::HAVE_RESOURCES);
- cond.objectType = reader->readUInt8();
- cond.value = reader->readInt32();
- specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[279];
- specialVictory.onFulfill = VLC->generaltexth->allTexts[278];
- specialVictory.trigger = EventExpression(cond);
- break;
- }
- case EVictoryConditionType::BUILDCITY:
- {
- EventExpression::OperatorAll oper;
- EventCondition cond(EventCondition::HAVE_BUILDING);
- cond.position = reader->readInt3();
- cond.objectType = BuildingID::TOWN_HALL + reader->readUInt8();
- oper.expressions.emplace_back(cond);
- cond.objectType = BuildingID::FORT + reader->readUInt8();
- oper.expressions.emplace_back(cond);
- specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[283];
- specialVictory.onFulfill = VLC->generaltexth->allTexts[282];
- specialVictory.trigger = EventExpression(oper);
- break;
- }
- case EVictoryConditionType::BUILDGRAIL:
- {
- EventCondition cond(EventCondition::HAVE_BUILDING);
- cond.objectType = BuildingID::GRAIL;
- cond.position = reader->readInt3();
- if(cond.position.z > 2)
- cond.position = int3(-1,-1,-1);
- specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[285];
- specialVictory.onFulfill = VLC->generaltexth->allTexts[284];
- specialVictory.trigger = EventExpression(cond);
- break;
- }
- case EVictoryConditionType::BEATHERO:
- {
- EventCondition cond(EventCondition::DESTROY);
- cond.objectType = Obj::HERO;
- cond.position = reader->readInt3();
- specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[253];
- specialVictory.onFulfill = VLC->generaltexth->allTexts[252];
- specialVictory.trigger = EventExpression(cond);
- break;
- }
- case EVictoryConditionType::CAPTURECITY:
- {
- EventCondition cond(EventCondition::CONTROL);
- cond.objectType = Obj::TOWN;
- cond.position = reader->readInt3();
- specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[250];
- specialVictory.onFulfill = VLC->generaltexth->allTexts[249];
- specialVictory.trigger = EventExpression(cond);
- break;
- }
- case EVictoryConditionType::BEATMONSTER:
- {
- EventCondition cond(EventCondition::DESTROY);
- cond.objectType = Obj::MONSTER;
- cond.position = reader->readInt3();
- specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[287];
- specialVictory.onFulfill = VLC->generaltexth->allTexts[286];
- specialVictory.trigger = EventExpression(cond);
- break;
- }
- case EVictoryConditionType::TAKEDWELLINGS:
- {
- EventExpression::OperatorAll oper;
- oper.expressions.emplace_back(EventCondition(EventCondition::CONTROL, 0, Obj::CREATURE_GENERATOR1));
- oper.expressions.emplace_back(EventCondition(EventCondition::CONTROL, 0, Obj::CREATURE_GENERATOR4));
- specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[289];
- specialVictory.onFulfill = VLC->generaltexth->allTexts[288];
- specialVictory.trigger = EventExpression(oper);
- break;
- }
- case EVictoryConditionType::TAKEMINES:
- {
- EventCondition cond(EventCondition::CONTROL);
- cond.objectType = Obj::MINE;
- specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[291];
- specialVictory.onFulfill = VLC->generaltexth->allTexts[290];
- specialVictory.trigger = EventExpression(cond);
- break;
- }
- case EVictoryConditionType::TRANSPORTITEM:
- {
- EventCondition cond(EventCondition::TRANSPORT);
- cond.objectType = reader->readUInt8();
- cond.position = reader->readInt3();
- specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[293];
- specialVictory.onFulfill = VLC->generaltexth->allTexts[292];
- specialVictory.trigger = EventExpression(cond);
- break;
- }
- case EVictoryConditionType::HOTA_ELIMINATE_ALL_MONSTERS:
- //TODO: HOTA
- logGlobal->warn("Map '%s': Victory condition 'Eliminate all monsters' is not implemented!", mapName);
- break;
- case EVictoryConditionType::HOTA_SURVIVE_FOR_DAYS:
- {
- //TODO: HOTA
- uint32_t daysToSurvive = reader->readUInt32(); // Number of days
- logGlobal->error("Map '%s': Victory condition 'Survive for %d days' is not implemented!", mapName, daysToSurvive);
- break;
- }
- default:
- assert(0);
- }
- // if condition is human-only turn it into following construction: AllOf(human, condition)
- if (!appliesToAI)
- {
- EventExpression::OperatorAll oper;
- EventCondition notAI(EventCondition::IS_HUMAN);
- notAI.value = 1;
- oper.expressions.emplace_back(notAI);
- oper.expressions.push_back(specialVictory.trigger.get());
- specialVictory.trigger = EventExpression(oper);
- }
- // if normal victory allowed - add one more quest
- if (allowNormalVictory)
- {
- mapHeader->victoryMessage += " / ";
- mapHeader->victoryMessage += VLC->generaltexth->victoryConditions[0];
- mapHeader->triggeredEvents.push_back(standardVictory);
- }
- mapHeader->triggeredEvents.push_back(specialVictory);
- }
- // Read loss conditions
- auto lossCond = static_cast<ELossConditionType>(reader->readUInt8());
- if (lossCond == ELossConditionType::LOSSSTANDARD)
- {
- mapHeader->defeatIconIndex = 3;
- mapHeader->defeatMessage = VLC->generaltexth->lossCondtions[0];
- }
- else
- {
- TriggeredEvent specialDefeat;
- specialDefeat.effect.type = EventEffect::DEFEAT;
- specialDefeat.effect.toOtherMessage = VLC->generaltexth->allTexts[5];
- specialDefeat.identifier = "specialDefeat";
- specialDefeat.description.clear(); // TODO: display in quest window
- mapHeader->defeatIconIndex = static_cast<ui16>(lossCond);
- mapHeader->defeatMessage = VLC->generaltexth->lossCondtions[static_cast<size_t>(lossCond) + 1];
- switch(lossCond)
- {
- case ELossConditionType::LOSSCASTLE:
- {
- EventExpression::OperatorNone noneOf;
- EventCondition cond(EventCondition::CONTROL);
- cond.objectType = Obj::TOWN;
- cond.position = reader->readInt3();
- noneOf.expressions.emplace_back(cond);
- specialDefeat.onFulfill = VLC->generaltexth->allTexts[251];
- specialDefeat.trigger = EventExpression(noneOf);
- break;
- }
- case ELossConditionType::LOSSHERO:
- {
- EventExpression::OperatorNone noneOf;
- EventCondition cond(EventCondition::CONTROL);
- cond.objectType = Obj::HERO;
- cond.position = reader->readInt3();
- noneOf.expressions.emplace_back(cond);
- specialDefeat.onFulfill = VLC->generaltexth->allTexts[253];
- specialDefeat.trigger = EventExpression(noneOf);
- break;
- }
- case ELossConditionType::TIMEEXPIRES:
- {
- EventCondition cond(EventCondition::DAYS_PASSED);
- cond.value = reader->readUInt16();
- specialDefeat.onFulfill = VLC->generaltexth->allTexts[254];
- specialDefeat.trigger = EventExpression(cond);
- break;
- }
- }
- // turn simple loss condition into complete one that can be evaluated later:
- // - any of :
- // - days without town: 7
- // - all of:
- // - is human
- // - (expression)
- EventExpression::OperatorAll allOf;
- EventCondition isHuman(EventCondition::IS_HUMAN);
- isHuman.value = 1;
- allOf.expressions.emplace_back(isHuman);
- allOf.expressions.push_back(specialDefeat.trigger.get());
- specialDefeat.trigger = EventExpression(allOf);
- mapHeader->triggeredEvents.push_back(specialDefeat);
- }
- mapHeader->triggeredEvents.push_back(standardDefeat);
- }
- void CMapLoaderH3M::readTeamInfo()
- {
- mapHeader->howManyTeams = reader->readUInt8();
- if(mapHeader->howManyTeams > 0)
- {
- // Teams
- for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; ++i)
- {
- mapHeader->players[i].team = TeamID(reader->readUInt8());
- }
- }
- else
- {
- // No alliances
- for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
- {
- if(mapHeader->players[i].canComputerPlay || mapHeader->players[i].canHumanPlay)
- {
- mapHeader->players[i].team = TeamID(mapHeader->howManyTeams++);
- }
- }
- }
- }
- void CMapLoaderH3M::readAllowedHeroes()
- {
- mapHeader->allowedHeroes = VLC->heroh->getDefaultAllowed();
- uint32_t heroesCount = features.heroesCount;
- uint32_t heroesBytes = features.heroesBytes;
- if (features.levelHOTA)
- {
- heroesCount = reader->readUInt32();
- heroesBytes = (heroesCount + 7) / 8;
- }
- assert(heroesCount <= features.heroesCount);
- reader->readBitmask(mapHeader->allowedHeroes, heroesBytes, heroesCount, false);
- //TODO: unknown value. Check meaning? Only present in campaign maps.
- if(features.levelAB)
- {
- uint32_t placeholdersQty = reader->readUInt32();
- reader->skipUnused(placeholdersQty * 1);
- }
- }
- void CMapLoaderH3M::readDisposedHeroes()
- {
- // Reading disposed heroes (20 bytes)
- if(features.levelSOD)
- {
- ui8 disp = reader->readUInt8();
- map->disposedHeroes.resize(disp);
- for(int g = 0; g < disp; ++g)
- {
- map->disposedHeroes[g].heroId = reader->readHero().getNum();
- map->disposedHeroes[g].portrait = reader->readHero().getNum();
- map->disposedHeroes[g].name = readLocalizedString(TextIdentifier("header", "heroes", map->disposedHeroes[g].heroId));
- map->disposedHeroes[g].players = reader->readUInt8();
- }
- }
- }
- void CMapLoaderH3M::readMapOptions()
- {
- //omitting NULLS
- reader->skipZero(31);
- if (features.levelHOTA)
- {
- //TODO: HotA
- bool allowSpecialMonths = reader->readBool();
- if (!allowSpecialMonths)
- logGlobal->warn("Map '%s': Option 'allow special months' is not implemented!", mapName);
- reader->skipZero(3);
- uint8_t unknownConstant = reader->readUInt8();
- assert(unknownConstant == 16);
- MAYBE_UNUSED(unknownConstant);
- reader->skipZero(5);
- }
- if (features.levelHOTA3)
- {
- //TODO: HotA
- int32_t roundLimit = reader->readInt32();
- if (roundLimit != -1)
- logGlobal->warn("Map '%s': roundLimit of %d is not implemented!", mapName, roundLimit);
- }
- }
- void CMapLoaderH3M::readAllowedArtifacts()
- {
- map->allowedArtifact = VLC->arth->getDefaultAllowed();
- uint32_t artifactsCount = features.artifactsCount;
- uint32_t artifactsBytes = features.artifactsBytes;
- if (features.levelHOTA)
- {
- artifactsCount = reader->readUInt32();
- artifactsBytes = (artifactsCount + 7) / 8;
- }
- assert(artifactsCount <= features.artifactsCount);
- if(features.levelAB)
- reader->readBitmask(map->allowedArtifact, artifactsBytes, artifactsCount, true);
- // ban combo artifacts
- if (!features.levelSOD)
- {
- for(CArtifact * artifact : VLC->arth->objects)
- if (artifact->constituents)
- map->allowedArtifact[artifact->getId()] = false;
- }
- if (!features.levelAB)
- {
- map->allowedArtifact[ArtifactID::VIAL_OF_DRAGON_BLOOD] = false;
- map->allowedArtifact[ArtifactID::ARMAGEDDONS_BLADE] = false;
- }
- // Messy, but needed
- for (TriggeredEvent & event : map->triggeredEvents)
- {
- auto patcher = [&](EventCondition cond) -> EventExpression::Variant
- {
- if (cond.condition == EventCondition::HAVE_ARTIFACT ||
- cond.condition == EventCondition::TRANSPORT)
- {
- map->allowedArtifact[cond.objectType] = false;
- }
- return cond;
- };
- event.trigger = event.trigger.morph(patcher);
- }
- }
- void CMapLoaderH3M::readAllowedSpellsAbilities()
- {
- map->allowedSpell = VLC->spellh->getDefaultAllowed();
- map->allowedAbilities = VLC->skillh->getDefaultAllowed();
- if(features.levelSOD)
- {
- reader->readBitmask(map->allowedSpell, features.spellsBytes, features.spellsCount, true);
- reader->readBitmask(map->allowedAbilities, features.skillsBytes, features.skillsCount, true);
- }
- }
- void CMapLoaderH3M::readRumors()
- {
- uint32_t rumorsCount = reader->readUInt32();
- assert(rumorsCount < 100); // sanity check
- for(int it = 0; it < rumorsCount; it++)
- {
- Rumor ourRumor;
- ourRumor.name = readBasicString();
- ourRumor.text = readLocalizedString(TextIdentifier("header", "rumor", it, "text"));
- map->rumors.push_back(ourRumor);
- }
- }
- void CMapLoaderH3M::readPredefinedHeroes()
- {
- if (!features.levelSOD)
- return;
- uint32_t heroesCount = features.heroesCount;
- if (features.levelHOTA)
- heroesCount = reader->readUInt32();
- assert(heroesCount <= features.heroesCount);
- for(int z = 0; z < heroesCount; z++)
- {
- bool custom = reader->readBool();
- if(!custom)
- continue;
- auto * hero = new CGHeroInstance();
- hero->ID = Obj::HERO;
- hero->subID = z;
- bool hasExp = reader->readBool();
- if(hasExp)
- {
- hero->exp = reader->readUInt32();
- }
- else
- {
- hero->exp = 0;
- }
- bool hasSecSkills = reader->readBool();
- if(hasSecSkills)
- {
- uint32_t howMany = reader->readUInt32();
- hero->secSkills.resize(howMany);
- for(int yy = 0; yy < howMany; ++yy)
- {
- hero->secSkills[yy].first = reader->readSkill();
- hero->secSkills[yy].second = reader->readUInt8();
- }
- }
- loadArtifactsOfHero(hero);
- bool hasCustomBio = reader->readBool();
- if(hasCustomBio)
- hero->biographyCustom = readLocalizedString(TextIdentifier("heroes", z, "biography"));
- // 0xFF is default, 00 male, 01 female
- hero->gender = static_cast<EHeroGender>(reader->readUInt8());
- assert(hero->gender == EHeroGender::MALE || hero->gender == EHeroGender::FEMALE || hero->gender == EHeroGender::DEFAULT);
- bool hasCustomSpells = reader->readBool();
- if(hasCustomSpells)
- readSpells(hero->spells);
- bool hasCustomPrimSkills = reader->readBool();
- if(hasCustomPrimSkills)
- {
- for(int xx = 0; xx < GameConstants::PRIMARY_SKILLS; xx++)
- {
- hero->pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(xx), reader->readUInt8());
- }
- }
- map->predefinedHeroes.emplace_back(hero);
- }
- }
- void CMapLoaderH3M::loadArtifactsOfHero(CGHeroInstance * hero)
- {
- bool hasArtSet = reader->readBool();
- // True if artifact set is not default (hero has some artifacts)
- if(!hasArtSet)
- return;
- if(!hero->artifactsWorn.empty() || !hero->artifactsInBackpack.empty())
- {
- 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());
- hero->artifactsInBackpack.clear();
- while(!hero->artifactsWorn.empty())
- hero->eraseArtSlot(hero->artifactsWorn.begin()->first);
- }
- for(int pom = 0; pom < features.artifactSlotsCount; pom++)
- loadArtifactToSlot(hero, pom);
- // bag artifacts
- // number of artifacts in hero's bag
- int amount = reader->readUInt16();
- for(int ss = 0; ss < amount; ++ss)
- {
- loadArtifactToSlot(hero, GameConstants::BACKPACK_START + static_cast<int>(hero->artifactsInBackpack.size()));
- }
- }
- bool CMapLoaderH3M::loadArtifactToSlot(CGHeroInstance * hero, int slot)
- {
- ArtifactID aid = reader->readArtifact();
- if(aid == ArtifactID::NONE)
- return false;
- const Artifact * art = ArtifactID(aid).toArtifact(VLC->artifacts());
- if(nullptr == art)
- {
- logGlobal->warn("Invalid artifact in hero's backpack, ignoring...");
- return false;
- }
- if(art->isBig() && slot >= GameConstants::BACKPACK_START)
- {
- logGlobal->warn("A big artifact (war machine) in hero's backpack, ignoring...");
- return false;
- }
- // H3 bug workaround - Enemy hero on 3rd scenario of Good1.h3c campaign ("Long Live The Queen")
- // He has Shackles of War (normally - MISC slot artifact) in LEFT_HAND slot set in editor
- // Artifact seems to be missing in game, so skip artifacts that don't fit target slot
- auto * artifact = CArtifactInstance::createArtifact(map, aid);
- auto artifactPos = ArtifactPosition(slot);
- if (artifact->canBePutAt(ArtifactLocation(hero, artifactPos)))
- {
- hero->putArtifact(artifactPos, artifact);
- }
- else
- {
- logGlobal->debug("Artifact '%s' can't be put at the slot %d", artifact->artType->getNameTranslated(), slot);
- return false;
- }
- return true;
- }
- void CMapLoaderH3M::readTerrain()
- {
- map->initTerrain();
- // Read terrain
- int3 pos;
- for(pos.z = 0; pos.z < map->levels(); ++pos.z)
- {
- //OH3 format is [z][y][x]
- for(pos.y = 0; pos.y < map->height; pos.y++)
- {
- for(pos.x = 0; pos.x < map->width; pos.x++)
- {
- auto & tile = map->getTile(pos);
- tile.terType = VLC->terrainTypeHandler->getById(reader->readTerrain());
- tile.terView = reader->readUInt8();
- tile.riverType = VLC->riverTypeHandler->getById(reader->readRiver());
- tile.riverDir = reader->readUInt8();
- tile.roadType = VLC->roadTypeHandler->getById(reader->readRoad());
- tile.roadDir = reader->readUInt8();
- tile.extTileFlags = reader->readUInt8();
- tile.blocked = !tile.terType->isPassable();
- tile.visitable = false;
- assert(tile.terType->getId() != ETerrainId::NONE);
- }
- }
- }
- }
- void CMapLoaderH3M::readDefInfo()
- {
- uint32_t defAmount = reader->readUInt32();
- templates.reserve(defAmount);
- // Read custom defs
- for(int idd = 0; idd < defAmount; ++idd)
- {
- auto * tmpl = new ObjectTemplate;
- tmpl->readMap(reader->getInternalReader());
- templates.push_back(std::shared_ptr<const ObjectTemplate>(tmpl));
- }
- }
- CGObjectInstance * CMapLoaderH3M::readEvent(const int3 & objPos)
- {
- auto * object = new CGEvent();
- readBoxContent(object, objPos);
- object->availableFor = reader->readUInt8();
- object->computerActivate = reader->readBool();
- object->removeAfterVisit = reader->readBool();
- reader->skipZero(4);
- if (features.levelHOTA3)
- object->humanActivate = reader->readBool();
- else
- object->humanActivate = true;
- return object;
- }
- CGObjectInstance * CMapLoaderH3M::readPandora(const int3 & position)
- {
- auto * object = new CGPandoraBox();
- readBoxContent(object, position);
- return object;
- }
- void CMapLoaderH3M::readBoxContent(CGPandoraBox * object, const int3 & position)
- {
- readMessageAndGuards(object->message, object, position);
- object->gainedExp = reader->readUInt32();
- object->manaDiff = reader->readInt32();
- object->moraleDiff = reader->readInt8();
- object->luckDiff = reader->readInt8();
- reader->readResourses(object->resources);
- object->primskills.resize(GameConstants::PRIMARY_SKILLS);
- for(int x = 0; x < GameConstants::PRIMARY_SKILLS; ++x)
- object->primskills[x] = static_cast<PrimarySkill::PrimarySkill>(reader->readUInt8());
- int gabn = reader->readUInt8();//number of gained abilities
- for(int oo = 0; oo < gabn; ++oo)
- {
- object->abilities.emplace_back(reader->readSkill());
- object->abilityLevels.push_back(reader->readUInt8());
- }
- int gart = reader->readUInt8(); //number of gained artifacts
- for(int oo = 0; oo < gart; ++oo)
- object->artifacts.emplace_back(reader->readArtifact());
- int gspel = reader->readUInt8(); //number of gained spells
- for(int oo = 0; oo < gspel; ++oo)
- object->spells.emplace_back(reader->readSpell());
- int gcre = reader->readUInt8(); //number of gained creatures
- readCreatureSet(&object->creatures, gcre);
- reader->skipZero(8);
- }
- CGObjectInstance * CMapLoaderH3M::readMonster(const int3 & objPos, const ObjectInstanceID & idToBeGiven)
- {
- auto * object = new CGCreature();
- if(features.levelAB)
- {
- object->identifier = reader->readUInt32();
- map->questIdentifierToId[object->identifier] = idToBeGiven;
- }
- auto * hlp = new CStackInstance();
- hlp->count = reader->readUInt16();
- //type will be set during initialization
- object->putStack(SlotID(0), hlp);
- object->character = reader->readInt8();
- bool hasMessage = reader->readBool();
- if(hasMessage)
- {
- object->message = readLocalizedString(TextIdentifier("monster", objPos.x, objPos.y, objPos.z, "message"));
- reader->readResourses(object->resources);
- object->gainedArtifact = reader->readArtifact();
- }
- object->neverFlees = reader->readBool();
- object->notGrowingTeam = reader->readBool();
- reader->skipZero(2);
- if (features.levelHOTA3)
- {
- //TODO: HotA
- uint32_t agressionExact = reader->readUInt32();
- bool joinOnlyForMoney = reader->readBool();
- uint32_t joinPercent = reader->readUInt32();
- uint32_t upgradedStack = reader->readUInt32();
- uint32_t splitStack = reader->readUInt32();
- logGlobal->warn("Map '%s': creature %s settings %d %d %d %d %d are not implemeted!", mapName, objPos.toString(), agressionExact, int(joinOnlyForMoney), joinPercent, upgradedStack, splitStack);
- }
- return object;
- }
- CGObjectInstance * CMapLoaderH3M::readSign(const int3 & objPos)
- {
- auto * object = new CGSignBottle();
- object->message = readLocalizedString(TextIdentifier("sign", objPos.x, objPos.y, objPos.z, "message"));
- reader->skipZero(4);
- return object;
- }
- CGObjectInstance * CMapLoaderH3M::readWitchHut(const int3 & position)
- {
- auto * object = new CGWitchHut();
- // AB and later maps have allowed abilities defined in H3M
- if(features.levelAB)
- {
- reader->readBitmask(object->allowedAbilities, features.skillsBytes, features.skillsCount, false);
- if(object->allowedAbilities.size() != 1)
- {
- auto defaultAllowed = VLC->skillh->getDefaultAllowed();
- for(int skillID = 0; skillID < VLC->skillh->size(); ++skillID)
- if (defaultAllowed[skillID])
- object->allowedAbilities.insert(skillID);
- }
- }
- return object;
- }
- CGObjectInstance * CMapLoaderH3M::readScholar(const int3 & position)
- {
- auto * object = new CGScholar();
- object->bonusType = static_cast<CGScholar::EBonusType>(reader->readUInt8());
- object->bonusID = reader->readUInt8();
- reader->skipZero(6);
- return object;
- }
- CGObjectInstance * CMapLoaderH3M::readGarrison(const int3 & position)
- {
- auto * object = new CGGarrison();
- object->setOwner(reader->readPlayer32());
- readCreatureSet(object, 7);
- if(features.levelAB)
- object->removableUnits = reader->readBool();
- else
- object->removableUnits = true;
- reader->skipZero(8);
- return object;
- }
- CGObjectInstance * CMapLoaderH3M::readArtifact(const int3 & objPos, std::shared_ptr<const ObjectTemplate> objTempl)
- {
- auto artID = ArtifactID::NONE; //random, set later
- int spellID = -1;
- auto * object = new CGArtifact();
- readMessageAndGuards(object->message, object, objPos);
- if(objTempl->id == Obj::SPELL_SCROLL)
- {
- spellID = reader->readSpell32();
- artID = ArtifactID::SPELL_SCROLL;
- }
- else if(objTempl->id == Obj::ARTIFACT)
- {
- //specific artifact
- artID = ArtifactID(objTempl->subid);
- }
- object->storedArtifact = CArtifactInstance::createArtifact(map, artID, spellID);
- return object;
- }
- CGObjectInstance * CMapLoaderH3M::readResource(const int3 & position, std::shared_ptr<const ObjectTemplate> objTempl)
- {
- auto * object = new CGResource();
- readMessageAndGuards(object->message, object, position);
- object->amount = reader->readUInt32();
- if(objTempl->subid == GameResID(EGameResID::GOLD))
- {
- // Gold is multiplied by 100.
- object->amount *= 100;
- }
- reader->skipZero(4);
- return object;
- }
- CGObjectInstance * CMapLoaderH3M::readMine(const int3 & position, std::shared_ptr<const ObjectTemplate> objTempl)
- {
- auto * object = new CGMine();
- if (objTempl->subid < 7 )
- {
- object->setOwner(reader->readPlayer32());
- }
- else
- {
- object->setOwner(PlayerColor::NEUTRAL);
- reader->readBitmask(object->abandonedMineResources, features.resourcesBytes, features.resourcesCount, false);
- }
- return object;
- }
- CGObjectInstance * CMapLoaderH3M::readDwelling(const int3 & position)
- {
- auto * object = new CGDwelling();
- object->setOwner(reader->readPlayer32());
- return object;
- }
- CGObjectInstance * CMapLoaderH3M::readDwellingRandom(const int3 & position, std::shared_ptr<const ObjectTemplate> objTempl )
- {
- auto * object = new CGDwelling();
- CSpecObjInfo * spec = nullptr;
- switch(objTempl->id)
- {
- case Obj::RANDOM_DWELLING:
- spec = new CCreGenLeveledCastleInfo();
- break;
- case Obj::RANDOM_DWELLING_LVL:
- spec = new CCreGenAsCastleInfo();
- break;
- case Obj::RANDOM_DWELLING_FACTION:
- spec = new CCreGenLeveledInfo();
- break;
- default:
- throw std::runtime_error("Invalid random dwelling format");
- }
- spec->owner = object;
- object->setOwner(reader->readPlayer32());
- //216 and 217
- if(auto * castleSpec = dynamic_cast<CCreGenAsCastleInfo *>(spec))
- {
- castleSpec->instanceId = "";
- castleSpec->identifier = reader->readUInt32();
- if(!castleSpec->identifier)
- {
- castleSpec->asCastle = false;
- const int MASK_SIZE = 8;
- ui8 mask[2];
- mask[0] = reader->readUInt8();
- mask[1] = reader->readUInt8();
- castleSpec->allowedFactions.clear();
- castleSpec->allowedFactions.resize(VLC->townh->size(), false);
- for(int i = 0; i < MASK_SIZE; i++)
- castleSpec->allowedFactions[i] = ((mask[0] & (1 << i))>0);
- for(int i = 0; i < (GameConstants::F_NUMBER-MASK_SIZE); i++)
- castleSpec->allowedFactions[i+MASK_SIZE] = ((mask[1] & (1 << i))>0);
- }
- else
- {
- castleSpec->asCastle = true;
- }
- }
- //216 and 218
- if(auto * lvlSpec = dynamic_cast<CCreGenLeveledInfo *>(spec))
- {
- lvlSpec->minLevel = std::max(reader->readUInt8(), static_cast<ui8>(1));
- lvlSpec->maxLevel = std::min(reader->readUInt8(), static_cast<ui8>(7));
- }
- object->info = spec;
- return object;
- }
- CGObjectInstance * CMapLoaderH3M::readShrine(const int3 & position)
- {
- auto * object = new CGShrine();
- object->spell = reader->readSpell32();
- return object;
- }
- CGObjectInstance * CMapLoaderH3M::readHeroPlaceholder(const int3 & position)
- {
- auto * object = new CGHeroPlaceholder();
- object->setOwner(reader->readPlayer());
- HeroTypeID htid = reader->readHero(); //hero type id
- object->subID = htid.getNum();
- if(htid.getNum() == -1)
- {
- object->power = reader->readUInt8();
- logGlobal->debug("Hero placeholder: by power at %s", position.toString());
- }
- else
- {
- object->power = 0;
- logGlobal->debug("Hero placeholder: %s at %s", VLC->heroh->getById(htid)->getNameTranslated(), position.toString());
- }
- return object;
- }
- CGObjectInstance * CMapLoaderH3M::readGrail(const int3 & position)
- {
- map->grailPos = position;
- map->grailRadius = reader->readInt32();
- return nullptr;
- }
- CGObjectInstance * CMapLoaderH3M::readBlank(const int3 & position, std::shared_ptr<const ObjectTemplate> objTempl)
- {
- if (VLC->objtypeh->knownSubObjects(objTempl->id).count(objTempl->subid))
- return VLC->objtypeh->getHandlerFor(objTempl->id, objTempl->subid)->create(objTempl);
- logGlobal->warn("Unrecognized object: %d:%d ('%s') at %s on map '%s'", objTempl->id.toEnum(), objTempl->subid, objTempl->animationFile, position.toString(), map->name);
- return new CGObjectInstance();
- }
- CGObjectInstance * CMapLoaderH3M::readPyramid(const int3 & position, std::shared_ptr<const ObjectTemplate> objTempl)
- {
- if(objTempl->subid == 0)
- return new CBank();
- return new CGObjectInstance();
- }
- CGObjectInstance * CMapLoaderH3M::readQuestGuard(const int3 & position)
- {
- auto * guard = new CGQuestGuard();
- readQuest(guard, position);
- return guard;
- }
- CGObjectInstance * CMapLoaderH3M::readShipyard(const int3 & position)
- {
- auto * object = new CGShipyard();
- object->setOwner(reader->readPlayer32());
- return object;
- }
- CGObjectInstance * CMapLoaderH3M::readBorderGuard(const int3 & position)
- {
- return new CGBorderGuard();
- }
- CGObjectInstance * CMapLoaderH3M::readBorderGate(const int3 & position, std::shared_ptr<const ObjectTemplate> objTempl)
- {
- if (objTempl->subid < 1000)
- return new CGBorderGate();
- //TODO: HotA - grave has same ID as border gate? WTF?
- if (objTempl->subid == 1001)
- return new CGObjectInstance();
- logGlobal->warn("Map '%s: Quest gates at %s are not implemented!", mapName, position.toString());
- return readQuestGuard(position);
- }
- CGObjectInstance * CMapLoaderH3M::readLighthouse(const int3 & position)
- {
- auto * object = new CGLighthouse();
- object->tempOwner = reader->readPlayer32();
- return object;
- }
- CGObjectInstance * CMapLoaderH3M::readBank(const int3 & position, std::shared_ptr<const ObjectTemplate> objTempl)
- {
- if (features.levelHOTA3)
- {
- //TODO: HotA
- uint32_t field1 = reader->readUInt32();
- uint8_t field2 = reader->readUInt8();
- std::vector<ArtifactID> artifacts;
- int artNumber = reader->readUInt32();
- for(int yy = 0; yy < artNumber; ++yy)
- {
- artifacts.push_back(reader->readArtifact());
- }
- logGlobal->warn("Map '%s: creature bank at %s settings %d %d %d are not implemented!", mapName, position.toString(), field1, int(field2), artifacts.size());
- }
- return readBlank(position, objTempl);
- }
- CGObjectInstance * CMapLoaderH3M::readObject(std::shared_ptr<const ObjectTemplate> objectTemplate, const int3 & objectPosition, const ObjectInstanceID & idToBeGiven)
- {
- switch(objectTemplate->id)
- {
- case Obj::EVENT:
- return readEvent(objectPosition);
- case Obj::HERO:
- case Obj::RANDOM_HERO:
- case Obj::PRISON:
- return readHero(objectPosition, idToBeGiven);
- case Obj::MONSTER:
- case Obj::RANDOM_MONSTER:
- case Obj::RANDOM_MONSTER_L1:
- case Obj::RANDOM_MONSTER_L2:
- case Obj::RANDOM_MONSTER_L3:
- case Obj::RANDOM_MONSTER_L4:
- case Obj::RANDOM_MONSTER_L5:
- case Obj::RANDOM_MONSTER_L6:
- case Obj::RANDOM_MONSTER_L7:
- return readMonster(objectPosition, idToBeGiven);
- case Obj::OCEAN_BOTTLE:
- case Obj::SIGN:
- return readSign(objectPosition);
- case Obj::SEER_HUT:
- return readSeerHut(objectPosition);
- case Obj::WITCH_HUT:
- return readWitchHut(objectPosition);
- case Obj::SCHOLAR:
- return readScholar(objectPosition);
- case Obj::GARRISON:
- case Obj::GARRISON2:
- return readGarrison(objectPosition);
- case Obj::ARTIFACT:
- case Obj::RANDOM_ART:
- case Obj::RANDOM_TREASURE_ART:
- case Obj::RANDOM_MINOR_ART:
- case Obj::RANDOM_MAJOR_ART:
- case Obj::RANDOM_RELIC_ART:
- case Obj::SPELL_SCROLL:
- return readArtifact(objectPosition, objectTemplate);
- case Obj::RANDOM_RESOURCE:
- case Obj::RESOURCE:
- return readResource(objectPosition, objectTemplate);
- case Obj::RANDOM_TOWN:
- case Obj::TOWN:
- return readTown(objectPosition, objectTemplate);
- case Obj::MINE:
- case Obj::ABANDONED_MINE:
- return readMine(objectPosition, objectTemplate);
- case Obj::CREATURE_GENERATOR1:
- case Obj::CREATURE_GENERATOR2:
- case Obj::CREATURE_GENERATOR3:
- case Obj::CREATURE_GENERATOR4:
- return readDwelling(objectPosition);
- case Obj::SHRINE_OF_MAGIC_INCANTATION:
- case Obj::SHRINE_OF_MAGIC_GESTURE:
- case Obj::SHRINE_OF_MAGIC_THOUGHT:
- return readShrine(objectPosition);
- case Obj::PANDORAS_BOX:
- return readPandora(objectPosition);
- case Obj::GRAIL:
- return readGrail(objectPosition);
- case Obj::RANDOM_DWELLING:
- case Obj::RANDOM_DWELLING_LVL:
- case Obj::RANDOM_DWELLING_FACTION:
- return readDwellingRandom(objectPosition, objectTemplate);
- case Obj::QUEST_GUARD:
- return readQuestGuard(objectPosition);
- case Obj::SHIPYARD:
- return readShipyard(objectPosition);
- case Obj::HERO_PLACEHOLDER:
- return readHeroPlaceholder(objectPosition);
- case Obj::BORDERGUARD:
- return readBorderGuard(objectPosition);
- case Obj::BORDER_GATE:
- return readBorderGate(objectPosition, objectTemplate);
- case Obj::PYRAMID:
- return readPyramid(objectPosition, objectTemplate);
- case Obj::LIGHTHOUSE:
- return readLighthouse(objectPosition);
- case Obj::CREATURE_BANK:
- case Obj::DERELICT_SHIP:
- case Obj::DRAGON_UTOPIA:
- case Obj::CRYPT:
- case Obj::SHIPWRECK:
- return readBank(objectPosition, objectTemplate);
- default: //any other object
- return readBlank(objectPosition, objectTemplate);
- }
- }
- void CMapLoaderH3M::readObjects()
- {
- uint32_t howManyObjs = reader->readUInt32();
- for(uint32_t ww = 0; ww < howManyObjs; ++ww)
- {
- int3 objPos = reader->readInt3();
- uint32_t defnum = reader->readUInt32();
- ObjectInstanceID idToBeGiven = ObjectInstanceID(static_cast<si32>(map->objects.size()));
- std::shared_ptr<const ObjectTemplate> objTempl = templates.at(defnum);
- reader->skipZero(5);
- CGObjectInstance * nobj = readObject(objTempl, objPos, idToBeGiven);
- if (!nobj)
- continue;
- nobj->pos = objPos;
- nobj->ID = objTempl->id;
- nobj->id = idToBeGiven;
- if(nobj->ID != Obj::HERO && nobj->ID != Obj::HERO_PLACEHOLDER && nobj->ID != Obj::PRISON)
- {
- nobj->subID = objTempl->subid;
- }
- nobj->appearance = objTempl;
- assert(idToBeGiven == ObjectInstanceID((si32)map->objects.size()));
- {
- //TODO: define valid typeName and subtypeName for H3M maps
- //boost::format fmt("%s_%d");
- //fmt % nobj->typeName % nobj->id.getNum();
- boost::format fmt("obj_%d");
- fmt % nobj->id.getNum();
- nobj->instanceName = fmt.str();
- }
- map->addNewObject(nobj);
- }
- std::sort(map->heroesOnMap.begin(), map->heroesOnMap.end(), [](const ConstTransitivePtr<CGHeroInstance> & a, const ConstTransitivePtr<CGHeroInstance> & b)
- {
- return a->subID < b->subID;
- });
- }
- void CMapLoaderH3M::readCreatureSet(CCreatureSet * out, int number)
- {
- for(int ir = 0; ir < number; ++ir)
- {
- CreatureID creID = reader->readCreature();
- int count = reader->readUInt16();
- // Empty slot
- if(creID == CreatureID::NONE)
- continue;
- auto * hlp = new CStackInstance();
- hlp->count = count;
- if(creID < CreatureID::NONE)
- {
- int value = - creID.getNum() - 2;
- assert(value >= 0 && value < 14);
- uint8_t level = value / 2;
- uint8_t upgrade = value % 2;
- //this will happen when random object has random army
- hlp->randomStack = CStackInstance::RandomStackInfo{level, upgrade};
- }
- else
- {
- hlp->setType(creID);
- }
- out->putStack(SlotID(ir), hlp);
- }
- out->validTypes(true);
- }
- CGObjectInstance * CMapLoaderH3M::readHero(const int3 & initialPos, const ObjectInstanceID & idToBeGiven)
- {
- auto * nhi = new CGHeroInstance();
- if(features.levelAB)
- {
- unsigned int identifier = reader->readUInt32();
- map->questIdentifierToId[identifier] = idToBeGiven;
- }
- PlayerColor owner = reader->readPlayer();
- nhi->subID = reader->readUInt8();
- //If hero of this type has been predefined, use that as a base.
- //Instance data will overwrite the predefined values where appropriate.
- for(auto & elem : map->predefinedHeroes)
- {
- if(elem->subID == nhi->subID)
- {
- logGlobal->debug("Hero %d will be taken from the predefined heroes list.", nhi->subID);
- delete nhi;
- nhi = elem;
- break;
- }
- }
- nhi->setOwner(owner);
- nhi->portrait = nhi->subID;
- for(auto & elem : map->disposedHeroes)
- {
- if(elem.heroId == nhi->subID)
- {
- nhi->nameCustom = elem.name;
- nhi->portrait = elem.portrait;
- break;
- }
- }
- bool hasName = reader->readBool();
- if(hasName)
- nhi->nameCustom = readLocalizedString(TextIdentifier("heroes", nhi->subID, "name"));
- if(features.levelSOD)
- {
- bool hasExp = reader->readBool();
- if(hasExp)
- nhi->exp = reader->readUInt32();
- else
- nhi->exp = CGHeroInstance::UNINITIALIZED_EXPERIENCE;
- }
- else
- {
- nhi->exp = reader->readUInt32();
- //0 means "not set" in <=AB maps
- if(!nhi->exp)
- nhi->exp = CGHeroInstance::UNINITIALIZED_EXPERIENCE;
- }
- bool hasPortrait = reader->readBool();
- if(hasPortrait)
- nhi->portrait = reader->readHero().getNum();
- bool hasSecSkills = reader->readBool();
- if(hasSecSkills)
- {
- if(!nhi->secSkills.empty())
- {
- if (nhi->secSkills[0].first != SecondarySkill::DEFAULT)
- 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);
- nhi->secSkills.clear();
- }
- uint32_t howMany = reader->readUInt32();
- nhi->secSkills.resize(howMany);
- for(int yy = 0; yy < howMany; ++yy)
- {
- nhi->secSkills[yy].first = reader->readSkill();
- nhi->secSkills[yy].second = reader->readUInt8();
- }
- }
- bool hasGarison = reader->readBool();
- if(hasGarison)
- readCreatureSet(nhi, 7);
- nhi->formation = static_cast<EArmyFormation>(reader->readUInt8());
- assert(nhi->formation == EArmyFormation::WIDE || nhi->formation == EArmyFormation::TIGHT);
- loadArtifactsOfHero(nhi);
- nhi->patrol.patrolRadius = reader->readUInt8();
- nhi->patrol.patrolling = (nhi->patrol.patrolRadius != 0xff);
- if(features.levelAB)
- {
- bool hasCustomBiography = reader->readBool();
- if(hasCustomBiography)
- nhi->biographyCustom = readLocalizedString(TextIdentifier("heroes", nhi->subID, "biography"));
- nhi->gender = static_cast<EHeroGender>(reader->readUInt8());
- assert(nhi->gender == EHeroGender::MALE || nhi->gender == EHeroGender::FEMALE || nhi->gender == EHeroGender::DEFAULT);
- }
- else
- {
- nhi->gender = EHeroGender::DEFAULT;
- }
- // Spells
- if(features.levelSOD)
- {
- bool hasCustomSpells = reader->readBool();
- if(hasCustomSpells)
- {
- if(!nhi->spells.empty())
- {
- nhi->clear();
- 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);
- }
- nhi->spells.insert(SpellID::PRESET); //placeholder "preset spells"
- readSpells(nhi->spells);
- }
- }
- else if(features.levelAB)
- {
- //we can read one spell
- SpellID spell = reader->readSpell();
- if(spell != SpellID::NONE)
- nhi->spells.insert(spell);
- }
- if(features.levelSOD)
- {
- bool hasCustomPrimSkills = reader->readBool();
- if(hasCustomPrimSkills)
- {
- auto ps = nhi->getAllBonuses(Selector::type()(Bonus::PRIMARY_SKILL)
- .And(Selector::sourceType()(Bonus::HERO_BASE_SKILL)), nullptr);
- if(ps->size())
- {
- 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);
- for(const auto & b : *ps)
- nhi->removeBonus(b);
- }
- for(int xx = 0; xx < GameConstants::PRIMARY_SKILLS; ++xx)
- {
- nhi->pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(xx), reader->readUInt8());
- }
- }
- }
- reader->skipZero(16);
- return nhi;
- }
- CGObjectInstance * CMapLoaderH3M::readSeerHut(const int3 & position)
- {
- auto * hut = new CGSeerHut();
- uint32_t questsCount = 1;
- if (features.levelHOTA3)
- questsCount = reader->readUInt32();
- //TODO: HotA
- if (questsCount > 1)
- logGlobal->warn("Map '%s': Seer Hut at %s - %d quests are not implemented!", mapName, position.toString());
- for (size_t i = 0; i < questsCount; ++i)
- readSeerHutQuest(hut, position);
- if (features.levelHOTA3)
- {
- uint32_t repeateableQuestsCount = reader->readUInt32();
- if (questsCount != 0)
- logGlobal->warn("Map '%s': Seer Hut at %s - %d repeatable quests are not implemented!", mapName, position.toString(), repeateableQuestsCount);
- for (size_t i = 0; i < repeateableQuestsCount; ++i)
- readSeerHutQuest(hut, position);
- }
- reader->skipZero(2);
- return hut;
- }
- void CMapLoaderH3M::readSeerHutQuest(CGSeerHut * hut, const int3 & position)
- {
- if(features.levelAB)
- {
- readQuest(hut, position);
- }
- else
- {
- //RoE
- auto artID = reader->readArtifact();
- if (artID != ArtifactID::NONE)
- {
- //not none quest
- hut->quest->addArtifactID(artID);
- hut->quest->missionType = CQuest::MISSION_ART;
- }
- else
- {
- hut->quest->missionType = CQuest::MISSION_NONE;
- }
- hut->quest->lastDay = -1; //no timeout
- hut->quest->isCustomFirst = false;
- hut->quest->isCustomNext = false;
- hut->quest->isCustomComplete = false;
- }
- if (hut->quest->missionType)
- {
- auto rewardType = static_cast<CGSeerHut::ERewardType>(reader->readUInt8());
- hut->rewardType = rewardType;
- switch(rewardType)
- {
- case CGSeerHut::EXPERIENCE:
- {
- hut->rVal = reader->readUInt32();
- break;
- }
- case CGSeerHut::MANA_POINTS:
- {
- hut->rVal = reader->readUInt32();
- break;
- }
- case CGSeerHut::MORALE_BONUS:
- {
- hut->rVal = reader->readUInt8();
- break;
- }
- case CGSeerHut::LUCK_BONUS:
- {
- hut->rVal = reader->readUInt8();
- break;
- }
- case CGSeerHut::RESOURCES:
- {
- hut->rID = reader->readUInt8();
- hut->rVal = reader->readUInt32();
- assert(hut->rID < features.resourcesCount);
- assert((hut->rVal & 0x00ffffff) == hut->rVal);
- break;
- }
- case CGSeerHut::PRIMARY_SKILL:
- {
- hut->rID = reader->readUInt8();
- hut->rVal = reader->readUInt8();
- break;
- }
- case CGSeerHut::SECONDARY_SKILL:
- {
- hut->rID = reader->readSkill();
- hut->rVal = reader->readUInt8();
- break;
- }
- case CGSeerHut::ARTIFACT:
- {
- hut->rID = reader->readArtifact();
- break;
- }
- case CGSeerHut::SPELL:
- {
- hut->rID = reader->readSpell();
- break;
- }
- case CGSeerHut::CREATURE:
- {
- hut->rID = reader->readCreature();
- hut->rVal = reader->readUInt16();
- break;
- }
- case CGSeerHut::NOTHING:
- {
- // no-op
- break;
- }
- default:
- {
- assert(0);
- }
- }
- }
- else
- {
- // missionType==255
- reader->skipZero(1);
- }
- }
- void CMapLoaderH3M::readQuest(IQuestObject * guard, const int3 & position)
- {
- guard->quest->missionType = static_cast<CQuest::Emission>(reader->readUInt8());
- switch(guard->quest->missionType)
- {
- case CQuest::MISSION_NONE:
- return;
- case CQuest::MISSION_PRIMARY_STAT:
- {
- guard->quest->m2stats.resize(4);
- for(int x = 0; x < 4; ++x)
- {
- guard->quest->m2stats[x] = reader->readUInt8();
- }
- }
- break;
- case CQuest::MISSION_LEVEL:
- case CQuest::MISSION_KILL_HERO:
- case CQuest::MISSION_KILL_CREATURE:
- {
- guard->quest->m13489val = reader->readUInt32();
- break;
- }
- case CQuest::MISSION_ART:
- {
- int artNumber = reader->readUInt8();
- for(int yy = 0; yy < artNumber; ++yy)
- {
- auto artid = reader->readArtifact();
- guard->quest->addArtifactID(artid);
- map->allowedArtifact[artid] = false; //these are unavailable for random generation
- }
- break;
- }
- case CQuest::MISSION_ARMY:
- {
- int typeNumber = reader->readUInt8();
- guard->quest->m6creatures.resize(typeNumber);
- for(int hh = 0; hh < typeNumber; ++hh)
- {
- guard->quest->m6creatures[hh].type = VLC->creh->objects[reader->readCreature()];
- guard->quest->m6creatures[hh].count = reader->readUInt16();
- }
- break;
- }
- case CQuest::MISSION_RESOURCES:
- {
- for(int x = 0; x < 7; ++x)
- guard->quest->m7resources[x] = reader->readUInt32();
- break;
- }
- case CQuest::MISSION_HERO:
- {
- guard->quest->m13489val = reader->readHero().getNum();
- break;
- }
- case CQuest::MISSION_PLAYER:
- {
- guard->quest->m13489val = reader->readPlayer().getNum();
- break;
- }
- case CQuest::MISSION_HOTA_MULTI:
- {
- uint32_t missionSubID = reader->readUInt32();
- if (missionSubID == 0)
- {
- guard->quest->missionType = CQuest::MISSION_HOTA_HERO_CLASS;
- std::set<HeroClassID> heroClasses;
- uint32_t classesCount = reader->readUInt32();
- uint32_t classesBytes = (classesCount + 7) / 8;
- reader->readBitmask(heroClasses, classesBytes, classesCount, false);
- logGlobal->warn("Map '%s': Quest at %s 'Belong to one of %d classes' is not implemented!", mapName, position.toString(), heroClasses.size());
- break;
- }
- if (missionSubID == 1)
- {
- guard->quest->missionType = CQuest::MISSION_HOTA_REACH_DATE;
- uint32_t daysPassed = reader->readUInt32();
- logGlobal->warn("Map '%s': Quest at %s 'Wait till %d days passed' is not implemented!", mapName, position.toString(), daysPassed);
- break;
- }
- assert(0);
- break;
- }
- default:
- {
- assert(0);
- }
- }
- guard->quest->lastDay = reader->readInt32();
- guard->quest->firstVisitText = readLocalizedString(TextIdentifier("quest", position.x, position.y, position.z, "firstVisit"));
- guard->quest->nextVisitText = readLocalizedString(TextIdentifier("quest", position.x, position.y, position.z, "nextVisit"));
- guard->quest->completedText = readLocalizedString(TextIdentifier("quest", position.x, position.y, position.z, "completed"));
- guard->quest->isCustomFirst = !guard->quest->firstVisitText.empty();
- guard->quest->isCustomNext = !guard->quest->nextVisitText.empty();
- guard->quest->isCustomComplete = !guard->quest->completedText.empty();
- }
- CGObjectInstance * CMapLoaderH3M::readTown(const int3 & position, std::shared_ptr<const ObjectTemplate> objTempl)
- {
- auto * nt = new CGTownInstance();
- if(features.levelAB)
- nt->identifier = reader->readUInt32();
- nt->tempOwner = reader->readPlayer();
- bool hasName = reader->readBool();
- if(hasName)
- nt->setNameTranslated(readLocalizedString(TextIdentifier("town", position.x, position.y, position.z, "name")));
- bool hasGarrison = reader->readBool();
- if(hasGarrison)
- readCreatureSet(nt, 7);
- nt->formation = static_cast<EArmyFormation>(reader->readUInt8());
- assert(nt->formation == EArmyFormation::WIDE || nt->formation == EArmyFormation::TIGHT);
- bool hasCustomBuildings = reader->readBool();
- if(hasCustomBuildings)
- {
- reader->readBitmask(nt->builtBuildings, features.buildingsBytes,features.buildingsCount,false);
- reader->readBitmask(nt->forbiddenBuildings,features.buildingsBytes,features.buildingsCount,false);
- nt->builtBuildings = convertBuildings(nt->builtBuildings, objTempl->subid);
- nt->forbiddenBuildings = convertBuildings(nt->forbiddenBuildings, objTempl->subid);
- }
- // Standard buildings
- else
- {
- bool hasFort = reader->readBool();
- if(hasFort)
- nt->builtBuildings.insert(BuildingID::FORT);
- //means that set of standard building should be included
- nt->builtBuildings.insert(BuildingID::DEFAULT);
- }
- if(features.levelAB)
- {
- std::set<SpellID> spellsMask;
- reader->readBitmask(spellsMask, features.spellsBytes, features.spellsCount, false );
- std::copy(spellsMask.begin(), spellsMask.end(), std::back_inserter(nt->obligatorySpells));
- }
- {
- std::set<SpellID> spellsMask;
- reader->readBitmask(spellsMask, features.spellsBytes, features.spellsCount, true );
- std::copy(spellsMask.begin(), spellsMask.end(), std::back_inserter(nt->possibleSpells));
- auto defaultAllowed = VLC->spellh->getDefaultAllowed();
- //add all spells from mods
- for (int i = features.spellsCount; i < defaultAllowed.size(); ++i)
- if (defaultAllowed[i])
- nt->possibleSpells.emplace_back(i);
- }
- if (features.levelHOTA)
- {
- // TODO: HOTA support
- bool spellResearchAvailable = reader->readBool();
- MAYBE_UNUSED(spellResearchAvailable);
- }
- // Read castle events
- uint32_t numberOfEvent = reader->readUInt32();
- for(int gh = 0; gh < numberOfEvent; ++gh)
- {
- CCastleEvent nce;
- nce.town = nt;
- nce.name = readBasicString();
- nce.message = readLocalizedString(TextIdentifier("town", position.x, position.y, position.z, "event", gh, "description"));
- reader->readResourses(nce.resources);
- nce.players = reader->readUInt8();
- if(features.levelSOD)
- nce.humanAffected = reader->readBool();
- else
- nce.humanAffected = true;
- nce.computerAffected = reader->readUInt8();
- nce.firstOccurence = reader->readUInt16();
- nce.nextOccurence = reader->readUInt8();
- reader->skipZero(17);
- // New buildings
- reader->readBitmask(nce.buildings, features.buildingsBytes, features.buildingsCount, false);
- nce.buildings = convertBuildings(nce.buildings, objTempl->subid, false);
- nce.creatures.resize(7);
- for(int vv = 0; vv < 7; ++vv)
- nce.creatures[vv] = reader->readUInt16();
- reader->skipZero(4);
- nt->events.push_back(nce);
- }
- if(features.levelHOTA)
- {
- // TODO: HOTA support
- uint8_t alignment = reader->readUInt8();
- if (alignment < PlayerColor::PLAYER_LIMIT.getNum() || alignment == PlayerColor::NEUTRAL.getNum())
- nt->alignmentToPlayer = PlayerColor(alignment);
- else
- logGlobal->warn("%s - Aligment of town at %s 'not as player %d' is not implemented!", mapName, position.toString(), alignment - PlayerColor::PLAYER_LIMIT.getNum());
- }
- else if(features.levelSOD)
- {
- nt->alignmentToPlayer = reader->readPlayer();
- }
- reader->skipZero(3);
- return nt;
- }
- std::set<BuildingID> CMapLoaderH3M::convertBuildings(const std::set<BuildingID> & h3m, int castleID, bool addAuxiliary) const
- {
- std::map<int, BuildingID> helperMap;
- std::set<BuildingID> ret;
- // Note: this file is parsed many times.
- static const JsonNode config(ResourceID("config/buildings5.json"));
- for(const JsonNode & entry : config["table"].Vector())
- {
- int town = static_cast<int>(entry["town"].Float());
- if (town == castleID || town == -1)
- {
- helperMap[static_cast<int>(entry["h3"].Float())] = BuildingID(static_cast<si32>(entry["vcmi"].Float()));
- }
- }
- for(const auto & elem : h3m)
- {
- if(helperMap[elem] >= BuildingID::FIRST_REGULAR_ID)
- {
- ret.insert(helperMap[elem]);
- }
- // horde buildings use indexes from -1 to -5, where creature level is 1 to 5
- else if(helperMap[elem] >= (-GameConstants::CREATURES_PER_TOWN))
- {
- int level = (helperMap[elem]);
- //(-30)..(-36) - horde buildings (for game loading only)
- //They will be replaced in CGameState::initTowns()
- ret.insert(BuildingID(level + BuildingID::HORDE_BUILDING_CONVERTER)); //-1 => -30
- }
- else
- {
- logGlobal->warn("Conversion warning: unknown building %d in castle %d", elem.num, castleID);
- }
- }
- if(addAuxiliary)
- {
- //village hall is always present
- ret.insert(BuildingID::VILLAGE_HALL);
- if(ret.find(BuildingID::CITY_HALL) != ret.end())
- {
- ret.insert(BuildingID::EXTRA_CITY_HALL);
- }
- if(ret.find(BuildingID::TOWN_HALL) != ret.end())
- {
- ret.insert(BuildingID::EXTRA_TOWN_HALL);
- }
- if(ret.find(BuildingID::CAPITOL) != ret.end())
- {
- ret.insert(BuildingID::EXTRA_CAPITOL);
- }
- }
- return ret;
- }
- void CMapLoaderH3M::readEvents()
- {
- uint32_t numberOfEvents = reader->readUInt32();
- for(int yyoo = 0; yyoo < numberOfEvents; ++yyoo)
- {
- CMapEvent ne;
- ne.name = readBasicString();
- ne.message = readLocalizedString(TextIdentifier("event", yyoo, "description"));
- reader->readResourses(ne.resources);
- ne.players = reader->readUInt8();
- if(features.levelSOD)
- {
- ne.humanAffected = reader->readBool();
- }
- else
- {
- ne.humanAffected = true;
- }
- ne.computerAffected = reader->readBool();
- ne.firstOccurence = reader->readUInt16();
- ne.nextOccurence = reader->readUInt8();
- reader->skipZero(17);
- map->events.push_back(ne);
- }
- }
- void CMapLoaderH3M::readMessageAndGuards(std::string& message, CCreatureSet* guards, const int3 & position)
- {
- bool hasMessage = reader->readBool();
- if(hasMessage)
- {
- message = readLocalizedString(TextIdentifier("guards", position.x, position.y, position.z, "message"));
- bool hasGuards = reader->readBool();
- if(hasGuards)
- readCreatureSet(guards, 7);
- reader->skipZero(4);
- }
- }
- void CMapLoaderH3M::readSpells(std::set<SpellID>& dest)
- {
- reader->readBitmask(dest,features.spellsBytes,features.spellsCount,false);
- }
- std::string CMapLoaderH3M::readBasicString()
- {
- return TextOperations::toUnicode(reader->readBaseString(), fileEncoding);
- }
- std::string CMapLoaderH3M::readLocalizedString(const TextIdentifier & stringIdentifier)
- {
- std::string mapString = TextOperations::toUnicode(reader->readBaseString(), fileEncoding);
- TextIdentifier fullIdentifier("map", mapName, stringIdentifier.get());
- if (mapString.empty())
- return "";
- VLC->generaltexth->registerString(modName, fullIdentifier, mapString);
- return VLC->generaltexth->translate(fullIdentifier.get());
- }
- void CMapLoaderH3M::afterRead()
- {
- //convert main town positions for all players to actual object position, in H3M it is position of active tile
- for(auto & p : map->players)
- {
- int3 posOfMainTown = p.posOfMainTown;
- if(posOfMainTown.valid() && map->isInTheMap(posOfMainTown))
- {
- const TerrainTile & t = map->getTile(posOfMainTown);
- const CGObjectInstance * mainTown = nullptr;
- for(auto * obj : t.visitableObjects)
- {
- if(obj->ID == Obj::TOWN || obj->ID == Obj::RANDOM_TOWN)
- {
- mainTown = obj;
- break;
- }
- }
- if(mainTown == nullptr)
- continue;
- p.posOfMainTown = posOfMainTown + mainTown->getVisitableOffset();
- }
- }
- }
- VCMI_LIB_NAMESPACE_END
|