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