JsonNode.cpp 19 KB

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