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