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 void Cbuf_ParseText(cmd_state_t *cmd, llist_t *head, cmd_input_t *existing, const char *text, qbool allowpending);
78 static void Cbuf_LinkString(cmd_state_t *cmd, llist_t *head, cmd_input_t *existing, const char *text, qbool leavepending, unsigned int cmdsize);
79 static void Cmd_Defer_f (cmd_state_t *cmd)
82 cmd_buf_t *cbuf = cmd->cbuf;
85 if(Cmd_Argc(cmd) == 1)
87 if(List_Is_Empty(&cbuf->deferred))
88 Con_Printf("No commands are pending.\n");
91 List_For_Each_Entry(current, &cbuf->deferred, cmd_input_t, list)
92 Con_Printf("-> In %9.2f: %s\n", current->delay, current->text);
95 else if(Cmd_Argc(cmd) == 2 && !strcasecmp("clear", Cmd_Argv(cmd, 1)))
97 while(!List_Is_Empty(&cbuf->deferred))
99 cbuf->size -= List_Entry(cbuf->deferred.next, cmd_input_t, list)->length;
100 List_Move_Tail(cbuf->deferred.next, &cbuf->free);
103 else if(Cmd_Argc(cmd) == 3 && (cmdsize = strlen(Cmd_Argv(cmd, 2))) )
107 Cbuf_LinkString(cmd, &cbuf->deferred, NULL, Cmd_Argv(cmd, 2), false, cmdsize);
108 List_Entry(cbuf->deferred.prev, cmd_input_t, list)->delay = atof(Cmd_Argv(cmd, 1));
114 Con_Printf("usage: defer <seconds> <command>\n"
121 =============================================================================
125 * The Quake command-line is super basic. It can be entered in the console
126 * or in config files. A semicolon is used to terminate a command and chain
127 * them together. Otherwise, a newline delineates command input.
129 * In most engines, the Quake command-line is a simple linear text buffer that
130 * is parsed when it executes. In Darkplaces, we use a linked list of command
131 * input and parse the input on the spot.
133 * This was done because Darkplaces allows multiple command interpreters on the
134 * same thread. Previously, each interpreter maintained its own buffer and this
135 * caused problems related to execution order, and maintaining a single simple
136 * buffer for all interpreters makes it non-trivial to keep track of which
137 * command should execute on which interpreter.
139 =============================================================================
146 Returns an existing buffer node for appending or reuse, or allocates a new one
149 static cmd_input_t *Cbuf_NodeGet(cmd_buf_t *cbuf, cmd_input_t *existing)
152 if(existing && existing->pending)
154 else if(!List_Is_Empty(&cbuf->free))
156 node = List_Entry(cbuf->free.next, cmd_input_t, list);
157 node->length = node->pending = 0;
161 node = (cmd_input_t *)Mem_Alloc(cbuf_mempool, sizeof(cmd_input_t));
162 node->list.prev = node->list.next = &node->list;
163 node->size = node->length = node->pending = 0;
172 Copies a command string into a buffer node
175 static void Cbuf_LinkString(cmd_state_t *cmd, llist_t *head, cmd_input_t *existing, const char *text, qbool leavepending, unsigned int cmdsize)
177 cmd_buf_t *cbuf = cmd->cbuf;
178 cmd_input_t *node = Cbuf_NodeGet(cbuf, existing);
179 unsigned int offset = node->length; // > 0 if(pending)
181 // node will match existing if its text was pending continuation
185 List_Move_Tail(&node->list, head);
188 node->length += cmdsize;
189 if(node->size < node->length)
191 node->text = (char *)Mem_Realloc(cbuf_mempool, node->text, node->length + 1);
192 node->size = node->length;
194 cbuf->size += cmdsize;
196 strlcpy(&node->text[offset], text, cmdsize + 1); // always sets the last char to \0
197 //Con_Printf("^5Cbuf_LinkString(): %s `^7%s^5`\n", node->pending ? "append" : "new", &node->text[offset]);
198 node->pending = leavepending;
205 Parses text to isolate command strings for linking into the buffer
206 separators: \n \r or unquoted and uncommented ';'
209 static void Cbuf_ParseText(cmd_state_t *cmd, llist_t *head, cmd_input_t *existing, const char *text, qbool allowpending)
211 unsigned int cmdsize = 0, start = 0, pos;
212 qbool quotes = false, comment = false;
214 for (pos = 0; text[pos]; ++pos)
219 if (comment || quotes)
224 quotes = false; // matches div0-stable
227 Cbuf_LinkString(cmd, head, existing, &text[start], false, cmdsize);
230 else if (existing && existing->pending) // all I got was this lousy \n
231 existing->pending = false;
232 continue; // don't increment cmdsize
235 if (!quotes && text[pos + 1] == '/' && (pos == 0 || ISWHITESPACE(text[pos - 1])))
239 if (!comment && (pos == 0 || text[pos - 1] != '\\'))
252 if (cmdsize) // the line didn't end yet but we do have a string
253 Cbuf_LinkString(cmd, head, existing, &text[start], allowpending, cmdsize);
260 Adds command text at the end of the buffer
263 void Cbuf_AddText (cmd_state_t *cmd, const char *text)
265 size_t l = strlen(text);
266 cmd_buf_t *cbuf = cmd->cbuf;
267 llist_t llist = {&llist, &llist};
269 if (cbuf->size + l > cbuf->maxsize)
271 Con_Printf(CON_WARN "Cbuf_AddText: input too large, %zuKB ought to be enough for anybody.\n", cbuf->maxsize / 1024);
277 // If the string terminates but the (last) line doesn't, the node will be left in the pending state (to be continued).
278 Cbuf_ParseText(cmd, &llist, (List_Is_Empty(&cbuf->start) ? NULL : List_Entry(cbuf->start.prev, cmd_input_t, list)), text, true);
279 List_Splice_Tail(&llist, &cbuf->start);
288 Adds command text immediately after the current command
291 void Cbuf_InsertText (cmd_state_t *cmd, const char *text)
293 cmd_buf_t *cbuf = cmd->cbuf;
294 llist_t llist = {&llist, &llist};
295 size_t l = strlen(text);
297 if (cbuf->size + l > cbuf->maxsize)
299 Con_Printf(CON_WARN "Cbuf_InsertText: input too large, %zuKB ought to be enough for anybody.\n", cbuf->maxsize / 1024);
305 // bones_was_here assertion: when prepending to the buffer it never makes sense to leave node(s) in the `pending` state,
306 // it would have been impossible to append to such text later in the old raw text buffer,
307 // and allowing it causes bugs when .cfg files lack \n at EOF (see: https://gitlab.com/xonotic/darkplaces/-/issues/378).
308 Cbuf_ParseText(cmd, &llist, (List_Is_Empty(&cbuf->start) ? NULL : List_Entry(cbuf->start.next, cmd_input_t, list)), text, false);
309 List_Splice(&llist, &cbuf->start);
316 Cbuf_Execute_Deferred --blub
319 static void Cbuf_Execute_Deferred (cmd_buf_t *cbuf)
321 cmd_input_t *current, *n;
324 if (host.realtime - cbuf->deferred_oldtime < 0 || host.realtime - cbuf->deferred_oldtime > 1800)
325 cbuf->deferred_oldtime = host.realtime;
326 eat = host.realtime - cbuf->deferred_oldtime;
329 cbuf->deferred_oldtime = host.realtime;
331 List_For_Each_Entry_Safe(current, n, &cbuf->deferred, cmd_input_t, list)
333 current->delay -= eat;
334 if(current->delay <= 0)
336 Cbuf_AddText(current->source, current->text); // parse deferred string and append its cmdstring(s)
337 List_Entry(cbuf->start.prev, cmd_input_t, list)->pending = false; // faster than div0-stable's Cbuf_AddText(";\n");
338 List_Move_Tail(¤t->list, &cbuf->free); // make deferred string memory available for reuse
339 cbuf->size -= current->length;
349 extern qbool prvm_runawaycheck;
350 static qbool Cmd_PreprocessString(cmd_state_t *cmd, const char *intext, char *outtext, unsigned maxoutlen, cmd_alias_t *alias );
351 void Cbuf_Execute (cmd_buf_t *cbuf)
353 cmd_input_t *current;
354 char preprocessed[MAX_INPUTLINE];
358 // LadyHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
359 cbuf->tokenizebufferpos = 0;
361 while (!List_Is_Empty(&cbuf->start))
364 * Delete the text from the command buffer and move remaining
365 * commands down. This is necessary because commands (exec, alias)
366 * can insert data at the beginning of the text buffer
368 current = List_Entry(cbuf->start.next, cmd_input_t, list);
371 * Assume we're rolling with the current command-line and
372 * always set this false because alias expansion or cbuf insertion
373 * without a newline may set this true, and cause weirdness.
375 current->pending = false;
377 cbuf->size -= current->length;
379 firstchar = current->text;
380 while(*firstchar && ISWHITESPACE(*firstchar))
382 if((strncmp(firstchar, "alias", 5) || !ISWHITESPACE(firstchar[5])) &&
383 (strncmp(firstchar, "bind", 4) || !ISWHITESPACE(firstchar[4])) &&
384 (strncmp(firstchar, "in_bind", 7) || !ISWHITESPACE(firstchar[7])))
386 if(Cmd_PreprocessString(current->source, current->text, preprocessed, sizeof(preprocessed), NULL ))
387 Cmd_ExecuteString(current->source, preprocessed, src_local, false);
391 Cmd_ExecuteString (current->source, current->text, src_local, false);
394 // Recycle memory so using WASD doesn't cause a malloc and free
395 List_Move_Tail(¤t->list, &cbuf->free);
402 * Skip out while text still remains in
403 * buffer, leaving it for next frame
409 if (++i == 1000000 && prvm_runawaycheck)
411 Con_Printf(CON_WARN "Cbuf_Execute: runaway loop counter hit limit of %d commands, clearing command buffers!\n", i);
421 Add them exactly as if they had been typed at the console
424 static void Cbuf_Frame_Input(void)
428 // bones_was_here: prepending allows a loop such as `alias foo "bar; wait; foo"; foo`
429 // to be broken with an alias or unalias command
430 while ((line = Sys_ConsoleInput()))
431 Cbuf_InsertText(cmd_local, line);
434 void Cbuf_Frame(cmd_buf_t *cbuf)
436 // check for commands typed to the host
439 // R_TimeReport("preconsole");
441 // execute commands queued with the defer command
442 Cbuf_Execute_Deferred(cbuf);
445 SV_LockThreadMutex();
447 SV_UnlockThreadMutex();
450 // R_TimeReport("console");
453 void Cbuf_Clear(cmd_buf_t *cbuf)
455 while (!List_Is_Empty(&cbuf->start))
456 List_Move_Tail(cbuf->start.next, &cbuf->free);
457 while (!List_Is_Empty(&cbuf->deferred))
458 List_Move_Tail(cbuf->deferred.next, &cbuf->free);
463 ==============================================================================
467 ==============================================================================
474 Adds command line parameters as script statements
475 Commands lead with a +, and continue until a - or another +
476 quake +prog jctest.qp +cmd amlev1
477 quake -nosound +cmd amlev1
480 static void Cmd_StuffCmds_f (cmd_state_t *cmd)
483 // this is for all commandline options combined (and is bounds checked)
484 char build[MAX_INPUTLINE];
486 if (Cmd_Argc (cmd) != 1)
488 Con_Print("stuffcmds : execute command line parameters\n");
492 // no reason to run the commandline arguments twice
493 if (host_stuffcmdsrun)
496 host_stuffcmdsrun = true;
499 for (i = 0;i < sys.argc;i++)
501 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)
504 while (sys.argv[i][j])
505 build[l++] = sys.argv[i][j++];
507 for (;i < sys.argc;i++)
511 if ((sys.argv[i][0] == '+' || sys.argv[i][0] == '-') && (sys.argv[i][1] < '0' || sys.argv[i][1] > '9'))
513 if (l + strlen(sys.argv[i]) + 4 > sizeof(build) - 1)
516 if (strchr(sys.argv[i], ' '))
518 for (j = 0;sys.argv[i][j];j++)
519 build[l++] = sys.argv[i][j];
520 if (strchr(sys.argv[i], ' '))
527 // now terminate the combined string and prepend it to the command buffer
528 // we already reserved space for the terminator
530 Cbuf_InsertText (cmd, build);
533 static void Cmd_Exec(cmd_state_t *cmd, const char *filename)
536 size_t filenameLen = strlen(filename);
538 !strcmp(filename, "default.cfg") ||
539 (filenameLen >= 12 && !strcmp(filename + filenameLen - 12, "/default.cfg"));
541 if (!strcmp(filename, "config.cfg"))
543 filename = CONFIGFILENAME;
544 if (Sys_CheckParm("-noconfig"))
545 return; // don't execute config.cfg
548 f = (char *)FS_LoadFile (filename, tempmempool, false, NULL);
551 Con_Printf(CON_WARN "couldn't exec %s\n",filename);
554 Con_Printf("execing %s\n",filename);
556 // if executing default.cfg for the first time, lock the cvar defaults
557 // it may seem backwards to insert this text BEFORE the default.cfg
558 // but Cbuf_InsertText inserts before, so this actually ends up after it.
560 Cbuf_InsertText(cmd, "\ncvar_lockdefaults\n");
562 Cbuf_InsertText (cmd, f);
567 // special defaults for specific games go here, these execute before default.cfg
568 // Nehahra pushable crates malfunction in some levels if this is on
569 // Nehahra NPC AI is confused by blowupfallenzombies
573 Cbuf_InsertText(cmd, "\n"
574 "sv_gameplayfix_blowupfallenzombies 0\n"
575 "sv_gameplayfix_findradiusdistancetobox 0\n"
576 "sv_gameplayfix_grenadebouncedownslopes 0\n"
577 "sv_gameplayfix_slidemoveprojectiles 0\n"
578 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
579 "sv_gameplayfix_setmodelrealbox 0\n"
580 "sv_gameplayfix_droptofloorstartsolid 0\n"
581 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
582 "sv_gameplayfix_noairborncorpse 0\n"
583 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
584 "sv_gameplayfix_easierwaterjump 0\n"
585 "sv_gameplayfix_delayprojectiles 0\n"
586 "sv_gameplayfix_multiplethinksperframe 0\n"
587 "sv_gameplayfix_fixedcheckwatertransition 0\n"
588 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
589 "sv_gameplayfix_swiminbmodels 0\n"
590 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
591 "sys_ticrate 0.01388889\n"
593 "r_shadow_bumpscale_basetexture 0\n"
594 "csqc_polygons_defaultmaterial_nocullface 0\n"
598 Cbuf_InsertText(cmd, "\n"
599 "sv_gameplayfix_blowupfallenzombies 0\n"
600 "sv_gameplayfix_findradiusdistancetobox 0\n"
601 "sv_gameplayfix_grenadebouncedownslopes 0\n"
602 "sv_gameplayfix_slidemoveprojectiles 0\n"
603 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
604 "sv_gameplayfix_setmodelrealbox 0\n"
605 "sv_gameplayfix_droptofloorstartsolid 0\n"
606 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
607 "sv_gameplayfix_noairborncorpse 0\n"
608 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
609 "sv_gameplayfix_easierwaterjump 0\n"
610 "sv_gameplayfix_delayprojectiles 0\n"
611 "sv_gameplayfix_multiplethinksperframe 0\n"
612 "sv_gameplayfix_fixedcheckwatertransition 0\n"
613 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
614 "sv_gameplayfix_swiminbmodels 0\n"
615 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
616 "sys_ticrate 0.01388889\n"
618 "r_shadow_bumpscale_basetexture 0\n"
619 "csqc_polygons_defaultmaterial_nocullface 0\n"
622 // 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.
623 // 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
624 // hipnotic mission pack has issues in their proximity mine sticking code, which causes them to bounce off.
627 Cbuf_InsertText(cmd, "\n"
628 "sv_gameplayfix_blowupfallenzombies 0\n"
629 "sv_gameplayfix_findradiusdistancetobox 0\n"
630 "sv_gameplayfix_grenadebouncedownslopes 0\n"
631 "sv_gameplayfix_slidemoveprojectiles 0\n"
632 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
633 "sv_gameplayfix_setmodelrealbox 0\n"
634 "sv_gameplayfix_droptofloorstartsolid 0\n"
635 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
636 "sv_gameplayfix_noairborncorpse 0\n"
637 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
638 "sv_gameplayfix_easierwaterjump 0\n"
639 "sv_gameplayfix_delayprojectiles 0\n"
640 "sv_gameplayfix_multiplethinksperframe 0\n"
641 "sv_gameplayfix_fixedcheckwatertransition 0\n"
642 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
643 "sv_gameplayfix_swiminbmodels 0\n"
644 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
647 "r_shadow_bumpscale_basetexture 0\n"
648 "csqc_polygons_defaultmaterial_nocullface 0\n"
651 // rogue mission pack has a guardian boss that does not wake up if findradius returns one of the entities around its spawn area
653 Cbuf_InsertText(cmd, "\n"
654 "sv_gameplayfix_blowupfallenzombies 0\n"
655 "sv_gameplayfix_findradiusdistancetobox 0\n"
656 "sv_gameplayfix_grenadebouncedownslopes 0\n"
657 "sv_gameplayfix_slidemoveprojectiles 0\n"
658 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
659 "sv_gameplayfix_setmodelrealbox 0\n"
660 "sv_gameplayfix_droptofloorstartsolid 0\n"
661 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
662 "sv_gameplayfix_noairborncorpse 0\n"
663 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
664 "sv_gameplayfix_easierwaterjump 0\n"
665 "sv_gameplayfix_delayprojectiles 0\n"
666 "sv_gameplayfix_multiplethinksperframe 0\n"
667 "sv_gameplayfix_fixedcheckwatertransition 0\n"
668 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
669 "sv_gameplayfix_swiminbmodels 0\n"
670 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
671 "sys_ticrate 0.01388889\n"
673 "r_shadow_bumpscale_basetexture 0\n"
674 "csqc_polygons_defaultmaterial_nocullface 0\n"
678 Cbuf_InsertText(cmd, "\n"
679 "sv_gameplayfix_blowupfallenzombies 0\n"
680 "sv_gameplayfix_findradiusdistancetobox 0\n"
681 "sv_gameplayfix_grenadebouncedownslopes 0\n"
682 "sv_gameplayfix_slidemoveprojectiles 0\n"
683 "sv_gameplayfix_upwardvelocityclearsongroundflag 0\n"
684 "sv_gameplayfix_setmodelrealbox 0\n"
685 "sv_gameplayfix_droptofloorstartsolid 0\n"
686 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 0\n"
687 "sv_gameplayfix_noairborncorpse 0\n"
688 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 0\n"
689 "sv_gameplayfix_easierwaterjump 0\n"
690 "sv_gameplayfix_delayprojectiles 0\n"
691 "sv_gameplayfix_multiplethinksperframe 0\n"
692 "sv_gameplayfix_fixedcheckwatertransition 0\n"
693 "sv_gameplayfix_q1bsptracelinereportstexture 0\n"
694 "sv_gameplayfix_swiminbmodels 0\n"
695 "sv_gameplayfix_downtracesupportsongroundflag 0\n"
696 "sys_ticrate 0.01388889\n"
698 "r_shadow_bumpscale_basetexture 4\n"
699 "csqc_polygons_defaultmaterial_nocullface 0\n"
703 Cbuf_InsertText(cmd, "\n"
704 "sv_gameplayfix_blowupfallenzombies 1\n"
705 "sv_gameplayfix_findradiusdistancetobox 1\n"
706 "sv_gameplayfix_grenadebouncedownslopes 1\n"
707 "sv_gameplayfix_slidemoveprojectiles 1\n"
708 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
709 "sv_gameplayfix_setmodelrealbox 1\n"
710 "sv_gameplayfix_droptofloorstartsolid 1\n"
711 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
712 "sv_gameplayfix_noairborncorpse 1\n"
713 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
714 "sv_gameplayfix_easierwaterjump 1\n"
715 "sv_gameplayfix_delayprojectiles 1\n"
716 "sv_gameplayfix_multiplethinksperframe 1\n"
717 "sv_gameplayfix_fixedcheckwatertransition 1\n"
718 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
719 "sv_gameplayfix_swiminbmodels 1\n"
720 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
721 "sys_ticrate 0.01388889\n"
722 "sv_gameplayfix_q2airaccelerate 1\n"
723 "sv_gameplayfix_stepmultipletimes 1\n"
724 "csqc_polygons_defaultmaterial_nocullface 1\n"
725 "con_chatsound_team_mask 13\n"
729 case GAME_VORETOURNAMENT:
730 // 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
731 Cbuf_InsertText(cmd, "\n"
732 "csqc_polygons_defaultmaterial_nocullface 1\n"
733 "con_chatsound_team_mask 13\n"
735 "mod_q1bsp_zero_hullsize_cutoff 8.03125\n"
738 // Steel Storm: Burning Retribution csqc misinterprets CSQC_InputEvent if type is a value other than 0 or 1
739 case GAME_STEELSTORM:
740 Cbuf_InsertText(cmd, "\n"
741 "sv_gameplayfix_blowupfallenzombies 1\n"
742 "sv_gameplayfix_findradiusdistancetobox 1\n"
743 "sv_gameplayfix_grenadebouncedownslopes 1\n"
744 "sv_gameplayfix_slidemoveprojectiles 1\n"
745 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
746 "sv_gameplayfix_setmodelrealbox 1\n"
747 "sv_gameplayfix_droptofloorstartsolid 1\n"
748 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
749 "sv_gameplayfix_noairborncorpse 1\n"
750 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
751 "sv_gameplayfix_easierwaterjump 1\n"
752 "sv_gameplayfix_delayprojectiles 1\n"
753 "sv_gameplayfix_multiplethinksperframe 1\n"
754 "sv_gameplayfix_fixedcheckwatertransition 1\n"
755 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
756 "sv_gameplayfix_swiminbmodels 1\n"
757 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
758 "sys_ticrate 0.01388889\n"
759 "cl_csqc_generatemousemoveevents 0\n"
760 "csqc_polygons_defaultmaterial_nocullface 1\n"
764 Cbuf_InsertText(cmd, "\n"
765 "sv_gameplayfix_blowupfallenzombies 1\n"
766 "sv_gameplayfix_findradiusdistancetobox 1\n"
767 "sv_gameplayfix_grenadebouncedownslopes 1\n"
768 "sv_gameplayfix_slidemoveprojectiles 1\n"
769 "sv_gameplayfix_upwardvelocityclearsongroundflag 1\n"
770 "sv_gameplayfix_setmodelrealbox 1\n"
771 "sv_gameplayfix_droptofloorstartsolid 1\n"
772 "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect 1\n"
773 "sv_gameplayfix_noairborncorpse 1\n"
774 "sv_gameplayfix_noairborncorpse_allowsuspendeditems 1\n"
775 "sv_gameplayfix_easierwaterjump 1\n"
776 "sv_gameplayfix_delayprojectiles 1\n"
777 "sv_gameplayfix_multiplethinksperframe 1\n"
778 "sv_gameplayfix_fixedcheckwatertransition 1\n"
779 "sv_gameplayfix_q1bsptracelinereportstexture 1\n"
780 "sv_gameplayfix_swiminbmodels 1\n"
781 "sv_gameplayfix_downtracesupportsongroundflag 1\n"
782 "sys_ticrate 0.01388889\n"
783 "csqc_polygons_defaultmaterial_nocullface 0\n"
795 static void Cmd_Exec_f (cmd_state_t *cmd)
800 if (Cmd_Argc(cmd) != 2)
802 Con_Print("exec <filename> : execute a script file\n");
806 s = FS_Search(Cmd_Argv(cmd, 1), true, true, NULL);
807 if(!s || !s->numfilenames)
809 Con_Printf(CON_WARN "couldn't exec %s\n",Cmd_Argv(cmd, 1));
813 for(i = 0; i < s->numfilenames; ++i)
814 Cmd_Exec(cmd, s->filenames[i]);
824 Just prints the rest of the line to the console
827 static void Cmd_Echo_f (cmd_state_t *cmd)
831 for (i=1 ; i<Cmd_Argc(cmd) ; i++)
832 Con_Printf("%s ",Cmd_Argv(cmd, i));
837 // Support Doom3-style Toggle Console Command
842 Toggles a specified console variable amongst the values specified (default is 0 and 1)
845 static void Cmd_Toggle_f(cmd_state_t *cmd)
847 // Acquire Number of Arguments
848 int nNumArgs = Cmd_Argc(cmd);
851 // No Arguments Specified; Print Usage
852 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");
854 { // Correct Arguments Specified
855 // Acquire Potential CVar
856 cvar_t* cvCVar = Cvar_FindVar(cmd->cvars, Cmd_Argv(cmd, 1), cmd->cvars_flagsmask);
863 Cvar_SetValueQuick(cvCVar, 0);
865 Cvar_SetValueQuick(cvCVar, 1);
869 { // 0 and Specified Usage
870 if(cvCVar->integer == atoi(Cmd_Argv(cmd, 2) ) )
871 // CVar is Specified Value; // Reset to 0
872 Cvar_SetValueQuick(cvCVar, 0);
874 if(cvCVar->integer == 0)
875 // CVar is 0; Specify Value
876 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
878 // CVar does not match; Reset to 0
879 Cvar_SetValueQuick(cvCVar, 0);
882 { // Variable Values Specified
886 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
887 { // Cycle through Values
888 if( strcmp(cvCVar->string, Cmd_Argv(cmd, nCnt) ) == 0)
889 { // Current Value Located; Increment to Next
890 if( (nCnt + 1) == nNumArgs)
891 // Max Value Reached; Reset
892 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
895 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, nCnt + 1) );
904 // Value not Found; Reset to Original
905 Cvar_SetQuick(cvCVar, Cmd_Argv(cmd, 2) );
911 Con_Printf(CON_WARN "ERROR : CVar '%s' not found\n", Cmd_Argv(cmd, 1) );
920 Creates a new command that executes a command string (possibly ; seperated)
923 static void Cmd_Alias_f (cmd_state_t *cmd)
926 char line[MAX_INPUTLINE];
931 if (Cmd_Argc(cmd) == 1)
933 Con_Print("Current alias commands:\n");
934 for (a = cmd->userdefined->alias ; a ; a=a->next)
935 Con_Printf("%s : %s", a->name, a->value);
939 s = Cmd_Argv(cmd, 1);
940 if (strlen(s) >= MAX_ALIAS_NAME)
942 Con_Print(CON_WARN "Alias name is too long\n");
946 // if the alias already exists, reuse it
947 for (a = cmd->userdefined->alias ; a ; a=a->next)
949 if (!strcmp(s, a->name))
958 cmd_alias_t *prev, *current;
960 a = (cmd_alias_t *)Z_Malloc (sizeof(cmd_alias_t));
961 strlcpy (a->name, s, sizeof (a->name));
962 // insert it at the right alphanumeric position
963 for( prev = NULL, current = cmd->userdefined->alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
968 cmd->userdefined->alias = a;
974 // copy the rest of the command line
975 line[0] = 0; // start out with a null string
977 for (i=2 ; i < c ; i++)
980 strlcat (line, " ", sizeof (line));
981 strlcat (line, Cmd_Argv(cmd, i), sizeof (line));
983 strlcat (line, "\n", sizeof (line));
985 alloclen = strlen (line) + 1;
987 line[alloclen - 2] = '\n'; // to make sure a newline is appended even if too long
988 a->value = (char *)Z_Malloc (alloclen);
989 memcpy (a->value, line, alloclen);
996 Remove existing aliases.
999 static void Cmd_UnAlias_f (cmd_state_t *cmd)
1005 if(Cmd_Argc(cmd) == 1)
1007 Con_Print("unalias: Usage: unalias alias1 [alias2 ...]\n");
1011 for(i = 1; i < Cmd_Argc(cmd); ++i)
1013 s = Cmd_Argv(cmd, i);
1015 for(a = cmd->userdefined->alias; a; p = a, a = a->next)
1017 if(!strcmp(s, a->name))
1019 if (a->initstate) // we can not remove init aliases
1021 if(a == cmd->userdefined->alias)
1022 cmd->userdefined->alias = a->next;
1031 Con_Printf("unalias: %s alias not found\n", s);
1036 =============================================================================
1040 =============================================================================
1043 static const char *Cmd_GetDirectCvarValue(cmd_state_t *cmd, const char *varname, cmd_alias_t *alias, qbool *is_multiple)
1048 static char vabuf[1024]; // cmd_mutex
1051 *is_multiple = false;
1053 if(!varname || !*varname)
1058 if(!strcmp(varname, "*"))
1061 *is_multiple = true;
1062 return Cmd_Args(cmd);
1064 else if(!strcmp(varname, "#"))
1066 return va(vabuf, sizeof(vabuf), "%d", Cmd_Argc(cmd));
1068 else if(varname[strlen(varname) - 1] == '-')
1070 argno = strtol(varname, &endptr, 10);
1071 if(endptr == varname + strlen(varname) - 1)
1073 // whole string is a number, apart from the -
1074 const char *p = Cmd_Args(cmd);
1075 for(; argno > 1; --argno)
1076 if(!COM_ParseToken_Console(&p))
1081 *is_multiple = true;
1083 // kill pre-argument whitespace
1084 for (;*p && ISWHITESPACE(*p);p++)
1093 argno = strtol(varname, &endptr, 10);
1096 // whole string is a number
1097 // NOTE: we already made sure we don't have an empty cvar name!
1098 if(argno >= 0 && argno < Cmd_Argc(cmd))
1099 return Cmd_Argv(cmd, argno);
1104 if((cvar = Cvar_FindVar(cmd->cvars, varname, cmd->cvars_flagsmask)) && !(cvar->flags & CF_PRIVATE))
1105 return cvar->string;
1110 qbool Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset, qbool putquotes)
1112 qbool quote_quot = !!strchr(quoteset, '"');
1113 qbool quote_backslash = !!strchr(quoteset, '\\');
1114 qbool quote_dollar = !!strchr(quoteset, '$');
1123 *out++ = '"'; --outlen;
1129 if(*in == '"' && quote_quot)
1133 *out++ = '\\'; --outlen;
1134 *out++ = '"'; --outlen;
1136 else if(*in == '\\' && quote_backslash)
1140 *out++ = '\\'; --outlen;
1141 *out++ = '\\'; --outlen;
1143 else if(*in == '$' && quote_dollar)
1147 *out++ = '$'; --outlen;
1148 *out++ = '$'; --outlen;
1154 *out++ = *in; --outlen;
1169 static const char *Cmd_GetCvarValue(cmd_state_t *cmd, const char *var, size_t varlen, cmd_alias_t *alias)
1171 static char varname[MAX_INPUTLINE]; // cmd_mutex
1172 static char varval[MAX_INPUTLINE]; // cmd_mutex
1173 const char *varstr = NULL;
1175 qbool required = false;
1176 qbool optional = false;
1177 static char asis[] = "asis"; // just to suppress const char warnings
1179 if(varlen >= MAX_INPUTLINE)
1180 varlen = MAX_INPUTLINE - 1;
1181 memcpy(varname, var, varlen);
1182 varname[varlen] = 0;
1183 varfunc = strchr(varname, ' ');
1195 Con_Printf(CON_WARN "Warning: Could not expand $ in alias %s\n", alias->name);
1197 Con_Printf(CON_WARN "Warning: Could not expand $\n");
1205 while((p = strchr(varfunc, '?')))
1208 memmove(p, p+1, strlen(p)); // with final NUL
1211 while((p = strchr(varfunc, '!')))
1214 memmove(p, p+1, strlen(p)); // with final NUL
1217 while((p = strchr(varfunc, ' ')))
1219 memmove(p, p+1, strlen(p)); // with final NUL
1221 // if no function is left, NULL it
1226 if(varname[0] == '$')
1227 varstr = Cmd_GetDirectCvarValue(cmd, Cmd_GetDirectCvarValue(cmd, varname + 1, alias, NULL), alias, NULL);
1230 qbool is_multiple = false;
1231 // Exception: $* and $n- don't use the quoted form by default
1232 varstr = Cmd_GetDirectCvarValue(cmd, varname, alias, &is_multiple);
1243 Con_Printf(CON_ERROR "Error: Could not expand $%s in alias %s\n", varname, alias->name);
1245 Con_Printf(CON_ERROR "Error: Could not expand $%s\n", varname);
1255 Con_Printf(CON_WARN "Warning: Could not expand $%s in alias %s\n", varname, alias->name);
1257 Con_Printf(CON_WARN "Warning: Could not expand $%s\n", varname);
1258 dpsnprintf(varval, sizeof(varval), "$%s", varname);
1263 if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
1265 // quote it so it can be used inside double quotes
1266 // we just need to replace " by \", and of course, double backslashes
1267 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\", false);
1270 else if(!strcmp(varfunc, "asis"))
1275 Con_Printf("Unknown variable function %s\n", varfunc);
1281 Cmd_PreprocessString
1283 Preprocesses strings and replaces $*, $param#, $cvar accordingly. Also strips comments.
1285 static qbool Cmd_PreprocessString(cmd_state_t *cmd, const char *intext, char *outtext, unsigned maxoutlen, cmd_alias_t *alias ) {
1291 // don't crash if there's no room in the outtext buffer
1292 if( maxoutlen == 0 ) {
1295 maxoutlen--; // because of \0
1300 while( *in && outlen < maxoutlen ) {
1302 // this is some kind of expansion, see what comes after the $
1305 // The console does the following preprocessing:
1307 // - $$ is transformed to a single dollar sign.
1308 // - $var or ${var} are expanded to the contents of the named cvar,
1309 // with quotation marks and backslashes quoted so it can safely
1310 // be used inside quotation marks (and it should always be used
1312 // - ${var asis} inserts the cvar value as is, without doing this
1314 // - ${var ?} silently expands to the empty string if
1315 // $var does not exist
1316 // - ${var !} fails expansion and executes nothing if
1317 // $var does not exist
1318 // - prefix the cvar name with a dollar sign to do indirection;
1319 // for example, if $x has the value timelimit, ${$x} will return
1320 // the value of $timelimit
1321 // - when expanding an alias, the special variable name $* refers
1322 // to all alias parameters, and a number refers to that numbered
1323 // alias parameter, where the name of the alias is $0, the first
1324 // parameter is $1 and so on; as a special case, $* inserts all
1325 // parameters, without extra quoting, so one can use $* to just
1326 // pass all parameters around. All parameters starting from $n
1327 // can be referred to as $n- (so $* is equivalent to $1-).
1328 // - ${* q} and ${n- q} force quoting anyway
1330 // Note: when expanding an alias, cvar expansion is done in the SAME step
1331 // as alias expansion so that alias parameters or cvar values containing
1332 // dollar signs have no unwanted bad side effects. However, this needs to
1333 // be accounted for when writing complex aliases. For example,
1334 // alias foo "set x NEW; echo $x"
1335 // actually expands to
1336 // "set x NEW; echo OLD"
1337 // and will print OLD! To work around this, use a second alias:
1338 // alias foo "set x NEW; foo2"
1339 // alias foo2 "echo $x"
1341 // Also note: lines starting with alias are exempt from cvar expansion.
1342 // If you want cvar expansion, write "alias" instead:
1345 // alias foo "echo $x"
1346 // "alias" bar "echo $x"
1349 // foo will print 2, because the variable $x will be expanded when the alias
1350 // gets expanded. bar will print 1, because the variable $x was expanded
1351 // at definition time. foo can be equivalently defined as
1353 // "alias" foo "echo $$x"
1355 // because at definition time, $$ will get replaced to a single $.
1360 } else if(*in == '{') {
1361 varlen = strcspn(in + 1, "}");
1362 if(in[varlen + 1] == '}')
1364 val = Cmd_GetCvarValue(cmd, in + 1, varlen, alias);
1376 varlen = strspn(in, "#*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
1377 val = Cmd_GetCvarValue(cmd, in, varlen, alias);
1384 // insert the cvar value
1385 while(*val && outlen < maxoutlen)
1386 outtext[outlen++] = *val++;
1391 // copy the unexpanded text
1392 outtext[outlen++] = '$';
1393 while(eat && outlen < maxoutlen)
1395 outtext[outlen++] = *in++;
1401 outtext[outlen++] = *in++;
1403 outtext[outlen] = 0;
1411 Called for aliases and fills in the alias into the cbuffer
1414 static void Cmd_ExecuteAlias (cmd_state_t *cmd, cmd_alias_t *alias)
1416 static char buffer[ MAX_INPUTLINE ]; // cmd_mutex
1417 static char buffer2[ MAX_INPUTLINE ]; // cmd_mutex
1418 qbool ret = Cmd_PreprocessString( cmd, alias->value, buffer, sizeof(buffer) - 2, alias );
1421 // insert at start of command buffer, so that aliases execute in order
1422 // (fixes bug introduced by Black on 20050705)
1424 // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1425 // have to make sure that no second variable expansion takes place, otherwise
1426 // alias parameters containing dollar signs can have bad effects.
1427 Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$", false);
1428 Cbuf_InsertText(cmd, buffer2);
1435 CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1436 Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1440 static void Cmd_List_f (cmd_state_t *cmd)
1442 cmd_function_t *func;
1443 const char *partial;
1448 if (Cmd_Argc(cmd) > 1)
1450 partial = Cmd_Argv(cmd, 1);
1451 len = strlen(partial);
1452 ispattern = (strchr(partial, '*') || strchr(partial, '?'));
1462 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1464 if (partial && (ispattern ? !matchpattern_with_separator(func->name, partial, false, "", false) : strncmp(partial, func->name, len)))
1466 Con_Printf("%s : %s\n", func->name, func->description);
1469 for (func = cmd->engine_functions; func; func = func->next)
1471 if (partial && (ispattern ? !matchpattern_with_separator(func->name, partial, false, "", false) : strncmp(partial, func->name, len)))
1473 Con_Printf("%s : %s\n", func->name, func->description);
1480 Con_Printf("%i Command%s matching \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1482 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1485 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1488 static void Cmd_Apropos_f(cmd_state_t *cmd)
1490 cmd_function_t *func;
1493 const char *partial;
1498 if (Cmd_Argc(cmd) > 1)
1499 partial = Cmd_Args(cmd);
1502 Con_Printf("usage: %s <string>\n",Cmd_Argv(cmd, 0));
1506 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1508 partial = va(vabuf, sizeof(vabuf), "*%s*", partial);
1511 for (cvar = cmd->cvars->vars; cvar; cvar = cvar->next)
1513 if (matchpattern_with_separator(cvar->name, partial, true, "", false) ||
1514 matchpattern_with_separator(cvar->description, partial, true, "", false))
1516 Con_Printf ("cvar ");
1517 Cvar_PrintHelp(cvar, cvar->name, true);
1520 for (char **cvar_alias = cvar->aliases; cvar_alias && *cvar_alias; cvar_alias++)
1522 if (matchpattern_with_separator(*cvar_alias, partial, true, "", false))
1524 Con_Printf ("cvar ");
1525 Cvar_PrintHelp(cvar, *cvar_alias, true);
1530 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1532 if (!matchpattern_with_separator(func->name, partial, true, "", false))
1533 if (!matchpattern_with_separator(func->description, partial, true, "", false))
1535 Con_Printf("command ^2%s^7: %s\n", func->name, func->description);
1538 for (func = cmd->engine_functions; func; func = func->next)
1540 if (!matchpattern_with_separator(func->name, partial, true, "", false))
1541 if (!matchpattern_with_separator(func->description, partial, true, "", false))
1543 Con_Printf("command ^2%s^7: %s\n", func->name, func->description);
1546 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1548 // procede here a bit differently as an alias value always got a final \n
1549 if (!matchpattern_with_separator(alias->name, partial, true, "", false))
1550 if (!matchpattern_with_separator(alias->value, partial, true, "\n", false)) // when \n is as separator wildcards don't match it
1552 Con_Printf("alias ^5%s^7: %s", alias->name, alias->value); // do not print an extra \n
1555 Con_Printf("%i result%s\n\n", count, (count > 1) ? "s" : "");
1558 static cmd_state_t *Cmd_AddInterpreter(cmd_buf_t *cbuf, cvar_state_t *cvars, unsigned cvars_flagsmask, unsigned cmds_flagsmask, cmd_userdefined_t *userdefined)
1560 cmd_state_t *cmd = (cmd_state_t *)Mem_Alloc(tempmempool, sizeof(cmd_state_t));
1562 cmd->mempool = Mem_AllocPool("commands", 0, NULL);
1563 // space for commands and script files
1565 cmd->null_string = "";
1568 cmd->cvars_flagsmask = cvars_flagsmask;
1569 cmd->cmd_flagsmask = cmds_flagsmask;
1570 cmd->userdefined = userdefined;
1583 unsigned cvars_flagsmask, cmds_flagsmask;
1585 cbuf_mempool = Mem_AllocPool("Command buffer", 0, NULL);
1586 cbuf = (cmd_buf_t *)Mem_Alloc(cbuf_mempool, sizeof(cmd_buf_t));
1587 cbuf->maxsize = CMDBUFSIZE;
1588 cbuf->lock = Thread_CreateMutex();
1592 cbuf->start.prev = cbuf->start.next = &(cbuf->start);
1593 cbuf->deferred.prev = cbuf->deferred.next = &(cbuf->deferred);
1594 cbuf->free.prev = cbuf->free.next = &(cbuf->free);
1596 // FIXME: Get rid of cmd_iter_all eventually. This is just a hack to reduce the amount of work to make the interpreters dynamic.
1597 cmd_iter_all = (cmd_iter_t *)Mem_Alloc(tempmempool, sizeof(cmd_iter_t) * 3);
1600 if (cls.state == ca_dedicated)
1602 cvars_flagsmask = CF_SERVER;
1603 cmds_flagsmask = CF_SERVER | CF_SERVER_FROM_CLIENT;
1607 cvars_flagsmask = CF_CLIENT | CF_SERVER;
1608 cmds_flagsmask = CF_CLIENT | CF_SERVER | CF_CLIENT_FROM_SERVER | CF_SERVER_FROM_CLIENT;
1610 cmd_iter_all[0].cmd = cmd_local = Cmd_AddInterpreter(cbuf, &cvars_all, cvars_flagsmask, cmds_flagsmask, &cmd_userdefined_all);
1611 cmd_local->Handle = Cmd_CL_Callback;
1613 // server commands received from clients have no reason to access cvars, cvar expansion seems perilous.
1614 cmd_iter_all[1].cmd = cmd_serverfromclient = Cmd_AddInterpreter(cbuf, &cvars_null, 0, CF_SERVER_FROM_CLIENT | CF_USERINFO, &cmd_userdefined_null);
1615 cmd_serverfromclient->Handle = Cmd_SV_Callback;
1617 cmd_iter_all[2].cmd = NULL;
1619 // register our commands
1621 // client-only commands
1622 Cmd_AddCommand(CF_SHARED, "wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1624 // maintenance commands used for upkeep of cvars and saved configs
1625 Cmd_AddCommand(CF_SHARED, "stuffcmds", Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1626 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");
1627 Cmd_AddCommand(CF_SHARED, "cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1628 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)");
1629 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)");
1631 // general console commands used in multiple environments
1632 Cmd_AddCommand(CF_SHARED, "exec", Cmd_Exec_f, "execute a script file");
1633 Cmd_AddCommand(CF_SHARED, "echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1634 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");
1635 Cmd_AddCommand(CF_SHARED, "unalias",Cmd_UnAlias_f, "remove an alias");
1636 Cmd_AddCommand(CF_SHARED, "set", Cvar_Set_f, "create or change the value of a console variable");
1637 Cmd_AddCommand(CF_SHARED, "seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1638 Cmd_AddCommand(CF_SHARED, "unset", Cvar_Del_f, "delete a cvar (does not work for static ones like _cl_name, or read-only ones)");
1640 #ifdef FILLALLCVARSWITHRUBBISH
1641 Cmd_AddCommand(CF_SHARED, "fillallcvarswithrubbish", Cvar_FillAll_f, "fill all cvars with a specified number of characters to provoke buffer overruns");
1642 #endif /* FILLALLCVARSWITHRUBBISH */
1644 // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1645 // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1646 Cmd_AddCommand(CF_SHARED, "cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix or matching the specified wildcard pattern");
1647 Cmd_AddCommand(CF_SHARED, "cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix or matching the specified wildcard pattern");
1648 Cmd_AddCommand(CF_SHARED, "apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1649 Cmd_AddCommand(CF_SHARED, "find", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1651 Cmd_AddCommand(CF_SHARED, "defer", Cmd_Defer_f, "execute a command in the future");
1654 // Support Doom3-style Toggle Command
1655 Cmd_AddCommand(CF_SHARED | CF_CLIENT_FROM_SERVER, "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1663 void Cmd_Shutdown(void)
1665 cmd_iter_t *cmd_iter;
1666 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
1668 cmd_state_t *cmd = cmd_iter->cmd;
1670 if (cmd->cbuf->lock)
1672 // we usually have this locked when we get here from Host_Quit_f
1673 Cbuf_Unlock(cmd->cbuf);
1676 Mem_FreePool(&cmd->mempool);
1684 Parses the given string into command line tokens.
1685 Takes a null terminated string. Does not need to be /n terminated.
1688 // AK: This function should only be called from ExecuteString because the current design is a bit of an hack
1689 static void Cmd_TokenizeString (cmd_state_t *cmd, const char *text)
1695 cmd->cmdline = NULL;
1699 // skip whitespace up to a /n
1700 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1707 if (*text == '\n' || *text == '\r')
1709 // a newline separates commands in the buffer
1710 if (*text == '\r' && text[1] == '\n')
1720 cmd->cmdline = text;
1724 if (!COM_ParseToken_Console(&text))
1727 if (cmd->argc < MAX_ARGS)
1729 l = (int)strlen(com_token) + 1;
1730 if (cmd->cbuf->tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1732 Con_Printf(CON_WARN "Cmd_TokenizeString: ran out of %i character buffer space for command arguments\n", CMD_TOKENIZELENGTH);
1735 memcpy (cmd->cbuf->tokenizebuffer + cmd->cbuf->tokenizebufferpos, com_token, l);
1736 cmd->argv[cmd->argc] = cmd->cbuf->tokenizebuffer + cmd->cbuf->tokenizebufferpos;
1737 cmd->cbuf->tokenizebufferpos += l;
1749 void Cmd_AddCommand(unsigned flags, const char *cmd_name, xcommand_t function, const char *description)
1751 cmd_function_t *func;
1752 cmd_function_t *prev, *current;
1756 for (i = 0; i < 2; i++)
1758 cmd = cmd_iter_all[i].cmd;
1759 if (flags & cmd->cmd_flagsmask)
1761 // fail if the command is a variable name
1762 if (Cvar_FindVar(cmd->cvars, cmd_name, ~0))
1764 Con_Printf(CON_WARN "Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1770 // fail if the command already exists in this interpreter
1771 for (func = cmd->engine_functions; func; func = func->next)
1773 if (!strcmp(cmd_name, func->name))
1775 Con_Printf(CON_WARN "Cmd_AddCommand: %s already defined\n", cmd_name);
1780 func = (cmd_function_t *)Mem_Alloc(cmd->mempool, sizeof(cmd_function_t));
1781 func->flags = flags;
1782 func->name = cmd_name;
1783 func->function = function;
1784 func->description = description;
1785 func->next = cmd->engine_functions;
1787 // insert it at the right alphanumeric position
1788 for (prev = NULL, current = cmd->engine_functions; current && strcmp(current->name, func->name) < 0; prev = current, current = current->next)
1794 cmd->engine_functions = func;
1796 func->next = current;
1800 // mark qcfunc if the function already exists in the qc_functions list
1801 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1803 if (!strcmp(cmd_name, func->name))
1805 func->qcfunc = true; //[515]: csqc
1810 func = (cmd_function_t *)Mem_Alloc(cmd->mempool, sizeof(cmd_function_t));
1811 func->flags = flags;
1812 func->name = cmd_name;
1813 func->function = function;
1814 func->description = description;
1815 func->qcfunc = true; //[515]: csqc
1816 func->next = cmd->userdefined->qc_functions;
1818 // bones_was_here: if this QC command overrides an engine command, store its pointer
1819 // to avoid doing this search at invocation if QC declines to handle this command.
1820 for (cmd_function_t *f = cmd->engine_functions; f; f = f->next)
1822 if (!strcmp(cmd_name, f->name))
1824 Con_DPrintf("Adding QC override of engine command %s\n", cmd_name);
1825 func->overridden = f;
1830 // insert it at the right alphanumeric position
1831 for (prev = NULL, current = cmd->userdefined->qc_functions; current && strcmp(current->name, func->name) < 0; prev = current, current = current->next)
1837 cmd->userdefined->qc_functions = func;
1839 func->next = current;
1850 qbool Cmd_Exists (cmd_state_t *cmd, const char *cmd_name)
1852 cmd_function_t *func;
1854 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1855 if (!strcmp(cmd_name, func->name))
1858 for (func=cmd->engine_functions ; func ; func=func->next)
1859 if (!strcmp (cmd_name,func->name))
1871 const char *Cmd_CompleteCommand (cmd_state_t *cmd, const char *partial)
1873 cmd_function_t *func;
1876 len = strlen(partial);
1882 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1883 if (!strncasecmp(partial, func->name, len))
1886 for (func = cmd->engine_functions; func; func = func->next)
1887 if (!strncasecmp(partial, func->name, len))
1894 Cmd_CompleteCountPossible
1896 New function for tab-completion system
1897 Added by EvilTypeGuy
1898 Thanks to Fett erich@heintz.com
1902 int Cmd_CompleteCountPossible (cmd_state_t *cmd, const char *partial)
1904 cmd_function_t *func;
1909 len = strlen(partial);
1914 // Loop through the command list and count all partial matches
1915 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1916 if (!strncasecmp(partial, func->name, len))
1919 for (func = cmd->engine_functions; func; func = func->next)
1920 if (!strncasecmp(partial, func->name, len))
1927 Cmd_CompleteBuildList
1929 New function for tab-completion system
1930 Added by EvilTypeGuy
1931 Thanks to Fett erich@heintz.com
1935 const char **Cmd_CompleteBuildList (cmd_state_t *cmd, const char *partial)
1937 cmd_function_t *func;
1940 size_t sizeofbuf = (Cmd_CompleteCountPossible (cmd, partial) + 1) * sizeof (const char *);
1943 len = strlen(partial);
1944 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1945 // Loop through the functions lists and print all matches
1946 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1947 if (!strncasecmp(partial, func->name, len))
1948 buf[bpos++] = func->name;
1949 for (func = cmd->engine_functions; func; func = func->next)
1950 if (!strncasecmp(partial, func->name, len))
1951 buf[bpos++] = func->name;
1957 // written by LadyHavoc
1958 void Cmd_CompleteCommandPrint (cmd_state_t *cmd, const char *partial)
1960 cmd_function_t *func;
1961 size_t len = strlen(partial);
1962 // Loop through the command list and print all matches
1963 for (func = cmd->userdefined->qc_functions; func; func = func->next)
1964 if (!strncasecmp(partial, func->name, len))
1965 Con_Printf("^2%s^7: %s\n", func->name, func->description);
1966 for (func = cmd->engine_functions; func; func = func->next)
1967 if (!strncasecmp(partial, func->name, len))
1968 Con_Printf("^2%s^7: %s\n", func->name, func->description);
1974 New function for tab-completion system
1975 Added by EvilTypeGuy
1976 Thanks to Fett erich@heintz.com
1980 const char *Cmd_CompleteAlias (cmd_state_t *cmd, const char *partial)
1985 len = strlen(partial);
1991 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
1992 if (!strncasecmp(partial, alias->name, len))
1998 // written by LadyHavoc
1999 void Cmd_CompleteAliasPrint (cmd_state_t *cmd, const char *partial)
2002 size_t len = strlen(partial);
2003 // Loop through the alias list and print all matches
2004 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2005 if (!strncasecmp(partial, alias->name, len))
2006 Con_Printf("^5%s^7: %s", alias->name, alias->value);
2011 Cmd_CompleteAliasCountPossible
2013 New function for tab-completion system
2014 Added by EvilTypeGuy
2015 Thanks to Fett erich@heintz.com
2019 int Cmd_CompleteAliasCountPossible (cmd_state_t *cmd, const char *partial)
2027 len = strlen(partial);
2032 // Loop through the command list and count all partial matches
2033 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2034 if (!strncasecmp(partial, alias->name, len))
2041 Cmd_CompleteAliasBuildList
2043 New function for tab-completion system
2044 Added by EvilTypeGuy
2045 Thanks to Fett erich@heintz.com
2049 const char **Cmd_CompleteAliasBuildList (cmd_state_t *cmd, const char *partial)
2054 size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (cmd, partial) + 1) * sizeof (const char *);
2057 len = strlen(partial);
2058 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
2059 // Loop through the alias list and print all matches
2060 for (alias = cmd->userdefined->alias; alias; alias = alias->next)
2061 if (!strncasecmp(partial, alias->name, len))
2062 buf[bpos++] = alias->name;
2068 // TODO: Make this more generic?
2069 void Cmd_ClearCSQCCommands (cmd_state_t *cmd)
2071 cmd_function_t *func;
2072 cmd_function_t **next = &cmd->userdefined->qc_functions;
2082 extern cvar_t sv_cheats;
2085 * Cloudwalk FIXME: This idea sounded great in my head but...
2086 * How do we handle commands that can be received by the client,
2087 * but which the server can also execute locally?
2089 * If we create a callback where the engine will forward to server
2090 * but try to execute the command locally if it's dedicated,
2091 * we're back to intermixing client and server code which I'm
2092 * trying to avoid. There's no other way I can think of to
2093 * implement that behavior that doesn't involve an #ifdef, or
2094 * making a mess of hooks.
2096 qbool Cmd_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2099 func->function(cmd);
2101 Con_Printf(CON_WARN "Command \"%s\" can not be executed\n", Cmd_Argv(cmd, 0));
2105 qbool Cmd_CL_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2107 // TODO: Assign these functions to QC commands directly?
2110 if(((func->flags & CF_CLIENT) && CL_VM_ConsoleCommand(text)) ||
2111 ((func->flags & CF_SERVER) && SV_VM_ConsoleCommand(text)))
2114 if (func->overridden) // If this QC command overrides an engine command,
2115 func = func->overridden; // fall back to that command.
2117 if (func->flags & CF_SERVER_FROM_CLIENT)
2119 if(host_isclient.integer)
2121 CL_ForwardToServer_f(cmd);
2124 else if(!(func->flags & CF_SERVER))
2126 Con_Printf(CON_WARN "Cannot execute client commands from a dedicated server console.\n");
2130 return Cmd_Callback(cmd, func, text, src);
2133 qbool Cmd_SV_Callback(cmd_state_t *cmd, cmd_function_t *func, const char *text, cmd_source_t src)
2135 if(func->qcfunc && (func->flags & CF_SERVER))
2136 return SV_VM_ConsoleCommand(text);
2137 else if (src == src_client)
2139 if((func->flags & CF_CHEAT) && !sv_cheats.integer)
2140 SV_ClientPrintf(CON_WARN "No cheats allowed. The server must have sv_cheats set to 1\n");
2142 func->function(cmd);
2152 A complete command line has been parsed, so try to execute it
2153 FIXME: lookupnoadd the token to speed search?
2156 void Cmd_ExecuteString (cmd_state_t *cmd, const char *text, cmd_source_t src, qbool lockmutex)
2159 cmd_function_t *func;
2163 Cbuf_Lock(cmd->cbuf);
2164 oldpos = cmd->cbuf->tokenizebufferpos;
2167 Cmd_TokenizeString (cmd, text);
2169 // execute the command line
2171 goto done; // no tokens
2174 for (func = cmd->userdefined->qc_functions; func; func = func->next)
2175 if (!strcasecmp(cmd->argv[0], func->name))
2176 if(cmd->Handle(cmd, func, text, src))
2177 goto functions_done;
2179 for (func = cmd->engine_functions; func; func=func->next)
2180 if (!strcasecmp (cmd->argv[0], func->name))
2181 if(cmd->Handle(cmd, func, text, src))
2182 goto functions_done;
2185 // If it's a client command and wasn't found and handled, say so.
2186 // Also don't let clients call server aliases.
2187 if (cmd->source == src_client)
2190 Con_Printf("Client \"%s\" tried to execute \"%s\"\n", host_client->name, text);
2195 // Execute any alias with the same name as a command after the command.
2196 for (a=cmd->userdefined->alias ; a ; a=a->next)
2198 if (!strcasecmp (cmd->argv[0], a->name))
2200 Cmd_ExecuteAlias(cmd, a);
2205 // If the command was found and handled don't try to handle it as a cvar.
2210 if (!Cvar_Command(cmd) && host.framecount > 0)
2211 Con_Printf(CON_WARN "Unknown command \"%s\"\n", Cmd_Argv(cmd, 0));
2213 cmd->cbuf->tokenizebufferpos = oldpos;
2215 Cbuf_Unlock(cmd->cbuf);
2222 Returns the position (1 to argc-1) in the command's argument list
2223 where the given parameter apears, or 0 if not present
2227 int Cmd_CheckParm (cmd_state_t *cmd, const char *parm)
2233 Con_Printf(CON_WARN "Cmd_CheckParm: NULL");
2237 for (i = 1; i < Cmd_Argc (cmd); i++)
2238 if (!strcasecmp (parm, Cmd_Argv(cmd, i)))
2246 void Cmd_SaveInitState(void)
2248 cmd_iter_t *cmd_iter;
2249 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
2251 cmd_state_t *cmd = cmd_iter->cmd;
2254 for (f = cmd->userdefined->qc_functions; f; f = f->next)
2255 f->initstate = true;
2256 for (f = cmd->engine_functions; f; f = f->next)
2257 f->initstate = true;
2258 for (a = cmd->userdefined->alias; a; a = a->next)
2260 a->initstate = true;
2261 a->initialvalue = Mem_strdup(zonemempool, a->value);
2264 Cvar_SaveInitState(&cvars_all);
2267 void Cmd_RestoreInitState(void)
2269 cmd_iter_t *cmd_iter;
2270 for (cmd_iter = cmd_iter_all; cmd_iter->cmd; cmd_iter++)
2272 cmd_state_t *cmd = cmd_iter->cmd;
2273 cmd_function_t *f, **fp;
2274 cmd_alias_t *a, **ap;
2275 for (fp = &cmd->userdefined->qc_functions; (f = *fp);)
2281 // destroy this command, it didn't exist at init
2282 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
2287 for (fp = &cmd->engine_functions; (f = *fp);)
2293 // destroy this command, it didn't exist at init
2294 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
2299 for (ap = &cmd->userdefined->alias; (a = *ap);)
2303 // restore this alias, it existed at init
2304 if (strcmp(a->value ? a->value : "", a->initialvalue ? a->initialvalue : ""))
2306 Con_DPrintf("Cmd_RestoreInitState: Restoring alias %s\n", a->name);
2309 a->value = Mem_strdup(zonemempool, a->initialvalue);
2315 // free this alias, it didn't exist at init...
2316 Con_DPrintf("Cmd_RestoreInitState: Destroying alias %s\n", a->name);
2324 Cvar_RestoreInitState(&cvars_all);
2327 void Cmd_NoOperation_f(cmd_state_t *cmd)