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