JsonNode.cpp 21 KB

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