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