MapFormatJson.cpp 36 KB

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