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