]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - cmd.c
added Sys_PrintfToTerminal function for convenience, this replaces
[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 typedef struct cmdalias_s
26 {
27         struct cmdalias_s *next;
28         char name[MAX_ALIAS_NAME];
29         char *value;
30         qboolean initstate; // indicates this command existed at init
31         char *initialvalue; // backup copy of value at init
32 } cmdalias_t;
33
34 static cmdalias_t *cmd_alias;
35
36 static qboolean cmd_wait;
37
38 static mempool_t *cmd_mempool;
39
40 static char cmd_tokenizebuffer[CMD_TOKENIZELENGTH];
41 static int cmd_tokenizebufferpos = 0;
42
43 //=============================================================================
44
45 /*
46 ============
47 Cmd_Wait_f
48
49 Causes execution of the remainder of the command buffer to be delayed until
50 next frame.  This allows commands like:
51 bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2"
52 ============
53 */
54 static void Cmd_Wait_f (void)
55 {
56         cmd_wait = true;
57 }
58
59 typedef struct cmddeferred_s
60 {
61         struct cmddeferred_s *next;
62         char *value;
63         double delay;
64 } cmddeferred_t;
65
66 static cmddeferred_t *cmd_deferred_list = NULL;
67
68 /*
69 ============
70 Cmd_Defer_f
71
72 Cause a command to be executed after a delay.
73 ============
74 */
75 static void Cmd_Defer_f (void)
76 {
77         if(Cmd_Argc() == 1)
78         {
79                 cmddeferred_t *next = cmd_deferred_list;
80                 if(!next)
81                         Con_Printf("No commands are pending.\n");
82                 while(next)
83                 {
84                         Con_Printf("-> In %9.2f: %s\n", next->delay, next->value);
85                         next = next->next;
86                 }
87         } else if(Cmd_Argc() == 2 && !strcasecmp("clear", Cmd_Argv(1)))
88         {
89                 while(cmd_deferred_list)
90                 {
91                         cmddeferred_t *cmd = cmd_deferred_list;
92                         cmd_deferred_list = cmd->next;
93                         Mem_Free(cmd->value);
94                         Mem_Free(cmd);
95                 }
96         } else if(Cmd_Argc() == 3)
97         {
98                 const char *value = Cmd_Argv(2);
99                 cmddeferred_t *defcmd = (cmddeferred_t*)Mem_Alloc(tempmempool, sizeof(*defcmd));
100                 size_t len = strlen(value);
101
102                 defcmd->delay = atof(Cmd_Argv(1));
103                 defcmd->value = (char*)Mem_Alloc(tempmempool, len+1);
104                 memcpy(defcmd->value, value, len+1);
105                 defcmd->next = NULL;
106
107                 if(cmd_deferred_list)
108                 {
109                         cmddeferred_t *next = cmd_deferred_list;
110                         while(next->next)
111                                 next = next->next;
112                         next->next = defcmd;
113                 } else
114                         cmd_deferred_list = defcmd;
115                 /* Stupid me... this changes the order... so commands with the same delay go blub :S
116                   defcmd->next = cmd_deferred_list;
117                   cmd_deferred_list = defcmd;*/
118         } else {
119                 Con_Printf("usage: defer <seconds> <command>\n"
120                            "       defer clear\n");
121                 return;
122         }
123 }
124
125 /*
126 ============
127 Cmd_Centerprint_f
128
129 Print something to the center of the screen using SCR_Centerprint
130 ============
131 */
132 static void Cmd_Centerprint_f (void)
133 {
134         char msg[MAX_INPUTLINE];
135         unsigned int i, c, p;
136         c = Cmd_Argc();
137         if(c >= 2)
138         {
139                 strlcpy(msg, Cmd_Argv(1), sizeof(msg));
140                 for(i = 2; i < c; ++i)
141                 {
142                         strlcat(msg, " ", sizeof(msg));
143                         strlcat(msg, Cmd_Argv(i), sizeof(msg));
144                 }
145                 c = strlen(msg);
146                 for(p = 0, i = 0; i < c; ++i)
147                 {
148                         if(msg[i] == '\\')
149                         {
150                                 if(msg[i+1] == 'n')
151                                         msg[p++] = '\n';
152                                 else if(msg[i+1] == '\\')
153                                         msg[p++] = '\\';
154                                 else {
155                                         msg[p++] = '\\';
156                                         msg[p++] = msg[i+1];
157                                 }
158                                 ++i;
159                         } else {
160                                 msg[p++] = msg[i];
161                         }
162                 }
163                 msg[p] = '\0';
164                 SCR_CenterPrint(msg);
165         }
166 }
167
168 /*
169 =============================================================================
170
171                                                 COMMAND BUFFER
172
173 =============================================================================
174 */
175
176 static sizebuf_t        cmd_text;
177 static unsigned char            cmd_text_buf[CMDBUFSIZE];
178 void *cmd_text_mutex = NULL;
179
180 #define Cbuf_LockThreadMutex() (cmd_text_mutex ? Thread_LockMutex(cmd_text_mutex),1 : 0)
181 #define Cbuf_UnlockThreadMutex() (cmd_text_mutex ? Thread_UnlockMutex(cmd_text_mutex),1 : 0)
182
183 /*
184 ============
185 Cbuf_AddText
186
187 Adds command text at the end of the buffer
188 ============
189 */
190 void Cbuf_AddText (const char *text)
191 {
192         int             l;
193
194         l = (int)strlen(text);
195
196         Cbuf_LockThreadMutex();
197         if (cmd_text.cursize + l >= cmd_text.maxsize)
198                 Con_Print("Cbuf_AddText: overflow\n");
199         else
200                 SZ_Write(&cmd_text, (const unsigned char *)text, l);
201         Cbuf_UnlockThreadMutex();
202 }
203
204
205 /*
206 ============
207 Cbuf_InsertText
208
209 Adds command text immediately after the current command
210 Adds a \n to the text
211 FIXME: actually change the command buffer to do less copying
212 ============
213 */
214 void Cbuf_InsertText (const char *text)
215 {
216         size_t l = strlen(text);
217         Cbuf_LockThreadMutex();
218         // we need to memmove the existing text and stuff this in before it...
219         if (cmd_text.cursize + l >= (size_t)cmd_text.maxsize)
220                 Con_Print("Cbuf_InsertText: overflow\n");
221         else
222         {
223                 // we don't have a SZ_Prepend, so...
224                 memmove(cmd_text.data + l, cmd_text.data, cmd_text.cursize);
225                 cmd_text.cursize += l;
226                 memcpy(cmd_text.data, text, l);
227         }
228         Cbuf_UnlockThreadMutex();
229 }
230
231 /*
232 ============
233 Cbuf_Execute_Deferred --blub
234 ============
235 */
236 static void Cbuf_Execute_Deferred (void)
237 {
238         static double oldrealtime = 0;
239         cmddeferred_t *cmd, *prev;
240         double eat;
241         if (realtime - oldrealtime < 0 || realtime - oldrealtime > 1800) oldrealtime = realtime;
242         eat = realtime - oldrealtime;
243         if (eat < (1.0 / 120.0))
244                 return;
245         oldrealtime = realtime;
246         prev = NULL;
247         cmd = cmd_deferred_list;
248         while(cmd)
249         {
250                 cmd->delay -= eat;
251                 if(cmd->delay <= 0)
252                 {
253                         Cbuf_AddText(cmd->value);
254                         Cbuf_AddText(";\n");
255                         Mem_Free(cmd->value);
256
257                         if(prev) {
258                                 prev->next = cmd->next;
259                                 Mem_Free(cmd);
260                                 cmd = prev->next;
261                         } else {
262                                 cmd_deferred_list = cmd->next;
263                                 Mem_Free(cmd);
264                                 cmd = cmd_deferred_list;
265                         }
266                         continue;
267                 }
268                 prev = cmd;
269                 cmd = cmd->next;
270         }
271 }
272
273 /*
274 ============
275 Cbuf_Execute
276 ============
277 */
278 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias );
279 void Cbuf_Execute (void)
280 {
281         int i;
282         char *text;
283         char line[MAX_INPUTLINE];
284         char preprocessed[MAX_INPUTLINE];
285         char *firstchar;
286         qboolean quotes;
287         char *comment;
288
289         // LordHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
290         cmd_tokenizebufferpos = 0;
291
292         Cbuf_Execute_Deferred();
293         while (cmd_text.cursize)
294         {
295 // find a \n or ; line break
296                 text = (char *)cmd_text.data;
297
298                 quotes = false;
299                 comment = NULL;
300                 for (i=0 ; i < cmd_text.cursize ; i++)
301                 {
302                         if(!comment)
303                         {
304                                 if (text[i] == '"')
305                                         quotes = !quotes;
306
307                                 if(quotes)
308                                 {
309                                         // make sure i doesn't get > cursize which causes a negative
310                                         // size in memmove, which is fatal --blub
311                                         if (i < (cmd_text.cursize-1) && (text[i] == '\\' && (text[i+1] == '"' || text[i+1] == '\\')))
312                                                 i++;
313                                 }
314                                 else
315                                 {
316                                         if(text[i] == '/' && text[i + 1] == '/' && (i == 0 || ISWHITESPACE(text[i-1])))
317                                                 comment = &text[i];
318                                         if(text[i] == ';')
319                                                 break;  // don't break if inside a quoted string or comment
320                                 }
321                         }
322
323                         if (text[i] == '\r' || text[i] == '\n')
324                                 break;
325                 }
326
327                 // better than CRASHING on overlong input lines that may SOMEHOW enter the buffer
328                 if(i >= MAX_INPUTLINE)
329                 {
330                         Con_Printf("Warning: console input buffer had an overlong line. Ignored.\n");
331                         line[0] = 0;
332                 }
333                 else
334                 {
335                         memcpy (line, text, comment ? (comment - text) : i);
336                         line[comment ? (comment - text) : i] = 0;
337                 }
338
339 // delete the text from the command buffer and move remaining commands down
340 // this is necessary because commands (exec, alias) can insert data at the
341 // beginning of the text buffer
342
343                 if (i == cmd_text.cursize)
344                         cmd_text.cursize = 0;
345                 else
346                 {
347                         i++;
348                         cmd_text.cursize -= i;
349                         memmove (cmd_text.data, text+i, cmd_text.cursize);
350                 }
351
352 // execute the command line
353                 firstchar = line;
354                 while(*firstchar && ISWHITESPACE(*firstchar))
355                         ++firstchar;
356                 if(
357                         (strncmp(firstchar, "alias", 5) || !ISWHITESPACE(firstchar[5]))
358                         &&
359                         (strncmp(firstchar, "bind", 4) || !ISWHITESPACE(firstchar[4]))
360                         &&
361                         (strncmp(firstchar, "in_bind", 7) || !ISWHITESPACE(firstchar[7]))
362                 )
363                 {
364                         Cmd_PreprocessString( line, preprocessed, sizeof(preprocessed), NULL );
365                         Cmd_ExecuteString (preprocessed, src_command, false);
366                 }
367                 else
368                 {
369                         Cmd_ExecuteString (line, src_command, false);
370                 }
371
372                 if (cmd_wait)
373                 {       // skip out while text still remains in buffer, leaving it
374                         // for next frame
375                         cmd_wait = false;
376                         break;
377                 }
378         }
379 }
380
381 /*
382 ==============================================================================
383
384                                                 SCRIPT COMMANDS
385
386 ==============================================================================
387 */
388
389 /*
390 ===============
391 Cmd_StuffCmds_f
392
393 Adds command line parameters as script statements
394 Commands lead with a +, and continue until a - or another +
395 quake +prog jctest.qp +cmd amlev1
396 quake -nosound +cmd amlev1
397 ===============
398 */
399 qboolean host_stuffcmdsrun = false;
400 static void Cmd_StuffCmds_f (void)
401 {
402         int             i, j, l;
403         // this is for all commandline options combined (and is bounds checked)
404         char    build[MAX_INPUTLINE];
405
406         if (Cmd_Argc () != 1)
407         {
408                 Con_Print("stuffcmds : execute command line parameters\n");
409                 return;
410         }
411
412         // no reason to run the commandline arguments twice
413         if (host_stuffcmdsrun)
414                 return;
415
416         host_stuffcmdsrun = true;
417         build[0] = 0;
418         l = 0;
419         for (i = 0;i < com_argc;i++)
420         {
421                 if (com_argv[i] && com_argv[i][0] == '+' && (com_argv[i][1] < '0' || com_argv[i][1] > '9') && l + strlen(com_argv[i]) - 1 <= sizeof(build) - 1)
422                 {
423                         j = 1;
424                         while (com_argv[i][j])
425                                 build[l++] = com_argv[i][j++];
426                         i++;
427                         for (;i < com_argc;i++)
428                         {
429                                 if (!com_argv[i])
430                                         continue;
431                                 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
432                                         break;
433                                 if (l + strlen(com_argv[i]) + 4 > sizeof(build) - 1)
434                                         break;
435                                 build[l++] = ' ';
436                                 if (strchr(com_argv[i], ' '))
437                                         build[l++] = '\"';
438                                 for (j = 0;com_argv[i][j];j++)
439                                         build[l++] = com_argv[i][j];
440                                 if (strchr(com_argv[i], ' '))
441                                         build[l++] = '\"';
442                         }
443                         build[l++] = '\n';
444                         i--;
445                 }
446         }
447         // now terminate the combined string and prepend it to the command buffer
448         // we already reserved space for the terminator
449         build[l++] = 0;
450         Cbuf_InsertText (build);
451 }
452
453 static void Cmd_Exec(const char *filename)
454 {
455         char *f;
456         qboolean isdefaultcfg = strlen(filename) >= 11 && !strcmp(filename + strlen(filename) - 11, "default.cfg");
457
458         if (!strcmp(filename, "config.cfg"))
459         {
460                 filename = CONFIGFILENAME;
461                 if (COM_CheckParm("-noconfig"))
462                         return; // don't execute config.cfg
463         }
464
465         f = (char *)FS_LoadFile (filename, tempmempool, false, NULL);
466         if (!f)
467         {
468                 Con_Printf("couldn't exec %s\n",filename);
469                 return;
470         }
471         Con_Printf("execing %s\n",filename);
472
473         // if executing default.cfg for the first time, lock the cvar defaults
474         // it may seem backwards to insert this text BEFORE the default.cfg
475         // but Cbuf_InsertText inserts before, so this actually ends up after it.
476         if (isdefaultcfg)
477                 Cbuf_InsertText("\ncvar_lockdefaults\n");
478
479         // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
480         // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
481         Cbuf_InsertText ("\n");
482         Cbuf_InsertText (f);
483         Mem_Free(f);
484
485         if (isdefaultcfg)
486         {
487                 // special defaults for specific games go here, these execute before default.cfg
488                 // Nehahra pushable crates malfunction in some levels if this is on
489                 // Nehahra NPC AI is confused by blowupfallenzombies
490                 if (gamemode == GAME_NEHAHRA)
491                         Cbuf_InsertText("\nsv_gameplayfix_upwardvelocityclearsongroundflag 0\nsv_gameplayfix_blowupfallenzombies 0\n\n");
492                 // 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.
493                 // 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
494                 // hipnotic mission pack has issues in their proximity mine sticking code, which causes them to bounce off.
495                 if (gamemode == GAME_HIPNOTIC)
496                         Cbuf_InsertText("\nsv_gameplayfix_blowupfallenzombies 0\nsys_ticrate 0.02\nsv_gameplayfix_slidemoveprojectiles 0\n\n");
497                 // rogue mission pack has a guardian boss that does not wake up if findradius returns one of the entities around its spawn area
498                 if (gamemode == GAME_ROGUE)
499                         Cbuf_InsertText("\nsv_gameplayfix_findradiusdistancetobox 0\n\n");
500                 if (gamemode == GAME_NEXUIZ)
501                         Cbuf_InsertText("\nsv_gameplayfix_q2airaccelerate 1\nsv_gameplayfix_stepmultipletimes 1\n\n");
502                 if (gamemode == GAME_TENEBRAE)
503                         Cbuf_InsertText("\nr_shadow_gloss 2\nr_shadow_bumpscale_basetexture 4\n\n");
504                 // Steel Storm: Burning Retribution csqc misinterprets CSQC_InputEvent if type is a value other than 0 or 1
505                 if (gamemode == GAME_STEELSTORM)
506                         Cbuf_InsertText("\ncl_csqc_generatemousemoveevents 0\n\n");
507         }
508 }
509
510 /*
511 ===============
512 Cmd_Exec_f
513 ===============
514 */
515 static void Cmd_Exec_f (void)
516 {
517         fssearch_t *s;
518         int i;
519
520         if (Cmd_Argc () != 2)
521         {
522                 Con_Print("exec <filename> : execute a script file\n");
523                 return;
524         }
525
526         s = FS_Search(Cmd_Argv(1), true, true);
527         if(!s || !s->numfilenames)
528         {
529                 Con_Printf("couldn't exec %s\n",Cmd_Argv(1));
530                 return;
531         }
532
533         for(i = 0; i < s->numfilenames; ++i)
534                 Cmd_Exec(s->filenames[i]);
535
536         FS_FreeSearch(s);
537 }
538
539
540 /*
541 ===============
542 Cmd_Echo_f
543
544 Just prints the rest of the line to the console
545 ===============
546 */
547 static void Cmd_Echo_f (void)
548 {
549         int             i;
550
551         for (i=1 ; i<Cmd_Argc() ; i++)
552                 Con_Printf("%s ",Cmd_Argv(i));
553         Con_Print("\n");
554 }
555
556 // DRESK - 5/14/06
557 // Support Doom3-style Toggle Console Command
558 /*
559 ===============
560 Cmd_Toggle_f
561
562 Toggles a specified console variable amongst the values specified (default is 0 and 1)
563 ===============
564 */
565 static void Cmd_Toggle_f(void)
566 {
567         // Acquire Number of Arguments
568         int nNumArgs = Cmd_Argc();
569
570         if(nNumArgs == 1)
571                 // No Arguments Specified; Print Usage
572                 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");
573         else
574         { // Correct Arguments Specified
575                 // Acquire Potential CVar
576                 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
577
578                 if(cvCVar != NULL)
579                 { // Valid CVar
580                         if(nNumArgs == 2)
581                         { // Default Usage
582                                 if(cvCVar->integer)
583                                         Cvar_SetValueQuick(cvCVar, 0);
584                                 else
585                                         Cvar_SetValueQuick(cvCVar, 1);
586                         }
587                         else
588                         if(nNumArgs == 3)
589                         { // 0 and Specified Usage
590                                 if(cvCVar->integer == atoi(Cmd_Argv(2) ) )
591                                         // CVar is Specified Value; // Reset to 0
592                                         Cvar_SetValueQuick(cvCVar, 0);
593                                 else
594                                 if(cvCVar->integer == 0)
595                                         // CVar is 0; Specify Value
596                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
597                                 else
598                                         // CVar does not match; Reset to 0
599                                         Cvar_SetValueQuick(cvCVar, 0);
600                         }
601                         else
602                         { // Variable Values Specified
603                                 int nCnt;
604                                 int bFound = 0;
605
606                                 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
607                                 { // Cycle through Values
608                                         if( strcmp(cvCVar->string, Cmd_Argv(nCnt) ) == 0)
609                                         { // Current Value Located; Increment to Next
610                                                 if( (nCnt + 1) == nNumArgs)
611                                                         // Max Value Reached; Reset
612                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
613                                                 else
614                                                         // Next Value
615                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
616
617                                                 // End Loop
618                                                 nCnt = nNumArgs;
619                                                 // Assign Found
620                                                 bFound = 1;
621                                         }
622                                 }
623                                 if(!bFound)
624                                         // Value not Found; Reset to Original
625                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
626                         }
627
628                 }
629                 else
630                 { // Invalid CVar
631                         Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(1) );
632                 }
633         }
634 }
635
636 /*
637 ===============
638 Cmd_Alias_f
639
640 Creates a new command that executes a command string (possibly ; seperated)
641 ===============
642 */
643 static void Cmd_Alias_f (void)
644 {
645         cmdalias_t      *a;
646         char            cmd[MAX_INPUTLINE];
647         int                     i, c;
648         const char              *s;
649         size_t          alloclen;
650
651         if (Cmd_Argc() == 1)
652         {
653                 Con_Print("Current alias commands:\n");
654                 for (a = cmd_alias ; a ; a=a->next)
655                         Con_Printf("%s : %s", a->name, a->value);
656                 return;
657         }
658
659         s = Cmd_Argv(1);
660         if (strlen(s) >= MAX_ALIAS_NAME)
661         {
662                 Con_Print("Alias name is too long\n");
663                 return;
664         }
665
666         // if the alias already exists, reuse it
667         for (a = cmd_alias ; a ; a=a->next)
668         {
669                 if (!strcmp(s, a->name))
670                 {
671                         Z_Free (a->value);
672                         break;
673                 }
674         }
675
676         if (!a)
677         {
678                 cmdalias_t *prev, *current;
679
680                 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
681                 strlcpy (a->name, s, sizeof (a->name));
682                 // insert it at the right alphanumeric position
683                 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
684                         ;
685                 if( prev ) {
686                         prev->next = a;
687                 } else {
688                         cmd_alias = a;
689                 }
690                 a->next = current;
691         }
692
693
694 // copy the rest of the command line
695         cmd[0] = 0;             // start out with a null string
696         c = Cmd_Argc();
697         for (i=2 ; i < c ; i++)
698         {
699                 if (i != 2)
700                         strlcat (cmd, " ", sizeof (cmd));
701                 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
702         }
703         strlcat (cmd, "\n", sizeof (cmd));
704
705         alloclen = strlen (cmd) + 1;
706         if(alloclen >= 2)
707                 cmd[alloclen - 2] = '\n'; // to make sure a newline is appended even if too long
708         a->value = (char *)Z_Malloc (alloclen);
709         memcpy (a->value, cmd, alloclen);
710 }
711
712 /*
713 ===============
714 Cmd_UnAlias_f
715
716 Remove existing aliases.
717 ===============
718 */
719 static void Cmd_UnAlias_f (void)
720 {
721         cmdalias_t      *a, *p;
722         int i;
723         const char *s;
724
725         if(Cmd_Argc() == 1)
726         {
727                 Con_Print("unalias: Usage: unalias alias1 [alias2 ...]\n");
728                 return;
729         }
730
731         for(i = 1; i < Cmd_Argc(); ++i)
732         {
733                 s = Cmd_Argv(i);
734                 p = NULL;
735                 for(a = cmd_alias; a; p = a, a = a->next)
736                 {
737                         if(!strcmp(s, a->name))
738                         {
739                                 if (a->initstate) // we can not remove init aliases
740                                         continue;
741                                 if(a == cmd_alias)
742                                         cmd_alias = a->next;
743                                 if(p)
744                                         p->next = a->next;
745                                 Z_Free(a->value);
746                                 Z_Free(a);
747                                 break;
748                         }
749                 }
750                 if(!a)
751                         Con_Printf("unalias: %s alias not found\n", s);
752         }
753 }
754
755 /*
756 =============================================================================
757
758                                         COMMAND EXECUTION
759
760 =============================================================================
761 */
762
763 typedef struct cmd_function_s
764 {
765         struct cmd_function_s *next;
766         const char *name;
767         const char *description;
768         xcommand_t consolefunction;
769         xcommand_t clientfunction;
770         qboolean csqcfunc;
771         qboolean initstate; // indicates this command existed at init
772 } cmd_function_t;
773
774 static int cmd_argc;
775 static const char *cmd_argv[MAX_ARGS];
776 static const char *cmd_null_string = "";
777 static const char *cmd_args;
778 cmd_source_t cmd_source;
779
780
781 static cmd_function_t *cmd_functions;           // possible commands to execute
782
783 static const char *Cmd_GetDirectCvarValue(const char *varname, cmdalias_t *alias, qboolean *is_multiple)
784 {
785         cvar_t *cvar;
786         long argno;
787         char *endptr;
788         char vabuf[1024];
789
790         if(is_multiple)
791                 *is_multiple = false;
792
793         if(!varname || !*varname)
794                 return NULL;
795
796         if(alias)
797         {
798                 if(!strcmp(varname, "*"))
799                 {
800                         if(is_multiple)
801                                 *is_multiple = true;
802                         return Cmd_Args();
803                 }
804                 else if(!strcmp(varname, "#"))
805                 {
806                         return va(vabuf, sizeof(vabuf), "%d", Cmd_Argc());
807                 }
808                 else if(varname[strlen(varname) - 1] == '-')
809                 {
810                         argno = strtol(varname, &endptr, 10);
811                         if(endptr == varname + strlen(varname) - 1)
812                         {
813                                 // whole string is a number, apart from the -
814                                 const char *p = Cmd_Args();
815                                 for(; argno > 1; --argno)
816                                         if(!COM_ParseToken_Console(&p))
817                                                 break;
818                                 if(p)
819                                 {
820                                         if(is_multiple)
821                                                 *is_multiple = true;
822
823                                         // kill pre-argument whitespace
824                                         for (;*p && ISWHITESPACE(*p);p++)
825                                                 ;
826
827                                         return p;
828                                 }
829                         }
830                 }
831                 else
832                 {
833                         argno = strtol(varname, &endptr, 10);
834                         if(*endptr == 0)
835                         {
836                                 // whole string is a number
837                                 // NOTE: we already made sure we don't have an empty cvar name!
838                                 if(argno >= 0 && argno < Cmd_Argc())
839                                         return Cmd_Argv(argno);
840                         }
841                 }
842         }
843
844         if((cvar = Cvar_FindVar(varname)) && !(cvar->flags & CVAR_PRIVATE))
845                 return cvar->string;
846
847         return NULL;
848 }
849
850 qboolean Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset, qboolean putquotes)
851 {
852         qboolean quote_quot = !!strchr(quoteset, '"');
853         qboolean quote_backslash = !!strchr(quoteset, '\\');
854         qboolean quote_dollar = !!strchr(quoteset, '$');
855
856         if(putquotes)
857         {
858                 if(outlen <= 2)
859                 {
860                         *out++ = 0;
861                         return false;
862                 }
863                 *out++ = '"'; --outlen;
864                 --outlen;
865         }
866
867         while(*in)
868         {
869                 if(*in == '"' && quote_quot)
870                 {
871                         if(outlen <= 2)
872                                 goto fail;
873                         *out++ = '\\'; --outlen;
874                         *out++ = '"'; --outlen;
875                 }
876                 else if(*in == '\\' && quote_backslash)
877                 {
878                         if(outlen <= 2)
879                                 goto fail;
880                         *out++ = '\\'; --outlen;
881                         *out++ = '\\'; --outlen;
882                 }
883                 else if(*in == '$' && quote_dollar)
884                 {
885                         if(outlen <= 2)
886                                 goto fail;
887                         *out++ = '$'; --outlen;
888                         *out++ = '$'; --outlen;
889                 }
890                 else
891                 {
892                         if(outlen <= 1)
893                                 goto fail;
894                         *out++ = *in; --outlen;
895                 }
896                 ++in;
897         }
898         if(putquotes)
899                 *out++ = '"';
900         *out++ = 0;
901         return true;
902 fail:
903         if(putquotes)
904                 *out++ = '"';
905         *out++ = 0;
906         return false;
907 }
908
909 static const char *Cmd_GetCvarValue(const char *var, size_t varlen, cmdalias_t *alias)
910 {
911         static char varname[MAX_INPUTLINE]; // cmd_mutex
912         static char varval[MAX_INPUTLINE]; // cmd_mutex
913         const char *varstr;
914         char *varfunc;
915 static char asis[] = "asis"; // just to suppress const char warnings
916
917         if(varlen >= MAX_INPUTLINE)
918                 varlen = MAX_INPUTLINE - 1;
919         memcpy(varname, var, varlen);
920         varname[varlen] = 0;
921         varfunc = strchr(varname, ' ');
922
923         if(varfunc)
924         {
925                 *varfunc = 0;
926                 ++varfunc;
927         }
928
929         if(*var == 0)
930         {
931                 // empty cvar name?
932                 return NULL;
933         }
934
935         varstr = NULL;
936
937         if(varname[0] == '$')
938                 varstr = Cmd_GetDirectCvarValue(Cmd_GetDirectCvarValue(varname + 1, alias, NULL), alias, NULL);
939         else
940         {
941                 qboolean is_multiple = false;
942                 // Exception: $* and $n- don't use the quoted form by default
943                 varstr = Cmd_GetDirectCvarValue(varname, alias, &is_multiple);
944                 if(is_multiple)
945                         if(!varfunc)
946                                 varfunc = asis;
947         }
948
949         if(!varstr)
950         {
951                 if(alias)
952                         Con_Printf("Warning: Could not expand $%s in alias %s\n", varname, alias->name);
953                 else
954                         Con_Printf("Warning: Could not expand $%s\n", varname);
955                 return NULL;
956         }
957
958         if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
959         {
960                 // quote it so it can be used inside double quotes
961                 // we just need to replace " by \", and of course, double backslashes
962                 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\", false);
963                 return varval;
964         }
965         else if(!strcmp(varfunc, "asis"))
966         {
967                 return varstr;
968         }
969         else
970                 Con_Printf("Unknown variable function %s\n", varfunc);
971
972         return varstr;
973 }
974
975 /*
976 Cmd_PreprocessString
977
978 Preprocesses strings and replaces $*, $param#, $cvar accordingly. Also strips comments.
979 */
980 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
981         const char *in;
982         size_t eat, varlen;
983         unsigned outlen;
984         const char *val;
985
986         // don't crash if there's no room in the outtext buffer
987         if( maxoutlen == 0 ) {
988                 return;
989         }
990         maxoutlen--; // because of \0
991
992         in = intext;
993         outlen = 0;
994
995         while( *in && outlen < maxoutlen ) {
996                 if( *in == '$' ) {
997                         // this is some kind of expansion, see what comes after the $
998                         in++;
999
1000                         // The console does the following preprocessing:
1001                         //
1002                         // - $$ is transformed to a single dollar sign.
1003                         // - $var or ${var} are expanded to the contents of the named cvar,
1004                         //   with quotation marks and backslashes quoted so it can safely
1005                         //   be used inside quotation marks (and it should always be used
1006                         //   that way)
1007                         // - ${var asis} inserts the cvar value as is, without doing this
1008                         //   quoting
1009                         // - prefix the cvar name with a dollar sign to do indirection;
1010                         //   for example, if $x has the value timelimit, ${$x} will return
1011                         //   the value of $timelimit
1012                         // - when expanding an alias, the special variable name $* refers
1013                         //   to all alias parameters, and a number refers to that numbered
1014                         //   alias parameter, where the name of the alias is $0, the first
1015                         //   parameter is $1 and so on; as a special case, $* inserts all
1016                         //   parameters, without extra quoting, so one can use $* to just
1017                         //   pass all parameters around. All parameters starting from $n
1018                         //   can be referred to as $n- (so $* is equivalent to $1-).
1019                         //
1020                         // Note: when expanding an alias, cvar expansion is done in the SAME step
1021                         // as alias expansion so that alias parameters or cvar values containing
1022                         // dollar signs have no unwanted bad side effects. However, this needs to
1023                         // be accounted for when writing complex aliases. For example,
1024                         //   alias foo "set x NEW; echo $x"
1025                         // actually expands to
1026                         //   "set x NEW; echo OLD"
1027                         // and will print OLD! To work around this, use a second alias:
1028                         //   alias foo "set x NEW; foo2"
1029                         //   alias foo2 "echo $x"
1030                         //
1031                         // Also note: lines starting with alias are exempt from cvar expansion.
1032                         // If you want cvar expansion, write "alias" instead:
1033                         //
1034                         //   set x 1
1035                         //   alias foo "echo $x"
1036                         //   "alias" bar "echo $x"
1037                         //   set x 2
1038                         //
1039                         // foo will print 2, because the variable $x will be expanded when the alias
1040                         // gets expanded. bar will print 1, because the variable $x was expanded
1041                         // at definition time. foo can be equivalently defined as
1042                         //
1043                         //   "alias" foo "echo $$x"
1044                         //
1045                         // because at definition time, $$ will get replaced to a single $.
1046
1047                         if( *in == '$' ) {
1048                                 val = "$";
1049                                 eat = 1;
1050                         } else if(*in == '{') {
1051                                 varlen = strcspn(in + 1, "}");
1052                                 if(in[varlen + 1] == '}')
1053                                 {
1054                                         val = Cmd_GetCvarValue(in + 1, varlen, alias);
1055                                         eat = varlen + 2;
1056                                 }
1057                                 else
1058                                 {
1059                                         // ran out of data?
1060                                         val = NULL;
1061                                         eat = varlen + 1;
1062                                 }
1063                         } else {
1064                                 varlen = strspn(in, "#*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
1065                                 val = Cmd_GetCvarValue(in, varlen, alias);
1066                                 eat = varlen;
1067                         }
1068                         if(val)
1069                         {
1070                                 // insert the cvar value
1071                                 while(*val && outlen < maxoutlen)
1072                                         outtext[outlen++] = *val++;
1073                                 in += eat;
1074                         }
1075                         else
1076                         {
1077                                 // copy the unexpanded text
1078                                 outtext[outlen++] = '$';
1079                                 while(eat && outlen < maxoutlen)
1080                                 {
1081                                         outtext[outlen++] = *in++;
1082                                         --eat;
1083                                 }
1084                         }
1085                 }
1086                 else 
1087                         outtext[outlen++] = *in++;
1088         }
1089         outtext[outlen] = 0;
1090 }
1091
1092 /*
1093 ============
1094 Cmd_ExecuteAlias
1095
1096 Called for aliases and fills in the alias into the cbuffer
1097 ============
1098 */
1099 static void Cmd_ExecuteAlias (cmdalias_t *alias)
1100 {
1101         static char buffer[ MAX_INPUTLINE ]; // cmd_mutex
1102         static char buffer2[ MAX_INPUTLINE ]; // cmd_mutex
1103         Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
1104         // insert at start of command buffer, so that aliases execute in order
1105         // (fixes bug introduced by Black on 20050705)
1106
1107         // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1108         // have to make sure that no second variable expansion takes place, otherwise
1109         // alias parameters containing dollar signs can have bad effects.
1110         Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$", false);
1111         Cbuf_InsertText( buffer2 );
1112 }
1113
1114 /*
1115 ========
1116 Cmd_List
1117
1118         CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1119         Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1120
1121 ========
1122 */
1123 static void Cmd_List_f (void)
1124 {
1125         cmd_function_t *cmd;
1126         const char *partial;
1127         size_t len;
1128         int count;
1129         qboolean ispattern;
1130
1131         if (Cmd_Argc() > 1)
1132         {
1133                 partial = Cmd_Argv (1);
1134                 len = strlen(partial);
1135         }
1136         else
1137         {
1138                 partial = NULL;
1139                 len = 0;
1140         }
1141
1142         ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1143
1144         count = 0;
1145         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1146         {
1147                 if (partial && (ispattern ? !matchpattern_with_separator(cmd->name, partial, false, "", false) : strncmp(partial, cmd->name, len)))
1148                         continue;
1149                 Con_Printf("%s : %s\n", cmd->name, cmd->description);
1150                 count++;
1151         }
1152
1153         if (len)
1154         {
1155                 if(ispattern)
1156                         Con_Printf("%i Command%s matching \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1157                 else
1158                         Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1159         }
1160         else
1161                 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1162 }
1163
1164 static void Cmd_Apropos_f(void)
1165 {
1166         cmd_function_t *cmd;
1167         cvar_t *cvar;
1168         cmdalias_t *alias;
1169         const char *partial;
1170         int count;
1171         qboolean ispattern;
1172         char vabuf[1024];
1173
1174         if (Cmd_Argc() > 1)
1175                 partial = Cmd_Args();
1176         else
1177         {
1178                 Con_Printf("usage: apropos <string>\n");
1179                 return;
1180         }
1181
1182         ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1183         if(!ispattern)
1184                 partial = va(vabuf, sizeof(vabuf), "*%s*", partial);
1185
1186         count = 0;
1187         for (cvar = cvar_vars; cvar; cvar = cvar->next)
1188         {
1189                 if (!matchpattern_with_separator(cvar->name, partial, true, "", false))
1190                 if (!matchpattern_with_separator(cvar->description, partial, true, "", false))
1191                         continue;
1192                 Con_Printf ("cvar ^3%s^7 is \"%s\" [\"%s\"] %s\n", cvar->name, cvar->string, cvar->defstring, cvar->description);
1193                 count++;
1194         }
1195         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1196         {
1197                 if (!matchpattern_with_separator(cmd->name, partial, true, "", false))
1198                 if (!matchpattern_with_separator(cmd->description, partial, true, "", false))
1199                         continue;
1200                 Con_Printf("command ^2%s^7: %s\n", cmd->name, cmd->description);
1201                 count++;
1202         }
1203         for (alias = cmd_alias; alias; alias = alias->next)
1204         {
1205                 // procede here a bit differently as an alias value always got a final \n
1206                 if (!matchpattern_with_separator(alias->name, partial, true, "", false))
1207                 if (!matchpattern_with_separator(alias->value, partial, true, "\n", false)) // when \n is as separator wildcards don't match it
1208                         continue;
1209                 Con_Printf("alias ^5%s^7: %s", alias->name, alias->value); // do not print an extra \n
1210                 count++;
1211         }
1212         Con_Printf("%i result%s\n\n", count, (count > 1) ? "s" : "");
1213 }
1214
1215 /*
1216 ============
1217 Cmd_Init
1218 ============
1219 */
1220 void Cmd_Init (void)
1221 {
1222         cmd_mempool = Mem_AllocPool("commands", 0, NULL);
1223         // space for commands and script files
1224         cmd_text.data = cmd_text_buf;
1225         cmd_text.maxsize = sizeof(cmd_text_buf);
1226         cmd_text.cursize = 0;
1227
1228         if (Thread_HasThreads())
1229                 cmd_text_mutex = Thread_CreateMutex();
1230 }
1231
1232 void Cmd_Init_Commands (void)
1233 {
1234 //
1235 // register our commands
1236 //
1237         Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1238         Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
1239         Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1240         Cmd_AddCommand ("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");
1241         Cmd_AddCommand ("unalias",Cmd_UnAlias_f, "remove an alias");
1242         Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
1243         Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1244         Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
1245         Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1246         Cmd_AddCommand ("unset", Cvar_Del_f, "delete a cvar (does not work for static ones like _cl_name, or read-only ones)");
1247 #ifdef FILLALLCVARSWITHRUBBISH
1248         Cmd_AddCommand ("fillallcvarswithrubbish", Cvar_FillAll_f, "fill all cvars with a specified number of characters to provoke buffer overruns");
1249 #endif /* FILLALLCVARSWITHRUBBISH */
1250
1251         // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1252         // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1253         Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix or matching the specified wildcard pattern");
1254         Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix or matching the specified wildcard pattern");
1255         Cmd_AddCommand ("apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1256
1257         Cmd_AddCommand ("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");
1258         Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1259         Cmd_AddCommand ("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)");
1260         Cmd_AddCommand ("cvar_resettodefaults_saveonly", Cvar_ResetToDefaults_SaveOnly_f, "sets all saved cvars to their locked default values (variables that will be saved to config.cfg)");
1261
1262         Cmd_AddCommand ("cprint", Cmd_Centerprint_f, "print something at the screen center");
1263         Cmd_AddCommand ("defer", Cmd_Defer_f, "execute a command in the future");
1264
1265         // DRESK - 5/14/06
1266         // Support Doom3-style Toggle Command
1267         Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1268 }
1269
1270 /*
1271 ============
1272 Cmd_Shutdown
1273 ============
1274 */
1275 void Cmd_Shutdown(void)
1276 {
1277         if (cmd_text_mutex)
1278         {
1279                 // we usually have this locked when we get here from Host_Quit_f
1280                 Cbuf_UnlockThreadMutex();
1281                 Thread_DestroyMutex(cmd_text_mutex);
1282         }
1283         cmd_text_mutex = NULL;
1284
1285         Mem_FreePool(&cmd_mempool);
1286 }
1287
1288 /*
1289 ============
1290 Cmd_Argc
1291 ============
1292 */
1293 int             Cmd_Argc (void)
1294 {
1295         return cmd_argc;
1296 }
1297
1298 /*
1299 ============
1300 Cmd_Argv
1301 ============
1302 */
1303 const char *Cmd_Argv (int arg)
1304 {
1305         if (arg >= cmd_argc )
1306                 return cmd_null_string;
1307         return cmd_argv[arg];
1308 }
1309
1310 /*
1311 ============
1312 Cmd_Args
1313 ============
1314 */
1315 const char *Cmd_Args (void)
1316 {
1317         return cmd_args;
1318 }
1319
1320
1321 /*
1322 ============
1323 Cmd_TokenizeString
1324
1325 Parses the given string into command line tokens.
1326 ============
1327 */
1328 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1329 static void Cmd_TokenizeString (const char *text)
1330 {
1331         int l;
1332
1333         cmd_argc = 0;
1334         cmd_args = NULL;
1335
1336         while (1)
1337         {
1338                 // skip whitespace up to a /n
1339                 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1340                         text++;
1341
1342                 // line endings:
1343                 // UNIX: \n
1344                 // Mac: \r
1345                 // Windows: \r\n
1346                 if (*text == '\n' || *text == '\r')
1347                 {
1348                         // a newline separates commands in the buffer
1349                         if (*text == '\r' && text[1] == '\n')
1350                                 text++;
1351                         text++;
1352                         break;
1353                 }
1354
1355                 if (!*text)
1356                         return;
1357
1358                 if (cmd_argc == 1)
1359                         cmd_args = text;
1360
1361                 if (!COM_ParseToken_Console(&text))
1362                         return;
1363
1364                 if (cmd_argc < MAX_ARGS)
1365                 {
1366                         l = (int)strlen(com_token) + 1;
1367                         if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1368                         {
1369                                 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
1370                                 break;
1371                         }
1372                         memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
1373                         cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
1374                         cmd_tokenizebufferpos += l;
1375                         cmd_argc++;
1376                 }
1377         }
1378 }
1379
1380
1381 /*
1382 ============
1383 Cmd_AddCommand
1384 ============
1385 */
1386 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
1387 {
1388         cmd_function_t *cmd;
1389         cmd_function_t *prev, *current;
1390
1391 // fail if the command is a variable name
1392         if (Cvar_FindVar( cmd_name ))
1393         {
1394                 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1395                 return;
1396         }
1397
1398 // fail if the command already exists
1399         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1400         {
1401                 if (!strcmp (cmd_name, cmd->name))
1402                 {
1403                         if (consolefunction || clientfunction)
1404                         {
1405                                 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1406                                 return;
1407                         }
1408                         else    //[515]: csqc
1409                         {
1410                                 cmd->csqcfunc = true;
1411                                 return;
1412                         }
1413                 }
1414         }
1415
1416         cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
1417         cmd->name = cmd_name;
1418         cmd->consolefunction = consolefunction;
1419         cmd->clientfunction = clientfunction;
1420         cmd->description = description;
1421         if(!consolefunction && !clientfunction)                 //[515]: csqc
1422                 cmd->csqcfunc = true;
1423         cmd->next = cmd_functions;
1424
1425 // insert it at the right alphanumeric position
1426         for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
1427                 ;
1428         if( prev ) {
1429                 prev->next = cmd;
1430         } else {
1431                 cmd_functions = cmd;
1432         }
1433         cmd->next = current;
1434 }
1435
1436 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
1437 {
1438         Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
1439 }
1440
1441 /*
1442 ============
1443 Cmd_Exists
1444 ============
1445 */
1446 qboolean Cmd_Exists (const char *cmd_name)
1447 {
1448         cmd_function_t  *cmd;
1449
1450         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1451                 if (!strcmp (cmd_name,cmd->name))
1452                         return true;
1453
1454         return false;
1455 }
1456
1457
1458 /*
1459 ============
1460 Cmd_CompleteCommand
1461 ============
1462 */
1463 const char *Cmd_CompleteCommand (const char *partial)
1464 {
1465         cmd_function_t *cmd;
1466         size_t len;
1467
1468         len = strlen(partial);
1469
1470         if (!len)
1471                 return NULL;
1472
1473 // check functions
1474         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1475                 if (!strncasecmp(partial, cmd->name, len))
1476                         return cmd->name;
1477
1478         return NULL;
1479 }
1480
1481 /*
1482         Cmd_CompleteCountPossible
1483
1484         New function for tab-completion system
1485         Added by EvilTypeGuy
1486         Thanks to Fett erich@heintz.com
1487         Thanks to taniwha
1488
1489 */
1490 int Cmd_CompleteCountPossible (const char *partial)
1491 {
1492         cmd_function_t *cmd;
1493         size_t len;
1494         int h;
1495
1496         h = 0;
1497         len = strlen(partial);
1498
1499         if (!len)
1500                 return 0;
1501
1502         // Loop through the command list and count all partial matches
1503         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1504                 if (!strncasecmp(partial, cmd->name, len))
1505                         h++;
1506
1507         return h;
1508 }
1509
1510 /*
1511         Cmd_CompleteBuildList
1512
1513         New function for tab-completion system
1514         Added by EvilTypeGuy
1515         Thanks to Fett erich@heintz.com
1516         Thanks to taniwha
1517
1518 */
1519 const char **Cmd_CompleteBuildList (const char *partial)
1520 {
1521         cmd_function_t *cmd;
1522         size_t len = 0;
1523         size_t bpos = 0;
1524         size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
1525         const char **buf;
1526
1527         len = strlen(partial);
1528         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1529         // Loop through the alias list and print all matches
1530         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1531                 if (!strncasecmp(partial, cmd->name, len))
1532                         buf[bpos++] = cmd->name;
1533
1534         buf[bpos] = NULL;
1535         return buf;
1536 }
1537
1538 // written by LordHavoc
1539 void Cmd_CompleteCommandPrint (const char *partial)
1540 {
1541         cmd_function_t *cmd;
1542         size_t len = strlen(partial);
1543         // Loop through the command list and print all matches
1544         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1545                 if (!strncasecmp(partial, cmd->name, len))
1546                         Con_Printf("^2%s^7: %s\n", cmd->name, cmd->description);
1547 }
1548
1549 /*
1550         Cmd_CompleteAlias
1551
1552         New function for tab-completion system
1553         Added by EvilTypeGuy
1554         Thanks to Fett erich@heintz.com
1555         Thanks to taniwha
1556
1557 */
1558 const char *Cmd_CompleteAlias (const char *partial)
1559 {
1560         cmdalias_t *alias;
1561         size_t len;
1562
1563         len = strlen(partial);
1564
1565         if (!len)
1566                 return NULL;
1567
1568         // Check functions
1569         for (alias = cmd_alias; alias; alias = alias->next)
1570                 if (!strncasecmp(partial, alias->name, len))
1571                         return alias->name;
1572
1573         return NULL;
1574 }
1575
1576 // written by LordHavoc
1577 void Cmd_CompleteAliasPrint (const char *partial)
1578 {
1579         cmdalias_t *alias;
1580         size_t len = strlen(partial);
1581         // Loop through the alias list and print all matches
1582         for (alias = cmd_alias; alias; alias = alias->next)
1583                 if (!strncasecmp(partial, alias->name, len))
1584                         Con_Printf("^5%s^7: %s", alias->name, alias->value);
1585 }
1586
1587
1588 /*
1589         Cmd_CompleteAliasCountPossible
1590
1591         New function for tab-completion system
1592         Added by EvilTypeGuy
1593         Thanks to Fett erich@heintz.com
1594         Thanks to taniwha
1595
1596 */
1597 int Cmd_CompleteAliasCountPossible (const char *partial)
1598 {
1599         cmdalias_t      *alias;
1600         size_t          len;
1601         int                     h;
1602
1603         h = 0;
1604
1605         len = strlen(partial);
1606
1607         if (!len)
1608                 return 0;
1609
1610         // Loop through the command list and count all partial matches
1611         for (alias = cmd_alias; alias; alias = alias->next)
1612                 if (!strncasecmp(partial, alias->name, len))
1613                         h++;
1614
1615         return h;
1616 }
1617
1618 /*
1619         Cmd_CompleteAliasBuildList
1620
1621         New function for tab-completion system
1622         Added by EvilTypeGuy
1623         Thanks to Fett erich@heintz.com
1624         Thanks to taniwha
1625
1626 */
1627 const char **Cmd_CompleteAliasBuildList (const char *partial)
1628 {
1629         cmdalias_t *alias;
1630         size_t len = 0;
1631         size_t bpos = 0;
1632         size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
1633         const char **buf;
1634
1635         len = strlen(partial);
1636         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1637         // Loop through the alias list and print all matches
1638         for (alias = cmd_alias; alias; alias = alias->next)
1639                 if (!strncasecmp(partial, alias->name, len))
1640                         buf[bpos++] = alias->name;
1641
1642         buf[bpos] = NULL;
1643         return buf;
1644 }
1645
1646 void Cmd_ClearCsqcFuncs (void)
1647 {
1648         cmd_function_t *cmd;
1649         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1650                 cmd->csqcfunc = false;
1651 }
1652
1653 /*
1654 ============
1655 Cmd_ExecuteString
1656
1657 A complete command line has been parsed, so try to execute it
1658 FIXME: lookupnoadd the token to speed search?
1659 ============
1660 */
1661 void Cmd_ExecuteString (const char *text, cmd_source_t src, qboolean lockmutex)
1662 {
1663         int oldpos;
1664         int found;
1665         cmd_function_t *cmd;
1666         cmdalias_t *a;
1667
1668         oldpos = cmd_tokenizebufferpos;
1669         cmd_source = src;
1670         found = false;
1671
1672         Cmd_TokenizeString (text);
1673
1674 // execute the command line
1675         if (!Cmd_Argc())
1676                 goto done; // no tokens
1677
1678 // check functions
1679         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1680         {
1681                 if (!strcasecmp (cmd_argv[0],cmd->name))
1682                 {
1683                         if (cmd->csqcfunc && CL_VM_ConsoleCommand (text))       //[515]: csqc
1684                                 goto done;
1685                         switch (src)
1686                         {
1687                         case src_command:
1688                                 if (cmd->consolefunction)
1689                                         cmd->consolefunction ();
1690                                 else if (cmd->clientfunction)
1691                                 {
1692                                         if (cls.state == ca_connected)
1693                                         {
1694                                                 // forward remote commands to the server for execution
1695                                                 Cmd_ForwardToServer();
1696                                         }
1697                                         else
1698                                                 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
1699                                 }
1700                                 else
1701                                         Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
1702                                 found = true;
1703                                 goto command_found;
1704                         case src_client:
1705                                 if (cmd->clientfunction)
1706                                 {
1707                                         cmd->clientfunction ();
1708                                         goto done;
1709                                 }
1710                                 break;
1711                         }
1712                         break;
1713                 }
1714         }
1715 command_found:
1716
1717         // if it's a client command and no command was found, say so.
1718         if (cmd_source == src_client)
1719         {
1720                 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
1721                 goto done;
1722         }
1723
1724 // check alias
1725         for (a=cmd_alias ; a ; a=a->next)
1726         {
1727                 if (!strcasecmp (cmd_argv[0], a->name))
1728                 {
1729                         Cmd_ExecuteAlias(a);
1730                         goto done;
1731                 }
1732         }
1733
1734         if(found) // if the command was hooked and found, all is good
1735                 goto done;
1736
1737 // check cvars
1738         if (!Cvar_Command () && host_framecount > 0)
1739                 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
1740
1741 done:
1742         cmd_tokenizebufferpos = oldpos;
1743 }
1744
1745
1746 /*
1747 ===================
1748 Cmd_ForwardStringToServer
1749
1750 Sends an entire command string over to the server, unprocessed
1751 ===================
1752 */
1753 void Cmd_ForwardStringToServer (const char *s)
1754 {
1755         char temp[128];
1756         if (cls.state != ca_connected)
1757         {
1758                 Con_Printf("Can't \"%s\", not connected\n", s);
1759                 return;
1760         }
1761
1762         if (!cls.netcon)
1763                 return;
1764
1765         // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
1766         // attention, it has been eradicated from here, its only (former) use in
1767         // all of darkplaces.
1768         if (cls.protocol == PROTOCOL_QUAKEWORLD)
1769                 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
1770         else
1771                 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
1772         if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
1773         {
1774                 // say/say_team commands can replace % character codes with status info
1775                 while (*s)
1776                 {
1777                         if (*s == '%' && s[1])
1778                         {
1779                                 // handle proquake message macros
1780                                 temp[0] = 0;
1781                                 switch (s[1])
1782                                 {
1783                                 case 'l': // current location
1784                                         CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
1785                                         break;
1786                                 case 'h': // current health
1787                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
1788                                         break;
1789                                 case 'a': // current armor
1790                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
1791                                         break;
1792                                 case 'x': // current rockets
1793                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
1794                                         break;
1795                                 case 'c': // current cells
1796                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
1797                                         break;
1798                                 // silly proquake macros
1799                                 case 'd': // loc at last death
1800                                         CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
1801                                         break;
1802                                 case 't': // current time
1803                                         dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
1804                                         break;
1805                                 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
1806                                         if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
1807                                                 dpsnprintf(temp, sizeof(temp), "I need RL");
1808                                         else if (!cl.stats[STAT_ROCKETS])
1809                                                 dpsnprintf(temp, sizeof(temp), "I need rockets");
1810                                         else
1811                                                 dpsnprintf(temp, sizeof(temp), "I have RL");
1812                                         break;
1813                                 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
1814                                         if (cl.stats[STAT_ITEMS] & IT_QUAD)
1815                                         {
1816                                                 if (temp[0])
1817                                                         strlcat(temp, " ", sizeof(temp));
1818                                                 strlcat(temp, "quad", sizeof(temp));
1819                                         }
1820                                         if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
1821                                         {
1822                                                 if (temp[0])
1823                                                         strlcat(temp, " ", sizeof(temp));
1824                                                 strlcat(temp, "pent", sizeof(temp));
1825                                         }
1826                                         if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1827                                         {
1828                                                 if (temp[0])
1829                                                         strlcat(temp, " ", sizeof(temp));
1830                                                 strlcat(temp, "eyes", sizeof(temp));
1831                                         }
1832                                         break;
1833                                 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
1834                                         if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
1835                                                 strlcat(temp, "SSG", sizeof(temp));
1836                                         strlcat(temp, ":", sizeof(temp));
1837                                         if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
1838                                                 strlcat(temp, "NG", sizeof(temp));
1839                                         strlcat(temp, ":", sizeof(temp));
1840                                         if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
1841                                                 strlcat(temp, "SNG", sizeof(temp));
1842                                         strlcat(temp, ":", sizeof(temp));
1843                                         if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
1844                                                 strlcat(temp, "GL", sizeof(temp));
1845                                         strlcat(temp, ":", sizeof(temp));
1846                                         if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
1847                                                 strlcat(temp, "RL", sizeof(temp));
1848                                         strlcat(temp, ":", sizeof(temp));
1849                                         if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
1850                                                 strlcat(temp, "LG", sizeof(temp));
1851                                         break;
1852                                 default:
1853                                         // not a recognized macro, print it as-is...
1854                                         temp[0] = s[0];
1855                                         temp[1] = s[1];
1856                                         temp[2] = 0;
1857                                         break;
1858                                 }
1859                                 // write the resulting text
1860                                 SZ_Write(&cls.netcon->message, (unsigned char *)temp, strlen(temp));
1861                                 s += 2;
1862                                 continue;
1863                         }
1864                         MSG_WriteByte(&cls.netcon->message, *s);
1865                         s++;
1866                 }
1867                 MSG_WriteByte(&cls.netcon->message, 0);
1868         }
1869         else // any other command is passed on as-is
1870                 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
1871 }
1872
1873 /*
1874 ===================
1875 Cmd_ForwardToServer
1876
1877 Sends the entire command line over to the server
1878 ===================
1879 */
1880 void Cmd_ForwardToServer (void)
1881 {
1882         const char *s;
1883         char vabuf[1024];
1884         if (!strcasecmp(Cmd_Argv(0), "cmd"))
1885         {
1886                 // we want to strip off "cmd", so just send the args
1887                 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1888         }
1889         else
1890         {
1891                 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
1892                 s = va(vabuf, sizeof(vabuf), "%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
1893         }
1894         // don't send an empty forward message if the user tries "cmd" by itself
1895         if (!s || !*s)
1896                 return;
1897         Cmd_ForwardStringToServer(s);
1898 }
1899
1900
1901 /*
1902 ================
1903 Cmd_CheckParm
1904
1905 Returns the position (1 to argc-1) in the command's argument list
1906 where the given parameter apears, or 0 if not present
1907 ================
1908 */
1909
1910 int Cmd_CheckParm (const char *parm)
1911 {
1912         int i;
1913
1914         if (!parm)
1915         {
1916                 Con_Printf ("Cmd_CheckParm: NULL");
1917                 return 0;
1918         }
1919
1920         for (i = 1; i < Cmd_Argc (); i++)
1921                 if (!strcasecmp (parm, Cmd_Argv (i)))
1922                         return i;
1923
1924         return 0;
1925 }
1926
1927
1928
1929 void Cmd_SaveInitState(void)
1930 {
1931         cmd_function_t *f;
1932         cmdalias_t *a;
1933         for (f = cmd_functions;f;f = f->next)
1934                 f->initstate = true;
1935         for (a = cmd_alias;a;a = a->next)
1936         {
1937                 a->initstate = true;
1938                 a->initialvalue = Mem_strdup(zonemempool, a->value);
1939         }
1940         Cvar_SaveInitState();
1941 }
1942
1943 void Cmd_RestoreInitState(void)
1944 {
1945         cmd_function_t *f, **fp;
1946         cmdalias_t *a, **ap;
1947         for (fp = &cmd_functions;(f = *fp);)
1948         {
1949                 if (f->initstate)
1950                         fp = &f->next;
1951                 else
1952                 {
1953                         // destroy this command, it didn't exist at init
1954                         Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
1955                         *fp = f->next;
1956                         Z_Free(f);
1957                 }
1958         }
1959         for (ap = &cmd_alias;(a = *ap);)
1960         {
1961                 if (a->initstate)
1962                 {
1963                         // restore this alias, it existed at init
1964                         if (strcmp(a->value ? a->value : "", a->initialvalue ? a->initialvalue : ""))
1965                         {
1966                                 Con_DPrintf("Cmd_RestoreInitState: Restoring alias %s\n", a->name);
1967                                 if (a->value)
1968                                         Z_Free(a->value);
1969                                 a->value = Mem_strdup(zonemempool, a->initialvalue);
1970                         }
1971                         ap = &a->next;
1972                 }
1973                 else
1974                 {
1975                         // free this alias, it didn't exist at init...
1976                         Con_DPrintf("Cmd_RestoreInitState: Destroying alias %s\n", a->name);
1977                         *ap = a->next;
1978                         if (a->value)
1979                                 Z_Free(a->value);
1980                         Z_Free(a);
1981                 }
1982         }
1983         Cvar_RestoreInitState();
1984 }