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