MapFormatJson.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  1. /*
  2. * MapFormatJson.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 "MapFormatJson.h"
  12. #include "../filesystem/CInputStream.h"
  13. #include "../filesystem/COutputStream.h"
  14. #include "../json/JsonWriter.h"
  15. #include "CMap.h"
  16. #include "MapFormat.h"
  17. #include "../ArtifactUtils.h"
  18. #include "../CHeroHandler.h"
  19. #include "../CTownHandler.h"
  20. #include "../VCMI_Lib.h"
  21. #include "../RiverHandler.h"
  22. #include "../RoadHandler.h"
  23. #include "../TerrainHandler.h"
  24. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  25. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  26. #include "../mapObjects/ObjectTemplate.h"
  27. #include "../mapObjects/CGHeroInstance.h"
  28. #include "../mapObjects/CGTownInstance.h"
  29. #include "../mapObjects/MiscObjects.h"
  30. #include "../modding/ModScope.h"
  31. #include "../modding/ModUtility.h"
  32. #include "../spells/CSpellHandler.h"
  33. #include "../CSkillHandler.h"
  34. #include "../constants/StringConstants.h"
  35. #include "../serializer/JsonDeserializer.h"
  36. #include "../serializer/JsonSerializer.h"
  37. #include "../Languages.h"
  38. VCMI_LIB_NAMESPACE_BEGIN
  39. class MapObjectResolver: public IInstanceResolver
  40. {
  41. public:
  42. MapObjectResolver(const CMapFormatJson * owner_);
  43. si32 decode (const std::string & identifier) const override;
  44. std::string encode(si32 identifier) const override;
  45. private:
  46. const CMapFormatJson * owner;
  47. };
  48. MapObjectResolver::MapObjectResolver(const CMapFormatJson * owner_):
  49. owner(owner_)
  50. {
  51. }
  52. si32 MapObjectResolver::decode(const std::string & identifier) const
  53. {
  54. //always decode as ObjectInstanceID
  55. auto it = owner->map->instanceNames.find(identifier);
  56. if(it != owner->map->instanceNames.end())
  57. {
  58. return (*it).second->id.getNum();
  59. }
  60. else
  61. {
  62. logGlobal->error("Object not found: %s", identifier);
  63. return -1;
  64. }
  65. }
  66. std::string MapObjectResolver::encode(si32 identifier) const
  67. {
  68. ObjectInstanceID id;
  69. //use h3m questIdentifiers if they are present
  70. if(owner->map->questIdentifierToId.empty())
  71. {
  72. id = ObjectInstanceID(identifier);
  73. }
  74. else
  75. {
  76. id = owner->map->questIdentifierToId[identifier];
  77. }
  78. si32 oid = id.getNum();
  79. if(oid < 0 || oid >= owner->map->objects.size())
  80. {
  81. logGlobal->error("Cannot get object with id %d", oid);
  82. return "";
  83. }
  84. return owner->map->objects[oid]->instanceName;
  85. }
  86. namespace HeaderDetail
  87. {
  88. static const std::vector<std::string> difficultyMap =
  89. {
  90. "EASY",
  91. "NORMAL",
  92. "HARD",
  93. "EXPERT",
  94. "IMPOSSIBLE"
  95. };
  96. enum class ECanPlay
  97. {
  98. NONE = 0,
  99. PLAYER_OR_AI = 1,
  100. PLAYER_ONLY = 2,
  101. AI_ONLY = 3
  102. };
  103. static const std::vector<std::string> canPlayMap =
  104. {
  105. "",
  106. "PlayerOrAI",
  107. "PlayerOnly",
  108. "AIOnly"
  109. };
  110. }
  111. namespace TriggeredEventsDetail
  112. {
  113. static const std::array conditionNames =
  114. {
  115. "haveArtifact", "haveCreatures", "haveResources", "haveBuilding",
  116. "control", "destroy", "transport", "daysPassed",
  117. "isHuman", "daysWithoutTown", "standardWin", "constValue"
  118. };
  119. static const std::array typeNames = { "victory", "defeat" };
  120. static EventCondition JsonToCondition(const JsonNode & node)
  121. {
  122. EventCondition event;
  123. const auto & conditionName = node.Vector()[0].String();
  124. auto pos = vstd::find_pos(conditionNames, conditionName);
  125. event.condition = static_cast<EventCondition::EWinLoseType>(pos);
  126. if (node.Vector().size() > 1)
  127. {
  128. const JsonNode & data = node.Vector()[1];
  129. event.objectInstanceName = data["object"].String();
  130. event.value = data["value"].Integer();
  131. switch (event.condition)
  132. {
  133. case EventCondition::HAVE_ARTIFACT:
  134. case EventCondition::TRANSPORT:
  135. if (data["type"].isNumber()) // compatibility
  136. event.objectType = ArtifactID(data["type"].Integer());
  137. else
  138. event.objectType = ArtifactID(ArtifactID::decode(data["type"].String()));
  139. break;
  140. case EventCondition::HAVE_CREATURES:
  141. if (data["type"].isNumber()) // compatibility
  142. event.objectType = CreatureID(data["type"].Integer());
  143. else
  144. event.objectType = CreatureID(CreatureID::decode(data["type"].String()));
  145. break;
  146. case EventCondition::HAVE_RESOURCES:
  147. if (data["type"].isNumber()) // compatibility
  148. event.objectType = GameResID(data["type"].Integer());
  149. else
  150. event.objectType = GameResID(GameResID::decode(data["type"].String()));
  151. break;
  152. case EventCondition::HAVE_BUILDING:
  153. if (data["type"].isNumber()) // compatibility
  154. event.objectType = BuildingID(data["type"].Integer());
  155. else
  156. event.objectType = BuildingID(BuildingID::decode(data["type"].String()));
  157. break;
  158. case EventCondition::CONTROL:
  159. case EventCondition::DESTROY:
  160. if (data["type"].isNumber()) // compatibility
  161. event.objectType = MapObjectID(data["type"].Integer());
  162. else
  163. event.objectType = MapObjectID(MapObjectID::decode(data["type"].String()));
  164. break;
  165. }
  166. if (!data["position"].isNull())
  167. {
  168. const auto & position = data["position"].Vector();
  169. event.position.x = static_cast<si32>(position.at(0).Float());
  170. event.position.y = static_cast<si32>(position.at(1).Float());
  171. event.position.z = static_cast<si32>(position.at(2).Float());
  172. }
  173. }
  174. return event;
  175. }
  176. static JsonNode ConditionToJson(const EventCondition & event)
  177. {
  178. JsonNode json;
  179. JsonVector & asVector = json.Vector();
  180. JsonNode condition;
  181. condition.String() = conditionNames.at(event.condition);
  182. asVector.push_back(condition);
  183. JsonNode data;
  184. if(!event.objectInstanceName.empty())
  185. data["object"].String() = event.objectInstanceName;
  186. data["type"].String() = event.objectType.toString();
  187. data["value"].Integer() = event.value;
  188. if(event.position != int3(-1, -1, -1))
  189. {
  190. auto & position = data["position"].Vector();
  191. position.resize(3);
  192. position[0].Float() = event.position.x;
  193. position[1].Float() = event.position.y;
  194. position[2].Float() = event.position.z;
  195. }
  196. if(!data.isNull())
  197. asVector.push_back(data);
  198. return json;
  199. }
  200. }//namespace TriggeredEventsDetail
  201. namespace TerrainDetail
  202. {
  203. static const std::array<char, 4> flipCodes =
  204. {
  205. '_', '-', '|', '+'
  206. };
  207. }
  208. ///CMapFormatJson
  209. const int CMapFormatJson::VERSION_MAJOR = 2;
  210. const int CMapFormatJson::VERSION_MINOR = 0;
  211. const std::string CMapFormatJson::HEADER_FILE_NAME = "header.json";
  212. const std::string CMapFormatJson::OBJECTS_FILE_NAME = "objects.json";
  213. const std::string CMapFormatJson::TERRAIN_FILE_NAMES[2] = {"surface_terrain.json", "underground_terrain.json"};
  214. CMapFormatJson::CMapFormatJson():
  215. fileVersionMajor(0), fileVersionMinor(0),
  216. mapObjectResolver(std::make_unique<MapObjectResolver>(this)),
  217. map(nullptr), mapHeader(nullptr)
  218. {
  219. }
  220. TerrainType * CMapFormatJson::getTerrainByCode(const std::string & code)
  221. {
  222. for(const auto & object : VLC->terrainTypeHandler->objects)
  223. {
  224. if(object->shortIdentifier == code)
  225. return const_cast<TerrainType *>(object.get());
  226. }
  227. return nullptr;
  228. }
  229. RiverType * CMapFormatJson::getRiverByCode(const std::string & code)
  230. {
  231. for(const auto & object : VLC->riverTypeHandler->objects)
  232. {
  233. if (object->shortIdentifier == code)
  234. return const_cast<RiverType *>(object.get());
  235. }
  236. return nullptr;
  237. }
  238. RoadType * CMapFormatJson::getRoadByCode(const std::string & code)
  239. {
  240. for(const auto & object : VLC->roadTypeHandler->objects)
  241. {
  242. if (object->shortIdentifier == code)
  243. return const_cast<RoadType *>(object.get());
  244. }
  245. return nullptr;
  246. }
  247. void CMapFormatJson::serializeAllowedFactions(JsonSerializeFormat & handler, std::set<FactionID> & value) const
  248. {
  249. std::set<FactionID> temp;
  250. if(handler.saving)
  251. {
  252. for(auto faction : VLC->townh->objects)
  253. if(faction->town && vstd::contains(value, faction->getId()))
  254. temp.insert(faction->getId());
  255. }
  256. handler.serializeLIC("allowedFactions", &FactionID::decode, &FactionID::encode, VLC->townh->getDefaultAllowed(), temp);
  257. if(!handler.saving)
  258. value = temp;
  259. }
  260. void CMapFormatJson::serializeHeader(JsonSerializeFormat & handler)
  261. {
  262. handler.serializeStruct("name", mapHeader->name);
  263. handler.serializeStruct("description", mapHeader->description);
  264. handler.serializeInt("heroLevelLimit", mapHeader->levelLimit, 0);
  265. //todo: support arbitrary percentage
  266. handler.serializeEnum("difficulty", mapHeader->difficulty, HeaderDetail::difficultyMap);
  267. serializePlayerInfo(handler);
  268. handler.serializeLIC("allowedHeroes", &HeroTypeID::decode, &HeroTypeID::encode, VLC->heroh->getDefaultAllowed(), mapHeader->allowedHeroes);
  269. handler.serializeStruct("victoryMessage", mapHeader->victoryMessage);
  270. handler.serializeInt("victoryIconIndex", mapHeader->victoryIconIndex);
  271. handler.serializeStruct("defeatMessage", mapHeader->defeatMessage);
  272. handler.serializeInt("defeatIconIndex", mapHeader->defeatIconIndex);
  273. }
  274. void CMapFormatJson::serializePlayerInfo(JsonSerializeFormat & handler)
  275. {
  276. auto playersData = handler.enterStruct("players");
  277. for(int player = 0; player < PlayerColor::PLAYER_LIMIT_I; player++)
  278. {
  279. PlayerInfo & info = mapHeader->players[player];
  280. if(handler.saving)
  281. {
  282. if(!info.canAnyonePlay())
  283. continue;
  284. }
  285. auto playerData = handler.enterStruct(GameConstants::PLAYER_COLOR_NAMES[player]);
  286. if(!handler.saving)
  287. {
  288. if(handler.getCurrent().isNull())
  289. {
  290. info.canComputerPlay = false;
  291. info.canHumanPlay = false;
  292. continue;
  293. }
  294. }
  295. serializeAllowedFactions(handler, info.allowedFactions);
  296. HeaderDetail::ECanPlay canPlay = HeaderDetail::ECanPlay::NONE;
  297. if(handler.saving)
  298. {
  299. if(info.canComputerPlay)
  300. {
  301. canPlay = info.canHumanPlay ? HeaderDetail::ECanPlay::PLAYER_OR_AI : HeaderDetail::ECanPlay::AI_ONLY;
  302. }
  303. else
  304. {
  305. canPlay = info.canHumanPlay ? HeaderDetail::ECanPlay::PLAYER_ONLY : HeaderDetail::ECanPlay::NONE;
  306. }
  307. }
  308. handler.serializeEnum("canPlay", canPlay, HeaderDetail::canPlayMap);
  309. if(!handler.saving)
  310. {
  311. switch(canPlay)
  312. {
  313. case HeaderDetail::ECanPlay::PLAYER_OR_AI:
  314. info.canComputerPlay = true;
  315. info.canHumanPlay = true;
  316. break;
  317. case HeaderDetail::ECanPlay::PLAYER_ONLY:
  318. info.canComputerPlay = false;
  319. info.canHumanPlay = true;
  320. break;
  321. case HeaderDetail::ECanPlay::AI_ONLY:
  322. info.canComputerPlay = true;
  323. info.canHumanPlay = false;
  324. break;
  325. default:
  326. info.canComputerPlay = false;
  327. info.canHumanPlay = false;
  328. break;
  329. }
  330. }
  331. //saving whole structure only if position is valid
  332. if(!handler.saving || info.posOfMainTown.valid())
  333. {
  334. auto mainTown = handler.enterStruct("mainTown");
  335. handler.serializeBool("generateHero", info.generateHeroAtMainTown);
  336. handler.serializeInt("x", info.posOfMainTown.x, -1);
  337. handler.serializeInt("y", info.posOfMainTown.y, -1);
  338. handler.serializeInt("l", info.posOfMainTown.z, -1);
  339. }
  340. if(!handler.saving)
  341. {
  342. info.hasMainTown = info.posOfMainTown.valid();
  343. }
  344. handler.serializeString("mainHero", info.mainHeroInstance);//must be before "heroes"
  345. //heroes
  346. if(handler.saving)
  347. {
  348. //ignoring heroesNames and saving from actual map objects
  349. //TODO: optimize
  350. for(auto & obj : map->objects)
  351. {
  352. if((obj->ID == Obj::HERO || obj->ID == Obj::RANDOM_HERO) && obj->tempOwner == PlayerColor(player))
  353. {
  354. auto * hero = dynamic_cast<CGHeroInstance *>(obj.get());
  355. auto heroes = handler.enterStruct("heroes");
  356. if(hero)
  357. {
  358. auto heroData = handler.enterStruct(hero->instanceName);
  359. heroData->serializeString("name", hero->nameCustomTextId);
  360. if(hero->ID == Obj::HERO)
  361. {
  362. std::string temp;
  363. if(hero->type)
  364. temp = hero->type->getJsonKey();
  365. else
  366. temp = hero->getHeroType().toEntity(VLC)->getJsonKey();
  367. handler.serializeString("type", temp);
  368. }
  369. }
  370. }
  371. }
  372. }
  373. else
  374. {
  375. info.heroesNames.clear();
  376. auto heroes = handler.enterStruct("heroes");
  377. for(const auto & hero : handler.getCurrent().Struct())
  378. {
  379. const JsonNode & data = hero.second;
  380. const std::string instanceName = hero.first;
  381. SHeroName hname;
  382. hname.heroId = HeroTypeID::NONE;
  383. std::string rawId = data["type"].String();
  384. if(!rawId.empty())
  385. hname.heroId = HeroTypeID(HeroTypeID::decode(rawId));
  386. hname.heroName = data["name"].String();
  387. if(instanceName == info.mainHeroInstance)
  388. {
  389. //this is main hero
  390. info.mainCustomHeroNameTextId = hname.heroName;
  391. info.hasRandomHero = (hname.heroId == HeroTypeID::NONE);
  392. info.mainCustomHeroId = hname.heroId;
  393. info.mainCustomHeroPortrait = HeroTypeID::NONE;
  394. //todo:mainHeroPortrait
  395. }
  396. info.heroesNames.push_back(hname);
  397. }
  398. }
  399. handler.serializeBool("randomFaction", info.isFactionRandom);
  400. }
  401. }
  402. void CMapFormatJson::readTeams(JsonDeserializer & handler)
  403. {
  404. auto teams = handler.enterArray("teams");
  405. const JsonNode & src = teams->getCurrent();
  406. if(src.getType() != JsonNode::JsonType::DATA_VECTOR)
  407. {
  408. // No alliances
  409. if(src.getType() != JsonNode::JsonType::DATA_NULL)
  410. logGlobal->error("Invalid teams field type");
  411. mapHeader->howManyTeams = 0;
  412. for(auto & player : mapHeader->players)
  413. if(player.canAnyonePlay())
  414. player.team = TeamID(mapHeader->howManyTeams++);
  415. }
  416. else
  417. {
  418. const JsonVector & srcVector = src.Vector();
  419. mapHeader->howManyTeams = static_cast<ui8>(srcVector.size());
  420. for(int team = 0; team < mapHeader->howManyTeams; team++)
  421. for(const JsonNode & playerData : srcVector[team].Vector())
  422. {
  423. PlayerColor player = PlayerColor(vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, playerData.String()));
  424. if(player.isValidPlayer())
  425. if(mapHeader->players[player.getNum()].canAnyonePlay())
  426. mapHeader->players[player.getNum()].team = TeamID(team);
  427. }
  428. for(PlayerInfo & player : mapHeader->players)
  429. if(player.canAnyonePlay() && player.team == TeamID::NO_TEAM)
  430. player.team = TeamID(mapHeader->howManyTeams++);
  431. }
  432. }
  433. void CMapFormatJson::writeTeams(JsonSerializer & handler)
  434. {
  435. std::vector<std::set<PlayerColor>> teamsData;
  436. teamsData.resize(mapHeader->howManyTeams);
  437. //get raw data
  438. for(int idx = 0; idx < mapHeader->players.size(); idx++)
  439. {
  440. const PlayerInfo & player = mapHeader->players.at(idx);
  441. int team = player.team.getNum();
  442. if(vstd::iswithin(team, 0, mapHeader->howManyTeams-1) && player.canAnyonePlay())
  443. teamsData.at(team).insert(PlayerColor(idx));
  444. }
  445. //remove single-member teams
  446. vstd::erase_if(teamsData, [](std::set<PlayerColor> & elem) -> bool
  447. {
  448. return elem.size() <= 1;
  449. });
  450. if(!teamsData.empty())
  451. {
  452. JsonNode dest;
  453. //construct output
  454. dest.setType(JsonNode::JsonType::DATA_VECTOR);
  455. for(const std::set<PlayerColor> & teamData : teamsData)
  456. {
  457. JsonNode team;
  458. for(const PlayerColor & player : teamData)
  459. team.Vector().emplace_back(GameConstants::PLAYER_COLOR_NAMES[player.getNum()]);
  460. dest.Vector().push_back(std::move(team));
  461. }
  462. handler.serializeRaw("teams", dest, std::nullopt);
  463. }
  464. }
  465. void CMapFormatJson::readTriggeredEvents(JsonDeserializer & handler)
  466. {
  467. const JsonNode & input = handler.getCurrent();
  468. mapHeader->triggeredEvents.clear();
  469. for(const auto & entry : input["triggeredEvents"].Struct())
  470. {
  471. TriggeredEvent event;
  472. event.identifier = entry.first;
  473. readTriggeredEvent(event, entry.second);
  474. mapHeader->triggeredEvents.push_back(event);
  475. }
  476. }
  477. void CMapFormatJson::readTriggeredEvent(TriggeredEvent & event, const JsonNode & source) const
  478. {
  479. using namespace TriggeredEventsDetail;
  480. event.onFulfill.jsonDeserialize(source["message"]);
  481. event.description.jsonDeserialize(source["description"]);
  482. event.effect.type = vstd::find_pos(typeNames, source["effect"]["type"].String());
  483. event.effect.toOtherMessage.jsonDeserialize(source["effect"]["messageToSend"]);
  484. event.trigger = EventExpression(source["condition"], JsonToCondition); // logical expression
  485. }
  486. void CMapFormatJson::writeTriggeredEvents(JsonSerializer & handler)
  487. {
  488. JsonNode triggeredEvents;
  489. for(const auto & event : mapHeader->triggeredEvents)
  490. writeTriggeredEvent(event, triggeredEvents[event.identifier]);
  491. handler.serializeRaw("triggeredEvents", triggeredEvents, std::nullopt);
  492. }
  493. void CMapFormatJson::writeTriggeredEvent(const TriggeredEvent & event, JsonNode & dest) const
  494. {
  495. using namespace TriggeredEventsDetail;
  496. if(!event.onFulfill.empty())
  497. event.onFulfill.jsonSerialize(dest["message"]);
  498. if(!event.description.empty())
  499. event.description.jsonSerialize(dest["description"]);
  500. dest["effect"]["type"].String() = typeNames.at(static_cast<size_t>(event.effect.type));
  501. if(!event.effect.toOtherMessage.empty())
  502. event.description.jsonSerialize(dest["effect"]["messageToSend"]);
  503. dest["condition"] = event.trigger.toJson(ConditionToJson);
  504. }
  505. void CMapFormatJson::readDisposedHeroes(JsonSerializeFormat & handler)
  506. {
  507. auto definitions = handler.enterStruct("predefinedHeroes");//DisposedHeroes are part of predefinedHeroes in VCMI map format
  508. const JsonNode & data = handler.getCurrent();
  509. for(const auto & entry : data.Struct())
  510. {
  511. HeroTypeID type(HeroTypeID::decode(entry.first));
  512. std::set<PlayerColor> mask;
  513. for(const JsonNode & playerData : entry.second["availableFor"].Vector())
  514. {
  515. PlayerColor player = PlayerColor(vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, playerData.String()));
  516. if(player.isValidPlayer())
  517. mask.insert(player);
  518. }
  519. if(!mask.empty() && mask.size() != PlayerColor::PLAYER_LIMIT_I && type.getNum() >= 0)
  520. {
  521. DisposedHero hero;
  522. hero.heroId = type;
  523. hero.players = mask;
  524. //name and portrait are not used
  525. map->disposedHeroes.push_back(hero);
  526. }
  527. }
  528. }
  529. void CMapFormatJson::writeDisposedHeroes(JsonSerializeFormat & handler)
  530. {
  531. if(map->disposedHeroes.empty())
  532. return;
  533. auto definitions = handler.enterStruct("predefinedHeroes");//DisposedHeroes are part of predefinedHeroes in VCMI map format
  534. for(DisposedHero & hero : map->disposedHeroes)
  535. {
  536. std::string type = HeroTypeID::encode(hero.heroId.getNum());
  537. auto definition = definitions->enterStruct(type);
  538. JsonNode players;
  539. definition->serializeIdArray("availableFor", hero.players);
  540. }
  541. }
  542. void CMapFormatJson::serializeRumors(JsonSerializeFormat & handler)
  543. {
  544. auto rumors = handler.enterArray("rumors");
  545. rumors.serializeStruct(map->rumors);
  546. }
  547. void CMapFormatJson::serializeTimedEvents(JsonSerializeFormat & handler)
  548. {
  549. auto events = handler.enterArray("events");
  550. std::vector<CMapEvent> temp(map->events.begin(), map->events.end());
  551. events.serializeStruct(temp);
  552. map->events.assign(temp.begin(), temp.end());
  553. }
  554. void CMapFormatJson::serializePredefinedHeroes(JsonSerializeFormat & handler)
  555. {
  556. //todo:serializePredefinedHeroes
  557. if(handler.saving)
  558. {
  559. if(!map->predefinedHeroes.empty())
  560. {
  561. auto predefinedHeroes = handler.enterStruct("predefinedHeroes");
  562. for(auto & hero : map->predefinedHeroes)
  563. {
  564. auto predefinedHero = handler.enterStruct(hero->getHeroTypeName());
  565. hero->serializeJsonDefinition(handler);
  566. }
  567. }
  568. }
  569. else
  570. {
  571. auto predefinedHeroes = handler.enterStruct("predefinedHeroes");
  572. const JsonNode & data = handler.getCurrent();
  573. for(const auto & p : data.Struct())
  574. {
  575. auto predefinedHero = handler.enterStruct(p.first);
  576. auto * hero = new CGHeroInstance(map->cb);
  577. hero->ID = Obj::HERO;
  578. hero->setHeroTypeName(p.first);
  579. hero->serializeJsonDefinition(handler);
  580. map->predefinedHeroes.emplace_back(hero);
  581. }
  582. }
  583. }
  584. void CMapFormatJson::serializeOptions(JsonSerializeFormat & handler)
  585. {
  586. serializeRumors(handler);
  587. serializeTimedEvents(handler);
  588. serializePredefinedHeroes(handler);
  589. handler.serializeLIC("allowedAbilities", &SecondarySkill::decode, &SecondarySkill::encode, VLC->skillh->getDefaultAllowed(), map->allowedAbilities);
  590. handler.serializeLIC("allowedArtifacts", &ArtifactID::decode, &ArtifactID::encode, VLC->arth->getDefaultAllowed(), map->allowedArtifact);
  591. handler.serializeLIC("allowedSpells", &SpellID::decode, &SpellID::encode, VLC->spellh->getDefaultAllowed(), map->allowedSpells);
  592. //todo:events
  593. }
  594. void CMapFormatJson::readOptions(JsonDeserializer & handler)
  595. {
  596. readDisposedHeroes(handler);
  597. serializeOptions(handler);
  598. }
  599. void CMapFormatJson::writeOptions(JsonSerializer & handler)
  600. {
  601. writeDisposedHeroes(handler);
  602. serializeOptions(handler);
  603. }
  604. ///CMapPatcher
  605. CMapPatcher::CMapPatcher(const JsonNode & stream): input(stream)
  606. {
  607. //todo: update map patches and change this
  608. fileVersionMajor = 0;
  609. fileVersionMinor = 0;
  610. }
  611. void CMapPatcher::patchMapHeader(std::unique_ptr<CMapHeader> & header)
  612. {
  613. map = nullptr;
  614. mapHeader = header.get();
  615. if (!input.isNull())
  616. readPatchData();
  617. }
  618. void CMapPatcher::readPatchData()
  619. {
  620. JsonDeserializer handler(mapObjectResolver.get(), input);
  621. readTriggeredEvents(handler);
  622. handler.serializeInt("defeatIconIndex", mapHeader->defeatIconIndex);
  623. handler.serializeInt("victoryIconIndex", mapHeader->victoryIconIndex);
  624. handler.serializeStruct("victoryString", mapHeader->victoryMessage);
  625. handler.serializeStruct("defeatString", mapHeader->defeatMessage);
  626. }
  627. ///CMapLoaderJson
  628. CMapLoaderJson::CMapLoaderJson(CInputStream * stream)
  629. : buffer(stream)
  630. , ioApi(new CProxyROIOApi(buffer))
  631. , loader("", "_", ioApi)
  632. {
  633. }
  634. std::unique_ptr<CMap> CMapLoaderJson::loadMap(IGameCallback * cb)
  635. {
  636. LOG_TRACE(logGlobal);
  637. auto result = std::make_unique<CMap>(cb);
  638. map = result.get();
  639. mapHeader = map;
  640. readMap();
  641. return result;
  642. }
  643. std::unique_ptr<CMapHeader> CMapLoaderJson::loadMapHeader()
  644. {
  645. LOG_TRACE(logGlobal);
  646. map = nullptr;
  647. auto result = std::make_unique<CMapHeader>();
  648. mapHeader = result.get();
  649. readHeader(false);
  650. return result;
  651. }
  652. bool CMapLoaderJson::isExistArchive(const std::string & archiveFilename)
  653. {
  654. return loader.existsResource(JsonPath::builtin(archiveFilename));
  655. }
  656. JsonNode CMapLoaderJson::getFromArchive(const std::string & archiveFilename)
  657. {
  658. JsonPath resource = JsonPath::builtin(archiveFilename);
  659. if(!loader.existsResource(resource))
  660. throw std::runtime_error(archiveFilename+" not found");
  661. auto data = loader.load(resource)->readAll();
  662. JsonNode res(reinterpret_cast<const std::byte*>(data.first.get()), data.second);
  663. return res;
  664. }
  665. void CMapLoaderJson::readMap()
  666. {
  667. LOG_TRACE(logGlobal);
  668. readHeader(true);
  669. map->initTerrain();
  670. readTerrain();
  671. readObjects();
  672. map->calculateGuardingGreaturePositions();
  673. }
  674. void CMapLoaderJson::readHeader(const bool complete)
  675. {
  676. //do not use map field here, use only mapHeader
  677. JsonNode header = getFromArchive(HEADER_FILE_NAME);
  678. fileVersionMajor = static_cast<int>(header["versionMajor"].Integer());
  679. if(fileVersionMajor > VERSION_MAJOR)
  680. {
  681. logGlobal->error("Unsupported map format version: %d", fileVersionMajor);
  682. throw std::runtime_error("Unsupported map format version");
  683. }
  684. fileVersionMinor = static_cast<int>(header["versionMinor"].Integer());
  685. if(fileVersionMinor > VERSION_MINOR)
  686. {
  687. logGlobal->warn("Too new map format revision: %d. This map should work but some of map features may be ignored.", fileVersionMinor);
  688. }
  689. JsonDeserializer handler(mapObjectResolver.get(), header);
  690. mapHeader->version = EMapFormat::VCMI;//todo: new version field
  691. //loading mods
  692. if(!header["mods"].isNull())
  693. {
  694. for(auto & mod : header["mods"].Vector())
  695. {
  696. ModVerificationInfo info;
  697. info.version = CModVersion::fromString(mod["version"].String());
  698. info.checksum = mod["checksum"].Integer();
  699. info.name = mod["name"].String();
  700. info.parent = mod["parent"].String();
  701. info.impactsGameplay = true;
  702. if(!mod["modId"].isNull())
  703. mapHeader->mods[mod["modId"].String()] = info;
  704. else
  705. mapHeader->mods[mod["name"].String()] = info;
  706. }
  707. }
  708. //todo: multilevel map load support
  709. {
  710. auto levels = handler.enterStruct("mapLevels");
  711. {
  712. auto surface = handler.enterStruct("surface");
  713. handler.serializeInt("height", mapHeader->height);
  714. handler.serializeInt("width", mapHeader->width);
  715. }
  716. {
  717. auto underground = handler.enterStruct("underground");
  718. mapHeader->twoLevel = !underground->getCurrent().isNull();
  719. }
  720. }
  721. serializeHeader(handler);
  722. readTriggeredEvents(handler);
  723. readTeams(handler);
  724. //TODO: check mods
  725. if(complete)
  726. readOptions(handler);
  727. readTranslations();
  728. }
  729. void CMapLoaderJson::readTerrainTile(const std::string & src, TerrainTile & tile)
  730. {
  731. try
  732. {
  733. using namespace TerrainDetail;
  734. {//terrain type
  735. const std::string typeCode = src.substr(0, 2);
  736. tile.terType = getTerrainByCode(typeCode);
  737. }
  738. int startPos = 2; //0+typeCode fixed length
  739. {//terrain view
  740. int pos = startPos;
  741. while (isdigit(src.at(pos)))
  742. pos++;
  743. int len = pos - startPos;
  744. if (len <= 0)
  745. throw std::runtime_error("Invalid terrain view in " + src);
  746. const std::string rawCode = src.substr(startPos, len);
  747. tile.terView = atoi(rawCode.c_str());
  748. startPos += len;
  749. }
  750. {//terrain flip
  751. int terrainFlip = vstd::find_pos(flipCodes, src.at(startPos++));
  752. if (terrainFlip < 0)
  753. throw std::runtime_error("Invalid terrain flip in " + src);
  754. else
  755. tile.extTileFlags = terrainFlip;
  756. }
  757. if (startPos >= src.size())
  758. return;
  759. bool hasRoad = true;
  760. {//road type
  761. const std::string typeCode = src.substr(startPos, 2);
  762. startPos += 2;
  763. tile.roadType = getRoadByCode(typeCode);
  764. if(!tile.roadType) //it's not a road, it's a river
  765. {
  766. tile.roadType = VLC->roadTypeHandler->getById(Road::NO_ROAD);
  767. tile.riverType = getRiverByCode(typeCode);
  768. hasRoad = false;
  769. if(!tile.riverType)
  770. {
  771. throw std::runtime_error("Invalid river type in " + src);
  772. }
  773. }
  774. }
  775. if (hasRoad)
  776. {//road dir
  777. int pos = startPos;
  778. while (isdigit(src.at(pos)))
  779. pos++;
  780. int len = pos - startPos;
  781. if (len <= 0)
  782. throw std::runtime_error("Invalid road dir in " + src);
  783. const std::string rawCode = src.substr(startPos, len);
  784. tile.roadDir = atoi(rawCode.c_str());
  785. startPos += len;
  786. }
  787. if (hasRoad)
  788. {//road flip
  789. int flip = vstd::find_pos(flipCodes, src.at(startPos++));
  790. if (flip < 0)
  791. throw std::runtime_error("Invalid road flip in " + src);
  792. else
  793. tile.extTileFlags |= (flip << 4);
  794. }
  795. if (startPos >= src.size())
  796. return;
  797. if (hasRoad)
  798. {//river type
  799. const std::string typeCode = src.substr(startPos, 2);
  800. startPos += 2;
  801. tile.riverType = getRiverByCode(typeCode);
  802. }
  803. {//river dir
  804. int pos = startPos;
  805. while (isdigit(src.at(pos)))
  806. pos++;
  807. int len = pos - startPos;
  808. if (len <= 0)
  809. throw std::runtime_error("Invalid river dir in " + src);
  810. const std::string rawCode = src.substr(startPos, len);
  811. tile.riverDir = atoi(rawCode.c_str());
  812. startPos += len;
  813. }
  814. {//river flip
  815. int flip = vstd::find_pos(flipCodes, src.at(startPos++));
  816. if (flip < 0)
  817. throw std::runtime_error("Invalid road flip in " + src);
  818. else
  819. tile.extTileFlags |= (flip << 2);
  820. }
  821. }
  822. catch (const std::exception &)
  823. {
  824. logGlobal->error("Failed to read terrain tile: %s");
  825. }
  826. }
  827. void CMapLoaderJson::readTerrainLevel(const JsonNode & src, const int index)
  828. {
  829. int3 pos(0, 0, index);
  830. const JsonVector & rows = src.Vector();
  831. if(rows.size() != map->height)
  832. throw std::runtime_error("Invalid terrain data");
  833. for(pos.y = 0; pos.y < map->height; pos.y++)
  834. {
  835. const JsonVector & tiles = rows[pos.y].Vector();
  836. if(tiles.size() != map->width)
  837. throw std::runtime_error("Invalid terrain data");
  838. for(pos.x = 0; pos.x < map->width; pos.x++)
  839. readTerrainTile(tiles[pos.x].String(), map->getTile(pos));
  840. }
  841. }
  842. void CMapLoaderJson::readTerrain()
  843. {
  844. {
  845. const JsonNode surface = getFromArchive(TERRAIN_FILE_NAMES[0]);
  846. readTerrainLevel(surface, 0);
  847. }
  848. if(map->twoLevel)
  849. {
  850. const JsonNode underground = getFromArchive(TERRAIN_FILE_NAMES[1]);
  851. readTerrainLevel(underground, 1);
  852. }
  853. map->calculateWaterContent();
  854. }
  855. CMapLoaderJson::MapObjectLoader::MapObjectLoader(CMapLoaderJson * _owner, JsonMap::value_type & json):
  856. owner(_owner), instance(nullptr), id(-1), jsonKey(json.first), configuration(json.second)
  857. {
  858. }
  859. void CMapLoaderJson::MapObjectLoader::construct()
  860. {
  861. //TODO:consider move to ObjectTypeHandler
  862. //find type handler
  863. std::string typeName = configuration["type"].String();
  864. std::string subtypeName = configuration["subtype"].String();
  865. if(typeName.empty())
  866. {
  867. logGlobal->error("Object type missing");
  868. logGlobal->debug(configuration.toString());
  869. return;
  870. }
  871. int3 pos;
  872. pos.x = static_cast<si32>(configuration["x"].Float());
  873. pos.y = static_cast<si32>(configuration["y"].Float());
  874. pos.z = static_cast<si32>(configuration["l"].Float());
  875. //special case for grail
  876. if(typeName == "grail")
  877. {
  878. owner->map->grailPos = pos;
  879. owner->map->grailRadius = static_cast<int>(configuration["options"]["grailRadius"].Float());
  880. return;
  881. }
  882. else if(subtypeName.empty())
  883. {
  884. logGlobal->error("Object subtype missing");
  885. logGlobal->debug(configuration.toString());
  886. return;
  887. }
  888. auto handler = VLC->objtypeh->getHandlerFor( ModScope::scopeMap(), typeName, subtypeName);
  889. auto appearance = std::make_shared<ObjectTemplate>();
  890. appearance->id = Obj(handler->getIndex());
  891. appearance->subid = handler->getSubIndex();
  892. appearance->readJson(configuration["template"], false);
  893. // Will be destroyed soon and replaced with shared template
  894. instance = handler->create(owner->map->cb, appearance);
  895. instance->id = ObjectInstanceID(static_cast<si32>(owner->map->objects.size()));
  896. instance->instanceName = jsonKey;
  897. instance->pos = pos;
  898. owner->map->addNewObject(instance);
  899. }
  900. void CMapLoaderJson::MapObjectLoader::configure()
  901. {
  902. if(nullptr == instance)
  903. return;
  904. JsonDeserializer handler(owner->mapObjectResolver.get(), configuration);
  905. instance->serializeJson(handler);
  906. //artifact instance serialization requires access to Map object, handle it here for now
  907. //todo: find better solution for artifact instance serialization
  908. if(auto * art = dynamic_cast<CGArtifact *>(instance))
  909. {
  910. ArtifactID artID = ArtifactID::NONE;
  911. SpellID spellID = SpellID::NONE;
  912. if(art->ID == Obj::SPELL_SCROLL)
  913. {
  914. auto spellIdentifier = configuration["options"]["spell"].String();
  915. auto rawId = VLC->identifiers()->getIdentifier(ModScope::scopeBuiltin(), "spell", spellIdentifier);
  916. if(rawId)
  917. spellID = rawId.value();
  918. else
  919. spellID = 0;
  920. artID = ArtifactID::SPELL_SCROLL;
  921. }
  922. else if(art->ID == Obj::ARTIFACT)
  923. {
  924. //specific artifact
  925. artID = art->getArtifact();
  926. }
  927. art->storedArtifact = ArtifactUtils::createArtifact(owner->map, artID, spellID.getNum());
  928. }
  929. if(auto * hero = dynamic_cast<CGHeroInstance *>(instance))
  930. {
  931. auto o = handler.enterStruct("options");
  932. hero->serializeJsonArtifacts(handler, "artifacts", owner->map);
  933. }
  934. }
  935. void CMapLoaderJson::readObjects()
  936. {
  937. LOG_TRACE(logGlobal);
  938. std::vector<std::unique_ptr<MapObjectLoader>> loaders;//todo: optimize MapObjectLoader memory layout
  939. JsonNode data = getFromArchive(OBJECTS_FILE_NAME);
  940. //get raw data
  941. for(auto & p : data.Struct())
  942. loaders.push_back(std::make_unique<MapObjectLoader>(this, p));
  943. for(auto & ptr : loaders)
  944. ptr->construct();
  945. //configure objects after all objects are constructed so we may resolve internal IDs even to actual pointers OTF
  946. for(auto & ptr : loaders)
  947. ptr->configure();
  948. std::sort(map->heroesOnMap.begin(), map->heroesOnMap.end(), [](const ConstTransitivePtr<CGHeroInstance> & a, const ConstTransitivePtr<CGHeroInstance> & b)
  949. {
  950. return a->getObjTypeIndex() < b->getObjTypeIndex();
  951. });
  952. std::set<HeroTypeID> debugHeroesOnMap;
  953. for (auto const & object : map->objects)
  954. {
  955. if(object->ID != Obj::HERO && object->ID != Obj::PRISON)
  956. continue;
  957. auto * hero = dynamic_cast<const CGHeroInstance *>(object.get());
  958. if (debugHeroesOnMap.count(hero->getHeroType()))
  959. logGlobal->error("Hero is already on the map at %s", hero->visitablePos().toString());
  960. debugHeroesOnMap.insert(hero->getHeroType());
  961. }
  962. }
  963. void CMapLoaderJson::readTranslations()
  964. {
  965. std::list<Languages::Options> languages{Languages::getLanguageList().begin(), Languages::getLanguageList().end()};
  966. for(auto & language : Languages::getLanguageList())
  967. {
  968. if(isExistArchive(language.identifier + ".json"))
  969. mapHeader->translations.Struct()[language.identifier] = getFromArchive(language.identifier + ".json");
  970. }
  971. mapHeader->registerMapStrings();
  972. }
  973. ///CMapSaverJson
  974. CMapSaverJson::CMapSaverJson(CInputOutputStream * stream)
  975. : buffer(stream)
  976. , ioApi(new CProxyIOApi(buffer))
  977. , saver(ioApi, "_")
  978. {
  979. fileVersionMajor = VERSION_MAJOR;
  980. fileVersionMinor = VERSION_MINOR;
  981. }
  982. //must be instantiated in .cpp file for access to complete types of all member fields
  983. CMapSaverJson::~CMapSaverJson() = default;
  984. void CMapSaverJson::addToArchive(const JsonNode & data, const std::string & filename)
  985. {
  986. std::ostringstream out;
  987. JsonWriter writer(out, false);
  988. writer.writeNode(data);
  989. out.flush();
  990. {
  991. auto s = out.str();
  992. std::unique_ptr<COutputStream> stream = saver.addFile(filename);
  993. if(stream->write(reinterpret_cast<const ui8 *>(s.c_str()), s.size()) != s.size())
  994. throw std::runtime_error("CMapSaverJson::saveHeader() zip compression failed.");
  995. }
  996. }
  997. void CMapSaverJson::saveMap(const std::unique_ptr<CMap>& map)
  998. {
  999. this->map = map.get();
  1000. this->mapHeader = this->map;
  1001. writeHeader();
  1002. writeTerrain();
  1003. writeObjects();
  1004. }
  1005. void CMapSaverJson::writeHeader()
  1006. {
  1007. logGlobal->trace("Saving header");
  1008. JsonNode header;
  1009. JsonSerializer handler(mapObjectResolver.get(), header);
  1010. header["versionMajor"].Float() = VERSION_MAJOR;
  1011. header["versionMinor"].Float() = VERSION_MINOR;
  1012. //write mods
  1013. JsonNode & mods = header["mods"];
  1014. for(const auto & mod : mapHeader->mods)
  1015. {
  1016. JsonNode modWriter;
  1017. modWriter["modId"].String() = mod.first;
  1018. modWriter["name"].String() = mod.second.name;
  1019. modWriter["parent"].String() = mod.second.parent;
  1020. modWriter["version"].String() = mod.second.version.toString();
  1021. modWriter["checksum"].Integer() = mod.second.checksum;
  1022. mods.Vector().push_back(modWriter);
  1023. }
  1024. //todo: multilevel map save support
  1025. JsonNode & levels = header["mapLevels"];
  1026. levels["surface"]["height"].Float() = mapHeader->height;
  1027. levels["surface"]["width"].Float() = mapHeader->width;
  1028. levels["surface"]["index"].Float() = 0;
  1029. if(mapHeader->twoLevel)
  1030. {
  1031. levels["underground"]["height"].Float() = mapHeader->height;
  1032. levels["underground"]["width"].Float() = mapHeader->width;
  1033. levels["underground"]["index"].Float() = 1;
  1034. }
  1035. serializeHeader(handler);
  1036. writeTriggeredEvents(handler);
  1037. writeTeams(handler);
  1038. writeOptions(handler);
  1039. writeTranslations();
  1040. addToArchive(header, HEADER_FILE_NAME);
  1041. }
  1042. std::string CMapSaverJson::writeTerrainTile(const TerrainTile & tile)
  1043. {
  1044. using namespace TerrainDetail;
  1045. std::ostringstream out;
  1046. out.setf(std::ios::dec, std::ios::basefield);
  1047. out.unsetf(std::ios::showbase);
  1048. out << tile.terType->shortIdentifier << static_cast<int>(tile.terView) << flipCodes[tile.extTileFlags % 4];
  1049. if(tile.roadType->getId() != Road::NO_ROAD)
  1050. out << tile.roadType->shortIdentifier << static_cast<int>(tile.roadDir) << flipCodes[(tile.extTileFlags >> 4) % 4];
  1051. if(tile.riverType->getId() != River::NO_RIVER)
  1052. out << tile.riverType->shortIdentifier << static_cast<int>(tile.riverDir) << flipCodes[(tile.extTileFlags >> 2) % 4];
  1053. return out.str();
  1054. }
  1055. JsonNode CMapSaverJson::writeTerrainLevel(const int index)
  1056. {
  1057. JsonNode data;
  1058. int3 pos(0,0,index);
  1059. data.Vector().resize(map->height);
  1060. for(pos.y = 0; pos.y < map->height; pos.y++)
  1061. {
  1062. JsonNode & row = data.Vector()[pos.y];
  1063. row.Vector().resize(map->width);
  1064. for(pos.x = 0; pos.x < map->width; pos.x++)
  1065. row.Vector()[pos.x].String() = writeTerrainTile(map->getTile(pos));
  1066. }
  1067. return data;
  1068. }
  1069. void CMapSaverJson::writeTerrain()
  1070. {
  1071. logGlobal->trace("Saving terrain");
  1072. //todo: multilevel map save support
  1073. JsonNode surface = writeTerrainLevel(0);
  1074. addToArchive(surface, TERRAIN_FILE_NAMES[0]);
  1075. if(map->twoLevel)
  1076. {
  1077. JsonNode underground = writeTerrainLevel(1);
  1078. addToArchive(underground, TERRAIN_FILE_NAMES[1]);
  1079. }
  1080. }
  1081. void CMapSaverJson::writeObjects()
  1082. {
  1083. logGlobal->trace("Saving objects");
  1084. JsonNode data;
  1085. JsonSerializer handler(mapObjectResolver.get(), data);
  1086. for(CGObjectInstance * obj : map->objects)
  1087. {
  1088. //logGlobal->trace("\t%s", obj->instanceName);
  1089. auto temp = handler.enterStruct(obj->instanceName);
  1090. obj->serializeJson(handler);
  1091. }
  1092. if(map->grailPos.valid())
  1093. {
  1094. JsonNode grail;
  1095. grail["type"].String() = "grail";
  1096. grail["x"].Float() = map->grailPos.x;
  1097. grail["y"].Float() = map->grailPos.y;
  1098. grail["l"].Float() = map->grailPos.z;
  1099. grail["options"]["radius"].Float() = map->grailRadius;
  1100. std::string grailId = boost::str(boost::format("grail_%d") % map->objects.size());
  1101. data[grailId] = grail;
  1102. }
  1103. //cleanup empty options
  1104. for(auto & p : data.Struct())
  1105. {
  1106. JsonNode & obj = p.second;
  1107. if(obj["options"].Struct().empty())
  1108. obj.Struct().erase("options");
  1109. }
  1110. addToArchive(data, OBJECTS_FILE_NAME);
  1111. }
  1112. void CMapSaverJson::writeTranslations()
  1113. {
  1114. for(auto & s : mapHeader->translations.Struct())
  1115. {
  1116. auto & language = s.first;
  1117. if(Languages::getLanguageOptions(language).identifier.empty())
  1118. {
  1119. logGlobal->error("Serializing of unsupported language %s is not permitted", language);
  1120. continue;
  1121. }
  1122. logGlobal->trace("Saving translations, language: %s", language);
  1123. addToArchive(s.second, language + ".json");
  1124. }
  1125. }
  1126. VCMI_LIB_NAMESPACE_END