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