]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/lib/cvar.qh
5ee3222bc6367908243d56899535728ddd2d2b97
[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     localcmd(sprintf("\nset %1$s \"$%1$s\" \"%2$s\"\n", name, MakeConsoleSafe(desc)));
22 }
23
24 void cvar_archive(string name) {
25     localcmd(sprintf("\nseta %1$s \"$%1$s\"\n", name));
26 }
27
28 void RegisterCvars_Set(string name, string def, string desc, bool archive, string file)
29 {
30     cvar_describe(name, desc);
31     if (archive) cvar_archive(name);
32 }
33
34 int RegisterCvars_Save_fd;
35 void RegisterCvars_Save(string name, string def, string desc, bool archive, string file)
36 {
37     if (!archive) return;
38     fputs(RegisterCvars_Save_fd, sprintf("seta %s \"%s\"\n", name, def));
39 }
40
41 STATIC_INIT_LATE(Cvars) {
42     RegisterCvars(RegisterCvars_Set);
43     RegisterCvars_Save_fd = fopen(sprintf("default%s.cfg", PROGNAME), FILE_WRITE);
44     if (RegisterCvars_Save_fd >= 0) {
45         RegisterCvars(RegisterCvars_Save);
46         fclose(RegisterCvars_Save_fd);
47     }
48 }
49
50 const noref bool default_bool = false;
51 const noref int default_int = 0;
52 const noref float default_float = 0;
53 const noref string default_string = "";
54 const noref vector default_vector = '0 0 0';
55
56 #define repr_cvar_bool(x)   ((x) ? "1" : "0")
57 #define repr_cvar_int(x)    (ftos(x))
58 #define repr_cvar_float(x)  (ftos(x))
59 #define repr_cvar_string(x) (x)
60 #define repr_cvar_vector(x) (sprintf("%v", x))
61
62 #define __AUTOCVAR(file, archive, var, type, desc, default) \
63     [[accumulate]] void RegisterCvars(void(string, string, string, bool, string) f) { f(#var, repr_cvar_##type(default), desc, archive, file); } \
64     type autocvar_##var = default
65 #define AUTOCVAR_5(file, archive, var, type, desc) \
66     __AUTOCVAR(file, archive, var, type, desc, default_##type)
67 #define AUTOCVAR_6(file, archive, var, type, default, desc) \
68     __AUTOCVAR(file, archive, var, type, desc, default)
69 #define _AUTOCVAR(...) EVAL(OVERLOAD(AUTOCVAR, __FILE__, __VA_ARGS__))
70 #define AUTOCVAR_SAVE(...) _AUTOCVAR(true, __VA_ARGS__)
71 #define AUTOCVAR(...) _AUTOCVAR(false, __VA_ARGS__)
72
73 #endif