MapFormatJson.cpp 36 KB

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