MapFormatJson.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354
  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 "../GameLibrary.h"
  19. #include "../RiverHandler.h"
  20. #include "../RoadHandler.h"
  21. #include "../TerrainHandler.h"
  22. #include "../entities/faction/CTownHandler.h"
  23. #include "../entities/hero/CHeroHandler.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 "../texts/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. TerrainId CMapFormatJson::getTerrainByCode(const std::string & code)
  221. {
  222. for(const auto & object : LIBRARY->terrainTypeHandler->objects)
  223. {
  224. if(object->shortIdentifier == code)
  225. return object->getId();
  226. }
  227. return TerrainId::NONE;
  228. }
  229. RiverId CMapFormatJson::getRiverByCode(const std::string & code)
  230. {
  231. for(const auto & object : LIBRARY->riverTypeHandler->objects)
  232. {
  233. if (object->shortIdentifier == code)
  234. return object->getId();
  235. }
  236. return RiverId::NO_RIVER;
  237. }
  238. RoadId CMapFormatJson::getRoadByCode(const std::string & code)
  239. {
  240. for(const auto & object : LIBRARY->roadTypeHandler->objects)
  241. {
  242. if (object->shortIdentifier == code)
  243. return object->getId();
  244. }
  245. return RoadId::NO_ROAD;
  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 const factionID : LIBRARY->townh->getDefaultAllowed())
  253. if(vstd::contains(value, factionID))
  254. temp.insert(factionID);
  255. }
  256. handler.serializeLIC("allowedFactions", &FactionID::decode, &FactionID::encode, LIBRARY->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.serializeStruct("author", mapHeader->author);
  265. handler.serializeStruct("authorContact", mapHeader->authorContact);
  266. handler.serializeStruct("mapVersion", mapHeader->mapVersion);
  267. handler.serializeInt("creationDateTime", mapHeader->creationDateTime, 0);
  268. handler.serializeInt("heroLevelLimit", mapHeader->levelLimit, 0);
  269. //todo: support arbitrary percentage
  270. handler.serializeEnum("difficulty", mapHeader->difficulty, HeaderDetail::difficultyMap);
  271. serializePlayerInfo(handler);
  272. handler.serializeLIC("allowedHeroes", &HeroTypeID::decode, &HeroTypeID::encode, LIBRARY->heroh->getDefaultAllowed(), mapHeader->allowedHeroes);
  273. handler.serializeStruct("victoryMessage", mapHeader->victoryMessage);
  274. handler.serializeInt("victoryIconIndex", mapHeader->victoryIconIndex);
  275. handler.serializeStruct("defeatMessage", mapHeader->defeatMessage);
  276. handler.serializeInt("defeatIconIndex", mapHeader->defeatIconIndex);
  277. handler.serializeIdArray("reservedCampaignHeroes", mapHeader->reservedCampaignHeroes);
  278. }
  279. void CMapFormatJson::serializePlayerInfo(JsonSerializeFormat & handler)
  280. {
  281. auto playersData = handler.enterStruct("players");
  282. for(int player = 0; player < PlayerColor::PLAYER_LIMIT_I; player++)
  283. {
  284. PlayerInfo & info = mapHeader->players[player];
  285. if(handler.saving)
  286. {
  287. if(!info.canAnyonePlay())
  288. continue;
  289. }
  290. auto playerData = handler.enterStruct(GameConstants::PLAYER_COLOR_NAMES[player]);
  291. if(!handler.saving)
  292. {
  293. if(handler.getCurrent().isNull())
  294. {
  295. info.canComputerPlay = false;
  296. info.canHumanPlay = false;
  297. continue;
  298. }
  299. }
  300. serializeAllowedFactions(handler, info.allowedFactions);
  301. HeaderDetail::ECanPlay canPlay = HeaderDetail::ECanPlay::NONE;
  302. if(handler.saving)
  303. {
  304. if(info.canComputerPlay)
  305. {
  306. canPlay = info.canHumanPlay ? HeaderDetail::ECanPlay::PLAYER_OR_AI : HeaderDetail::ECanPlay::AI_ONLY;
  307. }
  308. else
  309. {
  310. canPlay = info.canHumanPlay ? HeaderDetail::ECanPlay::PLAYER_ONLY : HeaderDetail::ECanPlay::NONE;
  311. }
  312. }
  313. handler.serializeEnum("canPlay", canPlay, HeaderDetail::canPlayMap);
  314. if(!handler.saving)
  315. {
  316. switch(canPlay)
  317. {
  318. case HeaderDetail::ECanPlay::PLAYER_OR_AI:
  319. info.canComputerPlay = true;
  320. info.canHumanPlay = true;
  321. break;
  322. case HeaderDetail::ECanPlay::PLAYER_ONLY:
  323. info.canComputerPlay = false;
  324. info.canHumanPlay = true;
  325. break;
  326. case HeaderDetail::ECanPlay::AI_ONLY:
  327. info.canComputerPlay = true;
  328. info.canHumanPlay = false;
  329. break;
  330. default:
  331. info.canComputerPlay = false;
  332. info.canHumanPlay = false;
  333. break;
  334. }
  335. }
  336. //saving whole structure only if position is valid
  337. if(!handler.saving || info.posOfMainTown.isValid())
  338. {
  339. auto mainTown = handler.enterStruct("mainTown");
  340. handler.serializeBool("generateHero", info.generateHeroAtMainTown);
  341. handler.serializeInt("x", info.posOfMainTown.x, -1);
  342. handler.serializeInt("y", info.posOfMainTown.y, -1);
  343. handler.serializeInt("l", info.posOfMainTown.z, -1);
  344. }
  345. if(!handler.saving)
  346. {
  347. info.hasMainTown = info.posOfMainTown.isValid();
  348. }
  349. handler.serializeString("mainHero", info.mainHeroInstance);//must be before "heroes"
  350. //heroes
  351. if(handler.saving)
  352. {
  353. //ignoring heroesNames and saving from actual map objects
  354. //TODO: optimize
  355. for(auto & obj : map->objects)
  356. {
  357. if((obj->ID == Obj::HERO || obj->ID == Obj::RANDOM_HERO) && obj->tempOwner == PlayerColor(player))
  358. {
  359. auto * hero = dynamic_cast<CGHeroInstance *>(obj.get());
  360. auto heroes = handler.enterStruct("heroes");
  361. if(hero)
  362. {
  363. auto heroData = handler.enterStruct(hero->instanceName);
  364. heroData->serializeString("name", hero->nameCustomTextId);
  365. if(hero->ID == Obj::HERO)
  366. {
  367. std::string temp;
  368. if(hero->getHeroTypeID().hasValue())
  369. temp = hero->getHeroType()->getJsonKey();
  370. handler.serializeString("type", temp);
  371. }
  372. }
  373. }
  374. }
  375. }
  376. else
  377. {
  378. info.heroesNames.clear();
  379. auto heroes = handler.enterStruct("heroes");
  380. for(const auto & hero : handler.getCurrent().Struct())
  381. {
  382. const JsonNode & data = hero.second;
  383. const std::string instanceName = hero.first;
  384. SHeroName hname;
  385. hname.heroId = HeroTypeID::NONE;
  386. std::string rawId = data["type"].String();
  387. if(!rawId.empty())
  388. hname.heroId = HeroTypeID(HeroTypeID::decode(rawId));
  389. hname.heroName = data["name"].String();
  390. if(instanceName == info.mainHeroInstance)
  391. {
  392. //this is main hero
  393. info.mainCustomHeroNameTextId = hname.heroName;
  394. info.hasRandomHero = (hname.heroId == HeroTypeID::NONE);
  395. info.mainCustomHeroId = hname.heroId;
  396. info.mainCustomHeroPortrait = HeroTypeID::NONE;
  397. //todo:mainHeroPortrait
  398. }
  399. info.heroesNames.push_back(hname);
  400. }
  401. }
  402. handler.serializeBool("randomFaction", info.isFactionRandom);
  403. }
  404. }
  405. void CMapFormatJson::readTeams(JsonDeserializer & handler)
  406. {
  407. auto teams = handler.enterArray("teams");
  408. const JsonNode & src = teams->getCurrent();
  409. if(src.getType() != JsonNode::JsonType::DATA_VECTOR)
  410. {
  411. // No alliances
  412. if(src.getType() != JsonNode::JsonType::DATA_NULL)
  413. logGlobal->error("Invalid teams field type");
  414. mapHeader->howManyTeams = 0;
  415. for(auto & player : mapHeader->players)
  416. if(player.canAnyonePlay())
  417. player.team = TeamID(mapHeader->howManyTeams++);
  418. }
  419. else
  420. {
  421. const JsonVector & srcVector = src.Vector();
  422. mapHeader->howManyTeams = static_cast<ui8>(srcVector.size());
  423. for(int team = 0; team < mapHeader->howManyTeams; team++)
  424. for(const JsonNode & playerData : srcVector[team].Vector())
  425. {
  426. PlayerColor player = PlayerColor(vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, playerData.String()));
  427. if(player.isValidPlayer())
  428. if(mapHeader->players[player.getNum()].canAnyonePlay())
  429. mapHeader->players[player.getNum()].team = TeamID(team);
  430. }
  431. for(PlayerInfo & player : mapHeader->players)
  432. if(player.canAnyonePlay() && player.team == TeamID::NO_TEAM)
  433. player.team = TeamID(mapHeader->howManyTeams++);
  434. }
  435. }
  436. void CMapFormatJson::writeTeams(JsonSerializer & handler)
  437. {
  438. std::vector<std::set<PlayerColor>> teamsData;
  439. teamsData.resize(mapHeader->howManyTeams);
  440. //get raw data
  441. for(int idx = 0; idx < mapHeader->players.size(); idx++)
  442. {
  443. const PlayerInfo & player = mapHeader->players.at(idx);
  444. int team = player.team.getNum();
  445. if(vstd::iswithin(team, 0, mapHeader->howManyTeams-1) && player.canAnyonePlay())
  446. teamsData.at(team).insert(PlayerColor(idx));
  447. }
  448. //remove single-member teams
  449. vstd::erase_if(teamsData, [](std::set<PlayerColor> & elem) -> bool
  450. {
  451. return elem.size() <= 1;
  452. });
  453. if(!teamsData.empty())
  454. {
  455. JsonNode dest;
  456. //construct output
  457. dest.setType(JsonNode::JsonType::DATA_VECTOR);
  458. for(const std::set<PlayerColor> & teamData : teamsData)
  459. {
  460. JsonNode team;
  461. for(const PlayerColor & player : teamData)
  462. team.Vector().emplace_back(GameConstants::PLAYER_COLOR_NAMES[player.getNum()]);
  463. dest.Vector().push_back(std::move(team));
  464. }
  465. handler.serializeRaw("teams", dest, std::nullopt);
  466. }
  467. }
  468. void CMapFormatJson::readTriggeredEvents(JsonDeserializer & handler)
  469. {
  470. const JsonNode & input = handler.getCurrent();
  471. mapHeader->triggeredEvents.clear();
  472. for(const auto & entry : input["triggeredEvents"].Struct())
  473. {
  474. TriggeredEvent event;
  475. event.identifier = entry.first;
  476. readTriggeredEvent(event, entry.second);
  477. mapHeader->triggeredEvents.push_back(event);
  478. }
  479. }
  480. void CMapFormatJson::readTriggeredEvent(TriggeredEvent & event, const JsonNode & source) const
  481. {
  482. using namespace TriggeredEventsDetail;
  483. event.onFulfill.jsonDeserialize(source["message"]);
  484. event.description.jsonDeserialize(source["description"]);
  485. event.effect.type = vstd::find_pos(typeNames, source["effect"]["type"].String());
  486. event.effect.toOtherMessage.jsonDeserialize(source["effect"]["messageToSend"]);
  487. event.trigger = EventExpression(source["condition"], JsonToCondition); // logical expression
  488. }
  489. void CMapFormatJson::writeTriggeredEvents(JsonSerializer & handler)
  490. {
  491. JsonNode triggeredEvents;
  492. for(const auto & event : mapHeader->triggeredEvents)
  493. writeTriggeredEvent(event, triggeredEvents[event.identifier]);
  494. handler.serializeRaw("triggeredEvents", triggeredEvents, std::nullopt);
  495. }
  496. void CMapFormatJson::writeTriggeredEvent(const TriggeredEvent & event, JsonNode & dest) const
  497. {
  498. using namespace TriggeredEventsDetail;
  499. if(!event.onFulfill.empty())
  500. event.onFulfill.jsonSerialize(dest["message"]);
  501. if(!event.description.empty())
  502. event.description.jsonSerialize(dest["description"]);
  503. dest["effect"]["type"].String() = typeNames.at(static_cast<size_t>(event.effect.type));
  504. if(!event.effect.toOtherMessage.empty())
  505. event.description.jsonSerialize(dest["effect"]["messageToSend"]);
  506. dest["condition"] = event.trigger.toJson(ConditionToJson);
  507. }
  508. void CMapFormatJson::readDisposedHeroes(JsonSerializeFormat & handler)
  509. {
  510. auto definitions = handler.enterStruct("predefinedHeroes");//DisposedHeroes are part of predefinedHeroes in VCMI map format
  511. const JsonNode & data = handler.getCurrent();
  512. for(const auto & entry : data.Struct())
  513. {
  514. HeroTypeID type(HeroTypeID::decode(entry.first));
  515. std::set<PlayerColor> mask;
  516. for(const JsonNode & playerData : entry.second["availableFor"].Vector())
  517. {
  518. PlayerColor player = PlayerColor(vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, playerData.String()));
  519. if(player.isValidPlayer())
  520. mask.insert(player);
  521. }
  522. if(!mask.empty() && mask.size() != PlayerColor::PLAYER_LIMIT_I && type.getNum() >= 0)
  523. {
  524. DisposedHero hero;
  525. hero.heroId = type;
  526. hero.players = mask;
  527. //name and portrait are not used
  528. mapHeader->disposedHeroes.push_back(hero);
  529. }
  530. }
  531. }
  532. void CMapFormatJson::writeDisposedHeroes(JsonSerializeFormat & handler)
  533. {
  534. if(mapHeader->disposedHeroes.empty())
  535. return;
  536. auto definitions = handler.enterStruct("predefinedHeroes");//DisposedHeroes are part of predefinedHeroes in VCMI map format
  537. for(DisposedHero & hero : mapHeader->disposedHeroes)
  538. {
  539. std::string type = HeroTypeID::encode(hero.heroId.getNum());
  540. auto definition = definitions->enterStruct(type);
  541. JsonNode players;
  542. definition->serializeIdArray("availableFor", hero.players);
  543. }
  544. }
  545. void CMapFormatJson::serializeRumors(JsonSerializeFormat & handler)
  546. {
  547. auto rumors = handler.enterArray("rumors");
  548. rumors.serializeStruct(map->rumors);
  549. }
  550. void CMapFormatJson::serializeTimedEvents(JsonSerializeFormat & handler)
  551. {
  552. auto events = handler.enterArray("events");
  553. std::vector<CMapEvent> temp(map->events.begin(), map->events.end());
  554. events.serializeStruct(temp);
  555. map->events.assign(temp.begin(), temp.end());
  556. }
  557. void CMapFormatJson::serializePredefinedHeroes(JsonSerializeFormat & handler)
  558. {
  559. //todo:serializePredefinedHeroes
  560. if(handler.saving)
  561. {
  562. if(!map->predefinedHeroes.empty())
  563. {
  564. auto predefinedHeroes = handler.enterStruct("predefinedHeroes");
  565. for(auto & hero : map->predefinedHeroes)
  566. {
  567. auto predefinedHero = handler.enterStruct(hero->getHeroTypeName());
  568. hero->serializeJsonDefinition(handler);
  569. }
  570. }
  571. }
  572. else
  573. {
  574. auto predefinedHeroes = handler.enterStruct("predefinedHeroes");
  575. const JsonNode & data = handler.getCurrent();
  576. for(const auto & p : data.Struct())
  577. {
  578. auto predefinedHero = handler.enterStruct(p.first);
  579. auto * hero = new CGHeroInstance(map->cb);
  580. hero->ID = Obj::HERO;
  581. hero->setHeroTypeName(p.first);
  582. hero->serializeJsonDefinition(handler);
  583. map->predefinedHeroes.emplace_back(hero);
  584. }
  585. }
  586. }
  587. void CMapFormatJson::serializeOptions(JsonSerializeFormat & handler)
  588. {
  589. serializeRumors(handler);
  590. serializeTimedEvents(handler);
  591. serializePredefinedHeroes(handler);
  592. handler.serializeLIC("allowedAbilities", &SecondarySkill::decode, &SecondarySkill::encode, LIBRARY->skillh->getDefaultAllowed(), map->allowedAbilities);
  593. handler.serializeLIC("allowedArtifacts", &ArtifactID::decode, &ArtifactID::encode, LIBRARY->arth->getDefaultAllowed(), map->allowedArtifact);
  594. handler.serializeLIC("allowedSpells", &SpellID::decode, &SpellID::encode, LIBRARY->spellh->getDefaultAllowed(), map->allowedSpells);
  595. //todo:events
  596. }
  597. void CMapFormatJson::readOptions(JsonDeserializer & handler)
  598. {
  599. readDisposedHeroes(handler);
  600. serializeOptions(handler);
  601. }
  602. void CMapFormatJson::writeOptions(JsonSerializer & handler)
  603. {
  604. writeDisposedHeroes(handler);
  605. serializeOptions(handler);
  606. }
  607. ///CMapPatcher
  608. CMapPatcher::CMapPatcher(const JsonNode & stream): input(stream)
  609. {
  610. //todo: update map patches and change this
  611. fileVersionMajor = 0;
  612. fileVersionMinor = 0;
  613. }
  614. void CMapPatcher::patchMapHeader(std::unique_ptr<CMapHeader> & header)
  615. {
  616. map = nullptr;
  617. mapHeader = header.get();
  618. if (!input.isNull())
  619. readPatchData();
  620. }
  621. void CMapPatcher::readPatchData()
  622. {
  623. JsonDeserializer handler(mapObjectResolver.get(), input);
  624. readTriggeredEvents(handler);
  625. handler.serializeInt("defeatIconIndex", mapHeader->defeatIconIndex);
  626. handler.serializeInt("victoryIconIndex", mapHeader->victoryIconIndex);
  627. handler.serializeStruct("victoryString", mapHeader->victoryMessage);
  628. handler.serializeStruct("defeatString", mapHeader->defeatMessage);
  629. }
  630. ///CMapLoaderJson
  631. CMapLoaderJson::CMapLoaderJson(CInputStream * stream)
  632. : buffer(stream)
  633. , ioApi(new CProxyROIOApi(buffer))
  634. , loader("", "_", ioApi)
  635. {
  636. }
  637. std::unique_ptr<CMap> CMapLoaderJson::loadMap(IGameCallback * cb)
  638. {
  639. LOG_TRACE(logGlobal);
  640. auto result = std::make_unique<CMap>(cb);
  641. map = result.get();
  642. mapHeader = map;
  643. readMap();
  644. return result;
  645. }
  646. std::unique_ptr<CMapHeader> CMapLoaderJson::loadMapHeader()
  647. {
  648. LOG_TRACE(logGlobal);
  649. map = nullptr;
  650. auto result = std::make_unique<CMapHeader>();
  651. mapHeader = result.get();
  652. readHeader(false);
  653. return result;
  654. }
  655. bool CMapLoaderJson::isExistArchive(const std::string & archiveFilename)
  656. {
  657. return loader.existsResource(JsonPath::builtin(archiveFilename));
  658. }
  659. JsonNode CMapLoaderJson::getFromArchive(const std::string & archiveFilename)
  660. {
  661. JsonPath resource = JsonPath::builtin(archiveFilename);
  662. if(!loader.existsResource(resource))
  663. throw std::runtime_error(archiveFilename+" not found");
  664. auto data = loader.load(resource)->readAll();
  665. JsonNode res(reinterpret_cast<const std::byte*>(data.first.get()), data.second, archiveFilename);
  666. return res;
  667. }
  668. void CMapLoaderJson::readMap()
  669. {
  670. LOG_TRACE(logGlobal);
  671. readHeader(true);
  672. map->initTerrain();
  673. readTerrain();
  674. readObjects();
  675. map->calculateGuardingGreaturePositions();
  676. }
  677. void CMapLoaderJson::readHeader(const bool complete)
  678. {
  679. //do not use map field here, use only mapHeader
  680. JsonNode header = getFromArchive(HEADER_FILE_NAME);
  681. fileVersionMajor = static_cast<int>(header["versionMajor"].Integer());
  682. if(fileVersionMajor > VERSION_MAJOR)
  683. {
  684. logGlobal->error("Unsupported map format version: %d", fileVersionMajor);
  685. throw std::runtime_error("Unsupported map format version");
  686. }
  687. fileVersionMinor = static_cast<int>(header["versionMinor"].Integer());
  688. if(fileVersionMinor > VERSION_MINOR)
  689. {
  690. logGlobal->warn("Too new map format revision: %d. This map should work but some of map features may be ignored.", fileVersionMinor);
  691. }
  692. JsonDeserializer handler(mapObjectResolver.get(), header);
  693. mapHeader->version = EMapFormat::VCMI;//todo: new version field
  694. //loading mods
  695. mapHeader->mods = ModVerificationInfo::jsonDeserializeList(header["mods"]);
  696. //todo: multilevel map load support
  697. {
  698. auto levels = handler.enterStruct("mapLevels");
  699. {
  700. auto surface = handler.enterStruct("surface");
  701. handler.serializeInt("height", mapHeader->height);
  702. handler.serializeInt("width", mapHeader->width);
  703. }
  704. {
  705. auto underground = handler.enterStruct("underground");
  706. mapHeader->twoLevel = !underground->getCurrent().isNull();
  707. }
  708. }
  709. serializeHeader(handler);
  710. readTriggeredEvents(handler);
  711. readTeams(handler);
  712. //TODO: check mods
  713. if(complete)
  714. readOptions(handler);
  715. readTranslations();
  716. }
  717. void CMapLoaderJson::readTerrainTile(const std::string & src, TerrainTile & tile)
  718. {
  719. try
  720. {
  721. using namespace TerrainDetail;
  722. {//terrain type
  723. const std::string typeCode = src.substr(0, 2);
  724. tile.terrainType = getTerrainByCode(typeCode);
  725. }
  726. int startPos = 2; //0+typeCode fixed length
  727. {//terrain view
  728. int pos = startPos;
  729. while (isdigit(src.at(pos)))
  730. pos++;
  731. int len = pos - startPos;
  732. if (len <= 0)
  733. throw std::runtime_error("Invalid terrain view in " + src);
  734. const std::string rawCode = src.substr(startPos, len);
  735. tile.terView = atoi(rawCode.c_str());
  736. startPos += len;
  737. }
  738. {//terrain flip
  739. int terrainFlip = vstd::find_pos(flipCodes, src.at(startPos++));
  740. if (terrainFlip < 0)
  741. throw std::runtime_error("Invalid terrain flip in " + src);
  742. else
  743. tile.extTileFlags = terrainFlip;
  744. }
  745. if (startPos >= src.size())
  746. return;
  747. bool hasRoad = true;
  748. {//road type
  749. const std::string typeCode = src.substr(startPos, 2);
  750. startPos += 2;
  751. tile.roadType = getRoadByCode(typeCode);
  752. if(!tile.roadType) //it's not a road, it's a river
  753. {
  754. tile.roadType = Road::NO_ROAD;
  755. tile.riverType = getRiverByCode(typeCode);
  756. hasRoad = false;
  757. if(!tile.riverType)
  758. {
  759. throw std::runtime_error("Invalid river type in " + src);
  760. }
  761. }
  762. }
  763. if (hasRoad)
  764. {//road dir
  765. int pos = startPos;
  766. while (isdigit(src.at(pos)))
  767. pos++;
  768. int len = pos - startPos;
  769. if (len <= 0)
  770. throw std::runtime_error("Invalid road dir in " + src);
  771. const std::string rawCode = src.substr(startPos, len);
  772. tile.roadDir = atoi(rawCode.c_str());
  773. startPos += len;
  774. }
  775. if (hasRoad)
  776. {//road flip
  777. int flip = vstd::find_pos(flipCodes, src.at(startPos++));
  778. if (flip < 0)
  779. throw std::runtime_error("Invalid road flip in " + src);
  780. else
  781. tile.extTileFlags |= (flip << 4);
  782. }
  783. if (startPos >= src.size())
  784. return;
  785. if (hasRoad)
  786. {//river type
  787. const std::string typeCode = src.substr(startPos, 2);
  788. startPos += 2;
  789. tile.riverType = getRiverByCode(typeCode);
  790. }
  791. {//river dir
  792. int pos = startPos;
  793. while (isdigit(src.at(pos)))
  794. pos++;
  795. int len = pos - startPos;
  796. if (len <= 0)
  797. throw std::runtime_error("Invalid river dir in " + src);
  798. const std::string rawCode = src.substr(startPos, len);
  799. tile.riverDir = atoi(rawCode.c_str());
  800. startPos += len;
  801. }
  802. {//river flip
  803. int flip = vstd::find_pos(flipCodes, src.at(startPos++));
  804. if (flip < 0)
  805. throw std::runtime_error("Invalid road flip in " + src);
  806. else
  807. tile.extTileFlags |= (flip << 2);
  808. }
  809. }
  810. catch (const std::exception &)
  811. {
  812. logGlobal->error("Failed to read terrain tile: %s");
  813. }
  814. }
  815. void CMapLoaderJson::readTerrainLevel(const JsonNode & src, const int index)
  816. {
  817. int3 pos(0, 0, index);
  818. const JsonVector & rows = src.Vector();
  819. if(rows.size() != map->height)
  820. throw std::runtime_error("Invalid terrain data");
  821. for(pos.y = 0; pos.y < map->height; pos.y++)
  822. {
  823. const JsonVector & tiles = rows[pos.y].Vector();
  824. if(tiles.size() != map->width)
  825. throw std::runtime_error("Invalid terrain data");
  826. for(pos.x = 0; pos.x < map->width; pos.x++)
  827. readTerrainTile(tiles[pos.x].String(), map->getTile(pos));
  828. }
  829. }
  830. void CMapLoaderJson::readTerrain()
  831. {
  832. {
  833. const JsonNode surface = getFromArchive(TERRAIN_FILE_NAMES[0]);
  834. readTerrainLevel(surface, 0);
  835. }
  836. if(map->twoLevel)
  837. {
  838. const JsonNode underground = getFromArchive(TERRAIN_FILE_NAMES[1]);
  839. readTerrainLevel(underground, 1);
  840. }
  841. }
  842. CMapLoaderJson::MapObjectLoader::MapObjectLoader(CMapLoaderJson * _owner, JsonMap::value_type & json):
  843. owner(_owner), instance(nullptr), id(-1), jsonKey(json.first), configuration(json.second)
  844. {
  845. }
  846. void CMapLoaderJson::MapObjectLoader::construct()
  847. {
  848. //TODO:consider move to ObjectTypeHandler
  849. //find type handler
  850. std::string typeName = configuration["type"].String();
  851. std::string subtypeName = configuration["subtype"].String();
  852. if(typeName.empty())
  853. {
  854. logGlobal->error("Object type missing");
  855. logGlobal->debug(configuration.toString());
  856. return;
  857. }
  858. int3 pos;
  859. pos.x = static_cast<si32>(configuration["x"].Float());
  860. pos.y = static_cast<si32>(configuration["y"].Float());
  861. pos.z = static_cast<si32>(configuration["l"].Float());
  862. //special case for grail
  863. if(typeName == "grail")
  864. {
  865. owner->map->grailPos = pos;
  866. owner->map->grailRadius = static_cast<int>(configuration["options"]["grailRadius"].Float());
  867. return;
  868. }
  869. else if(subtypeName.empty())
  870. {
  871. logGlobal->error("Object subtype missing");
  872. logGlobal->debug(configuration.toString());
  873. return;
  874. }
  875. auto handler = LIBRARY->objtypeh->getHandlerFor( ModScope::scopeMap(), typeName, subtypeName);
  876. auto appearance = std::make_shared<ObjectTemplate>();
  877. appearance->id = Obj(handler->getIndex());
  878. appearance->subid = handler->getSubIndex();
  879. appearance->readJson(configuration["template"], false);
  880. // Will be destroyed soon and replaced with shared template
  881. instance = handler->create(owner->map->cb, appearance);
  882. instance->id = ObjectInstanceID(static_cast<si32>(owner->map->objects.size()));
  883. instance->instanceName = jsonKey;
  884. instance->setAnchorPos(pos);
  885. owner->map->addNewObject(instance);
  886. }
  887. void CMapLoaderJson::MapObjectLoader::configure()
  888. {
  889. if(nullptr == instance)
  890. return;
  891. JsonDeserializer handler(owner->mapObjectResolver.get(), configuration);
  892. instance->serializeJson(handler);
  893. //artifact instance serialization requires access to Map object, handle it here for now
  894. //todo: find better solution for artifact instance serialization
  895. if(auto art = std::dynamic_pointer_cast<CGArtifact>(instance))
  896. {
  897. ArtifactID artID = ArtifactID::NONE;
  898. SpellID spellID = SpellID::NONE;
  899. if(art->ID == Obj::SPELL_SCROLL)
  900. {
  901. auto spellIdentifier = configuration["options"]["spell"].String();
  902. auto rawId = LIBRARY->identifiers()->getIdentifier(ModScope::scopeBuiltin(), "spell", spellIdentifier);
  903. if(rawId)
  904. spellID = rawId.value();
  905. else
  906. spellID = 0;
  907. artID = ArtifactID::SPELL_SCROLL;
  908. }
  909. else if(art->ID == Obj::ARTIFACT)
  910. {
  911. //specific artifact
  912. artID = art->getArtifact();
  913. }
  914. art->storedArtifact = owner->map->createArtifact(artID, spellID.getNum());
  915. }
  916. if(auto hero = std::dynamic_pointer_cast<CGHeroInstance>(instance))
  917. {
  918. auto o = handler.enterStruct("options");
  919. hero->serializeJsonArtifacts(handler, "artifacts", owner->map);
  920. }
  921. }
  922. void CMapLoaderJson::readObjects()
  923. {
  924. LOG_TRACE(logGlobal);
  925. std::vector<std::unique_ptr<MapObjectLoader>> loaders;//todo: optimize MapObjectLoader memory layout
  926. JsonNode data = getFromArchive(OBJECTS_FILE_NAME);
  927. //get raw data
  928. for(auto & p : data.Struct())
  929. loaders.push_back(std::make_unique<MapObjectLoader>(this, p));
  930. for(auto & ptr : loaders)
  931. ptr->construct();
  932. //configure objects after all objects are constructed so we may resolve internal IDs even to actual pointers OTF
  933. for(auto & ptr : loaders)
  934. ptr->configure();
  935. map->postInitialize();
  936. std::set<HeroTypeID> debugHeroesOnMap;
  937. for (auto const & object : map->objects)
  938. {
  939. if(object->ID != Obj::HERO && object->ID != Obj::PRISON)
  940. continue;
  941. auto * hero = dynamic_cast<const CGHeroInstance *>(object.get());
  942. if (debugHeroesOnMap.count(hero->getHeroTypeID()))
  943. logGlobal->error("Hero is already on the map at %s", hero->visitablePos().toString());
  944. debugHeroesOnMap.insert(hero->getHeroTypeID());
  945. }
  946. }
  947. void CMapLoaderJson::readTranslations()
  948. {
  949. std::list<Languages::Options> languages{Languages::getLanguageList().begin(), Languages::getLanguageList().end()};
  950. for(auto & language : Languages::getLanguageList())
  951. {
  952. if(isExistArchive(language.identifier + ".json"))
  953. mapHeader->translations.Struct()[language.identifier] = getFromArchive(language.identifier + ".json");
  954. }
  955. mapHeader->registerMapStrings();
  956. }
  957. ///CMapSaverJson
  958. CMapSaverJson::CMapSaverJson(CInputOutputStream * stream)
  959. : buffer(stream)
  960. , ioApi(new CProxyIOApi(buffer))
  961. , saver(ioApi, "_")
  962. {
  963. fileVersionMajor = VERSION_MAJOR;
  964. fileVersionMinor = VERSION_MINOR;
  965. }
  966. //must be instantiated in .cpp file for access to complete types of all member fields
  967. CMapSaverJson::~CMapSaverJson() = default;
  968. void CMapSaverJson::addToArchive(const JsonNode & data, const std::string & filename)
  969. {
  970. std::ostringstream out;
  971. JsonWriter writer(out, false);
  972. writer.writeNode(data);
  973. out.flush();
  974. {
  975. auto s = out.str();
  976. std::unique_ptr<COutputStream> stream = saver.addFile(filename);
  977. if(stream->write(reinterpret_cast<const ui8 *>(s.c_str()), s.size()) != s.size())
  978. throw std::runtime_error("CMapSaverJson::saveHeader() zip compression failed.");
  979. }
  980. }
  981. void CMapSaverJson::saveMap(const std::unique_ptr<CMap>& map)
  982. {
  983. this->map = map.get();
  984. this->mapHeader = this->map;
  985. writeHeader();
  986. writeTerrain();
  987. writeObjects();
  988. }
  989. void CMapSaverJson::writeHeader()
  990. {
  991. logGlobal->trace("Saving header");
  992. JsonNode header;
  993. JsonSerializer handler(mapObjectResolver.get(), header);
  994. header["versionMajor"].Float() = VERSION_MAJOR;
  995. header["versionMinor"].Float() = VERSION_MINOR;
  996. //write mods
  997. header["mods"] = ModVerificationInfo::jsonSerializeList(mapHeader->mods);
  998. //todo: multilevel map save support
  999. JsonNode & levels = header["mapLevels"];
  1000. levels["surface"]["height"].Float() = mapHeader->height;
  1001. levels["surface"]["width"].Float() = mapHeader->width;
  1002. levels["surface"]["index"].Float() = 0;
  1003. if(mapHeader->twoLevel)
  1004. {
  1005. levels["underground"]["height"].Float() = mapHeader->height;
  1006. levels["underground"]["width"].Float() = mapHeader->width;
  1007. levels["underground"]["index"].Float() = 1;
  1008. }
  1009. serializeHeader(handler);
  1010. writeTriggeredEvents(handler);
  1011. writeTeams(handler);
  1012. writeOptions(handler);
  1013. writeTranslations();
  1014. addToArchive(header, HEADER_FILE_NAME);
  1015. }
  1016. std::string CMapSaverJson::writeTerrainTile(const TerrainTile & tile)
  1017. {
  1018. using namespace TerrainDetail;
  1019. std::ostringstream out;
  1020. out.setf(std::ios::dec, std::ios::basefield);
  1021. out.unsetf(std::ios::showbase);
  1022. out << tile.getTerrain()->shortIdentifier << static_cast<int>(tile.terView) << flipCodes[tile.extTileFlags % 4];
  1023. if(tile.hasRoad())
  1024. out << tile.getRoad()->shortIdentifier << static_cast<int>(tile.roadDir) << flipCodes[(tile.extTileFlags >> 4) % 4];
  1025. if(tile.hasRiver())
  1026. out << tile.getRiver()->shortIdentifier << static_cast<int>(tile.riverDir) << flipCodes[(tile.extTileFlags >> 2) % 4];
  1027. return out.str();
  1028. }
  1029. JsonNode CMapSaverJson::writeTerrainLevel(const int index)
  1030. {
  1031. JsonNode data;
  1032. int3 pos(0,0,index);
  1033. data.Vector().resize(map->height);
  1034. for(pos.y = 0; pos.y < map->height; pos.y++)
  1035. {
  1036. JsonNode & row = data.Vector()[pos.y];
  1037. row.Vector().resize(map->width);
  1038. for(pos.x = 0; pos.x < map->width; pos.x++)
  1039. row.Vector()[pos.x].String() = writeTerrainTile(map->getTile(pos));
  1040. }
  1041. return data;
  1042. }
  1043. void CMapSaverJson::writeTerrain()
  1044. {
  1045. logGlobal->trace("Saving terrain");
  1046. //todo: multilevel map save support
  1047. JsonNode surface = writeTerrainLevel(0);
  1048. addToArchive(surface, TERRAIN_FILE_NAMES[0]);
  1049. if(map->twoLevel)
  1050. {
  1051. JsonNode underground = writeTerrainLevel(1);
  1052. addToArchive(underground, TERRAIN_FILE_NAMES[1]);
  1053. }
  1054. }
  1055. void CMapSaverJson::writeObjects()
  1056. {
  1057. logGlobal->trace("Saving objects");
  1058. JsonNode data;
  1059. JsonSerializer handler(mapObjectResolver.get(), data);
  1060. for(const auto & obj : map->objects)
  1061. {
  1062. //logGlobal->trace("\t%s", obj->instanceName);
  1063. auto temp = handler.enterStruct(obj->instanceName);
  1064. obj->serializeJson(handler);
  1065. }
  1066. if(map->grailPos.isValid())
  1067. {
  1068. JsonNode grail;
  1069. grail["type"].String() = "grail";
  1070. grail["x"].Float() = map->grailPos.x;
  1071. grail["y"].Float() = map->grailPos.y;
  1072. grail["l"].Float() = map->grailPos.z;
  1073. grail["options"]["radius"].Float() = map->grailRadius;
  1074. std::string grailId = boost::str(boost::format("grail_%d") % map->objects.size());
  1075. data[grailId] = grail;
  1076. }
  1077. //cleanup empty options
  1078. for(auto & p : data.Struct())
  1079. {
  1080. JsonNode & obj = p.second;
  1081. if(obj["options"].Struct().empty())
  1082. obj.Struct().erase("options");
  1083. }
  1084. addToArchive(data, OBJECTS_FILE_NAME);
  1085. }
  1086. void CMapSaverJson::writeTranslations()
  1087. {
  1088. for(auto & s : mapHeader->translations.Struct())
  1089. {
  1090. auto & language = s.first;
  1091. if(Languages::getLanguageOptions(language).identifier.empty())
  1092. {
  1093. logGlobal->error("Serializing of unsupported language %s is not permitted", language);
  1094. continue;
  1095. }
  1096. logGlobal->trace("Saving translations, language: %s", language);
  1097. addToArchive(s.second, language + ".json");
  1098. }
  1099. }
  1100. VCMI_LIB_NAMESPACE_END