JsonNode.cpp 21 KB

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