]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/lib/cvar.qh
Merge branch 'master' into TimePath/items
[xonotic/xonotic-data.pk3dir.git] / qcsrc / lib / cvar.qh
1 #ifndef CVAR_H
2 #define CVAR_H
3
4 #include "nil.qh"
5 #include "progname.qh"
6 #include "static.qh"
7
8 void RegisterCvars(void(string name, string def, string desc, bool archive, string file)f) {}
9
10 /** escape the string to make it safe for consoles */
11 string MakeConsoleSafe(string input)
12 {
13         input = strreplace("\n", "", input);
14         input = strreplace("\\", "\\\\", input);
15         input = strreplace("$", "$$", input);
16         input = strreplace("\"", "\\\"", input);
17         return input;
18 }
19
20 void cvar_describe(string name, string desc)
21 {
22         localcmd(sprintf("\nset %1$s \"$%1$s\" \"%2$s\"\n", name, MakeConsoleSafe(desc)));
23 }
24
25 void cvar_archive(string name)
26 {
27         localcmd(sprintf("\nseta %1$s \"$%1$s\"\n", name));
28 }
29
30 void RegisterCvars_Set(string name, string def, string desc, bool archive, string file)
31 {
32         cvar_describe(name, desc);
33         if (archive) cvar_archive(name);
34 }
35
36 int RegisterCvars_Save_fd;
37 void RegisterCvars_Save(string name, string def, string desc, bool archive, string file)
38 {
39         if (!archive) return;
40         fputs(RegisterCvars_Save_fd, sprintf("seta %s \"%s\"\n", name, def));
41 }
42
43 STATIC_INIT_LATE(Cvars)
44 {
45         RegisterCvars(RegisterCvars_Set);
46         RegisterCvars_Save_fd = fopen(sprintf("default%s.cfg", PROGNAME), FILE_WRITE);
47         if (RegisterCvars_Save_fd >= 0)
48         {
49                 RegisterCvars(RegisterCvars_Save);
50                 fclose(RegisterCvars_Save_fd);
51         }
52 }
53
54 const noref bool default_bool = false;
55 const noref int default_int = 0;
56 const noref float default_float = 0;
57 const noref string default_string = "";
58 const noref vector default_vector = '0 0 0';
59
60 #define repr_cvar_bool(x) ((x) ? "1" : "0")
61 #define repr_cvar_int(x) (ftos(x))
62 #define repr_cvar_float(x) (ftos(x))
63 #define repr_cvar_string(x) (x)
64 #define repr_cvar_vector(x) (sprintf("%v", x))
65
66 #define __AUTOCVAR(file, archive, var, type, desc, default) \
67         [[accumulate]] void RegisterCvars(void(string, string, string, bool, string)f) \
68         { \
69                 f( #var, repr_cvar_##type(default), desc, archive, file); \
70         } \
71         type autocvar_##var = default
72 #define AUTOCVAR_5(file, archive, var, type, desc) \
73         __AUTOCVAR(file, archive, var, type, desc, default_##type)
74 #define AUTOCVAR_6(file, archive, var, type, default, desc) \
75         __AUTOCVAR(file, archive, var, type, desc, default)
76 #define _AUTOCVAR(...) EVAL(OVERLOAD(AUTOCVAR, __FILE__, __VA_ARGS__))
77 #define AUTOCVAR_SAVE(...) _AUTOCVAR(true, __VA_ARGS__)
78 #define AUTOCVAR(...) _AUTOCVAR(false, __VA_ARGS__)
79
80 #endif