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