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