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