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