JsonNode.cpp 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  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(JsonType::DATA_NULL)
  25. {
  26. setType(Type);
  27. }
  28. JsonNode::JsonNode(const char *data, size_t datasize):
  29. type(JsonType::DATA_NULL)
  30. {
  31. JsonParser parser(data, datasize);
  32. *this = parser.parse("<unknown>");
  33. }
  34. JsonNode::JsonNode(ResourceID && fileURI):
  35. type(JsonType::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(JsonType::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(JsonType::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(JsonType::DATA_NULL),
  58. meta(copy.meta),
  59. flags(copy.flags)
  60. {
  61. setType(copy.getType());
  62. switch(type)
  63. {
  64. break; case JsonType::DATA_NULL:
  65. break; case JsonType::DATA_BOOL: Bool() = copy.Bool();
  66. break; case JsonType::DATA_FLOAT: Float() = copy.Float();
  67. break; case JsonType::DATA_STRING: String() = copy.String();
  68. break; case JsonType::DATA_VECTOR: Vector() = copy.Vector();
  69. break; case JsonType::DATA_STRUCT: Struct() = copy.Struct();
  70. break; case JsonType::DATA_INTEGER:Integer() = copy.Integer();
  71. }
  72. }
  73. JsonNode::~JsonNode()
  74. {
  75. setType(JsonType::DATA_NULL);
  76. }
  77. void JsonNode::swap(JsonNode &b)
  78. {
  79. using std::swap;
  80. swap(meta, b.meta);
  81. swap(data, b.data);
  82. swap(type, b.type);
  83. swap(flags, b.flags);
  84. }
  85. JsonNode & JsonNode::operator =(JsonNode node)
  86. {
  87. swap(node);
  88. return *this;
  89. }
  90. bool JsonNode::operator == (const JsonNode &other) const
  91. {
  92. if (getType() == other.getType())
  93. {
  94. switch(type)
  95. {
  96. case JsonType::DATA_NULL: return true;
  97. case JsonType::DATA_BOOL: return Bool() == other.Bool();
  98. case JsonType::DATA_FLOAT: return Float() == other.Float();
  99. case JsonType::DATA_STRING: return String() == other.String();
  100. case JsonType::DATA_VECTOR: return Vector() == other.Vector();
  101. case JsonType::DATA_STRUCT: return Struct() == other.Struct();
  102. case JsonType::DATA_INTEGER:return Integer()== other.Integer();
  103. }
  104. }
  105. return false;
  106. }
  107. bool JsonNode::operator != (const JsonNode &other) const
  108. {
  109. return !(*this == other);
  110. }
  111. JsonNode::JsonType JsonNode::getType() const
  112. {
  113. return type;
  114. }
  115. void JsonNode::setMeta(std::string metadata, bool recursive)
  116. {
  117. meta = metadata;
  118. if (recursive)
  119. {
  120. switch (type)
  121. {
  122. break; case JsonType::DATA_VECTOR:
  123. {
  124. for(auto & node : Vector())
  125. {
  126. node.setMeta(metadata);
  127. }
  128. }
  129. break; case JsonType::DATA_STRUCT:
  130. {
  131. for(auto & node : Struct())
  132. {
  133. node.second.setMeta(metadata);
  134. }
  135. }
  136. }
  137. }
  138. }
  139. void JsonNode::setType(JsonType Type)
  140. {
  141. if (type == Type)
  142. return;
  143. //float<->int conversion
  144. if(type == JsonType::DATA_FLOAT && Type == JsonType::DATA_INTEGER)
  145. {
  146. si64 converted = data.Float;
  147. type = Type;
  148. data.Integer = converted;
  149. return;
  150. }
  151. else if(type == JsonType::DATA_INTEGER && Type == JsonType::DATA_FLOAT)
  152. {
  153. double converted = data.Integer;
  154. type = Type;
  155. data.Float = converted;
  156. return;
  157. }
  158. //Reset node to nullptr
  159. if (Type != JsonType::DATA_NULL)
  160. setType(JsonType::DATA_NULL);
  161. switch (type)
  162. {
  163. break; case JsonType::DATA_STRING: delete data.String;
  164. break; case JsonType::DATA_VECTOR: delete data.Vector;
  165. break; case JsonType::DATA_STRUCT: delete data.Struct;
  166. break; default:
  167. break;
  168. }
  169. //Set new node type
  170. type = Type;
  171. switch(type)
  172. {
  173. break; case JsonType::DATA_NULL:
  174. break; case JsonType::DATA_BOOL: data.Bool = false;
  175. break; case JsonType::DATA_FLOAT: data.Float = 0;
  176. break; case JsonType::DATA_STRING: data.String = new std::string();
  177. break; case JsonType::DATA_VECTOR: data.Vector = new JsonVector();
  178. break; case JsonType::DATA_STRUCT: data.Struct = new JsonMap();
  179. break; case JsonType::DATA_INTEGER: data.Integer = 0;
  180. }
  181. }
  182. bool JsonNode::isNull() const
  183. {
  184. return type == JsonType::DATA_NULL;
  185. }
  186. bool JsonNode::isNumber() const
  187. {
  188. return type == JsonType::DATA_INTEGER || type == JsonType::DATA_FLOAT;
  189. }
  190. bool JsonNode::containsBaseData() const
  191. {
  192. switch(type)
  193. {
  194. case JsonType::DATA_NULL:
  195. return false;
  196. case JsonType::DATA_STRUCT:
  197. for(auto elem : *data.Struct)
  198. {
  199. if(elem.second.containsBaseData())
  200. return true;
  201. }
  202. return false;
  203. default:
  204. //other types (including vector) cannot be extended via merge
  205. return true;
  206. }
  207. }
  208. bool JsonNode::isCompact() const
  209. {
  210. switch(type)
  211. {
  212. case JsonType::DATA_VECTOR:
  213. for(JsonNode & elem : *data.Vector)
  214. {
  215. if(!elem.isCompact())
  216. return false;
  217. }
  218. return true;
  219. case JsonType::DATA_STRUCT:
  220. {
  221. int propertyCount = data.Struct->size();
  222. if(propertyCount == 0)
  223. return true;
  224. else if(propertyCount == 1)
  225. return data.Struct->begin()->second.isCompact();
  226. }
  227. return false;
  228. default:
  229. return true;
  230. }
  231. }
  232. void JsonNode::clear()
  233. {
  234. setType(JsonType::DATA_NULL);
  235. }
  236. bool & JsonNode::Bool()
  237. {
  238. setType(JsonType::DATA_BOOL);
  239. return data.Bool;
  240. }
  241. double & JsonNode::Float()
  242. {
  243. setType(JsonType::DATA_FLOAT);
  244. return data.Float;
  245. }
  246. si64 & JsonNode::Integer()
  247. {
  248. setType(JsonType::DATA_INTEGER);
  249. return data.Integer;
  250. }
  251. std::string & JsonNode::String()
  252. {
  253. setType(JsonType::DATA_STRING);
  254. return *data.String;
  255. }
  256. JsonVector & JsonNode::Vector()
  257. {
  258. setType(JsonType::DATA_VECTOR);
  259. return *data.Vector;
  260. }
  261. JsonMap & JsonNode::Struct()
  262. {
  263. setType(JsonType::DATA_STRUCT);
  264. return *data.Struct;
  265. }
  266. const bool boolDefault = false;
  267. bool JsonNode::Bool() const
  268. {
  269. if (type == JsonType::DATA_NULL)
  270. return boolDefault;
  271. assert(type == JsonType::DATA_BOOL);
  272. return data.Bool;
  273. }
  274. const double floatDefault = 0;
  275. double JsonNode::Float() const
  276. {
  277. if(type == JsonType::DATA_NULL)
  278. return floatDefault;
  279. else if(type == JsonType::DATA_INTEGER)
  280. return data.Integer;
  281. assert(type == JsonType::DATA_FLOAT);
  282. return data.Float;
  283. }
  284. const si64 integetDefault = 0;
  285. si64 JsonNode::Integer() const
  286. {
  287. if(type == JsonType::DATA_NULL)
  288. return integetDefault;
  289. else if(type == JsonType::DATA_FLOAT)
  290. return data.Float;
  291. assert(type == JsonType::DATA_INTEGER);
  292. return data.Integer;
  293. }
  294. const std::string stringDefault = std::string();
  295. const std::string & JsonNode::String() const
  296. {
  297. if (type == JsonType::DATA_NULL)
  298. return stringDefault;
  299. assert(type == JsonType::DATA_STRING);
  300. return *data.String;
  301. }
  302. const JsonVector vectorDefault = JsonVector();
  303. const JsonVector & JsonNode::Vector() const
  304. {
  305. if (type == JsonType::DATA_NULL)
  306. return vectorDefault;
  307. assert(type == JsonType::DATA_VECTOR);
  308. return *data.Vector;
  309. }
  310. const JsonMap mapDefault = JsonMap();
  311. const JsonMap & JsonNode::Struct() const
  312. {
  313. if (type == JsonType::DATA_NULL)
  314. return mapDefault;
  315. assert(type == JsonType::DATA_STRUCT);
  316. return *data.Struct;
  317. }
  318. JsonNode & JsonNode::operator[](std::string child)
  319. {
  320. return Struct()[child];
  321. }
  322. const JsonNode & JsonNode::operator[](std::string child) const
  323. {
  324. auto it = Struct().find(child);
  325. if (it != Struct().end())
  326. return it->second;
  327. return nullNode;
  328. }
  329. // to avoid duplicating const and non-const code
  330. template<typename Node>
  331. Node & resolvePointer(Node & in, const std::string & pointer)
  332. {
  333. if (pointer.empty())
  334. return in;
  335. assert(pointer[0] == '/');
  336. size_t splitPos = pointer.find('/', 1);
  337. std::string entry = pointer.substr(1, splitPos -1);
  338. std::string remainer = splitPos == std::string::npos ? "" : pointer.substr(splitPos);
  339. if (in.getType() == JsonNode::JsonType::DATA_VECTOR)
  340. {
  341. if (entry.find_first_not_of("0123456789") != std::string::npos) // non-numbers in string
  342. throw std::runtime_error("Invalid Json pointer");
  343. if (entry.size() > 1 && entry[0] == '0') // leading zeros are not allowed
  344. throw std::runtime_error("Invalid Json pointer");
  345. size_t index = boost::lexical_cast<size_t>(entry);
  346. if (in.Vector().size() > index)
  347. return in.Vector()[index].resolvePointer(remainer);
  348. }
  349. return in[entry].resolvePointer(remainer);
  350. }
  351. const JsonNode & JsonNode::resolvePointer(const std::string &jsonPointer) const
  352. {
  353. return ::resolvePointer(*this, jsonPointer);
  354. }
  355. JsonNode & JsonNode::resolvePointer(const std::string &jsonPointer)
  356. {
  357. return ::resolvePointer(*this, jsonPointer);
  358. }
  359. std::string JsonNode::toJson(bool compact) const
  360. {
  361. std::ostringstream out;
  362. JsonWriter writer(out, compact);
  363. writer.writeNode(*this);
  364. return out.str();
  365. }
  366. ///JsonUtils
  367. void JsonUtils::parseTypedBonusShort(const JsonVector& source, std::shared_ptr<Bonus> dest)
  368. {
  369. dest->val = source[1].Float();
  370. resolveIdentifier(source[2],dest->subtype);
  371. dest->additionalInfo = source[3].Float();
  372. dest->duration = Bonus::PERMANENT; //TODO: handle flags (as integer)
  373. dest->turnsRemain = 0;
  374. }
  375. std::shared_ptr<Bonus> JsonUtils::parseBonus (const JsonVector &ability_vec) //TODO: merge with AddAbility, create universal parser for all bonus properties
  376. {
  377. auto b = std::make_shared<Bonus>();
  378. std::string type = ability_vec[0].String();
  379. auto it = bonusNameMap.find(type);
  380. if (it == bonusNameMap.end())
  381. {
  382. logMod->error("Error: invalid ability type %s.", type);
  383. return b;
  384. }
  385. b->type = it->second;
  386. parseTypedBonusShort(ability_vec, b);
  387. return b;
  388. }
  389. template <typename T>
  390. const T & parseByMap(const std::map<std::string, T> & map, const JsonNode * val, std::string err)
  391. {
  392. static T defaultValue = T();
  393. if (!val->isNull())
  394. {
  395. std::string type = val->String();
  396. auto it = map.find(type);
  397. if (it == map.end())
  398. {
  399. logMod->error("Error: invalid %s%s.", err, type);
  400. return defaultValue;
  401. }
  402. else
  403. {
  404. return it->second;
  405. }
  406. }
  407. else
  408. return defaultValue;
  409. }
  410. void JsonUtils::resolveIdentifier(si32 &var, const JsonNode &node, std::string name)
  411. {
  412. const JsonNode &value = node[name];
  413. if (!value.isNull())
  414. {
  415. switch (value.getType())
  416. {
  417. case JsonNode::JsonType::DATA_INTEGER:
  418. var = value.Integer();
  419. break;
  420. case JsonNode::JsonType::DATA_FLOAT:
  421. var = value.Float();
  422. break;
  423. case JsonNode::JsonType::DATA_STRING:
  424. VLC->modh->identifiers.requestIdentifier(value, [&](si32 identifier)
  425. {
  426. var = identifier;
  427. });
  428. break;
  429. default:
  430. logMod->error("Error! Wrong identifier used for value of %s.", name);
  431. }
  432. }
  433. }
  434. void JsonUtils::resolveAddInfo(CAddInfo & var, const JsonNode & node)
  435. {
  436. const JsonNode & value = node["addInfo"];
  437. if (!value.isNull())
  438. {
  439. switch (value.getType())
  440. {
  441. case JsonNode::JsonType::DATA_INTEGER:
  442. var = value.Integer();
  443. break;
  444. case JsonNode::JsonType::DATA_FLOAT:
  445. var = value.Float();
  446. break;
  447. case JsonNode::JsonType::DATA_STRING:
  448. VLC->modh->identifiers.requestIdentifier(value, [&](si32 identifier)
  449. {
  450. var = identifier;
  451. });
  452. break;
  453. case JsonNode::JsonType::DATA_VECTOR:
  454. {
  455. const JsonVector & vec = value.Vector();
  456. var.resize(vec.size());
  457. for(int i = 0; i < vec.size(); i++)
  458. {
  459. switch(vec[i].getType())
  460. {
  461. case JsonNode::JsonType::DATA_INTEGER:
  462. var[i] = vec[i].Integer();
  463. break;
  464. case JsonNode::JsonType::DATA_FLOAT:
  465. var[i] = vec[i].Float();
  466. break;
  467. case JsonNode::JsonType::DATA_STRING:
  468. VLC->modh->identifiers.requestIdentifier(vec[i], [&var,i](si32 identifier)
  469. {
  470. var[i] = identifier;
  471. });
  472. break;
  473. default:
  474. logMod->error("Error! Wrong identifier used for value of addInfo[%d].", i);
  475. }
  476. }
  477. break;
  478. }
  479. default:
  480. logMod->error("Error! Wrong identifier used for value of addInfo.");
  481. }
  482. }
  483. }
  484. void JsonUtils::resolveIdentifier(const JsonNode &node, si32 &var)
  485. {
  486. switch (node.getType())
  487. {
  488. case JsonNode::JsonType::DATA_INTEGER:
  489. var = node.Integer();
  490. break;
  491. case JsonNode::JsonType::DATA_FLOAT:
  492. var = node.Float();
  493. break;
  494. case JsonNode::JsonType::DATA_STRING:
  495. VLC->modh->identifiers.requestIdentifier(node, [&](si32 identifier)
  496. {
  497. var = identifier;
  498. });
  499. break;
  500. default:
  501. logMod->error("Error! Wrong identifier used for identifier!");
  502. }
  503. }
  504. std::shared_ptr<Bonus> JsonUtils::parseBonus(const JsonNode &ability)
  505. {
  506. auto b = std::make_shared<Bonus>();
  507. if (!parseBonus(ability, b.get()))
  508. {
  509. return nullptr;
  510. }
  511. return b;
  512. }
  513. bool JsonUtils::parseBonus(const JsonNode &ability, Bonus *b)
  514. {
  515. const JsonNode *value;
  516. std::string type = ability["type"].String();
  517. auto it = bonusNameMap.find(type);
  518. if (it == bonusNameMap.end())
  519. {
  520. logMod->error("Error: invalid ability type %s.", type);
  521. return false;
  522. }
  523. b->type = it->second;
  524. resolveIdentifier(b->subtype, ability, "subtype");
  525. b->val = ability["val"].Float();
  526. value = &ability["valueType"];
  527. if (!value->isNull())
  528. b->valType = static_cast<Bonus::ValueType>(parseByMap(bonusValueMap, value, "value type "));
  529. resolveAddInfo(b->additionalInfo, ability);
  530. b->turnsRemain = ability["turns"].Float();
  531. b->sid = ability["sourceID"].Float();
  532. b->description = ability["description"].String();
  533. value = &ability["effectRange"];
  534. if (!value->isNull())
  535. b->effectRange = static_cast<Bonus::LimitEffect>(parseByMap(bonusLimitEffect, value, "effect range "));
  536. value = &ability["duration"];
  537. if (!value->isNull())
  538. {
  539. switch (value->getType())
  540. {
  541. case JsonNode::JsonType::DATA_STRING:
  542. b->duration = parseByMap(bonusDurationMap, value, "duration type ");
  543. break;
  544. case JsonNode::JsonType::DATA_VECTOR:
  545. {
  546. ui16 dur = 0;
  547. for (const JsonNode & d : value->Vector())
  548. {
  549. dur |= parseByMap(bonusDurationMap, &d, "duration type ");
  550. }
  551. b->duration = dur;
  552. }
  553. break;
  554. default:
  555. logMod->error("Error! Wrong bonus duration format.");
  556. }
  557. }
  558. value = &ability["source"];
  559. if (!value->isNull())
  560. b->source = static_cast<Bonus::BonusSource>(parseByMap(bonusSourceMap, value, "source type "));
  561. value = &ability["limiters"];
  562. if (!value->isNull())
  563. {
  564. for (const JsonNode & limiter : value->Vector())
  565. {
  566. switch (limiter.getType())
  567. {
  568. case JsonNode::JsonType::DATA_STRING: //pre-defined limiters
  569. b->limiter = parseByMap(bonusLimiterMap, &limiter, "limiter type ");
  570. break;
  571. case JsonNode::JsonType::DATA_STRUCT: //customizable limiters
  572. {
  573. std::shared_ptr<ILimiter> l;
  574. if (limiter["type"].String() == "CREATURE_TYPE_LIMITER")
  575. {
  576. std::shared_ptr<CCreatureTypeLimiter> l2 = std::make_shared<CCreatureTypeLimiter>(); //TODO: How the hell resolve pointer to creature?
  577. const JsonVector vec = limiter["parameters"].Vector();
  578. VLC->modh->identifiers.requestIdentifier("creature", vec[0], [=](si32 creature)
  579. {
  580. l2->setCreature(CreatureID(creature));
  581. });
  582. if (vec.size() > 1)
  583. {
  584. l2->includeUpgrades = vec[1].Bool();
  585. }
  586. else
  587. l2->includeUpgrades = false;
  588. l = l2;
  589. }
  590. if (limiter["type"].String() == "HAS_ANOTHER_BONUS_LIMITER")
  591. {
  592. std::shared_ptr<HasAnotherBonusLimiter> l2 = std::make_shared<HasAnotherBonusLimiter>();
  593. const JsonVector vec = limiter["parameters"].Vector();
  594. std::string anotherBonusType = vec[0].String();
  595. auto it = bonusNameMap.find(anotherBonusType);
  596. if (it == bonusNameMap.end())
  597. {
  598. logMod->error("Error: invalid ability type %s.", anotherBonusType);
  599. continue;
  600. }
  601. l2->type = it->second;
  602. if (vec.size() > 1 )
  603. {
  604. resolveIdentifier(vec[1], l2->subtype);
  605. l2->isSubtypeRelevant = true;
  606. }
  607. l = l2;
  608. }
  609. b->addLimiter(l);
  610. }
  611. break;
  612. }
  613. }
  614. }
  615. value = &ability["propagator"];
  616. if (!value->isNull())
  617. b->propagator = parseByMap(bonusPropagatorMap, value, "propagator type ");
  618. value = &ability["updater"];
  619. if(!value->isNull())
  620. {
  621. const JsonNode & updaterJson = *value;
  622. switch(updaterJson.getType())
  623. {
  624. case JsonNode::JsonType::DATA_STRING:
  625. b->addUpdater(parseByMap(bonusUpdaterMap, &updaterJson, "updater type "));
  626. break;
  627. case JsonNode::JsonType::DATA_STRUCT:
  628. if(updaterJson["type"].String() == "GROWS_WITH_LEVEL")
  629. {
  630. std::shared_ptr<GrowsWithLevelUpdater> updater = std::make_shared<GrowsWithLevelUpdater>();
  631. const JsonVector param = updaterJson["parameters"].Vector();
  632. updater->valPer20 = param[0].Integer();
  633. if(param.size() > 1)
  634. updater->stepSize = param[1].Integer();
  635. b->addUpdater(updater);
  636. }
  637. else
  638. logMod->warn("Unknown updater type \"%s\"", updaterJson["type"].String());
  639. break;
  640. }
  641. }
  642. return true;
  643. }
  644. //returns first Key with value equal to given one
  645. template<class Key, class Val>
  646. Key reverseMapFirst(const Val & val, const std::map<Key, Val> & map)
  647. {
  648. for(auto it : map)
  649. {
  650. if(it.second == val)
  651. {
  652. return it.first;
  653. }
  654. }
  655. assert(0);
  656. return "";
  657. }
  658. void JsonUtils::unparseBonus( JsonNode &node, const std::shared_ptr<Bonus>& bonus )
  659. {
  660. node["type"].String() = reverseMapFirst<std::string, Bonus::BonusType>(bonus->type, bonusNameMap);
  661. node["subtype"].Float() = bonus->subtype;
  662. node["val"].Float() = bonus->val;
  663. node["valueType"].String() = reverseMapFirst<std::string, Bonus::ValueType>(bonus->valType, bonusValueMap);
  664. node["additionalInfo"] = bonus->additionalInfo.toJsonNode();
  665. node["turns"].Float() = bonus->turnsRemain;
  666. node["sourceID"].Float() = bonus->source;
  667. node["description"].String() = bonus->description;
  668. node["effectRange"].String() = reverseMapFirst<std::string, Bonus::LimitEffect>(bonus->effectRange, bonusLimitEffect);
  669. node["duration"].String() = reverseMapFirst<std::string, ui16>(bonus->duration, bonusDurationMap);
  670. node["source"].String() = reverseMapFirst<std::string, Bonus::BonusSource>(bonus->source, bonusSourceMap);
  671. if(bonus->limiter)
  672. {
  673. node["limiter"].String() = reverseMapFirst<std::string, TLimiterPtr>(bonus->limiter, bonusLimiterMap);
  674. }
  675. if(bonus->propagator)
  676. {
  677. node["propagator"].String() = reverseMapFirst<std::string, TPropagatorPtr>(bonus->propagator, bonusPropagatorMap);
  678. }
  679. }
  680. void minimizeNode(JsonNode & node, const JsonNode & schema)
  681. {
  682. if (schema["type"].String() == "object")
  683. {
  684. std::set<std::string> foundEntries;
  685. for(auto & entry : schema["required"].Vector())
  686. {
  687. std::string name = entry.String();
  688. foundEntries.insert(name);
  689. minimizeNode(node[name], schema["properties"][name]);
  690. if (vstd::contains(node.Struct(), name) &&
  691. node[name] == schema["properties"][name]["default"])
  692. {
  693. node.Struct().erase(name);
  694. }
  695. }
  696. // erase all unhandled entries
  697. for (auto it = node.Struct().begin(); it != node.Struct().end();)
  698. {
  699. if (!vstd::contains(foundEntries, it->first))
  700. it = node.Struct().erase(it);
  701. else
  702. it++;
  703. }
  704. }
  705. }
  706. void JsonUtils::minimize(JsonNode & node, std::string schemaName)
  707. {
  708. minimizeNode(node, getSchema(schemaName));
  709. }
  710. // FIXME: except for several lines function is identical to minimizeNode. Some way to reduce duplication?
  711. void maximizeNode(JsonNode & node, const JsonNode & schema)
  712. {
  713. // "required" entry can only be found in object/struct
  714. if (schema["type"].String() == "object")
  715. {
  716. std::set<std::string> foundEntries;
  717. // check all required entries that have default version
  718. for(auto & entry : schema["required"].Vector())
  719. {
  720. std::string name = entry.String();
  721. foundEntries.insert(name);
  722. if (node[name].isNull() &&
  723. !schema["properties"][name]["default"].isNull())
  724. {
  725. node[name] = schema["properties"][name]["default"];
  726. }
  727. maximizeNode(node[name], schema["properties"][name]);
  728. }
  729. // erase all unhandled entries
  730. for (auto it = node.Struct().begin(); it != node.Struct().end();)
  731. {
  732. if (!vstd::contains(foundEntries, it->first))
  733. it = node.Struct().erase(it);
  734. else
  735. it++;
  736. }
  737. }
  738. }
  739. void JsonUtils::maximize(JsonNode & node, std::string schemaName)
  740. {
  741. maximizeNode(node, getSchema(schemaName));
  742. }
  743. bool JsonUtils::validate(const JsonNode &node, std::string schemaName, std::string dataName)
  744. {
  745. std::string log = Validation::check(schemaName, node);
  746. if (!log.empty())
  747. {
  748. logMod->warn("Data in %s is invalid!", dataName);
  749. logMod->warn(log);
  750. logMod->trace("%s json: %s", dataName, node.toJson(true));
  751. }
  752. return log.empty();
  753. }
  754. const JsonNode & getSchemaByName(std::string name)
  755. {
  756. // cached schemas to avoid loading json data multiple times
  757. static std::map<std::string, JsonNode> loadedSchemas;
  758. if (vstd::contains(loadedSchemas, name))
  759. return loadedSchemas[name];
  760. std::string filename = "config/schemas/" + name + ".json";
  761. if (CResourceHandler::get()->existsResource(ResourceID(filename)))
  762. {
  763. loadedSchemas[name] = JsonNode(ResourceID(filename));
  764. return loadedSchemas[name];
  765. }
  766. logMod->error("Error: missing schema with name %s!", name);
  767. assert(0);
  768. return nullNode;
  769. }
  770. const JsonNode & JsonUtils::getSchema(std::string URI)
  771. {
  772. size_t posColon = URI.find(':');
  773. size_t posHash = URI.find('#');
  774. if(posColon == std::string::npos)
  775. {
  776. logMod->error("Invalid schema URI:%s", URI);
  777. return nullNode;
  778. }
  779. std::string protocolName = URI.substr(0, posColon);
  780. std::string filename = URI.substr(posColon + 1, posHash - posColon - 1);
  781. if(protocolName != "vcmi")
  782. {
  783. logMod->error("Error: unsupported URI protocol for schema: %s", URI);
  784. return nullNode;
  785. }
  786. // check if json pointer if present (section after hash in string)
  787. if(posHash == std::string::npos || posHash == URI.size() - 1)
  788. return getSchemaByName(filename);
  789. else
  790. return getSchemaByName(filename).resolvePointer(URI.substr(posHash + 1));
  791. }
  792. void JsonUtils::merge(JsonNode & dest, JsonNode & source, bool noOverride)
  793. {
  794. if (dest.getType() == JsonNode::JsonType::DATA_NULL)
  795. {
  796. std::swap(dest, source);
  797. return;
  798. }
  799. switch (source.getType())
  800. {
  801. case JsonNode::JsonType::DATA_NULL:
  802. {
  803. dest.clear();
  804. break;
  805. }
  806. case JsonNode::JsonType::DATA_BOOL:
  807. case JsonNode::JsonType::DATA_FLOAT:
  808. case JsonNode::JsonType::DATA_INTEGER:
  809. case JsonNode::JsonType::DATA_STRING:
  810. case JsonNode::JsonType::DATA_VECTOR:
  811. {
  812. std::swap(dest, source);
  813. break;
  814. }
  815. case JsonNode::JsonType::DATA_STRUCT:
  816. {
  817. if(!noOverride && vstd::contains(source.flags, "override"))
  818. {
  819. std::swap(dest, source);
  820. }
  821. else
  822. {
  823. //recursively merge all entries from struct
  824. for(auto & node : source.Struct())
  825. merge(dest[node.first], node.second, noOverride);
  826. }
  827. }
  828. }
  829. }
  830. void JsonUtils::mergeCopy(JsonNode & dest, JsonNode source, bool noOverride)
  831. {
  832. // uses copy created in stack to safely merge two nodes
  833. merge(dest, source, noOverride);
  834. }
  835. void JsonUtils::inherit(JsonNode & descendant, const JsonNode & base)
  836. {
  837. JsonNode inheritedNode(base);
  838. merge(inheritedNode, descendant, true);
  839. descendant.swap(inheritedNode);
  840. }
  841. JsonNode JsonUtils::intersect(const std::vector<JsonNode> & nodes, bool pruneEmpty)
  842. {
  843. if(nodes.size() == 0)
  844. return nullNode;
  845. JsonNode result = nodes[0];
  846. for(int i = 1; i < nodes.size(); i++)
  847. {
  848. if(result.isNull())
  849. break;
  850. result = JsonUtils::intersect(result, nodes[i], pruneEmpty);
  851. }
  852. return result;
  853. }
  854. JsonNode JsonUtils::intersect(const JsonNode & a, const JsonNode & b, bool pruneEmpty)
  855. {
  856. if(a.getType() == JsonNode::JsonType::DATA_STRUCT && b.getType() == JsonNode::JsonType::DATA_STRUCT)
  857. {
  858. // intersect individual properties
  859. JsonNode result(JsonNode::JsonType::DATA_STRUCT);
  860. for(auto property : a.Struct())
  861. {
  862. if(vstd::contains(b.Struct(), property.first))
  863. {
  864. JsonNode propertyIntersect = JsonUtils::intersect(property.second, b.Struct().find(property.first)->second);
  865. if(pruneEmpty && !propertyIntersect.containsBaseData())
  866. continue;
  867. result[property.first] = propertyIntersect;
  868. }
  869. }
  870. return result;
  871. }
  872. else
  873. {
  874. // not a struct - same or different, no middle ground
  875. if(a == b)
  876. return a;
  877. }
  878. return nullNode;
  879. }
  880. JsonNode JsonUtils::difference(const JsonNode & node, const JsonNode & base)
  881. {
  882. auto addsInfo = [](JsonNode diff) -> bool
  883. {
  884. switch(diff.getType())
  885. {
  886. case JsonNode::JsonType::DATA_NULL:
  887. return false;
  888. case JsonNode::JsonType::DATA_STRUCT:
  889. return diff.Struct().size() > 0;
  890. default:
  891. return true;
  892. }
  893. };
  894. if(node.getType() == JsonNode::JsonType::DATA_STRUCT && base.getType() == JsonNode::JsonType::DATA_STRUCT)
  895. {
  896. // subtract individual properties
  897. JsonNode result(JsonNode::JsonType::DATA_STRUCT);
  898. for(auto property : node.Struct())
  899. {
  900. if(vstd::contains(base.Struct(), property.first))
  901. {
  902. const JsonNode propertyDifference = JsonUtils::difference(property.second, base.Struct().find(property.first)->second);
  903. if(addsInfo(propertyDifference))
  904. result[property.first] = propertyDifference;
  905. }
  906. else
  907. {
  908. result[property.first] = property.second;
  909. }
  910. }
  911. return result;
  912. }
  913. else
  914. {
  915. if(node == base)
  916. return nullNode;
  917. }
  918. return node;
  919. }
  920. JsonNode JsonUtils::assembleFromFiles(std::vector<std::string> files)
  921. {
  922. bool isValid;
  923. return assembleFromFiles(files, isValid);
  924. }
  925. JsonNode JsonUtils::assembleFromFiles(std::vector<std::string> files, bool &isValid)
  926. {
  927. isValid = true;
  928. JsonNode result;
  929. for(std::string file : files)
  930. {
  931. bool isValidFile;
  932. JsonNode section(ResourceID(file, EResType::TEXT), isValidFile);
  933. merge(result, section);
  934. isValid |= isValidFile;
  935. }
  936. return result;
  937. }
  938. JsonNode JsonUtils::assembleFromFiles(std::string filename)
  939. {
  940. JsonNode result;
  941. ResourceID resID(filename, EResType::TEXT);
  942. for(auto & loader : CResourceHandler::get()->getResourcesWithName(resID))
  943. {
  944. // FIXME: some way to make this code more readable
  945. auto stream = loader->load(resID);
  946. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  947. stream->read(textData.get(), stream->getSize());
  948. JsonNode section((char*)textData.get(), stream->getSize());
  949. merge(result, section);
  950. }
  951. return result;
  952. }
  953. DLL_LINKAGE JsonNode JsonUtils::boolNode(bool value)
  954. {
  955. JsonNode node;
  956. node.Bool() = value;
  957. return node;
  958. }
  959. DLL_LINKAGE JsonNode JsonUtils::floatNode(double value)
  960. {
  961. JsonNode node;
  962. node.Float() = value;
  963. return node;
  964. }
  965. DLL_LINKAGE JsonNode JsonUtils::stringNode(std::string value)
  966. {
  967. JsonNode node;
  968. node.String() = value;
  969. return node;
  970. }
  971. DLL_LINKAGE JsonNode JsonUtils::intNode(si64 value)
  972. {
  973. JsonNode node;
  974. node.Integer() = value;
  975. return node;
  976. }