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