From 81a36bb3add1f086f67014ab20d5a629e25e5946 Mon Sep 17 00:00:00 2001 From: Yamagi Burmeister Date: Mon, 2 Sep 2019 17:54:02 +0200 Subject: [PATCH] Add 'dec' and 'inc' operations. 'dec' decrements and 'inc' increments a given cvar either by 1 or a given value. The code was taken from q2pro. This closes issue #414. --- doc/04_cvarlist.md | 6 ++++ src/common/cvar.c | 79 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) diff --git a/doc/04_cvarlist.md b/doc/04_cvarlist.md index e81e5a6a..af9f3b91 100644 --- a/doc/04_cvarlist.md +++ b/doc/04_cvarlist.md @@ -261,6 +261,12 @@ cvar operations are special commands that allow the programmatic manipulation of cvar values. They can be used for scripting and the like. +* **dec [val]**: Decrements the given cvar by `1` or the optional + value `val`. + +* **inc [val]**: Increments the given cvar by `1` or the optional + value `val`. + * **reset **: Reset the given cvar to it's default value. * **resetall**: Reset all known cvar to their default values. diff --git a/src/common/cvar.c b/src/common/cvar.c index 134e5ce9..b42bdf45 100644 --- a/src/common/cvar.c +++ b/src/common/cvar.c @@ -135,6 +135,37 @@ Cvar_FindVar(const char *var_name) return NULL; } +static qboolean +Cvar_IsFloat(const char *s) +{ + int c, dot = '.'; + + if (*s == '-') + { + s++; + } + + if (!*s) + { + return false; + } + + do { + c = *s++; + + if (c == dot) + { + dot = 0; + } + else if (!(c >= '0' || c <= '9')) + { + return false; + } + } while (*s); + + return true; +} + float Cvar_VariableValue(char *var_name) { @@ -650,6 +681,50 @@ Cvar_Serverinfo(void) return Cvar_BitInfo(CVAR_SERVERINFO); } +/* + * Increments the given cvar by 1 or adds the + * optional given float value to it. + */ +void Cvar_Inc_f(void) +{ + char string[MAX_QPATH]; + cvar_t *var; + float value; + + if (Cmd_Argc() < 2) + { + Com_Printf("Usage: %s [value]\n", Cmd_Argv(0)); + return; + } + + var = Cvar_FindVar(Cmd_Argv(1)); + + if (!var) + { + Com_Printf("%s is not a cvar\n", Cmd_Argv(1)); + return; + } + + if (!Cvar_IsFloat(var->string)) + { + Com_Printf("\"%s\" is \"%s\", can't %s\n", var->name, var->string, Cmd_Argv(0)); + return; + } + + value = 1; + + if (Cmd_Argc() > 2) { + value = atof(Cmd_Argv(2)); + } + + if (!strcmp(Cmd_Argv(0), "dec")) { + value = -value; + } + + Com_sprintf(string, sizeof(string), "%f", var->value + value); + Cvar_Set(var->name, string); +} + /* * Resets a cvar to its default value. */ @@ -759,6 +834,8 @@ void Cvar_Init(void) { Cmd_AddCommand("cvarlist", Cvar_List_f); + Cmd_AddCommand("dec", Cvar_Inc_f); + Cmd_AddCommand("inc", Cvar_Inc_f); Cmd_AddCommand("reset", Cvar_Reset_f); Cmd_AddCommand("resetall", Cvar_ResetAll_f); Cmd_AddCommand("set", Cvar_Set_f); @@ -783,6 +860,8 @@ Cvar_Fini(void) } Cmd_RemoveCommand("cvarlist"); + Cmd_RemoveCommand("dec"); + Cmd_RemoveCommand("inc"); Cmd_RemoveCommand("reset"); Cmd_RemoveCommand("resetall"); Cmd_RemoveCommand("set");