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