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