JsonNode.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. /*
  2. * JsonNode.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 "JsonNode.h"
  12. #include "ScopeGuard.h"
  13. #include "HeroBonus.h"
  14. #include "filesystem/Filesystem.h"
  15. #include "VCMI_Lib.h" //for identifier resolution
  16. #include "CModHandler.h"
  17. #include "CGeneralTextHandler.h"
  18. #include "JsonDetail.h"
  19. using namespace JsonDetail;
  20. class LibClasses;
  21. class CModHandler;
  22. static const JsonNode nullNode;
  23. std::ostream & operator<<(std::ostream &out, const JsonNode &node)
  24. {
  25. JsonWriter writer(out, node);
  26. return out << "\n";
  27. }
  28. JsonNode::JsonNode(JsonType Type):
  29. type(DATA_NULL)
  30. {
  31. setType(Type);
  32. }
  33. JsonNode::JsonNode(const char *data, size_t datasize):
  34. type(DATA_NULL)
  35. {
  36. JsonParser parser(data, datasize);
  37. *this = parser.parse("<unknown>");
  38. }
  39. JsonNode::JsonNode(ResourceID && fileURI):
  40. type(DATA_NULL)
  41. {
  42. auto file = CResourceHandler::get()->load(fileURI)->readAll();
  43. JsonParser parser(reinterpret_cast<char*>(file.first.get()), file.second);
  44. *this = parser.parse(fileURI.getName());
  45. }
  46. JsonNode::JsonNode(const ResourceID & fileURI):
  47. type(DATA_NULL)
  48. {
  49. auto file = CResourceHandler::get()->load(fileURI)->readAll();
  50. JsonParser parser(reinterpret_cast<char*>(file.first.get()), file.second);
  51. *this = parser.parse(fileURI.getName());
  52. }
  53. JsonNode::JsonNode(ResourceID && fileURI, bool &isValidSyntax):
  54. type(DATA_NULL)
  55. {
  56. auto file = CResourceHandler::get()->load(fileURI)->readAll();
  57. JsonParser parser(reinterpret_cast<char*>(file.first.get()), file.second);
  58. *this = parser.parse(fileURI.getName());
  59. isValidSyntax = parser.isValid();
  60. }
  61. JsonNode::JsonNode(const JsonNode &copy):
  62. type(DATA_NULL),
  63. meta(copy.meta)
  64. {
  65. setType(copy.getType());
  66. switch(type)
  67. {
  68. break; case DATA_NULL:
  69. break; case DATA_BOOL: Bool() = copy.Bool();
  70. break; case DATA_FLOAT: Float() = copy.Float();
  71. break; case DATA_STRING: String() = copy.String();
  72. break; case DATA_VECTOR: Vector() = copy.Vector();
  73. break; case DATA_STRUCT: Struct() = copy.Struct();
  74. }
  75. }
  76. JsonNode::~JsonNode()
  77. {
  78. setType(DATA_NULL);
  79. }
  80. void JsonNode::swap(JsonNode &b)
  81. {
  82. using std::swap;
  83. swap(meta, b.meta);
  84. swap(data, b.data);
  85. swap(type, b.type);
  86. }
  87. JsonNode & JsonNode::operator =(JsonNode node)
  88. {
  89. swap(node);
  90. return *this;
  91. }
  92. bool JsonNode::operator == (const JsonNode &other) const
  93. {
  94. if (getType() == other.getType())
  95. {
  96. switch(type)
  97. {
  98. case DATA_NULL: return true;
  99. case DATA_BOOL: return Bool() == other.Bool();
  100. case DATA_FLOAT: return Float() == other.Float();
  101. case DATA_STRING: return String() == other.String();
  102. case DATA_VECTOR: return Vector() == other.Vector();
  103. case DATA_STRUCT: return Struct() == other.Struct();
  104. }
  105. }
  106. return false;
  107. }
  108. bool JsonNode::operator != (const JsonNode &other) const
  109. {
  110. return !(*this == other);
  111. }
  112. JsonNode::JsonType JsonNode::getType() const
  113. {
  114. return type;
  115. }
  116. void JsonNode::setMeta(std::string metadata, bool recursive)
  117. {
  118. meta = metadata;
  119. if (recursive)
  120. {
  121. switch (type)
  122. {
  123. break; case DATA_VECTOR:
  124. {
  125. for(auto & node : Vector())
  126. {
  127. node.setMeta(metadata);
  128. }
  129. }
  130. break; case DATA_STRUCT:
  131. {
  132. for(auto & node : Struct())
  133. {
  134. node.second.setMeta(metadata);
  135. }
  136. }
  137. }
  138. }
  139. }
  140. void JsonNode::setType(JsonType Type)
  141. {
  142. if (type == Type)
  143. return;
  144. //Reset node to nullptr
  145. if (Type != DATA_NULL)
  146. setType(DATA_NULL);
  147. switch (type)
  148. {
  149. break; case DATA_STRING: delete data.String;
  150. break; case DATA_VECTOR: delete data.Vector;
  151. break; case DATA_STRUCT: delete data.Struct;
  152. break; default:
  153. break;
  154. }
  155. //Set new node type
  156. type = Type;
  157. switch(type)
  158. {
  159. break; case DATA_NULL:
  160. break; case DATA_BOOL: data.Bool = false;
  161. break; case DATA_FLOAT: data.Float = 0;
  162. break; case DATA_STRING: data.String = new std::string();
  163. break; case DATA_VECTOR: data.Vector = new JsonVector();
  164. break; case DATA_STRUCT: data.Struct = new JsonMap();
  165. }
  166. }
  167. bool JsonNode::isNull() const
  168. {
  169. return type == DATA_NULL;
  170. }
  171. void JsonNode::clear()
  172. {
  173. setType(DATA_NULL);
  174. }
  175. bool & JsonNode::Bool()
  176. {
  177. setType(DATA_BOOL);
  178. return data.Bool;
  179. }
  180. double & JsonNode::Float()
  181. {
  182. setType(DATA_FLOAT);
  183. return data.Float;
  184. }
  185. std::string & JsonNode::String()
  186. {
  187. setType(DATA_STRING);
  188. return *data.String;
  189. }
  190. JsonVector & JsonNode::Vector()
  191. {
  192. setType(DATA_VECTOR);
  193. return *data.Vector;
  194. }
  195. JsonMap & JsonNode::Struct()
  196. {
  197. setType(DATA_STRUCT);
  198. return *data.Struct;
  199. }
  200. const bool boolDefault = false;
  201. const bool & JsonNode::Bool() const
  202. {
  203. if (type == DATA_NULL)
  204. return boolDefault;
  205. assert(type == DATA_BOOL);
  206. return data.Bool;
  207. }
  208. const double floatDefault = 0;
  209. const double & JsonNode::Float() const
  210. {
  211. if (type == DATA_NULL)
  212. return floatDefault;
  213. assert(type == DATA_FLOAT);
  214. return data.Float;
  215. }
  216. const std::string stringDefault = std::string();
  217. const std::string & JsonNode::String() const
  218. {
  219. if (type == DATA_NULL)
  220. return stringDefault;
  221. assert(type == DATA_STRING);
  222. return *data.String;
  223. }
  224. const JsonVector vectorDefault = JsonVector();
  225. const JsonVector & JsonNode::Vector() const
  226. {
  227. if (type == DATA_NULL)
  228. return vectorDefault;
  229. assert(type == DATA_VECTOR);
  230. return *data.Vector;
  231. }
  232. const JsonMap mapDefault = JsonMap();
  233. const JsonMap & JsonNode::Struct() const
  234. {
  235. if (type == DATA_NULL)
  236. return mapDefault;
  237. assert(type == DATA_STRUCT);
  238. return *data.Struct;
  239. }
  240. JsonNode & JsonNode::operator[](std::string child)
  241. {
  242. return Struct()[child];
  243. }
  244. const JsonNode & JsonNode::operator[](std::string child) const
  245. {
  246. auto it = Struct().find(child);
  247. if (it != Struct().end())
  248. return it->second;
  249. return nullNode;
  250. }
  251. // to avoid duplicating const and non-const code
  252. template<typename Node>
  253. Node & resolvePointer(Node & in, const std::string & pointer)
  254. {
  255. if (pointer.empty())
  256. return in;
  257. assert(pointer[0] == '/');
  258. size_t splitPos = pointer.find('/', 1);
  259. std::string entry = pointer.substr(1, splitPos -1);
  260. std::string remainer = splitPos == std::string::npos ? "" : pointer.substr(splitPos);
  261. if (in.getType() == JsonNode::DATA_VECTOR)
  262. {
  263. if (entry.find_first_not_of("0123456789") != std::string::npos) // non-numbers in string
  264. throw std::runtime_error("Invalid Json pointer");
  265. if (entry.size() > 1 && entry[0] == '0') // leading zeros are not allowed
  266. throw std::runtime_error("Invalid Json pointer");
  267. size_t index = boost::lexical_cast<size_t>(entry);
  268. if (in.Vector().size() > index)
  269. return in.Vector()[index].resolvePointer(remainer);
  270. }
  271. return in[entry].resolvePointer(remainer);
  272. }
  273. const JsonNode & JsonNode::resolvePointer(const std::string &jsonPointer) const
  274. {
  275. return ::resolvePointer(*this, jsonPointer);
  276. }
  277. JsonNode & JsonNode::resolvePointer(const std::string &jsonPointer)
  278. {
  279. return ::resolvePointer(*this, jsonPointer);
  280. }
  281. ///JsonUtils
  282. void JsonUtils::parseTypedBonusShort(const JsonVector& source, std::shared_ptr<Bonus> dest)
  283. {
  284. dest->val = source[1].Float();
  285. resolveIdentifier(source[2],dest->subtype);
  286. dest->additionalInfo = source[3].Float();
  287. dest->duration = Bonus::PERMANENT; //TODO: handle flags (as integer)
  288. dest->turnsRemain = 0;
  289. }
  290. std::shared_ptr<Bonus> JsonUtils::parseBonus (const JsonVector &ability_vec) //TODO: merge with AddAbility, create universal parser for all bonus properties
  291. {
  292. auto b = std::make_shared<Bonus>();
  293. std::string type = ability_vec[0].String();
  294. auto it = bonusNameMap.find(type);
  295. if (it == bonusNameMap.end())
  296. {
  297. logGlobal->errorStream() << "Error: invalid ability type " << type;
  298. return b;
  299. }
  300. b->type = it->second;
  301. parseTypedBonusShort(ability_vec, b);
  302. return b;
  303. }
  304. template <typename T>
  305. const T & parseByMap(const std::map<std::string, T> & map, const JsonNode * val, std::string err)
  306. {
  307. static T defaultValue = T();
  308. if (!val->isNull())
  309. {
  310. std::string type = val->String();
  311. auto it = map.find(type);
  312. if (it == map.end())
  313. {
  314. logGlobal->errorStream() << "Error: invalid " << err << type;
  315. return defaultValue;
  316. }
  317. else
  318. {
  319. return it->second;
  320. }
  321. }
  322. else
  323. return defaultValue;
  324. }
  325. void JsonUtils::resolveIdentifier(si32 &var, const JsonNode &node, std::string name)
  326. {
  327. const JsonNode &value = node[name];
  328. if (!value.isNull())
  329. {
  330. switch (value.getType())
  331. {
  332. case JsonNode::DATA_FLOAT:
  333. var = value.Float();
  334. break;
  335. case JsonNode::DATA_STRING:
  336. VLC->modh->identifiers.requestIdentifier(value, [&](si32 identifier)
  337. {
  338. var = identifier;
  339. });
  340. break;
  341. default:
  342. logGlobal->errorStream() << "Error! Wrong identifier used for value of " << name;
  343. }
  344. }
  345. }
  346. void JsonUtils::resolveIdentifier(const JsonNode &node, si32 &var)
  347. {
  348. switch (node.getType())
  349. {
  350. case JsonNode::DATA_FLOAT:
  351. var = node.Float();
  352. break;
  353. case JsonNode::DATA_STRING:
  354. VLC->modh->identifiers.requestIdentifier(node, [&](si32 identifier)
  355. {
  356. var = identifier;
  357. });
  358. break;
  359. default:
  360. logGlobal->errorStream() << "Error! Wrong identifier used for identifier!";
  361. }
  362. }
  363. std::shared_ptr<Bonus> JsonUtils::parseBonus(const JsonNode &ability)
  364. {
  365. auto b = std::make_shared<Bonus>();
  366. if (!parseBonus(ability, b.get()))
  367. {
  368. return nullptr;
  369. }
  370. return b;
  371. }
  372. bool JsonUtils::parseBonus(const JsonNode &ability, Bonus *b)
  373. {
  374. const JsonNode *value;
  375. std::string type = ability["type"].String();
  376. auto it = bonusNameMap.find(type);
  377. if (it == bonusNameMap.end())
  378. {
  379. logGlobal->errorStream() << "Error: invalid ability type " << type;
  380. return false;
  381. }
  382. b->type = it->second;
  383. resolveIdentifier(b->subtype, ability, "subtype");
  384. b->val = ability["val"].Float();
  385. value = &ability["valueType"];
  386. if (!value->isNull())
  387. b->valType = static_cast<Bonus::ValueType>(parseByMap(bonusValueMap, value, "value type "));
  388. resolveIdentifier(b->additionalInfo, ability, "addInfo");
  389. b->turnsRemain = ability["turns"].Float();
  390. b->sid = ability["sourceID"].Float();
  391. b->description = ability["description"].String();
  392. value = &ability["effectRange"];
  393. if (!value->isNull())
  394. b->effectRange = static_cast<Bonus::LimitEffect>(parseByMap(bonusLimitEffect, value, "effect range "));
  395. value = &ability["duration"];
  396. if (!value->isNull())
  397. {
  398. switch (value->getType())
  399. {
  400. case JsonNode::DATA_STRING:
  401. b->duration = parseByMap(bonusDurationMap, value, "duration type ");
  402. break;
  403. case JsonNode::DATA_VECTOR:
  404. {
  405. ui16 dur = 0;
  406. for (const JsonNode & d : value->Vector())
  407. {
  408. dur |= parseByMap(bonusDurationMap, &d, "duration type ");
  409. }
  410. b->duration = dur;
  411. }
  412. break;
  413. default:
  414. logGlobal->errorStream() << "Error! Wrong bonus duration format.";
  415. }
  416. }
  417. value = &ability["source"];
  418. if (!value->isNull())
  419. b->source = static_cast<Bonus::BonusSource>(parseByMap(bonusSourceMap, value, "source type "));
  420. value = &ability["limiters"];
  421. if (!value->isNull())
  422. {
  423. for (const JsonNode & limiter : value->Vector())
  424. {
  425. switch (limiter.getType())
  426. {
  427. case JsonNode::DATA_STRING: //pre-defined limiters
  428. b->limiter = parseByMap(bonusLimiterMap, &limiter, "limiter type ");
  429. break;
  430. case JsonNode::DATA_STRUCT: //customizable limiters
  431. {
  432. std::shared_ptr<ILimiter> l;
  433. if (limiter["type"].String() == "CREATURE_TYPE_LIMITER")
  434. {
  435. std::shared_ptr<CCreatureTypeLimiter> l2 = std::make_shared<CCreatureTypeLimiter>(); //TODO: How the hell resolve pointer to creature?
  436. const JsonVector vec = limiter["parameters"].Vector();
  437. VLC->modh->identifiers.requestIdentifier("creature", vec[0], [=](si32 creature)
  438. {
  439. l2->setCreature(CreatureID(creature));
  440. });
  441. if (vec.size() > 1)
  442. {
  443. l2->includeUpgrades = vec[1].Bool();
  444. }
  445. else
  446. l2->includeUpgrades = false;
  447. l = l2;
  448. }
  449. if (limiter["type"].String() == "HAS_ANOTHER_BONUS_LIMITER")
  450. {
  451. std::shared_ptr<HasAnotherBonusLimiter> l2 = std::make_shared<HasAnotherBonusLimiter>();
  452. const JsonVector vec = limiter["parameters"].Vector();
  453. std::string anotherBonusType = vec[0].String();
  454. auto it = bonusNameMap.find(anotherBonusType);
  455. if (it == bonusNameMap.end())
  456. {
  457. logGlobal->errorStream() << "Error: invalid ability type " << anotherBonusType;
  458. continue;
  459. }
  460. l2->type = it->second;
  461. if (vec.size() > 1 )
  462. {
  463. resolveIdentifier(vec[1], l2->subtype);
  464. l2->isSubtypeRelevant = true;
  465. }
  466. l = l2;
  467. }
  468. b->addLimiter(l);
  469. }
  470. break;
  471. }
  472. }
  473. }
  474. value = &ability["propagator"];
  475. if (!value->isNull())
  476. b->propagator = parseByMap(bonusPropagatorMap, value, "propagator type ");
  477. return true;
  478. }
  479. //returns first Key with value equal to given one
  480. template<class Key, class Val>
  481. Key reverseMapFirst(const Val & val, const std::map<Key, Val> & map)
  482. {
  483. for(auto it : map)
  484. {
  485. if(it.second == val)
  486. {
  487. return it.first;
  488. }
  489. }
  490. assert(0);
  491. return "";
  492. }
  493. void JsonUtils::unparseBonus( JsonNode &node, const std::shared_ptr<Bonus>& bonus )
  494. {
  495. node["type"].String() = reverseMapFirst<std::string, Bonus::BonusType>(bonus->type, bonusNameMap);
  496. node["subtype"].Float() = bonus->subtype;
  497. node["val"].Float() = bonus->val;
  498. node["valueType"].String() = reverseMapFirst<std::string, Bonus::ValueType>(bonus->valType, bonusValueMap);
  499. node["additionalInfo"].Float() = bonus->additionalInfo;
  500. node["turns"].Float() = bonus->turnsRemain;
  501. node["sourceID"].Float() = bonus->source;
  502. node["description"].String() = bonus->description;
  503. node["effectRange"].String() = reverseMapFirst<std::string, Bonus::LimitEffect>(bonus->effectRange, bonusLimitEffect);
  504. node["duration"].String() = reverseMapFirst<std::string, ui16>(bonus->duration, bonusDurationMap);
  505. node["source"].String() = reverseMapFirst<std::string, Bonus::BonusSource>(bonus->source, bonusSourceMap);
  506. if(bonus->limiter)
  507. {
  508. node["limiter"].String() = reverseMapFirst<std::string, TLimiterPtr>(bonus->limiter, bonusLimiterMap);
  509. }
  510. if(bonus->propagator)
  511. {
  512. node["propagator"].String() = reverseMapFirst<std::string, TPropagatorPtr>(bonus->propagator, bonusPropagatorMap);
  513. }
  514. }
  515. void minimizeNode(JsonNode & node, const JsonNode & schema)
  516. {
  517. if (schema["type"].String() == "object")
  518. {
  519. std::set<std::string> foundEntries;
  520. for(auto & entry : schema["required"].Vector())
  521. {
  522. std::string name = entry.String();
  523. foundEntries.insert(name);
  524. minimizeNode(node[name], schema["properties"][name]);
  525. if (vstd::contains(node.Struct(), name) &&
  526. node[name] == schema["properties"][name]["default"])
  527. {
  528. node.Struct().erase(name);
  529. }
  530. }
  531. // erase all unhandled entries
  532. for (auto it = node.Struct().begin(); it != node.Struct().end();)
  533. {
  534. if (!vstd::contains(foundEntries, it->first))
  535. it = node.Struct().erase(it);
  536. else
  537. it++;
  538. }
  539. }
  540. }
  541. void JsonUtils::minimize(JsonNode & node, std::string schemaName)
  542. {
  543. minimizeNode(node, getSchema(schemaName));
  544. }
  545. // FIXME: except for several lines function is identical to minimizeNode. Some way to reduce duplication?
  546. void maximizeNode(JsonNode & node, const JsonNode & schema)
  547. {
  548. // "required" entry can only be found in object/struct
  549. if (schema["type"].String() == "object")
  550. {
  551. std::set<std::string> foundEntries;
  552. // check all required entries that have default version
  553. for(auto & entry : schema["required"].Vector())
  554. {
  555. std::string name = entry.String();
  556. foundEntries.insert(name);
  557. if (node[name].isNull() &&
  558. !schema["properties"][name]["default"].isNull())
  559. {
  560. node[name] = schema["properties"][name]["default"];
  561. }
  562. maximizeNode(node[name], schema["properties"][name]);
  563. }
  564. // erase all unhandled entries
  565. for (auto it = node.Struct().begin(); it != node.Struct().end();)
  566. {
  567. if (!vstd::contains(foundEntries, it->first))
  568. it = node.Struct().erase(it);
  569. else
  570. it++;
  571. }
  572. }
  573. }
  574. void JsonUtils::maximize(JsonNode & node, std::string schemaName)
  575. {
  576. maximizeNode(node, getSchema(schemaName));
  577. }
  578. bool JsonUtils::validate(const JsonNode &node, std::string schemaName, std::string dataName)
  579. {
  580. std::string log = Validation::check(schemaName, node);
  581. if (!log.empty())
  582. {
  583. logGlobal->warnStream() << "Data in " << dataName << " is invalid!";
  584. logGlobal->warnStream() << log;
  585. }
  586. return log.empty();
  587. }
  588. const JsonNode & getSchemaByName(std::string name)
  589. {
  590. // cached schemas to avoid loading json data multiple times
  591. static std::map<std::string, JsonNode> loadedSchemas;
  592. if (vstd::contains(loadedSchemas, name))
  593. return loadedSchemas[name];
  594. std::string filename = "config/schemas/" + name + ".json";
  595. if (CResourceHandler::get()->existsResource(ResourceID(filename)))
  596. {
  597. loadedSchemas[name] = JsonNode(ResourceID(filename));
  598. return loadedSchemas[name];
  599. }
  600. logGlobal->errorStream() << "Error: missing schema with name " << name << "!";
  601. assert(0);
  602. return nullNode;
  603. }
  604. const JsonNode & JsonUtils::getSchema(std::string URI)
  605. {
  606. std::vector<std::string> segments;
  607. size_t posColon = URI.find(':');
  608. size_t posHash = URI.find('#');
  609. assert(posColon != std::string::npos);
  610. std::string protocolName = URI.substr(0, posColon);
  611. std::string filename = URI.substr(posColon + 1, posHash - posColon - 1);
  612. if (protocolName != "vcmi")
  613. {
  614. logGlobal->errorStream() << "Error: unsupported URI protocol for schema: " << segments[0];
  615. return nullNode;
  616. }
  617. // check if json pointer if present (section after hash in string)
  618. if (posHash == std::string::npos || posHash == URI.size() - 1)
  619. return getSchemaByName(filename);
  620. else
  621. return getSchemaByName(filename).resolvePointer(URI.substr(posHash + 1));
  622. }
  623. void JsonUtils::merge(JsonNode & dest, JsonNode & source)
  624. {
  625. if (dest.getType() == JsonNode::DATA_NULL)
  626. {
  627. std::swap(dest, source);
  628. return;
  629. }
  630. switch (source.getType())
  631. {
  632. case JsonNode::DATA_NULL:
  633. {
  634. dest.clear();
  635. break;
  636. }
  637. case JsonNode::DATA_BOOL:
  638. case JsonNode::DATA_FLOAT:
  639. case JsonNode::DATA_STRING:
  640. case JsonNode::DATA_VECTOR:
  641. {
  642. std::swap(dest, source);
  643. break;
  644. }
  645. case JsonNode::DATA_STRUCT:
  646. {
  647. //recursively merge all entries from struct
  648. for(auto & node : source.Struct())
  649. merge(dest[node.first], node.second);
  650. }
  651. }
  652. }
  653. void JsonUtils::mergeCopy(JsonNode & dest, JsonNode source)
  654. {
  655. // uses copy created in stack to safely merge two nodes
  656. merge(dest, source);
  657. }
  658. void JsonUtils::inherit(JsonNode & descendant, const JsonNode & base)
  659. {
  660. JsonNode inheritedNode(base);
  661. merge(inheritedNode,descendant);
  662. descendant.swap(inheritedNode);
  663. }
  664. JsonNode JsonUtils::assembleFromFiles(std::vector<std::string> files)
  665. {
  666. bool isValid;
  667. return assembleFromFiles(files, isValid);
  668. }
  669. JsonNode JsonUtils::assembleFromFiles(std::vector<std::string> files, bool &isValid)
  670. {
  671. isValid = true;
  672. JsonNode result;
  673. for(std::string file : files)
  674. {
  675. bool isValidFile;
  676. JsonNode section(ResourceID(file, EResType::TEXT), isValidFile);
  677. merge(result, section);
  678. isValid |= isValidFile;
  679. }
  680. return result;
  681. }
  682. JsonNode JsonUtils::assembleFromFiles(std::string filename)
  683. {
  684. JsonNode result;
  685. ResourceID resID(filename, EResType::TEXT);
  686. for(auto & loader : CResourceHandler::get()->getResourcesWithName(resID))
  687. {
  688. // FIXME: some way to make this code more readable
  689. auto stream = loader->load(resID);
  690. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  691. stream->read(textData.get(), stream->getSize());
  692. JsonNode section((char*)textData.get(), stream->getSize());
  693. merge(result, section);
  694. }
  695. return result;
  696. }