MapFormatJson.cpp 35 KB

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