2 Copyright (C) 1996-1997 Id Software, Inc.
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.
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.
13 See the GNU General Public License for more details.
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.
20 // cmd.c -- Quake script command processing module
25 typedef struct cmdalias_s
27 struct cmdalias_s *next;
28 char name[MAX_ALIAS_NAME];
30 qboolean initstate; // indicates this command existed at init
31 char *initialvalue; // backup copy of value at init
34 static cmdalias_t *cmd_alias;
36 static qboolean cmd_wait;
38 static mempool_t *cmd_mempool;
40 static char cmd_tokenizebuffer[CMD_TOKENIZELENGTH];
41 static int cmd_tokenizebufferpos = 0;
43 //=============================================================================
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"
54 static void Cmd_Wait_f (void)
59 typedef struct cmddeferred_s
61 struct cmddeferred_s *next;
66 static cmddeferred_t *cmd_deferred_list = NULL;
72 Cause a command to be executed after a delay.
75 static void Cmd_Defer_f (void)
79 double time = Sys_DoubleTime();
80 cmddeferred_t *next = cmd_deferred_list;
82 Con_Printf("No commands are pending.\n");
85 Con_Printf("-> In %9.2f: %s\n", next->time-time, next->value);
88 } else if(Cmd_Argc() == 2 && !strcasecmp("clear", Cmd_Argv(1)))
90 while(cmd_deferred_list)
92 cmddeferred_t *cmd = cmd_deferred_list;
93 cmd_deferred_list = cmd->next;
97 } else if(Cmd_Argc() == 3)
99 const char *value = Cmd_Argv(2);
100 cmddeferred_t *defcmd = (cmddeferred_t*)Mem_Alloc(tempmempool, sizeof(*defcmd));
101 size_t len = strlen(value);
103 defcmd->time = Sys_DoubleTime() + atof(Cmd_Argv(1));
104 defcmd->value = (char*)Mem_Alloc(tempmempool, len+1);
105 memcpy(defcmd->value, value, len+1);
108 if(cmd_deferred_list)
110 cmddeferred_t *next = cmd_deferred_list;
115 cmd_deferred_list = defcmd;
116 /* Stupid me... this changes the order... so commands with the same delay go blub :S
117 defcmd->next = cmd_deferred_list;
118 cmd_deferred_list = defcmd;*/
120 Con_Printf("usage: defer <seconds> <command>\n"
130 Print something to the center of the screen using SCR_Centerprint
133 static void Cmd_Centerprint_f (void)
135 char msg[MAX_INPUTLINE];
136 unsigned int i, c, p;
140 strlcpy(msg, Cmd_Argv(1), sizeof(msg));
141 for(i = 2; i < c; ++i)
143 strlcat(msg, " ", sizeof(msg));
144 strlcat(msg, Cmd_Argv(i), sizeof(msg));
147 for(p = 0, i = 0; i < c; ++i)
153 else if(msg[i+1] == '\\')
165 SCR_CenterPrint(msg);
170 =============================================================================
174 =============================================================================
177 static sizebuf_t cmd_text;
178 static unsigned char cmd_text_buf[CMDBUFSIZE];
179 void *cmd_text_mutex = NULL;
181 static void Cbuf_LockThreadMutex(void)
184 Thread_LockMutex(cmd_text_mutex);
187 static void Cbuf_UnlockThreadMutex(void)
190 Thread_UnlockMutex(cmd_text_mutex);
197 Adds command text at the end of the buffer
200 void Cbuf_AddText (const char *text)
204 l = (int)strlen(text);
206 Cbuf_LockThreadMutex();
207 if (cmd_text.cursize + l >= cmd_text.maxsize)
208 Con_Print("Cbuf_AddText: overflow\n");
210 SZ_Write(&cmd_text, (const unsigned char *)text, (int)strlen (text));
211 Cbuf_UnlockThreadMutex();
219 Adds command text immediately after the current command
220 Adds a \n to the text
221 FIXME: actually change the command buffer to do less copying
224 void Cbuf_InsertText (const char *text)
229 Cbuf_LockThreadMutex();
231 // copy off any commands still remaining in the exec buffer
232 templen = cmd_text.cursize;
235 temp = (char *)Mem_Alloc (tempmempool, templen);
236 memcpy (temp, cmd_text.data, templen);
237 SZ_Clear (&cmd_text);
242 // add the entire text of the file
245 // add the copied off data
248 SZ_Write (&cmd_text, (const unsigned char *)temp, templen);
252 Cbuf_UnlockThreadMutex();
257 Cbuf_Execute_Deferred --blub
260 void Cbuf_Execute_Deferred (void)
262 cmddeferred_t *cmd, *prev;
263 double time = Sys_DoubleTime();
265 cmd = cmd_deferred_list;
268 if(cmd->time <= time)
270 Cbuf_AddText(cmd->value);
272 Mem_Free(cmd->value);
275 prev->next = cmd->next;
279 cmd_deferred_list = cmd->next;
281 cmd = cmd_deferred_list;
295 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias );
296 void Cbuf_Execute (void)
300 char line[MAX_INPUTLINE];
301 char preprocessed[MAX_INPUTLINE];
306 Cbuf_LockThreadMutex();
307 SV_LockThreadMutex();
309 // LordHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
310 cmd_tokenizebufferpos = 0;
312 Cbuf_Execute_Deferred();
313 while (cmd_text.cursize)
315 // find a \n or ; line break
316 text = (char *)cmd_text.data;
320 for (i=0 ; i < cmd_text.cursize ; i++)
329 // make sure i doesn't get > cursize which causes a negative
330 // size in memmove, which is fatal --blub
331 if (i < (cmd_text.cursize-1) && (text[i] == '\\' && (text[i+1] == '"' || text[i+1] == '\\')))
336 if(text[i] == '/' && text[i + 1] == '/' && (i == 0 || ISWHITESPACE(text[i-1])))
339 break; // don't break if inside a quoted string or comment
343 if (text[i] == '\r' || text[i] == '\n')
347 // better than CRASHING on overlong input lines that may SOMEHOW enter the buffer
348 if(i >= MAX_INPUTLINE)
350 Con_Printf("Warning: console input buffer had an overlong line. Ignored.\n");
355 memcpy (line, text, comment ? (comment - text) : i);
356 line[comment ? (comment - text) : i] = 0;
359 // delete the text from the command buffer and move remaining commands down
360 // this is necessary because commands (exec, alias) can insert data at the
361 // beginning of the text buffer
363 if (i == cmd_text.cursize)
364 cmd_text.cursize = 0;
368 cmd_text.cursize -= i;
369 memmove (cmd_text.data, text+i, cmd_text.cursize);
372 // execute the command line
374 while(*firstchar && ISWHITESPACE(*firstchar))
377 (strncmp(firstchar, "alias", 5) || !ISWHITESPACE(firstchar[5]))
379 (strncmp(firstchar, "bind", 4) || !ISWHITESPACE(firstchar[4]))
381 (strncmp(firstchar, "in_bind", 7) || !ISWHITESPACE(firstchar[7]))
384 Cmd_PreprocessString( line, preprocessed, sizeof(preprocessed), NULL );
385 Cmd_ExecuteString (preprocessed, src_command, false);
389 Cmd_ExecuteString (line, src_command, false);
393 { // skip out while text still remains in buffer, leaving it
400 SV_UnlockThreadMutex();
401 Cbuf_UnlockThreadMutex();
405 ==============================================================================
409 ==============================================================================
416 Adds command line parameters as script statements
417 Commands lead with a +, and continue until a - or another +
418 quake +prog jctest.qp +cmd amlev1
419 quake -nosound +cmd amlev1
422 qboolean host_stuffcmdsrun = false;
423 void Cmd_StuffCmds_f (void)
426 // this is for all commandline options combined (and is bounds checked)
427 char build[MAX_INPUTLINE];
429 if (Cmd_Argc () != 1)
431 Con_Print("stuffcmds : execute command line parameters\n");
435 // no reason to run the commandline arguments twice
436 if (host_stuffcmdsrun)
439 host_stuffcmdsrun = true;
442 for (i = 0;i < com_argc;i++)
444 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)
447 while (com_argv[i][j])
448 build[l++] = com_argv[i][j++];
450 for (;i < com_argc;i++)
454 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
456 if (l + strlen(com_argv[i]) + 4 > sizeof(build) - 1)
459 if (strchr(com_argv[i], ' '))
461 for (j = 0;com_argv[i][j];j++)
462 build[l++] = com_argv[i][j];
463 if (strchr(com_argv[i], ' '))
470 // now terminate the combined string and prepend it to the command buffer
471 // we already reserved space for the terminator
473 Cbuf_InsertText (build);
476 static void Cmd_Exec(const char *filename)
479 qboolean isdefaultcfg = strlen(filename) >= 11 && !strcmp(filename + strlen(filename) - 11, "default.cfg");
481 if (!strcmp(filename, "config.cfg"))
483 filename = CONFIGFILENAME;
484 if (COM_CheckParm("-noconfig"))
485 return; // don't execute config.cfg
488 f = (char *)FS_LoadFile (filename, tempmempool, false, NULL);
491 Con_Printf("couldn't exec %s\n",filename);
494 Con_Printf("execing %s\n",filename);
496 // if executing default.cfg for the first time, lock the cvar defaults
497 // it may seem backwards to insert this text BEFORE the default.cfg
498 // but Cbuf_InsertText inserts before, so this actually ends up after it.
500 Cbuf_InsertText("\ncvar_lockdefaults\n");
502 // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
503 // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
504 Cbuf_InsertText ("\n");
510 // special defaults for specific games go here, these execute before default.cfg
511 // Nehahra pushable crates malfunction in some levels if this is on
512 // Nehahra NPC AI is confused by blowupfallenzombies
513 if (gamemode == GAME_NEHAHRA)
514 Cbuf_InsertText("\nsv_gameplayfix_upwardvelocityclearsongroundflag 0\nsv_gameplayfix_blowupfallenzombies 0\n\n");
515 // 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.
516 // 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
517 // hipnotic mission pack has issues in their proximity mine sticking code, which causes them to bounce off.
518 if (gamemode == GAME_HIPNOTIC)
519 Cbuf_InsertText("\nsv_gameplayfix_blowupfallenzombies 0\nsys_ticrate 0.02\nsv_gameplayfix_slidemoveprojectiles 0\n\n");
520 // rogue mission pack has a guardian boss that does not wake up if findradius returns one of the entities around its spawn area
521 if (gamemode == GAME_ROGUE)
522 Cbuf_InsertText("\nsv_gameplayfix_findradiusdistancetobox 0\n\n");
523 if (gamemode == GAME_NEXUIZ)
524 Cbuf_InsertText("\nsv_gameplayfix_q2airaccelerate 1\nsv_gameplayfix_stepmultipletimes 1\n\n");
525 if (gamemode == GAME_TENEBRAE)
526 Cbuf_InsertText("\nr_shadow_gloss 2\nr_shadow_bumpscale_basetexture 4\n\n");
527 // Steel Storm: Burning Retribution csqc misinterprets CSQC_InputEvent if type is a value other than 0 or 1
528 if (gamemode == GAME_STEELSTORM)
529 Cbuf_InsertText("\ncl_csqc_generatemousemoveevents 0\n\n");
538 static void Cmd_Exec_f (void)
543 if (Cmd_Argc () != 2)
545 Con_Print("exec <filename> : execute a script file\n");
549 s = FS_Search(Cmd_Argv(1), true, true);
550 if(!s || !s->numfilenames)
552 Con_Printf("couldn't exec %s\n",Cmd_Argv(1));
556 for(i = 0; i < s->numfilenames; ++i)
557 Cmd_Exec(s->filenames[i]);
567 Just prints the rest of the line to the console
570 static void Cmd_Echo_f (void)
574 for (i=1 ; i<Cmd_Argc() ; i++)
575 Con_Printf("%s ",Cmd_Argv(i));
580 // Support Doom3-style Toggle Console Command
585 Toggles a specified console variable amongst the values specified (default is 0 and 1)
588 static void Cmd_Toggle_f(void)
590 // Acquire Number of Arguments
591 int nNumArgs = Cmd_Argc();
594 // No Arguments Specified; Print Usage
595 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");
597 { // Correct Arguments Specified
598 // Acquire Potential CVar
599 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
606 Cvar_SetValueQuick(cvCVar, 0);
608 Cvar_SetValueQuick(cvCVar, 1);
612 { // 0 and Specified Usage
613 if(cvCVar->integer == atoi(Cmd_Argv(2) ) )
614 // CVar is Specified Value; // Reset to 0
615 Cvar_SetValueQuick(cvCVar, 0);
617 if(cvCVar->integer == 0)
618 // CVar is 0; Specify Value
619 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
621 // CVar does not match; Reset to 0
622 Cvar_SetValueQuick(cvCVar, 0);
625 { // Variable Values Specified
629 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
630 { // Cycle through Values
631 if( strcmp(cvCVar->string, Cmd_Argv(nCnt) ) == 0)
632 { // Current Value Located; Increment to Next
633 if( (nCnt + 1) == nNumArgs)
634 // Max Value Reached; Reset
635 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
638 Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
647 // Value not Found; Reset to Original
648 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
654 Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(1) );
663 Creates a new command that executes a command string (possibly ; seperated)
666 static void Cmd_Alias_f (void)
669 char cmd[MAX_INPUTLINE];
676 Con_Print("Current alias commands:\n");
677 for (a = cmd_alias ; a ; a=a->next)
678 Con_Printf("%s : %s", a->name, a->value);
683 if (strlen(s) >= MAX_ALIAS_NAME)
685 Con_Print("Alias name is too long\n");
689 // if the alias already exists, reuse it
690 for (a = cmd_alias ; a ; a=a->next)
692 if (!strcmp(s, a->name))
701 cmdalias_t *prev, *current;
703 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
704 strlcpy (a->name, s, sizeof (a->name));
705 // insert it at the right alphanumeric position
706 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
717 // copy the rest of the command line
718 cmd[0] = 0; // start out with a null string
720 for (i=2 ; i < c ; i++)
723 strlcat (cmd, " ", sizeof (cmd));
724 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
726 strlcat (cmd, "\n", sizeof (cmd));
728 alloclen = strlen (cmd) + 1;
730 cmd[alloclen - 2] = '\n'; // to make sure a newline is appended even if too long
731 a->value = (char *)Z_Malloc (alloclen);
732 memcpy (a->value, cmd, alloclen);
739 Remove existing aliases.
742 static void Cmd_UnAlias_f (void)
750 Con_Print("unalias: Usage: unalias alias1 [alias2 ...]\n");
754 for(i = 1; i < Cmd_Argc(); ++i)
758 for(a = cmd_alias; a; p = a, a = a->next)
760 if(!strcmp(s, a->name))
762 if (a->initstate) // we can not remove init aliases
774 Con_Printf("unalias: %s alias not found\n", s);
779 =============================================================================
783 =============================================================================
786 typedef struct cmd_function_s
788 struct cmd_function_s *next;
790 const char *description;
791 xcommand_t consolefunction;
792 xcommand_t clientfunction;
794 qboolean initstate; // indicates this command existed at init
798 static const char *cmd_argv[MAX_ARGS];
799 static const char *cmd_null_string = "";
800 static const char *cmd_args;
801 cmd_source_t cmd_source;
804 static cmd_function_t *cmd_functions; // possible commands to execute
806 static const char *Cmd_GetDirectCvarValue(const char *varname, cmdalias_t *alias, qboolean *is_multiple)
813 *is_multiple = false;
815 if(!varname || !*varname)
820 if(!strcmp(varname, "*"))
826 else if(!strcmp(varname, "#"))
828 return va("%d", Cmd_Argc());
830 else if(varname[strlen(varname) - 1] == '-')
832 argno = strtol(varname, &endptr, 10);
833 if(endptr == varname + strlen(varname) - 1)
835 // whole string is a number, apart from the -
836 const char *p = Cmd_Args();
837 for(; argno > 1; --argno)
838 if(!COM_ParseToken_Console(&p))
845 // kill pre-argument whitespace
846 for (;*p && ISWHITESPACE(*p);p++)
855 argno = strtol(varname, &endptr, 10);
858 // whole string is a number
859 // NOTE: we already made sure we don't have an empty cvar name!
860 if(argno >= 0 && argno < Cmd_Argc())
861 return Cmd_Argv(argno);
866 if((cvar = Cvar_FindVar(varname)) && !(cvar->flags & CVAR_PRIVATE))
872 qboolean Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset, qboolean putquotes)
874 qboolean quote_quot = !!strchr(quoteset, '"');
875 qboolean quote_backslash = !!strchr(quoteset, '\\');
876 qboolean quote_dollar = !!strchr(quoteset, '$');
885 *out++ = '"'; --outlen;
891 if(*in == '"' && quote_quot)
895 *out++ = '\\'; --outlen;
896 *out++ = '"'; --outlen;
898 else if(*in == '\\' && quote_backslash)
902 *out++ = '\\'; --outlen;
903 *out++ = '\\'; --outlen;
905 else if(*in == '$' && quote_dollar)
909 *out++ = '$'; --outlen;
910 *out++ = '$'; --outlen;
916 *out++ = *in; --outlen;
931 static const char *Cmd_GetCvarValue(const char *var, size_t varlen, cmdalias_t *alias)
933 static char varname[MAX_INPUTLINE];
934 static char varval[MAX_INPUTLINE];
937 static char asis[] = "asis"; // just to suppress const char warnings
939 if(varlen >= MAX_INPUTLINE)
940 varlen = MAX_INPUTLINE - 1;
941 memcpy(varname, var, varlen);
943 varfunc = strchr(varname, ' ');
959 if(varname[0] == '$')
960 varstr = Cmd_GetDirectCvarValue(Cmd_GetDirectCvarValue(varname + 1, alias, NULL), alias, NULL);
963 qboolean is_multiple = false;
964 // Exception: $* and $n- don't use the quoted form by default
965 varstr = Cmd_GetDirectCvarValue(varname, alias, &is_multiple);
974 Con_Printf("Warning: Could not expand $%s in alias %s\n", varname, alias->name);
976 Con_Printf("Warning: Could not expand $%s\n", varname);
980 if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
982 // quote it so it can be used inside double quotes
983 // we just need to replace " by \", and of course, double backslashes
984 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\", false);
987 else if(!strcmp(varfunc, "asis"))
992 Con_Printf("Unknown variable function %s\n", varfunc);
1000 Preprocesses strings and replaces $*, $param#, $cvar accordingly. Also strips comments.
1002 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
1008 // don't crash if there's no room in the outtext buffer
1009 if( maxoutlen == 0 ) {
1012 maxoutlen--; // because of \0
1017 while( *in && outlen < maxoutlen ) {
1019 // this is some kind of expansion, see what comes after the $
1022 // The console does the following preprocessing:
1024 // - $$ is transformed to a single dollar sign.
1025 // - $var or ${var} are expanded to the contents of the named cvar,
1026 // with quotation marks and backslashes quoted so it can safely
1027 // be used inside quotation marks (and it should always be used
1029 // - ${var asis} inserts the cvar value as is, without doing this
1031 // - prefix the cvar name with a dollar sign to do indirection;
1032 // for example, if $x has the value timelimit, ${$x} will return
1033 // the value of $timelimit
1034 // - when expanding an alias, the special variable name $* refers
1035 // to all alias parameters, and a number refers to that numbered
1036 // alias parameter, where the name of the alias is $0, the first
1037 // parameter is $1 and so on; as a special case, $* inserts all
1038 // parameters, without extra quoting, so one can use $* to just
1039 // pass all parameters around. All parameters starting from $n
1040 // can be referred to as $n- (so $* is equivalent to $1-).
1042 // Note: when expanding an alias, cvar expansion is done in the SAME step
1043 // as alias expansion so that alias parameters or cvar values containing
1044 // dollar signs have no unwanted bad side effects. However, this needs to
1045 // be accounted for when writing complex aliases. For example,
1046 // alias foo "set x NEW; echo $x"
1047 // actually expands to
1048 // "set x NEW; echo OLD"
1049 // and will print OLD! To work around this, use a second alias:
1050 // alias foo "set x NEW; foo2"
1051 // alias foo2 "echo $x"
1053 // Also note: lines starting with alias are exempt from cvar expansion.
1054 // If you want cvar expansion, write "alias" instead:
1057 // alias foo "echo $x"
1058 // "alias" bar "echo $x"
1061 // foo will print 2, because the variable $x will be expanded when the alias
1062 // gets expanded. bar will print 1, because the variable $x was expanded
1063 // at definition time. foo can be equivalently defined as
1065 // "alias" foo "echo $$x"
1067 // because at definition time, $$ will get replaced to a single $.
1072 } else if(*in == '{') {
1073 varlen = strcspn(in + 1, "}");
1074 if(in[varlen + 1] == '}')
1076 val = Cmd_GetCvarValue(in + 1, varlen, alias);
1086 varlen = strspn(in, "#*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
1087 val = Cmd_GetCvarValue(in, varlen, alias);
1092 // insert the cvar value
1093 while(*val && outlen < maxoutlen)
1094 outtext[outlen++] = *val++;
1099 // copy the unexpanded text
1100 outtext[outlen++] = '$';
1101 while(eat && outlen < maxoutlen)
1103 outtext[outlen++] = *in++;
1109 outtext[outlen++] = *in++;
1111 outtext[outlen] = 0;
1118 Called for aliases and fills in the alias into the cbuffer
1121 static void Cmd_ExecuteAlias (cmdalias_t *alias)
1123 static char buffer[ MAX_INPUTLINE ];
1124 static char buffer2[ MAX_INPUTLINE ];
1125 Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
1126 // insert at start of command buffer, so that aliases execute in order
1127 // (fixes bug introduced by Black on 20050705)
1129 // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1130 // have to make sure that no second variable expansion takes place, otherwise
1131 // alias parameters containing dollar signs can have bad effects.
1132 Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$", false);
1133 Cbuf_InsertText( buffer2 );
1140 CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1141 Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1145 static void Cmd_List_f (void)
1147 cmd_function_t *cmd;
1148 const char *partial;
1155 partial = Cmd_Argv (1);
1156 len = strlen(partial);
1164 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1167 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1169 if (partial && (ispattern ? !matchpattern_with_separator(cmd->name, partial, false, "", false) : strncmp(partial, cmd->name, len)))
1171 Con_Printf("%s : %s\n", cmd->name, cmd->description);
1178 Con_Printf("%i Command%s matching \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1180 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1183 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1186 static void Cmd_Apropos_f(void)
1188 cmd_function_t *cmd;
1191 const char *partial;
1196 partial = Cmd_Args();
1199 Con_Printf("usage: apropos <string>\n");
1203 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1205 partial = va("*%s*", partial);
1208 for (cvar = cvar_vars; cvar; cvar = cvar->next)
1210 if (!matchpattern_with_separator(cvar->name, partial, true, "", false))
1211 if (!matchpattern_with_separator(cvar->description, partial, true, "", false))
1213 Con_Printf ("cvar ^3%s^7 is \"%s\" [\"%s\"] %s\n", cvar->name, cvar->string, cvar->defstring, cvar->description);
1216 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1218 if (!matchpattern_with_separator(cmd->name, partial, true, "", false))
1219 if (!matchpattern_with_separator(cmd->description, partial, true, "", false))
1221 Con_Printf("command ^2%s^7: %s\n", cmd->name, cmd->description);
1224 for (alias = cmd_alias; alias; alias = alias->next)
1226 // procede here a bit differently as an alias value always got a final \n
1227 if (!matchpattern_with_separator(alias->name, partial, true, "", false))
1228 if (!matchpattern_with_separator(alias->value, partial, true, "\n", false)) // when \n is as separator wildcards don't match it
1230 Con_Printf("alias ^5%s^7: %s", alias->name, alias->value); // do not print an extra \n
1233 Con_Printf("%i result%s\n\n", count, (count > 1) ? "s" : "");
1241 void Cmd_Init (void)
1243 cmd_mempool = Mem_AllocPool("commands", 0, NULL);
1244 // space for commands and script files
1245 cmd_text.data = cmd_text_buf;
1246 cmd_text.maxsize = sizeof(cmd_text_buf);
1247 cmd_text.cursize = 0;
1249 if (Thread_HasThreads())
1250 cmd_text_mutex = Thread_CreateMutex();
1253 void Cmd_Init_Commands (void)
1256 // register our commands
1258 Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1259 Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
1260 Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1261 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");
1262 Cmd_AddCommand ("unalias",Cmd_UnAlias_f, "remove an alias");
1263 Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
1264 Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1265 Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
1266 Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1267 Cmd_AddCommand ("unset", Cvar_Del_f, "delete a cvar (does not work for static ones like _cl_name, or read-only ones)");
1268 #ifdef FILLALLCVARSWITHRUBBISH
1269 Cmd_AddCommand ("fillallcvarswithrubbish", Cvar_FillAll_f, "fill all cvars with a specified number of characters to provoke buffer overruns");
1270 #endif /* FILLALLCVARSWITHRUBBISH */
1272 // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1273 // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1274 Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix or matching the specified wildcard pattern");
1275 Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix or matching the specified wildcard pattern");
1276 Cmd_AddCommand ("apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1278 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");
1279 Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1280 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)");
1281 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)");
1283 Cmd_AddCommand ("cprint", Cmd_Centerprint_f, "print something at the screen center");
1284 Cmd_AddCommand ("defer", Cmd_Defer_f, "execute a command in the future");
1287 // Support Doom3-style Toggle Command
1288 Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1296 void Cmd_Shutdown(void)
1299 Thread_DestroyMutex(cmd_text_mutex);
1300 cmd_text_mutex = NULL;
1302 Mem_FreePool(&cmd_mempool);
1320 const char *Cmd_Argv (int arg)
1322 if (arg >= cmd_argc )
1323 return cmd_null_string;
1324 return cmd_argv[arg];
1332 const char *Cmd_Args (void)
1342 Parses the given string into command line tokens.
1345 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1346 static void Cmd_TokenizeString (const char *text)
1355 // skip whitespace up to a /n
1356 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1363 if (*text == '\n' || *text == '\r')
1365 // a newline separates commands in the buffer
1366 if (*text == '\r' && text[1] == '\n')
1378 if (!COM_ParseToken_Console(&text))
1381 if (cmd_argc < MAX_ARGS)
1383 l = (int)strlen(com_token) + 1;
1384 if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1386 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
1389 memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
1390 cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
1391 cmd_tokenizebufferpos += l;
1403 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
1405 cmd_function_t *cmd;
1406 cmd_function_t *prev, *current;
1408 // fail if the command is a variable name
1409 if (Cvar_FindVar( cmd_name ))
1411 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1415 // fail if the command already exists
1416 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1418 if (!strcmp (cmd_name, cmd->name))
1420 if (consolefunction || clientfunction)
1422 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1427 cmd->csqcfunc = true;
1433 cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
1434 cmd->name = cmd_name;
1435 cmd->consolefunction = consolefunction;
1436 cmd->clientfunction = clientfunction;
1437 cmd->description = description;
1438 if(!consolefunction && !clientfunction) //[515]: csqc
1439 cmd->csqcfunc = true;
1440 cmd->next = cmd_functions;
1442 // insert it at the right alphanumeric position
1443 for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
1448 cmd_functions = cmd;
1450 cmd->next = current;
1453 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
1455 Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
1463 qboolean Cmd_Exists (const char *cmd_name)
1465 cmd_function_t *cmd;
1467 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1468 if (!strcmp (cmd_name,cmd->name))
1480 const char *Cmd_CompleteCommand (const char *partial)
1482 cmd_function_t *cmd;
1485 len = strlen(partial);
1491 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1492 if (!strncasecmp(partial, cmd->name, len))
1499 Cmd_CompleteCountPossible
1501 New function for tab-completion system
1502 Added by EvilTypeGuy
1503 Thanks to Fett erich@heintz.com
1507 int Cmd_CompleteCountPossible (const char *partial)
1509 cmd_function_t *cmd;
1514 len = strlen(partial);
1519 // Loop through the command list and count all partial matches
1520 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1521 if (!strncasecmp(partial, cmd->name, len))
1528 Cmd_CompleteBuildList
1530 New function for tab-completion system
1531 Added by EvilTypeGuy
1532 Thanks to Fett erich@heintz.com
1536 const char **Cmd_CompleteBuildList (const char *partial)
1538 cmd_function_t *cmd;
1541 size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
1544 len = strlen(partial);
1545 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1546 // Loop through the alias list and print all matches
1547 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1548 if (!strncasecmp(partial, cmd->name, len))
1549 buf[bpos++] = cmd->name;
1555 // written by LordHavoc
1556 void Cmd_CompleteCommandPrint (const char *partial)
1558 cmd_function_t *cmd;
1559 size_t len = strlen(partial);
1560 // Loop through the command list and print all matches
1561 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1562 if (!strncasecmp(partial, cmd->name, len))
1563 Con_Printf("^2%s^7: %s\n", cmd->name, cmd->description);
1569 New function for tab-completion system
1570 Added by EvilTypeGuy
1571 Thanks to Fett erich@heintz.com
1575 const char *Cmd_CompleteAlias (const char *partial)
1580 len = strlen(partial);
1586 for (alias = cmd_alias; alias; alias = alias->next)
1587 if (!strncasecmp(partial, alias->name, len))
1593 // written by LordHavoc
1594 void Cmd_CompleteAliasPrint (const char *partial)
1597 size_t len = strlen(partial);
1598 // Loop through the alias list and print all matches
1599 for (alias = cmd_alias; alias; alias = alias->next)
1600 if (!strncasecmp(partial, alias->name, len))
1601 Con_Printf("^5%s^7: %s", alias->name, alias->value);
1606 Cmd_CompleteAliasCountPossible
1608 New function for tab-completion system
1609 Added by EvilTypeGuy
1610 Thanks to Fett erich@heintz.com
1614 int Cmd_CompleteAliasCountPossible (const char *partial)
1622 len = strlen(partial);
1627 // Loop through the command list and count all partial matches
1628 for (alias = cmd_alias; alias; alias = alias->next)
1629 if (!strncasecmp(partial, alias->name, len))
1636 Cmd_CompleteAliasBuildList
1638 New function for tab-completion system
1639 Added by EvilTypeGuy
1640 Thanks to Fett erich@heintz.com
1644 const char **Cmd_CompleteAliasBuildList (const char *partial)
1649 size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
1652 len = strlen(partial);
1653 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1654 // Loop through the alias list and print all matches
1655 for (alias = cmd_alias; alias; alias = alias->next)
1656 if (!strncasecmp(partial, alias->name, len))
1657 buf[bpos++] = alias->name;
1663 void Cmd_ClearCsqcFuncs (void)
1665 cmd_function_t *cmd;
1666 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1667 cmd->csqcfunc = false;
1670 qboolean CL_VM_ConsoleCommand (const char *cmd);
1675 A complete command line has been parsed, so try to execute it
1676 FIXME: lookupnoadd the token to speed search?
1679 void Cmd_ExecuteString (const char *text, cmd_source_t src, qboolean lockmutex)
1683 cmd_function_t *cmd;
1687 Cbuf_LockThreadMutex();
1688 oldpos = cmd_tokenizebufferpos;
1692 Cmd_TokenizeString (text);
1694 // execute the command line
1696 goto done; // no tokens
1699 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1701 if (!strcasecmp (cmd_argv[0],cmd->name))
1703 if (cmd->csqcfunc && CL_VM_ConsoleCommand (text)) //[515]: csqc
1708 if (cmd->consolefunction)
1709 cmd->consolefunction ();
1710 else if (cmd->clientfunction)
1712 if (cls.state == ca_connected)
1714 // forward remote commands to the server for execution
1715 Cmd_ForwardToServer();
1718 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
1721 Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
1725 if (cmd->clientfunction)
1727 cmd->clientfunction ();
1737 // if it's a client command and no command was found, say so.
1738 if (cmd_source == src_client)
1740 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
1745 for (a=cmd_alias ; a ; a=a->next)
1747 if (!strcasecmp (cmd_argv[0], a->name))
1749 Cmd_ExecuteAlias(a);
1754 if(found) // if the command was hooked and found, all is good
1758 if (!Cvar_Command () && host_framecount > 0)
1759 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
1762 cmd_tokenizebufferpos = oldpos;
1764 Cbuf_UnlockThreadMutex();
1770 Cmd_ForwardStringToServer
1772 Sends an entire command string over to the server, unprocessed
1775 void Cmd_ForwardStringToServer (const char *s)
1778 if (cls.state != ca_connected)
1780 Con_Printf("Can't \"%s\", not connected\n", s);
1787 // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
1788 // attention, it has been eradicated from here, its only (former) use in
1789 // all of darkplaces.
1790 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1791 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
1793 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
1794 if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
1796 // say/say_team commands can replace % character codes with status info
1799 if (*s == '%' && s[1])
1801 // handle proquake message macros
1805 case 'l': // current location
1806 CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
1808 case 'h': // current health
1809 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
1811 case 'a': // current armor
1812 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
1814 case 'x': // current rockets
1815 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
1817 case 'c': // current cells
1818 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
1820 // silly proquake macros
1821 case 'd': // loc at last death
1822 CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
1824 case 't': // current time
1825 dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
1827 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
1828 if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
1829 dpsnprintf(temp, sizeof(temp), "I need RL");
1830 else if (!cl.stats[STAT_ROCKETS])
1831 dpsnprintf(temp, sizeof(temp), "I need rockets");
1833 dpsnprintf(temp, sizeof(temp), "I have RL");
1835 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
1836 if (cl.stats[STAT_ITEMS] & IT_QUAD)
1839 strlcat(temp, " ", sizeof(temp));
1840 strlcat(temp, "quad", sizeof(temp));
1842 if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
1845 strlcat(temp, " ", sizeof(temp));
1846 strlcat(temp, "pent", sizeof(temp));
1848 if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1851 strlcat(temp, " ", sizeof(temp));
1852 strlcat(temp, "eyes", sizeof(temp));
1855 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
1856 if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
1857 strlcat(temp, "SSG", sizeof(temp));
1858 strlcat(temp, ":", sizeof(temp));
1859 if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
1860 strlcat(temp, "NG", sizeof(temp));
1861 strlcat(temp, ":", sizeof(temp));
1862 if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
1863 strlcat(temp, "SNG", sizeof(temp));
1864 strlcat(temp, ":", sizeof(temp));
1865 if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
1866 strlcat(temp, "GL", sizeof(temp));
1867 strlcat(temp, ":", sizeof(temp));
1868 if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
1869 strlcat(temp, "RL", sizeof(temp));
1870 strlcat(temp, ":", sizeof(temp));
1871 if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
1872 strlcat(temp, "LG", sizeof(temp));
1875 // not a recognized macro, print it as-is...
1881 // write the resulting text
1882 SZ_Write(&cls.netcon->message, (unsigned char *)temp, strlen(temp));
1886 MSG_WriteByte(&cls.netcon->message, *s);
1889 MSG_WriteByte(&cls.netcon->message, 0);
1891 else // any other command is passed on as-is
1892 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
1899 Sends the entire command line over to the server
1902 void Cmd_ForwardToServer (void)
1905 if (!strcasecmp(Cmd_Argv(0), "cmd"))
1907 // we want to strip off "cmd", so just send the args
1908 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1912 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
1913 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
1915 // don't send an empty forward message if the user tries "cmd" by itself
1918 Cmd_ForwardStringToServer(s);
1926 Returns the position (1 to argc-1) in the command's argument list
1927 where the given parameter apears, or 0 if not present
1931 int Cmd_CheckParm (const char *parm)
1937 Con_Printf ("Cmd_CheckParm: NULL");
1941 for (i = 1; i < Cmd_Argc (); i++)
1942 if (!strcasecmp (parm, Cmd_Argv (i)))
1950 void Cmd_SaveInitState(void)
1954 for (f = cmd_functions;f;f = f->next)
1955 f->initstate = true;
1956 for (a = cmd_alias;a;a = a->next)
1958 a->initstate = true;
1959 a->initialvalue = Mem_strdup(zonemempool, a->value);
1961 Cvar_SaveInitState();
1964 void Cmd_RestoreInitState(void)
1966 cmd_function_t *f, **fp;
1967 cmdalias_t *a, **ap;
1968 for (fp = &cmd_functions;(f = *fp);)
1974 // destroy this command, it didn't exist at init
1975 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
1980 for (ap = &cmd_alias;(a = *ap);)
1984 // restore this alias, it existed at init
1985 if (strcmp(a->value ? a->value : "", a->initialvalue ? a->initialvalue : ""))
1987 Con_DPrintf("Cmd_RestoreInitState: Restoring alias %s\n", a->name);
1990 a->value = Mem_strdup(zonemempool, a->initialvalue);
1996 // free this alias, it didn't exist at init...
1997 Con_DPrintf("Cmd_RestoreInitState: Destroying alias %s\n", a->name);
2004 Cvar_RestoreInitState();