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");
89 List_For_Each_Entry(current, &cbuf->deferred, cmd_input_t, list)
90 Con_Printf("-> In %9.2f: %s\n", current->delay, current->text);
93 else if(Cmd_Argc(cmd) == 2 && !strcasecmp("clear", Cmd_Argv(cmd, 1)))
95 while(!List_Is_Empty(&cbuf->deferred))
96 List_Move_Tail(cbuf->deferred.next, &cbuf->free);
98 else if(Cmd_Argc(cmd) == 3)
100 const char *text = Cmd_Argv(cmd, 2);
101 current = Cbuf_LinkGet(cbuf, NULL);
102 current->length = strlen(text);
103 current->source = cmd;
104 current->delay = atof(Cmd_Argv(cmd, 1));
106 if(current->size < current->length)
108 current->text = (char *)Mem_Realloc(cbuf_mempool, current->text, current->length + 1);
109 current->size = current->length;
112 strlcpy(current->text, text, current->length + 1);
114 List_Move_Tail(¤t->list, &cbuf->deferred);
118 Con_Printf("usage: defer <seconds> <command>\n"
128 Print something to the center of the screen using SCR_Centerprint
131 static void Cmd_Centerprint_f (cmd_state_t *cmd)
133 char msg[MAX_INPUTLINE];
134 unsigned int i, c, p;
138 strlcpy(msg, Cmd_Argv(cmd,1), sizeof(msg));
139 for(i = 2; i < c; ++i)
141 strlcat(msg, " ", sizeof(msg));
142 strlcat(msg, Cmd_Argv(cmd, i), sizeof(msg));
144 c = (unsigned int)strlen(msg);
145 for(p = 0, i = 0; i < c; ++i)
151 else if(msg[i+1] == '\\')
163 SCR_CenterPrint(msg);
168 =============================================================================
172 =============================================================================
175 static cmd_input_t *Cbuf_LinkGet(cmd_buf_t *cbuf, cmd_input_t *existing)
177 cmd_input_t *ret = NULL;
178 if(existing && existing->pending)
180 else if(!List_Is_Empty(&cbuf->free))
182 ret = List_Entry(cbuf->free.next, cmd_input_t, list);
184 ret->pending = false;
189 static cmd_input_t *Cmd_AllocInputNode(void)
191 cmd_input_t *node = (cmd_input_t *)Mem_Alloc(cbuf_mempool, sizeof(cmd_input_t));
192 node->list.prev = node->list.next = &node->list;
193 node->size = node->length = node->pending = 0;
198 // Cloudwalk FIXME: The entire design of this thing is overly complicated.
199 // We could very much safely have one input node per line whether or not
200 // the command was terminated. We don't need to split up input nodes per command
202 static size_t Cmd_ParseInput (cmd_input_t **output, char **input)
204 size_t pos, cmdsize = 0, start = 0;
205 qbool command = false, lookahead = false;
206 qbool quotes = false, comment = false;
207 qbool escaped = false;
210 * The Quake command-line is super basic. It can be entered in the console
211 * or in config files. A semicolon is used to terminate a command and chain
212 * them together. Otherwise, a newline delineates command input.
214 * In most engines, the Quake command-line is a simple linear text buffer that
215 * is parsed when it executes. In Darkplaces, we use a linked list of command
216 * input and parse the input on the spot.
218 * This was done because Darkplaces allows multiple command interpreters on the
219 * same thread. Previously, each interpreter maintained its own buffer and this
220 * caused problems related to execution order, and maintaining a single simple
221 * buffer for all interpreters makes it non-trivial to keep track of which
222 * command should execute on which interpreter.
225 // Run until command and lookahead are both true, or until we run out of input.
226 for (pos = 0; (*input)[pos]; pos++)
228 // Look for newlines and semicolons. Ignore semicolons in quotes.
229 switch((*input)[pos])
237 if(!comment) // Not a newline so far. Still not a valid command yet.
239 if(!quotes && (*input)[pos] == ';') // Ignore semicolons in quotes.
241 else if (ISCOMMENT((*input), pos)) // Comments
256 switch((*input)[pos])
265 if (!escaped && quotes)
274 if(cmdsize && !command)
277 if(command && lookahead)
286 *output = Cmd_AllocInputNode();
288 // Append, since this input line hasn't closed yet.
289 if((*output)->pending)
290 offset = (*output)->length;
292 (*output)->length += cmdsize;
294 if((*output)->size < (*output)->length)
296 (*output)->text = (char *)Mem_Realloc(cbuf_mempool, (*output)->text, (*output)->length + 1);
297 (*output)->size = (*output)->length;
300 strlcpy(&(*output)->text[offset], &(*input)[start], cmdsize + 1);
303 * If we were still looking ahead by the time we broke from the loop, the command input
304 * hasn't terminated yet and we're still expecting more, so keep this node open for appending later.
306 (*output)->pending = !lookahead;
309 // Set input to its new position. Can be NULL.
310 *input = &(*input)[pos];
315 // Cloudwalk: Not happy with this, but it works.
316 static void Cbuf_LinkCreate(cmd_state_t *cmd, llist_t *head, cmd_input_t *existing, const char *text)
318 char *in = (char *)&text[0];
319 cmd_buf_t *cbuf = cmd->cbuf;
320 size_t totalsize = 0, newsize = 0;
321 cmd_input_t *current = NULL;
323 // Slide the pointer down until we reach the end
326 // Check if the current node is still accepting input (input line hasn't terminated)
327 current = Cbuf_LinkGet(cbuf, existing);
328 newsize = Cmd_ParseInput(¤t, &in);
333 // current will match existing if the input line hasn't terminated yet
334 if(current != existing)
336 current->source = cmd;
337 List_Move_Tail(¤t->list, head);
340 totalsize += newsize;
342 else if (current == existing && !totalsize)
343 current->pending = false;
347 cbuf->size += totalsize;
354 Adds command text at the end of the buffer
357 void Cbuf_AddText (cmd_state_t *cmd, const char *text)
359 size_t l = strlen(text);
360 cmd_buf_t *cbuf = cmd->cbuf;
361 llist_t llist = {&llist, &llist};
365 if (cbuf->maxsize - cbuf->size <= l)
366 Con_Print("Cbuf_AddText: overflow\n");
369 Cbuf_LinkCreate(cmd, &llist, (List_Is_Empty(&cbuf->start) ? NULL : List_Entry(cbuf->start.prev, cmd_input_t, list)), text);
370 if(!List_Is_Empty(&llist))
371 List_Splice_Tail(&llist, &cbuf->start);
380 Adds command text immediately after the current command
381 FIXME: actually change the command buffer to do less copying
384 void Cbuf_InsertText (cmd_state_t *cmd, const char *text)
386 cmd_buf_t *cbuf = cmd->cbuf;
387 llist_t llist = {&llist, &llist};
388 size_t l = strlen(text);
392 // we need to memmove the existing text and stuff this in before it...
393 if (cbuf->size + l >= cbuf->maxsize)
394 Con_Print("Cbuf_InsertText: overflow\n");
397 Cbuf_LinkCreate(cmd, &llist, (List_Is_Empty(&cbuf->start) ? NULL : List_Entry(cbuf->start.next, cmd_input_t, list)), text);
398 if(!List_Is_Empty(&llist))
399 List_Splice(&llist, &cbuf->start);
407 Cbuf_Execute_Deferred --blub
410 static void Cbuf_Execute_Deferred (cmd_buf_t *cbuf)
412 cmd_input_t *current;
415 if (host.realtime - cbuf->deferred_oldtime < 0 || host.realtime - cbuf->deferred_oldtime > 1800)
416 cbuf->deferred_oldtime = host.realtime;
417 eat = host.realtime - cbuf->deferred_oldtime;
418 if (eat < (1.0 / 120.0))
420 cbuf->deferred_oldtime = host.realtime;
422 List_For_Each_Entry(current, &cbuf->deferred, cmd_input_t, list)
424 current->delay -= eat;
425 if(current->delay <= 0)
427 cbuf->size += current->length;
428 List_Move(¤t->list, &cbuf->start);
429 // We must return and come back next frame or the engine will freeze. Fragile... like glass :3
440 static qbool Cmd_PreprocessString(cmd_state_t *cmd, const char *intext, char *outtext, unsigned maxoutlen, cmd_alias_t *alias );
441 void Cbuf_Execute (cmd_buf_t *cbuf)
443 cmd_input_t *current;
444 char preprocessed[MAX_INPUTLINE];
447 // LadyHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
448 cbuf->tokenizebufferpos = 0;
450 while (!List_Is_Empty(&cbuf->start))
453 * Delete the text from the command buffer and move remaining
454 * commands down. This is necessary because commands (exec, alias)
455 * can insert data at the beginning of the text buffer
457 current = List_Entry(cbuf->start.next, cmd_input_t, list);
459 // Recycle memory so using WASD doesn't cause a malloc and free
460 List_Move_Tail(¤t->list, &cbuf->free);
463 * Assume we're rolling with the current command-line and
464 * always set this false because alias expansion or cbuf insertion
465 * without a newline may set this true, and cause weirdness.
467 current->pending = false;
469 cbuf->size -= current->length;
471 firstchar = current->text;
472 while(*firstchar && ISWHITESPACE(*firstchar))
474 if((strncmp(firstchar, "alias", 5) || !ISWHITESPACE(firstchar[5])) &&
475 (strncmp(firstchar, "bind", 4) || !ISWHITESPACE(firstchar[4])) &&
476 (strncmp(firstchar, "in_bind", 7) || !ISWHITESPACE(firstchar[7])))
478 if(Cmd_PreprocessString(current->source, current->text, preprocessed, sizeof(preprocessed), NULL ))
479 Cmd_ExecuteString(current->source, preprocessed, src_local, false);
483 Cmd_ExecuteString (current->source, current->text, src_local, false);
491 * Skip out while text still remains in
492 * buffer, leaving it for next frame
504 Add them exactly as if they had been typed at the console
507 static void Cbuf_Frame_Input(void)
511 while ((line = Sys_ConsoleInput()))
512 Cbuf_AddText(cmd_local, line);
515 void Cbuf_Frame(cmd_buf_t *cbuf)
517 // check for commands typed to the host
520 // R_TimeReport("preconsole");
522 // execute commands queued with the defer command
523 Cbuf_Execute_Deferred(cbuf);
526 SV_LockThreadMutex();
528 SV_UnlockThreadMutex();
531 // R_TimeReport("console");
535 ==============================================================================
539 ==============================================================================
546 Adds command line parameters as script statements
547 Commands lead with a +, and continue until a - or another +
548 quake +prog jctest.qp +cmd amlev1
549 quake -nosound +cmd amlev1
552 static void Cmd_StuffCmds_f (cmd_state_t *cmd)
555 // this is for all commandline options combined (and is bounds checked)
556 char build[MAX_INPUTLINE];
558 if (Cmd_Argc (cmd) != 1)
560 Con_Print("stuffcmds : execute command line parameters\n");
564 // no reason to run the commandline arguments twice
565 if (host_stuffcmdsrun)
568 host_stuffcmdsrun = true;
571 for (i = 0;i < sys.argc;i++)
573 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)
576 while (sys.argv[i][j])
577 build[l++] = sys.argv[i][j++];
579 for (;i < sys.argc;i++)
583 if ((sys.argv[i][0] == '+' || sys.argv[i][0] == '-') && (sys.argv[i][1] < '0' || sys.argv[i][1] > '9'))
585 if (l + strlen(sys.argv[i]) + 4 > sizeof(build) - 1)
588 if (strchr(sys.argv[i], ' '))
590 for (j = 0;sys.argv[i][j];j++)
591 build[l++] = sys.argv[i][j];
592 if (strchr(sys.argv[i], ' '))
599 // now terminate the combined string and prepend it to the command buffer
600 // we already reserved space for the terminator
602 Cbuf_InsertText (cmd, build);
605 static void Cmd_Exec(cmd_state_t *cmd, const char *filename)
608 size_t filenameLen = strlen(filename);
610 !strcmp(filename, "default.cfg") ||
611 (filenameLen >= 12 && !strcmp(filename + filenameLen - 12, "/default.cfg"));
613 if (!strcmp(filename, "config.cfg"))
615 filename = CONFIGFILENAME;
616 if (Sys_CheckParm("-noconfig"))
617 return; // don't execute config.cfg
620 f = (char *)FS_LoadFile (filename, tempmempool, false, NULL);
623 Con_Printf("couldn't exec %s\n",filename);
626 Con_Printf("execing %s\n",filename);
628 // if executing default.cfg for the first time, lock the cvar defaults
629 // it may seem backwards to insert this text BEFORE the default.cfg
630 // but Cbuf_InsertText inserts before, so this actually ends up after it.
632 Cbuf_InsertText(cmd, "\ncvar_lockdefaults\n");
634 Cbuf_InsertText (cmd, f);
639 // special defaults for specific games go here, these execute before default.cfg
640 // Nehahra pushable crates malfunction in some levels if this is on
641 // Nehahra NPC AI is confused by blowupfallenzombies
645 Cbuf_InsertText(cmd, "\n"
646 "sv_gameplayfix_blowupfallenzombies 0\n"
647 "sv_gameplayfix_findradiusdistancetobox 0\n"
648 "sv_gameplayfix_grenadebouncedownslopes 0\n"
649 "sv_gameplayfix_slidemoveprojectiles 0\n"
650 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
651 "sv_gameplayfix_setmodelrealbox 0\n"
652 "sv_gameplayfix_droptofloorstartsolid 0\n"
653 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
654 "sv_gameplayfix_noairborncorpse 0\n"
655 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
656 "sv_gameplayfix_easierwaterjump 0\n"
657 "sv_gameplayfix_delayprojectiles 0\n"
658 "sv_gameplayfix_multiplethinksperframe 0\n"
659 "sv_gameplayfix_fixedcheckwatertransition 0\n"
660 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
661 "sv_gameplayfix_swiminbmodels 0\n"
662 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
663 "sys_ticrate 0.01388889\n"
665 "r_shadow_bumpscale_basetexture 0\n"
666 "csqc_polygons_defaultmaterial_nocullface 0\n"
670 Cbuf_InsertText(cmd, "\n"
671 "sv_gameplayfix_blowupfallenzombies 0\n"
672 "sv_gameplayfix_findradiusdistancetobox 0\n"
673 "sv_gameplayfix_grenadebouncedownslopes 0\n"
674 "sv_gameplayfix_slidemoveprojectiles 0\n"
675 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
676 "sv_gameplayfix_setmodelrealbox 0\n"
677 "sv_gameplayfix_droptofloorstartsolid 0\n"
678 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
679 "sv_gameplayfix_noairborncorpse 0\n"
680 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
681 "sv_gameplayfix_easierwaterjump 0\n"
682 "sv_gameplayfix_delayprojectiles 0\n"
683 "sv_gameplayfix_multiplethinksperframe 0\n"
684 "sv_gameplayfix_fixedcheckwatertransition 0\n"
685 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
686 "sv_gameplayfix_swiminbmodels 0\n"
687 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
688 "sys_ticrate 0.01388889\n"
690 "r_shadow_bumpscale_basetexture 0\n"
691 "csqc_polygons_defaultmaterial_nocullface 0\n"
694 // 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.
695 // 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
696 // hipnotic mission pack has issues in their proximity mine sticking code, which causes them to bounce off.
699 Cbuf_InsertText(cmd, "\n"
700 "sv_gameplayfix_blowupfallenzombies 0\n"
701 "sv_gameplayfix_findradiusdistancetobox 0\n"
702 "sv_gameplayfix_grenadebouncedownslopes 0\n"
703 "sv_gameplayfix_slidemoveprojectiles 0\n"
704 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
705 "sv_gameplayfix_setmodelrealbox 0\n"
706 "sv_gameplayfix_droptofloorstartsolid 0\n"
707 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
708 "sv_gameplayfix_noairborncorpse 0\n"
709 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
710 "sv_gameplayfix_easierwaterjump 0\n"
711 "sv_gameplayfix_delayprojectiles 0\n"
712 "sv_gameplayfix_multiplethinksperframe 0\n"
713 "sv_gameplayfix_fixedcheckwatertransition 0\n"
714 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
715 "sv_gameplayfix_swiminbmodels 0\n"
716 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
719 "r_shadow_bumpscale_basetexture 0\n"
720 "csqc_polygons_defaultmaterial_nocullface 0\n"
723 // rogue mission pack has a guardian boss that does not wake up if findradius returns one of the entities around its spawn area
725 Cbuf_InsertText(cmd, "\n"
726 "sv_gameplayfix_blowupfallenzombies 0\n"
727 "sv_gameplayfix_findradiusdistancetobox 0\n"
728 "sv_gameplayfix_grenadebouncedownslopes 0\n"
729 "sv_gameplayfix_slidemoveprojectiles 0\n"
730 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
731 "sv_gameplayfix_setmodelrealbox 0\n"
732 "sv_gameplayfix_droptofloorstartsolid 0\n"
733 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
734 "sv_gameplayfix_noairborncorpse 0\n"
735 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
736 "sv_gameplayfix_easierwaterjump 0\n"
737 "sv_gameplayfix_delayprojectiles 0\n"
738 "sv_gameplayfix_multiplethinksperframe 0\n"
739 "sv_gameplayfix_fixedcheckwatertransition 0\n"
740 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
741 "sv_gameplayfix_swiminbmodels 0\n"
742 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
743 "sys_ticrate 0.01388889\n"
745 "r_shadow_bumpscale_basetexture 0\n"
746 "csqc_polygons_defaultmaterial_nocullface 0\n"
750 Cbuf_InsertText(cmd, "\n"
751 "sv_gameplayfix_blowupfallenzombies 0\n"
752 "sv_gameplayfix_findradiusdistancetobox 0\n"
753 "sv_gameplayfix_grenadebouncedownslopes 0\n"
754 "sv_gameplayfix_slidemoveprojectiles 0\n"
755 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
756 "sv_gameplayfix_setmodelrealbox 0\n"
757 "sv_gameplayfix_droptofloorstartsolid 0\n"
758 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
759 "sv_gameplayfix_noairborncorpse 0\n"
760 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
761 "sv_gameplayfix_easierwaterjump 0\n"
762 "sv_gameplayfix_delayprojectiles 0\n"
763 "sv_gameplayfix_multiplethinksperframe 0\n"
764 "sv_gameplayfix_fixedcheckwatertransition 0\n"
765 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
766 "sv_gameplayfix_swiminbmodels 0\n"
767 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
768 "sys_ticrate 0.01388889\n"
770 "r_shadow_bumpscale_basetexture 4\n"
771 "csqc_polygons_defaultmaterial_nocullface 0\n"
775 Cbuf_InsertText(cmd, "\n"
776 "sv_gameplayfix_blowupfallenzombies 1\n"
777 "sv_gameplayfix_findradiusdistancetobox 1\n"
778 "sv_gameplayfix_grenadebouncedownslopes 1\n"
779 "sv_gameplayfix_slidemoveprojectiles 1\n"
780 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
781 "sv_gameplayfix_setmodelrealbox 1\n"
782 "sv_gameplayfix_droptofloorstartsolid 1\n"
783 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
784 "sv_gameplayfix_noairborncorpse 1\n"
785 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
786 "sv_gameplayfix_easierwaterjump 1\n"
787 "sv_gameplayfix_delayprojectiles 1\n"
788 "sv_gameplayfix_multiplethinksperframe 1\n"
789 "sv_gameplayfix_fixedcheckwatertransition 1\n"
790 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
791 "sv_gameplayfix_swiminbmodels 1\n"
792 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
793 "sys_ticrate 0.01388889\n"
794 "sv_gameplayfix_q2airaccelerate 1\n"
795 "sv_gameplayfix_stepmultipletimes 1\n"
796 "csqc_polygons_defaultmaterial_nocullface 1\n"
797 "con_chatsound_team_mask 13\n"
801 case GAME_VORETOURNAMENT:
802 // 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
803 Cbuf_InsertText(cmd, "\n"
804 "csqc_polygons_defaultmaterial_nocullface 1\n"
805 "con_chatsound_team_mask 13\n"
806 "sv_gameplayfix_customstats 1\n"
807 "mod_q1bsp_zero_hullsize_cutoff 8.03125\n"
810 // Steel Storm: Burning Retribution csqc misinterprets CSQC_InputEvent if type is a value other than 0 or 1
811 case GAME_STEELSTORM:
812 Cbuf_InsertText(cmd, "\n"
813 "sv_gameplayfix_blowupfallenzombies 1\n"
814 "sv_gameplayfix_findradiusdistancetobox 1\n"
815 "sv_gameplayfix_grenadebouncedownslopes 1\n"
816 "sv_gameplayfix_slidemoveprojectiles 1\n"
817 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
818 "sv_gameplayfix_setmodelrealbox 1\n"
819 "sv_gameplayfix_droptofloorstartsolid 1\n"
820 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
821 "sv_gameplayfix_noairborncorpse 1\n"
822 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
823 "sv_gameplayfix_easierwaterjump 1\n"
824 "sv_gameplayfix_delayprojectiles 1\n"
825 "sv_gameplayfix_multiplethinksperframe 1\n"
826 "sv_gameplayfix_fixedcheckwatertransition 1\n"
827 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
828 "sv_gameplayfix_swiminbmodels 1\n"
829 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
830 "sys_ticrate 0.01388889\n"
831 "cl_csqc_generatemousemoveevents 0\n"
832 "csqc_polygons_defaultmaterial_nocullface 1\n"
836 Cbuf_InsertText(cmd, "\n"
837 "sv_gameplayfix_blowupfallenzombies 1\n"
838 "sv_gameplayfix_findradiusdistancetobox 1\n"
839 "sv_gameplayfix_grenadebouncedownslopes 1\n"
840 "sv_gameplayfix_slidemoveprojectiles 1\n"
841 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
842 "sv_gameplayfix_setmodelrealbox 1\n"
843 "sv_gameplayfix_droptofloorstartsolid 1\n"
844 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
845 "sv_gameplayfix_noairborncorpse 1\n"
846 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
847 "sv_gameplayfix_easierwaterjump 1\n"
848 "sv_gameplayfix_delayprojectiles 1\n"
849 "sv_gameplayfix_multiplethinksperframe 1\n"
850 "sv_gameplayfix_fixedcheckwatertransition 1\n"
851 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
852 "sv_gameplayfix_swiminbmodels 1\n"
853 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
854 "sys_ticrate 0.01388889\n"
855 "csqc_polygons_defaultmaterial_nocullface 0\n"
867 static void Cmd_Exec_f (cmd_state_t *cmd)
872 if (Cmd_Argc(cmd) != 2)
874 Con_Print("exec <filename> : execute a script file\n");
878 s = FS_Search(Cmd_Argv(cmd, 1), true, true, NULL);
879 if(!s || !s->numfilenames)
881 Con_Printf("couldn't exec %s\n",Cmd_Argv(cmd, 1));
885 for(i = 0; i < s->numfilenames; ++i)
886 Cmd_Exec(cmd, s->filenames[i]);
896 Just prints the rest of the line to the console
899 static void Cmd_Echo_f (cmd_state_t *cmd)
903 for (i=1 ; i<Cmd_Argc(cmd) ; i++)
904 Con_Printf("%s ",Cmd_Argv(cmd, i));
909 // Support Doom3-style Toggle Console Command
914 Toggles a specified console variable amongst the values specified (default is 0 and 1)
917 static void Cmd_Toggle_f(cmd_state_t *cmd)
919 // Acquire Number of Arguments
920 int nNumArgs = Cmd_Argc(cmd);
923 // No Arguments Specified; Print Usage
924 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");
926 { // Correct Arguments Specified
927 // Acquire Potential CVar
928 cvar_t* cvCVar = Cvar_FindVar(cmd->cvars, Cmd_Argv(cmd, 1), cmd->cvars_flagsmask);
935 Cvar_SetValueQuick(cvCVar, 0);
937 Cvar_SetValueQuick(cvCVar, 1);
941 { // 0 and Specified Usage
942 if(cvCVar->integer == atoi(Cmd_Argv(cmd, 2) ) )
943 // CVar is Specified Value; // Reset to 0
944 Cvar_SetValueQuick(cvCVar, 0);
946 if(cvCVar->integer == 0)
947 // CVar is 0; Specify Value
948 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
950 // CVar does not match; Reset to 0
951 Cvar_SetValueQuick(cvCVar, 0);
954 { // Variable Values Specified
958 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
959 { // Cycle through Values
960 if( strcmp(cvCVar->string, Cmd_Argv(cmd, nCnt) ) == 0)
961 { // Current Value Located; Increment to Next
962 if( (nCnt + 1) == nNumArgs)
963 // Max Value Reached; Reset
964 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
967 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, nCnt + 1) );
976 // Value not Found; Reset to Original
977 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
983 Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(cmd, 1) );
992 Creates a new command that executes a command string (possibly ; seperated)
995 static void Cmd_Alias_f (cmd_state_t *cmd)
998 char line[MAX_INPUTLINE];
1003 if (Cmd_Argc(cmd) == 1)
1005 Con_Print("Current alias commands:\n");
1006 for (a = cmd->userdefined->alias ; a ; a=a->next)
1007 Con_Printf("%s : %s", a->name, a->value);
1011 s = Cmd_Argv(cmd, 1);
1012 if (strlen(s) >= MAX_ALIAS_NAME)
1014 Con_Print("Alias name is too long\n");
1018 // if the alias already exists, reuse it
1019 for (a = cmd->userdefined->alias ; a ; a=a->next)
1021 if (!strcmp(s, a->name))
1030 cmd_alias_t *prev, *current;
1032 a = (cmd_alias_t *)Z_Malloc (sizeof(cmd_alias_t));
1033 strlcpy (a->name, s, sizeof (a->name));
1034 // insert it at the right alphanumeric position
1035 for( prev = NULL, current = cmd->userdefined->alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
1040 cmd->userdefined->alias = a;
1046 // copy the rest of the command line
1047 line[0] = 0; // start out with a null string
1049 for (i=2 ; i < c ; i++)
1052 strlcat (line, " ", sizeof (line));
1053 strlcat (line, Cmd_Argv(cmd, i), sizeof (line));
1055 strlcat (line, "\n", sizeof (line));
1057 alloclen = strlen (line) + 1;
1059 line[alloclen - 2] = '\n'; // to make sure a newline is appended even if too long
1060 a->value = (char *)Z_Malloc (alloclen);
1061 memcpy (a->value, line, alloclen);
1068 Remove existing aliases.
1071 static void Cmd_UnAlias_f (cmd_state_t *cmd)
1077 if(Cmd_Argc(cmd) == 1)
1079 Con_Print("unalias: Usage: unalias alias1 [alias2 ...]\n");
1083 for(i = 1; i < Cmd_Argc(cmd); ++i)
1085 s = Cmd_Argv(cmd, i);
1087 for(a = cmd->userdefined->alias; a; p = a, a = a->next)
1089 if(!strcmp(s, a->name))
1091 if (a->initstate) // we can not remove init aliases
1093 if(a == cmd->userdefined->alias)
1094 cmd->userdefined->alias = a->next;
1103 Con_Printf("unalias: %s alias not found\n", s);
1108 =============================================================================
1112 =============================================================================
1115 static const char *Cmd_GetDirectCvarValue(cmd_state_t *cmd, const char *varname, cmd_alias_t *alias, qbool *is_multiple)
1120 static char vabuf[1024]; // cmd_mutex
1123 *is_multiple = false;
1125 if(!varname || !*varname)
1130 if(!strcmp(varname, "*"))
1133 *is_multiple = true;
1134 return Cmd_Args(cmd);
1136 else if(!strcmp(varname, "#"))
1138 return va(vabuf, sizeof(vabuf), "%d", Cmd_Argc(cmd));
1140 else if(varname[strlen(varname) - 1] == '-')
1142 argno = strtol(varname, &endptr, 10);
1143 if(endptr == varname + strlen(varname) - 1)
1145 // whole string is a number, apart from the -
1146 const char *p = Cmd_Args(cmd);
1147 for(; argno > 1; --argno)
1148 if(!COM_ParseToken_Console(&p))
1153 *is_multiple = true;
1155 // kill pre-argument whitespace
1156 for (;*p && ISWHITESPACE(*p);p++)
1165 argno = strtol(varname, &endptr, 10);
1168 // whole string is a number
1169 // NOTE: we already made sure we don't have an empty cvar name!
1170 if(argno >= 0 && argno < Cmd_Argc(cmd))
1171 return Cmd_Argv(cmd, argno);
1176 if((cvar = Cvar_FindVar(cmd->cvars, varname, cmd->cvars_flagsmask)) && !(cvar->flags & CF_PRIVATE))
1177 return cvar->string;
1182 qbool Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset, qbool putquotes)
1184 qbool quote_quot = !!strchr(quoteset, '"');
1185 qbool quote_backslash = !!strchr(quoteset, '\\');
1186 qbool quote_dollar = !!strchr(quoteset, '$');
1195 *out++ = '"'; --outlen;
1201 if(*in == '"' && quote_quot)
1205 *out++ = '\\'; --outlen;
1206 *out++ = '"'; --outlen;
1208 else if(*in == '\\' && quote_backslash)
1212 *out++ = '\\'; --outlen;
1213 *out++ = '\\'; --outlen;
1215 else if(*in == '$' && quote_dollar)
1219 *out++ = '$'; --outlen;
1220 *out++ = '$'; --outlen;
1226 *out++ = *in; --outlen;
1241 static const char *Cmd_GetCvarValue(cmd_state_t *cmd, const char *var, size_t varlen, cmd_alias_t *alias)
1243 static char varname[MAX_INPUTLINE]; // cmd_mutex
1244 static char varval[MAX_INPUTLINE]; // cmd_mutex
1245 const char *varstr = NULL;
1247 qbool required = false;
1248 qbool optional = false;
1249 static char asis[] = "asis"; // just to suppress const char warnings
1251 if(varlen >= MAX_INPUTLINE)
1252 varlen = MAX_INPUTLINE - 1;
1253 memcpy(varname, var, varlen);
1254 varname[varlen] = 0;
1255 varfunc = strchr(varname, ' ');
1267 Con_Printf(CON_WARN "Warning: Could not expand $ in alias %s\n", alias->name);
1269 Con_Printf(CON_WARN "Warning: Could not expand $\n");
1277 while((p = strchr(varfunc, '?')))
1280 memmove(p, p+1, strlen(p)); // with final NUL
1283 while((p = strchr(varfunc, '!')))
1286 memmove(p, p+1, strlen(p)); // with final NUL
1289 while((p = strchr(varfunc, ' ')))
1291 memmove(p, p+1, strlen(p)); // with final NUL
1293 // if no function is left, NULL it
1298 if(varname[0] == '$')
1299 varstr = Cmd_GetDirectCvarValue(cmd, Cmd_GetDirectCvarValue(cmd, varname + 1, alias, NULL), alias, NULL);
1302 qbool is_multiple = false;
1303 // Exception: $* and $n- don't use the quoted form by default
1304 varstr = Cmd_GetDirectCvarValue(cmd, varname, alias, &is_multiple);
1315 Con_Printf(CON_ERROR "Error: Could not expand $%s in alias %s\n", varname, alias->name);
1317 Con_Printf(CON_ERROR "Error: Could not expand $%s\n", varname);
1327 Con_Printf(CON_WARN "Warning: Could not expand $%s in alias %s\n", varname, alias->name);
1329 Con_Printf(CON_WARN "Warning: Could not expand $%s\n", varname);
1330 dpsnprintf(varval, sizeof(varval), "$%s", varname);
1335 if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
1337 // quote it so it can be used inside double quotes
1338 // we just need to replace " by \", and of course, double backslashes
1339 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\", false);
1342 else if(!strcmp(varfunc, "asis"))
1347 Con_Printf("Unknown variable function %s\n", varfunc);
1353 Cmd_PreprocessString
1355 Preprocesses strings and replaces $*, $param#, $cvar accordingly. Also strips comments.
1357 static qbool Cmd_PreprocessString(cmd_state_t *cmd, const char *intext, char *outtext, unsigned maxoutlen, cmd_alias_t *alias ) {
1363 // don't crash if there's no room in the outtext buffer
1364 if( maxoutlen == 0 ) {
1367 maxoutlen--; // because of \0
1372 while( *in && outlen < maxoutlen ) {
1374 // this is some kind of expansion, see what comes after the $
1377 // The console does the following preprocessing:
1379 // - $$ is transformed to a single dollar sign.
1380 // - $var or ${var} are expanded to the contents of the named cvar,
1381 // with quotation marks and backslashes quoted so it can safely
1382 // be used inside quotation marks (and it should always be used
1384 // - ${var asis} inserts the cvar value as is, without doing this
1386 // - ${var ?} silently expands to the empty string if
1387 // $var does not exist
1388 // - ${var !} fails expansion and executes nothing if
1389 // $var does not exist
1390 // - prefix the cvar name with a dollar sign to do indirection;
1391 // for example, if $x has the value timelimit, ${$x} will return
1392 // the value of $timelimit
1393 // - when expanding an alias, the special variable name $* refers
1394 // to all alias parameters, and a number refers to that numbered
1395 // alias parameter, where the name of the alias is $0, the first
1396 // parameter is $1 and so on; as a special case, $* inserts all
1397 // parameters, without extra quoting, so one can use $* to just
1398 // pass all parameters around. All parameters starting from $n
1399 // can be referred to as $n- (so $* is equivalent to $1-).
1400 // - ${* q} and ${n- q} force quoting anyway
1402 // Note: when expanding an alias, cvar expansion is done in the SAME step
1403 // as alias expansion so that alias parameters or cvar values containing
1404 // dollar signs have no unwanted bad side effects. However, this needs to
1405 // be accounted for when writing complex aliases. For example,
1406 // alias foo "set x NEW; echo $x"
1407 // actually expands to
1408 // "set x NEW; echo OLD"
1409 // and will print OLD! To work around this, use a second alias:
1410 // alias foo "set x NEW; foo2"
1411 // alias foo2 "echo $x"
1413 // Also note: lines starting with alias are exempt from cvar expansion.
1414 // If you want cvar expansion, write "alias" instead:
1417 // alias foo "echo $x"
1418 // "alias" bar "echo $x"
1421 // foo will print 2, because the variable $x will be expanded when the alias
1422 // gets expanded. bar will print 1, because the variable $x was expanded
1423 // at definition time. foo can be equivalently defined as
1425 // "alias" foo "echo $$x"
1427 // because at definition time, $$ will get replaced to a single $.
1432 } else if(*in == '{') {
1433 varlen = strcspn(in + 1, "}");
1434 if(in[varlen + 1] == '}')
1436 val = Cmd_GetCvarValue(cmd, in + 1, varlen, alias);
1448 varlen = strspn(in, "#*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
1449 val = Cmd_GetCvarValue(cmd, in, varlen, alias);
1456 // insert the cvar value
1457 while(*val && outlen < maxoutlen)
1458 outtext[outlen++] = *val++;
1463 // copy the unexpanded text
1464 outtext[outlen++] = '$';
1465 while(eat && outlen < maxoutlen)
1467 outtext[outlen++] = *in++;
1473 outtext[outlen++] = *in++;
1475 outtext[outlen] = 0;
1483 Called for aliases and fills in the alias into the cbuffer
1486 static void Cmd_ExecuteAlias (cmd_state_t *cmd, cmd_alias_t *alias)
1488 static char buffer[ MAX_INPUTLINE ]; // cmd_mutex
1489 static char buffer2[ MAX_INPUTLINE ]; // cmd_mutex
1490 qbool ret = Cmd_PreprocessString( cmd, alias->value, buffer, sizeof(buffer) - 2, alias );
1493 // insert at start of command buffer, so that aliases execute in order
1494 // (fixes bug introduced by Black on 20050705)
1496 // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1497 // have to make sure that no second variable expansion takes place, otherwise
1498 // alias parameters containing dollar signs can have bad effects.
1499 Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$", false);
1500 Cbuf_InsertText(cmd, buffer2);
1507 CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1508 Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1512 static void Cmd_List_f (cmd_state_t *cmd)
1514 cmd_function_t *func;
1515 const char *partial;
1520 if (Cmd_Argc(cmd) > 1)
1522 partial = Cmd_Argv(cmd, 1);
1523 len = strlen(partial);
1524 ispattern = (strchr(partial, '*') || strchr(partial, '?'));
1534 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1536 if (partial && (ispattern ? !matchpattern_with_separator(func->name, partial, false, "", false) : strncmp(partial, func->name, len)))
1538 Con_Printf("%s : %s\n", func->name, func->description);
1541 for (func = cmd->engine_functions; func; func = func->next)
1543 if (partial && (ispattern ? !matchpattern_with_separator(func->name, partial, false, "", false) : strncmp(partial, func->name, len)))
1545 Con_Printf("%s : %s\n", func->name, func->description);
1552 Con_Printf("%i Command%s matching \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1554 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1557 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1560 static void Cmd_Apropos_f(cmd_state_t *cmd)
1562 cmd_function_t *func;
1565 const char *partial;
1570 if (Cmd_Argc(cmd) > 1)
1571 partial = Cmd_Args(cmd);
1574 Con_Printf("usage: %s <string>\n",Cmd_Argv(cmd, 0));
1578 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1580 partial = va(vabuf, sizeof(vabuf), "*%s*", partial);
1583 for (cvar = cmd->cvars->vars; cvar; cvar = cvar->next)
1585 if (matchpattern_with_separator(cvar->name, partial, true, "", false) ||
1586 matchpattern_with_separator(cvar->description, partial, true, "", false))
1588 Con_Printf ("cvar ");
1589 Cvar_PrintHelp(cvar, cvar->name, true);
1592 for (char **cvar_alias = cvar->aliases; cvar_alias && *cvar_alias; cvar_alias++)
1594 if (matchpattern_with_separator(*cvar_alias, partial, true, "", false))
1596 Con_Printf ("cvar ");
1597 Cvar_PrintHelp(cvar, *cvar_alias, true);
1602 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1604 if (!matchpattern_with_separator(func->name, partial, true, "", false))
1605 if (!matchpattern_with_separator(func->description, partial, true, "", false))
1607 Con_Printf("command ^2%s^7: %s\n", func->name, func->description);
1610 for (func = cmd->engine_functions; func; func = func->next)
1612 if (!matchpattern_with_separator(func->name, partial, true, "", false))
1613 if (!matchpattern_with_separator(func->description, partial, true, "", false))
1615 Con_Printf("command ^2%s^7: %s\n", func->name, func->description);
1618 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1620 // procede here a bit differently as an alias value always got a final \n
1621 if (!matchpattern_with_separator(alias->name, partial, true, "", false))
1622 if (!matchpattern_with_separator(alias->value, partial, true, "\n", false)) // when \n is as separator wildcards don't match it
1624 Con_Printf("alias ^5%s^7: %s", alias->name, alias->value); // do not print an extra \n
1627 Con_Printf("%i result%s\n\n", count, (count > 1) ? "s" : "");
1630 static cmd_state_t *Cmd_AddInterpreter(cmd_buf_t *cbuf, cvar_state_t *cvars, int cvars_flagsmask, int cmds_flagsmask, cmd_userdefined_t *userdefined)
1632 cmd_state_t *cmd = (cmd_state_t *)Mem_Alloc(tempmempool, sizeof(cmd_state_t));
1634 cmd->mempool = Mem_AllocPool("commands", 0, NULL);
1635 // space for commands and script files
1637 cmd->null_string = "";
1640 cmd->cvars_flagsmask = cvars_flagsmask;
1641 cmd->cmd_flags = cmds_flagsmask;
1642 cmd->userdefined = userdefined;
1655 cbuf_mempool = Mem_AllocPool("Command buffer", 0, NULL);
1656 cbuf = (cmd_buf_t *)Mem_Alloc(cbuf_mempool, sizeof(cmd_buf_t));
1657 cbuf->maxsize = 655360;
1658 cbuf->lock = Thread_CreateMutex();
1662 cbuf->start.prev = cbuf->start.next = &(cbuf->start);
1663 cbuf->deferred.prev = cbuf->deferred.next = &(cbuf->deferred);
1664 cbuf->free.prev = cbuf->free.next = &(cbuf->free);
1666 // FIXME: Get rid of cmd_iter_all eventually. This is just a hack to reduce the amount of work to make the interpreters dynamic.
1667 cmd_iter_all = (cmd_iter_t *)Mem_Alloc(tempmempool, sizeof(cmd_iter_t) * 3);
1670 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);
1671 cmd_local->Handle = Cmd_CL_Callback;
1672 cmd_local->NotFound = NULL;
1674 // server commands received from clients have no reason to access cvars, cvar expansion seems perilous.
1675 cmd_iter_all[1].cmd = cmd_serverfromclient = Cmd_AddInterpreter(cbuf, &cvars_null, 0, CF_SERVER_FROM_CLIENT | CF_USERINFO, &cmd_userdefined_null);
1676 cmd_serverfromclient->Handle = Cmd_SV_Callback;
1677 cmd_serverfromclient->NotFound = Cmd_SV_NotFound;
1679 cmd_iter_all[2].cmd = NULL;
1681 // register our commands
1683 // client-only commands
1684 Cmd_AddCommand(CF_SHARED, "wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1685 Cmd_AddCommand(CF_CLIENT, "cprint", Cmd_Centerprint_f, "print something at the screen center");
1687 // maintenance commands used for upkeep of cvars and saved configs
1688 Cmd_AddCommand(CF_SHARED, "stuffcmds", Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1689 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");
1690 Cmd_AddCommand(CF_SHARED, "cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1691 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)");
1692 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)");
1694 // general console commands used in multiple environments
1695 Cmd_AddCommand(CF_SHARED, "exec", Cmd_Exec_f, "execute a script file");
1696 Cmd_AddCommand(CF_SHARED, "echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1697 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");
1698 Cmd_AddCommand(CF_SHARED, "unalias",Cmd_UnAlias_f, "remove an alias");
1699 Cmd_AddCommand(CF_SHARED, "set", Cvar_Set_f, "create or change the value of a console variable");
1700 Cmd_AddCommand(CF_SHARED, "seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1701 Cmd_AddCommand(CF_SHARED, "unset", Cvar_Del_f, "delete a cvar (does not work for static ones like _cl_name, or read-only ones)");
1703 #ifdef FILLALLCVARSWITHRUBBISH
1704 Cmd_AddCommand(CF_SHARED, "fillallcvarswithrubbish", Cvar_FillAll_f, "fill all cvars with a specified number of characters to provoke buffer overruns");
1705 #endif /* FILLALLCVARSWITHRUBBISH */
1707 // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1708 // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1709 Cmd_AddCommand(CF_SHARED, "cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix or matching the specified wildcard pattern");
1710 Cmd_AddCommand(CF_SHARED, "cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix or matching the specified wildcard pattern");
1711 Cmd_AddCommand(CF_SHARED, "apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1712 Cmd_AddCommand(CF_SHARED, "find", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1714 Cmd_AddCommand(CF_SHARED, "defer", Cmd_Defer_f, "execute a command in the future");
1717 // Support Doom3-style Toggle Command
1718 Cmd_AddCommand(CF_SHARED | CF_CLIENT_FROM_SERVER, "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1726 void Cmd_Shutdown(void)
1728 cmd_iter_t *cmd_iter;
1729 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
1731 cmd_state_t *cmd = cmd_iter->cmd;
1733 if (cmd->cbuf->lock)
1735 // we usually have this locked when we get here from Host_Quit_f
1736 Cbuf_Unlock(cmd->cbuf);
1739 Mem_FreePool(&cmd->mempool);
1748 int Cmd_Argc (cmd_state_t *cmd)
1758 const char *Cmd_Argv(cmd_state_t *cmd, int arg)
1760 if (arg >= cmd->argc )
1761 return cmd->null_string;
1762 return cmd->argv[arg];
1770 const char *Cmd_Args (cmd_state_t *cmd)
1779 Parses the given string into command line tokens.
1782 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1783 static void Cmd_TokenizeString (cmd_state_t *cmd, const char *text)
1789 cmd->cmdline = NULL;
1793 // skip whitespace up to a /n
1794 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1801 if (*text == '\n' || *text == '\r')
1803 // a newline separates commands in the buffer
1804 if (*text == '\r' && text[1] == '\n')
1814 cmd->cmdline = text;
1818 if (!COM_ParseToken_Console(&text))
1821 if (cmd->argc < MAX_ARGS)
1823 l = (int)strlen(com_token) + 1;
1824 if (cmd->cbuf->tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1826 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguments\n", CMD_TOKENIZELENGTH);
1829 memcpy (cmd->cbuf->tokenizebuffer + cmd->cbuf->tokenizebufferpos, com_token, l);
1830 cmd->argv[cmd->argc] = cmd->cbuf->tokenizebuffer + cmd->cbuf->tokenizebufferpos;
1831 cmd->cbuf->tokenizebufferpos += l;
1843 void Cmd_AddCommand(int flags, const char *cmd_name, xcommand_t function, const char *description)
1845 cmd_function_t *func;
1846 cmd_function_t *prev, *current;
1850 for (i = 0; i < 2; i++)
1852 cmd = cmd_iter_all[i].cmd;
1853 if (flags & cmd->cmd_flags)
1855 // fail if the command is a variable name
1856 if (Cvar_FindVar(cmd->cvars, cmd_name, ~0))
1858 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1864 // fail if the command already exists in this interpreter
1865 for (func = cmd->engine_functions; func; func = func->next)
1867 if (!strcmp(cmd_name, func->name))
1869 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1874 func = (cmd_function_t *)Mem_Alloc(cmd->mempool, sizeof(cmd_function_t));
1875 func->flags = flags;
1876 func->name = cmd_name;
1877 func->function = function;
1878 func->description = description;
1879 func->next = cmd->engine_functions;
1881 // insert it at the right alphanumeric position
1882 for (prev = NULL, current = cmd->engine_functions; current && strcmp(current->name, func->name) < 0; prev = current, current = current->next)
1888 cmd->engine_functions = func;
1890 func->next = current;
1894 // mark qcfunc if the function already exists in the qc_functions list
1895 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1897 if (!strcmp(cmd_name, func->name))
1899 func->qcfunc = true; //[515]: csqc
1904 func = (cmd_function_t *)Mem_Alloc(cmd->mempool, sizeof(cmd_function_t));
1905 func->flags = flags;
1906 func->name = cmd_name;
1907 func->function = function;
1908 func->description = description;
1909 func->qcfunc = true; //[515]: csqc
1910 func->next = cmd->userdefined->qc_functions;
1912 // bones_was_here: if this QC command overrides an engine command, store its pointer
1913 // to avoid doing this search at invocation if QC declines to handle this command.
1914 for (cmd_function_t *f = cmd->engine_functions; f; f = f->next)
1916 if (!strcmp(cmd_name, f->name))
1918 Con_DPrintf("Adding QC override of engine command %s\n", cmd_name);
1919 func->overridden = f;
1924 // insert it at the right alphanumeric position
1925 for (prev = NULL, current = cmd->userdefined->qc_functions; current && strcmp(current->name, func->name) < 0; prev = current, current = current->next)
1931 cmd->userdefined->qc_functions = func;
1933 func->next = current;
1944 qbool Cmd_Exists (cmd_state_t *cmd, const char *cmd_name)
1946 cmd_function_t *func;
1948 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1949 if (!strcmp(cmd_name, func->name))
1952 for (func=cmd->engine_functions ; func ; func=func->next)
1953 if (!strcmp (cmd_name,func->name))
1965 const char *Cmd_CompleteCommand (cmd_state_t *cmd, const char *partial)
1967 cmd_function_t *func;
1970 len = strlen(partial);
1976 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1977 if (!strncasecmp(partial, func->name, len))
1980 for (func = cmd->engine_functions; func; func = func->next)
1981 if (!strncasecmp(partial, func->name, len))
1988 Cmd_CompleteCountPossible
1990 New function for tab-completion system
1991 Added by EvilTypeGuy
1992 Thanks to Fett erich@heintz.com
1996 int Cmd_CompleteCountPossible (cmd_state_t *cmd, const char *partial)
1998 cmd_function_t *func;
2003 len = strlen(partial);
2008 // Loop through the command list and count all partial matches
2009 for (func = cmd->userdefined->qc_functions; func; func = func->next)
2010 if (!strncasecmp(partial, func->name, len))
2013 for (func = cmd->engine_functions; func; func = func->next)
2014 if (!strncasecmp(partial, func->name, len))
2021 Cmd_CompleteBuildList
2023 New function for tab-completion system
2024 Added by EvilTypeGuy
2025 Thanks to Fett erich@heintz.com
2029 const char **Cmd_CompleteBuildList (cmd_state_t *cmd, const char *partial)
2031 cmd_function_t *func;
2034 size_t sizeofbuf = (Cmd_CompleteCountPossible (cmd, partial) + 1) * sizeof (const char *);
2037 len = strlen(partial);
2038 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
2039 // Loop through the functions lists and print all matches
2040 for (func = cmd->userdefined->qc_functions; func; func = func->next)
2041 if (!strncasecmp(partial, func->name, len))
2042 buf[bpos++] = func->name;
2043 for (func = cmd->engine_functions; func; func = func->next)
2044 if (!strncasecmp(partial, func->name, len))
2045 buf[bpos++] = func->name;
2051 // written by LadyHavoc
2052 void Cmd_CompleteCommandPrint (cmd_state_t *cmd, const char *partial)
2054 cmd_function_t *func;
2055 size_t len = strlen(partial);
2056 // Loop through the command list and print all matches
2057 for (func = cmd->userdefined->qc_functions; func; func = func->next)
2058 if (!strncasecmp(partial, func->name, len))
2059 Con_Printf("^2%s^7: %s\n", func->name, func->description);
2060 for (func = cmd->engine_functions; func; func = func->next)
2061 if (!strncasecmp(partial, func->name, len))
2062 Con_Printf("^2%s^7: %s\n", func->name, func->description);
2068 New function for tab-completion system
2069 Added by EvilTypeGuy
2070 Thanks to Fett erich@heintz.com
2074 const char *Cmd_CompleteAlias (cmd_state_t *cmd, const char *partial)
2079 len = strlen(partial);
2085 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2086 if (!strncasecmp(partial, alias->name, len))
2092 // written by LadyHavoc
2093 void Cmd_CompleteAliasPrint (cmd_state_t *cmd, const char *partial)
2096 size_t len = strlen(partial);
2097 // Loop through the alias list and print all matches
2098 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2099 if (!strncasecmp(partial, alias->name, len))
2100 Con_Printf("^5%s^7: %s", alias->name, alias->value);
2105 Cmd_CompleteAliasCountPossible
2107 New function for tab-completion system
2108 Added by EvilTypeGuy
2109 Thanks to Fett erich@heintz.com
2113 int Cmd_CompleteAliasCountPossible (cmd_state_t *cmd, const char *partial)
2121 len = strlen(partial);
2126 // Loop through the command list and count all partial matches
2127 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2128 if (!strncasecmp(partial, alias->name, len))
2135 Cmd_CompleteAliasBuildList
2137 New function for tab-completion system
2138 Added by EvilTypeGuy
2139 Thanks to Fett erich@heintz.com
2143 const char **Cmd_CompleteAliasBuildList (cmd_state_t *cmd, const char *partial)
2148 size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (cmd, partial) + 1) * sizeof (const char *);
2151 len = strlen(partial);
2152 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
2153 // Loop through the alias list and print all matches
2154 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2155 if (!strncasecmp(partial, alias->name, len))
2156 buf[bpos++] = alias->name;
2162 // TODO: Make this more generic?
2163 void Cmd_ClearCSQCCommands (cmd_state_t *cmd)
2165 cmd_function_t *func;
2166 cmd_function_t **next = &cmd->userdefined->qc_functions;
2176 extern cvar_t sv_cheats;
2179 * Cloudwalk FIXME: This idea sounded great in my head but...
2180 * How do we handle commands that can be received by the client,
2181 * but which the server can also execute locally?
2183 * If we create a callback where the engine will forward to server
2184 * but try to execute the command locally if it's dedicated,
2185 * we're back to intermixing client and server code which I'm
2186 * trying to avoid. There's no other way I can think of to
2187 * implement that behavior that doesn't involve an #ifdef, or
2188 * making a mess of hooks.
2190 qbool Cmd_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2193 func->function(cmd);
2195 Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(cmd, 0));
2199 qbool Cmd_CL_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2201 // TODO: Assign these functions to QC commands directly?
2204 if(((func->flags & CF_CLIENT) && CL_VM_ConsoleCommand(text)) ||
2205 ((func->flags & CF_SERVER) && SV_VM_ConsoleCommand(text)))
2208 if (func->overridden) // If this QC command overrides an engine command,
2209 func = func->overridden; // fall back to that command.
2211 if (func->flags & CF_SERVER_FROM_CLIENT)
2213 if(host_isclient.integer)
2215 CL_ForwardToServer_f(cmd);
2218 else if(!(func->flags & CF_SERVER))
2220 Con_Printf("Cannot execute client commands from a dedicated server console.\n");
2224 return Cmd_Callback(cmd, func, text, src);
2227 qbool Cmd_SV_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2229 if(func->qcfunc && (func->flags & CF_SERVER))
2230 return SV_VM_ConsoleCommand(text);
2231 else if (src == src_client)
2233 if((func->flags & CF_CHEAT) && !sv_cheats.integer)
2234 SV_ClientPrintf("No cheats allowed. The server must have sv_cheats set to 1\n");
2236 func->function(cmd);
2242 qbool Cmd_SV_NotFound(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2244 if (cmd->source == src_client)
2246 Con_Printf("Client \"%s\" tried to execute \"%s\"\n", host_client->name, text);
2255 A complete command line has been parsed, so try to execute it
2256 FIXME: lookupnoadd the token to speed search?
2259 void Cmd_ExecuteString (cmd_state_t *cmd, const char *text, cmd_source_t src, qbool lockmutex)
2262 cmd_function_t *func;
2265 Cbuf_Lock(cmd->cbuf);
2266 oldpos = cmd->cbuf->tokenizebufferpos;
2269 Cmd_TokenizeString (cmd, text);
2271 // execute the command line
2273 goto done; // no tokens
2276 for (func = cmd->userdefined->qc_functions; func; func = func->next)
2278 if (!strcasecmp(cmd->argv[0], func->name))
2280 if(cmd->Handle(cmd, func, text, src))
2285 for (func = cmd->engine_functions; func; func=func->next)
2287 if (!strcasecmp (cmd->argv[0], func->name))
2289 if(cmd->Handle(cmd, func, text, src))
2294 // if it's a client command and no command was found, say so.
2297 if(cmd->NotFound(cmd, func, text, src))
2302 for (a=cmd->userdefined->alias ; a ; a=a->next)
2304 if (!strcasecmp (cmd->argv[0], a->name))
2306 Cmd_ExecuteAlias(cmd, a);
2312 if (!Cvar_Command(cmd) && host.framecount > 0)
2313 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(cmd, 0));
2315 cmd->cbuf->tokenizebufferpos = oldpos;
2317 Cbuf_Unlock(cmd->cbuf);
2324 Returns the position (1 to argc-1) in the command's argument list
2325 where the given parameter apears, or 0 if not present
2329 int Cmd_CheckParm (cmd_state_t *cmd, const char *parm)
2335 Con_Printf ("Cmd_CheckParm: NULL");
2339 for (i = 1; i < Cmd_Argc (cmd); i++)
2340 if (!strcasecmp (parm, Cmd_Argv(cmd, i)))
2348 void Cmd_SaveInitState(void)
2350 cmd_iter_t *cmd_iter;
2351 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
2353 cmd_state_t *cmd = cmd_iter->cmd;
2356 for (f = cmd->userdefined->qc_functions; f; f = f->next)
2357 f->initstate = true;
2358 for (f = cmd->engine_functions; f; f = f->next)
2359 f->initstate = true;
2360 for (a = cmd->userdefined->alias; a; a = a->next)
2362 a->initstate = true;
2363 a->initialvalue = Mem_strdup(zonemempool, a->value);
2366 Cvar_SaveInitState(&cvars_all);
2369 void Cmd_RestoreInitState(void)
2371 cmd_iter_t *cmd_iter;
2372 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
2374 cmd_state_t *cmd = cmd_iter->cmd;
2375 cmd_function_t *f, **fp;
2376 cmd_alias_t *a, **ap;
2377 for (fp = &cmd->userdefined->qc_functions; (f = *fp);)
2383 // destroy this command, it didn't exist at init
2384 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
2389 for (fp = &cmd->engine_functions; (f = *fp);)
2395 // destroy this command, it didn't exist at init
2396 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
2401 for (ap = &cmd->userdefined->alias; (a = *ap);)
2405 // restore this alias, it existed at init
2406 if (strcmp(a->value ? a->value : "", a->initialvalue ? a->initialvalue : ""))
2408 Con_DPrintf("Cmd_RestoreInitState: Restoring alias %s\n", a->name);
2411 a->value = Mem_strdup(zonemempool, a->initialvalue);
2417 // free this alias, it didn't exist at init...
2418 Con_DPrintf("Cmd_RestoreInitState: Destroying alias %s\n", a->name);
2426 Cvar_RestoreInitState(&cvars_all);
2429 void Cmd_NoOperation_f(cmd_state_t *cmd)