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