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