JsonNode.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  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, 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. Bonus * JsonUtils::parseBonus (const JsonVector &ability_vec) //TODO: merge with AddAbility, create universal parser for all bonus properties
  291. {
  292. auto b = new 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. Bonus * JsonUtils::parseBonus (const JsonNode &ability)
  364. {
  365. auto b = new Bonus();
  366. const JsonNode *value;
  367. std::string type = ability["type"].String();
  368. auto it = bonusNameMap.find(type);
  369. if (it == bonusNameMap.end())
  370. {
  371. logGlobal->errorStream() << "Error: invalid ability type " << type;
  372. return b;
  373. }
  374. b->type = it->second;
  375. resolveIdentifier (b->subtype, ability, "subtype");
  376. b->val = ability["val"].Float();
  377. value = &ability["valueType"];
  378. if (!value->isNull())
  379. b->valType = static_cast<Bonus::ValueType>(parseByMap(bonusValueMap, value, "value type "));
  380. resolveIdentifier (b->additionalInfo, ability, "addInfo");
  381. b->turnsRemain = ability["turns"].Float();
  382. b->sid = ability["sourceID"].Float();
  383. b->description = ability["description"].String();
  384. value = &ability["effectRange"];
  385. if (!value->isNull())
  386. b->effectRange = static_cast<Bonus::LimitEffect>(parseByMap(bonusLimitEffect, value, "effect range "));
  387. value = &ability["duration"];
  388. if (!value->isNull())
  389. {
  390. switch (value->getType())
  391. {
  392. case JsonNode::DATA_STRING:
  393. b->duration = parseByMap(bonusDurationMap, value, "duration type ");
  394. break;
  395. case JsonNode::DATA_VECTOR:
  396. {
  397. ui16 dur = 0;
  398. for (const JsonNode & d : value->Vector())
  399. {
  400. dur |= parseByMap(bonusDurationMap, &d, "duration type ");
  401. }
  402. b->duration = dur;
  403. }
  404. break;
  405. default:
  406. logGlobal->errorStream() << "Error! Wrong bonus duration format.";
  407. }
  408. }
  409. value = &ability["source"];
  410. if (!value->isNull())
  411. b->source = static_cast<Bonus::BonusSource>(parseByMap(bonusSourceMap, value, "source type "));
  412. value = &ability["limiters"];
  413. if (!value->isNull())
  414. {
  415. for (const JsonNode & limiter : value->Vector())
  416. {
  417. switch (limiter.getType())
  418. {
  419. case JsonNode::DATA_STRING: //pre-defined limiters
  420. b->limiter = parseByMap(bonusLimiterMap, &limiter, "limiter type ");
  421. break;
  422. case JsonNode::DATA_STRUCT: //customizable limiters
  423. {
  424. std::shared_ptr<ILimiter> l;
  425. if (limiter["type"].String() == "CREATURE_TYPE_LIMITER")
  426. {
  427. std::shared_ptr<CCreatureTypeLimiter> l2 = std::make_shared<CCreatureTypeLimiter>(); //TODO: How the hell resolve pointer to creature?
  428. const JsonVector vec = limiter["parameters"].Vector();
  429. VLC->modh->identifiers.requestIdentifier("creature", vec[0], [=](si32 creature)
  430. {
  431. l2->setCreature (CreatureID(creature));
  432. });
  433. if (vec.size() > 1)
  434. {
  435. l2->includeUpgrades = vec[1].Bool();
  436. }
  437. else
  438. l2->includeUpgrades = false;
  439. l = l2;
  440. }
  441. if (limiter["type"].String() == "HAS_ANOTHER_BONUS_LIMITER")
  442. {
  443. std::shared_ptr<HasAnotherBonusLimiter> l2 = std::make_shared<HasAnotherBonusLimiter>();
  444. const JsonVector vec = limiter["parameters"].Vector();
  445. std::string anotherBonusType = vec[0].String();
  446. auto it = bonusNameMap.find (anotherBonusType);
  447. if (it == bonusNameMap.end())
  448. {
  449. logGlobal->errorStream() << "Error: invalid ability type " << anotherBonusType;
  450. continue;
  451. }
  452. l2->type = it->second;
  453. if (vec.size() > 1 )
  454. {
  455. resolveIdentifier (vec[1], l2->subtype);
  456. l2->isSubtypeRelevant = true;
  457. }
  458. l = l2;
  459. }
  460. b->addLimiter(l);
  461. }
  462. break;
  463. }
  464. }
  465. }
  466. value = &ability["propagator"];
  467. if (!value->isNull())
  468. b->propagator = parseByMap(bonusPropagatorMap, value, "propagator type ");
  469. return b;
  470. }
  471. //returns first Key with value equal to given one
  472. template<class Key, class Val>
  473. Key reverseMapFirst(const Val & val, const std::map<Key, Val> & map)
  474. {
  475. for(auto it : map)
  476. {
  477. if(it.second == val)
  478. {
  479. return it.first;
  480. }
  481. }
  482. assert(0);
  483. return "";
  484. }
  485. void JsonUtils::unparseBonus( JsonNode &node, const Bonus * bonus )
  486. {
  487. node["type"].String() = reverseMapFirst<std::string, Bonus::BonusType>(bonus->type, bonusNameMap);
  488. node["subtype"].Float() = bonus->subtype;
  489. node["val"].Float() = bonus->val;
  490. node["valueType"].String() = reverseMapFirst<std::string, Bonus::ValueType>(bonus->valType, bonusValueMap);
  491. node["additionalInfo"].Float() = bonus->additionalInfo;
  492. node["turns"].Float() = bonus->turnsRemain;
  493. node["sourceID"].Float() = bonus->source;
  494. node["description"].String() = bonus->description;
  495. node["effectRange"].String() = reverseMapFirst<std::string, Bonus::LimitEffect>(bonus->effectRange, bonusLimitEffect);
  496. node["duration"].String() = reverseMapFirst<std::string, ui16>(bonus->duration, bonusDurationMap);
  497. node["source"].String() = reverseMapFirst<std::string, Bonus::BonusSource>(bonus->source, bonusSourceMap);
  498. if(bonus->limiter)
  499. {
  500. node["limiter"].String() = reverseMapFirst<std::string, TLimiterPtr>(bonus->limiter, bonusLimiterMap);
  501. }
  502. if(bonus->propagator)
  503. {
  504. node["propagator"].String() = reverseMapFirst<std::string, TPropagatorPtr>(bonus->propagator, bonusPropagatorMap);
  505. }
  506. }
  507. void minimizeNode(JsonNode & node, const JsonNode & schema)
  508. {
  509. if (schema["type"].String() == "object")
  510. {
  511. std::set<std::string> foundEntries;
  512. for(auto & entry : schema["required"].Vector())
  513. {
  514. std::string name = entry.String();
  515. foundEntries.insert(name);
  516. minimizeNode(node[name], schema["properties"][name]);
  517. if (vstd::contains(node.Struct(), name) &&
  518. node[name] == schema["properties"][name]["default"])
  519. {
  520. node.Struct().erase(name);
  521. }
  522. }
  523. // erase all unhandled entries
  524. for (auto it = node.Struct().begin(); it != node.Struct().end();)
  525. {
  526. if (!vstd::contains(foundEntries, it->first))
  527. it = node.Struct().erase(it);
  528. else
  529. it++;
  530. }
  531. }
  532. }
  533. void JsonUtils::minimize(JsonNode & node, std::string schemaName)
  534. {
  535. minimizeNode(node, getSchema(schemaName));
  536. }
  537. // FIXME: except for several lines function is identical to minimizeNode. Some way to reduce duplication?
  538. void maximizeNode(JsonNode & node, const JsonNode & schema)
  539. {
  540. // "required" entry can only be found in object/struct
  541. if (schema["type"].String() == "object")
  542. {
  543. std::set<std::string> foundEntries;
  544. // check all required entries that have default version
  545. for(auto & entry : schema["required"].Vector())
  546. {
  547. std::string name = entry.String();
  548. foundEntries.insert(name);
  549. if (node[name].isNull() &&
  550. !schema["properties"][name]["default"].isNull())
  551. {
  552. node[name] = schema["properties"][name]["default"];
  553. }
  554. maximizeNode(node[name], schema["properties"][name]);
  555. }
  556. // erase all unhandled entries
  557. for (auto it = node.Struct().begin(); it != node.Struct().end();)
  558. {
  559. if (!vstd::contains(foundEntries, it->first))
  560. it = node.Struct().erase(it);
  561. else
  562. it++;
  563. }
  564. }
  565. }
  566. void JsonUtils::maximize(JsonNode & node, std::string schemaName)
  567. {
  568. maximizeNode(node, getSchema(schemaName));
  569. }
  570. bool JsonUtils::validate(const JsonNode &node, std::string schemaName, std::string dataName)
  571. {
  572. std::string log = Validation::check(schemaName, node);
  573. if (!log.empty())
  574. {
  575. logGlobal->warnStream() << "Data in " << dataName << " is invalid!";
  576. logGlobal->warnStream() << log;
  577. }
  578. return log.empty();
  579. }
  580. const JsonNode & getSchemaByName(std::string name)
  581. {
  582. // cached schemas to avoid loading json data multiple times
  583. static std::map<std::string, JsonNode> loadedSchemas;
  584. if (vstd::contains(loadedSchemas, name))
  585. return loadedSchemas[name];
  586. std::string filename = "config/schemas/" + name + ".json";
  587. if (CResourceHandler::get()->existsResource(ResourceID(filename)))
  588. {
  589. loadedSchemas[name] = JsonNode(ResourceID(filename));
  590. return loadedSchemas[name];
  591. }
  592. logGlobal->errorStream() << "Error: missing schema with name " << name << "!";
  593. assert(0);
  594. return nullNode;
  595. }
  596. const JsonNode & JsonUtils::getSchema(std::string URI)
  597. {
  598. std::vector<std::string> segments;
  599. size_t posColon = URI.find(':');
  600. size_t posHash = URI.find('#');
  601. assert(posColon != std::string::npos);
  602. std::string protocolName = URI.substr(0, posColon);
  603. std::string filename = URI.substr(posColon + 1, posHash - posColon - 1);
  604. if (protocolName != "vcmi")
  605. {
  606. logGlobal->errorStream() << "Error: unsupported URI protocol for schema: " << segments[0];
  607. return nullNode;
  608. }
  609. // check if json pointer if present (section after hash in string)
  610. if (posHash == std::string::npos || posHash == URI.size() - 1)
  611. return getSchemaByName(filename);
  612. else
  613. return getSchemaByName(filename).resolvePointer(URI.substr(posHash + 1));
  614. }
  615. void JsonUtils::merge(JsonNode & dest, JsonNode & source)
  616. {
  617. if (dest.getType() == JsonNode::DATA_NULL)
  618. {
  619. std::swap(dest, source);
  620. return;
  621. }
  622. switch (source.getType())
  623. {
  624. case JsonNode::DATA_NULL:
  625. {
  626. dest.clear();
  627. break;
  628. }
  629. case JsonNode::DATA_BOOL:
  630. case JsonNode::DATA_FLOAT:
  631. case JsonNode::DATA_STRING:
  632. case JsonNode::DATA_VECTOR:
  633. {
  634. std::swap(dest, source);
  635. break;
  636. }
  637. case JsonNode::DATA_STRUCT:
  638. {
  639. //recursively merge all entries from struct
  640. for(auto & node : source.Struct())
  641. merge(dest[node.first], node.second);
  642. }
  643. }
  644. }
  645. void JsonUtils::mergeCopy(JsonNode & dest, JsonNode source)
  646. {
  647. // uses copy created in stack to safely merge two nodes
  648. merge(dest, source);
  649. }
  650. void JsonUtils::inherit(JsonNode & descendant, const JsonNode & base)
  651. {
  652. JsonNode inheritedNode(base);
  653. merge(inheritedNode,descendant);
  654. descendant.swap(inheritedNode);
  655. }
  656. JsonNode JsonUtils::assembleFromFiles(std::vector<std::string> files)
  657. {
  658. bool isValid;
  659. return assembleFromFiles(files, isValid);
  660. }
  661. JsonNode JsonUtils::assembleFromFiles(std::vector<std::string> files, bool &isValid)
  662. {
  663. isValid = true;
  664. JsonNode result;
  665. for(std::string file : files)
  666. {
  667. bool isValidFile;
  668. JsonNode section(ResourceID(file, EResType::TEXT), isValidFile);
  669. merge(result, section);
  670. isValid |= isValidFile;
  671. }
  672. return result;
  673. }
  674. JsonNode JsonUtils::assembleFromFiles(std::string filename)
  675. {
  676. JsonNode result;
  677. ResourceID resID(filename, EResType::TEXT);
  678. for(auto & loader : CResourceHandler::get()->getResourcesWithName(resID))
  679. {
  680. // FIXME: some way to make this code more readable
  681. auto stream = loader->load(resID);
  682. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  683. stream->read(textData.get(), stream->getSize());
  684. JsonNode section((char*)textData.get(), stream->getSize());
  685. merge(result, section);
  686. }
  687. return result;
  688. }