]> icculus.org git repositories - divverent/darkplaces.git/blob - cmd.c
patch from div0 that adds sv_random_seed for benchmarking servers with bots the same...
[divverent/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
24 #define MAX_ALIAS_NAME  32
25 // this is the largest script file that can be executed in one step
26 // LordHavoc: inreased this from 8192 to 32768
27 #define CMDBUFSIZE 32768
28 // maximum number of parameters to a command
29 #define MAX_ARGS 80
30 // maximum tokenizable commandline length (counting NUL terminations)
31 #define CMD_TOKENIZELENGTH (MAX_INPUTLINE + 80)
32
33 typedef struct cmdalias_s
34 {
35         struct cmdalias_s *next;
36         char name[MAX_ALIAS_NAME];
37         char *value;
38 } cmdalias_t;
39
40 static cmdalias_t *cmd_alias;
41
42 static qboolean cmd_wait;
43
44 static mempool_t *cmd_mempool;
45
46 static char cmd_tokenizebuffer[CMD_TOKENIZELENGTH];
47 static int cmd_tokenizebufferpos = 0;
48
49 //=============================================================================
50
51 /*
52 ============
53 Cmd_Wait_f
54
55 Causes execution of the remainder of the command buffer to be delayed until
56 next frame.  This allows commands like:
57 bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2"
58 ============
59 */
60 static void Cmd_Wait_f (void)
61 {
62         cmd_wait = true;
63 }
64
65 /*
66 =============================================================================
67
68                                                 COMMAND BUFFER
69
70 =============================================================================
71 */
72
73 static sizebuf_t        cmd_text;
74 static unsigned char            cmd_text_buf[CMDBUFSIZE];
75
76 /*
77 ============
78 Cbuf_AddText
79
80 Adds command text at the end of the buffer
81 ============
82 */
83 void Cbuf_AddText (const char *text)
84 {
85         int             l;
86
87         l = (int)strlen (text);
88
89         if (cmd_text.cursize + l >= cmd_text.maxsize)
90         {
91                 Con_Print("Cbuf_AddText: overflow\n");
92                 return;
93         }
94
95         SZ_Write (&cmd_text, (const unsigned char *)text, (int)strlen (text));
96 }
97
98
99 /*
100 ============
101 Cbuf_InsertText
102
103 Adds command text immediately after the current command
104 Adds a \n to the text
105 FIXME: actually change the command buffer to do less copying
106 ============
107 */
108 void Cbuf_InsertText (const char *text)
109 {
110         char    *temp;
111         int             templen;
112
113         // copy off any commands still remaining in the exec buffer
114         templen = cmd_text.cursize;
115         if (templen)
116         {
117                 temp = (char *)Mem_Alloc (tempmempool, templen);
118                 memcpy (temp, cmd_text.data, templen);
119                 SZ_Clear (&cmd_text);
120         }
121         else
122                 temp = NULL;
123
124         // add the entire text of the file
125         Cbuf_AddText (text);
126
127         // add the copied off data
128         if (temp != NULL)
129         {
130                 SZ_Write (&cmd_text, (const unsigned char *)temp, templen);
131                 Mem_Free (temp);
132         }
133 }
134
135 /*
136 ============
137 Cbuf_Execute
138 ============
139 */
140 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias );
141 void Cbuf_Execute (void)
142 {
143         int i;
144         char *text;
145         char line[MAX_INPUTLINE];
146         char preprocessed[MAX_INPUTLINE];
147         int quotes;
148
149         // LordHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
150         cmd_tokenizebufferpos = 0;
151
152         while (cmd_text.cursize)
153         {
154 // find a \n or ; line break
155                 text = (char *)cmd_text.data;
156
157                 quotes = 0;
158                 for (i=0 ; i< cmd_text.cursize ; i++)
159                 {
160                         if (text[i] == '"')
161                                 quotes ^= 1;
162                         if ( !quotes &&  text[i] == ';')
163                                 break;  // don't break if inside a quoted string
164                         if (text[i] == '\r' || text[i] == '\n')
165                                 break;
166                 }
167
168                 memcpy (line, text, i);
169                 line[i] = 0;
170
171 // delete the text from the command buffer and move remaining commands down
172 // this is necessary because commands (exec, alias) can insert data at the
173 // beginning of the text buffer
174
175                 if (i == cmd_text.cursize)
176                         cmd_text.cursize = 0;
177                 else
178                 {
179                         i++;
180                         cmd_text.cursize -= i;
181                         memcpy (cmd_text.data, text+i, cmd_text.cursize);
182                 }
183
184 // execute the command line
185                 Cmd_PreprocessString( line, preprocessed, sizeof(preprocessed), NULL );
186                 Cmd_ExecuteString (preprocessed, src_command);
187
188                 if (cmd_wait)
189                 {       // skip out while text still remains in buffer, leaving it
190                         // for next frame
191                         cmd_wait = false;
192                         break;
193                 }
194         }
195 }
196
197 /*
198 ==============================================================================
199
200                                                 SCRIPT COMMANDS
201
202 ==============================================================================
203 */
204
205 /*
206 ===============
207 Cmd_StuffCmds_f
208
209 Adds command line parameters as script statements
210 Commands lead with a +, and continue until a - or another +
211 quake +prog jctest.qp +cmd amlev1
212 quake -nosound +cmd amlev1
213 ===============
214 */
215 qboolean host_stuffcmdsrun = false;
216 void Cmd_StuffCmds_f (void)
217 {
218         int             i, j, l;
219         // this is per command, and bounds checked (no buffer overflows)
220         char    build[MAX_INPUTLINE];
221
222         if (Cmd_Argc () != 1)
223         {
224                 Con_Print("stuffcmds : execute command line parameters\n");
225                 return;
226         }
227
228         // no reason to run the commandline arguments twice
229         if (host_stuffcmdsrun)
230                 return;
231
232         host_stuffcmdsrun = true;
233         for (i = 0;i < com_argc;i++)
234         {
235                 if (com_argv[i] && com_argv[i][0] == '+' && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
236                 {
237                         l = 0;
238                         j = 1;
239                         while (com_argv[i][j])
240                                 build[l++] = com_argv[i][j++];
241                         i++;
242                         for (;i < com_argc;i++)
243                         {
244                                 if (!com_argv[i])
245                                         continue;
246                                 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
247                                         break;
248                                 if (l + strlen(com_argv[i]) + 5 > sizeof(build))
249                                         break;
250                                 build[l++] = ' ';
251                                 build[l++] = '\"';
252                                 for (j = 0;com_argv[i][j];j++)
253                                         build[l++] = com_argv[i][j];
254                                 build[l++] = '\"';
255                         }
256                         build[l++] = '\n';
257                         build[l++] = 0;
258                         Cbuf_InsertText (build);
259                         i--;
260                 }
261         }
262 }
263
264
265 /*
266 ===============
267 Cmd_Exec_f
268 ===============
269 */
270 static void Cmd_Exec_f (void)
271 {
272         char *f;
273
274         if (Cmd_Argc () != 2)
275         {
276                 Con_Print("exec <filename> : execute a script file\n");
277                 return;
278         }
279
280         f = (char *)FS_LoadFile (Cmd_Argv(1), tempmempool, false, NULL);
281         if (!f)
282         {
283                 Con_Printf("couldn't exec %s\n",Cmd_Argv(1));
284                 return;
285         }
286         Con_DPrintf("execing %s\n",Cmd_Argv(1));
287
288         // if executing default.cfg for the first time, lock the cvar defaults
289         // it may seem backwards to insert this text BEFORE the default.cfg
290         // but Cbuf_InsertText inserts before, so this actually ends up after it.
291         if (!strcmp(Cmd_Argv(1), "default.cfg"))
292                 Cbuf_InsertText("\ncvar_lockdefaults\n");
293
294         // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
295         // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
296         Cbuf_InsertText ("\n");
297         Cbuf_InsertText (f);
298         Mem_Free(f);
299 }
300
301
302 /*
303 ===============
304 Cmd_Echo_f
305
306 Just prints the rest of the line to the console
307 ===============
308 */
309 static void Cmd_Echo_f (void)
310 {
311         int             i;
312
313         for (i=1 ; i<Cmd_Argc() ; i++)
314                 Con_Printf("%s ",Cmd_Argv(i));
315         Con_Print("\n");
316 }
317
318 // DRESK - 5/14/06
319 // Support Doom3-style Toggle Console Command
320 /*
321 ===============
322 Cmd_Toggle_f
323
324 Toggles a specified console variable amongst the values specified (default is 0 and 1)
325 ===============
326 */
327 static void Cmd_Toggle_f(void)
328 {
329         // Acquire Number of Arguments
330         int nNumArgs = Cmd_Argc();
331
332         if(nNumArgs == 1)
333                 // No Arguments Specified; Print Usage
334                 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");
335         else
336         { // Correct Arguments Specified
337                 // Acquire Potential CVar
338                 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
339
340                 if(cvCVar != NULL)
341                 { // Valid CVar
342                         if(nNumArgs == 2)
343                         { // Default Usage
344                                 if(cvCVar->integer)
345                                         Cvar_SetValueQuick(cvCVar, 0);
346                                 else
347                                         Cvar_SetValueQuick(cvCVar, 1);
348                         }
349                         else
350                         if(nNumArgs == 3)
351                         { // 0 and Specified Usage
352                                 if(cvCVar->integer == atoi(Cmd_Argv(2) ) )
353                                         // CVar is Specified Value; // Reset to 0
354                                         Cvar_SetValueQuick(cvCVar, 0);
355                                 else
356                                 if(cvCVar->integer == 0)
357                                         // CVar is 0; Specify Value
358                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
359                                 else
360                                         // CVar does not match; Reset to 0
361                                         Cvar_SetValueQuick(cvCVar, 0);
362                         }
363                         else
364                         { // Variable Values Specified
365                                 int nCnt;
366                                 int bFound = 0;
367
368                                 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
369                                 { // Cycle through Values
370                                         if( strcmp(cvCVar->string, Cmd_Argv(nCnt) ) == 0)
371                                         { // Current Value Located; Increment to Next
372                                                 if( (nCnt + 1) == nNumArgs)
373                                                         // Max Value Reached; Reset
374                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
375                                                 else
376                                                         // Next Value
377                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
378
379                                                 // End Loop
380                                                 nCnt = nNumArgs;
381                                                 // Assign Found
382                                                 bFound = 1;
383                                         }
384                                 }
385                                 if(!bFound)
386                                         // Value not Found; Reset to Original
387                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
388                         }
389
390                 }
391                 else
392                 { // Invalid CVar
393                         Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(2) );
394                 }
395         }
396 }
397
398 /*
399 ===============
400 Cmd_Alias_f
401
402 Creates a new command that executes a command string (possibly ; seperated)
403 ===============
404 */
405 static void Cmd_Alias_f (void)
406 {
407         cmdalias_t      *a;
408         char            cmd[MAX_INPUTLINE];
409         int                     i, c;
410         const char              *s;
411         size_t          alloclen;
412
413         if (Cmd_Argc() == 1)
414         {
415                 Con_Print("Current alias commands:\n");
416                 for (a = cmd_alias ; a ; a=a->next)
417                         Con_Printf("%s : %s\n", a->name, a->value);
418                 return;
419         }
420
421         s = Cmd_Argv(1);
422         if (strlen(s) >= MAX_ALIAS_NAME)
423         {
424                 Con_Print("Alias name is too long\n");
425                 return;
426         }
427
428         // if the alias already exists, reuse it
429         for (a = cmd_alias ; a ; a=a->next)
430         {
431                 if (!strcmp(s, a->name))
432                 {
433                         Z_Free (a->value);
434                         break;
435                 }
436         }
437
438         if (!a)
439         {
440                 cmdalias_t *prev, *current;
441
442                 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
443                 strlcpy (a->name, s, sizeof (a->name));
444                 // insert it at the right alphanumeric position
445                 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
446                         ;
447                 if( prev ) {
448                         prev->next = a;
449                 } else {
450                         cmd_alias = a;
451                 }
452                 a->next = current;
453         }
454
455
456 // copy the rest of the command line
457         cmd[0] = 0;             // start out with a null string
458         c = Cmd_Argc();
459         for (i=2 ; i< c ; i++)
460         {
461                 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
462                 if (i != c)
463                         strlcat (cmd, " ", sizeof (cmd));
464         }
465         strlcat (cmd, "\n", sizeof (cmd));
466
467         alloclen = strlen (cmd) + 1;
468         a->value = (char *)Z_Malloc (alloclen);
469         memcpy (a->value, cmd, alloclen);
470 }
471
472 /*
473 =============================================================================
474
475                                         COMMAND EXECUTION
476
477 =============================================================================
478 */
479
480 typedef struct cmd_function_s
481 {
482         struct cmd_function_s *next;
483         const char *name;
484         const char *description;
485         xcommand_t consolefunction;
486         xcommand_t clientfunction;
487         qboolean csqcfunc;
488 } cmd_function_t;
489
490 static int cmd_argc;
491 static const char *cmd_argv[MAX_ARGS];
492 static const char *cmd_null_string = "";
493 static const char *cmd_args;
494 cmd_source_t cmd_source;
495
496
497 static cmd_function_t *cmd_functions;           // possible commands to execute
498
499 /*
500 Cmd_PreprocessString
501
502 Preprocesses strings and replaces $*, $param#, $cvar accordingly
503 */
504 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
505         const char *in;
506         unsigned outlen;
507         int inquote;
508
509         // don't crash if there's no room in the outtext buffer
510         if( maxoutlen == 0 ) {
511                 return;
512         }
513         maxoutlen--; // because of \0
514
515         in = intext;
516         outlen = 0;
517         inquote = 0;
518
519         while( *in && outlen < maxoutlen ) {
520                 if( *in == '$' && !inquote ) {
521                         // this is some kind of expansion, see what comes after the $
522                         in++;
523                         // replacements that can always be used:
524                         // $$ is replaced with $, to allow escaping $
525                         // $<cvarname> is replaced with the contents of the cvar
526                         //
527                         // the following can be used in aliases only:
528                         // $* is replaced with all formal parameters (including name of the alias - this probably is not desirable)
529                         // $0 is replaced with the name of this alias
530                         // $<number> is replaced with an argument to this alias (or copied as-is if no such parameter exists), can be multiple digits
531                         if( *in == '$' ) {
532                                 outtext[outlen++] = *in++;
533                         } else if( *in == '*' && alias ) {
534                                 const char *linein = Cmd_Args();
535
536                                 // include all parameters
537                                 if (linein) {
538                                         while( *linein && outlen < maxoutlen ) {
539                                                 outtext[outlen++] = *linein++;
540                                         }
541                                 }
542
543                                 in++;
544                         } else if( '0' <= *in && *in <= '9' && alias ) {
545                                 char *nexttoken;
546                                 int argnum;
547
548                                 argnum = strtol( in, &nexttoken, 10 );
549
550                                 if( 0 <= argnum && argnum < Cmd_Argc() ) {
551                                         const char *param = Cmd_Argv( argnum );
552                                         while( *param && outlen < maxoutlen ) {
553                                                 outtext[outlen++] = *param++;
554                                         }
555                                         in = nexttoken;
556                                 } else if( argnum >= Cmd_Argc() ) {
557                                         Con_Printf( "Warning: Not enough parameters passed to alias '%s', at least %i expected:\n    %s\n", alias->name, argnum, alias->value );
558                                         outtext[outlen++] = '$';
559                                 }
560                         } else {
561                                 cvar_t *cvar;
562                                 const char *tempin = in;
563
564                                 COM_ParseTokenConsole( &tempin );
565                                 // don't expand rcon_password or similar cvars (CVAR_PRIVATE flag)
566                                 if ((cvar = Cvar_FindVar(&com_token[0])) && !(cvar->flags & CVAR_PRIVATE)) {
567                                         const char *cvarcontent = cvar->string;
568                                         while( *cvarcontent && outlen < maxoutlen ) {
569                                                 outtext[outlen++] = *cvarcontent++;
570                                         }
571                                         in = tempin;
572                                 } else {
573                                         if( alias ) {
574                                                 Con_Printf( "Warning: could not find cvar %s when expanding alias %s\n    %s\n", com_token, alias->name, alias->value );
575                                         } else {
576                                                 Con_Printf( "Warning: could not find cvar %s\n", com_token );
577                                         }
578                                         outtext[outlen++] = '$';
579                                 }
580                         }
581                 } else {
582                         if( *in == '"' ) {
583                                 inquote ^= 1;
584                         }
585                         outtext[outlen++] = *in++;
586                 }
587         }
588         outtext[outlen] = 0;
589 }
590
591 /*
592 ============
593 Cmd_ExecuteAlias
594
595 Called for aliases and fills in the alias into the cbuffer
596 ============
597 */
598 static void Cmd_ExecuteAlias (cmdalias_t *alias)
599 {
600         static char buffer[ MAX_INPUTLINE + 2 ];
601         Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
602         // insert at start of command buffer, so that aliases execute in order
603         // (fixes bug introduced by Black on 20050705)
604         Cbuf_InsertText( buffer );
605 }
606
607 /*
608 ========
609 Cmd_List
610
611         CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
612         Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
613
614 ========
615 */
616 static void Cmd_List_f (void)
617 {
618         cmd_function_t *cmd;
619         const char *partial;
620         int len, count;
621
622         if (Cmd_Argc() > 1)
623         {
624                 partial = Cmd_Argv (1);
625                 len = (int)strlen(partial);
626         }
627         else
628         {
629                 partial = NULL;
630                 len = 0;
631         }
632
633         count = 0;
634         for (cmd = cmd_functions; cmd; cmd = cmd->next)
635         {
636                 if (partial && strncmp(partial, cmd->name, len))
637                         continue;
638                 Con_Printf("%s : %s\n", cmd->name, cmd->description);
639                 count++;
640         }
641
642         if (partial)
643                 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
644         else
645                 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
646 }
647
648 /*
649 ============
650 Cmd_Init
651 ============
652 */
653 void Cmd_Init (void)
654 {
655         cmd_mempool = Mem_AllocPool("commands", 0, NULL);
656         // space for commands and script files
657         cmd_text.data = cmd_text_buf;
658         cmd_text.maxsize = sizeof(cmd_text_buf);
659         cmd_text.cursize = 0;
660 }
661
662 void Cmd_Init_Commands (void)
663 {
664 //
665 // register our commands
666 //
667         Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
668         Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
669         Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
670         Cmd_AddCommand ("alias",Cmd_Alias_f, "create a script function (parameters are passed in as $1 through $9, and $* for all parameters)");
671         Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
672         Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
673         Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
674         Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
675
676         // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
677         // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
678         Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix");
679         Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix");
680
681         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");
682         Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
683         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)");
684         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)");
685
686         // DRESK - 5/14/06
687         // Support Doom3-style Toggle Command
688         Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
689 }
690
691 /*
692 ============
693 Cmd_Shutdown
694 ============
695 */
696 void Cmd_Shutdown(void)
697 {
698         Mem_FreePool(&cmd_mempool);
699 }
700
701 /*
702 ============
703 Cmd_Argc
704 ============
705 */
706 int             Cmd_Argc (void)
707 {
708         return cmd_argc;
709 }
710
711 /*
712 ============
713 Cmd_Argv
714 ============
715 */
716 const char *Cmd_Argv (int arg)
717 {
718         if (arg >= cmd_argc )
719                 return cmd_null_string;
720         return cmd_argv[arg];
721 }
722
723 /*
724 ============
725 Cmd_Args
726 ============
727 */
728 const char *Cmd_Args (void)
729 {
730         return cmd_args;
731 }
732
733
734 /*
735 ============
736 Cmd_TokenizeString
737
738 Parses the given string into command line tokens.
739 ============
740 */
741 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
742 static void Cmd_TokenizeString (const char *text)
743 {
744         int l;
745
746         cmd_argc = 0;
747         cmd_args = NULL;
748
749         while (1)
750         {
751                 // skip whitespace up to a /n
752                 while (*text && *text <= ' ' && *text != '\r' && *text != '\n')
753                         text++;
754
755                 // line endings:
756                 // UNIX: \n
757                 // Mac: \r
758                 // Windows: \r\n
759                 if (*text == '\n' || *text == '\r')
760                 {
761                         // a newline separates commands in the buffer
762                         if (*text == '\r' && text[1] == '\n')
763                                 text++;
764                         text++;
765                         break;
766                 }
767
768                 if (!*text)
769                         return;
770
771                 if (cmd_argc == 1)
772                         cmd_args = text;
773
774                 if (!COM_ParseTokenConsole(&text))
775                         return;
776
777                 if (cmd_argc < MAX_ARGS)
778                 {
779                         l = (int)strlen(com_token) + 1;
780                         if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
781                         {
782                                 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
783                                 break;
784                         }
785                         memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
786                         cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
787                         cmd_tokenizebufferpos += l;
788                         cmd_argc++;
789                 }
790         }
791 }
792
793
794 /*
795 ============
796 Cmd_AddCommand
797 ============
798 */
799 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
800 {
801         cmd_function_t *cmd;
802         cmd_function_t *prev, *current;
803
804 // fail if the command is a variable name
805         if (Cvar_FindVar( cmd_name ))
806         {
807                 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
808                 return;
809         }
810
811 // fail if the command already exists
812         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
813         {
814                 if (!strcmp (cmd_name, cmd->name))
815                 {
816                         if (consolefunction || clientfunction)
817                         {
818                                 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
819                                 return;
820                         }
821                         else    //[515]: csqc
822                         {
823                                 cmd->csqcfunc = true;
824                                 return;
825                         }
826                 }
827         }
828
829         cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
830         cmd->name = cmd_name;
831         cmd->consolefunction = consolefunction;
832         cmd->clientfunction = clientfunction;
833         cmd->description = description;
834         if(!consolefunction && !clientfunction)                 //[515]: csqc
835                 cmd->csqcfunc = true;
836         cmd->next = cmd_functions;
837
838 // insert it at the right alphanumeric position
839         for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
840                 ;
841         if( prev ) {
842                 prev->next = cmd;
843         } else {
844                 cmd_functions = cmd;
845         }
846         cmd->next = current;
847 }
848
849 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
850 {
851         Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
852 }
853
854 /*
855 ============
856 Cmd_Exists
857 ============
858 */
859 qboolean Cmd_Exists (const char *cmd_name)
860 {
861         cmd_function_t  *cmd;
862
863         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
864                 if (!strcmp (cmd_name,cmd->name))
865                         return true;
866
867         return false;
868 }
869
870
871 /*
872 ============
873 Cmd_CompleteCommand
874 ============
875 */
876 const char *Cmd_CompleteCommand (const char *partial)
877 {
878         cmd_function_t *cmd;
879         size_t len;
880
881         len = strlen(partial);
882
883         if (!len)
884                 return NULL;
885
886 // check functions
887         for (cmd = cmd_functions; cmd; cmd = cmd->next)
888                 if (!strncasecmp(partial, cmd->name, len))
889                         return cmd->name;
890
891         return NULL;
892 }
893
894 /*
895         Cmd_CompleteCountPossible
896
897         New function for tab-completion system
898         Added by EvilTypeGuy
899         Thanks to Fett erich@heintz.com
900         Thanks to taniwha
901
902 */
903 int Cmd_CompleteCountPossible (const char *partial)
904 {
905         cmd_function_t *cmd;
906         size_t len;
907         int h;
908
909         h = 0;
910         len = strlen(partial);
911
912         if (!len)
913                 return 0;
914
915         // Loop through the command list and count all partial matches
916         for (cmd = cmd_functions; cmd; cmd = cmd->next)
917                 if (!strncasecmp(partial, cmd->name, len))
918                         h++;
919
920         return h;
921 }
922
923 /*
924         Cmd_CompleteBuildList
925
926         New function for tab-completion system
927         Added by EvilTypeGuy
928         Thanks to Fett erich@heintz.com
929         Thanks to taniwha
930
931 */
932 const char **Cmd_CompleteBuildList (const char *partial)
933 {
934         cmd_function_t *cmd;
935         size_t len = 0;
936         size_t bpos = 0;
937         size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
938         const char **buf;
939
940         len = strlen(partial);
941         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
942         // Loop through the alias list and print all matches
943         for (cmd = cmd_functions; cmd; cmd = cmd->next)
944                 if (!strncasecmp(partial, cmd->name, len))
945                         buf[bpos++] = cmd->name;
946
947         buf[bpos] = NULL;
948         return buf;
949 }
950
951 // written by LordHavoc
952 void Cmd_CompleteCommandPrint (const char *partial)
953 {
954         cmd_function_t *cmd;
955         size_t len = strlen(partial);
956         // Loop through the command list and print all matches
957         for (cmd = cmd_functions; cmd; cmd = cmd->next)
958                 if (!strncasecmp(partial, cmd->name, len))
959                         Con_Printf("%s : %s\n", cmd->name, cmd->description);
960 }
961
962 /*
963         Cmd_CompleteAlias
964
965         New function for tab-completion system
966         Added by EvilTypeGuy
967         Thanks to Fett erich@heintz.com
968         Thanks to taniwha
969
970 */
971 const char *Cmd_CompleteAlias (const char *partial)
972 {
973         cmdalias_t *alias;
974         size_t len;
975
976         len = strlen(partial);
977
978         if (!len)
979                 return NULL;
980
981         // Check functions
982         for (alias = cmd_alias; alias; alias = alias->next)
983                 if (!strncasecmp(partial, alias->name, len))
984                         return alias->name;
985
986         return NULL;
987 }
988
989 // written by LordHavoc
990 void Cmd_CompleteAliasPrint (const char *partial)
991 {
992         cmdalias_t *alias;
993         size_t len = strlen(partial);
994         // Loop through the alias list and print all matches
995         for (alias = cmd_alias; alias; alias = alias->next)
996                 if (!strncasecmp(partial, alias->name, len))
997                         Con_Printf("%s : %s\n", alias->name, alias->value);
998 }
999
1000
1001 /*
1002         Cmd_CompleteAliasCountPossible
1003
1004         New function for tab-completion system
1005         Added by EvilTypeGuy
1006         Thanks to Fett erich@heintz.com
1007         Thanks to taniwha
1008
1009 */
1010 int Cmd_CompleteAliasCountPossible (const char *partial)
1011 {
1012         cmdalias_t      *alias;
1013         size_t          len;
1014         int                     h;
1015
1016         h = 0;
1017
1018         len = strlen(partial);
1019
1020         if (!len)
1021                 return 0;
1022
1023         // Loop through the command list and count all partial matches
1024         for (alias = cmd_alias; alias; alias = alias->next)
1025                 if (!strncasecmp(partial, alias->name, len))
1026                         h++;
1027
1028         return h;
1029 }
1030
1031 /*
1032         Cmd_CompleteAliasBuildList
1033
1034         New function for tab-completion system
1035         Added by EvilTypeGuy
1036         Thanks to Fett erich@heintz.com
1037         Thanks to taniwha
1038
1039 */
1040 const char **Cmd_CompleteAliasBuildList (const char *partial)
1041 {
1042         cmdalias_t *alias;
1043         size_t len = 0;
1044         size_t bpos = 0;
1045         size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
1046         const char **buf;
1047
1048         len = strlen(partial);
1049         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1050         // Loop through the alias list and print all matches
1051         for (alias = cmd_alias; alias; alias = alias->next)
1052                 if (!strncasecmp(partial, alias->name, len))
1053                         buf[bpos++] = alias->name;
1054
1055         buf[bpos] = NULL;
1056         return buf;
1057 }
1058
1059 void Cmd_ClearCsqcFuncs (void)
1060 {
1061         cmd_function_t *cmd;
1062         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1063                 cmd->csqcfunc = false;
1064 }
1065
1066 qboolean CL_VM_ConsoleCommand (const char *cmd);
1067 /*
1068 ============
1069 Cmd_ExecuteString
1070
1071 A complete command line has been parsed, so try to execute it
1072 FIXME: lookupnoadd the token to speed search?
1073 ============
1074 */
1075 void Cmd_ExecuteString (const char *text, cmd_source_t src)
1076 {
1077         int oldpos;
1078         cmd_function_t *cmd;
1079         cmdalias_t *a;
1080
1081         oldpos = cmd_tokenizebufferpos;
1082         cmd_source = src;
1083
1084         Cmd_TokenizeString (text);
1085
1086 // execute the command line
1087         if (!Cmd_Argc())
1088         {
1089                 cmd_tokenizebufferpos = oldpos;
1090                 return;         // no tokens
1091         }
1092
1093 // check functions
1094         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1095         {
1096                 if (!strcasecmp (cmd_argv[0],cmd->name))
1097                 {
1098                         if (cmd->csqcfunc && CL_VM_ConsoleCommand (text))       //[515]: csqc
1099                                 return;
1100                         switch (src)
1101                         {
1102                         case src_command:
1103                                 if (cmd->consolefunction)
1104                                         cmd->consolefunction ();
1105                                 else if (cmd->clientfunction)
1106                                 {
1107                                         if (cls.state == ca_connected)
1108                                         {
1109                                                 // forward remote commands to the server for execution
1110                                                 Cmd_ForwardToServer();
1111                                         }
1112                                         else
1113                                                 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
1114                                 }
1115                                 else
1116                                         Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
1117                                 cmd_tokenizebufferpos = oldpos;
1118                                 return;
1119                         case src_client:
1120                                 if (cmd->clientfunction)
1121                                 {
1122                                         cmd->clientfunction ();
1123                                         cmd_tokenizebufferpos = oldpos;
1124                                         return;
1125                                 }
1126                                 break;
1127                         }
1128                         break;
1129                 }
1130         }
1131
1132         // if it's a client command and no command was found, say so.
1133         if (cmd_source == src_client)
1134         {
1135                 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
1136                 return;
1137         }
1138
1139 // check alias
1140         for (a=cmd_alias ; a ; a=a->next)
1141         {
1142                 if (!strcasecmp (cmd_argv[0], a->name))
1143                 {
1144                         Cmd_ExecuteAlias(a);
1145                         cmd_tokenizebufferpos = oldpos;
1146                         return;
1147                 }
1148         }
1149
1150 // check cvars
1151         if (!Cvar_Command () && host_framecount > 0)
1152                 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
1153
1154         cmd_tokenizebufferpos = oldpos;
1155 }
1156
1157
1158 /*
1159 ===================
1160 Cmd_ForwardStringToServer
1161
1162 Sends an entire command string over to the server, unprocessed
1163 ===================
1164 */
1165 void Cmd_ForwardStringToServer (const char *s)
1166 {
1167         if (cls.state != ca_connected)
1168         {
1169                 Con_Printf("Can't \"%s\", not connected\n", s);
1170                 return;
1171         }
1172
1173         if (!cls.netcon)
1174                 return;
1175
1176         // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
1177         // attention, it has been eradicated from here, its only (former) use in
1178         // all of darkplaces.
1179         if (cls.protocol == PROTOCOL_QUAKEWORLD)
1180                 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
1181         else
1182                 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
1183         SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
1184 }
1185
1186 /*
1187 ===================
1188 Cmd_ForwardToServer
1189
1190 Sends the entire command line over to the server
1191 ===================
1192 */
1193 void Cmd_ForwardToServer (void)
1194 {
1195         const char *s;
1196         if (!strcasecmp(Cmd_Argv(0), "cmd"))
1197         {
1198                 // we want to strip off "cmd", so just send the args
1199                 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1200         }
1201         else
1202         {
1203                 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
1204                 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
1205         }
1206         // don't send an empty forward message if the user tries "cmd" by itself
1207         if (!s || !*s)
1208                 return;
1209         Cmd_ForwardStringToServer(s);
1210 }
1211
1212
1213 /*
1214 ================
1215 Cmd_CheckParm
1216
1217 Returns the position (1 to argc-1) in the command's argument list
1218 where the given parameter apears, or 0 if not present
1219 ================
1220 */
1221
1222 int Cmd_CheckParm (const char *parm)
1223 {
1224         int i;
1225
1226         if (!parm)
1227         {
1228                 Con_Printf ("Cmd_CheckParm: NULL");
1229                 return 0;
1230         }
1231
1232         for (i = 1; i < Cmd_Argc (); i++)
1233                 if (!strcasecmp (parm, Cmd_Argv (i)))
1234                         return i;
1235
1236         return 0;
1237 }
1238