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