2 Copyright (C) 1996-1997 Id Software, Inc.
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.
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.
13 See the GNU General Public License for more details.
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.
20 // cmd.c -- Quake script command processing module
25 cmd_state_t *cmd_local;
26 cmd_state_t *cmd_serverfromclient;
28 cmd_userdefined_t cmd_userdefined_all;
29 cmd_userdefined_t cmd_userdefined_null;
31 typedef struct cmd_iter_s {
36 static cmd_iter_t *cmd_iter_all;
38 mempool_t *cbuf_mempool;
40 // we only run the +whatever commandline arguments once
41 qbool host_stuffcmdsrun = false;
43 //=============================================================================
45 void Cbuf_Lock(cmd_buf_t *cbuf)
47 Thread_LockMutex(cbuf->lock);
50 void Cbuf_Unlock(cmd_buf_t *cbuf)
52 Thread_UnlockMutex(cbuf->lock);
60 Causes execution of the remainder of the command buffer to be delayed until
61 next frame. This allows commands like:
62 bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2"
65 static void Cmd_Wait_f (cmd_state_t *cmd)
67 cmd->cbuf->wait = true;
74 Cause a command to be executed after a delay.
77 static cmd_input_t *Cbuf_LinkGet(cmd_buf_t *cbuf, cmd_input_t *existing);
78 static void Cmd_Defer_f (cmd_state_t *cmd)
81 cmd_buf_t *cbuf = cmd->cbuf;
83 if(Cmd_Argc(cmd) == 1)
85 if(List_Is_Empty(&cbuf->deferred))
86 Con_Printf("No commands are pending.\n");
90 List_For_Each(pos, &cbuf->deferred)
92 current = List_Entry(*pos, cmd_input_t, list);
93 Con_Printf("-> In %9.2f: %s\n", current->delay, current->text);
97 else if(Cmd_Argc(cmd) == 2 && !strcasecmp("clear", Cmd_Argv(cmd, 1)))
99 while(!List_Is_Empty(&cbuf->deferred))
100 List_Move_Tail(cbuf->deferred.next, &cbuf->free);
102 else if(Cmd_Argc(cmd) == 3)
104 const char *text = Cmd_Argv(cmd, 2);
105 current = Cbuf_LinkGet(cbuf, NULL);
106 current->length = strlen(text);
107 current->source = cmd;
108 current->delay = atof(Cmd_Argv(cmd, 1));
110 if(current->size < current->length)
112 current->text = (char *)Mem_Realloc(cbuf_mempool, current->text, current->length + 1);
113 current->size = current->length;
116 strlcpy(current->text, text, current->length + 1);
118 List_Move_Tail(¤t->list, &cbuf->deferred);
122 Con_Printf("usage: defer <seconds> <command>\n"
132 Print something to the center of the screen using SCR_Centerprint
135 static void Cmd_Centerprint_f (cmd_state_t *cmd)
137 char msg[MAX_INPUTLINE];
138 unsigned int i, c, p;
142 strlcpy(msg, Cmd_Argv(cmd,1), sizeof(msg));
143 for(i = 2; i < c; ++i)
145 strlcat(msg, " ", sizeof(msg));
146 strlcat(msg, Cmd_Argv(cmd, i), sizeof(msg));
148 c = (unsigned int)strlen(msg);
149 for(p = 0, i = 0; i < c; ++i)
155 else if(msg[i+1] == '\\')
167 SCR_CenterPrint(msg);
172 =============================================================================
176 =============================================================================
179 static cmd_input_t *Cbuf_LinkGet(cmd_buf_t *cbuf, cmd_input_t *existing)
181 cmd_input_t *ret = NULL;
182 if(existing && existing->pending)
184 else if(!List_Is_Empty(&cbuf->free))
186 ret = List_Entry(*cbuf->free.next, cmd_input_t, list);
188 ret->pending = false;
193 static cmd_input_t *Cmd_AllocInputNode(void)
195 cmd_input_t *node = (cmd_input_t *)Mem_Alloc(cbuf_mempool, sizeof(cmd_input_t));
196 node->list.prev = node->list.next = &node->list;
197 node->size = node->length = node->pending = 0;
202 // Cloudwalk FIXME: The entire design of this thing is overly complicated.
203 // We could very much safely have one input node per line whether or not
204 // the command was terminated. We don't need to split up input nodes per command
206 static size_t Cmd_ParseInput (cmd_input_t **output, char **input)
208 size_t pos, cmdsize = 0, start = 0;
209 qbool command = false, lookahead = false;
210 qbool quotes = false, comment = false;
211 qbool escaped = false;
214 * The Quake command-line is super basic. It can be entered in the console
215 * or in config files. A semicolon is used to terminate a command and chain
216 * them together. Otherwise, a newline delineates command input.
218 * In most engines, the Quake command-line is a simple linear text buffer that
219 * is parsed when it executes. In Darkplaces, we use a linked list of command
220 * input and parse the input on the spot.
222 * This was done because Darkplaces allows multiple command interpreters on the
223 * same thread. Previously, each interpreter maintained its own buffer and this
224 * caused problems related to execution order, and maintaining a single simple
225 * buffer for all interpreters makes it non-trivial to keep track of which
226 * command should execute on which interpreter.
229 // Run until command and lookahead are both true, or until we run out of input.
230 for (pos = 0; (*input)[pos]; pos++)
232 // Look for newlines and semicolons. Ignore semicolons in quotes.
233 switch((*input)[pos])
241 if(!comment) // Not a newline so far. Still not a valid command yet.
243 if(!quotes && (*input)[pos] == ';') // Ignore semicolons in quotes.
245 else if (ISCOMMENT((*input), pos)) // Comments
260 switch((*input)[pos])
269 if (!escaped && quotes)
278 if(cmdsize && !command)
281 if(command && lookahead)
290 *output = Cmd_AllocInputNode();
292 // Append, since this input line hasn't closed yet.
293 if((*output)->pending)
294 offset = (*output)->length;
296 (*output)->length += cmdsize;
298 if((*output)->size < (*output)->length)
300 (*output)->text = (char *)Mem_Realloc(cbuf_mempool, (*output)->text, (*output)->length + 1);
301 (*output)->size = (*output)->length;
304 strlcpy(&(*output)->text[offset], &(*input)[start], cmdsize + 1);
307 * If we were still looking ahead by the time we broke from the loop, the command input
308 * hasn't terminated yet and we're still expecting more, so keep this node open for appending later.
310 (*output)->pending = !lookahead;
313 // Set input to its new position. Can be NULL.
314 *input = &(*input)[pos];
319 // Cloudwalk: Not happy with this, but it works.
320 static void Cbuf_LinkCreate(cmd_state_t *cmd, llist_t *head, cmd_input_t *existing, const char *text)
322 char *in = (char *)&text[0];
323 cmd_buf_t *cbuf = cmd->cbuf;
324 size_t totalsize = 0, newsize = 0;
325 cmd_input_t *current = NULL;
327 // Slide the pointer down until we reach the end
330 // Check if the current node is still accepting input (input line hasn't terminated)
331 current = Cbuf_LinkGet(cbuf, existing);
332 newsize = Cmd_ParseInput(¤t, &in);
337 // current will match existing if the input line hasn't terminated yet
338 if(current != existing)
340 current->source = cmd;
341 List_Move_Tail(¤t->list, head);
344 totalsize += newsize;
346 else if (current == existing && !totalsize)
347 current->pending = false;
351 cbuf->size += totalsize;
358 Adds command text at the end of the buffer
361 void Cbuf_AddText (cmd_state_t *cmd, const char *text)
363 size_t l = strlen(text);
364 cmd_buf_t *cbuf = cmd->cbuf;
365 llist_t llist = {&llist, &llist};
369 if (cbuf->maxsize - cbuf->size <= l)
370 Con_Print("Cbuf_AddText: overflow\n");
373 Cbuf_LinkCreate(cmd, &llist, (List_Is_Empty(&cbuf->start) ? NULL : List_Entry(*cbuf->start.prev, cmd_input_t, list)), text);
374 if(!List_Is_Empty(&llist))
375 List_Splice_Tail(&llist, &cbuf->start);
384 Adds command text immediately after the current command
385 FIXME: actually change the command buffer to do less copying
388 void Cbuf_InsertText (cmd_state_t *cmd, const char *text)
390 cmd_buf_t *cbuf = cmd->cbuf;
391 llist_t llist = {&llist, &llist};
392 size_t l = strlen(text);
396 // we need to memmove the existing text and stuff this in before it...
397 if (cbuf->size + l >= cbuf->maxsize)
398 Con_Print("Cbuf_InsertText: overflow\n");
401 Cbuf_LinkCreate(cmd, &llist, List_Entry(*cbuf->start.next, cmd_input_t, list), text);
402 if(!List_Is_Empty(&llist))
403 List_Splice(&llist, &cbuf->start);
411 Cbuf_Execute_Deferred --blub
414 static void Cbuf_Execute_Deferred (cmd_buf_t *cbuf)
417 cmd_input_t *current;
420 if (host.realtime - cbuf->deferred_oldtime < 0 || host.realtime - cbuf->deferred_oldtime > 1800)
421 cbuf->deferred_oldtime = host.realtime;
422 eat = host.realtime - cbuf->deferred_oldtime;
423 if (eat < (1.0 / 120.0))
425 cbuf->deferred_oldtime = host.realtime;
427 List_For_Each(pos, &cbuf->deferred)
429 current = List_Entry(*pos, cmd_input_t, list);
430 current->delay -= eat;
431 if(current->delay <= 0)
433 cbuf->size += current->length;
434 List_Move(pos, &cbuf->start);
435 // We must return and come back next frame or the engine will freeze. Fragile... like glass :3
446 static qbool Cmd_PreprocessString(cmd_state_t *cmd, const char *intext, char *outtext, unsigned maxoutlen, cmd_alias_t *alias );
447 void Cbuf_Execute (cmd_buf_t *cbuf)
449 cmd_input_t *current;
450 char preprocessed[MAX_INPUTLINE];
453 // LadyHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
454 cbuf->tokenizebufferpos = 0;
456 while (!List_Is_Empty(&cbuf->start))
459 * Delete the text from the command buffer and move remaining
460 * commands down. This is necessary because commands (exec, alias)
461 * can insert data at the beginning of the text buffer
463 current = List_Entry(*cbuf->start.next, cmd_input_t, list);
465 // Recycle memory so using WASD doesn't cause a malloc and free
466 List_Move_Tail(¤t->list, &cbuf->free);
469 * Assume we're rolling with the current command-line and
470 * always set this false because alias expansion or cbuf insertion
471 * without a newline may set this true, and cause weirdness.
473 current->pending = false;
475 cbuf->size -= current->length;
477 firstchar = current->text;
478 while(*firstchar && ISWHITESPACE(*firstchar))
480 if((strncmp(firstchar, "alias", 5) || !ISWHITESPACE(firstchar[5])) &&
481 (strncmp(firstchar, "bind", 4) || !ISWHITESPACE(firstchar[4])) &&
482 (strncmp(firstchar, "in_bind", 7) || !ISWHITESPACE(firstchar[7])))
484 if(Cmd_PreprocessString(current->source, current->text, preprocessed, sizeof(preprocessed), NULL ))
485 Cmd_ExecuteString(current->source, preprocessed, src_local, false);
489 Cmd_ExecuteString (current->source, current->text, src_local, false);
497 * Skip out while text still remains in
498 * buffer, leaving it for next frame
510 Add them exactly as if they had been typed at the console
513 static void Cbuf_Frame_Input(void)
517 while ((line = Sys_ConsoleInput()))
518 Cbuf_AddText(cmd_local, line);
521 void Cbuf_Frame(cmd_buf_t *cbuf)
523 // check for commands typed to the host
526 // R_TimeReport("preconsole");
528 // execute commands queued with the defer command
529 Cbuf_Execute_Deferred(cbuf);
532 SV_LockThreadMutex();
534 SV_UnlockThreadMutex();
537 // R_TimeReport("console");
541 ==============================================================================
545 ==============================================================================
552 Adds command line parameters as script statements
553 Commands lead with a +, and continue until a - or another +
554 quake +prog jctest.qp +cmd amlev1
555 quake -nosound +cmd amlev1
558 static void Cmd_StuffCmds_f (cmd_state_t *cmd)
561 // this is for all commandline options combined (and is bounds checked)
562 char build[MAX_INPUTLINE];
564 if (Cmd_Argc (cmd) != 1)
566 Con_Print("stuffcmds : execute command line parameters\n");
570 // no reason to run the commandline arguments twice
571 if (host_stuffcmdsrun)
574 host_stuffcmdsrun = true;
577 for (i = 0;i < sys.argc;i++)
579 if (sys.argv[i] && sys.argv[i][0] == '+' && (sys.argv[i][1] < '0' || sys.argv[i][1] > '9') && l + strlen(sys.argv[i]) - 1 <= sizeof(build) - 1)
582 while (sys.argv[i][j])
583 build[l++] = sys.argv[i][j++];
585 for (;i < sys.argc;i++)
589 if ((sys.argv[i][0] == '+' || sys.argv[i][0] == '-') && (sys.argv[i][1] < '0' || sys.argv[i][1] > '9'))
591 if (l + strlen(sys.argv[i]) + 4 > sizeof(build) - 1)
594 if (strchr(sys.argv[i], ' '))
596 for (j = 0;sys.argv[i][j];j++)
597 build[l++] = sys.argv[i][j];
598 if (strchr(sys.argv[i], ' '))
605 // now terminate the combined string and prepend it to the command buffer
606 // we already reserved space for the terminator
608 Cbuf_InsertText (cmd, build);
611 static void Cmd_Exec(cmd_state_t *cmd, const char *filename)
614 size_t filenameLen = strlen(filename);
616 !strcmp(filename, "default.cfg") ||
617 (filenameLen >= 12 && !strcmp(filename + filenameLen - 12, "/default.cfg"));
619 if (!strcmp(filename, "config.cfg"))
621 filename = CONFIGFILENAME;
622 if (Sys_CheckParm("-noconfig"))
623 return; // don't execute config.cfg
626 f = (char *)FS_LoadFile (filename, tempmempool, false, NULL);
629 Con_Printf("couldn't exec %s\n",filename);
632 Con_Printf("execing %s\n",filename);
634 // if executing default.cfg for the first time, lock the cvar defaults
635 // it may seem backwards to insert this text BEFORE the default.cfg
636 // but Cbuf_InsertText inserts before, so this actually ends up after it.
638 Cbuf_InsertText(cmd, "\ncvar_lockdefaults\n");
640 Cbuf_InsertText (cmd, f);
645 // special defaults for specific games go here, these execute before default.cfg
646 // Nehahra pushable crates malfunction in some levels if this is on
647 // Nehahra NPC AI is confused by blowupfallenzombies
651 Cbuf_InsertText(cmd, "\n"
652 "sv_gameplayfix_blowupfallenzombies 0\n"
653 "sv_gameplayfix_findradiusdistancetobox 0\n"
654 "sv_gameplayfix_grenadebouncedownslopes 0\n"
655 "sv_gameplayfix_slidemoveprojectiles 0\n"
656 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
657 "sv_gameplayfix_setmodelrealbox 0\n"
658 "sv_gameplayfix_droptofloorstartsolid 0\n"
659 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
660 "sv_gameplayfix_noairborncorpse 0\n"
661 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
662 "sv_gameplayfix_easierwaterjump 0\n"
663 "sv_gameplayfix_delayprojectiles 0\n"
664 "sv_gameplayfix_multiplethinksperframe 0\n"
665 "sv_gameplayfix_fixedcheckwatertransition 0\n"
666 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
667 "sv_gameplayfix_swiminbmodels 0\n"
668 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
669 "sys_ticrate 0.01388889\n"
671 "r_shadow_bumpscale_basetexture 0\n"
672 "csqc_polygons_defaultmaterial_nocullface 0\n"
676 Cbuf_InsertText(cmd, "\n"
677 "sv_gameplayfix_blowupfallenzombies 0\n"
678 "sv_gameplayfix_findradiusdistancetobox 0\n"
679 "sv_gameplayfix_grenadebouncedownslopes 0\n"
680 "sv_gameplayfix_slidemoveprojectiles 0\n"
681 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
682 "sv_gameplayfix_setmodelrealbox 0\n"
683 "sv_gameplayfix_droptofloorstartsolid 0\n"
684 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
685 "sv_gameplayfix_noairborncorpse 0\n"
686 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
687 "sv_gameplayfix_easierwaterjump 0\n"
688 "sv_gameplayfix_delayprojectiles 0\n"
689 "sv_gameplayfix_multiplethinksperframe 0\n"
690 "sv_gameplayfix_fixedcheckwatertransition 0\n"
691 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
692 "sv_gameplayfix_swiminbmodels 0\n"
693 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
694 "sys_ticrate 0.01388889\n"
696 "r_shadow_bumpscale_basetexture 0\n"
697 "csqc_polygons_defaultmaterial_nocullface 0\n"
700 // hipnotic mission pack has issues in their 'friendly monster' ai, which seem to attempt to attack themselves for some reason when findradius() returns non-solid entities.
701 // hipnotic mission pack has issues with bobbing water entities 'jittering' between different heights on alternate frames at the default 0.0138889 ticrate, 0.02 avoids this issue
702 // hipnotic mission pack has issues in their proximity mine sticking code, which causes them to bounce off.
705 Cbuf_InsertText(cmd, "\n"
706 "sv_gameplayfix_blowupfallenzombies 0\n"
707 "sv_gameplayfix_findradiusdistancetobox 0\n"
708 "sv_gameplayfix_grenadebouncedownslopes 0\n"
709 "sv_gameplayfix_slidemoveprojectiles 0\n"
710 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
711 "sv_gameplayfix_setmodelrealbox 0\n"
712 "sv_gameplayfix_droptofloorstartsolid 0\n"
713 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
714 "sv_gameplayfix_noairborncorpse 0\n"
715 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
716 "sv_gameplayfix_easierwaterjump 0\n"
717 "sv_gameplayfix_delayprojectiles 0\n"
718 "sv_gameplayfix_multiplethinksperframe 0\n"
719 "sv_gameplayfix_fixedcheckwatertransition 0\n"
720 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
721 "sv_gameplayfix_swiminbmodels 0\n"
722 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
725 "r_shadow_bumpscale_basetexture 0\n"
726 "csqc_polygons_defaultmaterial_nocullface 0\n"
729 // rogue mission pack has a guardian boss that does not wake up if findradius returns one of the entities around its spawn area
731 Cbuf_InsertText(cmd, "\n"
732 "sv_gameplayfix_blowupfallenzombies 0\n"
733 "sv_gameplayfix_findradiusdistancetobox 0\n"
734 "sv_gameplayfix_grenadebouncedownslopes 0\n"
735 "sv_gameplayfix_slidemoveprojectiles 0\n"
736 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
737 "sv_gameplayfix_setmodelrealbox 0\n"
738 "sv_gameplayfix_droptofloorstartsolid 0\n"
739 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
740 "sv_gameplayfix_noairborncorpse 0\n"
741 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
742 "sv_gameplayfix_easierwaterjump 0\n"
743 "sv_gameplayfix_delayprojectiles 0\n"
744 "sv_gameplayfix_multiplethinksperframe 0\n"
745 "sv_gameplayfix_fixedcheckwatertransition 0\n"
746 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
747 "sv_gameplayfix_swiminbmodels 0\n"
748 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
749 "sys_ticrate 0.01388889\n"
751 "r_shadow_bumpscale_basetexture 0\n"
752 "csqc_polygons_defaultmaterial_nocullface 0\n"
756 Cbuf_InsertText(cmd, "\n"
757 "sv_gameplayfix_blowupfallenzombies 0\n"
758 "sv_gameplayfix_findradiusdistancetobox 0\n"
759 "sv_gameplayfix_grenadebouncedownslopes 0\n"
760 "sv_gameplayfix_slidemoveprojectiles 0\n"
761 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
762 "sv_gameplayfix_setmodelrealbox 0\n"
763 "sv_gameplayfix_droptofloorstartsolid 0\n"
764 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
765 "sv_gameplayfix_noairborncorpse 0\n"
766 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
767 "sv_gameplayfix_easierwaterjump 0\n"
768 "sv_gameplayfix_delayprojectiles 0\n"
769 "sv_gameplayfix_multiplethinksperframe 0\n"
770 "sv_gameplayfix_fixedcheckwatertransition 0\n"
771 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
772 "sv_gameplayfix_swiminbmodels 0\n"
773 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
774 "sys_ticrate 0.01388889\n"
776 "r_shadow_bumpscale_basetexture 4\n"
777 "csqc_polygons_defaultmaterial_nocullface 0\n"
781 Cbuf_InsertText(cmd, "\n"
782 "sv_gameplayfix_blowupfallenzombies 1\n"
783 "sv_gameplayfix_findradiusdistancetobox 1\n"
784 "sv_gameplayfix_grenadebouncedownslopes 1\n"
785 "sv_gameplayfix_slidemoveprojectiles 1\n"
786 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
787 "sv_gameplayfix_setmodelrealbox 1\n"
788 "sv_gameplayfix_droptofloorstartsolid 1\n"
789 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
790 "sv_gameplayfix_noairborncorpse 1\n"
791 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
792 "sv_gameplayfix_easierwaterjump 1\n"
793 "sv_gameplayfix_delayprojectiles 1\n"
794 "sv_gameplayfix_multiplethinksperframe 1\n"
795 "sv_gameplayfix_fixedcheckwatertransition 1\n"
796 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
797 "sv_gameplayfix_swiminbmodels 1\n"
798 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
799 "sys_ticrate 0.01388889\n"
800 "sv_gameplayfix_q2airaccelerate 1\n"
801 "sv_gameplayfix_stepmultipletimes 1\n"
802 "csqc_polygons_defaultmaterial_nocullface 1\n"
803 "con_chatsound_team_mask 13\n"
807 case GAME_VORETOURNAMENT:
808 // compatibility for versions prior to 2020-05-25, this can be overridden in newer versions to get the default behavior and be consistent with FTEQW engine
809 Cbuf_InsertText(cmd, "\n"
810 "csqc_polygons_defaultmaterial_nocullface 1\n"
811 "con_chatsound_team_mask 13\n"
812 "sv_gameplayfix_customstats 1\n"
815 // Steel Storm: Burning Retribution csqc misinterprets CSQC_InputEvent if type is a value other than 0 or 1
816 case GAME_STEELSTORM:
817 Cbuf_InsertText(cmd, "\n"
818 "sv_gameplayfix_blowupfallenzombies 1\n"
819 "sv_gameplayfix_findradiusdistancetobox 1\n"
820 "sv_gameplayfix_grenadebouncedownslopes 1\n"
821 "sv_gameplayfix_slidemoveprojectiles 1\n"
822 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
823 "sv_gameplayfix_setmodelrealbox 1\n"
824 "sv_gameplayfix_droptofloorstartsolid 1\n"
825 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
826 "sv_gameplayfix_noairborncorpse 1\n"
827 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
828 "sv_gameplayfix_easierwaterjump 1\n"
829 "sv_gameplayfix_delayprojectiles 1\n"
830 "sv_gameplayfix_multiplethinksperframe 1\n"
831 "sv_gameplayfix_fixedcheckwatertransition 1\n"
832 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
833 "sv_gameplayfix_swiminbmodels 1\n"
834 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
835 "sys_ticrate 0.01388889\n"
836 "cl_csqc_generatemousemoveevents 0\n"
837 "csqc_polygons_defaultmaterial_nocullface 1\n"
841 Cbuf_InsertText(cmd, "\n"
842 "sv_gameplayfix_blowupfallenzombies 1\n"
843 "sv_gameplayfix_findradiusdistancetobox 1\n"
844 "sv_gameplayfix_grenadebouncedownslopes 1\n"
845 "sv_gameplayfix_slidemoveprojectiles 1\n"
846 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
847 "sv_gameplayfix_setmodelrealbox 1\n"
848 "sv_gameplayfix_droptofloorstartsolid 1\n"
849 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
850 "sv_gameplayfix_noairborncorpse 1\n"
851 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
852 "sv_gameplayfix_easierwaterjump 1\n"
853 "sv_gameplayfix_delayprojectiles 1\n"
854 "sv_gameplayfix_multiplethinksperframe 1\n"
855 "sv_gameplayfix_fixedcheckwatertransition 1\n"
856 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
857 "sv_gameplayfix_swiminbmodels 1\n"
858 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
859 "sv_gameplayfix_stepmultipletimes 1\n"
860 "sv_gameplayfix_nogravityonground 1\n"
861 "sys_ticrate 0.01388889\n"
865 Cbuf_InsertText(cmd, "\n"
866 "sv_gameplayfix_blowupfallenzombies 1\n"
867 "sv_gameplayfix_findradiusdistancetobox 1\n"
868 "sv_gameplayfix_grenadebouncedownslopes 1\n"
869 "sv_gameplayfix_slidemoveprojectiles 1\n"
870 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
871 "sv_gameplayfix_setmodelrealbox 1\n"
872 "sv_gameplayfix_droptofloorstartsolid 1\n"
873 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
874 "sv_gameplayfix_noairborncorpse 1\n"
875 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
876 "sv_gameplayfix_easierwaterjump 1\n"
877 "sv_gameplayfix_delayprojectiles 1\n"
878 "sv_gameplayfix_multiplethinksperframe 1\n"
879 "sv_gameplayfix_fixedcheckwatertransition 1\n"
880 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
881 "sv_gameplayfix_swiminbmodels 1\n"
882 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
883 "sys_ticrate 0.01388889\n"
884 "csqc_polygons_defaultmaterial_nocullface 0\n"
896 static void Cmd_Exec_f (cmd_state_t *cmd)
901 if (Cmd_Argc(cmd) != 2)
903 Con_Print("exec <filename> : execute a script file\n");
907 s = FS_Search(Cmd_Argv(cmd, 1), true, true, NULL);
908 if(!s || !s->numfilenames)
910 Con_Printf("couldn't exec %s\n",Cmd_Argv(cmd, 1));
914 for(i = 0; i < s->numfilenames; ++i)
915 Cmd_Exec(cmd, s->filenames[i]);
925 Just prints the rest of the line to the console
928 static void Cmd_Echo_f (cmd_state_t *cmd)
932 for (i=1 ; i<Cmd_Argc(cmd) ; i++)
933 Con_Printf("%s ",Cmd_Argv(cmd, i));
938 // Support Doom3-style Toggle Console Command
943 Toggles a specified console variable amongst the values specified (default is 0 and 1)
946 static void Cmd_Toggle_f(cmd_state_t *cmd)
948 // Acquire Number of Arguments
949 int nNumArgs = Cmd_Argc(cmd);
952 // No Arguments Specified; Print Usage
953 Con_Print("Toggle Console Variable - Usage\n toggle <variable> - toggles between 0 and 1\n toggle <variable> <value> - toggles between 0 and <value>\n toggle <variable> [string 1] [string 2]...[string n] - cycles through all strings\n");
955 { // Correct Arguments Specified
956 // Acquire Potential CVar
957 cvar_t* cvCVar = Cvar_FindVar(cmd->cvars, Cmd_Argv(cmd, 1), cmd->cvars_flagsmask);
964 Cvar_SetValueQuick(cvCVar, 0);
966 Cvar_SetValueQuick(cvCVar, 1);
970 { // 0 and Specified Usage
971 if(cvCVar->integer == atoi(Cmd_Argv(cmd, 2) ) )
972 // CVar is Specified Value; // Reset to 0
973 Cvar_SetValueQuick(cvCVar, 0);
975 if(cvCVar->integer == 0)
976 // CVar is 0; Specify Value
977 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
979 // CVar does not match; Reset to 0
980 Cvar_SetValueQuick(cvCVar, 0);
983 { // Variable Values Specified
987 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
988 { // Cycle through Values
989 if( strcmp(cvCVar->string, Cmd_Argv(cmd, nCnt) ) == 0)
990 { // Current Value Located; Increment to Next
991 if( (nCnt + 1) == nNumArgs)
992 // Max Value Reached; Reset
993 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
996 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, nCnt + 1) );
1005 // Value not Found; Reset to Original
1006 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
1012 Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(cmd, 1) );
1021 Creates a new command that executes a command string (possibly ; seperated)
1024 static void Cmd_Alias_f (cmd_state_t *cmd)
1027 char line[MAX_INPUTLINE];
1032 if (Cmd_Argc(cmd) == 1)
1034 Con_Print("Current alias commands:\n");
1035 for (a = cmd->userdefined->alias ; a ; a=a->next)
1036 Con_Printf("%s : %s", a->name, a->value);
1040 s = Cmd_Argv(cmd, 1);
1041 if (strlen(s) >= MAX_ALIAS_NAME)
1043 Con_Print("Alias name is too long\n");
1047 // if the alias already exists, reuse it
1048 for (a = cmd->userdefined->alias ; a ; a=a->next)
1050 if (!strcmp(s, a->name))
1059 cmd_alias_t *prev, *current;
1061 a = (cmd_alias_t *)Z_Malloc (sizeof(cmd_alias_t));
1062 strlcpy (a->name, s, sizeof (a->name));
1063 // insert it at the right alphanumeric position
1064 for( prev = NULL, current = cmd->userdefined->alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
1069 cmd->userdefined->alias = a;
1075 // copy the rest of the command line
1076 line[0] = 0; // start out with a null string
1078 for (i=2 ; i < c ; i++)
1081 strlcat (line, " ", sizeof (line));
1082 strlcat (line, Cmd_Argv(cmd, i), sizeof (line));
1084 strlcat (line, "\n", sizeof (line));
1086 alloclen = strlen (line) + 1;
1088 line[alloclen - 2] = '\n'; // to make sure a newline is appended even if too long
1089 a->value = (char *)Z_Malloc (alloclen);
1090 memcpy (a->value, line, alloclen);
1097 Remove existing aliases.
1100 static void Cmd_UnAlias_f (cmd_state_t *cmd)
1106 if(Cmd_Argc(cmd) == 1)
1108 Con_Print("unalias: Usage: unalias alias1 [alias2 ...]\n");
1112 for(i = 1; i < Cmd_Argc(cmd); ++i)
1114 s = Cmd_Argv(cmd, i);
1116 for(a = cmd->userdefined->alias; a; p = a, a = a->next)
1118 if(!strcmp(s, a->name))
1120 if (a->initstate) // we can not remove init aliases
1122 if(a == cmd->userdefined->alias)
1123 cmd->userdefined->alias = a->next;
1132 Con_Printf("unalias: %s alias not found\n", s);
1137 =============================================================================
1141 =============================================================================
1144 static const char *Cmd_GetDirectCvarValue(cmd_state_t *cmd, const char *varname, cmd_alias_t *alias, qbool *is_multiple)
1149 static char vabuf[1024]; // cmd_mutex
1152 *is_multiple = false;
1154 if(!varname || !*varname)
1159 if(!strcmp(varname, "*"))
1162 *is_multiple = true;
1163 return Cmd_Args(cmd);
1165 else if(!strcmp(varname, "#"))
1167 return va(vabuf, sizeof(vabuf), "%d", Cmd_Argc(cmd));
1169 else if(varname[strlen(varname) - 1] == '-')
1171 argno = strtol(varname, &endptr, 10);
1172 if(endptr == varname + strlen(varname) - 1)
1174 // whole string is a number, apart from the -
1175 const char *p = Cmd_Args(cmd);
1176 for(; argno > 1; --argno)
1177 if(!COM_ParseToken_Console(&p))
1182 *is_multiple = true;
1184 // kill pre-argument whitespace
1185 for (;*p && ISWHITESPACE(*p);p++)
1194 argno = strtol(varname, &endptr, 10);
1197 // whole string is a number
1198 // NOTE: we already made sure we don't have an empty cvar name!
1199 if(argno >= 0 && argno < Cmd_Argc(cmd))
1200 return Cmd_Argv(cmd, argno);
1205 if((cvar = Cvar_FindVar(cmd->cvars, varname, cmd->cvars_flagsmask)) && !(cvar->flags & CF_PRIVATE))
1206 return cvar->string;
1211 qbool Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset, qbool putquotes)
1213 qbool quote_quot = !!strchr(quoteset, '"');
1214 qbool quote_backslash = !!strchr(quoteset, '\\');
1215 qbool quote_dollar = !!strchr(quoteset, '$');
1224 *out++ = '"'; --outlen;
1230 if(*in == '"' && quote_quot)
1234 *out++ = '\\'; --outlen;
1235 *out++ = '"'; --outlen;
1237 else if(*in == '\\' && quote_backslash)
1241 *out++ = '\\'; --outlen;
1242 *out++ = '\\'; --outlen;
1244 else if(*in == '$' && quote_dollar)
1248 *out++ = '$'; --outlen;
1249 *out++ = '$'; --outlen;
1255 *out++ = *in; --outlen;
1270 static const char *Cmd_GetCvarValue(cmd_state_t *cmd, const char *var, size_t varlen, cmd_alias_t *alias)
1272 static char varname[MAX_INPUTLINE]; // cmd_mutex
1273 static char varval[MAX_INPUTLINE]; // cmd_mutex
1274 const char *varstr = NULL;
1276 qbool required = false;
1277 qbool optional = false;
1278 static char asis[] = "asis"; // just to suppress const char warnings
1280 if(varlen >= MAX_INPUTLINE)
1281 varlen = MAX_INPUTLINE - 1;
1282 memcpy(varname, var, varlen);
1283 varname[varlen] = 0;
1284 varfunc = strchr(varname, ' ');
1296 Con_Printf(CON_WARN "Warning: Could not expand $ in alias %s\n", alias->name);
1298 Con_Printf(CON_WARN "Warning: Could not expand $\n");
1306 while((p = strchr(varfunc, '?')))
1309 memmove(p, p+1, strlen(p)); // with final NUL
1312 while((p = strchr(varfunc, '!')))
1315 memmove(p, p+1, strlen(p)); // with final NUL
1318 while((p = strchr(varfunc, ' ')))
1320 memmove(p, p+1, strlen(p)); // with final NUL
1322 // if no function is left, NULL it
1327 if(varname[0] == '$')
1328 varstr = Cmd_GetDirectCvarValue(cmd, Cmd_GetDirectCvarValue(cmd, varname + 1, alias, NULL), alias, NULL);
1331 qbool is_multiple = false;
1332 // Exception: $* and $n- don't use the quoted form by default
1333 varstr = Cmd_GetDirectCvarValue(cmd, varname, alias, &is_multiple);
1344 Con_Printf(CON_ERROR "Error: Could not expand $%s in alias %s\n", varname, alias->name);
1346 Con_Printf(CON_ERROR "Error: Could not expand $%s\n", varname);
1356 Con_Printf(CON_WARN "Warning: Could not expand $%s in alias %s\n", varname, alias->name);
1358 Con_Printf(CON_WARN "Warning: Could not expand $%s\n", varname);
1359 dpsnprintf(varval, sizeof(varval), "$%s", varname);
1364 if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
1366 // quote it so it can be used inside double quotes
1367 // we just need to replace " by \", and of course, double backslashes
1368 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\", false);
1371 else if(!strcmp(varfunc, "asis"))
1376 Con_Printf("Unknown variable function %s\n", varfunc);
1382 Cmd_PreprocessString
1384 Preprocesses strings and replaces $*, $param#, $cvar accordingly. Also strips comments.
1386 static qbool Cmd_PreprocessString(cmd_state_t *cmd, const char *intext, char *outtext, unsigned maxoutlen, cmd_alias_t *alias ) {
1392 // don't crash if there's no room in the outtext buffer
1393 if( maxoutlen == 0 ) {
1396 maxoutlen--; // because of \0
1401 while( *in && outlen < maxoutlen ) {
1403 // this is some kind of expansion, see what comes after the $
1406 // The console does the following preprocessing:
1408 // - $$ is transformed to a single dollar sign.
1409 // - $var or ${var} are expanded to the contents of the named cvar,
1410 // with quotation marks and backslashes quoted so it can safely
1411 // be used inside quotation marks (and it should always be used
1413 // - ${var asis} inserts the cvar value as is, without doing this
1415 // - ${var ?} silently expands to the empty string if
1416 // $var does not exist
1417 // - ${var !} fails expansion and executes nothing if
1418 // $var does not exist
1419 // - prefix the cvar name with a dollar sign to do indirection;
1420 // for example, if $x has the value timelimit, ${$x} will return
1421 // the value of $timelimit
1422 // - when expanding an alias, the special variable name $* refers
1423 // to all alias parameters, and a number refers to that numbered
1424 // alias parameter, where the name of the alias is $0, the first
1425 // parameter is $1 and so on; as a special case, $* inserts all
1426 // parameters, without extra quoting, so one can use $* to just
1427 // pass all parameters around. All parameters starting from $n
1428 // can be referred to as $n- (so $* is equivalent to $1-).
1429 // - ${* q} and ${n- q} force quoting anyway
1431 // Note: when expanding an alias, cvar expansion is done in the SAME step
1432 // as alias expansion so that alias parameters or cvar values containing
1433 // dollar signs have no unwanted bad side effects. However, this needs to
1434 // be accounted for when writing complex aliases. For example,
1435 // alias foo "set x NEW; echo $x"
1436 // actually expands to
1437 // "set x NEW; echo OLD"
1438 // and will print OLD! To work around this, use a second alias:
1439 // alias foo "set x NEW; foo2"
1440 // alias foo2 "echo $x"
1442 // Also note: lines starting with alias are exempt from cvar expansion.
1443 // If you want cvar expansion, write "alias" instead:
1446 // alias foo "echo $x"
1447 // "alias" bar "echo $x"
1450 // foo will print 2, because the variable $x will be expanded when the alias
1451 // gets expanded. bar will print 1, because the variable $x was expanded
1452 // at definition time. foo can be equivalently defined as
1454 // "alias" foo "echo $$x"
1456 // because at definition time, $$ will get replaced to a single $.
1461 } else if(*in == '{') {
1462 varlen = strcspn(in + 1, "}");
1463 if(in[varlen + 1] == '}')
1465 val = Cmd_GetCvarValue(cmd, in + 1, varlen, alias);
1477 varlen = strspn(in, "#*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
1478 val = Cmd_GetCvarValue(cmd, in, varlen, alias);
1485 // insert the cvar value
1486 while(*val && outlen < maxoutlen)
1487 outtext[outlen++] = *val++;
1492 // copy the unexpanded text
1493 outtext[outlen++] = '$';
1494 while(eat && outlen < maxoutlen)
1496 outtext[outlen++] = *in++;
1502 outtext[outlen++] = *in++;
1504 outtext[outlen] = 0;
1512 Called for aliases and fills in the alias into the cbuffer
1515 static void Cmd_ExecuteAlias (cmd_state_t *cmd, cmd_alias_t *alias)
1517 static char buffer[ MAX_INPUTLINE ]; // cmd_mutex
1518 static char buffer2[ MAX_INPUTLINE ]; // cmd_mutex
1519 qbool ret = Cmd_PreprocessString( cmd, alias->value, buffer, sizeof(buffer) - 2, alias );
1522 // insert at start of command buffer, so that aliases execute in order
1523 // (fixes bug introduced by Black on 20050705)
1525 // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1526 // have to make sure that no second variable expansion takes place, otherwise
1527 // alias parameters containing dollar signs can have bad effects.
1528 Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$", false);
1529 Cbuf_InsertText(cmd, buffer2);
1536 CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1537 Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1541 static void Cmd_List_f (cmd_state_t *cmd)
1543 cmd_function_t *func;
1544 const char *partial;
1549 if (Cmd_Argc(cmd) > 1)
1551 partial = Cmd_Argv(cmd, 1);
1552 len = strlen(partial);
1553 ispattern = (strchr(partial, '*') || strchr(partial, '?'));
1563 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1565 if (partial && (ispattern ? !matchpattern_with_separator(func->name, partial, false, "", false) : strncmp(partial, func->name, len)))
1567 Con_Printf("%s : %s\n", func->name, func->description);
1570 for (func = cmd->engine_functions; func; func = func->next)
1572 if (partial && (ispattern ? !matchpattern_with_separator(func->name, partial, false, "", false) : strncmp(partial, func->name, len)))
1574 Con_Printf("%s : %s\n", func->name, func->description);
1581 Con_Printf("%i Command%s matching \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1583 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1586 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1589 static void Cmd_Apropos_f(cmd_state_t *cmd)
1591 cmd_function_t *func;
1594 const char *partial;
1599 if (Cmd_Argc(cmd) > 1)
1600 partial = Cmd_Args(cmd);
1603 Con_Printf("usage: %s <string>\n",Cmd_Argv(cmd, 0));
1607 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1609 partial = va(vabuf, sizeof(vabuf), "*%s*", partial);
1612 for (cvar = cmd->cvars->vars; cvar; cvar = cvar->next)
1614 if (matchpattern_with_separator(cvar->name, partial, true, "", false) ||
1615 matchpattern_with_separator(cvar->description, partial, true, "", false))
1617 Con_Printf ("cvar ");
1618 Cvar_PrintHelp(cvar, cvar->name, true);
1621 for (char **cvar_alias = cvar->aliases; cvar_alias && *cvar_alias; cvar_alias++)
1623 if (matchpattern_with_separator(*cvar_alias, partial, true, "", false))
1625 Con_Printf ("cvar ");
1626 Cvar_PrintHelp(cvar, *cvar_alias, true);
1631 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1633 if (!matchpattern_with_separator(func->name, partial, true, "", false))
1634 if (!matchpattern_with_separator(func->description, partial, true, "", false))
1636 Con_Printf("command ^2%s^7: %s\n", func->name, func->description);
1639 for (func = cmd->engine_functions; func; func = func->next)
1641 if (!matchpattern_with_separator(func->name, partial, true, "", false))
1642 if (!matchpattern_with_separator(func->description, partial, true, "", false))
1644 Con_Printf("command ^2%s^7: %s\n", func->name, func->description);
1647 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1649 // procede here a bit differently as an alias value always got a final \n
1650 if (!matchpattern_with_separator(alias->name, partial, true, "", false))
1651 if (!matchpattern_with_separator(alias->value, partial, true, "\n", false)) // when \n is as separator wildcards don't match it
1653 Con_Printf("alias ^5%s^7: %s", alias->name, alias->value); // do not print an extra \n
1656 Con_Printf("%i result%s\n\n", count, (count > 1) ? "s" : "");
1659 static cmd_state_t *Cmd_AddInterpreter(cmd_buf_t *cbuf, cvar_state_t *cvars, int cvars_flagsmask, int cmds_flagsmask, cmd_userdefined_t *userdefined)
1661 cmd_state_t *cmd = (cmd_state_t *)Mem_Alloc(tempmempool, sizeof(cmd_state_t));
1663 cmd->mempool = Mem_AllocPool("commands", 0, NULL);
1664 // space for commands and script files
1666 cmd->null_string = "";
1669 cmd->cvars_flagsmask = cvars_flagsmask;
1670 cmd->cmd_flags = cmds_flagsmask;
1671 cmd->userdefined = userdefined;
1684 cbuf_mempool = Mem_AllocPool("Command buffer", 0, NULL);
1685 cbuf = (cmd_buf_t *)Mem_Alloc(cbuf_mempool, sizeof(cmd_buf_t));
1686 cbuf->maxsize = 655360;
1687 cbuf->lock = Thread_CreateMutex();
1691 cbuf->start.prev = cbuf->start.next = &(cbuf->start);
1692 cbuf->deferred.prev = cbuf->deferred.next = &(cbuf->deferred);
1693 cbuf->free.prev = cbuf->free.next = &(cbuf->free);
1695 // FIXME: Get rid of cmd_iter_all eventually. This is just a hack to reduce the amount of work to make the interpreters dynamic.
1696 cmd_iter_all = (cmd_iter_t *)Mem_Alloc(tempmempool, sizeof(cmd_iter_t) * 3);
1699 cmd_iter_all[0].cmd = cmd_local = Cmd_AddInterpreter(cbuf, &cvars_all, CF_CLIENT | CF_SERVER, CF_CLIENT | CF_CLIENT_FROM_SERVER | CF_SERVER_FROM_CLIENT, &cmd_userdefined_all);
1700 cmd_local->Handle = Cmd_CL_Callback;
1701 cmd_local->NotFound = NULL;
1703 // server commands received from clients have no reason to access cvars, cvar expansion seems perilous.
1704 cmd_iter_all[1].cmd = cmd_serverfromclient = Cmd_AddInterpreter(cbuf, &cvars_null, 0, CF_SERVER_FROM_CLIENT | CF_USERINFO, &cmd_userdefined_null);
1705 cmd_serverfromclient->Handle = Cmd_SV_Callback;
1706 cmd_serverfromclient->NotFound = Cmd_SV_NotFound;
1708 cmd_iter_all[2].cmd = NULL;
1710 // register our commands
1712 // client-only commands
1713 Cmd_AddCommand(CF_SHARED, "wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1714 Cmd_AddCommand(CF_CLIENT, "cprint", Cmd_Centerprint_f, "print something at the screen center");
1716 // maintenance commands used for upkeep of cvars and saved configs
1717 Cmd_AddCommand(CF_SHARED, "stuffcmds", Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1718 Cmd_AddCommand(CF_SHARED, "cvar_lockdefaults", Cvar_LockDefaults_f, "stores the current values of all cvars into their default values, only used once during startup after parsing default.cfg");
1719 Cmd_AddCommand(CF_SHARED, "cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1720 Cmd_AddCommand(CF_SHARED, "cvar_resettodefaults_nosaveonly", Cvar_ResetToDefaults_NoSaveOnly_f, "sets all non-saved cvars to their locked default values (variables that will not be saved to config.cfg)");
1721 Cmd_AddCommand(CF_SHARED, "cvar_resettodefaults_saveonly", Cvar_ResetToDefaults_SaveOnly_f, "sets all saved cvars to their locked default values (variables that will be saved to config.cfg)");
1723 // general console commands used in multiple environments
1724 Cmd_AddCommand(CF_SHARED, "exec", Cmd_Exec_f, "execute a script file");
1725 Cmd_AddCommand(CF_SHARED, "echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1726 Cmd_AddCommand(CF_SHARED, "alias",Cmd_Alias_f, "create a script function (parameters are passed in as $X (being X a number), $* for all parameters, $X- for all parameters starting from $X). Without arguments show the list of all alias");
1727 Cmd_AddCommand(CF_SHARED, "unalias",Cmd_UnAlias_f, "remove an alias");
1728 Cmd_AddCommand(CF_SHARED, "set", Cvar_Set_f, "create or change the value of a console variable");
1729 Cmd_AddCommand(CF_SHARED, "seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1730 Cmd_AddCommand(CF_SHARED, "unset", Cvar_Del_f, "delete a cvar (does not work for static ones like _cl_name, or read-only ones)");
1732 #ifdef FILLALLCVARSWITHRUBBISH
1733 Cmd_AddCommand(CF_SHARED, "fillallcvarswithrubbish", Cvar_FillAll_f, "fill all cvars with a specified number of characters to provoke buffer overruns");
1734 #endif /* FILLALLCVARSWITHRUBBISH */
1736 // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1737 // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1738 Cmd_AddCommand(CF_SHARED, "cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix or matching the specified wildcard pattern");
1739 Cmd_AddCommand(CF_SHARED, "cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix or matching the specified wildcard pattern");
1740 Cmd_AddCommand(CF_SHARED, "apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1741 Cmd_AddCommand(CF_SHARED, "find", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1743 Cmd_AddCommand(CF_SHARED, "defer", Cmd_Defer_f, "execute a command in the future");
1746 // Support Doom3-style Toggle Command
1747 Cmd_AddCommand(CF_SHARED | CF_CLIENT_FROM_SERVER, "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1755 void Cmd_Shutdown(void)
1757 cmd_iter_t *cmd_iter;
1758 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
1760 cmd_state_t *cmd = cmd_iter->cmd;
1762 if (cmd->cbuf->lock)
1764 // we usually have this locked when we get here from Host_Quit_f
1765 Cbuf_Unlock(cmd->cbuf);
1768 Mem_FreePool(&cmd->mempool);
1777 int Cmd_Argc (cmd_state_t *cmd)
1787 const char *Cmd_Argv(cmd_state_t *cmd, int arg)
1789 if (arg >= cmd->argc )
1790 return cmd->null_string;
1791 return cmd->argv[arg];
1799 const char *Cmd_Args (cmd_state_t *cmd)
1808 Parses the given string into command line tokens.
1811 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1812 static void Cmd_TokenizeString (cmd_state_t *cmd, const char *text)
1818 cmd->cmdline = NULL;
1822 // skip whitespace up to a /n
1823 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1830 if (*text == '\n' || *text == '\r')
1832 // a newline separates commands in the buffer
1833 if (*text == '\r' && text[1] == '\n')
1843 cmd->cmdline = text;
1847 if (!COM_ParseToken_Console(&text))
1850 if (cmd->argc < MAX_ARGS)
1852 l = (int)strlen(com_token) + 1;
1853 if (cmd->cbuf->tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1855 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguments\n", CMD_TOKENIZELENGTH);
1858 memcpy (cmd->cbuf->tokenizebuffer + cmd->cbuf->tokenizebufferpos, com_token, l);
1859 cmd->argv[cmd->argc] = cmd->cbuf->tokenizebuffer + cmd->cbuf->tokenizebufferpos;
1860 cmd->cbuf->tokenizebufferpos += l;
1872 void Cmd_AddCommand(int flags, const char *cmd_name, xcommand_t function, const char *description)
1874 cmd_function_t *func;
1875 cmd_function_t *prev, *current;
1879 for (i = 0; i < 2; i++)
1881 cmd = cmd_iter_all[i].cmd;
1882 if (flags & cmd->cmd_flags)
1884 // fail if the command is a variable name
1885 if (Cvar_FindVar(cmd->cvars, cmd_name, ~0))
1887 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1893 // fail if the command already exists in this interpreter
1894 for (func = cmd->engine_functions; func; func = func->next)
1896 if (!strcmp(cmd_name, func->name))
1898 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1903 func = (cmd_function_t *)Mem_Alloc(cmd->mempool, sizeof(cmd_function_t));
1904 func->flags = flags;
1905 func->name = cmd_name;
1906 func->function = function;
1907 func->description = description;
1908 func->next = cmd->engine_functions;
1910 // insert it at the right alphanumeric position
1911 for (prev = NULL, current = cmd->engine_functions; current && strcmp(current->name, func->name) < 0; prev = current, current = current->next)
1917 cmd->engine_functions = func;
1919 func->next = current;
1923 // mark qcfunc if the function already exists in the qc_functions list
1924 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1926 if (!strcmp(cmd_name, func->name))
1928 func->qcfunc = true; //[515]: csqc
1934 func = (cmd_function_t *)Mem_Alloc(cmd->mempool, sizeof(cmd_function_t));
1935 func->flags = flags;
1936 func->name = cmd_name;
1937 func->function = function;
1938 func->description = description;
1939 func->qcfunc = true; //[515]: csqc
1940 func->next = cmd->userdefined->qc_functions;
1942 // insert it at the right alphanumeric position
1943 for (prev = NULL, current = cmd->userdefined->qc_functions; current && strcmp(current->name, func->name) < 0; prev = current, current = current->next)
1949 cmd->userdefined->qc_functions = func;
1951 func->next = current;
1962 qbool Cmd_Exists (cmd_state_t *cmd, const char *cmd_name)
1964 cmd_function_t *func;
1966 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1967 if (!strcmp(cmd_name, func->name))
1970 for (func=cmd->engine_functions ; func ; func=func->next)
1971 if (!strcmp (cmd_name,func->name))
1983 const char *Cmd_CompleteCommand (cmd_state_t *cmd, const char *partial)
1985 cmd_function_t *func;
1988 len = strlen(partial);
1994 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1995 if (!strncasecmp(partial, func->name, len))
1998 for (func = cmd->engine_functions; func; func = func->next)
1999 if (!strncasecmp(partial, func->name, len))
2006 Cmd_CompleteCountPossible
2008 New function for tab-completion system
2009 Added by EvilTypeGuy
2010 Thanks to Fett erich@heintz.com
2014 int Cmd_CompleteCountPossible (cmd_state_t *cmd, const char *partial)
2016 cmd_function_t *func;
2021 len = strlen(partial);
2026 // Loop through the command list and count all partial matches
2027 for (func = cmd->userdefined->qc_functions; func; func = func->next)
2028 if (!strncasecmp(partial, func->name, len))
2031 for (func = cmd->engine_functions; func; func = func->next)
2032 if (!strncasecmp(partial, func->name, len))
2039 Cmd_CompleteBuildList
2041 New function for tab-completion system
2042 Added by EvilTypeGuy
2043 Thanks to Fett erich@heintz.com
2047 const char **Cmd_CompleteBuildList (cmd_state_t *cmd, const char *partial)
2049 cmd_function_t *func;
2052 size_t sizeofbuf = (Cmd_CompleteCountPossible (cmd, partial) + 1) * sizeof (const char *);
2055 len = strlen(partial);
2056 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
2057 // Loop through the functions lists and print all matches
2058 for (func = cmd->userdefined->qc_functions; func; func = func->next)
2059 if (!strncasecmp(partial, func->name, len))
2060 buf[bpos++] = func->name;
2061 for (func = cmd->engine_functions; func; func = func->next)
2062 if (!strncasecmp(partial, func->name, len))
2063 buf[bpos++] = func->name;
2069 // written by LadyHavoc
2070 void Cmd_CompleteCommandPrint (cmd_state_t *cmd, const char *partial)
2072 cmd_function_t *func;
2073 size_t len = strlen(partial);
2074 // Loop through the command list and print all matches
2075 for (func = cmd->userdefined->qc_functions; func; func = func->next)
2076 if (!strncasecmp(partial, func->name, len))
2077 Con_Printf("^2%s^7: %s\n", func->name, func->description);
2078 for (func = cmd->engine_functions; func; func = func->next)
2079 if (!strncasecmp(partial, func->name, len))
2080 Con_Printf("^2%s^7: %s\n", func->name, func->description);
2086 New function for tab-completion system
2087 Added by EvilTypeGuy
2088 Thanks to Fett erich@heintz.com
2092 const char *Cmd_CompleteAlias (cmd_state_t *cmd, const char *partial)
2097 len = strlen(partial);
2103 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2104 if (!strncasecmp(partial, alias->name, len))
2110 // written by LadyHavoc
2111 void Cmd_CompleteAliasPrint (cmd_state_t *cmd, const char *partial)
2114 size_t len = strlen(partial);
2115 // Loop through the alias list and print all matches
2116 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2117 if (!strncasecmp(partial, alias->name, len))
2118 Con_Printf("^5%s^7: %s", alias->name, alias->value);
2123 Cmd_CompleteAliasCountPossible
2125 New function for tab-completion system
2126 Added by EvilTypeGuy
2127 Thanks to Fett erich@heintz.com
2131 int Cmd_CompleteAliasCountPossible (cmd_state_t *cmd, const char *partial)
2139 len = strlen(partial);
2144 // Loop through the command list and count all partial matches
2145 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2146 if (!strncasecmp(partial, alias->name, len))
2153 Cmd_CompleteAliasBuildList
2155 New function for tab-completion system
2156 Added by EvilTypeGuy
2157 Thanks to Fett erich@heintz.com
2161 const char **Cmd_CompleteAliasBuildList (cmd_state_t *cmd, const char *partial)
2166 size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (cmd, partial) + 1) * sizeof (const char *);
2169 len = strlen(partial);
2170 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
2171 // Loop through the alias list and print all matches
2172 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2173 if (!strncasecmp(partial, alias->name, len))
2174 buf[bpos++] = alias->name;
2180 // TODO: Make this more generic?
2181 void Cmd_ClearCSQCCommands (cmd_state_t *cmd)
2183 cmd_function_t *func;
2184 cmd_function_t **next = &cmd->userdefined->qc_functions;
2194 extern cvar_t sv_cheats;
2197 * Cloudwalk FIXME: This idea sounded great in my head but...
2198 * How do we handle commands that can be received by the client,
2199 * but which the server can also execute locally?
2201 * If we create a callback where the engine will forward to server
2202 * but try to execute the command locally if it's dedicated,
2203 * we're back to intermixing client and server code which I'm
2204 * trying to avoid. There's no other way I can think of to
2205 * implement that behavior that doesn't involve an #ifdef, or
2206 * making a mess of hooks.
2208 qbool Cmd_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2211 func->function(cmd);
2213 Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(cmd, 0));
2217 qbool Cmd_CL_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2219 // TODO: Assign these functions to QC commands directly?
2222 if(((func->flags & CF_CLIENT) && CL_VM_ConsoleCommand(text)) ||
2223 ((func->flags & CF_SERVER) && SV_VM_ConsoleCommand(text)))
2226 if (func->flags & CF_SERVER_FROM_CLIENT)
2228 if(host_isclient.integer)
2230 CL_ForwardToServer_f(cmd);
2233 else if(!(func->flags & CF_SERVER))
2235 Con_Printf("Cannot execute client commands from a dedicated server console.\n");
2239 return Cmd_Callback(cmd, func, text, src);
2242 qbool Cmd_SV_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2244 if(func->qcfunc && (func->flags & CF_SERVER))
2245 return SV_VM_ConsoleCommand(text);
2246 else if (src == src_client)
2248 if((func->flags & CF_CHEAT) && !sv_cheats.integer)
2249 SV_ClientPrintf("No cheats allowed. The server must have sv_cheats set to 1\n");
2251 func->function(cmd);
2257 qbool Cmd_SV_NotFound(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2259 if (cmd->source == src_client)
2261 Con_Printf("Client \"%s\" tried to execute \"%s\"\n", host_client->name, text);
2270 A complete command line has been parsed, so try to execute it
2271 FIXME: lookupnoadd the token to speed search?
2274 void Cmd_ExecuteString (cmd_state_t *cmd, const char *text, cmd_source_t src, qbool lockmutex)
2277 cmd_function_t *func;
2280 Cbuf_Lock(cmd->cbuf);
2281 oldpos = cmd->cbuf->tokenizebufferpos;
2284 Cmd_TokenizeString (cmd, text);
2286 // execute the command line
2288 goto done; // no tokens
2291 for (func = cmd->userdefined->qc_functions; func; func = func->next)
2293 if (!strcasecmp(cmd->argv[0], func->name))
2295 if(cmd->Handle(cmd, func, text, src))
2300 for (func = cmd->engine_functions; func; func=func->next)
2302 if (!strcasecmp (cmd->argv[0], func->name))
2304 if(cmd->Handle(cmd, func, text, src))
2309 // if it's a client command and no command was found, say so.
2312 if(cmd->NotFound(cmd, func, text, src))
2317 for (a=cmd->userdefined->alias ; a ; a=a->next)
2319 if (!strcasecmp (cmd->argv[0], a->name))
2321 Cmd_ExecuteAlias(cmd, a);
2327 if (!Cvar_Command(cmd) && host.framecount > 0)
2328 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(cmd, 0));
2330 cmd->cbuf->tokenizebufferpos = oldpos;
2332 Cbuf_Unlock(cmd->cbuf);
2339 Returns the position (1 to argc-1) in the command's argument list
2340 where the given parameter apears, or 0 if not present
2344 int Cmd_CheckParm (cmd_state_t *cmd, const char *parm)
2350 Con_Printf ("Cmd_CheckParm: NULL");
2354 for (i = 1; i < Cmd_Argc (cmd); i++)
2355 if (!strcasecmp (parm, Cmd_Argv(cmd, i)))
2363 void Cmd_SaveInitState(void)
2365 cmd_iter_t *cmd_iter;
2366 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
2368 cmd_state_t *cmd = cmd_iter->cmd;
2371 for (f = cmd->userdefined->qc_functions; f; f = f->next)
2372 f->initstate = true;
2373 for (f = cmd->engine_functions; f; f = f->next)
2374 f->initstate = true;
2375 for (a = cmd->userdefined->alias; a; a = a->next)
2377 a->initstate = true;
2378 a->initialvalue = Mem_strdup(zonemempool, a->value);
2381 Cvar_SaveInitState(&cvars_all);
2384 void Cmd_RestoreInitState(void)
2386 cmd_iter_t *cmd_iter;
2387 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
2389 cmd_state_t *cmd = cmd_iter->cmd;
2390 cmd_function_t *f, **fp;
2391 cmd_alias_t *a, **ap;
2392 for (fp = &cmd->userdefined->qc_functions; (f = *fp);)
2398 // destroy this command, it didn't exist at init
2399 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
2404 for (fp = &cmd->engine_functions; (f = *fp);)
2410 // destroy this command, it didn't exist at init
2411 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
2416 for (ap = &cmd->userdefined->alias; (a = *ap);)
2420 // restore this alias, it existed at init
2421 if (strcmp(a->value ? a->value : "", a->initialvalue ? a->initialvalue : ""))
2423 Con_DPrintf("Cmd_RestoreInitState: Restoring alias %s\n", a->name);
2426 a->value = Mem_strdup(zonemempool, a->initialvalue);
2432 // free this alias, it didn't exist at init...
2433 Con_DPrintf("Cmd_RestoreInitState: Destroying alias %s\n", a->name);
2441 Cvar_RestoreInitState(&cvars_all);
2444 void Cmd_NoOperation_f(cmd_state_t *cmd)