g_save.cpp 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609
  1. // Copyright (c) ZeniMax Media Inc.
  2. // Licensed under the GNU General Public License 2.0.
  3. #include <sstream>
  4. #include "g_local.h"
  5. #include <float.h>
  6. #ifdef __clang__
  7. #pragma clang diagnostic push
  8. #pragma GCC diagnostic ignored "-Weverything"
  9. #endif
  10. #include "json/json.h"
  11. #include "json/config.h"
  12. #ifdef __clang__
  13. #pragma clang diagnostic pop
  14. #endif
  15. // new save format;
  16. // - simple JSON format
  17. // - work via 'type' definitions which declare the type
  18. // that is at the specified offset of a struct
  19. // - backwards & forwards compatible with this same format
  20. // - I wrote this initially when the codebase was in C, so it
  21. // does have some C-isms in here.
  22. constexpr size_t SAVE_FORMAT_VERSION = 1;
  23. #include <unordered_map>
  24. // Professor Daniel J. Bernstein; https://www.partow.net/programming/hashfunctions/#APHashFunction MIT
  25. struct cstring_hash
  26. {
  27. inline std::size_t operator()(const char *str) const
  28. {
  29. size_t len = strlen(str);
  30. uint32_t hash = 5381;
  31. uint32_t i = 0;
  32. for (i = 0; i < len; ++str, ++i)
  33. hash = ((hash << 5) + hash) + (*str);
  34. return hash;
  35. }
  36. };
  37. struct cstring_equal
  38. {
  39. inline bool operator()(const char *a, const char *b) const
  40. {
  41. return strcmp(a, b) == 0;
  42. }
  43. };
  44. struct ptr_tag_hash
  45. {
  46. inline std::size_t operator()(const std::tuple<const void *, save_data_tag_t> &v) const
  47. {
  48. return (std::hash<const void *>()(std::get<0>(v)) * 8747) + std::get<1>(v);
  49. }
  50. };
  51. static bool save_data_initialized = false;
  52. static const save_data_list_t *list_head = nullptr;
  53. static std::unordered_map<const void *, const save_data_list_t *> list_hash;
  54. static std::unordered_map<const char *, const save_data_list_t *, cstring_hash, cstring_equal> list_str_hash;
  55. static std::unordered_map<std::tuple<const void *, save_data_tag_t>, const save_data_list_t *, ptr_tag_hash> list_from_ptr_hash;
  56. #include <cassert>
  57. void InitSave()
  58. {
  59. if (save_data_initialized)
  60. return;
  61. for (const save_data_list_t *link = list_head; link; link = link->next)
  62. {
  63. const void *link_ptr = link;
  64. if (list_hash.find(link_ptr) != list_hash.end())
  65. {
  66. auto existing = *list_hash.find(link_ptr);
  67. // [0] is just to silence warning
  68. assert(false || "invalid save pointer; break here to find which pointer it is"[0]);
  69. if (g_strict_saves->integer)
  70. gi.Com_ErrorFmt("link pointer {} already linked as {}; fatal error", link_ptr, existing.second->name);
  71. else
  72. gi.Com_PrintFmt("link pointer {} already linked as {}; fatal error", link_ptr, existing.second->name);
  73. }
  74. if (list_str_hash.find(link->name) != list_str_hash.end())
  75. {
  76. auto existing = *list_str_hash.find(link->name);
  77. // [0] is just to silence warning
  78. assert(false || "invalid save pointer; break here to find which pointer it is"[0]);
  79. if (g_strict_saves->integer)
  80. gi.Com_ErrorFmt("link pointer {} already linked as {}; fatal error", link_ptr, existing.second->name);
  81. else
  82. gi.Com_PrintFmt("link pointer {} already linked as {}; fatal error", link_ptr, existing.second->name);
  83. }
  84. list_hash.emplace(link_ptr, link);
  85. list_str_hash.emplace(link->name, link);
  86. list_from_ptr_hash.emplace(std::make_tuple(link->ptr, link->tag), link);
  87. }
  88. save_data_initialized = true;
  89. }
  90. // initializer for save data
  91. save_data_list_t::save_data_list_t(const char *name_in, save_data_tag_t tag_in, const void *ptr_in) :
  92. name(name_in),
  93. tag(tag_in),
  94. ptr(ptr_in)
  95. {
  96. if (save_data_initialized)
  97. gi.Com_Error("attempted to create save_data_list at runtime");
  98. next = list_head;
  99. list_head = this;
  100. }
  101. const save_data_list_t *save_data_list_t::fetch(const void *ptr, save_data_tag_t tag)
  102. {
  103. auto link = list_from_ptr_hash.find(std::make_tuple(ptr, tag));
  104. if (link != list_from_ptr_hash.end() && link->second->tag == tag)
  105. return link->second;
  106. // [0] is just to silence warning
  107. assert(false || "invalid save pointer; break here to find which pointer it is"[0]);
  108. if (g_strict_saves->integer)
  109. gi.Com_ErrorFmt("value pointer {} was not linked to save tag {}", ptr, (int32_t) tag);
  110. else
  111. gi.Com_PrintFmt("value pointer {} was not linked to save tag {}", ptr, (int32_t) tag);
  112. return nullptr;
  113. }
  114. std::string json_error_stack;
  115. void json_push_stack(const std::string &stack)
  116. {
  117. json_error_stack += "::" + stack;
  118. }
  119. void json_pop_stack()
  120. {
  121. size_t o = json_error_stack.find_last_of("::");
  122. if (o != std::string::npos)
  123. json_error_stack.resize(o - 1);
  124. }
  125. void json_print_error(const char *field, const char *message, bool fatal)
  126. {
  127. if (fatal || g_strict_saves->integer)
  128. gi.Com_ErrorFmt("Error loading JSON\n{}.{}: {}", json_error_stack, field, message);
  129. gi.Com_PrintFmt("Warning loading JSON\n{}.{}: {}\n", json_error_stack, field, message);
  130. }
  131. using save_void_t = save_data_t<void, UINT_MAX>;
  132. enum save_type_id_t
  133. {
  134. // never valid
  135. ST_INVALID,
  136. // integral types
  137. ST_BOOL,
  138. ST_INT8,
  139. ST_INT16,
  140. ST_INT32,
  141. ST_INT64,
  142. ST_UINT8,
  143. ST_UINT16,
  144. ST_UINT32,
  145. ST_UINT64,
  146. ST_ENUM, // "count" = sizeof(enum_type)
  147. // floating point
  148. ST_FLOAT,
  149. ST_DOUBLE,
  150. ST_STRING, // "tag" = memory tag, "count" = fixed length if specified, otherwise dynamic
  151. ST_FIXED_STRING, // "count" = length
  152. ST_FIXED_ARRAY,
  153. // for simple types (ones that don't require extra info), "tag" = type and "count" = N
  154. // otherwise, "type_resolver" for nested arrays, structures, string/function arrays, etc
  155. ST_STRUCT, // "count" = sizeof(struct), "structure" = ptr to save_struct_t to save
  156. ST_BITSET, // bitset; "count" = N bits
  157. // special Quake types
  158. ST_ENTITY, // serialized as s.number
  159. ST_ITEM_POINTER, // serialized as classname
  160. ST_ITEM_INDEX, // serialized as classname
  161. ST_TIME, // serialized as milliseconds
  162. ST_DATA, // serialized as name of data ptr from global list; `tag` = list tag
  163. ST_INVENTORY, // serialized as classname => number key/value pairs
  164. ST_REINFORCEMENTS, // serialized as array of data
  165. ST_SAVABLE_DYNAMIC // serialized similar to ST_FIXED_ARRAY but includes count
  166. };
  167. struct save_struct_t;
  168. struct save_type_t
  169. {
  170. save_type_id_t id;
  171. int32_t tag = 0;
  172. size_t count = 0;
  173. save_type_t (*type_resolver)() = nullptr;
  174. const save_struct_t *structure = nullptr;
  175. bool never_empty = false; // this should be persisted even if all empty
  176. bool (*is_empty)(const void *data) = nullptr; // override default check
  177. void (*read)(void *data, const Json::Value &json, const char *field) = nullptr; // for custom reading
  178. bool (*write)(const void *data, bool null_for_empty, Json::Value &output) = nullptr; // for custom writing
  179. };
  180. struct save_field_t
  181. {
  182. const char *name;
  183. size_t offset;
  184. save_type_t type;
  185. // for easily chaining with FIELD_AUTO
  186. constexpr save_field_t &set_is_empty(decltype(save_type_t::is_empty) empty)
  187. {
  188. type.is_empty = empty;
  189. return *this;
  190. }
  191. };
  192. struct save_struct_t
  193. {
  194. const char *name;
  195. const std::initializer_list<save_field_t> fields; // field list
  196. std::string debug() const
  197. {
  198. std::stringstream s;
  199. for (auto &field : fields)
  200. s << field.name << " " << field.offset << " " << field.type.id << " " << field.type.tag << " "
  201. << field.type.count << '\n';
  202. return s.str();
  203. }
  204. };
  205. // field header macro
  206. #define SAVE_FIELD(n, f) #f, offsetof(n, f)
  207. // save struct header macro
  208. #define INTERNAL_SAVE_STRUCT_START2(struct_name) static const save_struct_t struct_name##_savestruct = { #struct_name, {
  209. #define INTERNAL_SAVE_STRUCT_START1(struct_name) INTERNAL_SAVE_STRUCT_START2(struct_name)
  210. #define SAVE_STRUCT_START INTERNAL_SAVE_STRUCT_START1(DECLARE_SAVE_STRUCT)
  211. #define SAVE_STRUCT_END \
  212. } \
  213. };
  214. // field header macro for current struct
  215. #define FIELD(f) SAVE_FIELD(DECLARE_SAVE_STRUCT, f)
  216. template<typename T, typename T2 = void>
  217. struct save_type_deducer
  218. {
  219. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  220. {
  221. static_assert(
  222. !std::is_same_v<T2, void>,
  223. "Can't automatically deduce type for save; implement save_type_deducer or use an explicit FIELD_ macro.");
  224. return {};
  225. }
  226. };
  227. // bool
  228. template<>
  229. struct save_type_deducer<bool>
  230. {
  231. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  232. {
  233. return { name, offset, { ST_BOOL } };
  234. }
  235. };
  236. // integral
  237. template<>
  238. struct save_type_deducer<int8_t>
  239. {
  240. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  241. {
  242. return { name, offset, { ST_INT8 } };
  243. }
  244. };
  245. template<>
  246. struct save_type_deducer<int16_t>
  247. {
  248. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  249. {
  250. return { name, offset, { ST_INT16 } };
  251. }
  252. };
  253. template<>
  254. struct save_type_deducer<int32_t>
  255. {
  256. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  257. {
  258. return { name, offset, { ST_INT32 } };
  259. }
  260. };
  261. template<>
  262. struct save_type_deducer<int64_t>
  263. {
  264. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  265. {
  266. return { name, offset, { ST_INT64 } };
  267. }
  268. };
  269. template<>
  270. struct save_type_deducer<uint8_t>
  271. {
  272. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  273. {
  274. return { name, offset, { ST_UINT8 } };
  275. }
  276. };
  277. template<>
  278. struct save_type_deducer<uint16_t>
  279. {
  280. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  281. {
  282. return { name, offset, { ST_UINT16 } };
  283. }
  284. };
  285. template<>
  286. struct save_type_deducer<uint32_t>
  287. {
  288. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  289. {
  290. return { name, offset, { ST_UINT32 } };
  291. }
  292. };
  293. template<>
  294. struct save_type_deducer<uint64_t>
  295. {
  296. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  297. {
  298. return { name, offset, { ST_UINT64 } };
  299. }
  300. };
  301. // floating point
  302. template<>
  303. struct save_type_deducer<float>
  304. {
  305. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  306. {
  307. return { name, offset, { ST_FLOAT } };
  308. }
  309. };
  310. template<>
  311. struct save_type_deducer<double>
  312. {
  313. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  314. {
  315. return { name, offset, { ST_DOUBLE } };
  316. }
  317. };
  318. // special types
  319. template<>
  320. struct save_type_deducer<edict_t *>
  321. {
  322. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  323. {
  324. return { name, offset, { ST_ENTITY } };
  325. }
  326. };
  327. template<>
  328. struct save_type_deducer<gitem_t *>
  329. {
  330. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  331. {
  332. return { name, offset, { ST_ITEM_POINTER } };
  333. }
  334. };
  335. template<>
  336. struct save_type_deducer<item_id_t>
  337. {
  338. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  339. {
  340. return { name, offset, { ST_ITEM_INDEX } };
  341. }
  342. };
  343. template<>
  344. struct save_type_deducer<gtime_t>
  345. {
  346. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  347. {
  348. return { name, offset, { ST_TIME } };
  349. }
  350. };
  351. template<>
  352. struct save_type_deducer<spawnflags_t>
  353. {
  354. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  355. {
  356. return { name, offset, { ST_UINT32 } };
  357. }
  358. };
  359. // static strings
  360. template<size_t N>
  361. struct save_type_deducer<char[N]>
  362. {
  363. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  364. {
  365. return { name, offset, { ST_FIXED_STRING, 0, N } };
  366. }
  367. };
  368. // enums
  369. template<typename T>
  370. struct save_type_deducer<T, typename std::enable_if_t<std::is_enum_v<T>>>
  371. {
  372. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  373. {
  374. return { name,
  375. offset,
  376. { ST_ENUM, 0,
  377. std::is_same_v<std::underlying_type_t<T>, uint64_t> ? 8
  378. : std::is_same_v<std::underlying_type_t<T>, uint32_t> ? 4
  379. : std::is_same_v<std::underlying_type_t<T>, uint16_t> ? 2
  380. : std::is_same_v<std::underlying_type_t<T>, uint8_t> ? 1
  381. : std::is_same_v<std::underlying_type_t<T>, int64_t> ? 8
  382. : std::is_same_v<std::underlying_type_t<T>, int32_t> ? 4
  383. : std::is_same_v<std::underlying_type_t<T>, int16_t> ? 2
  384. : std::is_same_v<std::underlying_type_t<T>, int8_t> ? 1
  385. : 0 } };
  386. }
  387. };
  388. // vector
  389. template<>
  390. struct save_type_deducer<vec3_t>
  391. {
  392. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  393. {
  394. return { name, offset, { ST_FIXED_ARRAY, ST_FLOAT, 3 } };
  395. }
  396. };
  397. // fixed-size arrays
  398. template<typename T, size_t N>
  399. struct save_type_deducer<T[N], typename std::enable_if_t<!std::is_same_v<T, char>>>
  400. {
  401. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  402. {
  403. auto type = save_type_deducer<std::remove_extent_t<T>>::get_save_type(nullptr, 0).type;
  404. if (type.id <= ST_BOOL || type.id >= ST_DOUBLE)
  405. return { name, offset, { ST_FIXED_ARRAY, ST_INVALID, 0, []() { return save_type_deducer<std::remove_extent_t<T>>::get_save_type(nullptr, 0).type; } } };
  406. return { name,
  407. offset,
  408. { ST_FIXED_ARRAY, type.id, N } };
  409. }
  410. };
  411. // std::array
  412. template<typename T, size_t N>
  413. struct save_type_deducer<std::array<T, N>>
  414. {
  415. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  416. {
  417. auto type = save_type_deducer<std::remove_extent_t<T>>::get_save_type(nullptr, 0).type;
  418. if (type.id <= ST_BOOL || type.id >= ST_DOUBLE)
  419. return { name, offset, { ST_FIXED_ARRAY, ST_INVALID, N, []() { return save_type_deducer<std::remove_extent_t<T>>::get_save_type(nullptr, 0).type; } } };
  420. return { name, offset, { ST_FIXED_ARRAY, type.id, N } };
  421. }
  422. };
  423. // savable_allocated_memory_t
  424. template<typename T, int32_t Tag>
  425. struct save_type_deducer<savable_allocated_memory_t<T, Tag>>
  426. {
  427. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  428. {
  429. auto type = save_type_deducer<std::remove_extent_t<T>>::get_save_type(nullptr, 0).type;
  430. if (type.id <= ST_BOOL || type.id >= ST_DOUBLE)
  431. return { name, offset, { ST_SAVABLE_DYNAMIC, ST_INVALID, Tag, []() { return save_type_deducer<std::remove_extent_t<T>>::get_save_type(nullptr, 0).type; } } };
  432. return { name, offset, { ST_SAVABLE_DYNAMIC, type.id, Tag } };
  433. }
  434. };
  435. // save_data_ref<T>
  436. template<typename T, size_t Tag>
  437. struct save_type_deducer<save_data_t<T, Tag>>
  438. {
  439. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  440. {
  441. return { name, offset, { ST_DATA, Tag, 0, nullptr, nullptr, false, nullptr } };
  442. }
  443. };
  444. // std::bitset<N>
  445. template<size_t N>
  446. struct save_type_deducer<std::bitset<N>>
  447. {
  448. static constexpr save_field_t get_save_type(const char *name, size_t offset)
  449. {
  450. return { name, offset, { ST_BITSET, 0, N, nullptr, nullptr, false, nullptr,
  451. [](void *data, const Json::Value &json, const char *field) {
  452. std::bitset<N> &as_bitset = *(std::bitset<N> *) data;
  453. as_bitset.reset();
  454. if (!json.isString())
  455. json_print_error(field, "expected string", false);
  456. else if (strlen(json.asCString()) > N)
  457. json_print_error(field, "bitset length overflow", false);
  458. else
  459. {
  460. const char *str = json.asCString();
  461. size_t len = strlen(str);
  462. for (size_t i = 0; i < len; i++)
  463. {
  464. if (str[i] == '0')
  465. continue;
  466. else if (str[i] == '1')
  467. as_bitset[i] = true;
  468. else
  469. json_print_error(field, "bad bitset value", false);
  470. }
  471. }
  472. },
  473. [](const void *data, bool null_for_empty, Json::Value &output) -> bool {
  474. const std::bitset<N> &as_bitset = *(std::bitset<N> *) data;
  475. if (as_bitset.none())
  476. {
  477. if (null_for_empty)
  478. return false;
  479. output = "";
  480. return true;
  481. }
  482. int32_t num_needed;
  483. for (num_needed = N - 1; num_needed >= 0; num_needed--)
  484. if (as_bitset[num_needed])
  485. break;
  486. // 00100000, num_needed = 2
  487. // num_needed always >= 0 since none() check done above
  488. num_needed++;
  489. std::string result(num_needed, '0');
  490. for (size_t n = 0; n < num_needed; n++)
  491. if (as_bitset[n])
  492. result[n] = '1';
  493. output = result;
  494. return true;
  495. }
  496. }
  497. };
  498. }
  499. };
  500. // deduce type via template deduction; use this generally
  501. // since it prevents user error and allows seamless type upgrades.
  502. #define FIELD_AUTO(f) save_type_deducer<decltype(DECLARE_SAVE_STRUCT::f)>::get_save_type(FIELD(f))
  503. // simple macro for a `char*` of TAG_LEVEL allocation
  504. #define FIELD_LEVEL_STRING(f) \
  505. { \
  506. FIELD(f), \
  507. { \
  508. ST_STRING, TAG_LEVEL \
  509. } \
  510. }
  511. // simple macro for a `char*` of TAG_GAME allocation
  512. #define FIELD_GAME_STRING(f) \
  513. { \
  514. FIELD(f), \
  515. { \
  516. ST_STRING, TAG_GAME \
  517. } \
  518. }
  519. // simple macro for a struct type
  520. #define FIELD_STRUCT(f, t) \
  521. { \
  522. FIELD(f), \
  523. { \
  524. ST_STRUCT, 0, sizeof(t), nullptr, &t##_savestruct \
  525. } \
  526. }
  527. // simple macro for a simple field with no parameters
  528. #define FIELD_SIMPLE(f, t) \
  529. { \
  530. FIELD(f), \
  531. { \
  532. t \
  533. } \
  534. }
  535. // macro for creating save type deducer for
  536. // specified struct type
  537. #define MAKE_STRUCT_SAVE_DEDUCER(t) \
  538. template<> \
  539. struct save_type_deducer<t> \
  540. { \
  541. static constexpr save_field_t get_save_type(const char *name, size_t offset) \
  542. { \
  543. return { name, offset, { ST_STRUCT, 0, sizeof(t), nullptr, &t##_savestruct } }; \
  544. } \
  545. };
  546. #define DECLARE_SAVE_STRUCT level_entry_t
  547. SAVE_STRUCT_START
  548. FIELD_AUTO(map_name),
  549. FIELD_AUTO(pretty_name),
  550. FIELD_AUTO(total_secrets),
  551. FIELD_AUTO(found_secrets),
  552. FIELD_AUTO(total_monsters),
  553. FIELD_AUTO(killed_monsters),
  554. FIELD_AUTO(time),
  555. FIELD_AUTO(visit_order)
  556. SAVE_STRUCT_END
  557. #undef DECLARE_SAVE_STRUCT
  558. MAKE_STRUCT_SAVE_DEDUCER(level_entry_t);
  559. // clang-format off
  560. #define DECLARE_SAVE_STRUCT game_locals_t
  561. SAVE_STRUCT_START
  562. FIELD_AUTO(helpmessage1),
  563. FIELD_AUTO(helpmessage2),
  564. FIELD_AUTO(help1changed),
  565. FIELD_AUTO(help2changed),
  566. // clients is set by load/init only
  567. FIELD_AUTO(spawnpoint),
  568. FIELD_AUTO(maxclients),
  569. FIELD_AUTO(maxentities),
  570. FIELD_AUTO(cross_level_flags),
  571. FIELD_AUTO(cross_unit_flags),
  572. FIELD_AUTO(autosaved),
  573. FIELD_AUTO(level_entries)
  574. SAVE_STRUCT_END
  575. #undef DECLARE_SAVE_STRUCT
  576. #define DECLARE_SAVE_STRUCT level_locals_t
  577. SAVE_STRUCT_START
  578. FIELD_AUTO(time),
  579. FIELD_AUTO(level_name),
  580. FIELD_AUTO(mapname),
  581. FIELD_AUTO(nextmap),
  582. FIELD_AUTO(intermissiontime),
  583. FIELD_LEVEL_STRING(changemap),
  584. FIELD_LEVEL_STRING(achievement),
  585. FIELD_AUTO(exitintermission),
  586. FIELD_AUTO(intermission_clear),
  587. FIELD_AUTO(intermission_origin),
  588. FIELD_AUTO(intermission_angle),
  589. // pic_health is set by worldspawn
  590. // pic_ping is set by worldspawn
  591. FIELD_AUTO(total_secrets),
  592. FIELD_AUTO(found_secrets),
  593. FIELD_AUTO(total_goals),
  594. FIELD_AUTO(found_goals),
  595. FIELD_AUTO(total_monsters),
  596. FIELD_AUTO(monsters_registered),
  597. FIELD_AUTO(killed_monsters),
  598. // current_entity not necessary to save
  599. FIELD_AUTO(body_que),
  600. FIELD_AUTO(power_cubes),
  601. // ROGUE
  602. FIELD_AUTO(disguise_violator),
  603. FIELD_AUTO(disguise_violation_time),
  604. // ROGUE
  605. FIELD_AUTO(coop_level_restart_time),
  606. FIELD_LEVEL_STRING(goals),
  607. FIELD_AUTO(goal_num),
  608. FIELD_AUTO(vwep_offset),
  609. FIELD_AUTO(valid_poi),
  610. FIELD_AUTO(current_poi),
  611. FIELD_AUTO(current_poi_stage),
  612. FIELD_AUTO(current_poi_image),
  613. FIELD_AUTO(current_dynamic_poi),
  614. FIELD_LEVEL_STRING(start_items),
  615. FIELD_AUTO(no_grapple),
  616. FIELD_AUTO(gravity),
  617. FIELD_AUTO(hub_map),
  618. FIELD_AUTO(health_bar_entities),
  619. FIELD_AUTO(intermission_server_frame),
  620. FIELD_AUTO(story_active),
  621. FIELD_AUTO(next_auto_save)
  622. SAVE_STRUCT_END
  623. #undef DECLARE_SAVE_STRUCT
  624. #define DECLARE_SAVE_STRUCT pmove_state_t
  625. SAVE_STRUCT_START
  626. FIELD_AUTO(pm_type),
  627. FIELD_AUTO(origin),
  628. FIELD_AUTO(velocity),
  629. FIELD_AUTO(pm_flags),
  630. FIELD_AUTO(pm_time),
  631. FIELD_AUTO(gravity),
  632. FIELD_AUTO(delta_angles),
  633. FIELD_AUTO(viewheight)
  634. SAVE_STRUCT_END
  635. #undef DECLARE_SAVE_STRUCT
  636. #define DECLARE_SAVE_STRUCT player_state_t
  637. SAVE_STRUCT_START
  638. FIELD_STRUCT(pmove, pmove_state_t),
  639. FIELD_AUTO(viewangles),
  640. FIELD_AUTO(viewoffset),
  641. // kick_angles only last 1 frame
  642. FIELD_AUTO(gunangles),
  643. FIELD_AUTO(gunoffset),
  644. FIELD_AUTO(gunindex),
  645. FIELD_AUTO(gunframe),
  646. FIELD_AUTO(gunskin),
  647. // blend is calculated by ClientEndServerFrame
  648. FIELD_AUTO(fov),
  649. // rdflags are generated by ClientEndServerFrame
  650. FIELD_AUTO(stats)
  651. SAVE_STRUCT_END
  652. #undef DECLARE_SAVE_STRUCT
  653. #define DECLARE_SAVE_STRUCT height_fog_t
  654. SAVE_STRUCT_START
  655. FIELD_AUTO(start),
  656. FIELD_AUTO(end),
  657. FIELD_AUTO(falloff),
  658. FIELD_AUTO(density)
  659. SAVE_STRUCT_END
  660. #undef DECLARE_SAVE_STRUCT
  661. #define DECLARE_SAVE_STRUCT client_persistant_t
  662. SAVE_STRUCT_START
  663. FIELD_AUTO(userinfo),
  664. FIELD_AUTO(social_id),
  665. FIELD_AUTO(netname),
  666. FIELD_AUTO(hand),
  667. FIELD_AUTO(health),
  668. FIELD_AUTO(max_health),
  669. FIELD_AUTO(savedFlags),
  670. FIELD_AUTO(selected_item),
  671. FIELD_SIMPLE(inventory, ST_INVENTORY),
  672. FIELD_AUTO(max_ammo),
  673. FIELD_AUTO(weapon),
  674. FIELD_AUTO(lastweapon),
  675. FIELD_AUTO(power_cubes),
  676. FIELD_AUTO(score),
  677. FIELD_AUTO(game_help1changed),
  678. FIELD_AUTO(game_help2changed),
  679. FIELD_AUTO(helpchanged),
  680. FIELD_AUTO(help_time),
  681. FIELD_AUTO(spectator),
  682. // save the wanted fog, but not the current fog
  683. // or transition time so it sends immediately
  684. FIELD_AUTO(wanted_fog),
  685. FIELD_STRUCT(wanted_heightfog, height_fog_t),
  686. FIELD_AUTO(megahealth_time),
  687. FIELD_AUTO(lives),
  688. FIELD_AUTO(n64_crouch_warn_times),
  689. FIELD_AUTO(n64_crouch_warning)
  690. SAVE_STRUCT_END
  691. #undef DECLARE_SAVE_STRUCT
  692. #define DECLARE_SAVE_STRUCT gclient_t
  693. SAVE_STRUCT_START
  694. FIELD_STRUCT(ps, player_state_t),
  695. // ping... duh
  696. FIELD_STRUCT(pers, client_persistant_t),
  697. FIELD_STRUCT(resp.coop_respawn, client_persistant_t),
  698. FIELD_AUTO(resp.entertime),
  699. FIELD_AUTO(resp.score),
  700. FIELD_AUTO(resp.cmd_angles),
  701. FIELD_AUTO(resp.spectator),
  702. // old_pmove is not necessary to persist
  703. // showscores, showinventory, showhelp not necessary
  704. // buttons, oldbuttons, latched_buttons not necessary
  705. // weapon_thunk not necessary
  706. FIELD_AUTO(newweapon),
  707. // damage_ members are calculated on damage
  708. FIELD_AUTO(killer_yaw),
  709. FIELD_AUTO(weaponstate),
  710. FIELD_AUTO(kick.angles),
  711. FIELD_AUTO(kick.origin),
  712. FIELD_AUTO(kick.total),
  713. FIELD_AUTO(kick.time),
  714. FIELD_AUTO(quake_time),
  715. FIELD_AUTO(v_dmg_roll),
  716. FIELD_AUTO(v_dmg_pitch),
  717. FIELD_AUTO(v_dmg_time),
  718. FIELD_AUTO(fall_time),
  719. FIELD_AUTO(fall_value),
  720. FIELD_AUTO(damage_alpha),
  721. FIELD_AUTO(bonus_alpha),
  722. FIELD_AUTO(damage_blend),
  723. FIELD_AUTO(v_angle),
  724. FIELD_AUTO(bobtime),
  725. FIELD_AUTO(oldviewangles),
  726. FIELD_AUTO(oldvelocity),
  727. FIELD_AUTO(oldgroundentity),
  728. FIELD_AUTO(next_drown_time),
  729. FIELD_AUTO(old_waterlevel),
  730. FIELD_AUTO(breather_sound),
  731. FIELD_AUTO(machinegun_shots),
  732. FIELD_AUTO(anim_end),
  733. FIELD_AUTO(anim_priority),
  734. FIELD_AUTO(anim_duck),
  735. FIELD_AUTO(anim_run),
  736. FIELD_AUTO(quad_time),
  737. FIELD_AUTO(invincible_time),
  738. FIELD_AUTO(breather_time),
  739. FIELD_AUTO(enviro_time),
  740. FIELD_AUTO(invisible_time),
  741. FIELD_AUTO(grenade_blew_up),
  742. FIELD_AUTO(grenade_time),
  743. FIELD_AUTO(grenade_finished_time),
  744. FIELD_AUTO(quadfire_time),
  745. FIELD_AUTO(silencer_shots),
  746. FIELD_AUTO(weapon_sound),
  747. FIELD_AUTO(pickup_msg_time),
  748. // flood stuff is dm only
  749. FIELD_AUTO(respawn_time),
  750. // chasecam not required to persist
  751. FIELD_AUTO(double_time),
  752. FIELD_AUTO(ir_time),
  753. FIELD_AUTO(nuke_time),
  754. FIELD_AUTO(tracker_pain_time),
  755. // owned_sphere is DM only
  756. FIELD_AUTO(empty_click_sound),
  757. FIELD_AUTO(trail_head),
  758. FIELD_AUTO(trail_tail),
  759. FIELD_GAME_STRING(landmark_name),
  760. FIELD_AUTO(landmark_rel_pos),
  761. FIELD_AUTO(landmark_free_fall),
  762. FIELD_AUTO(landmark_noise_time),
  763. FIELD_AUTO(invisibility_fade_time),
  764. FIELD_AUTO(last_ladder_pos),
  765. FIELD_AUTO(last_ladder_sound),
  766. FIELD_AUTO(sight_entity),
  767. FIELD_AUTO(sight_entity_time),
  768. FIELD_AUTO(sound_entity),
  769. FIELD_AUTO(sound_entity_time),
  770. FIELD_AUTO(sound2_entity),
  771. FIELD_AUTO(sound2_entity_time),
  772. FIELD_AUTO(last_firing_time),
  773. SAVE_STRUCT_END
  774. #undef DECLARE_SAVE_STRUCT
  775. // clang-format on
  776. static bool edict_t_gravity_is_empty(const void *data)
  777. {
  778. return *((const float *) data) == 1.f;
  779. }
  780. static bool edict_t_gravityVector_is_empty(const void *data)
  781. {
  782. constexpr vec3_t up_vector = { 0, 0, -1 };
  783. return *(const vec3_t *) data == up_vector;
  784. }
  785. // clang-format off
  786. #define DECLARE_SAVE_STRUCT edict_t
  787. SAVE_STRUCT_START
  788. // entity_state_t stuff; only one instance
  789. // so no need to do a whole save struct
  790. FIELD_AUTO(s.origin),
  791. FIELD_AUTO(s.angles),
  792. FIELD_AUTO(s.old_origin),
  793. FIELD_AUTO(s.modelindex),
  794. FIELD_AUTO(s.modelindex2),
  795. FIELD_AUTO(s.modelindex3),
  796. FIELD_AUTO(s.modelindex4),
  797. FIELD_AUTO(s.frame),
  798. FIELD_AUTO(s.skinnum),
  799. FIELD_AUTO(s.effects),
  800. FIELD_AUTO(s.renderfx),
  801. // s.solid is set by linkentity
  802. // events are cleared on each frame, no need to save
  803. FIELD_AUTO(s.sound),
  804. FIELD_AUTO(s.alpha),
  805. FIELD_AUTO(s.scale),
  806. FIELD_AUTO(s.instance_bits),
  807. // server stuff
  808. // client is auto-set
  809. // inuse is implied
  810. FIELD_AUTO(linkcount),
  811. // area, num_clusters, clusternums, headnode, areanum, areanum2
  812. // are set by linkentity and can't be saved
  813. FIELD_AUTO(svflags),
  814. FIELD_AUTO(mins),
  815. FIELD_AUTO(maxs),
  816. // absmin, absmax and size are set by linkentity
  817. FIELD_AUTO(solid),
  818. FIELD_AUTO(clipmask),
  819. FIELD_AUTO(owner),
  820. // game stuff
  821. FIELD_AUTO(spawn_count),
  822. FIELD_AUTO(movetype),
  823. FIELD_AUTO(flags),
  824. FIELD_LEVEL_STRING(model),
  825. FIELD_AUTO(freetime),
  826. FIELD_LEVEL_STRING(message),
  827. FIELD_LEVEL_STRING(classname), // FIXME: should allow loading from constants
  828. FIELD_AUTO(spawnflags),
  829. FIELD_AUTO(timestamp),
  830. FIELD_AUTO(angle),
  831. FIELD_LEVEL_STRING(target),
  832. FIELD_LEVEL_STRING(targetname),
  833. FIELD_LEVEL_STRING(killtarget),
  834. FIELD_LEVEL_STRING(team),
  835. FIELD_LEVEL_STRING(pathtarget),
  836. FIELD_LEVEL_STRING(deathtarget),
  837. FIELD_LEVEL_STRING(healthtarget),
  838. FIELD_LEVEL_STRING(itemtarget),
  839. FIELD_LEVEL_STRING(combattarget),
  840. FIELD_AUTO(target_ent),
  841. FIELD_AUTO(speed),
  842. FIELD_AUTO(accel),
  843. FIELD_AUTO(decel),
  844. FIELD_AUTO(movedir),
  845. FIELD_AUTO(pos1),
  846. FIELD_AUTO(pos2),
  847. FIELD_AUTO(pos3),
  848. FIELD_AUTO(velocity),
  849. FIELD_AUTO(avelocity),
  850. FIELD_AUTO(mass),
  851. FIELD_AUTO(air_finished),
  852. FIELD_AUTO(gravity).set_is_empty(edict_t_gravity_is_empty),
  853. FIELD_AUTO(goalentity),
  854. FIELD_AUTO(movetarget),
  855. FIELD_AUTO(yaw_speed),
  856. FIELD_AUTO(ideal_yaw),
  857. FIELD_AUTO(nextthink),
  858. FIELD_AUTO(prethink),
  859. FIELD_AUTO(postthink),
  860. FIELD_AUTO(think),
  861. FIELD_AUTO(touch),
  862. FIELD_AUTO(use),
  863. FIELD_AUTO(pain),
  864. FIELD_AUTO(die),
  865. FIELD_AUTO(touch_debounce_time),
  866. FIELD_AUTO(pain_debounce_time),
  867. FIELD_AUTO(damage_debounce_time),
  868. FIELD_AUTO(fly_sound_debounce_time),
  869. FIELD_AUTO(last_move_time),
  870. FIELD_AUTO(health),
  871. FIELD_AUTO(max_health),
  872. FIELD_AUTO(gib_health),
  873. FIELD_AUTO(deadflag),
  874. FIELD_AUTO(show_hostile),
  875. FIELD_AUTO(powerarmor_time),
  876. FIELD_LEVEL_STRING(map),
  877. FIELD_AUTO(viewheight),
  878. FIELD_AUTO(takedamage),
  879. FIELD_AUTO(dmg),
  880. FIELD_AUTO(radius_dmg),
  881. FIELD_AUTO(dmg_radius),
  882. FIELD_AUTO(sounds),
  883. FIELD_AUTO(count),
  884. FIELD_AUTO(chain),
  885. FIELD_AUTO(enemy),
  886. FIELD_AUTO(oldenemy),
  887. FIELD_AUTO(activator),
  888. FIELD_AUTO(groundentity),
  889. FIELD_AUTO(groundentity_linkcount),
  890. FIELD_AUTO(teamchain),
  891. FIELD_AUTO(teammaster),
  892. FIELD_AUTO(mynoise),
  893. FIELD_AUTO(mynoise2),
  894. FIELD_AUTO(noise_index),
  895. FIELD_AUTO(noise_index2),
  896. FIELD_AUTO(volume),
  897. FIELD_AUTO(attenuation),
  898. FIELD_AUTO(wait),
  899. FIELD_AUTO(delay),
  900. FIELD_AUTO(random),
  901. FIELD_AUTO(teleport_time),
  902. FIELD_AUTO(watertype),
  903. FIELD_AUTO(waterlevel),
  904. FIELD_AUTO(move_origin),
  905. FIELD_AUTO(move_angles),
  906. FIELD_AUTO(style),
  907. FIELD_LEVEL_STRING(style_on),
  908. FIELD_LEVEL_STRING(style_off),
  909. FIELD_AUTO(item),
  910. FIELD_AUTO(crosslevel_flags),
  911. // moveinfo_t
  912. FIELD_AUTO(moveinfo.start_origin),
  913. FIELD_AUTO(moveinfo.start_angles),
  914. FIELD_AUTO(moveinfo.end_origin),
  915. FIELD_AUTO(moveinfo.end_angles),
  916. FIELD_AUTO(moveinfo.end_angles_reversed),
  917. FIELD_AUTO(moveinfo.sound_start),
  918. FIELD_AUTO(moveinfo.sound_middle),
  919. FIELD_AUTO(moveinfo.sound_end),
  920. FIELD_AUTO(moveinfo.accel),
  921. FIELD_AUTO(moveinfo.speed),
  922. FIELD_AUTO(moveinfo.decel),
  923. FIELD_AUTO(moveinfo.distance),
  924. FIELD_AUTO(moveinfo.wait),
  925. FIELD_AUTO(moveinfo.state),
  926. FIELD_AUTO(moveinfo.reversing),
  927. FIELD_AUTO(moveinfo.dir),
  928. FIELD_AUTO(moveinfo.dest),
  929. FIELD_AUTO(moveinfo.current_speed),
  930. FIELD_AUTO(moveinfo.move_speed),
  931. FIELD_AUTO(moveinfo.next_speed),
  932. FIELD_AUTO(moveinfo.remaining_distance),
  933. FIELD_AUTO(moveinfo.decel_distance),
  934. FIELD_AUTO(moveinfo.endfunc),
  935. FIELD_AUTO(moveinfo.blocked),
  936. FIELD_AUTO(moveinfo.curve_ref),
  937. FIELD_AUTO(moveinfo.curve_positions),
  938. FIELD_AUTO(moveinfo.curve_frame),
  939. FIELD_AUTO(moveinfo.subframe),
  940. FIELD_AUTO(moveinfo.num_subframes),
  941. FIELD_AUTO(moveinfo.num_frames_done),
  942. // monsterinfo_t
  943. FIELD_AUTO(monsterinfo.active_move),
  944. FIELD_AUTO(monsterinfo.next_move),
  945. FIELD_AUTO(monsterinfo.aiflags),
  946. FIELD_AUTO(monsterinfo.nextframe),
  947. FIELD_AUTO(monsterinfo.scale),
  948. FIELD_AUTO(monsterinfo.stand),
  949. FIELD_AUTO(monsterinfo.idle),
  950. FIELD_AUTO(monsterinfo.search),
  951. FIELD_AUTO(monsterinfo.walk),
  952. FIELD_AUTO(monsterinfo.run),
  953. FIELD_AUTO(monsterinfo.dodge),
  954. FIELD_AUTO(monsterinfo.attack),
  955. FIELD_AUTO(monsterinfo.melee),
  956. FIELD_AUTO(monsterinfo.sight),
  957. FIELD_AUTO(monsterinfo.checkattack),
  958. FIELD_AUTO(monsterinfo.setskin),
  959. FIELD_AUTO(monsterinfo.pausetime),
  960. FIELD_AUTO(monsterinfo.attack_finished),
  961. FIELD_AUTO(monsterinfo.fire_wait),
  962. FIELD_AUTO(monsterinfo.saved_goal),
  963. FIELD_AUTO(monsterinfo.search_time),
  964. FIELD_AUTO(monsterinfo.trail_time),
  965. FIELD_AUTO(monsterinfo.last_sighting),
  966. FIELD_AUTO(monsterinfo.attack_state),
  967. FIELD_AUTO(monsterinfo.lefty),
  968. FIELD_AUTO(monsterinfo.idle_time),
  969. FIELD_AUTO(monsterinfo.linkcount),
  970. FIELD_AUTO(monsterinfo.power_armor_type),
  971. FIELD_AUTO(monsterinfo.power_armor_power),
  972. FIELD_AUTO(monsterinfo.initial_power_armor_type),
  973. FIELD_AUTO(monsterinfo.max_power_armor_power),
  974. FIELD_AUTO(monsterinfo.weapon_sound),
  975. FIELD_AUTO(monsterinfo.engine_sound),
  976. FIELD_AUTO(monsterinfo.blocked),
  977. FIELD_AUTO(monsterinfo.last_hint_time),
  978. FIELD_AUTO(monsterinfo.goal_hint),
  979. FIELD_AUTO(monsterinfo.medicTries),
  980. FIELD_AUTO(monsterinfo.badMedic1),
  981. FIELD_AUTO(monsterinfo.badMedic2),
  982. FIELD_AUTO(monsterinfo.healer),
  983. FIELD_AUTO(monsterinfo.duck),
  984. FIELD_AUTO(monsterinfo.unduck),
  985. FIELD_AUTO(monsterinfo.sidestep),
  986. FIELD_AUTO(monsterinfo.base_height),
  987. FIELD_AUTO(monsterinfo.next_duck_time),
  988. FIELD_AUTO(monsterinfo.duck_wait_time),
  989. FIELD_AUTO(monsterinfo.last_player_enemy),
  990. FIELD_AUTO(monsterinfo.blindfire),
  991. FIELD_AUTO(monsterinfo.can_jump),
  992. FIELD_AUTO(monsterinfo.had_visibility),
  993. FIELD_AUTO(monsterinfo.drop_height),
  994. FIELD_AUTO(monsterinfo.jump_height),
  995. FIELD_AUTO(monsterinfo.blind_fire_delay),
  996. FIELD_AUTO(monsterinfo.blind_fire_target),
  997. FIELD_AUTO(monsterinfo.monster_slots),
  998. FIELD_AUTO(monsterinfo.monster_used),
  999. FIELD_AUTO(monsterinfo.commander),
  1000. FIELD_AUTO( monsterinfo.quad_time ),
  1001. FIELD_AUTO( monsterinfo.invincible_time ),
  1002. FIELD_AUTO( monsterinfo.double_time ),
  1003. FIELD_AUTO( monsterinfo.surprise_time ),
  1004. FIELD_AUTO( monsterinfo.armor_type ),
  1005. FIELD_AUTO( monsterinfo.armor_power ),
  1006. FIELD_AUTO( monsterinfo.close_sight_tripped ),
  1007. FIELD_AUTO( monsterinfo.melee_debounce_time ),
  1008. FIELD_AUTO( monsterinfo.strafe_check_time ),
  1009. FIELD_AUTO( monsterinfo.base_health ),
  1010. FIELD_AUTO( monsterinfo.health_scaling ),
  1011. FIELD_AUTO( monsterinfo.next_move_time ),
  1012. FIELD_AUTO( monsterinfo.bad_move_time ),
  1013. FIELD_AUTO( monsterinfo.bump_time ),
  1014. FIELD_AUTO( monsterinfo.random_change_time ),
  1015. FIELD_AUTO( monsterinfo.path_blocked_counter ),
  1016. FIELD_AUTO( monsterinfo.path_wait_time ),
  1017. FIELD_AUTO( monsterinfo.combat_style ),
  1018. FIELD_AUTO( monsterinfo.fly_max_distance ),
  1019. FIELD_AUTO( monsterinfo.fly_min_distance ),
  1020. FIELD_AUTO( monsterinfo.fly_acceleration ),
  1021. FIELD_AUTO( monsterinfo.fly_speed ),
  1022. FIELD_AUTO( monsterinfo.fly_ideal_position ),
  1023. FIELD_AUTO( monsterinfo.fly_position_time ),
  1024. FIELD_AUTO( monsterinfo.fly_buzzard ),
  1025. FIELD_AUTO( monsterinfo.fly_above ),
  1026. FIELD_AUTO( monsterinfo.fly_pinned ),
  1027. FIELD_AUTO( monsterinfo.fly_thrusters ),
  1028. FIELD_AUTO( monsterinfo.fly_recovery_time ),
  1029. FIELD_AUTO( monsterinfo.fly_recovery_dir ),
  1030. FIELD_AUTO( monsterinfo.checkattack_time ),
  1031. FIELD_AUTO( monsterinfo.start_frame ),
  1032. FIELD_AUTO( monsterinfo.dodge_time ),
  1033. FIELD_AUTO( monsterinfo.move_block_counter ),
  1034. FIELD_AUTO( monsterinfo.move_block_change_time ),
  1035. FIELD_AUTO( monsterinfo.react_to_damage_time ),
  1036. FIELD_AUTO(monsterinfo.jump_time),
  1037. FIELD_SIMPLE( monsterinfo.reinforcements, ST_REINFORCEMENTS ),
  1038. FIELD_AUTO( monsterinfo.chosen_reinforcements ),
  1039. // back to edict_t
  1040. FIELD_AUTO( plat2flags ),
  1041. FIELD_AUTO( offset ),
  1042. FIELD_AUTO( gravityVector ).set_is_empty( edict_t_gravityVector_is_empty ),
  1043. FIELD_AUTO( bad_area ),
  1044. FIELD_AUTO( hint_chain ),
  1045. FIELD_AUTO( monster_hint_chain ),
  1046. FIELD_AUTO( target_hint_chain ),
  1047. FIELD_AUTO( hint_chain_id ),
  1048. FIELD_AUTO( clock_message ),
  1049. FIELD_AUTO( dead_time ),
  1050. FIELD_AUTO( beam ),
  1051. FIELD_AUTO( beam2 ),
  1052. FIELD_AUTO(proboscus),
  1053. FIELD_AUTO( disintegrator ),
  1054. FIELD_AUTO( disintegrator_time ),
  1055. FIELD_AUTO( hackflags ),
  1056. FIELD_AUTO( fog.color ),
  1057. FIELD_AUTO( fog.density ),
  1058. FIELD_AUTO( fog.color_off ),
  1059. FIELD_AUTO( fog.density_off ),
  1060. FIELD_AUTO( fog.sky_factor ),
  1061. FIELD_AUTO( fog.sky_factor_off ),
  1062. FIELD_AUTO( heightfog.falloff ),
  1063. FIELD_AUTO( heightfog.density ),
  1064. FIELD_AUTO( heightfog.start_color ),
  1065. FIELD_AUTO( heightfog.start_dist ),
  1066. FIELD_AUTO( heightfog.end_color ),
  1067. FIELD_AUTO( heightfog.end_dist ),
  1068. FIELD_AUTO( heightfog.falloff_off ),
  1069. FIELD_AUTO( heightfog.density_off ),
  1070. FIELD_AUTO( heightfog.start_color_off ),
  1071. FIELD_AUTO( heightfog.start_dist_off ),
  1072. FIELD_AUTO( heightfog.end_color_off ),
  1073. FIELD_AUTO( heightfog.end_dist_off ),
  1074. FIELD_AUTO( item_picked_up_by ),
  1075. FIELD_AUTO( slime_debounce_time ),
  1076. FIELD_AUTO( bmodel_anim.start ),
  1077. FIELD_AUTO( bmodel_anim.end ),
  1078. FIELD_AUTO( bmodel_anim.style ),
  1079. FIELD_AUTO( bmodel_anim.speed ),
  1080. FIELD_AUTO( bmodel_anim.nowrap ),
  1081. FIELD_AUTO( bmodel_anim.alt_start ),
  1082. FIELD_AUTO( bmodel_anim.alt_end ),
  1083. FIELD_AUTO( bmodel_anim.alt_style ),
  1084. FIELD_AUTO( bmodel_anim.alt_speed ),
  1085. FIELD_AUTO( bmodel_anim.alt_nowrap ),
  1086. FIELD_AUTO( bmodel_anim.enabled ),
  1087. FIELD_AUTO( bmodel_anim.alternate ),
  1088. FIELD_AUTO( bmodel_anim.currently_alternate ),
  1089. FIELD_AUTO( bmodel_anim.next_tick ),
  1090. FIELD_AUTO( lastMOD.id ),
  1091. FIELD_AUTO( lastMOD.friendly_fire ),
  1092. SAVE_STRUCT_END
  1093. #undef DECLARE_SAVE_STRUCT
  1094. // clang-format on
  1095. inline size_t get_simple_type_size(save_type_id_t id, bool fatal = true)
  1096. {
  1097. switch (id)
  1098. {
  1099. case ST_BOOL:
  1100. return sizeof(bool);
  1101. case ST_INT8:
  1102. case ST_UINT8:
  1103. return sizeof(uint8_t);
  1104. case ST_INT16:
  1105. case ST_UINT16:
  1106. return sizeof(uint16_t);
  1107. case ST_INT32:
  1108. case ST_UINT32:
  1109. return sizeof(uint32_t);
  1110. case ST_INT64:
  1111. case ST_UINT64:
  1112. case ST_TIME:
  1113. return sizeof(uint64_t);
  1114. case ST_FLOAT:
  1115. return sizeof(float);
  1116. case ST_DOUBLE:
  1117. return sizeof(double);
  1118. case ST_ENTITY:
  1119. case ST_ITEM_POINTER:
  1120. return sizeof(size_t);
  1121. case ST_ITEM_INDEX:
  1122. return sizeof(uint32_t);
  1123. case ST_SAVABLE_DYNAMIC:
  1124. return sizeof(savable_allocated_memory_t<void *, 0>);
  1125. default:
  1126. if (fatal)
  1127. gi.Com_ErrorFmt("Can't calculate static size for type ID {}", (int32_t) id);
  1128. break;
  1129. }
  1130. return 0;
  1131. }
  1132. size_t get_complex_type_size(const save_type_t &type)
  1133. {
  1134. // these are simple types
  1135. if (auto simple = get_simple_type_size(type.id, false))
  1136. return simple;
  1137. switch (type.id)
  1138. {
  1139. case ST_STRUCT:
  1140. return type.count;
  1141. case ST_FIXED_ARRAY: {
  1142. save_type_t element_type;
  1143. size_t element_size;
  1144. if (type.type_resolver)
  1145. {
  1146. element_type = type.type_resolver();
  1147. element_size = get_complex_type_size(element_type);
  1148. }
  1149. else
  1150. {
  1151. element_size = get_simple_type_size((save_type_id_t) type.tag);
  1152. element_type = { (save_type_id_t) type.tag };
  1153. }
  1154. return element_size * type.count;
  1155. }
  1156. default:
  1157. gi.Com_ErrorFmt("Can't calculate static size for type ID {}", (int32_t) type.id);
  1158. }
  1159. return 0;
  1160. }
  1161. void read_save_struct_json(const Json::Value &json, void *data, const save_struct_t *structure);
  1162. void read_save_type_json(const Json::Value &json, void *data, const save_type_t *type, const char *field)
  1163. {
  1164. switch (type->id)
  1165. {
  1166. case ST_BOOL:
  1167. if (!json.isBool())
  1168. json_print_error(field, "expected boolean", false);
  1169. else
  1170. *((bool *) data) = json.asBool();
  1171. return;
  1172. case ST_ENUM:
  1173. if (!json.isIntegral())
  1174. json_print_error(field, "expected integer", false);
  1175. else if (type->count == 1)
  1176. {
  1177. if (json.isInt())
  1178. {
  1179. if (json.asInt() < INT8_MIN || json.asInt() > INT8_MAX)
  1180. json_print_error(field, "int8 out of range", false);
  1181. else
  1182. *((int8_t *) data) = json.asInt();
  1183. }
  1184. else if (json.isUInt())
  1185. {
  1186. if (json.asUInt() > UINT8_MAX)
  1187. json_print_error(field, "uint8 out of range", false);
  1188. else
  1189. *((uint8_t *) data) = json.asUInt();
  1190. }
  1191. else
  1192. json_print_error(field, "int8 out of range (is 64-bit)", false);
  1193. return;
  1194. }
  1195. else if (type->count == 2)
  1196. {
  1197. if (json.isInt())
  1198. {
  1199. if (json.asInt() < INT16_MIN || json.asInt() > INT16_MAX)
  1200. json_print_error(field, "int16 out of range", false);
  1201. else
  1202. *((int16_t *) data) = json.asInt();
  1203. }
  1204. else if (json.isUInt())
  1205. {
  1206. if (json.asUInt() > UINT16_MAX)
  1207. json_print_error(field, "uint16 out of range", false);
  1208. else
  1209. *((uint16_t *) data) = json.asUInt();
  1210. }
  1211. else
  1212. json_print_error(field, "int16 out of range (is 64-bit)", false);
  1213. return;
  1214. }
  1215. else if (type->count == 4)
  1216. {
  1217. if (json.isInt())
  1218. {
  1219. if (json.asInt64() < INT32_MIN || json.asInt64() > INT32_MAX)
  1220. json_print_error(field, "int32 out of range", false);
  1221. else
  1222. *((int32_t *) data) = json.asInt();
  1223. }
  1224. else if (json.isUInt())
  1225. {
  1226. if (json.asUInt64() > UINT32_MAX)
  1227. json_print_error(field, "uint32 out of range", false);
  1228. else
  1229. *((uint32_t *) data) = json.asUInt();
  1230. }
  1231. else
  1232. json_print_error(field, "int32 out of range (is 64-bit)", false);
  1233. return;
  1234. }
  1235. else if (type->count == 8)
  1236. {
  1237. if (json.isInt64())
  1238. *((int64_t *) data) = json.asInt64();
  1239. else if (json.isUInt64())
  1240. *((int64_t *) data) = json.asUInt64();
  1241. else if (json.isInt())
  1242. *((int64_t *) data) = json.asInt();
  1243. else if (json.isUInt())
  1244. *((int64_t *) data) = json.asUInt();
  1245. else
  1246. json_print_error(field, "int64 not integral", false);
  1247. return;
  1248. }
  1249. json_print_error(field, "invalid enum size", true);
  1250. return;
  1251. case ST_INT8:
  1252. if (!json.isInt())
  1253. json_print_error(field, "expected integer", false);
  1254. else if (json.asInt() < INT8_MIN || json.asInt() > INT8_MAX)
  1255. json_print_error(field, "int8 out of range", false);
  1256. else
  1257. *((int8_t *) data) = json.asInt();
  1258. return;
  1259. case ST_INT16:
  1260. if (!json.isInt())
  1261. json_print_error(field, "expected integer", false);
  1262. else if (json.asInt() < INT16_MIN || json.asInt() > INT16_MAX)
  1263. json_print_error(field, "int16 out of range", false);
  1264. else
  1265. *((int16_t *) data) = json.asInt();
  1266. return;
  1267. case ST_INT32:
  1268. if (!json.isInt())
  1269. json_print_error(field, "expected integer", false);
  1270. else if (json.asInt() < INT32_MIN || json.asInt() > INT32_MAX)
  1271. json_print_error(field, "int32 out of range", false);
  1272. else
  1273. *((int32_t *) data) = json.asInt();
  1274. return;
  1275. case ST_INT64:
  1276. if (!json.isInt64())
  1277. json_print_error(field, "expected integer", false);
  1278. else
  1279. *((int64_t *) data) = json.asInt64();
  1280. return;
  1281. case ST_UINT8:
  1282. if (!json.isUInt())
  1283. json_print_error(field, "expected integer", false);
  1284. else if (json.asUInt() > UINT8_MAX)
  1285. json_print_error(field, "uint8 out of range", false);
  1286. else
  1287. *((uint8_t *) data) = json.asUInt();
  1288. return;
  1289. case ST_UINT16:
  1290. if (!json.isUInt())
  1291. json_print_error(field, "expected integer", false);
  1292. else if (json.asUInt() > UINT16_MAX)
  1293. json_print_error(field, "uint16 out of range", false);
  1294. else
  1295. *((uint16_t *) data) = json.asUInt();
  1296. return;
  1297. case ST_UINT32:
  1298. if (!json.isUInt())
  1299. json_print_error(field, "expected integer", false);
  1300. else if (json.asUInt() > UINT32_MAX)
  1301. json_print_error(field, "uint32 out of range", false);
  1302. else
  1303. *((uint32_t *) data) = json.asUInt();
  1304. return;
  1305. case ST_UINT64:
  1306. if (!json.isUInt64())
  1307. json_print_error(field, "expected integer", false);
  1308. else
  1309. *((uint64_t *) data) = json.asUInt64();
  1310. return;
  1311. case ST_FLOAT:
  1312. if (!json.isDouble())
  1313. json_print_error(field, "expected number", false);
  1314. else if (isnan(json.asDouble()))
  1315. *((float *) data) = std::numeric_limits<float>::quiet_NaN();
  1316. else
  1317. *((float *) data) = json.asFloat();
  1318. return;
  1319. case ST_DOUBLE:
  1320. if (!json.isDouble())
  1321. json_print_error(field, "expected number", false);
  1322. else
  1323. *((double *) data) = json.asDouble();
  1324. return;
  1325. case ST_STRING:
  1326. if (json.isNull())
  1327. *((char **) data) = nullptr;
  1328. else if (json.isString())
  1329. {
  1330. if (type->count && strlen(json.asCString()) >= type->count)
  1331. json_print_error(field, "static-length dynamic string overrun", false);
  1332. else
  1333. {
  1334. size_t len = strlen(json.asCString());
  1335. char *str = *((char **) data) = (char *) gi.TagMalloc(type->count ? type->count : (len + 1), type->tag);
  1336. strcpy(str, json.asCString());
  1337. str[len] = 0;
  1338. }
  1339. }
  1340. else if (json.isArray())
  1341. {
  1342. if (type->count && json.size() >= type->count - 1)
  1343. json_print_error(field, "static-length dynamic string overrun", false);
  1344. else
  1345. {
  1346. size_t len = json.size();
  1347. char *str = *((char **) data) = (char *) gi.TagMalloc(type->count ? type->count : (len + 1), type->tag);
  1348. for (Json::Value::ArrayIndex i = 0; i < json.size(); i++)
  1349. {
  1350. const Json::Value &chr = json[i];
  1351. if (!chr.isInt())
  1352. json_print_error(field, "expected number", false);
  1353. else if (chr.asInt() < 0 || chr.asInt() > UINT8_MAX)
  1354. json_print_error(field, "char out of range", false);
  1355. str[i] = chr.asInt();
  1356. }
  1357. str[len] = 0;
  1358. }
  1359. }
  1360. else
  1361. json_print_error(field, "expected string, array or null", false);
  1362. return;
  1363. case ST_FIXED_STRING:
  1364. if (json.isString())
  1365. {
  1366. if (type->count && strlen(json.asCString()) >= type->count)
  1367. json_print_error(field, "fixed length string overrun", false);
  1368. else
  1369. strcpy((char *) data, json.asCString());
  1370. }
  1371. else if (json.isArray())
  1372. {
  1373. if (type->count && json.size() >= type->count - 1)
  1374. json_print_error(field, "fixed length string overrun", false);
  1375. else
  1376. {
  1377. Json::Value::ArrayIndex i;
  1378. for (i = 0; i < json.size(); i++)
  1379. {
  1380. const Json::Value &chr = json[i];
  1381. if (!chr.isInt())
  1382. json_print_error(field, "expected number", false);
  1383. else if (chr.asInt() < 0 || chr.asInt() > UINT8_MAX)
  1384. json_print_error(field, "char out of range", false);
  1385. ((char *) data)[i] = chr.asInt();
  1386. }
  1387. ((char *) data)[i] = 0;
  1388. }
  1389. }
  1390. else
  1391. json_print_error(field, "expected string or array", false);
  1392. return;
  1393. case ST_FIXED_ARRAY:
  1394. if (!json.isArray())
  1395. json_print_error(field, "expected array", false);
  1396. else if (type->count != json.size())
  1397. json_print_error(field, "fixed array length mismatch", false);
  1398. else
  1399. {
  1400. uint8_t *element = (uint8_t *) data;
  1401. size_t element_size;
  1402. save_type_t element_type;
  1403. if (type->type_resolver)
  1404. {
  1405. element_type = type->type_resolver();
  1406. element_size = get_complex_type_size(element_type);
  1407. }
  1408. else
  1409. {
  1410. element_size = get_simple_type_size((save_type_id_t) type->tag);
  1411. element_type = { (save_type_id_t) type->tag };
  1412. }
  1413. for (Json::Value::ArrayIndex i = 0; i < type->count; i++, element += element_size)
  1414. {
  1415. const Json::Value &v = json[i];
  1416. read_save_type_json(v, element, &element_type,
  1417. fmt::format("[{}]", i).c_str());
  1418. }
  1419. }
  1420. return;
  1421. case ST_SAVABLE_DYNAMIC:
  1422. if (!json.isArray())
  1423. json_print_error(field, "expected array", false);
  1424. else
  1425. {
  1426. savable_allocated_memory_t<void, 0> *savptr = (savable_allocated_memory_t<void, 0> *) data;
  1427. size_t element_size;
  1428. save_type_t element_type;
  1429. if (type->type_resolver)
  1430. {
  1431. element_type = type->type_resolver();
  1432. element_size = get_complex_type_size(element_type);
  1433. }
  1434. else
  1435. {
  1436. element_size = get_simple_type_size((save_type_id_t) type->tag);
  1437. element_type = { (save_type_id_t) type->tag };
  1438. }
  1439. savptr->count = json.size();
  1440. savptr->ptr = gi.TagMalloc(element_size * savptr->count, type->count);
  1441. byte *out_element = (byte *) savptr->ptr;
  1442. for (Json::Value::ArrayIndex i = 0; i < savptr->count; i++, out_element += element_size)
  1443. {
  1444. const Json::Value &v = json[i];
  1445. read_save_type_json(v, out_element, &element_type,
  1446. fmt::format("[{}]", i).c_str());
  1447. }
  1448. }
  1449. return;
  1450. case ST_BITSET:
  1451. type->read(data, json, field);
  1452. return;
  1453. case ST_STRUCT:
  1454. if (!json.isNull())
  1455. {
  1456. json_push_stack(field);
  1457. read_save_struct_json(json, data, type->structure);
  1458. json_pop_stack();
  1459. }
  1460. return;
  1461. case ST_ENTITY:
  1462. if (json.isNull())
  1463. *((edict_t **) data) = nullptr;
  1464. else if (!json.isUInt())
  1465. json_print_error(field, "expected null or integer", false);
  1466. else if (json.asUInt() >= globals.max_edicts)
  1467. json_print_error(field, "entity index out of range", false);
  1468. else
  1469. *((edict_t **) data) = globals.edicts + json.asUInt();
  1470. return;
  1471. case ST_ITEM_POINTER:
  1472. case ST_ITEM_INDEX: {
  1473. gitem_t *item;
  1474. if (json.isNull())
  1475. item = nullptr;
  1476. else if (json.isString())
  1477. {
  1478. const char *classname = json.asCString();
  1479. item = FindItemByClassname(classname);
  1480. if (item == nullptr)
  1481. {
  1482. json_print_error(field, G_Fmt("item {} missing", classname).data(), false);
  1483. return;
  1484. }
  1485. }
  1486. else
  1487. {
  1488. json_print_error(field, "expected null or string", false);
  1489. return;
  1490. }
  1491. if (type->id == ST_ITEM_POINTER)
  1492. *((gitem_t **) data) = item;
  1493. else
  1494. *((int32_t *) data) = item ? item->id : 0;
  1495. return;
  1496. }
  1497. case ST_TIME:
  1498. if (!json.isInt64())
  1499. json_print_error(field, "expected integer", false);
  1500. else
  1501. *((gtime_t *) data) = gtime_t::from_ms(json.asInt64());
  1502. return;
  1503. case ST_DATA:
  1504. if (json.isNull())
  1505. *((void **) data) = nullptr;
  1506. else if (!json.isString())
  1507. json_print_error(field, "expected null or string", false);
  1508. else
  1509. {
  1510. const char *name = json.asCString();
  1511. auto link = list_str_hash.find(name);
  1512. if (link == list_str_hash.end())
  1513. json_print_error(
  1514. field, G_Fmt("unknown pointer {} in list {}", name, type->tag).data(), false);
  1515. else
  1516. (*reinterpret_cast<save_void_t *>(data)) = save_void_t(link->second);
  1517. }
  1518. return;
  1519. case ST_INVENTORY:
  1520. if (!json.isObject())
  1521. json_print_error(field, "expected object", false);
  1522. else
  1523. {
  1524. int32_t *inventory_ptr = (int32_t *) data;
  1525. //for (auto key : json.getMemberNames())
  1526. for (auto it = json.begin(); it != json.end(); it++)
  1527. {
  1528. //const char *classname = key.c_str();
  1529. const char *dummy;
  1530. const char *classname = it.memberName(&dummy);
  1531. const Json::Value &value = *it;
  1532. if (!value.isInt())
  1533. {
  1534. json_push_stack(classname);
  1535. json_print_error(field, "expected integer", false);
  1536. json_pop_stack();
  1537. continue;
  1538. }
  1539. gitem_t *item = FindItemByClassname(classname);
  1540. if (!item)
  1541. {
  1542. json_push_stack(classname);
  1543. json_print_error(field, G_Fmt("can't find item {}", classname).data(), false);
  1544. json_pop_stack();
  1545. continue;
  1546. }
  1547. inventory_ptr[item->id] = value.asInt();
  1548. }
  1549. return;
  1550. }
  1551. return;
  1552. case ST_REINFORCEMENTS:
  1553. if (!json.isArray())
  1554. json_print_error(field, "expected array", false);
  1555. else
  1556. {
  1557. reinforcement_list_t *list_ptr = (reinforcement_list_t *) data;
  1558. list_ptr->num_reinforcements = json.size();
  1559. list_ptr->reinforcements = (reinforcement_t *) gi.TagMalloc(sizeof(reinforcement_t) * list_ptr->num_reinforcements, TAG_LEVEL);
  1560. reinforcement_t *p = list_ptr->reinforcements;
  1561. for (Json::Value::ArrayIndex i = 0; i < json.size(); i++, p++)
  1562. {
  1563. const Json::Value &value = json[i];
  1564. if (!value.isObject())
  1565. {
  1566. json_push_stack(fmt::format("{}", i));
  1567. json_print_error(field, "expected object", false);
  1568. json_pop_stack();
  1569. continue;
  1570. }
  1571. // quick type checks
  1572. if (!value["classname"].isString())
  1573. {
  1574. json_push_stack(fmt::format("{}.classname", i));
  1575. json_print_error(field, "expected string", false);
  1576. json_pop_stack();
  1577. continue;
  1578. }
  1579. if (!value["mins"].isArray() || value["mins"].size() != 3)
  1580. {
  1581. json_push_stack(fmt::format("{}.mins", i));
  1582. json_print_error(field, "expected array[3]", false);
  1583. json_pop_stack();
  1584. continue;
  1585. }
  1586. if (!value["maxs"].isArray() || value["maxs"].size() != 3)
  1587. {
  1588. json_push_stack(fmt::format("{}.maxs", i));
  1589. json_print_error(field, "expected array[3]", false);
  1590. json_pop_stack();
  1591. continue;
  1592. }
  1593. if (!value["strength"].isInt())
  1594. {
  1595. json_push_stack(fmt::format("{}.strength", i));
  1596. json_print_error(field, "expected int", false);
  1597. json_pop_stack();
  1598. continue;
  1599. }
  1600. p->classname = G_CopyString(value["classname"].asCString(), TAG_LEVEL);
  1601. p->strength = value["strength"].asInt();
  1602. for (int32_t x = 0; x < 3; x++)
  1603. {
  1604. p->mins[x] = value["mins"][x].asInt();
  1605. p->maxs[x] = value["maxs"][x].asInt();
  1606. }
  1607. }
  1608. }
  1609. return;
  1610. default:
  1611. gi.Com_ErrorFmt("Can't read type ID {}", (int32_t) type->id);
  1612. break;
  1613. }
  1614. }
  1615. bool write_save_struct_json(const void *data, const save_struct_t *structure, bool null_for_empty, Json::Value &output);
  1616. #define TYPED_DATA_IS_EMPTY(type, expr) (type->is_empty ? type->is_empty(data) : (expr))
  1617. inline bool string_is_high(const char *c)
  1618. {
  1619. for (size_t i = 0; i < strlen(c); i++)
  1620. if (c[i] & 128)
  1621. return true;
  1622. return false;
  1623. }
  1624. inline Json::Value string_to_bytes(const char *c)
  1625. {
  1626. Json::Value array(Json::arrayValue);
  1627. for (size_t i = 0; i < strlen(c); i++)
  1628. array.append((int32_t) (unsigned char) c[i]);
  1629. return array;
  1630. }
  1631. // fetch a JSON value for the specified data.
  1632. // if allow_empty is true, false will be returned for
  1633. // values that are the same as zero'd memory, to save
  1634. // space in the resulting JSON. output will be
  1635. // unmodified in that case.
  1636. bool write_save_type_json(const void *data, const save_type_t *type, bool null_for_empty, Json::Value &output)
  1637. {
  1638. switch (type->id)
  1639. {
  1640. case ST_BOOL:
  1641. if (null_for_empty && TYPED_DATA_IS_EMPTY(type, !*(const bool *) data))
  1642. return false;
  1643. output = Json::Value(*(const bool *) data);
  1644. return true;
  1645. case ST_ENUM:
  1646. if (type->count == 1)
  1647. {
  1648. if (null_for_empty && TYPED_DATA_IS_EMPTY(type, !*(const int8_t *) data))
  1649. return false;
  1650. output = Json::Value(*(const int8_t *) data);
  1651. return true;
  1652. }
  1653. else if (type->count == 2)
  1654. {
  1655. if (null_for_empty && TYPED_DATA_IS_EMPTY(type, !*(const int16_t *) data))
  1656. return false;
  1657. output = Json::Value(*(const int16_t *) data);
  1658. return true;
  1659. }
  1660. else if (type->count == 4)
  1661. {
  1662. if (null_for_empty && TYPED_DATA_IS_EMPTY(type, !*(const int32_t *) data))
  1663. return false;
  1664. output = Json::Value(*(const int32_t *) data);
  1665. return true;
  1666. }
  1667. else if (type->count == 8)
  1668. {
  1669. if (null_for_empty && TYPED_DATA_IS_EMPTY(type, !*(const int64_t *) data))
  1670. return false;
  1671. output = Json::Value(*(const int64_t *) data);
  1672. return true;
  1673. }
  1674. gi.Com_Error("invalid enum length");
  1675. break;
  1676. case ST_INT8:
  1677. if (null_for_empty && TYPED_DATA_IS_EMPTY(type, !*(const int8_t *) data))
  1678. return false;
  1679. output = Json::Value(*(const int8_t *) data);
  1680. return true;
  1681. case ST_INT16:
  1682. if (null_for_empty && TYPED_DATA_IS_EMPTY(type, !*(const int16_t *) data))
  1683. return false;
  1684. output = Json::Value(*(const int16_t *) data);
  1685. return true;
  1686. case ST_INT32:
  1687. if (null_for_empty && TYPED_DATA_IS_EMPTY(type, !*(const int32_t *) data))
  1688. return false;
  1689. output = Json::Value(*(const int32_t *) data);
  1690. return true;
  1691. case ST_INT64:
  1692. if (null_for_empty && TYPED_DATA_IS_EMPTY(type, !*(const int64_t *) data))
  1693. return false;
  1694. output = Json::Value(*(const int64_t *) data);
  1695. return true;
  1696. case ST_UINT8:
  1697. if (null_for_empty && TYPED_DATA_IS_EMPTY(type, !*(const uint8_t *) data))
  1698. return false;
  1699. output = Json::Value(*(const uint8_t *) data);
  1700. return true;
  1701. case ST_UINT16:
  1702. if (null_for_empty && TYPED_DATA_IS_EMPTY(type, !*(const uint16_t *) data))
  1703. return false;
  1704. output = Json::Value(*(const uint16_t *) data);
  1705. return true;
  1706. case ST_UINT32:
  1707. if (null_for_empty && TYPED_DATA_IS_EMPTY(type, !*(const uint32_t *) data))
  1708. return false;
  1709. output = Json::Value(*(const uint32_t *) data);
  1710. return true;
  1711. case ST_UINT64:
  1712. if (null_for_empty && TYPED_DATA_IS_EMPTY(type, !*(const uint64_t *) data))
  1713. return false;
  1714. output = Json::Value(*(const uint64_t *) data);
  1715. return true;
  1716. case ST_FLOAT:
  1717. if (null_for_empty && TYPED_DATA_IS_EMPTY(type, !*(const float *) data))
  1718. return false;
  1719. output = Json::Value(static_cast<double>(*(const float *) data));
  1720. return true;
  1721. case ST_DOUBLE:
  1722. if (null_for_empty && TYPED_DATA_IS_EMPTY(type, !*(const double *) data))
  1723. return false;
  1724. output = Json::Value(*(const double *) data);
  1725. return true;
  1726. case ST_STRING: {
  1727. const char *const *str = reinterpret_cast<const char *const *>(data);
  1728. if (null_for_empty && TYPED_DATA_IS_EMPTY(type, *str == nullptr))
  1729. return false;
  1730. output = *str == nullptr ? Json::Value::nullSingleton() : string_is_high(*str) ? Json::Value(string_to_bytes(*str)) : Json::Value(Json::StaticString(*str));
  1731. return true;
  1732. }
  1733. case ST_FIXED_STRING:
  1734. if (null_for_empty && TYPED_DATA_IS_EMPTY(type, !strlen((const char *) data)))
  1735. return false;
  1736. output = string_is_high((const char *) data) ? Json::Value(string_to_bytes((const char *) data)) : Json::Value(Json::StaticString((const char *) data));
  1737. return true;
  1738. case ST_FIXED_ARRAY: {
  1739. const uint8_t *element = (const uint8_t *) data;
  1740. size_t i;
  1741. size_t element_size;
  1742. save_type_t element_type;
  1743. if (type->type_resolver)
  1744. {
  1745. element_type = type->type_resolver();
  1746. element_size = get_complex_type_size(element_type);
  1747. }
  1748. else
  1749. {
  1750. element_size = get_simple_type_size((save_type_id_t) type->tag);
  1751. element_type = { (save_type_id_t) type->tag };
  1752. }
  1753. if (null_for_empty)
  1754. {
  1755. if (type->is_empty)
  1756. {
  1757. if (type->is_empty(data))
  1758. return false;
  1759. }
  1760. else
  1761. {
  1762. for (i = 0; i < type->count; i++, element += element_size)
  1763. {
  1764. Json::Value value;
  1765. bool valid_value = write_save_type_json(element, &element_type, !element_type.never_empty, value);
  1766. if (valid_value)
  1767. break;
  1768. }
  1769. if (i == type->count)
  1770. return false;
  1771. }
  1772. }
  1773. element = (const uint8_t *) data;
  1774. Json::Value v(Json::arrayValue);
  1775. for (i = 0; i < type->count; i++, element += element_size)
  1776. {
  1777. Json::Value value;
  1778. write_save_type_json(element, &element_type, false, value);
  1779. v.append(std::move(value));
  1780. }
  1781. output = std::move(v);
  1782. return true;
  1783. }
  1784. case ST_SAVABLE_DYNAMIC: {
  1785. const savable_allocated_memory_t<void, 0> *savptr = (const savable_allocated_memory_t<void, 0> *) data;
  1786. size_t i;
  1787. size_t element_size;
  1788. save_type_t element_type;
  1789. if (type->type_resolver)
  1790. {
  1791. element_type = type->type_resolver();
  1792. element_size = get_complex_type_size(element_type);
  1793. }
  1794. else
  1795. {
  1796. element_size = get_simple_type_size((save_type_id_t) type->tag);
  1797. element_type = { (save_type_id_t) type->tag };
  1798. }
  1799. const uint8_t *element = (const uint8_t *) savptr->ptr;
  1800. if (null_for_empty)
  1801. {
  1802. if (type->is_empty)
  1803. {
  1804. if (type->is_empty(data))
  1805. return false;
  1806. }
  1807. else
  1808. {
  1809. for (i = 0; i < savptr->count; i++, element += element_size)
  1810. {
  1811. Json::Value value;
  1812. bool valid_value = write_save_type_json(element, &element_type, !element_type.never_empty, value);
  1813. if (valid_value)
  1814. break;
  1815. }
  1816. if (i == savptr->count)
  1817. return false;
  1818. }
  1819. }
  1820. element = (const uint8_t *) savptr->ptr;
  1821. Json::Value v(Json::arrayValue);
  1822. for (i = 0; i < savptr->count; i++, element += element_size)
  1823. {
  1824. Json::Value value;
  1825. write_save_type_json(element, &element_type, false, value);
  1826. v.append(std::move(value));
  1827. }
  1828. output = std::move(v);
  1829. return true;
  1830. }
  1831. case ST_BITSET:
  1832. return type->write(data, null_for_empty, output);
  1833. case ST_STRUCT: {
  1834. if (type->is_empty && type->is_empty(data))
  1835. return false;
  1836. Json::Value obj;
  1837. bool valid_value = write_save_struct_json(data, type->structure, true, obj);
  1838. if (null_for_empty && (!valid_value || !obj.size()))
  1839. return false;
  1840. output = std::move(obj);
  1841. return true;
  1842. }
  1843. case ST_ENTITY: {
  1844. const edict_t *entity = *reinterpret_cast<const edict_t *const *>(data);
  1845. if (null_for_empty && TYPED_DATA_IS_EMPTY(type, entity == nullptr))
  1846. return false;
  1847. if (!entity)
  1848. {
  1849. output = Json::Value::nullSingleton();
  1850. return true;
  1851. }
  1852. output = Json::Value(entity->s.number);
  1853. return true;
  1854. }
  1855. case ST_ITEM_POINTER: {
  1856. const gitem_t *item = *reinterpret_cast<const gitem_t *const *>(data);
  1857. if (item != nullptr && item->id != 0)
  1858. if (!strlen(item->classname))
  1859. gi.Com_ErrorFmt("Attempt to persist invalid item {} (index {})", item->pickup_name, (int32_t) item->id);
  1860. if (null_for_empty && TYPED_DATA_IS_EMPTY(type, item == nullptr))
  1861. return false;
  1862. if (item == nullptr)
  1863. {
  1864. output = Json::Value::nullSingleton();
  1865. return true;
  1866. }
  1867. output = Json::Value(Json::StaticString(item->classname));
  1868. return true;
  1869. }
  1870. case ST_ITEM_INDEX: {
  1871. const item_id_t index = *reinterpret_cast<const item_id_t *>(data);
  1872. if (index < IT_NULL || index >= IT_TOTAL)
  1873. gi.Com_ErrorFmt("Attempt to persist invalid item index {}", (int32_t) index);
  1874. const gitem_t *item = GetItemByIndex(index);
  1875. if (index)
  1876. if (!strlen(item->classname))
  1877. gi.Com_ErrorFmt("Attempt to persist invalid item {} (index {})", item->pickup_name, (int32_t) item->id);
  1878. if (null_for_empty && TYPED_DATA_IS_EMPTY(type, item == nullptr))
  1879. return false;
  1880. if (item == nullptr)
  1881. {
  1882. output = Json::Value::nullSingleton();
  1883. return true;
  1884. }
  1885. output = Json::Value(Json::StaticString(item->classname));
  1886. return true;
  1887. }
  1888. case ST_TIME: {
  1889. const gtime_t &time = *(const gtime_t *) data;
  1890. if (null_for_empty && TYPED_DATA_IS_EMPTY(type, !time))
  1891. return false;
  1892. output = Json::Value(time.milliseconds());
  1893. return true;
  1894. }
  1895. case ST_DATA: {
  1896. const save_void_t &ptr = *reinterpret_cast<const save_void_t *>(data);
  1897. if (null_for_empty && TYPED_DATA_IS_EMPTY(type, !ptr))
  1898. return false;
  1899. if (!ptr)
  1900. {
  1901. output = Json::Value::nullSingleton();
  1902. return true;
  1903. }
  1904. if (!ptr.save_list())
  1905. {
  1906. gi.Com_ErrorFmt("Attempt to persist invalid data pointer {} in list {}", ptr.pointer(), type->tag);
  1907. return false;
  1908. }
  1909. output = Json::Value(Json::StaticString(ptr.save_list()->name));
  1910. return true;
  1911. }
  1912. case ST_INVENTORY: {
  1913. Json::Value inventory = Json::Value(Json::objectValue);
  1914. const int32_t *inventory_ptr = (const int32_t *) data;
  1915. for (item_id_t i = static_cast<item_id_t>(IT_NULL + 1); i < IT_TOTAL; i = static_cast<item_id_t>(i + 1))
  1916. {
  1917. gitem_t *item = GetItemByIndex(i);
  1918. if (!item || !item->classname)
  1919. {
  1920. if (inventory_ptr[i])
  1921. gi.Com_ErrorFmt("Item index {} is in inventory but has no classname", (int32_t) i);
  1922. continue;
  1923. }
  1924. if (inventory_ptr[i])
  1925. inventory[item->classname] = Json::Value(inventory_ptr[i]);
  1926. }
  1927. if (null_for_empty && inventory.empty())
  1928. return false;
  1929. output = std::move(inventory);
  1930. return true;
  1931. }
  1932. case ST_REINFORCEMENTS: {
  1933. const reinforcement_list_t *reinforcement_ptr = (const reinforcement_list_t *) data;
  1934. if (null_for_empty && !reinforcement_ptr->num_reinforcements)
  1935. return false;
  1936. Json::Value reinforcements = Json::Value(Json::arrayValue);
  1937. reinforcements.resize(reinforcement_ptr->num_reinforcements);
  1938. for (uint32_t i = 0; i < reinforcement_ptr->num_reinforcements; i++)
  1939. {
  1940. const reinforcement_t *reinforcement = &reinforcement_ptr->reinforcements[i];
  1941. Json::Value obj = Json::Value(Json::objectValue);
  1942. obj["classname"] = Json::StaticString(reinforcement->classname);
  1943. obj["mins"] = Json::Value(Json::arrayValue);
  1944. obj["maxs"] = Json::Value(Json::arrayValue);
  1945. for (int32_t x = 0; x < 3; x++)
  1946. {
  1947. obj["mins"][x] = reinforcement->mins[x];
  1948. obj["maxs"][x] = reinforcement->maxs[x];
  1949. }
  1950. obj["strength"] = reinforcement->strength;
  1951. reinforcements[i] = obj;
  1952. }
  1953. output = std::move(reinforcements);
  1954. return true;
  1955. }
  1956. default:
  1957. gi.Com_ErrorFmt("Can't persist type ID {}", (int32_t) type->id);
  1958. }
  1959. return false;
  1960. }
  1961. // write the specified data+structure to the JSON object
  1962. // referred to by `json`.
  1963. bool write_save_struct_json(const void *data, const save_struct_t *structure, bool null_for_empty, Json::Value &output)
  1964. {
  1965. Json::Value obj(Json::objectValue);
  1966. for (auto &field : structure->fields)
  1967. {
  1968. const void *p = ((const uint8_t *) data) + field.offset;
  1969. Json::Value value;
  1970. bool valid_value = write_save_type_json(p, &field.type, !field.type.never_empty, value);
  1971. if (valid_value)
  1972. obj[field.name].swap(value);
  1973. }
  1974. if (null_for_empty && obj.empty())
  1975. return false;
  1976. output = std::move(obj);
  1977. return true;
  1978. }
  1979. // read the specified data+structure from the JSON object
  1980. // referred to by `json`.
  1981. void read_save_struct_json(const Json::Value &json, void *data, const save_struct_t *structure)
  1982. {
  1983. if (!json.isObject())
  1984. {
  1985. json_print_error("", "expected object", false);
  1986. return;
  1987. }
  1988. //for (auto key : json.getMemberNames())
  1989. for (auto it = json.begin(); it != json.end(); it++)
  1990. {
  1991. //const char *classname = key.c_str();
  1992. const char *dummy;
  1993. const char *key = it.memberName(&dummy);
  1994. const Json::Value &value = *it;//json[key];
  1995. const save_field_t *field;
  1996. for (field = structure->fields.begin(); field != structure->fields.end(); field++)
  1997. {
  1998. if (strcmp(key, field->name) == 0)
  1999. {
  2000. void *p = ((uint8_t *) data) + field->offset;
  2001. read_save_type_json(value, p, &field->type, field->name);
  2002. break;
  2003. }
  2004. }
  2005. if (!field->name)
  2006. json_print_error(key, "unknown field", false);
  2007. }
  2008. }
  2009. #include <fstream>
  2010. #include <memory>
  2011. static Json::Value parseJson(const char *jsonString)
  2012. {
  2013. Json::CharReaderBuilder reader;
  2014. reader["allowSpecialFloats"] = true;
  2015. Json::Value json;
  2016. JSONCPP_STRING errs;
  2017. std::stringstream ss(jsonString, std::ios_base::in | std::ios_base::binary);
  2018. if (!Json::parseFromStream(reader, ss, &json, &errs))
  2019. gi.Com_ErrorFmt("Couldn't decode JSON: {}", errs.c_str());
  2020. if (!json.isObject())
  2021. gi.Com_Error("expected object at root");
  2022. return json;
  2023. }
  2024. static char *saveJson(const Json::Value &json, size_t *out_size)
  2025. {
  2026. Json::StreamWriterBuilder builder;
  2027. builder["indentation"] = "\t";
  2028. builder["useSpecialFloats"] = true;
  2029. const std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
  2030. std::stringstream ss(std::ios_base::out | std::ios_base::binary);
  2031. writer->write(json, &ss);
  2032. *out_size = ss.tellp();
  2033. char *const out = static_cast<char *>(gi.TagMalloc(*out_size + 1, TAG_GAME));
  2034. // FIXME: some day...
  2035. std::string v = ss.str();
  2036. memcpy(out, v.c_str(), *out_size);
  2037. out[*out_size] = '\0';
  2038. return out;
  2039. }
  2040. // new entry point for WriteGame.
  2041. // returns pointer to TagMalloc'd JSON string.
  2042. char *WriteGameJson(bool autosave, size_t *out_size)
  2043. {
  2044. if (!autosave)
  2045. SaveClientData();
  2046. Json::Value json(Json::objectValue);
  2047. json["save_version"] = SAVE_FORMAT_VERSION;
  2048. // TODO: engine version ID?
  2049. // write game
  2050. game.autosaved = autosave;
  2051. write_save_struct_json(&game, &game_locals_t_savestruct, false, json["game"]);
  2052. game.autosaved = false;
  2053. // write clients
  2054. Json::Value clients(Json::arrayValue);
  2055. for (size_t i = 0; i < game.maxclients; i++)
  2056. {
  2057. Json::Value v;
  2058. write_save_struct_json(&game.clients[i], &gclient_t_savestruct, false, v);
  2059. clients.append(std::move(v));
  2060. }
  2061. json["clients"] = std::move(clients);
  2062. return saveJson(json, out_size);
  2063. }
  2064. void G_PrecacheInventoryItems();
  2065. // new entry point for ReadGame.
  2066. // takes in pointer to JSON data. does
  2067. // not store or modify it.
  2068. void ReadGameJson(const char *jsonString)
  2069. {
  2070. gi.FreeTags(TAG_GAME);
  2071. Json::Value json = parseJson(jsonString);
  2072. uint32_t max_entities = game.maxentities;
  2073. uint32_t max_clients = game.maxclients;
  2074. game = {};
  2075. g_edicts = (edict_t *) gi.TagMalloc(max_entities * sizeof(g_edicts[0]), TAG_GAME);
  2076. game.clients = (gclient_t *) gi.TagMalloc(max_clients * sizeof(game.clients[0]), TAG_GAME);
  2077. globals.edicts = g_edicts;
  2078. // read game
  2079. json_push_stack("game");
  2080. read_save_struct_json(json["game"], &game, &game_locals_t_savestruct);
  2081. json_pop_stack();
  2082. // read clients
  2083. const Json::Value &clients = json["clients"];
  2084. if (!clients.isArray())
  2085. gi.Com_Error("expected \"clients\" to be array");
  2086. else if (clients.size() != game.maxclients)
  2087. gi.Com_Error("mismatched client size");
  2088. size_t i = 0;
  2089. for (auto &v : clients)
  2090. {
  2091. json_push_stack(fmt::format("clients[{}]", i));
  2092. read_save_struct_json(v, &game.clients[i++], &gclient_t_savestruct);
  2093. json_pop_stack();
  2094. }
  2095. G_PrecacheInventoryItems();
  2096. }
  2097. // new entry point for WriteLevel.
  2098. // returns pointer to TagMalloc'd JSON string.
  2099. char *WriteLevelJson(bool transition, size_t *out_size)
  2100. {
  2101. // update current level entry now, just so we can
  2102. // use gamemap to test EOU
  2103. G_UpdateLevelEntry();
  2104. Json::Value json(Json::objectValue);
  2105. json["save_version"] = SAVE_FORMAT_VERSION;
  2106. // write level
  2107. write_save_struct_json(&level, &level_locals_t_savestruct, false, json["level"]);
  2108. // write entities
  2109. Json::Value entities(Json::objectValue);
  2110. char number[16];
  2111. for (uint32_t i = 0; i < globals.num_edicts; i++)
  2112. {
  2113. if (!globals.edicts[i].inuse)
  2114. continue;
  2115. // clear all the client inuse flags before saving so that
  2116. // when the level is re-entered, the clients will spawn
  2117. // at spawn points instead of occupying body shells
  2118. else if (transition && i >= 1 && i <= game.maxclients)
  2119. continue;
  2120. auto result = std::to_chars(number, number + sizeof(number) - 1, i);
  2121. if (result.ec == std::errc())
  2122. *result.ptr = '\0';
  2123. else
  2124. gi.Com_ErrorFmt("error formatting number: {}", std::make_error_code(result.ec).message());
  2125. write_save_struct_json(&globals.edicts[i], &edict_t_savestruct, false, entities[number]);
  2126. }
  2127. json["entities"] = std::move(entities);
  2128. return saveJson(json, out_size);
  2129. }
  2130. // new entry point for ReadLevel.
  2131. // takes in pointer to JSON data. does
  2132. // not store or modify it.
  2133. void ReadLevelJson(const char *jsonString)
  2134. {
  2135. // free any dynamic memory allocated by loading the level
  2136. // base state
  2137. gi.FreeTags(TAG_LEVEL);
  2138. Json::Value json = parseJson(jsonString);
  2139. // wipe all the entities
  2140. memset(g_edicts, 0, game.maxentities * sizeof(g_edicts[0]));
  2141. globals.num_edicts = game.maxclients + 1;
  2142. // read level
  2143. json_push_stack("level");
  2144. read_save_struct_json(json["level"], &level, &level_locals_t_savestruct);
  2145. json_pop_stack();
  2146. // read entities
  2147. const Json::Value &entities = json["entities"];
  2148. if (!entities.isObject())
  2149. gi.Com_Error("expected \"entities\" to be object");
  2150. //for (auto key : json.getMemberNames())
  2151. for (auto it = entities.begin(); it != entities.end(); it++)
  2152. {
  2153. //const char *classname = key.c_str();
  2154. const char *dummy;
  2155. const char *id = it.memberName(&dummy);
  2156. const Json::Value &value = *it;//json[key];
  2157. uint32_t number = strtoul(id, nullptr, 10);
  2158. if (number >= globals.num_edicts)
  2159. globals.num_edicts = number + 1;
  2160. edict_t *ent = &g_edicts[number];
  2161. G_InitEdict(ent);
  2162. json_push_stack(fmt::format("entities[{}]", number));
  2163. read_save_struct_json(value, ent, &edict_t_savestruct);
  2164. json_pop_stack();
  2165. gi.linkentity(ent);
  2166. }
  2167. // mark all clients as unconnected
  2168. for (size_t i = 0; i < game.maxclients; i++)
  2169. {
  2170. edict_t *ent = &g_edicts[i + 1];
  2171. ent->client = game.clients + i;
  2172. ent->client->pers.connected = false;
  2173. ent->client->pers.spawned = false;
  2174. }
  2175. // do any load time things at this point
  2176. for (size_t i = 0; i < globals.num_edicts; i++)
  2177. {
  2178. edict_t *ent = &g_edicts[i];
  2179. if (!ent->inuse)
  2180. continue;
  2181. // fire any cross-level/unit triggers
  2182. if (ent->classname)
  2183. if (strcmp(ent->classname, "target_crosslevel_target") == 0 ||
  2184. strcmp(ent->classname, "target_crossunit_target") == 0)
  2185. ent->nextthink = level.time + gtime_t::from_sec(ent->delay);
  2186. }
  2187. G_PrecacheInventoryItems();
  2188. // clear cached indices
  2189. cached_soundindex::reset_all();
  2190. cached_modelindex::reset_all();
  2191. cached_imageindex::reset_all();
  2192. G_LoadShadowLights();
  2193. }
  2194. // [Paril-KEX]
  2195. bool G_CanSave()
  2196. {
  2197. if (game.maxclients == 1 && g_edicts[1].health <= 0)
  2198. {
  2199. gi.LocClient_Print(&g_edicts[1], PRINT_CENTER, "$g_no_save_dead");
  2200. return false;
  2201. }
  2202. // don't allow saving during cameras/intermissions as this
  2203. // causes the game to act weird when these are loaded
  2204. else if (level.intermissiontime)
  2205. {
  2206. return false;
  2207. }
  2208. return true;
  2209. }
  2210. /*static*/ template<> cached_soundindex *cached_soundindex::head = nullptr;
  2211. /*static*/ template<> cached_modelindex *cached_modelindex::head = nullptr;
  2212. /*static*/ template<> cached_imageindex *cached_imageindex::head = nullptr;