]> git.xonotic.org Git - xonotic/darkplaces.git/blob - cvar.c
build: minor adjustments
[xonotic/darkplaces.git] / cvar.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2000-2021 DarkPlaces contributors
4
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License
7 as published by the Free Software Foundation; either version 2
8 of the License, or (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 See the GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19
20 */
21 // cvar.c -- dynamic variable tracking
22
23 #include "quakedef.h"
24
25 const char *cvar_dummy_description = "custom cvar";
26 static const char *cvar_null_string = "";
27
28 cvar_state_t cvars_all;
29 cvar_state_t cvars_null;
30
31 /*
32 ============
33 Cvar_FindVar
34 ============
35 */
36 cvar_t *Cvar_FindVar(cvar_state_t *cvars, const char *var_name, unsigned neededflags)
37 {
38         unsigned hashindex;
39         cvar_hash_t *hash;
40
41         // use hash lookup to minimize search time
42         hashindex = CRC_Block((const unsigned char *)var_name, strlen(var_name)) % CVAR_HASHSIZE;
43         for (hash = cvars->hashtable[hashindex];hash;hash = hash->next)
44                 if (!strcmp (var_name, hash->cvar->name) && (hash->cvar->flags & neededflags))
45                         return hash->cvar;
46                 else
47                         for (char **alias = hash->cvar->aliases; alias && *alias; alias++)
48                                 if (!strcmp (var_name, *alias) && (hash->cvar->flags & neededflags))
49                                         return hash->cvar;
50         return NULL;
51 }
52
53 cvar_t *Cvar_FindVarAfter(cvar_state_t *cvars, const char *prev_var_name, unsigned neededflags)
54 {
55         cvar_t *var;
56
57         if (*prev_var_name)
58         {
59                 var = Cvar_FindVar(cvars, prev_var_name, neededflags);
60                 if (!var)
61                         return NULL;
62                 var = var->next;
63         }
64         else
65                 var = cvars->vars;
66
67         // search for the next cvar matching the needed flags
68         while (var)
69         {
70                 if (var->flags & neededflags)
71                         break;
72                 var = var->next;
73         }
74         return var;
75 }
76
77 /**
78  * Returns a pointer to the pointer stored in hashtable[] (or the one it links to)
79  * because we'll need to update that when deleting a cvar as other cvar(s) may share its hashindex.
80  */
81 static cvar_hash_t **Cvar_FindVarLink(cvar_state_t *cvars, const char *var_name, cvar_t **prev_alpha, unsigned neededflags)
82 {
83         unsigned hashindex;
84         cvar_t *cvar;
85         cvar_hash_t **hashlinkptr;
86
87         // use hash lookup to minimize search time
88         hashindex = CRC_Block((const unsigned char *)var_name, strlen(var_name)) % CVAR_HASHSIZE;
89         if(prev_alpha) *prev_alpha = NULL;
90         hashlinkptr = &cvars->hashtable[hashindex];
91         for (hashlinkptr = &cvars->hashtable[hashindex]; *hashlinkptr; hashlinkptr = &(*hashlinkptr)->next)
92         {
93                 cvar = (*hashlinkptr)->cvar;
94                 if (!strcmp (var_name, cvar->name) && (cvar->flags & neededflags))
95                         goto match;
96                 else
97                         for (char **alias = cvar->aliases; alias && *alias; alias++)
98                                 if (!strcmp (var_name, *alias) && (cvar->flags & neededflags))
99                                         goto match;
100         }
101         return NULL;
102
103 match:
104         if(!prev_alpha || cvar == cvars->vars)
105                 return hashlinkptr;
106         *prev_alpha = cvars->vars;
107         // if prev_alpha happens to become NULL then there has been some inconsistency elsewhere
108         // already - should I still insert '*prev_alpha &&' in the loop?
109         while((*prev_alpha)->next != cvar)
110                 *prev_alpha = (*prev_alpha)->next;
111         return hashlinkptr;
112 }
113
114 /*
115 ============
116 Cvar_VariableValue
117 ============
118 */
119 float Cvar_VariableValueOr(cvar_state_t *cvars, const char *var_name, float def, unsigned neededflags)
120 {
121         cvar_t *var;
122
123         var = Cvar_FindVar(cvars, var_name, neededflags);
124         if (!var)
125                 return def;
126         return atof (var->string);
127 }
128
129 float Cvar_VariableValue(cvar_state_t *cvars, const char *var_name, unsigned neededflags)
130 {
131         return Cvar_VariableValueOr(cvars, var_name, 0, neededflags);
132 }
133
134 /*
135 ============
136 Cvar_VariableString
137 ============
138 */
139 const char *Cvar_VariableStringOr(cvar_state_t *cvars, const char *var_name, const char *def, unsigned neededflags)
140 {
141         cvar_t *var;
142
143         var = Cvar_FindVar(cvars, var_name, neededflags);
144         if (!var)
145                 return def;
146         return var->string;
147 }
148
149 const char *Cvar_VariableString(cvar_state_t *cvars, const char *var_name, unsigned neededflags)
150 {
151         return Cvar_VariableStringOr(cvars, var_name, cvar_null_string, neededflags);
152 }
153
154 /*
155 ============
156 Cvar_VariableDefString
157 ============
158 */
159 const char *Cvar_VariableDefString(cvar_state_t *cvars, const char *var_name, unsigned neededflags)
160 {
161         cvar_t *var;
162
163         var = Cvar_FindVar(cvars, var_name, neededflags);
164         if (!var)
165                 return cvar_null_string;
166         return var->defstring;
167 }
168
169 /*
170 ============
171 Cvar_VariableDescription
172 ============
173 */
174 const char *Cvar_VariableDescription(cvar_state_t *cvars, const char *var_name, unsigned neededflags)
175 {
176         cvar_t *var;
177
178         var = Cvar_FindVar(cvars, var_name, neededflags);
179         if (!var)
180                 return cvar_null_string;
181         return var->description;
182 }
183
184
185 /*
186 ============
187 Cvar_CompleteVariable
188 ============
189 */
190 const char *Cvar_CompleteVariable(cvar_state_t *cvars, const char *partial, unsigned neededflags)
191 {
192         cvar_t          *cvar;
193         size_t          len;
194
195         len = strlen(partial);
196
197         if (!len)
198                 return NULL;
199
200 // check functions
201         for (cvar=cvars->vars ; cvar ; cvar=cvar->next)
202                 if (!strncasecmp (partial,cvar->name, len) && (cvar->flags & neededflags))
203                         return cvar->name;
204
205         return NULL;
206 }
207
208
209 /*
210         CVar_CompleteCountPossible
211
212         New function for tab-completion system
213         Added by EvilTypeGuy
214         Thanks to Fett erich@heintz.com
215
216 */
217 int Cvar_CompleteCountPossible(cvar_state_t *cvars, const char *partial, unsigned neededflags)
218 {
219         cvar_t  *cvar;
220         size_t  len;
221         int             h;
222
223         h = 0;
224         len = strlen(partial);
225
226         if (!len)
227                 return  0;
228
229         // Loop through the cvars and count all possible matches
230         for (cvar = cvars->vars; cvar; cvar = cvar->next)
231                 if (!strncasecmp(partial, cvar->name, len) && (cvar->flags & neededflags))
232                         h++;
233                 else
234                         for (char **alias = cvar->aliases; alias && *alias; alias++)
235                                 if (!strncasecmp(partial, *alias, len) && (cvar->flags & neededflags))
236                                         h++;
237                 
238         return h;
239 }
240
241 /*
242         CVar_CompleteBuildList
243
244         New function for tab-completion system
245         Added by EvilTypeGuy
246         Thanks to Fett erich@heintz.com
247         Thanks to taniwha
248
249 */
250 const char **Cvar_CompleteBuildList(cvar_state_t *cvars, const char *partial, unsigned neededflags)
251 {
252         const cvar_t *cvar;
253         size_t len = 0;
254         size_t bpos = 0;
255         size_t sizeofbuf = (Cvar_CompleteCountPossible(cvars, partial, neededflags) + 1) * sizeof(const char *);
256         const char **buf;
257
258         len = strlen(partial);
259         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof(const char *));
260         // Loop through the alias list and print all matches
261         for (cvar = cvars->vars; cvar; cvar = cvar->next)
262                 if (!strncasecmp(partial, cvar->name, len) && (cvar->flags & neededflags))
263                         buf[bpos++] = cvar->name;
264                 else
265                         for (char **alias = cvar->aliases; alias && *alias; alias++)
266                                 if (!strncasecmp(partial, *alias, len) && (cvar->flags & neededflags))
267                                         buf[bpos++] = *alias;
268                 
269
270         buf[bpos] = NULL;
271         return buf;
272 }
273
274 void Cvar_PrintHelp(cvar_t *cvar, const char *name, qbool full)
275 {
276         // Aliases are purple, cvars are yellow
277         if (strcmp(cvar->name, name))
278                 Con_Printf("^6%s^7 (alias of ^3%s^7)", name, cvar->name);
279         else
280                 Con_Printf("^3%s^7", name);
281         Con_Printf(" is \"%s^7\" [\"%s^7\"]", ((cvar->flags & CF_PRIVATE) ? "********"/*hunter2*/ : cvar->string), cvar->defstring);
282         if (full)
283                 Con_Printf(" %s", cvar->description);
284         Con_Print("\n");
285 }
286
287 // written by LadyHavoc
288 void Cvar_CompleteCvarPrint(cvar_state_t *cvars, const char *partial, unsigned neededflags)
289 {
290         cvar_t *cvar;
291         size_t len = strlen(partial);
292         // Loop through the command list and print all matches
293         for (cvar = cvars->vars; cvar; cvar = cvar->next)
294                 if (!strncasecmp(partial, cvar->name, len) && (cvar->flags & neededflags))
295                         Cvar_PrintHelp(cvar, cvar->name, true);
296                 else
297                         for (char **alias = cvar->aliases; alias && *alias; alias++)
298                                 if (!strncasecmp (partial, *alias, len) && (cvar->flags & neededflags))
299                                         Cvar_PrintHelp(cvar, *alias, true);
300
301                 
302 }
303
304 /// Check if a cvar is held by some progs
305 /// in which case its name is returned, otherwise NULL.
306 static const char *Cvar_IsAutoCvar(cvar_t *var)
307 {
308         int i;
309         prvm_prog_t *prog;
310         for (i = 0;i < PRVM_PROG_MAX;i++)
311         {
312                 prog = &prvm_prog_list[i];
313                 if (prog->loaded && var->globaldefindex[i] >= 0)
314                         return prog->name;
315         }
316         return NULL;
317 }
318
319 /// we assume that prog is already set to the target progs
320 static void Cvar_UpdateAutoCvar(cvar_t *var)
321 {
322         int i;
323         int j;
324         const char *s;
325         vec3_t v;
326         prvm_prog_t *prog;
327         for (i = 0;i < PRVM_PROG_MAX;i++)
328         {
329                 prog = &prvm_prog_list[i];
330                 if (prog->loaded && var->globaldefindex[i] >= 0)
331                 {
332                         // MUST BE SYNCED WITH prvm_edict.c PRVM_Prog_Load
333                         switch(prog->globaldefs[var->globaldefindex[i]].type & ~DEF_SAVEGLOBAL)
334                         {
335                         case ev_float:
336                                 PRVM_GLOBALFIELDFLOAT(prog->globaldefs[var->globaldefindex[i]].ofs) = var->value;
337                                 break;
338                         case ev_vector:
339                                 s = var->string;
340                                 VectorClear(v);
341                                 for (j = 0;j < 3;j++)
342                                 {
343                                         while (*s && ISWHITESPACE(*s))
344                                                 s++;
345                                         if (!*s)
346                                                 break;
347                                         v[j] = atof(s);
348                                         while (!ISWHITESPACE(*s))
349                                                 s++;
350                                         if (!*s)
351                                                 break;
352                                 }
353                                 VectorCopy(v, PRVM_GLOBALFIELDVECTOR(prog->globaldefs[var->globaldefindex[i]].ofs));
354                                 break;
355                         case ev_string:
356                                 PRVM_ChangeEngineString(prog, var->globaldefindex_stringno[i], var->string);
357                                 PRVM_GLOBALFIELDSTRING(prog->globaldefs[var->globaldefindex[i]].ofs) = var->globaldefindex_stringno[i];
358                                 break;
359                         }
360                 }
361         }
362 }
363
364 /// called after loading a savegame
365 void Cvar_UpdateAllAutoCvars(cvar_state_t *cvars)
366 {
367         cvar_t *var;
368         for (var = cvars->vars ; var ; var = var->next)
369                 Cvar_UpdateAutoCvar(var);
370 }
371
372 void Cvar_Callback(cvar_t *var)
373 {
374         if (var == NULL)
375         {
376                 Con_Print(CON_WARN "Cvar_Callback: var == NULL\n");
377                 return;
378         }
379
380         if(var->callback)
381                 var->callback(var);
382 }
383
384 /*
385 ============
386 Cvar_Set
387 ============
388 */
389 extern cvar_t sv_disablenotify;
390 static void Cvar_SetQuick_Internal (cvar_t *var, const char *value)
391 {
392         qbool changed;
393         size_t valuelen;
394
395         changed = strcmp(var->string, value) != 0;
396         // LadyHavoc: don't reallocate when there is no change
397         if (!changed)
398                 goto cvar_callback;
399
400         // LadyHavoc: don't reallocate when the buffer is the same size
401         valuelen = strlen(value);
402         if (!var->string || strlen(var->string) != valuelen)
403         {
404                 Z_Free ((char *)var->string);   // free the old value string
405
406                 var->string = (char *)Z_Malloc (valuelen + 1);
407         }
408         memcpy ((char *)var->string, value, valuelen + 1);
409         var->value = atof (var->string);
410         var->integer = (int) var->value;
411         if ((var->flags & CF_NOTIFY) && sv.active && !sv_disablenotify.integer)
412                 SV_BroadcastPrintf("\003^3Server cvar \"%s\" changed to \"%s\"\n", var->name, var->string);
413 #if 0
414         // TODO: add infostring support to the server?
415         if ((var->flags & CF_SERVERINFO) && changed && sv.active)
416         {
417                 InfoString_SetValue(svs.serverinfo, sizeof(svs.serverinfo), var->name, var->string);
418                 if (sv.active)
419                 {
420                         MSG_WriteByte (&sv.reliable_datagram, svc_serverinfostring);
421                         MSG_WriteString (&sv.reliable_datagram, var->name);
422                         MSG_WriteString (&sv.reliable_datagram, var->string);
423                 }
424         }
425 #endif
426         if (var->flags & CF_USERINFO)
427                 CL_SetInfo(var->name, var->string, true, false, false, false);
428
429         Cvar_UpdateAutoCvar(var);
430
431 cvar_callback:
432         // Call the function stored in the cvar for bounds checking, cleanup, etc
433         Cvar_Callback(var);
434 }
435
436 void Cvar_SetQuick (cvar_t *var, const char *value)
437 {
438         if (var == NULL)
439         {
440                 Con_Print(CON_WARN "Cvar_SetQuick: var == NULL\n");
441                 return;
442         }
443
444         if (!(var->flags & CF_REGISTERED) && !(var->flags & CF_ALLOCATED))
445         {
446                 Con_Printf(CON_WARN "Warning: Cvar_SetQuick() cannot set unregistered cvar \"%s\"\n", var->name);
447                 return; // setting an unregistered engine cvar crashes
448         }
449
450         if (developer_extra.integer)
451                 Con_DPrintf("Cvar_SetQuick({\"%s\", \"%s\", %i, \"%s\"}, \"%s\");\n", var->name, var->string, var->flags, var->defstring, value);
452
453         Cvar_SetQuick_Internal(var, value);
454 }
455
456 void Cvar_Set(cvar_state_t *cvars, const char *var_name, const char *value)
457 {
458         cvar_t *var;
459         var = Cvar_FindVar(cvars, var_name, ~0);
460         if (var == NULL)
461         {
462                 Con_Printf(CON_WARN "Cvar_Set: variable %s not found\n", var_name);
463                 return;
464         }
465         Cvar_SetQuick(var, value);
466 }
467
468 /*
469 ============
470 Cvar_SetValue
471 ============
472 */
473 void Cvar_SetValueQuick(cvar_t *var, float value)
474 {
475         char val[MAX_INPUTLINE];
476
477         if ((float)((int)value) == value)
478                 dpsnprintf(val, sizeof(val), "%i", (int)value);
479         else
480                 dpsnprintf(val, sizeof(val), "%f", value);
481         Cvar_SetQuick(var, val);
482 }
483
484 void Cvar_SetValue(cvar_state_t *cvars, const char *var_name, float value)
485 {
486         char val[MAX_INPUTLINE];
487
488         if ((float)((int)value) == value)
489                 dpsnprintf(val, sizeof(val), "%i", (int)value);
490         else
491                 dpsnprintf(val, sizeof(val), "%f", value);
492         Cvar_Set(cvars, var_name, val);
493 }
494
495 void Cvar_RegisterCallback(cvar_t *variable, void (*callback)(cvar_t *))
496 {
497         if (variable == NULL)
498         {
499                 Con_Print(CON_WARN "Cvar_RegisterCallback: var == NULL\n");
500                 return;
501         }
502
503         if (!(variable->flags & cmd_local->cvars_flagsmask))
504         {
505                 if (developer_extra.integer)
506                         Con_DPrintf("^6Cvar_RegisterCallback: rejecting cvar \"%s\"\n", variable->name);
507                 return;
508         }
509
510         variable->callback = callback;
511 }
512
513 void Cvar_RegisterVirtual(cvar_t *variable, const char *name )
514 {
515         cvar_state_t *cvars = &cvars_all;
516         cvar_hash_t *hash;
517         unsigned hashindex;
518
519         if (!(variable->flags & cmd_local->cvars_flagsmask))
520         {
521                 if (developer_extra.integer)
522                         Con_DPrintf("^6Cvar_RegisterVirtual: rejecting cvar \"%s\" alias \"%s\"\n", variable->name, name);
523                 return;
524         }
525
526         if(!*name)
527         {
528                 Con_Printf(CON_WARN "Cvar_RegisterVirtual: invalid virtual cvar name\n");
529                 return;
530         }
531
532         // check for overlap with a command
533         if (Cmd_Exists(cmd_local, name))
534         {
535                 Con_Printf(CON_WARN "Cvar_RegisterVirtual: %s is a command\n", name);
536                 return;
537         }
538
539         if(Cvar_FindVar(&cvars_all, name, 0))
540         {
541                 Con_Printf(CON_WARN "Cvar_RegisterVirtual: %s is a cvar\n", name);
542                 return;
543         }
544
545         // Resize the variable->aliases list to have room for another entry and a null terminator.
546         // This zero-pads when resizing, so we don't need to write the NULL terminator manually here.
547         // Also if aliases is NULL this allocates fresh for the correct size, so it's fine to just do this.
548         variable->aliases = (char **)Z_Realloc(variable->aliases, sizeof(char *) * (variable->aliases_size + 2));
549         // Add the new alias, and increment the number of aliases in the list
550         variable->aliases[variable->aliases_size++] = Z_strdup(name);
551
552         // link to head of list in this hash table index
553         hash = (cvar_hash_t *)Z_Malloc(sizeof(cvar_hash_t));
554         hashindex = CRC_Block((const unsigned char *)name, strlen(name)) % CVAR_HASHSIZE;
555         hash->next = cvars->hashtable[hashindex];
556         cvars->hashtable[hashindex] = hash;
557         hash->cvar = variable;
558 }
559
560 /*
561 ============
562 Cvar_Link
563
564 Links a variable to the variable list and hashtable
565 ============
566 */
567 static void Cvar_Link(cvar_t *variable, cvar_state_t *cvars)
568 {
569         cvar_t *current, *next;
570         cvar_hash_t *hash;
571         unsigned hashindex;
572         /*
573          * Link the variable in
574          * alphanumerical order
575          */
576         for( current = NULL, next = cvars->vars ; next && strcmp( next->name, variable->name ) < 0 ; current = next, next = next->next )
577                 ;
578         if(current)
579                 current->next = variable;
580         else
581                 cvars->vars = variable;
582         variable->next = next;
583
584         // link to head of list in this hash table index
585         hash = (cvar_hash_t *)Z_Malloc(sizeof(cvar_hash_t));
586         hashindex = CRC_Block((const unsigned char *)variable->name, strlen(variable->name)) % CVAR_HASHSIZE;
587         hash->next = cvars->hashtable[hashindex];
588         hash->cvar = variable;
589         cvars->hashtable[hashindex] = hash;
590 }
591
592 /*
593 ============
594 Cvar_RegisterVariable
595
596 Adds a freestanding variable to the variable list.
597 ============
598 */
599 void Cvar_RegisterVariable (cvar_t *variable)
600 {
601         cvar_state_t *cvars = &cvars_all;
602         cvar_t *current, *cvar;
603         int i;
604
605         if (!(variable->flags & cmd_local->cvars_flagsmask))
606         {
607                 if (developer_extra.integer)
608                         Con_DPrintf("^2Cvar_RegisterVariable: rejecting cvar \"%s\"\n", variable->name);
609                 return;
610         }
611
612         if (developer_extra.integer)
613                 Con_DPrintf("Cvar_RegisterVariable({\"%s\", \"%s\", %i});\n", variable->name, variable->string, variable->flags);
614
615         // first check to see if it has already been defined
616         cvar = Cvar_FindVar(cvars, variable->name, ~0);
617         if (cvar)
618         {
619                 if (cvar->flags & CF_ALLOCATED)
620                 {
621                         if (developer_extra.integer)
622                                 Con_DPrintf("...  replacing existing allocated cvar {\"%s\", \"%s\", %i}\n", cvar->name, cvar->string, cvar->flags);
623                         // fixed variables replace allocated ones
624                         // (because the engine directly accesses fixed variables)
625                         // NOTE: this isn't actually used currently
626                         // (all cvars are registered before config parsing)
627                         variable->flags &= ~CF_ALLOCATED;
628                         // cvar->string is now owned by variable instead
629                         variable->string = cvar->string;
630                         variable->defstring = cvar->defstring;
631                         variable->value = atof (variable->string);
632                         variable->integer = (int) variable->value;
633                         // Preserve autocvar status.
634                         memcpy(variable->globaldefindex, cvar->globaldefindex, sizeof(variable->globaldefindex));
635                         memcpy(variable->globaldefindex_stringno, cvar->globaldefindex_stringno, sizeof(variable->globaldefindex_stringno));
636                         // replace cvar with this one...
637                         variable->next = cvar->next;
638                         if (cvars->vars == cvar)
639                         {
640                                 // head of the list is easy to change
641                                 cvars->vars = variable;
642                         }
643                         else
644                         {
645                                 // otherwise find it somewhere in the list
646                                 for (current = cvars->vars;current->next != cvar;current = current->next)
647                                         ;
648                                 current->next = variable;
649                         }
650
651                         // get rid of old allocated cvar
652                         // (but not cvar->string and cvar->defstring, because we kept those)
653                         Z_Free((char *)cvar->name);
654                         Z_Free(cvar);
655                 }
656                 else
657                         Con_DPrintf("Can't register variable %s, already defined\n", variable->name);
658                 return;
659         }
660
661         // check for overlap with a command
662         if (Cmd_Exists(cmd_local, variable->name))
663         {
664                 Con_Printf(CON_WARN "Cvar_RegisterVariable: %s is a command\n", variable->name);
665                 return;
666         }
667
668         // copy the value off, because future sets will Z_Free it
669         variable->name = Z_strdup(variable->name);
670         variable->string = Z_strdup(variable->string);
671         variable->defstring = Z_strdup(variable->string);
672         variable->value = atof (variable->string);
673         variable->integer = (int) variable->value;
674         variable->aliases = NULL;
675         variable->aliases_size = 0;
676         variable->initstring = NULL;
677
678         // Mark it as not an autocvar.
679         for (i = 0;i < PRVM_PROG_MAX;i++)
680                 variable->globaldefindex[i] = -1;
681
682         // Safe for Cvar_SetQuick()
683         variable->flags |= CF_REGISTERED;
684
685         Cvar_Link(variable, cvars);
686 }
687
688 /*
689 ============
690 Cvar_Get
691
692 Adds a newly allocated variable to the variable list or sets its value.
693 ============
694 */
695 cvar_t *Cvar_Get(cvar_state_t *cvars, const char *name, const char *value, unsigned flags, const char *newdescription)
696 {
697         cvar_t *cvar;
698         int i;
699
700         if (developer_extra.integer)
701                 Con_DPrintf("Cvar_Get(\"%s\", \"%s\", %i);\n", name, value, flags);
702
703         // first check to see if it has already been defined
704         cvar = Cvar_FindVar(cvars, name, ~0);
705         if (cvar)
706         {
707                 cvar->flags |= flags;
708                 Cvar_SetQuick_Internal (cvar, value);
709                 if(newdescription && (cvar->flags & CF_ALLOCATED))
710                 {
711                         if(cvar->description != cvar_dummy_description)
712                                 Z_Free((char *)cvar->description);
713
714                         if(*newdescription)
715                                 cvar->description = Z_strdup(newdescription);
716                         else
717                                 cvar->description = cvar_dummy_description;
718                 }
719                 return cvar;
720         }
721
722         // check for pure evil
723         if (!*name)
724         {
725                 Con_Printf(CON_WARN "Cvar_Get: invalid variable name\n");
726                 return NULL;
727         }
728
729         // check for overlap with a command
730         if (Cmd_Exists(cmd_local, name))
731         {
732                 Con_Printf(CON_WARN "Cvar_Get: %s is a command\n", name);
733                 return NULL;
734         }
735
736         // allocate a new cvar, cvar name, and cvar string
737         // TODO: factorize the following code with the one at the end of Cvar_RegisterVariable()
738         // FIXME: these never get Z_Free'd
739         cvar = (cvar_t *)Z_Malloc(sizeof(cvar_t));
740         cvar->flags = flags | CF_ALLOCATED;
741         cvar->name = Z_strdup(name);
742         cvar->string = Z_strdup(value);
743         cvar->defstring = Z_strdup(value);
744         cvar->value = atof (cvar->string);
745         cvar->integer = (int) cvar->value;
746         cvar->aliases = NULL;
747         cvar->aliases_size = 0;
748         cvar->initstring = NULL;
749
750         if(newdescription && *newdescription)
751                 cvar->description = Z_strdup(newdescription);
752         else
753                 cvar->description = cvar_dummy_description; // actually checked by VM_cvar_type
754
755         // Mark it as not an autocvar.
756         for (i = 0;i < PRVM_PROG_MAX;i++)
757                 cvar->globaldefindex[i] = -1;
758
759         Cvar_Link(cvar, cvars);
760
761         return cvar;
762 }
763
764 /// For "quiet" mode pass NULL as the callername.
765 /// Returns true if the cvar was deleted.
766 static qbool Cvar_Delete(cvar_state_t *cvars, const char *name, const char *callername)
767 {
768         cvar_t *cvar, *prev;
769         cvar_hash_t **hashlinkptr, *oldhashlink;
770         const char *progname;
771
772         hashlinkptr = Cvar_FindVarLink(cvars, name, &prev, ~0);
773         if(!hashlinkptr)
774         {
775                 if (callername)
776                         Con_Printf("%s: cvar \"%s\" is not defined.\n", callername, name);
777                 return false;
778         }
779         cvar = (*hashlinkptr)->cvar;
780
781         if(!(cvar->flags & CF_ALLOCATED))
782         {
783                 if (callername)
784                         Con_Printf(CON_WARN "%s: engine cvar \"%s\" cannot be deleted!\n", callername, cvar->name);
785                 return false;
786         }
787         if ((progname = Cvar_IsAutoCvar(cvar)))
788         {
789                 if (callername)
790                         Con_Printf(CON_WARN "%s: unable to delete cvar \"%s\", it is an autocvar used by running %s progs!\n", callername, cvar->name, progname);
791                 return false;
792         }
793
794         if(cvar == cvars->vars)
795                 cvars->vars = cvar->next;
796         else
797                 prev->next = cvar->next;
798
799         if(cvar->description != cvar_dummy_description)
800                 Z_Free((char *)cvar->description);
801         Z_Free((char *)cvar->name);
802         Z_Free((char *)cvar->string);
803         Z_Free((char *)cvar->defstring);
804         Z_Free(cvar);
805
806         oldhashlink = *hashlinkptr;
807         *hashlinkptr = (*hashlinkptr)->next;
808         Z_Free(oldhashlink);
809
810         return true;
811 }
812
813 qbool Cvar_Readonly (cvar_t *var, const char *cmd_name)
814 {
815         if (var->flags & CF_READONLY)
816         {
817                 Con_Print(CON_WARN);
818                 if(cmd_name)
819                         Con_Printf("%s: ",cmd_name);
820                 Con_Printf("%s is read-only\n", var->name);
821                 return true;
822         }
823         return false;
824 }
825
826 /*
827 ============
828 Cvar_Command
829
830 Handles variable inspection and changing from the console
831 ============
832 */
833 qbool   Cvar_Command (cmd_state_t *cmd)
834 {
835         cvar_state_t    *cvars = cmd->cvars;
836         cvar_t                  *v;
837
838         // check variables
839         v = Cvar_FindVar(cvars, Cmd_Argv(cmd, 0), (cmd->cvars_flagsmask));
840         if (!v)
841                 return false;
842
843         // perform a variable print or set
844         if (Cmd_Argc(cmd) == 1)
845         {
846                 Cvar_PrintHelp(v, Cmd_Argv(cmd, 0), true);
847                 return true;
848         }
849
850         if (developer_extra.integer)
851                 Con_DPrint("Cvar_Command: ");
852
853         if(Cvar_Readonly(v, NULL))
854                 return true;
855
856         Cvar_SetQuick(v, Cmd_Argv(cmd, 1));
857         if (developer_extra.integer)
858                 Con_DPrint("\n");
859         return true;
860 }
861
862 void Cvar_UnlockDefaults(cmd_state_t *cmd)
863 {
864         cvar_state_t *cvars = cmd->cvars;
865         cvar_t *var;
866         // unlock the default values of all cvars
867         for (var = cvars->vars ; var ; var = var->next)
868                 var->flags &= ~CF_DEFAULTSET;
869 }
870
871 void Cvar_LockDefaults_f(cmd_state_t *cmd)
872 {
873         cvar_state_t *cvars = cmd->cvars;
874         cvar_t *var;
875         // lock in the default values of all cvars
876         for (var = cvars->vars ; var ; var = var->next)
877         {
878                 if (!(var->flags & CF_DEFAULTSET))
879                 {
880                         size_t alloclen;
881
882                         //Con_Printf("locking cvar %s (%s -> %s)\n", var->name, var->string, var->defstring);
883                         var->flags |= CF_DEFAULTSET;
884                         Z_Free((char *)var->defstring);
885                         alloclen = strlen(var->string) + 1;
886                         var->defstring = (char *)Z_Malloc(alloclen);
887                         memcpy((char *)var->defstring, var->string, alloclen);
888                 }
889         }
890 }
891
892 void Cvar_SaveInitState(cvar_state_t *cvars)
893 {
894         cvar_t *c;
895
896         for (c = cvars->vars;c;c = c->next)
897                 if ((c->flags & (CF_PERSISTENT | CF_READONLY)) == 0)
898                         c->initstring = Z_strdup(c->string);
899 }
900
901 void Cvar_RestoreInitState(cvar_state_t *cvars)
902 {
903         cvar_t *c, *cp;
904
905         for (cp = cvars->vars; (c = cp);)
906         {
907                 cp = c->next; // get next cvar now in case we delete this cvar
908
909                 if (c->initstring)
910                 {
911                         // restore this cvar, it existed at init
912                         Con_DPrintf("Cvar_RestoreInitState: Restoring cvar \"%s\"\n", c->name);
913
914                         /* bones_was_here: intentionally NOT restoring defstring in this function.
915                          * The only callsite, Host_LoadConfig_f, will re-exec quake.rc, default.cfg, etc.
916                          * Defaults are unlocked here, so Cvar_LockDefaults_f will reset the defstring.
917                          * This is more correct than restoring the defstring here
918                          * because a gamedir change could load configs that should change defaults.
919                          */
920
921                         Cvar_SetQuick(c, c->initstring);
922                         c->flags &= ~CF_DEFAULTSET;
923                 }
924                 else if (!(c->flags & (CF_PERSISTENT | CF_READONLY))) // cvars with those flags have no initstring AND may not be deleted or reset
925                 {
926                         // remove this cvar, it did not exist at init
927                         Con_DPrintf("Cvar_RestoreInitState: cvar \"%s\"", c->name);
928                         if (Cvar_Delete(cvars, c->name, NULL))
929                                 Con_DPrint("deleted.\n");
930                         else
931                         {
932                                 // In this case, at least reset it to the default.
933                                 Con_DPrint("reset.\n");
934                                 Cvar_SetQuick(c, c->defstring);
935                         }
936                 }
937         }
938 }
939
940 void Cvar_ResetToDefaults_All_f(cmd_state_t *cmd)
941 {
942         cvar_state_t *cvars = cmd->cvars;
943         cvar_t *var;
944         // restore the default values of all cvars
945         for (var = cvars->vars ; var ; var = var->next)
946         {
947                 if((var->flags & (CF_PERSISTENT | CF_READONLY)) == 0)
948                         Cvar_SetQuick(var, var->defstring);
949         }
950 }
951
952 void Cvar_ResetToDefaults_NoSaveOnly_f(cmd_state_t *cmd)
953 {
954         cvar_state_t *cvars = cmd->cvars;
955         cvar_t *var;
956         // restore the default values of all cvars
957         for (var = cvars->vars ; var ; var = var->next)
958         {
959                 if ((var->flags & (CF_PERSISTENT | CF_READONLY | CF_ARCHIVE)) == 0)
960                         Cvar_SetQuick(var, var->defstring);
961         }
962 }
963
964
965 void Cvar_ResetToDefaults_SaveOnly_f(cmd_state_t *cmd)
966 {
967         cvar_state_t *cvars = cmd->cvars;
968         cvar_t *var;
969         // restore the default values of all cvars
970         for (var = cvars->vars ; var ; var = var->next)
971         {
972                 if ((var->flags & (CF_PERSISTENT | CF_READONLY | CF_ARCHIVE)) == CF_ARCHIVE)
973                         Cvar_SetQuick(var, var->defstring);
974         }
975 }
976
977 /*
978 ============
979 Cvar_WriteVariables
980
981 Writes lines containing "set variable value" for all variables
982 with the archive flag set to true.
983 ============
984 */
985 void Cvar_WriteVariables (cvar_state_t *cvars, qfile_t *f)
986 {
987         cvar_t  *var;
988         char buf1[MAX_INPUTLINE], buf2[MAX_INPUTLINE];
989
990         // don't save cvars that match their default value
991         for (var = cvars->vars ; var ; var = var->next) {
992                 if ((var->flags & CF_ARCHIVE) && (strcmp(var->string, var->defstring) || ((var->flags & CF_ALLOCATED) && !(var->flags & CF_DEFAULTSET))))
993                 {
994                         Cmd_QuoteString(buf1, sizeof(buf1), var->name, "\"\\$", false);
995                         Cmd_QuoteString(buf2, sizeof(buf2), var->string, "\"\\$", false);
996                         FS_Printf(f, "%s\"%s\" \"%s\"\n", var->flags & CF_ALLOCATED ? "seta " : "", buf1, buf2);
997                 }
998         }
999 }
1000
1001 // Added by EvilTypeGuy eviltypeguy@qeradiant.com
1002 // 2000-01-09 CvarList command By Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1003 /*
1004 =========
1005 Cvar_List
1006 =========
1007 */
1008 void Cvar_List_f(cmd_state_t *cmd)
1009 {
1010         cvar_state_t *cvars = cmd->cvars;
1011         cvar_t *cvar;
1012         const char *partial;
1013         int count;
1014         qbool ispattern;
1015         char vabuf[1024];
1016
1017         if (Cmd_Argc(cmd) > 1)
1018         {
1019                 partial = Cmd_Argv(cmd, 1);
1020                 ispattern = (strchr(partial, '*') || strchr(partial, '?'));
1021                 if(!ispattern)
1022                         partial = va(vabuf, sizeof(vabuf), "%s*", partial);
1023         }
1024         else
1025         {
1026                 partial = va(vabuf, sizeof(vabuf), "*");
1027                 ispattern = false;
1028         }
1029
1030         count = 0;
1031         for (cvar = cvars->vars; cvar; cvar = cvar->next)
1032         {
1033                 if (matchpattern_with_separator(cvar->name, partial, false, "", false))
1034                 {
1035                         Cvar_PrintHelp(cvar, cvar->name, true);
1036                         count++;
1037                 }
1038                 for (char **alias = cvar->aliases; alias && *alias; alias++)
1039                 {
1040                         if (matchpattern_with_separator(*alias, partial, false, "", false))
1041                         {
1042                                 Cvar_PrintHelp(cvar, *alias, true);
1043                                 count++;
1044                         }
1045                 }
1046         }
1047
1048         if (Cmd_Argc(cmd) > 1)
1049         {
1050                 if(ispattern)
1051                         Con_Printf("%i cvar%s matching \"%s\"\n", count, (count > 1) ? "s" : "", partial);
1052                 else
1053                         Con_Printf("%i cvar%s beginning with \"%s\"\n", count, (count > 1) ? "s" : "", Cmd_Argv(cmd,1));
1054         }
1055         else
1056                 Con_Printf("%i cvar(s)\n", count);
1057 }
1058 // 2000-01-09 CvarList command by Maddes
1059
1060 void Cvar_Set_f(cmd_state_t *cmd)
1061 {
1062         cvar_state_t *cvars = cmd->cvars;
1063         cvar_t *cvar;
1064
1065         // make sure it's the right number of parameters
1066         if (Cmd_Argc(cmd) < 3)
1067         {
1068                 Con_Printf("Set: wrong number of parameters, usage: set <variablename> <value> [<description>]\n");
1069                 return;
1070         }
1071
1072         // check if it's read-only
1073         cvar = Cvar_FindVar(cvars, Cmd_Argv(cmd, 1), ~0);
1074         if (cvar)
1075                 if(Cvar_Readonly(cvar,"Set"))
1076                         return;
1077
1078         if (developer_extra.integer)
1079                 Con_DPrint("Set: ");
1080
1081         // all looks ok, create/modify the cvar
1082         Cvar_Get(cvars, Cmd_Argv(cmd, 1), Cmd_Argv(cmd, 2), cmd->cvars_flagsmask, Cmd_Argc(cmd) > 3 ? Cmd_Argv(cmd, 3) : NULL);
1083 }
1084
1085 void Cvar_SetA_f(cmd_state_t *cmd)
1086 {
1087         cvar_state_t *cvars = cmd->cvars;
1088         cvar_t *cvar;
1089
1090         // make sure it's the right number of parameters
1091         if (Cmd_Argc(cmd) < 3)
1092         {
1093                 Con_Printf("SetA: wrong number of parameters, usage: seta <variablename> <value> [<description>]\n");
1094                 return;
1095         }
1096
1097         // check if it's read-only
1098         cvar = Cvar_FindVar(cvars, Cmd_Argv(cmd, 1), ~0);
1099         if (cvar)
1100                 if(Cvar_Readonly(cvar,"SetA"))
1101                         return;
1102
1103         if (developer_extra.integer)
1104                 Con_DPrint("SetA: ");
1105
1106         // all looks ok, create/modify the cvar
1107         Cvar_Get(cvars, Cmd_Argv(cmd, 1), Cmd_Argv(cmd, 2), cmd->cvars_flagsmask | CF_ARCHIVE, Cmd_Argc(cmd) > 3 ? Cmd_Argv(cmd, 3) : NULL);
1108 }
1109
1110 void Cvar_Del_f(cmd_state_t *cmd)
1111 {
1112         cvar_state_t *cvars = cmd->cvars;
1113         int i;
1114
1115         if(Cmd_Argc(cmd) < 2)
1116         {
1117                 Con_Printf("%s: wrong number of parameters, usage: unset <variablename1> [<variablename2> ...]\n", Cmd_Argv(cmd, 0));
1118                 return;
1119         }
1120         for(i = 1; i < Cmd_Argc(cmd); ++i)
1121                 Cvar_Delete(cvars, Cmd_Argv(cmd, i), Cmd_Argv(cmd, 0));
1122 }
1123
1124 #ifdef FILLALLCVARSWITHRUBBISH
1125 void Cvar_FillAll_f(cmd_state_t *cmd)
1126 {
1127         char *buf, *p, *q;
1128         int n, i;
1129         cvar_t *var;
1130         qbool verify;
1131         if(Cmd_Argc(cmd) != 2)
1132         {
1133                 Con_Printf("Usage: %s length to plant rubbish\n", Cmd_Argv(cmd, 0));
1134                 Con_Printf("Usage: %s -length to verify that the rubbish is still there\n", Cmd_Argv(cmd, 0));
1135                 return;
1136         }
1137         n = atoi(Cmd_Argv(cmd, 1));
1138         verify = (n < 0);
1139         if(verify)
1140                 n = -n;
1141         buf = Z_Malloc(n + 1);
1142         buf[n] = 0;
1143         for(var = cvars->vars; var; var = var->next)
1144         {
1145                 for(i = 0, p = buf, q = var->name; i < n; ++i)
1146                 {
1147                         *p++ = *q++;
1148                         if(!*q)
1149                                 q = var->name;
1150                 }
1151                 if(verify && strcmp(var->string, buf))
1152                 {
1153                         Con_Printf("\n%s does not contain the right rubbish, either this is the first run or a possible overrun was detected, or something changed it intentionally; it DOES contain: %s\n", var->name, var->string);
1154                 }
1155                 Cvar_SetQuick(var, buf);
1156         }
1157         Z_Free(buf);
1158 }
1159 #endif /* FILLALLCVARSWITHRUBBISH */