]> git.xonotic.org Git - xonotic/darkplaces.git/blob - cmd.c
Merge intoverflow.h into qdefs.h
[xonotic/darkplaces.git] / cmd.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 // cmd.c -- Quake script command processing module
21
22 #include "quakedef.h"
23 #include "thread.h"
24
25 cmd_state_t *cmd_local;
26 cmd_state_t *cmd_serverfromclient;
27
28 cmd_userdefined_t cmd_userdefined_all;
29 cmd_userdefined_t cmd_userdefined_null;
30
31 typedef struct cmd_iter_s {
32         cmd_state_t *cmd;
33 }
34 cmd_iter_t;
35
36 static cmd_iter_t *cmd_iter_all;
37
38 mempool_t *cbuf_mempool;
39
40 // we only run the +whatever commandline arguments once
41 qbool host_stuffcmdsrun = false;
42
43 //=============================================================================
44
45 void Cbuf_Lock(cmd_buf_t *cbuf)
46 {
47         Thread_LockMutex(cbuf->lock);
48 }
49
50 void Cbuf_Unlock(cmd_buf_t *cbuf)
51 {
52         Thread_UnlockMutex(cbuf->lock);
53 }
54
55
56 /*
57 ============
58 Cmd_Wait_f
59
60 Causes execution of the remainder of the command buffer to be delayed until
61 next frame.  This allows commands like:
62 bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2"
63 ============
64 */
65 static void Cmd_Wait_f (cmd_state_t *cmd)
66 {
67         cmd->cbuf->wait = true;
68 }
69
70 /*
71 ============
72 Cmd_Defer_f
73
74 Cause a command to be executed after a delay.
75 ============
76 */
77 static cmd_input_t *Cbuf_LinkGet(cmd_buf_t *cbuf, cmd_input_t *existing);
78 static void Cmd_Defer_f (cmd_state_t *cmd)
79 {
80         cmd_input_t *current;
81         cmd_buf_t *cbuf = cmd->cbuf;
82
83         if(Cmd_Argc(cmd) == 1)
84         {
85                 if(List_Is_Empty(&cbuf->deferred))
86                         Con_Printf("No commands are pending.\n");
87                 else
88                 {
89                         llist_t *pos;
90                 List_For_Each(pos, &cbuf->deferred)
91                 {
92                                 current = List_Entry(*pos, cmd_input_t, list);
93                                 Con_Printf("-> In %9.2f: %s\n", current->delay, current->text);
94                         }
95                 }
96         }
97         else if(Cmd_Argc(cmd) == 2 && !strcasecmp("clear", Cmd_Argv(cmd, 1)))
98         {
99                 while(!List_Is_Empty(&cbuf->deferred))
100                         List_Move_Tail(cbuf->deferred.next, &cbuf->free);
101         }
102         else if(Cmd_Argc(cmd) == 3)
103         {
104                 const char *text = Cmd_Argv(cmd, 2);
105                 current = Cbuf_LinkGet(cbuf, NULL);
106                 current->length = strlen(text);
107                 current->source = cmd;
108                 current->delay = atof(Cmd_Argv(cmd, 1));
109
110                 if(current->size < current->length)
111                 {
112                         current->text = (char *)Mem_Realloc(cbuf_mempool, current->text, current->length + 1);
113                         current->size = current->length;
114                 }
115
116                 strlcpy(current->text, text, current->length + 1);
117
118                 List_Move_Tail(&current->list, &cbuf->deferred);
119         }
120         else
121         {
122                 Con_Printf("usage: defer <seconds> <command>\n"
123                            "       defer clear\n");
124                 return;
125         }
126 }
127
128 /*
129 ============
130 Cmd_Centerprint_f
131
132 Print something to the center of the screen using SCR_Centerprint
133 ============
134 */
135 static void Cmd_Centerprint_f (cmd_state_t *cmd)
136 {
137         char msg[MAX_INPUTLINE];
138         unsigned int i, c, p;
139         c = Cmd_Argc(cmd);
140         if(c >= 2)
141         {
142                 strlcpy(msg, Cmd_Argv(cmd,1), sizeof(msg));
143                 for(i = 2; i < c; ++i)
144                 {
145                         strlcat(msg, " ", sizeof(msg));
146                         strlcat(msg, Cmd_Argv(cmd, i), sizeof(msg));
147                 }
148                 c = (unsigned int)strlen(msg);
149                 for(p = 0, i = 0; i < c; ++i)
150                 {
151                         if(msg[i] == '\\')
152                         {
153                                 if(msg[i+1] == 'n')
154                                         msg[p++] = '\n';
155                                 else if(msg[i+1] == '\\')
156                                         msg[p++] = '\\';
157                                 else {
158                                         msg[p++] = '\\';
159                                         msg[p++] = msg[i+1];
160                                 }
161                                 ++i;
162                         } else {
163                                 msg[p++] = msg[i];
164                         }
165                 }
166                 msg[p] = '\0';
167                 SCR_CenterPrint(msg);
168         }
169 }
170
171 /*
172 =============================================================================
173
174                                                 COMMAND BUFFER
175
176 =============================================================================
177 */
178
179 static cmd_input_t *Cbuf_LinkGet(cmd_buf_t *cbuf, cmd_input_t *existing)
180 {
181         cmd_input_t *ret = NULL;
182         if(existing && existing->pending)
183                 ret = existing;
184         else if(!List_Is_Empty(&cbuf->free))
185         {
186                 ret = List_Entry(*cbuf->free.next, cmd_input_t, list);
187                 ret->length = 0;
188                 ret->pending = false;
189         }
190         return ret;
191 }
192
193 static cmd_input_t *Cmd_AllocInputNode(void)
194 {
195         cmd_input_t *node = (cmd_input_t *)Mem_Alloc(cbuf_mempool, sizeof(cmd_input_t));
196         node->list.prev = node->list.next = &node->list;
197         node->size = node->length = node->pending = 0;
198         return node;
199 }
200
201
202 // Cloudwalk FIXME: The entire design of this thing is overly complicated.
203 // We could very much safely have one input node per line whether or not
204 // the command was terminated. We don't need to split up input nodes per command
205 // executed.
206 static size_t Cmd_ParseInput (cmd_input_t **output, char **input)
207 {
208         size_t pos, cmdsize = 0, start = 0;
209         qbool command = false, lookahead = false;
210         qbool quotes = false, comment = false;
211         qbool escaped = false;
212
213         /*
214          * The Quake command-line is super basic. It can be entered in the console
215          * or in config files. A semicolon is used to terminate a command and chain
216          * them together. Otherwise, a newline delineates command input.
217          * 
218          * In most engines, the Quake command-line is a simple linear text buffer that
219          * is parsed when it executes. In Darkplaces, we use a linked list of command
220          * input and parse the input on the spot.
221          * 
222          * This was done because Darkplaces allows multiple command interpreters on the
223          * same thread. Previously, each interpreter maintained its own buffer and this
224          * caused problems related to execution order, and maintaining a single simple
225          * buffer for all interpreters makes it non-trivial to keep track of which
226          * command should execute on which interpreter.
227          */
228
229         // Run until command and lookahead are both true, or until we run out of input.
230         for (pos = 0; (*input)[pos]; pos++)
231         {
232                 // Look for newlines and semicolons. Ignore semicolons in quotes.
233                 switch((*input)[pos])
234                 {
235                 case '\r':
236                 case '\n':
237                         command = false;
238                         comment = false;
239                         break;
240                 default: 
241                         if(!comment) // Not a newline so far. Still not a valid command yet.
242                         {
243                                 if(!quotes && (*input)[pos] == ';') // Ignore semicolons in quotes.
244                                         command = false;
245                                 else if (ISCOMMENT((*input), pos)) // Comments
246                                 {
247                                         comment = true;
248                                         command = false;
249                                 }
250                                 else
251                                 {
252                                         command = true;
253                                         if(!lookahead)
254                                         {
255                                                 if(!cmdsize)
256                                                         start = pos;
257                                                 cmdsize++;
258                                         }
259
260                                         switch((*input)[pos])
261                                         {
262                                         case '"':
263                                                 if (!escaped)
264                                                         quotes = !quotes;
265                                                 else
266                                                         escaped = false;
267                                                 break;
268                                         case '\\':
269                                                 if (!escaped && quotes)
270                                                         escaped = true;
271                                                 else if (escaped)
272                                                         escaped = false;
273                                                 break;
274                                         }
275                                 }
276                         }
277                 }
278                 if(cmdsize && !command)
279                         lookahead = true;
280
281                 if(command && lookahead)
282                         break;
283         }
284
285         if(cmdsize)
286         {
287                 size_t offset = 0;
288
289                 if(!*output)
290                         *output = Cmd_AllocInputNode();
291
292                 // Append, since this input line hasn't closed yet.
293                 if((*output)->pending)
294                         offset = (*output)->length;
295
296                 (*output)->length += cmdsize;
297
298                 if((*output)->size < (*output)->length)
299                 {
300                         (*output)->text = (char *)Mem_Realloc(cbuf_mempool, (*output)->text, (*output)->length + 1);
301                         (*output)->size = (*output)->length;
302                 }
303
304                 strlcpy(&(*output)->text[offset], &(*input)[start], cmdsize + 1);
305                 
306                 /*
307                  * If we were still looking ahead by the time we broke from the loop, the command input
308                  * hasn't terminated yet and we're still expecting more, so keep this node open for appending later.
309                  */
310                 (*output)->pending = !lookahead;
311         }
312
313         // Set input to its new position. Can be NULL.
314         *input = &(*input)[pos];
315
316         return cmdsize;
317 }
318
319 // Cloudwalk: Not happy with this, but it works.
320 static void Cbuf_LinkCreate(cmd_state_t *cmd, llist_t *head, cmd_input_t *existing, const char *text)
321 {
322         char *in = (char *)&text[0];
323         cmd_buf_t *cbuf = cmd->cbuf;
324         size_t totalsize = 0, newsize = 0;
325         cmd_input_t *current = NULL;
326
327         // Slide the pointer down until we reach the end
328         while(*in)
329         {
330                 // Check if the current node is still accepting input (input line hasn't terminated)
331                 current = Cbuf_LinkGet(cbuf, existing);
332                 newsize = Cmd_ParseInput(&current, &in);
333
334                 // Valid command
335                 if(newsize)
336                 {
337                         // current will match existing if the input line hasn't terminated yet
338                         if(current != existing)
339                         {
340                                 current->source = cmd;
341                                 List_Move_Tail(&current->list, head);
342                         }
343
344                         totalsize += newsize;
345                 }
346                 else if (current == existing && !totalsize)
347                         current->pending = false;
348                 current = NULL;
349         }
350
351         cbuf->size += totalsize;
352 }
353
354 /*
355 ============
356 Cbuf_AddText
357
358 Adds command text at the end of the buffer
359 ============
360 */
361 void Cbuf_AddText (cmd_state_t *cmd, const char *text)
362 {
363         size_t l = strlen(text);
364         cmd_buf_t *cbuf = cmd->cbuf;
365         llist_t llist = {&llist, &llist};
366
367         Cbuf_Lock(cbuf);
368
369         if (cbuf->maxsize - cbuf->size <= l)
370                 Con_Print("Cbuf_AddText: overflow\n");
371         else
372         {
373                 Cbuf_LinkCreate(cmd, &llist, (List_Is_Empty(&cbuf->start) ? NULL : List_Entry(*cbuf->start.prev, cmd_input_t, list)), text);
374                 if(!List_Is_Empty(&llist))
375                         List_Splice_Tail(&llist, &cbuf->start);
376         }
377         Cbuf_Unlock(cbuf);
378 }
379
380 /*
381 ============
382 Cbuf_InsertText
383
384 Adds command text immediately after the current command
385 FIXME: actually change the command buffer to do less copying
386 ============
387 */
388 void Cbuf_InsertText (cmd_state_t *cmd, const char *text)
389 {
390         cmd_buf_t *cbuf = cmd->cbuf;
391         llist_t llist = {&llist, &llist};
392         size_t l = strlen(text);
393
394         Cbuf_Lock(cbuf);
395
396         // we need to memmove the existing text and stuff this in before it...
397         if (cbuf->size + l >= cbuf->maxsize)
398                 Con_Print("Cbuf_InsertText: overflow\n");
399         else
400         {
401                 Cbuf_LinkCreate(cmd, &llist, List_Entry(*cbuf->start.next, cmd_input_t, list), text);
402                 if(!List_Is_Empty(&llist))
403                         List_Splice(&llist, &cbuf->start);
404         }
405
406         Cbuf_Unlock(cbuf);
407 }
408
409 /*
410 ============
411 Cbuf_Execute_Deferred --blub
412 ============
413 */
414 static void Cbuf_Execute_Deferred (cmd_buf_t *cbuf)
415 {
416         llist_t *pos;
417         cmd_input_t *current;
418         double eat;
419
420         if (host.realtime - cbuf->deferred_oldtime < 0 || host.realtime - cbuf->deferred_oldtime > 1800)
421                 cbuf->deferred_oldtime = host.realtime;
422         eat = host.realtime - cbuf->deferred_oldtime;
423         if (eat < (1.0 / 120.0))
424                 return;
425         cbuf->deferred_oldtime = host.realtime;
426
427     List_For_Each(pos, &cbuf->deferred)
428         {
429                 current = List_Entry(*pos, cmd_input_t, list);
430                 current->delay -= eat;
431                 if(current->delay <= 0)
432                 {
433                         cbuf->size += current->length;
434                         List_Move(pos, &cbuf->start);
435                         // We must return and come back next frame or the engine will freeze. Fragile... like glass :3
436                         return;
437                 }
438         }
439 }
440
441 /*
442 ============
443 Cbuf_Execute
444 ============
445 */
446 static qbool Cmd_PreprocessString(cmd_state_t *cmd, const char *intext, char *outtext, unsigned maxoutlen, cmd_alias_t *alias );
447 void Cbuf_Execute (cmd_buf_t *cbuf)
448 {
449         cmd_input_t *current;
450         char preprocessed[MAX_INPUTLINE];
451         char *firstchar;
452
453         // LadyHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
454         cbuf->tokenizebufferpos = 0;
455
456         while (!List_Is_Empty(&cbuf->start))
457         {
458                 /*
459                  * Delete the text from the command buffer and move remaining
460                  * commands down. This is necessary because commands (exec, alias)
461                  * can insert data at the beginning of the text buffer
462                  */
463                 current = List_Entry(*cbuf->start.next, cmd_input_t, list);
464                 
465                 // Recycle memory so using WASD doesn't cause a malloc and free
466                 List_Move_Tail(&current->list, &cbuf->free);
467                 
468                 /*
469                  * Assume we're rolling with the current command-line and
470                  * always set this false because alias expansion or cbuf insertion
471                  * without a newline may set this true, and cause weirdness.
472                  */
473                 current->pending = false;
474
475                 cbuf->size -= current->length;
476
477                 firstchar = current->text;
478                 while(*firstchar && ISWHITESPACE(*firstchar))
479                         ++firstchar;
480                 if((strncmp(firstchar, "alias", 5)   || !ISWHITESPACE(firstchar[5])) &&
481                    (strncmp(firstchar, "bind", 4)    || !ISWHITESPACE(firstchar[4])) &&
482                    (strncmp(firstchar, "in_bind", 7) || !ISWHITESPACE(firstchar[7])))
483                 {
484                         if(Cmd_PreprocessString(current->source, current->text, preprocessed, sizeof(preprocessed), NULL ))
485                                 Cmd_ExecuteString(current->source, preprocessed, src_local, false);
486                 }
487                 else
488                 {
489                         Cmd_ExecuteString (current->source, current->text, src_local, false);
490                 }
491
492                 current = NULL;
493
494                 if (cbuf->wait)
495                 {
496                         /*
497                          * Skip out while text still remains in
498                          * buffer, leaving it for next frame
499                          */
500                         cbuf->wait = false;
501                         break;
502                 }
503         }
504 }
505
506 /*
507 ===================
508 Cbuf_Frame_Input
509
510 Add them exactly as if they had been typed at the console
511 ===================
512 */
513 static void Cbuf_Frame_Input(void)
514 {
515         char *line;
516
517         while ((line = Sys_ConsoleInput()))
518                         Cbuf_AddText(cmd_local, line);
519 }
520
521 void Cbuf_Frame(cmd_buf_t *cbuf)
522 {
523         // check for commands typed to the host
524         Cbuf_Frame_Input();
525
526 //      R_TimeReport("preconsole");
527
528         // execute commands queued with the defer command
529         Cbuf_Execute_Deferred(cbuf);
530         if (cbuf->size)
531         {
532                 SV_LockThreadMutex();
533                 Cbuf_Execute(cbuf);
534                 SV_UnlockThreadMutex();
535         }
536
537 //      R_TimeReport("console");
538 }
539
540 /*
541 ==============================================================================
542
543                                                 SCRIPT COMMANDS
544
545 ==============================================================================
546 */
547
548 /*
549 ===============
550 Cmd_StuffCmds_f
551
552 Adds command line parameters as script statements
553 Commands lead with a +, and continue until a - or another +
554 quake +prog jctest.qp +cmd amlev1
555 quake -nosound +cmd amlev1
556 ===============
557 */
558 static void Cmd_StuffCmds_f (cmd_state_t *cmd)
559 {
560         int             i, j, l;
561         // this is for all commandline options combined (and is bounds checked)
562         char    build[MAX_INPUTLINE];
563
564         if (Cmd_Argc (cmd) != 1)
565         {
566                 Con_Print("stuffcmds : execute command line parameters\n");
567                 return;
568         }
569
570         // no reason to run the commandline arguments twice
571         if (host_stuffcmdsrun)
572                 return;
573
574         host_stuffcmdsrun = true;
575         build[0] = 0;
576         l = 0;
577         for (i = 0;i < sys.argc;i++)
578         {
579                 if (sys.argv[i] && sys.argv[i][0] == '+' && (sys.argv[i][1] < '0' || sys.argv[i][1] > '9') && l + strlen(sys.argv[i]) - 1 <= sizeof(build) - 1)
580                 {
581                         j = 1;
582                         while (sys.argv[i][j])
583                                 build[l++] = sys.argv[i][j++];
584                         i++;
585                         for (;i < sys.argc;i++)
586                         {
587                                 if (!sys.argv[i])
588                                         continue;
589                                 if ((sys.argv[i][0] == '+' || sys.argv[i][0] == '-') && (sys.argv[i][1] < '0' || sys.argv[i][1] > '9'))
590                                         break;
591                                 if (l + strlen(sys.argv[i]) + 4 > sizeof(build) - 1)
592                                         break;
593                                 build[l++] = ' ';
594                                 if (strchr(sys.argv[i], ' '))
595                                         build[l++] = '\"';
596                                 for (j = 0;sys.argv[i][j];j++)
597                                         build[l++] = sys.argv[i][j];
598                                 if (strchr(sys.argv[i], ' '))
599                                         build[l++] = '\"';
600                         }
601                         build[l++] = '\n';
602                         i--;
603                 }
604         }
605         // now terminate the combined string and prepend it to the command buffer
606         // we already reserved space for the terminator
607         build[l++] = 0;
608         Cbuf_InsertText (cmd, build);
609 }
610
611 static void Cmd_Exec(cmd_state_t *cmd, const char *filename)
612 {
613         char *f;
614         size_t filenameLen = strlen(filename);
615         qbool isdefaultcfg =
616                 !strcmp(filename, "default.cfg") ||
617                 (filenameLen >= 12 && !strcmp(filename + filenameLen - 12, "/default.cfg"));
618
619         if (!strcmp(filename, "config.cfg"))
620         {
621                 filename = CONFIGFILENAME;
622                 if (Sys_CheckParm("-noconfig"))
623                         return; // don't execute config.cfg
624         }
625
626         f = (char *)FS_LoadFile (filename, tempmempool, false, NULL);
627         if (!f)
628         {
629                 Con_Printf("couldn't exec %s\n",filename);
630                 return;
631         }
632         Con_Printf("execing %s\n",filename);
633
634         // if executing default.cfg for the first time, lock the cvar defaults
635         // it may seem backwards to insert this text BEFORE the default.cfg
636         // but Cbuf_InsertText inserts before, so this actually ends up after it.
637         if (isdefaultcfg)
638                 Cbuf_InsertText(cmd, "\ncvar_lockdefaults\n");
639
640         Cbuf_InsertText (cmd, f);
641         Mem_Free(f);
642
643         if (isdefaultcfg)
644         {
645                 // special defaults for specific games go here, these execute before default.cfg
646                 // Nehahra pushable crates malfunction in some levels if this is on
647                 // Nehahra NPC AI is confused by blowupfallenzombies
648                 switch(gamemode)
649                 {
650                 case GAME_NORMAL:
651                         Cbuf_InsertText(cmd, "\n"
652 "sv_gameplayfix_blowupfallenzombies 0\n"
653 "sv_gameplayfix_findradiusdistancetobox 0\n"
654 "sv_gameplayfix_grenadebouncedownslopes 0\n"
655 "sv_gameplayfix_slidemoveprojectiles 0\n"
656 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
657 "sv_gameplayfix_setmodelrealbox 0\n"
658 "sv_gameplayfix_droptofloorstartsolid 0\n"
659 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
660 "sv_gameplayfix_noairborncorpse 0\n"
661 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
662 "sv_gameplayfix_easierwaterjump 0\n"
663 "sv_gameplayfix_delayprojectiles 0\n"
664 "sv_gameplayfix_multiplethinksperframe 0\n"
665 "sv_gameplayfix_fixedcheckwatertransition 0\n"
666 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
667 "sv_gameplayfix_swiminbmodels 0\n"
668 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
669 "sys_ticrate 0.01388889\n"
670 "r_shadow_gloss 1\n"
671 "r_shadow_bumpscale_basetexture 0\n"
672 "csqc_polygons_defaultmaterial_nocullface 0\n"
673                                 );
674                         break;
675                 case GAME_NEHAHRA:
676                         Cbuf_InsertText(cmd, "\n"
677 "sv_gameplayfix_blowupfallenzombies 0\n"
678 "sv_gameplayfix_findradiusdistancetobox 0\n"
679 "sv_gameplayfix_grenadebouncedownslopes 0\n"
680 "sv_gameplayfix_slidemoveprojectiles 0\n"
681 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
682 "sv_gameplayfix_setmodelrealbox 0\n"
683 "sv_gameplayfix_droptofloorstartsolid 0\n"
684 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
685 "sv_gameplayfix_noairborncorpse 0\n"
686 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
687 "sv_gameplayfix_easierwaterjump 0\n"
688 "sv_gameplayfix_delayprojectiles 0\n"
689 "sv_gameplayfix_multiplethinksperframe 0\n"
690 "sv_gameplayfix_fixedcheckwatertransition 0\n"
691 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
692 "sv_gameplayfix_swiminbmodels 0\n"
693 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
694 "sys_ticrate 0.01388889\n"
695 "r_shadow_gloss 1\n"
696 "r_shadow_bumpscale_basetexture 0\n"
697 "csqc_polygons_defaultmaterial_nocullface 0\n"
698                                 );
699                         break;
700                 // hipnotic mission pack has issues in their 'friendly monster' ai, which seem to attempt to attack themselves for some reason when findradius() returns non-solid entities.
701                 // hipnotic mission pack has issues with bobbing water entities 'jittering' between different heights on alternate frames at the default 0.0138889 ticrate, 0.02 avoids this issue
702                 // hipnotic mission pack has issues in their proximity mine sticking code, which causes them to bounce off.
703                 case GAME_HIPNOTIC:
704                 case GAME_QUOTH:
705                         Cbuf_InsertText(cmd, "\n"
706 "sv_gameplayfix_blowupfallenzombies 0\n"
707 "sv_gameplayfix_findradiusdistancetobox 0\n"
708 "sv_gameplayfix_grenadebouncedownslopes 0\n"
709 "sv_gameplayfix_slidemoveprojectiles 0\n"
710 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
711 "sv_gameplayfix_setmodelrealbox 0\n"
712 "sv_gameplayfix_droptofloorstartsolid 0\n"
713 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
714 "sv_gameplayfix_noairborncorpse 0\n"
715 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
716 "sv_gameplayfix_easierwaterjump 0\n"
717 "sv_gameplayfix_delayprojectiles 0\n"
718 "sv_gameplayfix_multiplethinksperframe 0\n"
719 "sv_gameplayfix_fixedcheckwatertransition 0\n"
720 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
721 "sv_gameplayfix_swiminbmodels 0\n"
722 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
723 "sys_ticrate 0.02\n"
724 "r_shadow_gloss 1\n"
725 "r_shadow_bumpscale_basetexture 0\n"
726 "csqc_polygons_defaultmaterial_nocullface 0\n"
727                                 );
728                         break;
729                 // rogue mission pack has a guardian boss that does not wake up if findradius returns one of the entities around its spawn area
730                 case GAME_ROGUE:
731                         Cbuf_InsertText(cmd, "\n"
732 "sv_gameplayfix_blowupfallenzombies 0\n"
733 "sv_gameplayfix_findradiusdistancetobox 0\n"
734 "sv_gameplayfix_grenadebouncedownslopes 0\n"
735 "sv_gameplayfix_slidemoveprojectiles 0\n"
736 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
737 "sv_gameplayfix_setmodelrealbox 0\n"
738 "sv_gameplayfix_droptofloorstartsolid 0\n"
739 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
740 "sv_gameplayfix_noairborncorpse 0\n"
741 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
742 "sv_gameplayfix_easierwaterjump 0\n"
743 "sv_gameplayfix_delayprojectiles 0\n"
744 "sv_gameplayfix_multiplethinksperframe 0\n"
745 "sv_gameplayfix_fixedcheckwatertransition 0\n"
746 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
747 "sv_gameplayfix_swiminbmodels 0\n"
748 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
749 "sys_ticrate 0.01388889\n"
750 "r_shadow_gloss 1\n"
751 "r_shadow_bumpscale_basetexture 0\n"
752 "csqc_polygons_defaultmaterial_nocullface 0\n"
753                                 );
754                         break;
755                 case GAME_TENEBRAE:
756                         Cbuf_InsertText(cmd, "\n"
757 "sv_gameplayfix_blowupfallenzombies 0\n"
758 "sv_gameplayfix_findradiusdistancetobox 0\n"
759 "sv_gameplayfix_grenadebouncedownslopes 0\n"
760 "sv_gameplayfix_slidemoveprojectiles 0\n"
761 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
762 "sv_gameplayfix_setmodelrealbox 0\n"
763 "sv_gameplayfix_droptofloorstartsolid 0\n"
764 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
765 "sv_gameplayfix_noairborncorpse 0\n"
766 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
767 "sv_gameplayfix_easierwaterjump 0\n"
768 "sv_gameplayfix_delayprojectiles 0\n"
769 "sv_gameplayfix_multiplethinksperframe 0\n"
770 "sv_gameplayfix_fixedcheckwatertransition 0\n"
771 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
772 "sv_gameplayfix_swiminbmodels 0\n"
773 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
774 "sys_ticrate 0.01388889\n"
775 "r_shadow_gloss 2\n"
776 "r_shadow_bumpscale_basetexture 4\n"
777 "csqc_polygons_defaultmaterial_nocullface 0\n"
778                                 );
779                         break;
780                 case GAME_NEXUIZ:
781                         Cbuf_InsertText(cmd, "\n"
782 "sv_gameplayfix_blowupfallenzombies 1\n"
783 "sv_gameplayfix_findradiusdistancetobox 1\n"
784 "sv_gameplayfix_grenadebouncedownslopes 1\n"
785 "sv_gameplayfix_slidemoveprojectiles 1\n"
786 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
787 "sv_gameplayfix_setmodelrealbox 1\n"
788 "sv_gameplayfix_droptofloorstartsolid 1\n"
789 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
790 "sv_gameplayfix_noairborncorpse 1\n"
791 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
792 "sv_gameplayfix_easierwaterjump 1\n"
793 "sv_gameplayfix_delayprojectiles 1\n"
794 "sv_gameplayfix_multiplethinksperframe 1\n"
795 "sv_gameplayfix_fixedcheckwatertransition 1\n"
796 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
797 "sv_gameplayfix_swiminbmodels 1\n"
798 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
799 "sys_ticrate 0.01388889\n"
800 "sv_gameplayfix_q2airaccelerate 1\n"
801 "sv_gameplayfix_stepmultipletimes 1\n"
802 "csqc_polygons_defaultmaterial_nocullface 1\n"
803 "con_chatsound_team_mask 13\n"
804                                 );
805                         break;
806                 case GAME_XONOTIC:
807                 case GAME_VORETOURNAMENT:
808                         // compatibility for versions prior to 2020-05-25, this can be overridden in newer versions to get the default behavior and be consistent with FTEQW engine
809                         Cbuf_InsertText(cmd, "\n"
810 "csqc_polygons_defaultmaterial_nocullface 1\n"
811 "con_chatsound_team_mask 13\n"
812 "sv_gameplayfix_customstats 1\n"
813                                 );
814                         break;
815                 // Steel Storm: Burning Retribution csqc misinterprets CSQC_InputEvent if type is a value other than 0 or 1
816                 case GAME_STEELSTORM:
817                         Cbuf_InsertText(cmd, "\n"
818 "sv_gameplayfix_blowupfallenzombies 1\n"
819 "sv_gameplayfix_findradiusdistancetobox 1\n"
820 "sv_gameplayfix_grenadebouncedownslopes 1\n"
821 "sv_gameplayfix_slidemoveprojectiles 1\n"
822 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
823 "sv_gameplayfix_setmodelrealbox 1\n"
824 "sv_gameplayfix_droptofloorstartsolid 1\n"
825 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
826 "sv_gameplayfix_noairborncorpse 1\n"
827 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
828 "sv_gameplayfix_easierwaterjump 1\n"
829 "sv_gameplayfix_delayprojectiles 1\n"
830 "sv_gameplayfix_multiplethinksperframe 1\n"
831 "sv_gameplayfix_fixedcheckwatertransition 1\n"
832 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
833 "sv_gameplayfix_swiminbmodels 1\n"
834 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
835 "sys_ticrate 0.01388889\n"
836 "cl_csqc_generatemousemoveevents 0\n"
837 "csqc_polygons_defaultmaterial_nocullface 1\n"
838                                 );
839                         break;
840                 default:
841                         Cbuf_InsertText(cmd, "\n"
842 "sv_gameplayfix_blowupfallenzombies 1\n"
843 "sv_gameplayfix_findradiusdistancetobox 1\n"
844 "sv_gameplayfix_grenadebouncedownslopes 1\n"
845 "sv_gameplayfix_slidemoveprojectiles 1\n"
846 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
847 "sv_gameplayfix_setmodelrealbox 1\n"
848 "sv_gameplayfix_droptofloorstartsolid 1\n"
849 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
850 "sv_gameplayfix_noairborncorpse 1\n"
851 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
852 "sv_gameplayfix_easierwaterjump 1\n"
853 "sv_gameplayfix_delayprojectiles 1\n"
854 "sv_gameplayfix_multiplethinksperframe 1\n"
855 "sv_gameplayfix_fixedcheckwatertransition 1\n"
856 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
857 "sv_gameplayfix_swiminbmodels 1\n"
858 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
859 "sys_ticrate 0.01388889\n"
860 "csqc_polygons_defaultmaterial_nocullface 0\n"
861                                 );
862                         break;
863                 }
864         }
865 }
866
867 /*
868 ===============
869 Cmd_Exec_f
870 ===============
871 */
872 static void Cmd_Exec_f (cmd_state_t *cmd)
873 {
874         fssearch_t *s;
875         int i;
876
877         if (Cmd_Argc(cmd) != 2)
878         {
879                 Con_Print("exec <filename> : execute a script file\n");
880                 return;
881         }
882
883         s = FS_Search(Cmd_Argv(cmd, 1), true, true, NULL);
884         if(!s || !s->numfilenames)
885         {
886                 Con_Printf("couldn't exec %s\n",Cmd_Argv(cmd, 1));
887                 return;
888         }
889
890         for(i = 0; i < s->numfilenames; ++i)
891                 Cmd_Exec(cmd, s->filenames[i]);
892
893         FS_FreeSearch(s);
894 }
895
896
897 /*
898 ===============
899 Cmd_Echo_f
900
901 Just prints the rest of the line to the console
902 ===============
903 */
904 static void Cmd_Echo_f (cmd_state_t *cmd)
905 {
906         int             i;
907
908         for (i=1 ; i<Cmd_Argc(cmd) ; i++)
909                 Con_Printf("%s ",Cmd_Argv(cmd, i));
910         Con_Print("\n");
911 }
912
913 // DRESK - 5/14/06
914 // Support Doom3-style Toggle Console Command
915 /*
916 ===============
917 Cmd_Toggle_f
918
919 Toggles a specified console variable amongst the values specified (default is 0 and 1)
920 ===============
921 */
922 static void Cmd_Toggle_f(cmd_state_t *cmd)
923 {
924         // Acquire Number of Arguments
925         int nNumArgs = Cmd_Argc(cmd);
926
927         if(nNumArgs == 1)
928                 // No Arguments Specified; Print Usage
929                 Con_Print("Toggle Console Variable - Usage\n  toggle <variable> - toggles between 0 and 1\n  toggle <variable> <value> - toggles between 0 and <value>\n  toggle <variable> [string 1] [string 2]...[string n] - cycles through all strings\n");
930         else
931         { // Correct Arguments Specified
932                 // Acquire Potential CVar
933                 cvar_t* cvCVar = Cvar_FindVar(cmd->cvars, Cmd_Argv(cmd, 1), cmd->cvars_flagsmask);
934
935                 if(cvCVar != NULL)
936                 { // Valid CVar
937                         if(nNumArgs == 2)
938                         { // Default Usage
939                                 if(cvCVar->integer)
940                                         Cvar_SetValueQuick(cvCVar, 0);
941                                 else
942                                         Cvar_SetValueQuick(cvCVar, 1);
943                         }
944                         else
945                         if(nNumArgs == 3)
946                         { // 0 and Specified Usage
947                                 if(cvCVar->integer == atoi(Cmd_Argv(cmd, 2) ) )
948                                         // CVar is Specified Value; // Reset to 0
949                                         Cvar_SetValueQuick(cvCVar, 0);
950                                 else
951                                 if(cvCVar->integer == 0)
952                                         // CVar is 0; Specify Value
953                                         Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
954                                 else
955                                         // CVar does not match; Reset to 0
956                                         Cvar_SetValueQuick(cvCVar, 0);
957                         }
958                         else
959                         { // Variable Values Specified
960                                 int nCnt;
961                                 int bFound = 0;
962
963                                 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
964                                 { // Cycle through Values
965                                         if( strcmp(cvCVar->string, Cmd_Argv(cmd, nCnt) ) == 0)
966                                         { // Current Value Located; Increment to Next
967                                                 if( (nCnt + 1) == nNumArgs)
968                                                         // Max Value Reached; Reset
969                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
970                                                 else
971                                                         // Next Value
972                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, nCnt + 1) );
973
974                                                 // End Loop
975                                                 nCnt = nNumArgs;
976                                                 // Assign Found
977                                                 bFound = 1;
978                                         }
979                                 }
980                                 if(!bFound)
981                                         // Value not Found; Reset to Original
982                                         Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
983                         }
984
985                 }
986                 else
987                 { // Invalid CVar
988                         Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(cmd, 1) );
989                 }
990         }
991 }
992
993 /*
994 ===============
995 Cmd_Alias_f
996
997 Creates a new command that executes a command string (possibly ; seperated)
998 ===============
999 */
1000 static void Cmd_Alias_f (cmd_state_t *cmd)
1001 {
1002         cmd_alias_t     *a;
1003         char            line[MAX_INPUTLINE];
1004         int                     i, c;
1005         const char              *s;
1006         size_t          alloclen;
1007
1008         if (Cmd_Argc(cmd) == 1)
1009         {
1010                 Con_Print("Current alias commands:\n");
1011                 for (a = cmd->userdefined->alias ; a ; a=a->next)
1012                         Con_Printf("%s : %s", a->name, a->value);
1013                 return;
1014         }
1015
1016         s = Cmd_Argv(cmd, 1);
1017         if (strlen(s) >= MAX_ALIAS_NAME)
1018         {
1019                 Con_Print("Alias name is too long\n");
1020                 return;
1021         }
1022
1023         // if the alias already exists, reuse it
1024         for (a = cmd->userdefined->alias ; a ; a=a->next)
1025         {
1026                 if (!strcmp(s, a->name))
1027                 {
1028                         Z_Free (a->value);
1029                         break;
1030                 }
1031         }
1032
1033         if (!a)
1034         {
1035                 cmd_alias_t *prev, *current;
1036
1037                 a = (cmd_alias_t *)Z_Malloc (sizeof(cmd_alias_t));
1038                 strlcpy (a->name, s, sizeof (a->name));
1039                 // insert it at the right alphanumeric position
1040                 for( prev = NULL, current = cmd->userdefined->alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
1041                         ;
1042                 if( prev ) {
1043                         prev->next = a;
1044                 } else {
1045                         cmd->userdefined->alias = a;
1046                 }
1047                 a->next = current;
1048         }
1049
1050
1051 // copy the rest of the command line
1052         line[0] = 0;            // start out with a null string
1053         c = Cmd_Argc(cmd);
1054         for (i=2 ; i < c ; i++)
1055         {
1056                 if (i != 2)
1057                         strlcat (line, " ", sizeof (line));
1058                 strlcat (line, Cmd_Argv(cmd, i), sizeof (line));
1059         }
1060         strlcat (line, "\n", sizeof (line));
1061
1062         alloclen = strlen (line) + 1;
1063         if(alloclen >= 2)
1064                 line[alloclen - 2] = '\n'; // to make sure a newline is appended even if too long
1065         a->value = (char *)Z_Malloc (alloclen);
1066         memcpy (a->value, line, alloclen);
1067 }
1068
1069 /*
1070 ===============
1071 Cmd_UnAlias_f
1072
1073 Remove existing aliases.
1074 ===============
1075 */
1076 static void Cmd_UnAlias_f (cmd_state_t *cmd)
1077 {
1078         cmd_alias_t     *a, *p;
1079         int i;
1080         const char *s;
1081
1082         if(Cmd_Argc(cmd) == 1)
1083         {
1084                 Con_Print("unalias: Usage: unalias alias1 [alias2 ...]\n");
1085                 return;
1086         }
1087
1088         for(i = 1; i < Cmd_Argc(cmd); ++i)
1089         {
1090                 s = Cmd_Argv(cmd, i);
1091                 p = NULL;
1092                 for(a = cmd->userdefined->alias; a; p = a, a = a->next)
1093                 {
1094                         if(!strcmp(s, a->name))
1095                         {
1096                                 if (a->initstate) // we can not remove init aliases
1097                                         continue;
1098                                 if(a == cmd->userdefined->alias)
1099                                         cmd->userdefined->alias = a->next;
1100                                 if(p)
1101                                         p->next = a->next;
1102                                 Z_Free(a->value);
1103                                 Z_Free(a);
1104                                 break;
1105                         }
1106                 }
1107                 if(!a)
1108                         Con_Printf("unalias: %s alias not found\n", s);
1109         }
1110 }
1111
1112 /*
1113 =============================================================================
1114
1115                                         COMMAND EXECUTION
1116
1117 =============================================================================
1118 */
1119
1120 static const char *Cmd_GetDirectCvarValue(cmd_state_t *cmd, const char *varname, cmd_alias_t *alias, qbool *is_multiple)
1121 {
1122         cvar_t *cvar;
1123         long argno;
1124         char *endptr;
1125         static char vabuf[1024]; // cmd_mutex
1126
1127         if(is_multiple)
1128                 *is_multiple = false;
1129
1130         if(!varname || !*varname)
1131                 return NULL;
1132
1133         if(alias)
1134         {
1135                 if(!strcmp(varname, "*"))
1136                 {
1137                         if(is_multiple)
1138                                 *is_multiple = true;
1139                         return Cmd_Args(cmd);
1140                 }
1141                 else if(!strcmp(varname, "#"))
1142                 {
1143                         return va(vabuf, sizeof(vabuf), "%d", Cmd_Argc(cmd));
1144                 }
1145                 else if(varname[strlen(varname) - 1] == '-')
1146                 {
1147                         argno = strtol(varname, &endptr, 10);
1148                         if(endptr == varname + strlen(varname) - 1)
1149                         {
1150                                 // whole string is a number, apart from the -
1151                                 const char *p = Cmd_Args(cmd);
1152                                 for(; argno > 1; --argno)
1153                                         if(!COM_ParseToken_Console(&p))
1154                                                 break;
1155                                 if(p)
1156                                 {
1157                                         if(is_multiple)
1158                                                 *is_multiple = true;
1159
1160                                         // kill pre-argument whitespace
1161                                         for (;*p && ISWHITESPACE(*p);p++)
1162                                                 ;
1163
1164                                         return p;
1165                                 }
1166                         }
1167                 }
1168                 else
1169                 {
1170                         argno = strtol(varname, &endptr, 10);
1171                         if(*endptr == 0)
1172                         {
1173                                 // whole string is a number
1174                                 // NOTE: we already made sure we don't have an empty cvar name!
1175                                 if(argno >= 0 && argno < Cmd_Argc(cmd))
1176                                         return Cmd_Argv(cmd, argno);
1177                         }
1178                 }
1179         }
1180
1181         if((cvar = Cvar_FindVar(cmd->cvars, varname, cmd->cvars_flagsmask)) && !(cvar->flags & CF_PRIVATE))
1182                 return cvar->string;
1183
1184         return NULL;
1185 }
1186
1187 qbool Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset, qbool putquotes)
1188 {
1189         qbool quote_quot = !!strchr(quoteset, '"');
1190         qbool quote_backslash = !!strchr(quoteset, '\\');
1191         qbool quote_dollar = !!strchr(quoteset, '$');
1192
1193         if(putquotes)
1194         {
1195                 if(outlen <= 2)
1196                 {
1197                         *out++ = 0;
1198                         return false;
1199                 }
1200                 *out++ = '"'; --outlen;
1201                 --outlen;
1202         }
1203
1204         while(*in)
1205         {
1206                 if(*in == '"' && quote_quot)
1207                 {
1208                         if(outlen <= 2)
1209                                 goto fail;
1210                         *out++ = '\\'; --outlen;
1211                         *out++ = '"'; --outlen;
1212                 }
1213                 else if(*in == '\\' && quote_backslash)
1214                 {
1215                         if(outlen <= 2)
1216                                 goto fail;
1217                         *out++ = '\\'; --outlen;
1218                         *out++ = '\\'; --outlen;
1219                 }
1220                 else if(*in == '$' && quote_dollar)
1221                 {
1222                         if(outlen <= 2)
1223                                 goto fail;
1224                         *out++ = '$'; --outlen;
1225                         *out++ = '$'; --outlen;
1226                 }
1227                 else
1228                 {
1229                         if(outlen <= 1)
1230                                 goto fail;
1231                         *out++ = *in; --outlen;
1232                 }
1233                 ++in;
1234         }
1235         if(putquotes)
1236                 *out++ = '"';
1237         *out++ = 0;
1238         return true;
1239 fail:
1240         if(putquotes)
1241                 *out++ = '"';
1242         *out++ = 0;
1243         return false;
1244 }
1245
1246 static const char *Cmd_GetCvarValue(cmd_state_t *cmd, const char *var, size_t varlen, cmd_alias_t *alias)
1247 {
1248         static char varname[MAX_INPUTLINE]; // cmd_mutex
1249         static char varval[MAX_INPUTLINE]; // cmd_mutex
1250         const char *varstr = NULL;
1251         char *varfunc;
1252         qbool required = false;
1253         qbool optional = false;
1254         static char asis[] = "asis"; // just to suppress const char warnings
1255
1256         if(varlen >= MAX_INPUTLINE)
1257                 varlen = MAX_INPUTLINE - 1;
1258         memcpy(varname, var, varlen);
1259         varname[varlen] = 0;
1260         varfunc = strchr(varname, ' ');
1261
1262         if(varfunc)
1263         {
1264                 *varfunc = 0;
1265                 ++varfunc;
1266         }
1267
1268         if(*var == 0)
1269         {
1270                 // empty cvar name?
1271                 if(alias)
1272                         Con_Printf(CON_WARN "Warning: Could not expand $ in alias %s\n", alias->name);
1273                 else
1274                         Con_Printf(CON_WARN "Warning: Could not expand $\n");
1275                 return "$";
1276         }
1277
1278         if(varfunc)
1279         {
1280                 char *p;
1281                 // ? means optional
1282                 while((p = strchr(varfunc, '?')))
1283                 {
1284                         optional = true;
1285                         memmove(p, p+1, strlen(p)); // with final NUL
1286                 }
1287                 // ! means required
1288                 while((p = strchr(varfunc, '!')))
1289                 {
1290                         required = true;
1291                         memmove(p, p+1, strlen(p)); // with final NUL
1292                 }
1293                 // kill spaces
1294                 while((p = strchr(varfunc, ' ')))
1295                 {
1296                         memmove(p, p+1, strlen(p)); // with final NUL
1297                 }
1298                 // if no function is left, NULL it
1299                 if(!*varfunc)
1300                         varfunc = NULL;
1301         }
1302
1303         if(varname[0] == '$')
1304                 varstr = Cmd_GetDirectCvarValue(cmd, Cmd_GetDirectCvarValue(cmd, varname + 1, alias, NULL), alias, NULL);
1305         else
1306         {
1307                 qbool is_multiple = false;
1308                 // Exception: $* and $n- don't use the quoted form by default
1309                 varstr = Cmd_GetDirectCvarValue(cmd, varname, alias, &is_multiple);
1310                 if(is_multiple)
1311                         if(!varfunc)
1312                                 varfunc = asis;
1313         }
1314
1315         if(!varstr)
1316         {
1317                 if(required)
1318                 {
1319                         if(alias)
1320                                 Con_Printf(CON_ERROR "Error: Could not expand $%s in alias %s\n", varname, alias->name);
1321                         else
1322                                 Con_Printf(CON_ERROR "Error: Could not expand $%s\n", varname);
1323                         return NULL;
1324                 }
1325                 else if(optional)
1326                 {
1327                         return "";
1328                 }
1329                 else
1330                 {
1331                         if(alias)
1332                                 Con_Printf(CON_WARN "Warning: Could not expand $%s in alias %s\n", varname, alias->name);
1333                         else
1334                                 Con_Printf(CON_WARN "Warning: Could not expand $%s\n", varname);
1335                         dpsnprintf(varval, sizeof(varval), "$%s", varname);
1336                         return varval;
1337                 }
1338         }
1339
1340         if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
1341         {
1342                 // quote it so it can be used inside double quotes
1343                 // we just need to replace " by \", and of course, double backslashes
1344                 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\", false);
1345                 return varval;
1346         }
1347         else if(!strcmp(varfunc, "asis"))
1348         {
1349                 return varstr;
1350         }
1351         else
1352                 Con_Printf("Unknown variable function %s\n", varfunc);
1353
1354         return varstr;
1355 }
1356
1357 /*
1358 Cmd_PreprocessString
1359
1360 Preprocesses strings and replaces $*, $param#, $cvar accordingly. Also strips comments.
1361 */
1362 static qbool Cmd_PreprocessString(cmd_state_t *cmd, const char *intext, char *outtext, unsigned maxoutlen, cmd_alias_t *alias ) {
1363         const char *in;
1364         size_t eat, varlen;
1365         unsigned outlen;
1366         const char *val;
1367
1368         // don't crash if there's no room in the outtext buffer
1369         if( maxoutlen == 0 ) {
1370                 return false;
1371         }
1372         maxoutlen--; // because of \0
1373
1374         in = intext;
1375         outlen = 0;
1376
1377         while( *in && outlen < maxoutlen ) {
1378                 if( *in == '$' ) {
1379                         // this is some kind of expansion, see what comes after the $
1380                         in++;
1381
1382                         // The console does the following preprocessing:
1383                         //
1384                         // - $$ is transformed to a single dollar sign.
1385                         // - $var or ${var} are expanded to the contents of the named cvar,
1386                         //   with quotation marks and backslashes quoted so it can safely
1387                         //   be used inside quotation marks (and it should always be used
1388                         //   that way)
1389                         // - ${var asis} inserts the cvar value as is, without doing this
1390                         //   quoting
1391                         // - ${var ?} silently expands to the empty string if
1392                         //   $var does not exist
1393                         // - ${var !} fails expansion and executes nothing if
1394                         //   $var does not exist
1395                         // - prefix the cvar name with a dollar sign to do indirection;
1396                         //   for example, if $x has the value timelimit, ${$x} will return
1397                         //   the value of $timelimit
1398                         // - when expanding an alias, the special variable name $* refers
1399                         //   to all alias parameters, and a number refers to that numbered
1400                         //   alias parameter, where the name of the alias is $0, the first
1401                         //   parameter is $1 and so on; as a special case, $* inserts all
1402                         //   parameters, without extra quoting, so one can use $* to just
1403                         //   pass all parameters around. All parameters starting from $n
1404                         //   can be referred to as $n- (so $* is equivalent to $1-).
1405                         // - ${* q} and ${n- q} force quoting anyway
1406                         //
1407                         // Note: when expanding an alias, cvar expansion is done in the SAME step
1408                         // as alias expansion so that alias parameters or cvar values containing
1409                         // dollar signs have no unwanted bad side effects. However, this needs to
1410                         // be accounted for when writing complex aliases. For example,
1411                         //   alias foo "set x NEW; echo $x"
1412                         // actually expands to
1413                         //   "set x NEW; echo OLD"
1414                         // and will print OLD! To work around this, use a second alias:
1415                         //   alias foo "set x NEW; foo2"
1416                         //   alias foo2 "echo $x"
1417                         //
1418                         // Also note: lines starting with alias are exempt from cvar expansion.
1419                         // If you want cvar expansion, write "alias" instead:
1420                         //
1421                         //   set x 1
1422                         //   alias foo "echo $x"
1423                         //   "alias" bar "echo $x"
1424                         //   set x 2
1425                         //
1426                         // foo will print 2, because the variable $x will be expanded when the alias
1427                         // gets expanded. bar will print 1, because the variable $x was expanded
1428                         // at definition time. foo can be equivalently defined as
1429                         //
1430                         //   "alias" foo "echo $$x"
1431                         //
1432                         // because at definition time, $$ will get replaced to a single $.
1433
1434                         if( *in == '$' ) {
1435                                 val = "$";
1436                                 eat = 1;
1437                         } else if(*in == '{') {
1438                                 varlen = strcspn(in + 1, "}");
1439                                 if(in[varlen + 1] == '}')
1440                                 {
1441                                         val = Cmd_GetCvarValue(cmd, in + 1, varlen, alias);
1442                                         if(!val)
1443                                                 return false;
1444                                         eat = varlen + 2;
1445                                 }
1446                                 else
1447                                 {
1448                                         // ran out of data?
1449                                         val = NULL;
1450                                         eat = varlen + 1;
1451                                 }
1452                         } else {
1453                                 varlen = strspn(in, "#*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
1454                                 val = Cmd_GetCvarValue(cmd, in, varlen, alias);
1455                                 if(!val)
1456                                         return false;
1457                                 eat = varlen;
1458                         }
1459                         if(val)
1460                         {
1461                                 // insert the cvar value
1462                                 while(*val && outlen < maxoutlen)
1463                                         outtext[outlen++] = *val++;
1464                                 in += eat;
1465                         }
1466                         else
1467                         {
1468                                 // copy the unexpanded text
1469                                 outtext[outlen++] = '$';
1470                                 while(eat && outlen < maxoutlen)
1471                                 {
1472                                         outtext[outlen++] = *in++;
1473                                         --eat;
1474                                 }
1475                         }
1476                 }
1477                 else 
1478                         outtext[outlen++] = *in++;
1479         }
1480         outtext[outlen] = 0;
1481         return true;
1482 }
1483
1484 /*
1485 ============
1486 Cmd_ExecuteAlias
1487
1488 Called for aliases and fills in the alias into the cbuffer
1489 ============
1490 */
1491 static void Cmd_ExecuteAlias (cmd_state_t *cmd, cmd_alias_t *alias)
1492 {
1493         static char buffer[ MAX_INPUTLINE ]; // cmd_mutex
1494         static char buffer2[ MAX_INPUTLINE ]; // cmd_mutex
1495         qbool ret = Cmd_PreprocessString( cmd, alias->value, buffer, sizeof(buffer) - 2, alias );
1496         if(!ret)
1497                 return;
1498         // insert at start of command buffer, so that aliases execute in order
1499         // (fixes bug introduced by Black on 20050705)
1500
1501         // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1502         // have to make sure that no second variable expansion takes place, otherwise
1503         // alias parameters containing dollar signs can have bad effects.
1504         Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$", false);
1505         Cbuf_InsertText(cmd, buffer2);
1506 }
1507
1508 /*
1509 ========
1510 Cmd_List
1511
1512         CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1513         Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1514
1515 ========
1516 */
1517 static void Cmd_List_f (cmd_state_t *cmd)
1518 {
1519         cmd_function_t *func;
1520         const char *partial;
1521         size_t len;
1522         int count;
1523         qbool ispattern;
1524
1525         if (Cmd_Argc(cmd) > 1)
1526         {
1527                 partial = Cmd_Argv(cmd, 1);
1528                 len = strlen(partial);
1529                 ispattern = (strchr(partial, '*') || strchr(partial, '?'));
1530         }
1531         else
1532         {
1533                 partial = NULL;
1534                 len = 0;
1535                 ispattern = false;
1536         }
1537
1538         count = 0;
1539         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1540         {
1541                 if (partial && (ispattern ? !matchpattern_with_separator(func->name, partial, false, "", false) : strncmp(partial, func->name, len)))
1542                         continue;
1543                 Con_Printf("%s : %s\n", func->name, func->description);
1544                 count++;
1545         }
1546         for (func = cmd->engine_functions; func; func = func->next)
1547         {
1548                 if (partial && (ispattern ? !matchpattern_with_separator(func->name, partial, false, "", false) : strncmp(partial, func->name, len)))
1549                         continue;
1550                 Con_Printf("%s : %s\n", func->name, func->description);
1551                 count++;
1552         }
1553
1554         if (len)
1555         {
1556                 if(ispattern)
1557                         Con_Printf("%i Command%s matching \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1558                 else
1559                         Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1560         }
1561         else
1562                 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1563 }
1564
1565 static void Cmd_Apropos_f(cmd_state_t *cmd)
1566 {
1567         cmd_function_t *func;
1568         cvar_t *cvar;
1569         cmd_alias_t *alias;
1570         const char *partial;
1571         int count;
1572         qbool ispattern;
1573         char vabuf[1024];
1574
1575         if (Cmd_Argc(cmd) > 1)
1576                 partial = Cmd_Args(cmd);
1577         else
1578         {
1579                 Con_Printf("usage: %s <string>\n",Cmd_Argv(cmd, 0));
1580                 return;
1581         }
1582
1583         ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1584         if(!ispattern)
1585                 partial = va(vabuf, sizeof(vabuf), "*%s*", partial);
1586
1587         count = 0;
1588         for (cvar = cmd->cvars->vars; cvar; cvar = cvar->next)
1589         {
1590                 if (matchpattern_with_separator(cvar->name, partial, true, "", false) ||
1591                     matchpattern_with_separator(cvar->description, partial, true, "", false))
1592                 {
1593                         Con_Printf ("cvar ");
1594                         Cvar_PrintHelp(cvar, cvar->name, true);
1595                         count++;
1596                 }
1597                 for (int i = 0; i < cvar->aliasindex; i++)
1598                 {
1599                         if (matchpattern_with_separator(cvar->aliases[i], partial, true, "", false))
1600                         {
1601                                 Con_Printf ("cvar ");
1602                                 Cvar_PrintHelp(cvar, cvar->aliases[i], true);
1603                                 count++;
1604                         }
1605                 }
1606         }
1607         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1608         {
1609                 if (!matchpattern_with_separator(func->name, partial, true, "", false))
1610                         if (!matchpattern_with_separator(func->description, partial, true, "", false))
1611                                 continue;
1612                 Con_Printf("command ^2%s^7: %s\n", func->name, func->description);
1613                 count++;
1614         }
1615         for (func = cmd->engine_functions; func; func = func->next)
1616         {
1617                 if (!matchpattern_with_separator(func->name, partial, true, "", false))
1618                 if (!matchpattern_with_separator(func->description, partial, true, "", false))
1619                         continue;
1620                 Con_Printf("command ^2%s^7: %s\n", func->name, func->description);
1621                 count++;
1622         }
1623         for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1624         {
1625                 // procede here a bit differently as an alias value always got a final \n
1626                 if (!matchpattern_with_separator(alias->name, partial, true, "", false))
1627                 if (!matchpattern_with_separator(alias->value, partial, true, "\n", false)) // when \n is as separator wildcards don't match it
1628                         continue;
1629                 Con_Printf("alias ^5%s^7: %s", alias->name, alias->value); // do not print an extra \n
1630                 count++;
1631         }
1632         Con_Printf("%i result%s\n\n", count, (count > 1) ? "s" : "");
1633 }
1634
1635 static cmd_state_t *Cmd_AddInterpreter(cmd_buf_t *cbuf, cvar_state_t *cvars, int cvars_flagsmask, int cmds_flagsmask, cmd_userdefined_t *userdefined)
1636 {
1637         cmd_state_t *cmd = (cmd_state_t *)Mem_Alloc(tempmempool, sizeof(cmd_state_t));
1638         
1639         cmd->mempool = Mem_AllocPool("commands", 0, NULL);
1640         // space for commands and script files
1641         cmd->cbuf = cbuf;
1642         cmd->null_string = "";
1643
1644         cmd->cvars = cvars;
1645         cmd->cvars_flagsmask = cvars_flagsmask;
1646         cmd->cmd_flags = cmds_flagsmask;
1647         cmd->userdefined = userdefined;
1648
1649         return cmd;
1650 }
1651
1652 /*
1653 ============
1654 Cmd_Init
1655 ============
1656 */
1657 void Cmd_Init(void)
1658 {
1659         cmd_buf_t *cbuf;
1660         cbuf_mempool = Mem_AllocPool("Command buffer", 0, NULL);
1661         cbuf = (cmd_buf_t *)Mem_Alloc(cbuf_mempool, sizeof(cmd_buf_t));
1662         cbuf->maxsize = 655360;
1663         cbuf->lock = Thread_CreateMutex();
1664         cbuf->wait = false;
1665         host.cbuf = cbuf;
1666
1667         cbuf->start.prev = cbuf->start.next = &(cbuf->start);
1668         cbuf->deferred.prev = cbuf->deferred.next = &(cbuf->deferred);
1669         cbuf->free.prev = cbuf->free.next = &(cbuf->free);
1670
1671         // FIXME: Get rid of cmd_iter_all eventually. This is just a hack to reduce the amount of work to make the interpreters dynamic.
1672         cmd_iter_all = (cmd_iter_t *)Mem_Alloc(tempmempool, sizeof(cmd_iter_t) * 3);
1673
1674         // local console
1675         cmd_iter_all[0].cmd = cmd_local = Cmd_AddInterpreter(cbuf, &cvars_all, CF_CLIENT | CF_SERVER, CF_CLIENT | CF_CLIENT_FROM_SERVER | CF_SERVER_FROM_CLIENT, &cmd_userdefined_all);
1676         cmd_local->Handle = Cmd_CL_Callback;
1677         cmd_local->NotFound = NULL;
1678
1679         // server commands received from clients have no reason to access cvars, cvar expansion seems perilous.
1680         cmd_iter_all[1].cmd = cmd_serverfromclient = Cmd_AddInterpreter(cbuf, &cvars_null, 0, CF_SERVER_FROM_CLIENT | CF_USERINFO, &cmd_userdefined_null);
1681         cmd_serverfromclient->Handle = Cmd_SV_Callback;
1682         cmd_serverfromclient->NotFound = Cmd_SV_NotFound;
1683
1684         cmd_iter_all[2].cmd = NULL;
1685 //
1686 // register our commands
1687 //
1688         // client-only commands
1689         Cmd_AddCommand(CF_SHARED, "wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1690         Cmd_AddCommand(CF_CLIENT, "cprint", Cmd_Centerprint_f, "print something at the screen center");
1691
1692         // maintenance commands used for upkeep of cvars and saved configs
1693         Cmd_AddCommand(CF_SHARED, "stuffcmds", Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1694         Cmd_AddCommand(CF_SHARED, "cvar_lockdefaults", Cvar_LockDefaults_f, "stores the current values of all cvars into their default values, only used once during startup after parsing default.cfg");
1695         Cmd_AddCommand(CF_SHARED, "cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1696         Cmd_AddCommand(CF_SHARED, "cvar_resettodefaults_nosaveonly", Cvar_ResetToDefaults_NoSaveOnly_f, "sets all non-saved cvars to their locked default values (variables that will not be saved to config.cfg)");
1697         Cmd_AddCommand(CF_SHARED, "cvar_resettodefaults_saveonly", Cvar_ResetToDefaults_SaveOnly_f, "sets all saved cvars to their locked default values (variables that will be saved to config.cfg)");
1698
1699         // general console commands used in multiple environments
1700         Cmd_AddCommand(CF_SHARED, "exec", Cmd_Exec_f, "execute a script file");
1701         Cmd_AddCommand(CF_SHARED, "echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1702         Cmd_AddCommand(CF_SHARED, "alias",Cmd_Alias_f, "create a script function (parameters are passed in as $X (being X a number), $* for all parameters, $X- for all parameters starting from $X). Without arguments show the list of all alias");
1703         Cmd_AddCommand(CF_SHARED, "unalias",Cmd_UnAlias_f, "remove an alias");
1704         Cmd_AddCommand(CF_SHARED, "set", Cvar_Set_f, "create or change the value of a console variable");
1705         Cmd_AddCommand(CF_SHARED, "seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1706         Cmd_AddCommand(CF_SHARED, "unset", Cvar_Del_f, "delete a cvar (does not work for static ones like _cl_name, or read-only ones)");
1707
1708 #ifdef FILLALLCVARSWITHRUBBISH
1709         Cmd_AddCommand(CF_SHARED, "fillallcvarswithrubbish", Cvar_FillAll_f, "fill all cvars with a specified number of characters to provoke buffer overruns");
1710 #endif /* FILLALLCVARSWITHRUBBISH */
1711
1712         // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1713         // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1714         Cmd_AddCommand(CF_SHARED, "cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix or matching the specified wildcard pattern");
1715         Cmd_AddCommand(CF_SHARED, "cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix or matching the specified wildcard pattern");
1716         Cmd_AddCommand(CF_SHARED, "apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1717         Cmd_AddCommand(CF_SHARED, "find", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1718
1719         Cmd_AddCommand(CF_SHARED, "defer", Cmd_Defer_f, "execute a command in the future");
1720
1721         // DRESK - 5/14/06
1722         // Support Doom3-style Toggle Command
1723         Cmd_AddCommand(CF_SHARED | CF_CLIENT_FROM_SERVER, "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1724 }
1725
1726 /*
1727 ============
1728 Cmd_Shutdown
1729 ============
1730 */
1731 void Cmd_Shutdown(void)
1732 {
1733         cmd_iter_t *cmd_iter;
1734         for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
1735         {
1736                 cmd_state_t *cmd = cmd_iter->cmd;
1737
1738                 if (cmd->cbuf->lock)
1739                 {
1740                         // we usually have this locked when we get here from Host_Quit_f
1741                         Cbuf_Unlock(cmd->cbuf);
1742                 }
1743
1744                 Mem_FreePool(&cmd->mempool);
1745         }
1746 }
1747
1748 /*
1749 ============
1750 Cmd_Argc
1751 ============
1752 */
1753 int             Cmd_Argc (cmd_state_t *cmd)
1754 {
1755         return cmd->argc;
1756 }
1757
1758 /*
1759 ============
1760 Cmd_Argv
1761 ============
1762 */
1763 const char *Cmd_Argv(cmd_state_t *cmd, int arg)
1764 {
1765         if (arg >= cmd->argc )
1766                 return cmd->null_string;
1767         return cmd->argv[arg];
1768 }
1769
1770 /*
1771 ============
1772 Cmd_Args
1773 ============
1774 */
1775 const char *Cmd_Args (cmd_state_t *cmd)
1776 {
1777         return cmd->args;
1778 }
1779
1780 /*
1781 ============
1782 Cmd_TokenizeString
1783
1784 Parses the given string into command line tokens.
1785 ============
1786 */
1787 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1788 static void Cmd_TokenizeString (cmd_state_t *cmd, const char *text)
1789 {
1790         int l;
1791
1792         cmd->argc = 0;
1793         cmd->args = NULL;
1794         cmd->cmdline = NULL;
1795
1796         while (1)
1797         {
1798                 // skip whitespace up to a /n
1799                 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1800                         text++;
1801
1802                 // line endings:
1803                 // UNIX: \n
1804                 // Mac: \r
1805                 // Windows: \r\n
1806                 if (*text == '\n' || *text == '\r')
1807                 {
1808                         // a newline separates commands in the buffer
1809                         if (*text == '\r' && text[1] == '\n')
1810                                 text++;
1811                         text++;
1812                         break;
1813                 }
1814
1815                 if (!*text)
1816                         return;
1817
1818                 if(!cmd->argc)
1819                         cmd->cmdline = text;
1820                 if (cmd->argc == 1)
1821                         cmd->args = text;
1822
1823                 if (!COM_ParseToken_Console(&text))
1824                         return;
1825
1826                 if (cmd->argc < MAX_ARGS)
1827                 {
1828                         l = (int)strlen(com_token) + 1;
1829                         if (cmd->cbuf->tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1830                         {
1831                                 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguments\n", CMD_TOKENIZELENGTH);
1832                                 break;
1833                         }
1834                         memcpy (cmd->cbuf->tokenizebuffer + cmd->cbuf->tokenizebufferpos, com_token, l);
1835                         cmd->argv[cmd->argc] = cmd->cbuf->tokenizebuffer + cmd->cbuf->tokenizebufferpos;
1836                         cmd->cbuf->tokenizebufferpos += l;
1837                         cmd->argc++;
1838                 }
1839         }
1840 }
1841
1842
1843 /*
1844 ============
1845 Cmd_AddCommand
1846 ============
1847 */
1848 void Cmd_AddCommand(int flags, const char *cmd_name, xcommand_t function, const char *description)
1849 {
1850         cmd_function_t *func;
1851         cmd_function_t *prev, *current;
1852         cmd_state_t *cmd;
1853         int i;
1854
1855         for (i = 0; i < 2; i++)
1856         {
1857                 cmd = cmd_iter_all[i].cmd;
1858                 if (flags & cmd->cmd_flags)
1859                 {
1860                         // fail if the command is a variable name
1861                         if (Cvar_FindVar(cmd->cvars, cmd_name, ~0))
1862                         {
1863                                 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1864                                 return;
1865                         }
1866
1867                         if (function)
1868                         {
1869                                 // fail if the command already exists in this interpreter
1870                                 for (func = cmd->engine_functions; func; func = func->next)
1871                                 {
1872                                         if (!strcmp(cmd_name, func->name))
1873                                         {
1874                                                 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1875                                                 continue;
1876                                         }
1877                                 }
1878
1879                                 func = (cmd_function_t *)Mem_Alloc(cmd->mempool, sizeof(cmd_function_t));
1880                                 func->flags = flags;
1881                                 func->name = cmd_name;
1882                                 func->function = function;
1883                                 func->description = description;
1884                                 func->next = cmd->engine_functions;
1885
1886                                 // insert it at the right alphanumeric position
1887                                 for (prev = NULL, current = cmd->engine_functions; current && strcmp(current->name, func->name) < 0; prev = current, current = current->next)
1888                                         ;
1889                                 if (prev) {
1890                                         prev->next = func;
1891                                 }
1892                                 else {
1893                                         cmd->engine_functions = func;
1894                                 }
1895                                 func->next = current;
1896                         }
1897                         else
1898                         {
1899                                 // mark qcfunc if the function already exists in the qc_functions list
1900                                 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1901                                 {
1902                                         if (!strcmp(cmd_name, func->name))
1903                                         {
1904                                                 func->qcfunc = true; //[515]: csqc
1905                                                 continue;
1906                                         }
1907                                 }
1908
1909
1910                                 func = (cmd_function_t *)Mem_Alloc(cmd->mempool, sizeof(cmd_function_t));
1911                                 func->flags = flags;
1912                                 func->name = cmd_name;
1913                                 func->function = function;
1914                                 func->description = description;
1915                                 func->qcfunc = true; //[515]: csqc
1916                                 func->next = cmd->userdefined->qc_functions;
1917
1918                                 // insert it at the right alphanumeric position
1919                                 for (prev = NULL, current = cmd->userdefined->qc_functions; current && strcmp(current->name, func->name) < 0; prev = current, current = current->next)
1920                                         ;
1921                                 if (prev) {
1922                                         prev->next = func;
1923                                 }
1924                                 else {
1925                                         cmd->userdefined->qc_functions = func;
1926                                 }
1927                                 func->next = current;
1928                         }
1929                 }
1930         }
1931 }
1932
1933 /*
1934 ============
1935 Cmd_Exists
1936 ============
1937 */
1938 qbool Cmd_Exists (cmd_state_t *cmd, const char *cmd_name)
1939 {
1940         cmd_function_t  *func;
1941
1942         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1943                 if (!strcmp(cmd_name, func->name))
1944                         return true;
1945
1946         for (func=cmd->engine_functions ; func ; func=func->next)
1947                 if (!strcmp (cmd_name,func->name))
1948                         return true;
1949
1950         return false;
1951 }
1952
1953
1954 /*
1955 ============
1956 Cmd_CompleteCommand
1957 ============
1958 */
1959 const char *Cmd_CompleteCommand (cmd_state_t *cmd, const char *partial)
1960 {
1961         cmd_function_t *func;
1962         size_t len;
1963
1964         len = strlen(partial);
1965
1966         if (!len)
1967                 return NULL;
1968
1969 // check functions
1970         for (func = cmd->userdefined->qc_functions; func; func = func->next)
1971                 if (!strncasecmp(partial, func->name, len))
1972                         return func->name;
1973
1974         for (func = cmd->engine_functions; func; func = func->next)
1975                 if (!strncasecmp(partial, func->name, len))
1976                         return func->name;
1977
1978         return NULL;
1979 }
1980
1981 /*
1982         Cmd_CompleteCountPossible
1983
1984         New function for tab-completion system
1985         Added by EvilTypeGuy
1986         Thanks to Fett erich@heintz.com
1987         Thanks to taniwha
1988
1989 */
1990 int Cmd_CompleteCountPossible (cmd_state_t *cmd, const char *partial)
1991 {
1992         cmd_function_t *func;
1993         size_t len;
1994         int h;
1995
1996         h = 0;
1997         len = strlen(partial);
1998
1999         if (!len)
2000                 return 0;
2001
2002         // Loop through the command list and count all partial matches
2003         for (func = cmd->userdefined->qc_functions; func; func = func->next)
2004                 if (!strncasecmp(partial, func->name, len))
2005                         h++;
2006
2007         for (func = cmd->engine_functions; func; func = func->next)
2008                 if (!strncasecmp(partial, func->name, len))
2009                         h++;
2010
2011         return h;
2012 }
2013
2014 /*
2015         Cmd_CompleteBuildList
2016
2017         New function for tab-completion system
2018         Added by EvilTypeGuy
2019         Thanks to Fett erich@heintz.com
2020         Thanks to taniwha
2021
2022 */
2023 const char **Cmd_CompleteBuildList (cmd_state_t *cmd, const char *partial)
2024 {
2025         cmd_function_t *func;
2026         size_t len = 0;
2027         size_t bpos = 0;
2028         size_t sizeofbuf = (Cmd_CompleteCountPossible (cmd, partial) + 1) * sizeof (const char *);
2029         const char **buf;
2030
2031         len = strlen(partial);
2032         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
2033         // Loop through the functions lists and print all matches
2034         for (func = cmd->userdefined->qc_functions; func; func = func->next)
2035                 if (!strncasecmp(partial, func->name, len))
2036                         buf[bpos++] = func->name;
2037         for (func = cmd->engine_functions; func; func = func->next)
2038                 if (!strncasecmp(partial, func->name, len))
2039                         buf[bpos++] = func->name;
2040
2041         buf[bpos] = NULL;
2042         return buf;
2043 }
2044
2045 // written by LadyHavoc
2046 void Cmd_CompleteCommandPrint (cmd_state_t *cmd, const char *partial)
2047 {
2048         cmd_function_t *func;
2049         size_t len = strlen(partial);
2050         // Loop through the command list and print all matches
2051         for (func = cmd->userdefined->qc_functions; func; func = func->next)
2052                 if (!strncasecmp(partial, func->name, len))
2053                         Con_Printf("^2%s^7: %s\n", func->name, func->description);
2054         for (func = cmd->engine_functions; func; func = func->next)
2055                 if (!strncasecmp(partial, func->name, len))
2056                         Con_Printf("^2%s^7: %s\n", func->name, func->description);
2057 }
2058
2059 /*
2060         Cmd_CompleteAlias
2061
2062         New function for tab-completion system
2063         Added by EvilTypeGuy
2064         Thanks to Fett erich@heintz.com
2065         Thanks to taniwha
2066
2067 */
2068 const char *Cmd_CompleteAlias (cmd_state_t *cmd, const char *partial)
2069 {
2070         cmd_alias_t *alias;
2071         size_t len;
2072
2073         len = strlen(partial);
2074
2075         if (!len)
2076                 return NULL;
2077
2078         // Check functions
2079         for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2080                 if (!strncasecmp(partial, alias->name, len))
2081                         return alias->name;
2082
2083         return NULL;
2084 }
2085
2086 // written by LadyHavoc
2087 void Cmd_CompleteAliasPrint (cmd_state_t *cmd, const char *partial)
2088 {
2089         cmd_alias_t *alias;
2090         size_t len = strlen(partial);
2091         // Loop through the alias list and print all matches
2092         for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2093                 if (!strncasecmp(partial, alias->name, len))
2094                         Con_Printf("^5%s^7: %s", alias->name, alias->value);
2095 }
2096
2097
2098 /*
2099         Cmd_CompleteAliasCountPossible
2100
2101         New function for tab-completion system
2102         Added by EvilTypeGuy
2103         Thanks to Fett erich@heintz.com
2104         Thanks to taniwha
2105
2106 */
2107 int Cmd_CompleteAliasCountPossible (cmd_state_t *cmd, const char *partial)
2108 {
2109         cmd_alias_t     *alias;
2110         size_t          len;
2111         int                     h;
2112
2113         h = 0;
2114
2115         len = strlen(partial);
2116
2117         if (!len)
2118                 return 0;
2119
2120         // Loop through the command list and count all partial matches
2121         for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2122                 if (!strncasecmp(partial, alias->name, len))
2123                         h++;
2124
2125         return h;
2126 }
2127
2128 /*
2129         Cmd_CompleteAliasBuildList
2130
2131         New function for tab-completion system
2132         Added by EvilTypeGuy
2133         Thanks to Fett erich@heintz.com
2134         Thanks to taniwha
2135
2136 */
2137 const char **Cmd_CompleteAliasBuildList (cmd_state_t *cmd, const char *partial)
2138 {
2139         cmd_alias_t *alias;
2140         size_t len = 0;
2141         size_t bpos = 0;
2142         size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (cmd, partial) + 1) * sizeof (const char *);
2143         const char **buf;
2144
2145         len = strlen(partial);
2146         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
2147         // Loop through the alias list and print all matches
2148         for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2149                 if (!strncasecmp(partial, alias->name, len))
2150                         buf[bpos++] = alias->name;
2151
2152         buf[bpos] = NULL;
2153         return buf;
2154 }
2155
2156 // TODO: Make this more generic?
2157 void Cmd_ClearCSQCCommands (cmd_state_t *cmd)
2158 {
2159         cmd_function_t *func;
2160         cmd_function_t **next = &cmd->userdefined->qc_functions;
2161         
2162         while(*next)
2163         {
2164                 func = *next;
2165                 *next = func->next;
2166                 Z_Free(func);
2167         }
2168 }
2169
2170 extern cvar_t sv_cheats;
2171
2172 /*
2173  * Cloudwalk FIXME: This idea sounded great in my head but...
2174  * How do we handle commands that can be received by the client,
2175  * but which the server can also execute locally?
2176  * 
2177  * If we create a callback where the engine will forward to server
2178  * but try to execute the command locally if it's dedicated,
2179  * we're back to intermixing client and server code which I'm
2180  * trying to avoid. There's no other way I can think of to
2181  * implement that behavior that doesn't involve an #ifdef, or
2182  * making a mess of hooks.
2183  */
2184 qbool Cmd_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2185 {
2186         if (func->function)
2187                 func->function(cmd);
2188         else
2189                 Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(cmd, 0));
2190         return true;
2191 }
2192
2193 qbool Cmd_CL_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2194 {
2195         // TODO: Assign these functions to QC commands directly?
2196         if(func->qcfunc)
2197         {
2198                 if(((func->flags & CF_CLIENT) && CL_VM_ConsoleCommand(text)) ||
2199                    ((func->flags & CF_SERVER) && SV_VM_ConsoleCommand(text)))
2200                         return true;
2201         }
2202         if (func->flags & CF_SERVER_FROM_CLIENT)
2203         {
2204                 if(host_isclient.integer)
2205                 {
2206                         CL_ForwardToServer_f(cmd);
2207                         return true;
2208                 }
2209                 else if(!(func->flags & CF_SERVER))
2210                 {
2211                         Con_Printf("Cannot execute client commands from a dedicated server console.\n");
2212                         return true;
2213                 }
2214         }
2215         return Cmd_Callback(cmd, func, text, src);
2216 }
2217
2218 qbool Cmd_SV_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2219 {
2220         if(func->qcfunc && (func->flags & CF_SERVER))
2221                 return SV_VM_ConsoleCommand(text);
2222         else if (src == src_client)
2223         {
2224                 if((func->flags & CF_CHEAT) && !sv_cheats.integer)
2225                         SV_ClientPrintf("No cheats allowed. The server must have sv_cheats set to 1\n");
2226                 else
2227                         func->function(cmd);
2228                 return true;
2229         }
2230         return false;
2231 }
2232
2233 qbool Cmd_SV_NotFound(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2234 {
2235         if (cmd->source == src_client)
2236         {
2237                 Con_Printf("Client \"%s\" tried to execute \"%s\"\n", host_client->name, text);
2238                 return true;
2239         }
2240         return false;
2241 }
2242 /*
2243 ============
2244 Cmd_ExecuteString
2245
2246 A complete command line has been parsed, so try to execute it
2247 FIXME: lookupnoadd the token to speed search?
2248 ============
2249 */
2250 void Cmd_ExecuteString (cmd_state_t *cmd, const char *text, cmd_source_t src, qbool lockmutex)
2251 {
2252         int oldpos;
2253         cmd_function_t *func;
2254         cmd_alias_t *a;
2255         if (lockmutex)
2256                 Cbuf_Lock(cmd->cbuf);
2257         oldpos = cmd->cbuf->tokenizebufferpos;
2258         cmd->source = src;
2259
2260         Cmd_TokenizeString (cmd, text);
2261
2262 // execute the command line
2263         if (!Cmd_Argc(cmd))
2264                 goto done; // no tokens
2265
2266 // check functions
2267         for (func = cmd->userdefined->qc_functions; func; func = func->next)
2268         {
2269                 if (!strcasecmp(cmd->argv[0], func->name))
2270                 {
2271                         if(cmd->Handle(cmd, func, text, src))
2272                                 goto done;
2273                 }
2274         }
2275
2276         for (func = cmd->engine_functions; func; func=func->next)
2277         {
2278                 if (!strcasecmp (cmd->argv[0], func->name))
2279                 {
2280                         if(cmd->Handle(cmd, func, text, src))
2281                                 goto done;
2282                 }
2283         }
2284
2285         // if it's a client command and no command was found, say so.
2286         if(cmd->NotFound)
2287         {
2288                 if(cmd->NotFound(cmd, func, text, src))
2289                         goto done;
2290         }
2291
2292 // check alias
2293         for (a=cmd->userdefined->alias ; a ; a=a->next)
2294         {
2295                 if (!strcasecmp (cmd->argv[0], a->name))
2296                 {
2297                         Cmd_ExecuteAlias(cmd, a);
2298                         goto done;
2299                 }
2300         }
2301
2302 // check cvars
2303         if (!Cvar_Command(cmd) && host.framecount > 0)
2304                 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(cmd, 0));
2305 done:
2306         cmd->cbuf->tokenizebufferpos = oldpos;
2307         if (lockmutex)
2308                 Cbuf_Unlock(cmd->cbuf);
2309 }
2310
2311 /*
2312 ================
2313 Cmd_CheckParm
2314
2315 Returns the position (1 to argc-1) in the command's argument list
2316 where the given parameter apears, or 0 if not present
2317 ================
2318 */
2319
2320 int Cmd_CheckParm (cmd_state_t *cmd, const char *parm)
2321 {
2322         int i;
2323
2324         if (!parm)
2325         {
2326                 Con_Printf ("Cmd_CheckParm: NULL");
2327                 return 0;
2328         }
2329
2330         for (i = 1; i < Cmd_Argc (cmd); i++)
2331                 if (!strcasecmp (parm, Cmd_Argv(cmd, i)))
2332                         return i;
2333
2334         return 0;
2335 }
2336
2337
2338
2339 void Cmd_SaveInitState(void)
2340 {
2341         cmd_iter_t *cmd_iter;
2342         for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
2343         {
2344                 cmd_state_t *cmd = cmd_iter->cmd;
2345                 cmd_function_t *f;
2346                 cmd_alias_t *a;
2347                 for (f = cmd->userdefined->qc_functions; f; f = f->next)
2348                         f->initstate = true;
2349                 for (f = cmd->engine_functions; f; f = f->next)
2350                         f->initstate = true;
2351                 for (a = cmd->userdefined->alias; a; a = a->next)
2352                 {
2353                         a->initstate = true;
2354                         a->initialvalue = Mem_strdup(zonemempool, a->value);
2355                 }
2356         }
2357         Cvar_SaveInitState(&cvars_all);
2358 }
2359
2360 void Cmd_RestoreInitState(void)
2361 {
2362         cmd_iter_t *cmd_iter;
2363         for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
2364         {
2365                 cmd_state_t *cmd = cmd_iter->cmd;
2366                 cmd_function_t *f, **fp;
2367                 cmd_alias_t *a, **ap;
2368                 for (fp = &cmd->userdefined->qc_functions; (f = *fp);)
2369                 {
2370                         if (f->initstate)
2371                                 fp = &f->next;
2372                         else
2373                         {
2374                                 // destroy this command, it didn't exist at init
2375                                 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
2376                                 *fp = f->next;
2377                                 Z_Free(f);
2378                         }
2379                 }
2380                 for (fp = &cmd->engine_functions; (f = *fp);)
2381                 {
2382                         if (f->initstate)
2383                                 fp = &f->next;
2384                         else
2385                         {
2386                                 // destroy this command, it didn't exist at init
2387                                 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
2388                                 *fp = f->next;
2389                                 Z_Free(f);
2390                         }
2391                 }
2392                 for (ap = &cmd->userdefined->alias; (a = *ap);)
2393                 {
2394                         if (a->initstate)
2395                         {
2396                                 // restore this alias, it existed at init
2397                                 if (strcmp(a->value ? a->value : "", a->initialvalue ? a->initialvalue : ""))
2398                                 {
2399                                         Con_DPrintf("Cmd_RestoreInitState: Restoring alias %s\n", a->name);
2400                                         if (a->value)
2401                                                 Z_Free(a->value);
2402                                         a->value = Mem_strdup(zonemempool, a->initialvalue);
2403                                 }
2404                                 ap = &a->next;
2405                         }
2406                         else
2407                         {
2408                                 // free this alias, it didn't exist at init...
2409                                 Con_DPrintf("Cmd_RestoreInitState: Destroying alias %s\n", a->name);
2410                                 *ap = a->next;
2411                                 if (a->value)
2412                                         Z_Free(a->value);
2413                                 Z_Free(a);
2414                         }
2415                 }
2416         }
2417         Cvar_RestoreInitState(&cvars_all);
2418 }
2419
2420 void Cmd_NoOperation_f(cmd_state_t *cmd)
2421 {
2422 }