diff --git a/.idea/dictionaries/project.xml b/.idea/dictionaries/project.xml new file mode 100644 index 0000000..530a253 --- /dev/null +++ b/.idea/dictionaries/project.xml @@ -0,0 +1,7 @@ + + + + convar + + + \ No newline at end of file diff --git a/.idea/editor.xml b/.idea/editor.xml index ca29dcc..fef590b 100644 --- a/.idea/editor.xml +++ b/.idea/editor.xml @@ -1,6 +1,255 @@ + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + { + "associatedIndex": 6, + "fromUser": false +} - - - - - { + "profileIdByStamp": [ { - "first": { - "##RUN_CONFIGURATION##": "CMake Application.quakespasm", - "cmake": "CMakeBuildProfile:Debug" + "first": { + "##RUN_CONFIGURATION##": "CMake Application.quakespasm", + "cmake": "CMakeBuildProfile:Debug" }, - "second": "27852a6b-aee6-4e6c-a703-78c08d632bb7" + "second": "27852a6b-aee6-4e6c-a703-78c08d632bb7" } ], - "modificationCount": 4 -}]]> + "modificationCount": 4 +} @@ -139,4 +212,8 @@ + + + \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index 4ac2018..cc17ed1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7,7 +7,7 @@ find_package(SDL) find_package(SDL_net) find_package(OpenGL) -add_executable(quakespasm Quake/bgmusic.cpp Quake/cd_sdl.cpp Quake/cfgfile.cpp Quake/chase.cpp Quake/cl_demo.cpp Quake/cl_input.cpp Quake/cl_main.cpp Quake/cl_parse.cpp Quake/cl_tent.cpp Quake/cmd.cpp Quake/common.cpp Quake/console.cpp Quake/crc.cpp Quake/cvar.cpp Quake/gl_draw.cpp Quake/gl_fog.cpp Quake/gl_mesh.cpp Quake/gl_model.cpp Quake/gl_refrag.cpp Quake/gl_rlight.cpp Quake/gl_rmain.cpp Quake/gl_rmisc.cpp Quake/gl_screen.cpp Quake/gl_sky.cpp Quake/gl_texmgr.cpp Quake/gl_vidsdl.cpp Quake/gl_warp.cpp Quake/host.cpp Quake/host_cmd.cpp Quake/image.cpp Quake/in_sdl.cpp Quake/keys.cpp Quake/main_sdl.cpp Quake/mathlib.cpp Quake/menu.cpp Quake/miniz.cpp Quake/net_bsd.cpp Quake/net_dgrm.cpp Quake/net_loop.cpp Quake/net_main.cpp Quake/net_udp.cpp Quake/pl_linux.cpp Quake/pr_cmds.cpp Quake/pr_edict.cpp Quake/pr_exec.cpp Quake/r_alias.cpp Quake/r_brush.cpp Quake/r_part.cpp Quake/r_sprite.cpp Quake/r_world.cpp Quake/sbar.cpp Quake/snd_codec.cpp Quake/snd_dma.cpp Quake/snd_flac.cpp Quake/snd_mem.cpp Quake/snd_mikmod.cpp Quake/snd_mix.cpp Quake/snd_modplug.cpp Quake/snd_mp3.cpp Quake/snd_mp3tag.cpp Quake/snd_mpg123.cpp Quake/snd_opus.cpp Quake/snd_sdl.cpp Quake/snd_umx.cpp Quake/snd_vorbis.cpp Quake/snd_wave.cpp Quake/snd_xmp.cpp Quake/strlcat.cpp Quake/strlcpy.cpp Quake/sv_main.cpp Quake/sv_move.cpp Quake/sv_phys.cpp Quake/sv_user.cpp Quake/sys_sdl_unix.cpp Quake/view.cpp Quake/wad.cpp Quake/world.cpp Quake/zone.cpp ) +add_executable(quakespasm Quake/bgmusic.cpp Quake/cd_sdl.cpp Quake/cfgfile.cpp Quake/chase.cpp Quake/cl_demo.cpp Quake/cl_input.cpp Quake/cl_main.cpp Quake/cl_parse.cpp Quake/cl_tent.cpp Quake/cmd.cpp Quake/common.cpp Quake/console.cpp Quake/crc.cpp Quake/convar.cpp Quake/gl_draw.cpp Quake/gl_fog.cpp Quake/gl_mesh.cpp Quake/gl_model.cpp Quake/gl_refrag.cpp Quake/gl_rlight.cpp Quake/gl_rmain.cpp Quake/gl_rmisc.cpp Quake/gl_screen.cpp Quake/gl_sky.cpp Quake/gl_texmgr.cpp Quake/gl_vidsdl.cpp Quake/gl_warp.cpp Quake/host.cpp Quake/host_cmd.cpp Quake/image.cpp Quake/in_sdl.cpp Quake/keys.cpp Quake/main_sdl.cpp Quake/mathlib.cpp Quake/menu.cpp Quake/miniz.cpp Quake/net_bsd.cpp Quake/net_dgrm.cpp Quake/net_loop.cpp Quake/net_main.cpp Quake/net_udp.cpp Quake/pl_linux.cpp Quake/pr_cmds.cpp Quake/pr_edict.cpp Quake/pr_exec.cpp Quake/r_alias.cpp Quake/r_brush.cpp Quake/r_part.cpp Quake/r_sprite.cpp Quake/r_world.cpp Quake/sbar.cpp Quake/snd_codec.cpp Quake/snd_dma.cpp Quake/snd_flac.cpp Quake/snd_mem.cpp Quake/snd_mikmod.cpp Quake/snd_mix.cpp Quake/snd_modplug.cpp Quake/snd_mp3.cpp Quake/snd_mp3tag.cpp Quake/snd_mpg123.cpp Quake/snd_opus.cpp Quake/snd_sdl.cpp Quake/snd_umx.cpp Quake/snd_vorbis.cpp Quake/snd_wave.cpp Quake/snd_xmp.cpp Quake/strlcat.cpp Quake/strlcpy.cpp Quake/sv_main.cpp Quake/sv_move.cpp Quake/sv_phys.cpp Quake/sv_user.cpp Quake/sys_sdl_unix.cpp Quake/view.cpp Quake/wad.cpp Quake/world.cpp Quake/zone.cpp ) target_link_libraries(quakespasm OpenGL::GL) target_link_libraries(quakespasm SDL::SDL) diff --git a/Misc/fix_externaltex.patch b/Misc/fix_externaltex.patch index d18ac0f..2459a82 100644 --- a/Misc/fix_externaltex.patch +++ b/Misc/fix_externaltex.patch @@ -104,10 +104,10 @@ index 963d55e..e9b251b 100644 extern gltexture_t *playertextures[MAX_SCOREBOARD]; //johnfitz @@ -230,6 +231,7 @@ void R_Init (void) - Cvar_SetCallback (&r_lavaalpha, R_SetLavaalpha_f); - Cvar_SetCallback (&r_telealpha, R_SetTelealpha_f); - Cvar_SetCallback (&r_slimealpha, R_SetSlimealpha_f); -+ Cvar_RegisterVariable (&r_externaltexture_fix);//mk + r_lavaalpha.set_callback(R_SetLavaalpha_f); + r_telealpha.set_callback(R_SetTelealpha_f); + r_slimealpha.set_callback(R_SetSlimealpha_f); ++ r_externaltexture_fix.inscribe();//mk R_InitParticles (); R_SetClearColor_f (&r_clearcolor); //johnfitz diff --git a/Quake/bgmusic.cpp b/Quake/bgmusic.cpp index 65902df..aa612e3 100644 --- a/Quake/bgmusic.cpp +++ b/Quake/bgmusic.cpp @@ -29,7 +29,7 @@ #define MUSIC_DIRNAME "music" qboolean bgmloop; -cvar_t bgm_extmusic = {"bgm_extmusic", "1", CVAR_ARCHIVE}; +convar bgm_extmusic{"bgm_extmusic", "1", {.archive = true}}; static qboolean no_extmusic= false; static float old_volume = -1.0f; @@ -76,8 +76,8 @@ static snd_stream_t *bgmstream = NULL; static void BGM_Play_f (void) { - if (Cmd_Argc() == 2) { - BGM_Play (Cmd_Argv(1)); + if (command::argc() == 2) { + BGM_Play (command::argv(1)->c_str()); } else { Con_Printf ("music \n"); @@ -96,14 +96,14 @@ static void BGM_Resume_f (void) static void BGM_Loop_f (void) { - if (Cmd_Argc() == 2) { - if (q_strcasecmp(Cmd_Argv(1), "0") == 0 || - q_strcasecmp(Cmd_Argv(1),"off") == 0) + if (command::argc() == 2) { + if (q_strcasecmp(command::argv(1)->c_str(), "0") == 0 || + q_strcasecmp(command::argv(1)->c_str(),"off") == 0) bgmloop = false; - else if (q_strcasecmp(Cmd_Argv(1), "1") == 0 || - q_strcasecmp(Cmd_Argv(1),"on") == 0) + else if (q_strcasecmp(command::argv(1)->c_str(), "1") == 0 || + q_strcasecmp(command::argv(1)->c_str(),"on") == 0) bgmloop = true; - else if (q_strcasecmp(Cmd_Argv(1),"toggle") == 0) + else if (q_strcasecmp(command::argv(1)->c_str(),"toggle") == 0) bgmloop = !bgmloop; if (bgmstream) bgmstream->loop = bgmloop; @@ -122,11 +122,11 @@ static void BGM_Stop_f (void) static void BGM_Jump_f (void) { - if (Cmd_Argc() != 2) { + if (command::argc() != 2) { Con_Printf ("music_jump \n"); } else if (bgmstream) { - S_CodecJumpToOrder(bgmstream, atoi(Cmd_Argv(1))); + S_CodecJumpToOrder(bgmstream, atoi(command::argv(1)->c_str())); } } @@ -135,13 +135,13 @@ qboolean BGM_Init (void) music_handler_t *handlers = NULL; int i; - Cvar_RegisterVariable(&bgm_extmusic); - Cmd_AddCommand("music", BGM_Play_f); - Cmd_AddCommand("music_pause", BGM_Pause_f); - Cmd_AddCommand("music_resume", BGM_Resume_f); - Cmd_AddCommand("music_loop", BGM_Loop_f); - Cmd_AddCommand("music_stop", BGM_Stop_f); - Cmd_AddCommand("music_jump", BGM_Jump_f); + bgm_extmusic.inscribe(); + command::add("music", BGM_Play_f); + command::add("music_pause", BGM_Pause_f); + command::add("music_resume", BGM_Resume_f); + command::add("music_loop", BGM_Loop_f); + command::add("music_stop", BGM_Stop_f); + command::add("music_jump", BGM_Jump_f); if (COM_CheckParm("-noextmusic") != 0) no_extmusic = true; @@ -467,9 +467,9 @@ void BGM_Update (void) if (old_volume != bgmvolume.value) { if (bgmvolume.value < 0) - Cvar_SetQuick (&bgmvolume, "0"); + bgmvolume.set("0"); else if (bgmvolume.value > 1) - Cvar_SetQuick (&bgmvolume, "1"); + bgmvolume.set("1"); old_volume = bgmvolume.value; } if (bgmstream) diff --git a/Quake/bgmusic.hpp b/Quake/bgmusic.hpp index ec30820..0337d05 100644 --- a/Quake/bgmusic.hpp +++ b/Quake/bgmusic.hpp @@ -26,7 +26,7 @@ #define _BGMUSIC_H_ extern qboolean bgmloop; -extern cvar_t bgm_extmusic; +extern convar bgm_extmusic; qboolean BGM_Init (void); void BGM_Shutdown (void); diff --git a/Quake/cd_sdl.cpp b/Quake/cd_sdl.cpp index 1acd9d9..efa9579 100644 --- a/Quake/cd_sdl.cpp +++ b/Quake/cd_sdl.cpp @@ -221,7 +221,7 @@ static void CD_f (void) const char *command; int ret, n; - if (Cmd_Argc() < 2) + if (command::argc() < 2) { Con_Printf("commands:"); Con_Printf("on, off, reset, remap, \n"); @@ -230,7 +230,7 @@ static void CD_f (void) return; } - command = Cmd_Argv (1); + command = command::argv (1)->c_str(); if (q_strcasecmp(command, "on") == 0) { @@ -259,7 +259,7 @@ static void CD_f (void) if (q_strcasecmp(command, "remap") == 0) { - ret = Cmd_Argc() - 2; + ret = command::argc() - 2; if (ret <= 0) { for (n = 1; n < 100; n++) @@ -268,7 +268,7 @@ static void CD_f (void) return; } for (n = 1; n <= ret; n++) - remap[n] = atoi(Cmd_Argv (n + 1)); + remap[n] = atoi(command::argv (n + 1)->c_str()); return; } @@ -284,7 +284,7 @@ static void CD_f (void) if (q_strcasecmp(command, "play") == 0) { - n = atoi(Cmd_Argv (2)); + n = atoi(command::argv (2)->c_str()); if (n == 0) n = 1; CDAudio_Play((byte)n, false); @@ -293,7 +293,7 @@ static void CD_f (void) if (q_strcasecmp(command, "loop") == 0) { - CDAudio_Play((byte)atoi(Cmd_Argv (2)), true); + CDAudio_Play((byte)atoi(command::argv (2)->c_str()), true); return; } @@ -564,7 +564,7 @@ int CDAudio_Init(void) cdValid = false; } - Cmd_AddCommand ("cd", CD_f); + command::add ("cd", CD_f); hw_vol_works = CD_GetVolume (NULL); /* no SDL support at present. */ if (hw_vol_works) diff --git a/Quake/cfgfile.cpp b/Quake/cfgfile.cpp index 00c459d..7679356 100644 --- a/Quake/cfgfile.cpp +++ b/Quake/cfgfile.cpp @@ -94,7 +94,7 @@ void CFG_ReadCvars (const char **vars, int num_vars) tmp = strchr(buff, '\"'); if (tmp) { - Cvar_Set (vars[i], tmp + 1); + convar::set(vars[i], tmp + 1); j++; break; } @@ -135,7 +135,7 @@ void CFG_ReadCvarOverrides (const char **vars, int num_vars) if (j != 0 && j < com_argc - 1) { if (com_argv[j + 1][0] != '-' && com_argv[j + 1][0] != '+') - Cvar_Set(vars[i], com_argv[j + 1]); + convar::set(vars[i], com_argv[j + 1]); } } } diff --git a/Quake/chase.cpp b/Quake/chase.cpp index 870312b..e1c4462 100644 --- a/Quake/chase.cpp +++ b/Quake/chase.cpp @@ -23,10 +23,10 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.hpp" -cvar_t chase_back = {"chase_back", "100", CVAR_NONE}; -cvar_t chase_up = {"chase_up", "16", CVAR_NONE}; -cvar_t chase_right = {"chase_right", "0", CVAR_NONE}; -cvar_t chase_active = {"chase_active", "0", CVAR_NONE}; +convar chase_back{"chase_back", "100"}; +convar chase_up{"chase_up", "16"}; +convar chase_right{"chase_right", "0"}; +convar chase_active{"chase_active", "0"}; /* ============== @@ -35,10 +35,10 @@ Chase_Init */ void Chase_Init (void) { - Cvar_RegisterVariable (&chase_back); - Cvar_RegisterVariable (&chase_up); - Cvar_RegisterVariable (&chase_right); - Cvar_RegisterVariable (&chase_active); + chase_back.inscribe(); + chase_up.inscribe(); + chase_right.inscribe(); + chase_active.inscribe(); } /* diff --git a/Quake/cl_demo.cpp b/Quake/cl_demo.cpp index 331f975..f97411c 100644 --- a/Quake/cl_demo.cpp +++ b/Quake/cl_demo.cpp @@ -20,6 +20,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include +#include #include "quakedef.hpp" @@ -202,7 +203,7 @@ stop recording a demo */ void CL_Stop_f (void) { - if (cmd_source != src_command) + if (command::last_source != command::source::command) return; if (!cls.demorecording) @@ -239,7 +240,7 @@ void CL_Record_f (void) char name[MAX_OSPATH]; int track; - if (cmd_source != src_command) + if (command::last_source != command::source::command) return; if (cls.demoplayback) @@ -251,14 +252,14 @@ void CL_Record_f (void) if (cls.demorecording) CL_Stop_f(); - c = Cmd_Argc(); + c = command::argc(); if (c != 2 && c != 3 && c != 4) { Con_Printf ("record [ [cd track]]\n"); return; } - if (strstr(Cmd_Argv(1), "..")) + if (strstr(command::argv(1).value_or("").c_str(), "..")) { Con_Printf ("Relative pathnames are not allowed.\n"); return; @@ -280,7 +281,7 @@ void CL_Record_f (void) // write the forced cd track number, or -1 if (c == 4) { - track = atoi(Cmd_Argv(3)); + track = atoi(command::argv(3)->c_str()); Con_Printf ("Forcing CD track to %i\n", cls.forcetrack); } else @@ -288,12 +289,12 @@ void CL_Record_f (void) track = -1; } - q_snprintf (name, sizeof(name), "%s/%s", com_gamedir, Cmd_Argv(1)); + q_snprintf (name, sizeof(name), "%s/%s", com_gamedir, command::argv(1).value_or("").c_str()); // start the map up if (c > 2) { - Cmd_ExecuteString ( va("map %s", Cmd_Argv(2)), src_command); + command::execute_string ( std::format("map {:s}", *command::argv(2)), command::source::command); if (cls.state != ca_connected) return; } @@ -403,10 +404,10 @@ void CL_PlayDemo_f (void) { char name[MAX_OSPATH]; - if (cmd_source != src_command) + if (command::last_source != command::source::command) return; - if (Cmd_Argc() != 2) + if (command::argc() != 2) { Con_Printf ("playdemo : plays a demo\n"); return; @@ -416,7 +417,7 @@ void CL_PlayDemo_f (void) CL_Disconnect (); // open the demo file - std::strncpy(name, Cmd_Argv(1), sizeof(name)); + std::strncpy(name, command::argv(1).value_or("").c_str(), sizeof(name)); COM_AddExtension (name, ".dem", sizeof(name)); Con_Printf ("Playing demo from %s.\n", name); @@ -480,10 +481,10 @@ timedemo [demoname] */ void CL_TimeDemo_f (void) { - if (cmd_source != src_command) + if (command::last_source != command::source::command) return; - if (Cmd_Argc() != 2) + if (command::argc() != 2) { Con_Printf ("timedemo : gets demo speeds\n"); return; diff --git a/Quake/cl_input.cpp b/Quake/cl_input.cpp index cd72ab7..d14ebf3 100644 --- a/Quake/cl_input.cpp +++ b/Quake/cl_input.cpp @@ -26,8 +26,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.hpp" -extern cvar_t cl_maxpitch; //johnfitz -- variable pitch clamping -extern cvar_t cl_minpitch; //johnfitz -- variable pitch clamping +extern convar cl_maxpitch; //johnfitz -- variable pitch clamping +extern convar cl_minpitch; //johnfitz -- variable pitch clamping /* =============================================================================== @@ -63,11 +63,10 @@ int in_impulse; void KeyDown (kbutton_t *b) { int k; - const char *c; - c = Cmd_Argv(1); - if (c[0]) - k = atoi(c); + auto c = command::argv(1).value_or(""); + if (!c.empty()) + k = atoi(c.c_str()); else k = -1; // typed manually at the console for continuous down @@ -94,7 +93,7 @@ void KeyUp (kbutton_t *b) int k; const char *c; - c = Cmd_Argv(1); + c = command::argv(1)->c_str(); if (c[0]) k = atoi(c); else @@ -161,7 +160,7 @@ void IN_UseUp (void) {KeyUp(&in_use);} void IN_JumpDown (void) {KeyDown(&in_jump);} void IN_JumpUp (void) {KeyUp(&in_jump);} -void IN_Impulse (void) {in_impulse=Q_atoi(Cmd_Argv(1));} +void IN_Impulse (void) {in_impulse=Q_atoi(command::argv(1)->c_str());} /* =============== @@ -220,19 +219,19 @@ float CL_KeyState (kbutton_t *key) //========================================================================== -cvar_t cl_upspeed = {"cl_upspeed","200",CVAR_NONE}; -cvar_t cl_forwardspeed = {"cl_forwardspeed","200", CVAR_ARCHIVE}; -cvar_t cl_backspeed = {"cl_backspeed","200", CVAR_ARCHIVE}; -cvar_t cl_sidespeed = {"cl_sidespeed","350",CVAR_NONE}; +convar cl_upspeed{"cl_upspeed","200"}; +convar cl_forwardspeed{"cl_forwardspeed","200", {.archive = true}}; +convar cl_backspeed{"cl_backspeed","200", {.archive = true}}; +convar cl_sidespeed{"cl_sidespeed","350"}; -cvar_t cl_movespeedkey = {"cl_movespeedkey","2.0",CVAR_NONE}; +convar cl_movespeedkey{"cl_movespeedkey","2.0"}; -cvar_t cl_yawspeed = {"cl_yawspeed","140",CVAR_NONE}; -cvar_t cl_pitchspeed = {"cl_pitchspeed","150",CVAR_NONE}; +convar cl_yawspeed{"cl_yawspeed","140"}; +convar cl_pitchspeed{"cl_pitchspeed","150"}; -cvar_t cl_anglespeedkey = {"cl_anglespeedkey","1.5",CVAR_NONE}; +convar cl_anglespeedkey{"cl_anglespeedkey","1.5"}; -cvar_t cl_alwaysrun = {"cl_alwaysrun","0",CVAR_ARCHIVE}; // QuakeSpasm -- new always run +convar cl_alwaysrun{"cl_alwaysrun","0",{.archive = true}}; // QuakeSpasm -- new always run /* ================ @@ -414,41 +413,41 @@ CL_InitInput */ void CL_InitInput (void) { - Cmd_AddCommand ("+moveup",IN_UpDown); - Cmd_AddCommand ("-moveup",IN_UpUp); - Cmd_AddCommand ("+movedown",IN_DownDown); - Cmd_AddCommand ("-movedown",IN_DownUp); - Cmd_AddCommand ("+left",IN_LeftDown); - Cmd_AddCommand ("-left",IN_LeftUp); - Cmd_AddCommand ("+right",IN_RightDown); - Cmd_AddCommand ("-right",IN_RightUp); - Cmd_AddCommand ("+forward",IN_ForwardDown); - Cmd_AddCommand ("-forward",IN_ForwardUp); - Cmd_AddCommand ("+back",IN_BackDown); - Cmd_AddCommand ("-back",IN_BackUp); - Cmd_AddCommand ("+lookup", IN_LookupDown); - Cmd_AddCommand ("-lookup", IN_LookupUp); - Cmd_AddCommand ("+lookdown", IN_LookdownDown); - Cmd_AddCommand ("-lookdown", IN_LookdownUp); - Cmd_AddCommand ("+strafe", IN_StrafeDown); - Cmd_AddCommand ("-strafe", IN_StrafeUp); - Cmd_AddCommand ("+moveleft", IN_MoveleftDown); - Cmd_AddCommand ("-moveleft", IN_MoveleftUp); - Cmd_AddCommand ("+moveright", IN_MoverightDown); - Cmd_AddCommand ("-moveright", IN_MoverightUp); - Cmd_AddCommand ("+speed", IN_SpeedDown); - Cmd_AddCommand ("-speed", IN_SpeedUp); - Cmd_AddCommand ("+attack", IN_AttackDown); - Cmd_AddCommand ("-attack", IN_AttackUp); - Cmd_AddCommand ("+use", IN_UseDown); - Cmd_AddCommand ("-use", IN_UseUp); - Cmd_AddCommand ("+jump", IN_JumpDown); - Cmd_AddCommand ("-jump", IN_JumpUp); - Cmd_AddCommand ("impulse", IN_Impulse); - Cmd_AddCommand ("+klook", IN_KLookDown); - Cmd_AddCommand ("-klook", IN_KLookUp); - Cmd_AddCommand ("+mlook", IN_MLookDown); - Cmd_AddCommand ("-mlook", IN_MLookUp); + command::add ("+moveup",IN_UpDown); + command::add ("-moveup",IN_UpUp); + command::add ("+movedown",IN_DownDown); + command::add ("-movedown",IN_DownUp); + command::add ("+left",IN_LeftDown); + command::add ("-left",IN_LeftUp); + command::add ("+right",IN_RightDown); + command::add ("-right",IN_RightUp); + command::add ("+forward",IN_ForwardDown); + command::add ("-forward",IN_ForwardUp); + command::add ("+back",IN_BackDown); + command::add ("-back",IN_BackUp); + command::add ("+lookup", IN_LookupDown); + command::add ("-lookup", IN_LookupUp); + command::add ("+lookdown", IN_LookdownDown); + command::add ("-lookdown", IN_LookdownUp); + command::add ("+strafe", IN_StrafeDown); + command::add ("-strafe", IN_StrafeUp); + command::add ("+moveleft", IN_MoveleftDown); + command::add ("-moveleft", IN_MoveleftUp); + command::add ("+moveright", IN_MoverightDown); + command::add ("-moveright", IN_MoverightUp); + command::add ("+speed", IN_SpeedDown); + command::add ("-speed", IN_SpeedUp); + command::add ("+attack", IN_AttackDown); + command::add ("-attack", IN_AttackUp); + command::add ("+use", IN_UseDown); + command::add ("-use", IN_UseUp); + command::add ("+jump", IN_JumpDown); + command::add ("-jump", IN_JumpUp); + command::add ("impulse", IN_Impulse); + command::add ("+klook", IN_KLookDown); + command::add ("-klook", IN_KLookUp); + command::add ("+mlook", IN_MLookDown); + command::add ("-mlook", IN_MLookUp); } diff --git a/Quake/cl_main.cpp b/Quake/cl_main.cpp index 319010d..91eca7e 100644 --- a/Quake/cl_main.cpp +++ b/Quake/cl_main.cpp @@ -28,27 +28,27 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // references them even when on a unix system. // these two are not intended to be set directly -cvar_t cl_name = {"_cl_name", "player", CVAR_ARCHIVE}; -cvar_t cl_color = {"_cl_color", "0", CVAR_ARCHIVE}; +convar cl_name{"_cl_name", "player", {.archive = true}}; +convar cl_color{"_cl_color", "0", {.archive = true}}; -cvar_t cl_shownet = {"cl_shownet","0",CVAR_NONE}; // can be 0, 1, or 2 -cvar_t cl_nolerp = {"cl_nolerp","0",CVAR_NONE}; +convar cl_shownet{"cl_shownet","0"}; // can be 0, 1, or 2 +convar cl_nolerp{"cl_nolerp","0"}; -cvar_t cfg_unbindall = {"cfg_unbindall", "1", CVAR_ARCHIVE}; +convar cfg_unbindall{"cfg_unbindall", "1", {.archive = true}}; -cvar_t lookspring = {"lookspring","0", CVAR_ARCHIVE}; -cvar_t lookstrafe = {"lookstrafe","0", CVAR_ARCHIVE}; -cvar_t sensitivity = {"sensitivity","3", CVAR_ARCHIVE}; +convar lookspring{"lookspring","0", {.archive = true}}; +convar lookstrafe{"lookstrafe","0", {.archive = true}}; +convar sensitivity{"sensitivity","3", {.archive = true}}; -cvar_t m_pitch = {"m_pitch","0.022", CVAR_ARCHIVE}; -cvar_t m_yaw = {"m_yaw","0.022", CVAR_ARCHIVE}; -cvar_t m_forward = {"m_forward","1", CVAR_ARCHIVE}; -cvar_t m_side = {"m_side","0.8", CVAR_ARCHIVE}; +convar m_pitch{"m_pitch","0.022", {.archive = true}}; +convar m_yaw{"m_yaw","0.022", {.archive = true}}; +convar m_forward{"m_forward","1", {.archive = true}}; +convar m_side{"m_side","0.8", {.archive = true}}; -cvar_t cl_maxpitch = {"cl_maxpitch", "90", CVAR_ARCHIVE}; //johnfitz -- variable pitch clamping -cvar_t cl_minpitch = {"cl_minpitch", "-90", CVAR_ARCHIVE}; //johnfitz -- variable pitch clamping +convar cl_maxpitch{"cl_maxpitch", "90", {.archive = true}}; //johnfitz -- variable pitch clamping +convar cl_minpitch{"cl_minpitch", "-90", {.archive = true}}; //johnfitz -- variable pitch clamping -cvar_t cl_startdemos = {"cl_startdemos", "1", CVAR_ARCHIVE}; +convar cl_startdemos{"cl_startdemos", "1", {.archive = true}}; client_static_t cls; client_state_t cl; @@ -63,7 +63,7 @@ int cl_max_edicts; //johnfitz -- only changes when new map loads int cl_numvisedicts; entity_t *cl_visedicts[MAX_VISEDICTS]; -extern cvar_t r_lerpmodels, r_lerpmove; //johnfitz +extern convar r_lerpmodels, r_lerpmove; //johnfitz /* ===================== @@ -651,13 +651,13 @@ int CL_ReadFromServer (void) if (cl_numvisedicts > 256 && dev_peakstats.visedicts <= 256) Con_DWarning ("%i visedicts exceeds standard limit of 256 (max = %d).\n", cl_numvisedicts, MAX_VISEDICTS); dev_stats.visedicts = cl_numvisedicts; - dev_peakstats.visedicts = q_max(cl_numvisedicts, dev_peakstats.visedicts); + dev_peakstats.visedicts = std::max(cl_numvisedicts, dev_peakstats.visedicts); //temp entities if (num_temp_entities > 64 && dev_peakstats.tempents <= 64) Con_DWarning ("%i tempentities exceeds standard limit of 64 (max = %d).\n", num_temp_entities, MAX_TEMP_ENTITIES); dev_stats.tempents = num_temp_entities; - dev_peakstats.tempents = q_max(num_temp_entities, dev_peakstats.tempents); + dev_peakstats.tempents = std::max(num_temp_entities, dev_peakstats.tempents); //beams for (i=0, b=cl_beams ; i< MAX_BEAMS ; i++, b++) @@ -666,7 +666,7 @@ int CL_ReadFromServer (void) if (num_beams > 24 && dev_peakstats.beams <= 24) Con_DWarning ("%i beams exceeded standard limit of 24 (max = %d).\n", num_beams, MAX_BEAMS); dev_stats.beams = num_beams; - dev_peakstats.beams = q_max(num_beams, dev_peakstats.beams); + dev_peakstats.beams = std::max(num_beams, dev_peakstats.beams); //dlights for (i=0, l=cl_dlights ; i 32 && dev_peakstats.dlights <= 32) Con_DWarning ("%i dlights exceeded standard limit of 32 (max = %d).\n", num_dlights, MAX_DLIGHTS); dev_stats.dlights = num_dlights; - dev_peakstats.dlights = q_max(num_dlights, dev_peakstats.dlights); + dev_peakstats.dlights = std::max(num_dlights, dev_peakstats.dlights); //johnfitz @@ -798,44 +798,44 @@ void CL_Init (void) CL_InitInput (); CL_InitTEnts (); - Cvar_RegisterVariable (&cl_name); - Cvar_RegisterVariable (&cl_color); - Cvar_RegisterVariable (&cl_upspeed); - Cvar_RegisterVariable (&cl_forwardspeed); - Cvar_RegisterVariable (&cl_backspeed); - Cvar_RegisterVariable (&cl_sidespeed); - Cvar_RegisterVariable (&cl_movespeedkey); - Cvar_RegisterVariable (&cl_yawspeed); - Cvar_RegisterVariable (&cl_pitchspeed); - Cvar_RegisterVariable (&cl_anglespeedkey); - Cvar_RegisterVariable (&cl_shownet); - Cvar_RegisterVariable (&cl_nolerp); - Cvar_RegisterVariable (&lookspring); - Cvar_RegisterVariable (&lookstrafe); - Cvar_RegisterVariable (&sensitivity); + cl_name.inscribe(); + cl_color.inscribe(); + cl_upspeed.inscribe(); + cl_forwardspeed.inscribe(); + cl_backspeed.inscribe(); + cl_sidespeed.inscribe(); + cl_movespeedkey.inscribe(); + cl_yawspeed.inscribe(); + cl_pitchspeed.inscribe(); + cl_anglespeedkey.inscribe(); + cl_shownet.inscribe(); + cl_nolerp.inscribe(); + lookspring.inscribe(); + lookstrafe.inscribe(); + sensitivity.inscribe(); - Cvar_RegisterVariable (&cl_alwaysrun); + cl_alwaysrun.inscribe(); - Cvar_RegisterVariable (&m_pitch); - Cvar_RegisterVariable (&m_yaw); - Cvar_RegisterVariable (&m_forward); - Cvar_RegisterVariable (&m_side); + m_pitch.inscribe(); + m_yaw.inscribe(); + m_forward.inscribe(); + m_side.inscribe(); - Cvar_RegisterVariable (&cfg_unbindall); + cfg_unbindall.inscribe(); - Cvar_RegisterVariable (&cl_maxpitch); //johnfitz -- variable pitch clamping - Cvar_RegisterVariable (&cl_minpitch); //johnfitz -- variable pitch clamping + cl_maxpitch.inscribe(); //johnfitz -- variable pitch clamping + cl_minpitch.inscribe(); //johnfitz -- variable pitch clamping - Cvar_RegisterVariable (&cl_startdemos); + cl_startdemos.inscribe(); - Cmd_AddCommand ("entities", CL_PrintEntities_f); - Cmd_AddCommand ("disconnect", CL_Disconnect_f); - Cmd_AddCommand ("record", CL_Record_f); - Cmd_AddCommand ("stop", CL_Stop_f); - Cmd_AddCommand ("playdemo", CL_PlayDemo_f); - Cmd_AddCommand ("timedemo", CL_TimeDemo_f); + command::add ("entities", CL_PrintEntities_f); + command::add ("disconnect", CL_Disconnect_f); + command::add ("record", CL_Record_f); + command::add ("stop", CL_Stop_f); + command::add ("playdemo", CL_PlayDemo_f); + command::add ("timedemo", CL_TimeDemo_f); - Cmd_AddCommand ("tracepos", CL_Tracepos_f); //johnfitz - Cmd_AddCommand ("viewpos", CL_Viewpos_f); //johnfitz + command::add ("tracepos", CL_Tracepos_f); //johnfitz + command::add ("viewpos", CL_Viewpos_f); //johnfitz } diff --git a/Quake/cl_parse.cpp b/Quake/cl_parse.cpp index 0e31f55..518ab92 100644 --- a/Quake/cl_parse.cpp +++ b/Quake/cl_parse.cpp @@ -1067,7 +1067,7 @@ void CL_ParseServerMessage(void) { cl_lightstyle[i].peak = 'a'; for (j = 0; j < cl_lightstyle[i].length; j++) { total += cl_lightstyle[i].map[j] - 'a'; - cl_lightstyle[i].peak = q_max(cl_lightstyle[i].peak, cl_lightstyle[i].map[j]); + cl_lightstyle[i].peak = std::max(cl_lightstyle[i].peak, cl_lightstyle[i].map[j]); } cl_lightstyle[i].average = total / cl_lightstyle[i].length + 'a'; } else @@ -1214,7 +1214,7 @@ void CL_ParseServerMessage(void) { break; case svc_sellscreen: - Cmd_ExecuteString("help", src_command); + command::execute_string("help", command::source::command); break; //johnfitz -- new svc types @@ -1223,7 +1223,7 @@ void CL_ParseServerMessage(void) { break; case svc_bf: - Cmd_ExecuteString("bf", src_command); + command::execute_string("bf", command::source::command); break; case svc_fog: diff --git a/Quake/client.hpp b/Quake/client.hpp index e00d0ad..1c8f412 100644 --- a/Quake/client.hpp +++ b/Quake/client.hpp @@ -230,41 +230,41 @@ typedef struct // // cvars // -extern cvar_t cl_name; -extern cvar_t cl_color; +extern convar cl_name; +extern convar cl_color; -extern cvar_t cl_upspeed; -extern cvar_t cl_forwardspeed; -extern cvar_t cl_backspeed; -extern cvar_t cl_sidespeed; +extern convar cl_upspeed; +extern convar cl_forwardspeed; +extern convar cl_backspeed; +extern convar cl_sidespeed; -extern cvar_t cl_movespeedkey; +extern convar cl_movespeedkey; -extern cvar_t cl_yawspeed; -extern cvar_t cl_pitchspeed; +extern convar cl_yawspeed; +extern convar cl_pitchspeed; -extern cvar_t cl_anglespeedkey; +extern convar cl_anglespeedkey; -extern cvar_t cl_alwaysrun; // QuakeSpasm +extern convar cl_alwaysrun; // QuakeSpasm -extern cvar_t cl_autofire; +extern convar cl_autofire; -extern cvar_t cl_shownet; -extern cvar_t cl_nolerp; +extern convar cl_shownet; +extern convar cl_nolerp; -extern cvar_t cfg_unbindall; +extern convar cfg_unbindall; -extern cvar_t cl_pitchdriftspeed; -extern cvar_t lookspring; -extern cvar_t lookstrafe; -extern cvar_t sensitivity; +extern convar cl_pitchdriftspeed; +extern convar lookspring; +extern convar lookstrafe; +extern convar sensitivity; -extern cvar_t m_pitch; -extern cvar_t m_yaw; -extern cvar_t m_forward; -extern cvar_t m_side; +extern convar m_pitch; +extern convar m_yaw; +extern convar m_forward; +extern convar m_side; -extern cvar_t cl_startdemos; +extern convar cl_startdemos; #define MAX_TEMP_ENTITIES 256 //johnfitz -- was 64 @@ -368,7 +368,7 @@ void CL_SignonReply (void); // // chase // -extern cvar_t chase_active; +extern convar chase_active; void Chase_Init (void); void TraceLine (vec3_t start, vec3_t end, vec3_t impact); diff --git a/Quake/cmd.cpp b/Quake/cmd.cpp index f3d2be0..3132932 100644 --- a/Quake/cmd.cpp +++ b/Quake/cmd.cpp @@ -22,59 +22,484 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // cmd.c -- Quake script command processing module +#include +#include +#include +#include + #include "quakedef.hpp" -void Cmd_ForwardToServer (void); +void Cmd_ForwardToServer(void); -#define MAX_ALIAS_NAME 32 +constexpr int CMDLINE_LENGTH = 256; +constexpr int MAX_ARGS = 80; -#define CMDLINE_LENGTH 256 //johnfitz -- mirrored in common.c +extern convar cmdline; -typedef struct cmdalias_s -{ - struct cmdalias_s *next; - char name[MAX_ALIAS_NAME]; - char *value; -} cmdalias_t; -cmdalias_t *cmd_alias; +namespace command { + source last_source; + + namespace { + constexpr int MAX_ALIAS_LENGTH = 32; + + bool waiting{false}; + std::map > REFS{}; + std::map > ALIASES{}; + std::vector _argv{}; + std::string _args{}; + + /** + * Causes execution of the remainder of the command buffer to be delayed until + * next frame. This allows commands like: + * + * ``` + * bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2" + * ``` + */ + void set_wait() { + waiting = true; + } + + void stop_waiting() { + waiting = false; + } + + bool is_waiting() { + return waiting; + } + + void _list() { + std::optional partial{std::nullopt}; + + if (argc() > 1) { + partial = argv(1); + } + + auto count = 0; + for (auto &[name, ref]: std::ranges::views::values(REFS)) { + if (partial.has_value() && !name.starts_with(partial.value())) { + continue; + } + Con_SafePrintf(" %s\n", name.c_str()); + count++; + } + + Con_SafePrintf("%i commands", count); + if (partial) { + Con_SafePrintf(" beginning with \"%s\"", partial->c_str()); + } + Con_SafePrintf("\n"); + } + + void _unalias() { + switch (argc()) { + default: + case 1: + Con_Printf("unalias : delete alias\n"); + break; + case 2: { + const auto name = argv(1).value(); + if (ALIASES.contains(name)) { + ALIASES.erase(name); + } else { + Con_Printf("No alias named %s\n", name.c_str()); + } + break; + } + } + } + + void _alias() { + char cmd[1024]; + + switch (argc()) { + case 1: { + //list all aliases + auto count = 0; + for (auto &[name, alias]: command::ALIASES) { + Con_SafePrintf(" %s: %s", name.c_str(), alias.value.c_str()); + count++; + } + if (count != 0) + Con_SafePrintf("%i alias command(s)\n", count); + else + Con_SafePrintf("no alias commands found\n"); + break; + } + case 2: { + //output current alias string + const auto lookup = argv(1).value(); + for (auto &[name, alias]: command::ALIASES) + if (name.starts_with(lookup)) + Con_Printf(" %s: %s", name.c_str(), alias.value.c_str()); + break; + } + default: { + //set alias string + const auto new_name = argv(1).value(); + if (new_name.length() >= command::MAX_ALIAS_LENGTH) { + Con_Printf("Alias name is too long\n"); + return; + } + + std::optional new_alias = std::nullopt; + // if the alias already exists, reuse it + for (auto &[name, alias]: command::ALIASES) { + if (name == new_name) { + new_alias = alias; + alias.value.clear(); + break; + } + } + + if (!new_alias.has_value()) { + new_alias = command::alias{}; + } + new_alias->name = new_name; + + // copy the rest of the command line + cmd[0] = 0; // start out with a null string + auto c = argc(); + // TODO: ew + for (auto i = 2; i < c; i++) { + q_strlcat(cmd, argv(i).value().c_str(), sizeof(cmd)); + if (i != c - 1) + q_strlcat(cmd, " ", sizeof(cmd)); + } + if (q_strlcat(cmd, "\n", sizeof(cmd)) >= sizeof(cmd)) { + Con_Printf("alias value too long!\n"); + cmd[0] = '\n'; // nullify the string + cmd[1] = 0; + } + + new_alias->value = Z_Strdup(cmd); + break; + } + } + } + + void _unalias_all() { + ALIASES.clear(); + } + + /* + =============== + johnfitz -- rewritten to read the "cmdline" cvar, for use with dynamic mod loading + + Adds command line parameters as script statements + Commands lead with a +, and continue until a - or another + + quake +prog jctest.qp +cmd amlev1 + quake -nosound +cmd amlev1 + =============== + */ + void _stuffcmds() { + char cmds[CMDLINE_LENGTH]; + int i, j, plus; + + plus = false; // On Unix, argv[0] is command name + + for (i = 0, j = 0; cmdline.string[i]; i++) { + if (cmdline.string[i] == '+') { + plus = true; + if (j > 0) { + cmds[j - 1] = ';'; + cmds[j++] = ' '; + } + } else if (cmdline.string[i] == '-' && + (i == 0 || cmdline.string[i - 1] == ' ')) //johnfitz -- allow hypenated map names with +map + plus = false; + else if (plus) + cmds[j++] = cmdline.string[i]; + } + cmds[j] = 0; + + Cbuf_InsertText(cmds); + } + +#include "default_cfg.hpp" + + void _exec() { + const char *f; + int mark; + + if (argc() != 2) { + Con_Printf("exec : execute a script file\n"); + return; + } + + mark = Hunk_LowMark(); + auto filename = argv(1); + f = (const char *) COM_LoadHunkFile(filename->c_str(), NULL); + if (!f && !strcmp(argv(1)->c_str(), "default.cfg")) { + f = default_cfg; /* see above.. */ + } + if (!f) { + Con_Printf("couldn't exec %s\n", argv(1)->c_str()); + return; + } + Con_Printf("execing %s\n", argv(1)->c_str()); + + Cbuf_InsertText(f); + if (f != default_cfg) { + Hunk_FreeToLowMark(mark); + } + } + + void _echo() { + for (auto i = 1; i < argc(); i++) + Con_Printf("%s ", argv(i)->c_str()); + Con_Printf("\n"); + } + + char *tint_substring(const char *in, const char *substr, char *out, size_t outsize) { + int l; + char *m; + q_strlcpy(out, in, outsize); + while ((m = q_strcasestr(out, substr))) { + l = strlen(substr); + while (l-- > 0) + if (*m >= ' ' && *m < 127) + *m++ |= 0x80; + } + return out; + } + + /* + ============ + scans through each command and cvar names+descriptions for the given substring + we don't support descriptions, so this isn't really all that useful, but even without the sake of consistency it still combines cvars+commands under a single command. + ============ + */ + void _apropos() { + char tmpbuf[256]; + int hits = 0; + const auto substr = argv(1); + if (!substr.has_value()) { + Con_SafePrintf("%s : search through commands and cvars for the given substring\n", + argv(0).value().c_str()); + return; + } + for (const auto &name: REFS | std::views::keys) { + if (q_strcasestr(name.c_str(), substr.value().c_str())) { + hits++; + Con_SafePrintf( + "%s\n", tint_substring(name.c_str(), substr.value().c_str(), tmpbuf, sizeof(tmpbuf))); + } + } + + for (const auto &var: convar::get_variables()) { + if (q_strcasestr(var->name.c_str(), substr.value().c_str())) { + hits++; + Con_SafePrintf("%s (current value: \"%s\")\n", + tint_substring(var->name.c_str(), substr.value().c_str(), tmpbuf, sizeof(tmpbuf)), + var->string); + } + } + if (!hits) + Con_SafePrintf("no cvars nor commands contain that substring\n"); + } + } + + + void init() { + add("cmdlist", _list); //johnfitz + add("unalias", _unalias); //johnfitz + add("unaliasall", _unalias_all); //johnfitz + + add("stuffcmds", _stuffcmds); + add("exec", _exec); + add("echo", _echo); + add("alias", _alias); + add("cmd", Cmd_ForwardToServer); + add("wait", set_wait); + + add("apropos", _apropos); + add("find", _apropos); + } + + std::optional complete(const std::string &partial) { + if (partial.empty()) + return std::nullopt; + + for (const auto &name: REFS | std::views::keys) { + if (name.compare(0, partial.length(), partial) == 0) + return name; + } + return std::nullopt; + } + + void add(const std::string &name, const xcommand_t cmd) { + if (host_initialized) // because hunk allocation would get stomped + Sys_Error("Cmd_AddCommand after host_initialized"); + + // fail if the command is a variable name + if (convar::variable_string(name).has_value()) { + Con_Printf("Cmd_AddCommand: %s already defined as a var\n", name.c_str()); + return; + } + + // fail if the command already exists + for (auto &[other_name, func]: std::ranges::views::values(REFS)) { + if (name == other_name) { + Con_Printf("Cmd_AddCommand: %s already defined\n", name.c_str()); + return; + } + } + + REFS.emplace(name, definition{name, cmd}); + } + + bool exists(const std::string_view lookup) { + return std::ranges::any_of(REFS.begin(), REFS.end(), [lookup](const auto &pair) { + return pair.first == lookup; + }); + } + + int argc() { + return static_cast(_argv.size()); + } + + std::optional argv(const int arg) { + if (arg < 0 || arg >= _argv.size()) { + return std::nullopt; + } + return _argv[arg]; + } + + std::string args() { + return _args; + } + + int check_parm(const std::string &parm) { + if (parm.empty()) + Sys_Error("Cmd_CheckParm: null input\n"); + + for (auto i = 1; i < argc(); i++) + if (!q_strcasecmp(parm.c_str(), argv(i)->c_str())) + return i; + + return 0; + } + + /** + * Parses the given string into command line tokens. + * @param text + */ + void tokenize_string(const std::string &text) { + _argv.clear(); + _args = std::string{}; + std::istringstream ss{text}; + while (true) { + while (!ss.eof() && ss.peek() <= ' ' && ss.peek() != '\n') { + ss.get(); + } + + if (ss.peek() == '\n') + break; + + if (ss.eof()) + return; + + if (_argv.size() == 1) + _args = ss.str().substr(ss.tellg()); + + if (_argv.size() >= MAX_ARGS) { + return; + } + + auto token = common::parse_token(ss); + if (!token.has_value()) { + return; + } + _argv.emplace_back(token.value()); + } + } + + void execute_string(const std::string &text, const source src) { + last_source = src; + tokenize_string(text); + + // execute the command line + if (argc() == 0) + return; // no tokens + + auto needle = argv(0).value(); + // check functions + for (const auto &[name, ref]: REFS) { + if (!q_strcasecmp(needle.c_str(), name.c_str())) { + ref.func(); + return; + } + } + + // check alias + for (const auto &[name, alias]: ALIASES) { + if (!q_strcasecmp(argv(0).value().c_str(), name.c_str())) { + Cbuf_InsertText(alias.value.c_str()); + return; + } + } + + // check cvars + if (!Cvar_Command()) + Con_Printf("Unknown command \"%s\"\n", argv(0).value().c_str()); + } + + void forward_to_server() { + if (cls.state != ca_connected) { + Con_Printf("Can't \"%s\", not connected\n", argv(0).value_or("").c_str()); + return; + } + + if (cls.demoplayback) + return; // not really connected + + MSG_WriteByte(&cls.message, clc_stringcmd); + if (q_strcasecmp(argv(0).value_or("").c_str(), "cmd") != 0) { + SZ_Print(&cls.message, argv(0).value_or("").c_str()); + SZ_Print(&cls.message, " "); + } + if (argc() > 1) + SZ_Print(&cls.message, args().c_str()); + else + SZ_Print(&cls.message, "\n"); + } + + definition_view get_commands() { + return std::ranges::views::values(REFS); + } + + alias_view get_aliases() { + return std::ranges::views::values(ALIASES); + } + + void print(std::string text) { + } +} -qboolean cmd_wait; //============================================================================= -/* -============ -Cmd_Wait_f - -Causes execution of the remainder of the command buffer to be delayed until -next frame. This allows commands like: -bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2" -============ -*/ -void Cmd_Wait_f (void) -{ - cmd_wait = true; -} /* ============================================================================= - COMMAND BUFFER + COMMAND BUFFER ============================================================================= */ -sizebuf_t cmd_text; +sizebuf_t cmd_text; /* ============ Cbuf_Init ============ */ -void Cbuf_Init (void) -{ - SZ_Alloc (&cmd_text, 1<<18); // space for commands and script files. spike -- was 8192, but modern configs can be _HUGE_, at least if they contain lots of comments/docs for things. +void Cbuf_Init(void) { + SZ_Alloc(&cmd_text, 1 << 18); + // space for commands and script files. spike -- was 8192, but modern configs can be _HUGE_, at least if they contain lots of comments/docs for things. } @@ -85,19 +510,17 @@ Cbuf_AddText Adds command text at the end of the buffer ============ */ -void Cbuf_AddText (const char *text) -{ - int l; +void Cbuf_AddText(const char *text) { + int l; - l = Q_strlen (text); + l = Q_strlen(text); - if (cmd_text.cursize + l >= cmd_text.maxsize) - { - Con_Printf ("Cbuf_AddText: overflow\n"); - return; - } + if (cmd_text.cursize + l >= cmd_text.maxsize) { + Con_Printf("Cbuf_AddText: overflow\n"); + return; + } - SZ_Write (&cmd_text, text, Q_strlen (text)); + SZ_Write(&cmd_text, text, Q_strlen(text)); } @@ -110,31 +533,27 @@ Adds a \n to the text FIXME: actually change the command buffer to do less copying ============ */ -void Cbuf_InsertText (const char *text) -{ - char *temp; - int templen; +void Cbuf_InsertText(const char *text) { + char *temp; + int templen; -// copy off any commands still remaining in the exec buffer - templen = cmd_text.cursize; - if (templen) - { - temp = (char *) Z_Malloc (templen); - Q_memcpy (temp, cmd_text.data, templen); - SZ_Clear (&cmd_text); - } - else - temp = NULL; // shut up compiler + // copy off any commands still remaining in the exec buffer + templen = cmd_text.cursize; + if (templen) { + temp = (char *) Z_Malloc(templen); + Q_memcpy(temp, cmd_text.data, templen); + SZ_Clear(&cmd_text); + } else + temp = NULL; // shut up compiler -// add the entire text of the file - Cbuf_AddText (text); - SZ_Write (&cmd_text, "\n", 1); -// add the copied off data - if (templen) - { - SZ_Write (&cmd_text, temp, templen); - Z_Free (temp); - } + // add the entire text of the file + Cbuf_AddText(text); + SZ_Write(&cmd_text, "\n", 1); + // add the copied off data + if (templen) { + SZ_Write(&cmd_text, temp, templen); + Z_Free(temp); + } } /* @@ -142,606 +561,92 @@ void Cbuf_InsertText (const char *text) Cbuf_Execute ============ */ -void Cbuf_Execute (void) -{ - int i; - char *text; - char line[1024]; - int quotes; +void Cbuf_Execute(void) { + int i; + char *text; + char line[1024]; + int quotes; - while (cmd_text.cursize) - { -// find a \n or ; line break - text = (char *)cmd_text.data; + while (cmd_text.cursize) { + // find a \n or ; line break + text = (char *) cmd_text.data; - quotes = 0; - for (i=0 ; i< cmd_text.cursize ; i++) - { - if (text[i] == '"') - quotes++; - if ( !(quotes&1) && text[i] == ';') - break; // don't break if inside a quoted string - if (text[i] == '\n') - break; - } + quotes = 0; + for (i = 0; i < cmd_text.cursize; i++) { + if (text[i] == '"') + quotes++; + if (!(quotes & 1) && text[i] == ';') + break; // don't break if inside a quoted string + if (text[i] == '\n') + break; + } - if (i > (int)sizeof(line) - 1) - { - memcpy (line, text, sizeof(line) - 1); - line[sizeof(line) - 1] = 0; - } - else - { - memcpy (line, text, i); - line[i] = 0; - } + if (i > (int) sizeof(line) - 1) { + memcpy(line, text, sizeof(line) - 1); + line[sizeof(line) - 1] = 0; + } else { + memcpy(line, text, i); + line[i] = 0; + } -// delete the text from the command buffer and move remaining commands down -// this is necessary because commands (exec, alias) can insert data at the -// beginning of the text buffer + // delete the text from the command buffer and move remaining commands down + // this is necessary because commands (exec, alias) can insert data at the + // beginning of the text buffer - if (i == cmd_text.cursize) - cmd_text.cursize = 0; - else - { - i++; - cmd_text.cursize -= i; - memmove (text, text + i, cmd_text.cursize); - } + if (i == cmd_text.cursize) + cmd_text.cursize = 0; + else { + i++; + cmd_text.cursize -= i; + memmove(text, text + i, cmd_text.cursize); + } -// execute the command line - Cmd_ExecuteString (line, src_command); + // execute the command line + command::execute_string(line, command::source::command); - if (cmd_wait) - { // skip out while text still remains in buffer, leaving it - // for next frame - cmd_wait = false; - break; - } - } + if (command::is_waiting()) { + // skip out while text still remains in buffer, leaving it + // for next frame + command::stop_waiting(); + break; + } + } } /* ============================================================================== - SCRIPT COMMANDS + SCRIPT COMMANDS ============================================================================== */ -/* -=============== -Cmd_StuffCmds_f -- johnfitz -- rewritten to read the "cmdline" cvar, for use with dynamic mod loading - -Adds command line parameters as script statements -Commands lead with a +, and continue until a - or another + -quake +prog jctest.qp +cmd amlev1 -quake -nosound +cmd amlev1 -=============== -*/ -void Cmd_StuffCmds_f (void) -{ - extern cvar_t cmdline; - char cmds[CMDLINE_LENGTH]; - int i, j, plus; - - plus = false; // On Unix, argv[0] is command name - - for (i = 0, j = 0; cmdline.string[i]; i++) - { - if (cmdline.string[i] == '+') - { - plus = true; - if (j > 0) - { - cmds[j-1] = ';'; - cmds[j++] = ' '; - } - } - else if (cmdline.string[i] == '-' && - (i==0 || cmdline.string[i-1] == ' ')) //johnfitz -- allow hypenated map names with +map - plus = false; - else if (plus) - cmds[j++] = cmdline.string[i]; - } - cmds[j] = 0; - - Cbuf_InsertText (cmds); -} /* id1/pak0.pak from 2021 re-release doesn't have a default.cfg * embedding Quakespasm's customized default.cfg for that... */ -#include "default_cfg.hpp" -/* -=============== -Cmd_Exec_f -=============== -*/ -void Cmd_Exec_f (void) -{ - const char *f; - int mark; - - if (Cmd_Argc () != 2) - { - Con_Printf ("exec : execute a script file\n"); - return; - } - - mark = Hunk_LowMark (); - f = (const char *)COM_LoadHunkFile (Cmd_Argv(1), NULL); - if (!f && !strcmp(Cmd_Argv(1), "default.cfg")) { - f = default_cfg; /* see above.. */ - } - if (!f) - { - Con_Printf ("couldn't exec %s\n",Cmd_Argv(1)); - return; - } - Con_Printf ("execing %s\n",Cmd_Argv(1)); - - Cbuf_InsertText (f); - if (f != default_cfg) { - Hunk_FreeToLowMark (mark); - } -} - - -/* -=============== -Cmd_Echo_f - -Just prints the rest of the line to the console -=============== -*/ -void Cmd_Echo_f (void) -{ - int i; - - for (i=1 ; inext, i++) - Con_SafePrintf (" %s: %s", a->name, a->value); - if (i) - Con_SafePrintf ("%i alias command(s)\n", i); - else - Con_SafePrintf ("no alias commands found\n"); - break; - case 2: //output current alias string - for (a = cmd_alias ; a ; a=a->next) - if (!strcmp(Cmd_Argv(1), a->name)) - Con_Printf (" %s: %s", a->name, a->value); - break; - default: //set alias string - s = Cmd_Argv(1); - if (strlen(s) >= MAX_ALIAS_NAME) - { - Con_Printf ("Alias name is too long\n"); - return; - } - - // if the alias already exists, reuse it - for (a = cmd_alias ; a ; a=a->next) - { - if (!strcmp(s, a->name)) - { - Z_Free (a->value); - break; - } - } - - if (!a) - { - a = (cmdalias_t *) Z_Malloc (sizeof(cmdalias_t)); - a->next = cmd_alias; - cmd_alias = a; - } - strcpy (a->name, s); - - // copy the rest of the command line - cmd[0] = 0; // start out with a null string - c = Cmd_Argc(); - for (i = 2; i < c; i++) - { - q_strlcat (cmd, Cmd_Argv(i), sizeof(cmd)); - if (i != c - 1) - q_strlcat (cmd, " ", sizeof(cmd)); - } - if (q_strlcat(cmd, "\n", sizeof(cmd)) >= sizeof(cmd)) - { - Con_Printf("alias value too long!\n"); - cmd[0] = '\n'; // nullify the string - cmd[1] = 0; - } - - a->value = Z_Strdup (cmd); - break; - } -} - -/* -=============== -Cmd_Unalias_f -- johnfitz -=============== -*/ -void Cmd_Unalias_f (void) -{ - cmdalias_t *a, *prev; - - switch (Cmd_Argc()) - { - default: - case 1: - Con_Printf("unalias : delete alias\n"); - break; - case 2: - prev = NULL; - for (a = cmd_alias; a; a = a->next) - { - if (!strcmp(Cmd_Argv(1), a->name)) - { - if (prev) - prev->next = a->next; - else - cmd_alias = a->next; - - Z_Free (a->value); - Z_Free (a); - return; - } - prev = a; - } - Con_Printf ("No alias named %s\n", Cmd_Argv(1)); - break; - } -} - -/* -=============== -Cmd_Unaliasall_f -- johnfitz -=============== -*/ -void Cmd_Unaliasall_f (void) -{ - cmdalias_t *blah; - - while (cmd_alias) - { - blah = cmd_alias->next; - Z_Free(cmd_alias->value); - Z_Free(cmd_alias); - cmd_alias = blah; - } -} /* ============================================================================= - COMMAND EXECUTION + COMMAND EXECUTION ============================================================================= */ -typedef struct cmd_function_s -{ - struct cmd_function_s *next; - const char *name; - xcommand_t function; -} cmd_function_t; - - -#define MAX_ARGS 80 - -static int cmd_argc; -static char *cmd_argv[MAX_ARGS]; -static char cmd_null_string[] = ""; -static const char *cmd_args = NULL; - -cmd_source_t cmd_source; - -//johnfitz -- better tab completion -//static cmd_function_t *cmd_functions; // possible commands to execute -cmd_function_t *cmd_functions; // possible commands to execute -//johnfitz - -/* -============ -Cmd_List_f -- johnfitz -============ -*/ -void Cmd_List_f (void) -{ - cmd_function_t *cmd; - const char *partial; - int len, count; - - if (Cmd_Argc() > 1) - { - partial = Cmd_Argv (1); - len = Q_strlen(partial); - } - else - { - partial = NULL; - len = 0; - } - - count=0; - for (cmd=cmd_functions ; cmd ; cmd=cmd->next) - { - if (partial && Q_strncmp (partial,cmd->name, len)) - { - continue; - } - Con_SafePrintf (" %s\n", cmd->name); - count++; - } - - Con_SafePrintf ("%i commands", count); - if (partial) - { - Con_SafePrintf (" beginning with \"%s\"", partial); - } - Con_SafePrintf ("\n"); -} - -static char *Cmd_TintSubstring(const char *in, const char *substr, char *out, size_t outsize) -{ - int l; - char *m; - q_strlcpy(out, in, outsize); - while ((m = q_strcasestr(out, substr))) - { - l = strlen(substr); - while (l-->0) - if (*m >= ' ' && *m < 127) - *m++ |= 0x80; - } - return out; -} - -/* -============ -Cmd_Apropos_f - -scans through each command and cvar names+descriptions for the given substring -we don't support descriptions, so this isn't really all that useful, but even without the sake of consistency it still combines cvars+commands under a single command. -============ -*/ -void Cmd_Apropos_f(void) -{ - char tmpbuf[256]; - int hits = 0; - cmd_function_t *cmd; - cvar_t *var; - const char *substr = Cmd_Argv (1); - if (!*substr) - { - Con_SafePrintf ("%s : search through commands and cvars for the given substring\n", Cmd_Argv(0)); - return; - } - for (cmd=cmd_functions ; cmd ; cmd=cmd->next) - { - if (q_strcasestr(cmd->name, substr)) - { - hits++; - Con_SafePrintf ("%s\n", Cmd_TintSubstring(cmd->name, substr, tmpbuf, sizeof(tmpbuf))); - } - } - - // for (var=Cvar_FindVarAfter("", 0) ; var ; var=var->next) - // { - // if (q_strcasestr(var->name, substr)) - // { - // hits++; - // Con_SafePrintf ("%s (current value: \"%s\")\n", Cmd_TintSubstring(var->name, substr, tmpbuf, sizeof(tmpbuf)), var->string); - // } - // } // TODO: - if (!hits) - Con_SafePrintf ("no cvars nor commands contain that substring\n"); -} - -/* -============ -Cmd_Init -============ -*/ -void Cmd_Init (void) -{ - Cmd_AddCommand ("cmdlist", Cmd_List_f); //johnfitz - Cmd_AddCommand ("unalias", Cmd_Unalias_f); //johnfitz - Cmd_AddCommand ("unaliasall", Cmd_Unaliasall_f); //johnfitz - - Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f); - Cmd_AddCommand ("exec",Cmd_Exec_f); - Cmd_AddCommand ("echo",Cmd_Echo_f); - Cmd_AddCommand ("alias",Cmd_Alias_f); - Cmd_AddCommand ("cmd", Cmd_ForwardToServer); - Cmd_AddCommand ("wait", Cmd_Wait_f); - - Cmd_AddCommand ("apropos", Cmd_Apropos_f); - Cmd_AddCommand ("find", Cmd_Apropos_f); -} - -/* -============ -Cmd_Argc -============ -*/ -int Cmd_Argc (void) -{ - return cmd_argc; -} - -/* -============ -Cmd_Argv -============ -*/ -const char *Cmd_Argv (int arg) -{ - if (arg < 0 || arg >= cmd_argc) - return cmd_null_string; - return cmd_argv[arg]; -} - -/* -============ -Cmd_Args -============ -*/ -const char *Cmd_Args (void) -{ - return cmd_args; -} - - -/* -============ -Cmd_TokenizeString - -Parses the given string into command line tokens. -============ -*/ -void Cmd_TokenizeString (const char *text) -{ - int i; - -// clear the args from the last string - for (i=0 ; inext) - { - if (!Q_strcmp (cmd_name, cmd->name)) - { - Con_Printf ("Cmd_AddCommand: %s already defined\n", cmd_name); - return; - } - } - - cmd = (cmd_function_t *) Hunk_Alloc (sizeof(cmd_function_t)); - cmd->name = cmd_name; - cmd->function = function; - - //johnfitz -- insert each entry in alphabetical order - if (cmd_functions == NULL || strcmp(cmd->name, cmd_functions->name) < 0) //insert at front - { - cmd->next = cmd_functions; - cmd_functions = cmd; - } - else //insert later - { - prev = cmd_functions; - cursor = cmd_functions->next; - while ((cursor != NULL) && (strcmp(cmd->name, cursor->name) > 0)) - { - prev = cursor; - cursor = cursor->next; - } - cmd->next = prev->next; - prev->next = cmd; - } - //johnfitz -} /* ============ Cmd_Exists ============ */ -qboolean Cmd_Exists (const char *cmd_name) -{ - cmd_function_t *cmd; - - for (cmd=cmd_functions ; cmd ; cmd=cmd->next) - { - if (!Q_strcmp (cmd_name,cmd->name)) - return true; - } - - return false; -} - /* @@ -749,23 +654,7 @@ qboolean Cmd_Exists (const char *cmd_name) Cmd_CompleteCommand ============ */ -const char *Cmd_CompleteCommand (const char *partial) -{ - cmd_function_t *cmd; - int len; - len = Q_strlen(partial); - - if (!len) - return NULL; - -// check functions - for (cmd=cmd_functions ; cmd ; cmd=cmd->next) - if (!Q_strncmp (partial,cmd->name, len)) - return cmd->name; - - return NULL; -} /* ============ @@ -775,42 +664,6 @@ A complete command line has been parsed, so try to execute it FIXME: lookupnoadd the token to speed search? ============ */ -void Cmd_ExecuteString (const char *text, cmd_source_t src) -{ - cmd_function_t *cmd; - cmdalias_t *a; - - cmd_source = src; - Cmd_TokenizeString (text); - -// execute the command line - if (!Cmd_Argc()) - return; // no tokens - -// check functions - for (cmd=cmd_functions ; cmd ; cmd=cmd->next) - { - if (!q_strcasecmp (cmd_argv[0],cmd->name)) - { - cmd->function (); - return; - } - } - -// check alias - for (a=cmd_alias ; a ; a=a->next) - { - if (!q_strcasecmp (cmd_argv[0], a->name)) - { - Cbuf_InsertText (a->value); - return; - } - } - -// check cvars - if (!Cvar_Command ()) - Con_Printf ("Unknown command \"%s\"\n", Cmd_Argv(0)); -} /* @@ -820,27 +673,7 @@ Cmd_ForwardToServer Sends the entire command line over to the server =================== */ -void Cmd_ForwardToServer (void) -{ - if (cls.state != ca_connected) - { - Con_Printf ("Can't \"%s\", not connected\n", Cmd_Argv(0)); - return; - } - - if (cls.demoplayback) - return; // not really connected - - MSG_WriteByte (&cls.message, clc_stringcmd); - if (q_strcasecmp(Cmd_Argv(0), "cmd") != 0) - { - SZ_Print (&cls.message, Cmd_Argv(0)); - SZ_Print (&cls.message, " "); - } - if (Cmd_Argc() > 1) - SZ_Print (&cls.message, Cmd_Args()); - else - SZ_Print (&cls.message, "\n"); +void Cmd_ForwardToServer(void) { } @@ -853,17 +686,5 @@ where the given parameter apears, or 0 if not present ================ */ -int Cmd_CheckParm (const char *parm) -{ - int i; - - if (!parm) - Sys_Error ("Cmd_CheckParm: null input\n"); - - for (i = 1; i < Cmd_Argc (); i++) - if ( !q_strcasecmp (parm, Cmd_Argv (i)) ) - return i; - - return 0; +int Cmd_CheckParm(const char *parm) { } - diff --git a/Quake/cmd.hpp b/Quake/cmd.hpp index 9f688e2..33ec07f 100644 --- a/Quake/cmd.hpp +++ b/Quake/cmd.hpp @@ -20,8 +20,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ -#ifndef _QUAKE_CMD_H -#define _QUAKE_CMD_H +#pragma once // cmd.h -- Command buffer and command execution @@ -72,56 +71,77 @@ not apropriate. typedef void (*xcommand_t) (void); -typedef enum -{ - src_client, // came in over a net connection as a clc_stringcmd - // host_client will be valid during this state. - src_command // from the command buffer -} cmd_source_t; -extern cmd_source_t cmd_source; -void Cmd_Init (void); +namespace command { + enum class source { + client, + command + }; + + extern source last_source; + + struct alias { + std::string name; + std::string value; + }; + + struct definition { + std::string name{}; + xcommand_t func{nullptr}; + + definition(const std::string &name, const xcommand_t func) { + this->name = name; + this->func = func; + } + }; + + using definition_view = std::ranges::elements_view>>, 1>; + using alias_view = std::ranges::elements_view>>, 1>; + + + void init(); + + void add(const std::string &name, xcommand_t cmd); + std::optional complete(const std::string &partial); + bool exists(std::string_view lookup); + + int argc(); + std::optional argv(int arg); + std::string args(); + + int check_parm(const std::string &parm); + + void tokenize_string(const std::string &text); + + void execute_string(const std::string &text, source src); + + void forward_to_server(); + + definition_view get_commands(); + + alias_view get_aliases(); +} -void Cmd_AddCommand (const char *cmd_name, xcommand_t function); // called by the init functions of other parts of the program to // register commands and functions to call for them. // The cmd_name is referenced later, so it should not be in temp memory -qboolean Cmd_Exists (const char *cmd_name); // used by the cvar code to check for cvar / command name overlap -const char *Cmd_CompleteCommand (const char *partial); // attempts to match a partial command for automatic command line completion // returns NULL if nothing fits -int Cmd_Argc (void); -const char *Cmd_Argv (int arg); -const char *Cmd_Args (void); -// The functions that execute commands get their parameters with these -// functions. Cmd_Argv () will return an empty string, not a NULL -// if arg > argc, so string operations are allways safe. - -int Cmd_CheckParm (const char *parm); // Returns the position (1 to argc-1) in the command's argument list // where the given parameter apears, or 0 if not present -void Cmd_TokenizeString (const char *text); -// Takes a null terminated string. Does not need to be /n terminated. -// breaks the string up into arg tokens. - -void Cmd_ExecuteString (const char *text, cmd_source_t src); // Parses a single line of text into arguments and tries to execute it. // The text can come from the command buffer, a remote client, or stdin. -void Cmd_ForwardToServer (void); // adds the current command line as a clc_stringcmd to the client message. // things like godmode, noclip, etc, are commands directed to the server, // so when they are typed in at the console, they will need to be forwarded. -void Cmd_Print (const char *text); // used by command functions to send output to either the graphics console or // passed as a print message to the client -#endif /* _QUAKE_CMD_H */ - diff --git a/Quake/common.cpp b/Quake/common.cpp index 029c7f1..4da62f9 100644 --- a/Quake/common.cpp +++ b/Quake/common.cpp @@ -25,22 +25,23 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.hpp" #include "q_ctype.hpp" #include +#include #include "miniz.hpp" -static char *largv[MAX_NUM_ARGVS + 1]; -static char argvdummy[] = " "; +static char *largv[MAX_NUM_ARGVS + 1]; +static char argvdummy[] = " "; -int safemode; +int safemode; -cvar_t registered = {"registered","1",CVAR_ROM}; /* set to correct value in COM_CheckRegistered() */ -cvar_t cmdline = {"cmdline","",CVAR_ROM/*|CVAR_SERVERINFO*/}; /* sending cmdline upon CCREQ_RULE_INFO is evil */ +convar registered = {"registered", "1", {.rom = true}}; /* set to correct value in COM_CheckRegistered() */ +convar cmdline = {"cmdline", "", {.rom = true}/*|CVAR_SERVERINFO*/}; /* sending cmdline upon CCREQ_RULE_INFO is evil */ -static qboolean com_modified; // set true if using non-id files +static qboolean com_modified; // set true if using non-id files -qboolean fitzmode; +qboolean fitzmode; -static void COM_Path_f (void); +static void COM_Path_f(void); // if a packfile directory differs from this, it is assumed to be hacked #define PAK0_COUNT 339 /* id1/pak0.pak - v1.0x */ @@ -51,34 +52,33 @@ static void COM_Path_f (void); #define PAK0_COUNT_V091 308 /* id1/pak0.pak - v0.91/0.92, not supported */ #define PAK0_CRC_V091 28804 /* id1/pak0.pak - v0.91/0.92, not supported */ -char com_token[1024]; -int com_argc; -char **com_argv; +int com_argc; +char **com_argv; #define CMDLINE_LENGTH 256 /* johnfitz -- mirrored in cmd.c */ -char com_cmdline[CMDLINE_LENGTH]; +char com_cmdline[CMDLINE_LENGTH]; qboolean standard_quake = true, rogue, hipnotic; // this graphic needs to be in the pak file to use registered features static unsigned short pop[] = { - 0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000, - 0x0000,0x0000,0x6600,0x0000,0x0000,0x0000,0x6600,0x0000, - 0x0000,0x0066,0x0000,0x0000,0x0000,0x0000,0x0067,0x0000, - 0x0000,0x6665,0x0000,0x0000,0x0000,0x0000,0x0065,0x6600, - 0x0063,0x6561,0x0000,0x0000,0x0000,0x0000,0x0061,0x6563, - 0x0064,0x6561,0x0000,0x0000,0x0000,0x0000,0x0061,0x6564, - 0x0064,0x6564,0x0000,0x6469,0x6969,0x6400,0x0064,0x6564, - 0x0063,0x6568,0x6200,0x0064,0x6864,0x0000,0x6268,0x6563, - 0x0000,0x6567,0x6963,0x0064,0x6764,0x0063,0x6967,0x6500, - 0x0000,0x6266,0x6769,0x6a68,0x6768,0x6a69,0x6766,0x6200, - 0x0000,0x0062,0x6566,0x6666,0x6666,0x6666,0x6562,0x0000, - 0x0000,0x0000,0x0062,0x6364,0x6664,0x6362,0x0000,0x0000, - 0x0000,0x0000,0x0000,0x0062,0x6662,0x0000,0x0000,0x0000, - 0x0000,0x0000,0x0000,0x0061,0x6661,0x0000,0x0000,0x0000, - 0x0000,0x0000,0x0000,0x0000,0x6500,0x0000,0x0000,0x0000, - 0x0000,0x0000,0x0000,0x0000,0x6400,0x0000,0x0000,0x0000 + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x6600, 0x0000, 0x0000, 0x0000, 0x6600, 0x0000, + 0x0000, 0x0066, 0x0000, 0x0000, 0x0000, 0x0000, 0x0067, 0x0000, + 0x0000, 0x6665, 0x0000, 0x0000, 0x0000, 0x0000, 0x0065, 0x6600, + 0x0063, 0x6561, 0x0000, 0x0000, 0x0000, 0x0000, 0x0061, 0x6563, + 0x0064, 0x6561, 0x0000, 0x0000, 0x0000, 0x0000, 0x0061, 0x6564, + 0x0064, 0x6564, 0x0000, 0x6469, 0x6969, 0x6400, 0x0064, 0x6564, + 0x0063, 0x6568, 0x6200, 0x0064, 0x6864, 0x0000, 0x6268, 0x6563, + 0x0000, 0x6567, 0x6963, 0x0064, 0x6764, 0x0063, 0x6967, 0x6500, + 0x0000, 0x6266, 0x6769, 0x6a68, 0x6768, 0x6a69, 0x6766, 0x6200, + 0x0000, 0x0062, 0x6566, 0x6666, 0x6666, 0x6666, 0x6562, 0x0000, + 0x0000, 0x0000, 0x0062, 0x6364, 0x6664, 0x6362, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0062, 0x6662, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0061, 0x6661, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x6500, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x6400, 0x0000, 0x0000, 0x0000 }; /* @@ -117,31 +117,27 @@ override an explicit setting on the original command line. // ClearLink is used for new headnodes -void ClearLink (link_t *l) -{ - l->prev = l->next = l; +void ClearLink(link_t *l) { + l->prev = l->next = l; } -void RemoveLink (link_t *l) -{ - l->next->prev = l->prev; - l->prev->next = l->next; +void RemoveLink(link_t *l) { + l->next->prev = l->prev; + l->prev->next = l->next; } -void InsertLinkBefore (link_t *l, link_t *before) -{ - l->next = before; - l->prev = before->prev; - l->prev->next = l; - l->next->prev = l; +void InsertLinkBefore(link_t *l, link_t *before) { + l->next = before; + l->prev = before->prev; + l->prev->next = l; + l->next->prev = l; } -void InsertLinkAfter (link_t *l, link_t *after) -{ - l->next = after->next; - l->prev = after; - l->prev->next = l; - l->next->prev = l; +void InsertLinkAfter(link_t *l, link_t *after) { + l->next = after->next; + l->prev = after; + l->prev->next = l; + l->next->prev = l; } /* @@ -152,59 +148,53 @@ void InsertLinkAfter (link_t *l, link_t *after) ============================================================================ */ -void Vec_Grow (void **pvec, size_t element_size, size_t count) -{ - vec_header_t header; - if (*pvec) - header = VEC_HEADER(*pvec); - else - header.size = header.capacity = 0; +void Vec_Grow(void **pvec, size_t element_size, size_t count) { + vec_header_t header; + if (*pvec) + header = VEC_HEADER(*pvec); + else + header.size = header.capacity = 0; - if (header.size + count > header.capacity) - { - void *new_buffer; - size_t total_size; + if (header.size + count > header.capacity) { + void *new_buffer; + size_t total_size; - header.capacity = header.size + count; - header.capacity += header.capacity >> 1; - if (header.capacity < 16) - header.capacity = 16; - total_size = sizeof(vec_header_t) + header.capacity * element_size; + header.capacity = header.size + count; + header.capacity += header.capacity >> 1; + if (header.capacity < 16) + header.capacity = 16; + total_size = sizeof(vec_header_t) + header.capacity * element_size; - if (*pvec) - new_buffer = realloc (((vec_header_t*)*pvec) - 1, total_size); - else - new_buffer = malloc (total_size); - if (!new_buffer) - Sys_Error ("Vec_Grow: failed to allocate %lu bytes\n", (unsigned long)total_size); + if (*pvec) + new_buffer = realloc(((vec_header_t *) *pvec) - 1, total_size); + else + new_buffer = malloc(total_size); + if (!new_buffer) + Sys_Error("Vec_Grow: failed to allocate %lu bytes\n", (unsigned long) total_size); - *pvec = 1 + (vec_header_t*)new_buffer; - VEC_HEADER(*pvec) = header; - } + *pvec = 1 + (vec_header_t *) new_buffer; + VEC_HEADER(*pvec) = header; + } } -void Vec_Append (void **pvec, size_t element_size, const void *data, size_t count) -{ - if (!count) - return; - Vec_Grow (pvec, element_size, count); - memcpy ((byte *)*pvec + VEC_HEADER(*pvec).size, data, count * element_size); - VEC_HEADER(*pvec).size += count; +void Vec_Append(void **pvec, size_t element_size, const void *data, size_t count) { + if (!count) + return; + Vec_Grow(pvec, element_size, count); + memcpy((byte *) *pvec + VEC_HEADER(*pvec).size, data, count * element_size); + VEC_HEADER(*pvec).size += count; } -void Vec_Clear (void **pvec) -{ - if (*pvec) - VEC_HEADER(*pvec).size = 0; +void Vec_Clear(void **pvec) { + if (*pvec) + VEC_HEADER(*pvec).size = 0; } -void Vec_Free (void **pvec) -{ - if (*pvec) - { - free(&VEC_HEADER(*pvec)); - *pvec = NULL; - } +void Vec_Free(void **pvec) { + if (*pvec) { + free(&VEC_HEADER(*pvec)); + *pvec = NULL; + } } /* @@ -215,83 +205,73 @@ void Vec_Free (void **pvec) ============================================================================ */ -int q_strcasecmp(const char * s1, const char * s2) -{ - const char * p1 = s1; - const char * p2 = s2; - char c1, c2; +int q_strcasecmp(const char *s1, const char *s2) { + const char *p1 = s1; + const char *p2 = s2; + char c1, c2; - if (p1 == p2) - return 0; + if (p1 == p2) + return 0; - do - { - c1 = q_tolower (*p1++); - c2 = q_tolower (*p2++); - if (c1 == '\0') - break; - } while (c1 == c2); + do { + c1 = q_tolower(*p1++); + c2 = q_tolower(*p2++); + if (c1 == '\0') + break; + } while (c1 == c2); - return (int)(c1 - c2); + return (int) (c1 - c2); } -int q_strncasecmp(const char *s1, const char *s2, size_t n) -{ - const char * p1 = s1; - const char * p2 = s2; - char c1, c2; +int q_strncasecmp(const char *s1, const char *s2, size_t n) { + const char *p1 = s1; + const char *p2 = s2; + char c1, c2; - if (p1 == p2 || n == 0) - return 0; + if (p1 == p2 || n == 0) + return 0; - do - { - c1 = q_tolower (*p1++); - c2 = q_tolower (*p2++); - if (c1 == '\0' || c1 != c2) - break; - } while (--n > 0); + do { + c1 = q_tolower(*p1++); + c2 = q_tolower(*p2++); + if (c1 == '\0' || c1 != c2) + break; + } while (--n > 0); - return (int)(c1 - c2); + return (int) (c1 - c2); } -char *q_strcasestr(const char *haystack, const char *needle) -{ - const size_t len = strlen(needle); +char *q_strcasestr(const char *haystack, const char *needle) { + const size_t len = strlen(needle); - while (*haystack) - { - if (!q_strncasecmp(haystack, needle, len)) - return (char *)haystack; + while (*haystack) { + if (!q_strncasecmp(haystack, needle, len)) + return (char *) haystack; - ++haystack; - } + ++haystack; + } - return NULL; + return NULL; } -char *q_strlwr (char *str) -{ - char *c; - c = str; - while (*c) - { - *c = q_tolower(*c); - c++; - } - return str; +char *q_strlwr(char *str) { + char *c; + c = str; + while (*c) { + *c = q_tolower(*c); + c++; + } + return str; } -char *q_strupr (char *str) -{ - char *c; - c = str; - while (*c) - { - *c = q_toupper(*c); - c++; - } - return str; +char *q_strupr(char *str) { + char *c; + c = str; + while (*c) { + *c = q_toupper(*c); + c++; + } + return str; } /* platform dependant (v)snprintf function names: */ @@ -303,294 +283,256 @@ char *q_strupr (char *str) #define vsnprintf_func vsnprintf #endif -int q_vsnprintf(char *str, size_t size, const char *format, va_list args) -{ - int ret; +int q_vsnprintf(char *str, size_t size, const char *format, va_list args) { + int ret; - ret = vsnprintf_func (str, size, format, args); + ret = vsnprintf_func(str, size, format, args); - if (ret < 0) - ret = (int)size; - if (size == 0) /* no buffer */ - return ret; - if ((size_t)ret >= size) - str[size - 1] = '\0'; + if (ret < 0) + ret = (int) size; + if (size == 0) /* no buffer */ + return ret; + if ((size_t) ret >= size) + str[size - 1] = '\0'; - return ret; + return ret; } -int q_snprintf (char *str, size_t size, const char *format, ...) -{ - int ret; - va_list argptr; +int q_snprintf(char *str, size_t size, const char *format, ...) { + int ret; + va_list argptr; - va_start (argptr, format); - ret = q_vsnprintf (str, size, format, argptr); - va_end (argptr); + va_start(argptr, format); + ret = q_vsnprintf(str, size, format, argptr); + va_end(argptr); - return ret; + return ret; } -void Q_memset (void *dest, int fill, size_t count) -{ - size_t i; +void Q_memset(void *dest, int fill, size_t count) { + size_t i; - if ( (((uintptr_t)dest | count) & 3) == 0) - { - count >>= 2; - fill = fill | (fill<<8) | (fill<<16) | (fill<<24); - for (i = 0; i < count; i++) - ((int *)dest)[i] = fill; - } - else - for (i = 0; i < count; i++) - ((byte *)dest)[i] = fill; + if ((((uintptr_t) dest | count) & 3) == 0) { + count >>= 2; + fill = fill | (fill << 8) | (fill << 16) | (fill << 24); + for (i = 0; i < count; i++) + ((int *) dest)[i] = fill; + } else + for (i = 0; i < count; i++) + ((byte *) dest)[i] = fill; } -void Q_memcpy (void *dest, const void *src, size_t count) -{ - size_t i; +void Q_memcpy(void *dest, const void *src, size_t count) { + size_t i; - if (( ( (uintptr_t)dest | (uintptr_t)src | count) & 3) == 0) - { - count >>= 2; - for (i = 0; i < count; i++) - ((int *)dest)[i] = ((int *)src)[i]; - } - else - for (i = 0; i < count; i++) - ((byte *)dest)[i] = ((byte *)src)[i]; + if ((((uintptr_t) dest | (uintptr_t) src | count) & 3) == 0) { + count >>= 2; + for (i = 0; i < count; i++) + ((int *) dest)[i] = ((int *) src)[i]; + } else + for (i = 0; i < count; i++) + ((byte *) dest)[i] = ((byte *) src)[i]; } -int Q_memcmp (const void *m1, const void *m2, size_t count) -{ - while(count) - { - count--; - if (((byte *)m1)[count] != ((byte *)m2)[count]) - return -1; - } - return 0; +int Q_memcmp(const void *m1, const void *m2, size_t count) { + while (count) { + count--; + if (((byte *) m1)[count] != ((byte *) m2)[count]) + return -1; + } + return 0; } -void Q_strcpy (char *dest, const char *src) -{ - while (*src) - { - *dest++ = *src++; - } - *dest++ = 0; +void Q_strcpy(char *dest, const char *src) { + while (*src) { + *dest++ = *src++; + } + *dest++ = 0; } -void Q_strncpy (char *dest, const char *src, int count) -{ - while (*src && count--) - { - *dest++ = *src++; - } - if (count) - *dest++ = 0; +void Q_strncpy(char *dest, const char *src, int count) { + while (*src && count--) { + *dest++ = *src++; + } + if (count) + *dest++ = 0; } -int Q_strlen (const char *str) -{ - int count; +int Q_strlen(const char *str) { + int count; - count = 0; - while (str[count]) - count++; + count = 0; + while (str[count]) + count++; - return count; + return count; } -char *Q_strrchr(const char *s, char c) -{ - int len = Q_strlen(s); - s += len; - while (len--) - { - if (*--s == c) - return (char *)s; - } - return NULL; +char *Q_strrchr(const char *s, char c) { + int len = Q_strlen(s); + s += len; + while (len--) { + if (*--s == c) + return (char *) s; + } + return NULL; } -void Q_strcat (char *dest, const char *src) -{ - dest += Q_strlen(dest); - Q_strcpy (dest, src); +void Q_strcat(char *dest, const char *src) { + dest += Q_strlen(dest); + Q_strcpy(dest, src); } -int Q_strcmp (const char *s1, const char *s2) -{ - while (1) - { - if (*s1 != *s2) - return -1; // strings not equal - if (!*s1) - return 0; // strings are equal - s1++; - s2++; - } +int Q_strcmp(const char *s1, const char *s2) { + while (1) { + if (*s1 != *s2) + return -1; // strings not equal + if (!*s1) + return 0; // strings are equal + s1++; + s2++; + } - return -1; + return -1; } -int Q_strncmp (const char *s1, const char *s2, int count) -{ - while (1) - { - if (!count--) - return 0; - if (*s1 != *s2) - return -1; // strings not equal - if (!*s1) - return 0; // strings are equal - s1++; - s2++; - } +int Q_strncmp(const char *s1, const char *s2, int count) { + while (1) { + if (!count--) + return 0; + if (*s1 != *s2) + return -1; // strings not equal + if (!*s1) + return 0; // strings are equal + s1++; + s2++; + } - return -1; + return -1; } -int Q_atoi (const char *str) -{ - int val; - int sign; - int c; +int Q_atoi(const char *str) { + int val; + int sign; + int c; - while (q_isspace (*str)) - ++str; + while (q_isspace(*str)) + ++str; - if (*str == '-') - { - sign = -1; - str++; - } - else - sign = 1; + if (*str == '-') { + sign = -1; + str++; + } else + sign = 1; - val = 0; + val = 0; -// -// check for hex -// - if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X') ) - { - str += 2; - while (1) - { - c = *str++; - if (c >= '0' && c <= '9') - val = (val<<4) + c - '0'; - else if (c >= 'a' && c <= 'f') - val = (val<<4) + c - 'a' + 10; - else if (c >= 'A' && c <= 'F') - val = (val<<4) + c - 'A' + 10; - else - return val*sign; - } - } + // + // check for hex + // + if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) { + str += 2; + while (1) { + c = *str++; + if (c >= '0' && c <= '9') + val = (val << 4) + c - '0'; + else if (c >= 'a' && c <= 'f') + val = (val << 4) + c - 'a' + 10; + else if (c >= 'A' && c <= 'F') + val = (val << 4) + c - 'A' + 10; + else + return val * sign; + } + } -// -// check for character -// - if (str[0] == '\'') - { - return sign * str[1]; - } + // + // check for character + // + if (str[0] == '\'') { + return sign * str[1]; + } -// -// assume decimal -// - while (1) - { - c = *str++; - if (c <'0' || c > '9') - return val*sign; - val = val*10 + c - '0'; - } + // + // assume decimal + // + while (1) { + c = *str++; + if (c < '0' || c > '9') + return val * sign; + val = val * 10 + c - '0'; + } - return 0; + return 0; } -float Q_atof (const char *str) -{ - double val; - int sign; - int c; - int decimal, total; +float Q_atof(const char *str) { + double val; + int sign; + int c; + int decimal, total; - while (q_isspace (*str)) - ++str; + while (q_isspace(*str)) + ++str; - if (*str == '-') - { - sign = -1; - str++; - } - else - sign = 1; + if (*str == '-') { + sign = -1; + str++; + } else + sign = 1; - val = 0; + val = 0; -// -// check for hex -// - if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X') ) - { - str += 2; - while (1) - { - c = *str++; - if (c >= '0' && c <= '9') - val = (val*16) + c - '0'; - else if (c >= 'a' && c <= 'f') - val = (val*16) + c - 'a' + 10; - else if (c >= 'A' && c <= 'F') - val = (val*16) + c - 'A' + 10; - else - return val*sign; - } - } + // + // check for hex + // + if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) { + str += 2; + while (1) { + c = *str++; + if (c >= '0' && c <= '9') + val = (val * 16) + c - '0'; + else if (c >= 'a' && c <= 'f') + val = (val * 16) + c - 'a' + 10; + else if (c >= 'A' && c <= 'F') + val = (val * 16) + c - 'A' + 10; + else + return val * sign; + } + } -// -// check for character -// - if (str[0] == '\'') - { - return sign * str[1]; - } + // + // check for character + // + if (str[0] == '\'') { + return sign * str[1]; + } -// -// assume decimal -// - decimal = -1; - total = 0; - while (1) - { - c = *str++; - if (c == '.') - { - decimal = total; - continue; - } - if (c <'0' || c > '9') - break; - val = val*10 + c - '0'; - total++; - } + // + // assume decimal + // + decimal = -1; + total = 0; + while (1) { + c = *str++; + if (c == '.') { + decimal = total; + continue; + } + if (c < '0' || c > '9') + break; + val = val * 10 + c - '0'; + total++; + } - if (decimal == -1) - return val*sign; - while (total > decimal) - { - val /= 10; - total--; - } + if (decimal == -1) + return val * sign; + while (total > decimal) { + val /= 10; + total--; + } - return val*sign; + return val * sign; } /* @@ -601,67 +543,65 @@ float Q_atof (const char *str) ============================================================================ */ -qboolean host_bigendian; +qboolean host_bigendian; -short (*BigShort) (short l); -short (*LittleShort) (short l); -int (*BigLong) (int l); -int (*LittleLong) (int l); -float (*BigFloat) (float l); -float (*LittleFloat) (float l); +short (*BigShort)(short l); -short ShortSwap (short l) -{ - byte b1, b2; +short (*LittleShort)(short l); - b1 = l&255; - b2 = (l>>8)&255; +int (*BigLong)(int l); - return (b1<<8) + b2; +int (*LittleLong)(int l); + +float (*BigFloat)(float l); + +float (*LittleFloat)(float l); + +short ShortSwap(short l) { + byte b1, b2; + + b1 = l & 255; + b2 = (l >> 8) & 255; + + return (b1 << 8) + b2; } -short ShortNoSwap (short l) -{ - return l; +short ShortNoSwap(short l) { + return l; } -int LongSwap (int l) -{ - byte b1, b2, b3, b4; +int LongSwap(int l) { + byte b1, b2, b3, b4; - b1 = l&255; - b2 = (l>>8)&255; - b3 = (l>>16)&255; - b4 = (l>>24)&255; + b1 = l & 255; + b2 = (l >> 8) & 255; + b3 = (l >> 16) & 255; + b4 = (l >> 24) & 255; - return ((int)b1<<24) + ((int)b2<<16) + ((int)b3<<8) + b4; + return ((int) b1 << 24) + ((int) b2 << 16) + ((int) b3 << 8) + b4; } -int LongNoSwap (int l) -{ - return l; +int LongNoSwap(int l) { + return l; } -float FloatSwap (float f) -{ - union - { - float f; - byte b[4]; - } dat1, dat2; +float FloatSwap(float f) { + union { + float f; + byte b[4]; + } dat1, dat2; - dat1.f = f; - dat2.b[0] = dat1.b[3]; - dat2.b[1] = dat1.b[2]; - dat2.b[2] = dat1.b[1]; - dat2.b[3] = dat1.b[0]; - return dat2.f; + dat1.f = f; + dat2.b[0] = dat1.b[3]; + dat2.b[1] = dat1.b[2]; + dat2.b[2] = dat1.b[1]; + dat2.b[3] = dat1.b[0]; + return dat2.f; } -float FloatNoSwap (float f) -{ - return f; +float FloatNoSwap(float f) { + return f; } /* @@ -677,363 +617,326 @@ Handles byte ordering and avoids alignment errors // writing functions // -void MSG_WriteChar (sizebuf_t *sb, int c) -{ - byte *buf; +void MSG_WriteChar(sizebuf_t *sb, int c) { + byte *buf; #ifdef PARANOID - if (c < -128 || c > 127) - Sys_Error ("MSG_WriteChar: range error"); + if (c < -128 || c > 127) + Sys_Error("MSG_WriteChar: range error"); #endif - buf = (byte *) SZ_GetSpace (sb, 1); - buf[0] = c; + buf = (byte *) SZ_GetSpace(sb, 1); + buf[0] = c; } -void MSG_WriteByte (sizebuf_t *sb, int c) -{ - byte *buf; +void MSG_WriteByte(sizebuf_t *sb, int c) { + byte *buf; #ifdef PARANOID - if (c < 0 || c > 255) - Sys_Error ("MSG_WriteByte: range error"); + if (c < 0 || c > 255) + Sys_Error("MSG_WriteByte: range error"); #endif - buf = (byte *) SZ_GetSpace (sb, 1); - buf[0] = c; + buf = (byte *) SZ_GetSpace(sb, 1); + buf[0] = c; } -void MSG_WriteShort (sizebuf_t *sb, int c) -{ - byte *buf; +void MSG_WriteShort(sizebuf_t *sb, int c) { + byte *buf; #ifdef PARANOID - if (c < ((short)0x8000) || c > (short)0x7fff) - Sys_Error ("MSG_WriteShort: range error"); + if (c < ((short) 0x8000) || c > (short) 0x7fff) + Sys_Error("MSG_WriteShort: range error"); #endif - buf = (byte *) SZ_GetSpace (sb, 2); - buf[0] = c&0xff; - buf[1] = c>>8; + buf = (byte *) SZ_GetSpace(sb, 2); + buf[0] = c & 0xff; + buf[1] = c >> 8; } -void MSG_WriteLong (sizebuf_t *sb, int c) -{ - byte *buf; +void MSG_WriteLong(sizebuf_t *sb, int c) { + byte *buf; - buf = (byte *) SZ_GetSpace (sb, 4); - buf[0] = c&0xff; - buf[1] = (c>>8)&0xff; - buf[2] = (c>>16)&0xff; - buf[3] = c>>24; + buf = (byte *) SZ_GetSpace(sb, 4); + buf[0] = c & 0xff; + buf[1] = (c >> 8) & 0xff; + buf[2] = (c >> 16) & 0xff; + buf[3] = c >> 24; } -void MSG_WriteFloat (sizebuf_t *sb, float f) -{ - union - { - float f; - int l; - } dat; +void MSG_WriteFloat(sizebuf_t *sb, float f) { + union { + float f; + int l; + } dat; - dat.f = f; - dat.l = LittleLong (dat.l); + dat.f = f; + dat.l = LittleLong(dat.l); - SZ_Write (sb, &dat.l, 4); + SZ_Write(sb, &dat.l, 4); } -void MSG_WriteString (sizebuf_t *sb, const char *s) -{ - if (!s) - SZ_Write (sb, "", 1); - else - SZ_Write (sb, s, Q_strlen(s)+1); +void MSG_WriteString(sizebuf_t *sb, const char *s) { + if (!s) + SZ_Write(sb, "", 1); + else + SZ_Write(sb, s, Q_strlen(s) + 1); } //johnfitz -- original behavior, 13.3 fixed point coords, max range +-4096 -void MSG_WriteCoord16 (sizebuf_t *sb, float f) -{ - MSG_WriteShort (sb, Q_rint(f*8)); +void MSG_WriteCoord16(sizebuf_t *sb, float f) { + MSG_WriteShort(sb, Q_rint(f*8)); } //johnfitz -- 16.8 fixed point coords, max range +-32768 -void MSG_WriteCoord24 (sizebuf_t *sb, float f) -{ - MSG_WriteShort (sb, f); - MSG_WriteByte (sb, (int)(f*255)%255); +void MSG_WriteCoord24(sizebuf_t *sb, float f) { + MSG_WriteShort(sb, f); + MSG_WriteByte(sb, (int) (f * 255) % 255); } //johnfitz -- 32-bit float coords -void MSG_WriteCoord32f (sizebuf_t *sb, float f) -{ - MSG_WriteFloat (sb, f); +void MSG_WriteCoord32f(sizebuf_t *sb, float f) { + MSG_WriteFloat(sb, f); } -void MSG_WriteCoord (sizebuf_t *sb, float f, unsigned int flags) -{ - if (flags & PRFL_FLOATCOORD) - MSG_WriteFloat (sb, f); - else if (flags & PRFL_INT32COORD) - MSG_WriteLong (sb, Q_rint (f * 16)); - else if (flags & PRFL_24BITCOORD) - MSG_WriteCoord24 (sb, f); - else MSG_WriteCoord16 (sb, f); +void MSG_WriteCoord(sizebuf_t *sb, float f, unsigned int flags) { + if (flags & PRFL_FLOATCOORD) + MSG_WriteFloat(sb, f); + else if (flags & PRFL_INT32COORD) + MSG_WriteLong(sb, Q_rint(f * 16)); + else if (flags & PRFL_24BITCOORD) + MSG_WriteCoord24(sb, f); + else MSG_WriteCoord16(sb, f); } -void MSG_WriteAngle (sizebuf_t *sb, float f, unsigned int flags) -{ - if (flags & PRFL_FLOATANGLE) - MSG_WriteFloat (sb, f); - else if (flags & PRFL_SHORTANGLE) - MSG_WriteShort (sb, Q_rint(f * 65536.0 / 360.0) & 65535); - else MSG_WriteByte (sb, Q_rint(f * 256.0 / 360.0) & 255); //johnfitz -- use Q_rint instead of (int) } +void MSG_WriteAngle(sizebuf_t *sb, float f, unsigned int flags) { + if (flags & PRFL_FLOATANGLE) + MSG_WriteFloat(sb, f); + else if (flags & PRFL_SHORTANGLE) + MSG_WriteShort(sb, Q_rint(f * 65536.0 / 360.0) & 65535); + else MSG_WriteByte(sb, Q_rint(f * 256.0 / 360.0) & 255); //johnfitz -- use Q_rint instead of (int) } } //johnfitz -- for PROTOCOL_FITZQUAKE -void MSG_WriteAngle16 (sizebuf_t *sb, float f, unsigned int flags) -{ - if (flags & PRFL_FLOATANGLE) - MSG_WriteFloat (sb, f); - else MSG_WriteShort (sb, Q_rint(f * 65536.0 / 360.0) & 65535); +void MSG_WriteAngle16(sizebuf_t *sb, float f, unsigned int flags) { + if (flags & PRFL_FLOATANGLE) + MSG_WriteFloat(sb, f); + else MSG_WriteShort(sb, Q_rint(f * 65536.0 / 360.0) & 65535); } + //johnfitz // // reading functions // -int msg_readcount; -qboolean msg_badread; +int msg_readcount; +qboolean msg_badread; -void MSG_BeginReading (void) -{ - msg_readcount = 0; - msg_badread = false; +void MSG_BeginReading(void) { + msg_readcount = 0; + msg_badread = false; } // returns -1 and sets msg_badread if no more characters are available -int MSG_ReadChar (void) -{ - int c; +int MSG_ReadChar(void) { + int c; - if (msg_readcount+1 > net_message.cursize) - { - msg_badread = true; - return -1; - } + if (msg_readcount + 1 > net_message.cursize) { + msg_badread = true; + return -1; + } - c = (signed char)net_message.data[msg_readcount]; - msg_readcount++; + c = (signed char) net_message.data[msg_readcount]; + msg_readcount++; - return c; + return c; } -int MSG_ReadByte (void) -{ - int c; +int MSG_ReadByte(void) { + int c; - if (msg_readcount+1 > net_message.cursize) - { - msg_badread = true; - return -1; - } + if (msg_readcount + 1 > net_message.cursize) { + msg_badread = true; + return -1; + } - c = (unsigned char)net_message.data[msg_readcount]; - msg_readcount++; + c = (unsigned char) net_message.data[msg_readcount]; + msg_readcount++; - return c; + return c; } -int MSG_ReadShort (void) -{ - int c; +int MSG_ReadShort(void) { + int c; - if (msg_readcount+2 > net_message.cursize) - { - msg_badread = true; - return -1; - } + if (msg_readcount + 2 > net_message.cursize) { + msg_badread = true; + return -1; + } - c = (short)(net_message.data[msg_readcount] - + (net_message.data[msg_readcount+1]<<8)); + c = (short) (net_message.data[msg_readcount] + + (net_message.data[msg_readcount + 1] << 8)); - msg_readcount += 2; + msg_readcount += 2; - return c; + return c; } -int MSG_ReadLong (void) -{ - int c; +int MSG_ReadLong(void) { + int c; - if (msg_readcount+4 > net_message.cursize) - { - msg_badread = true; - return -1; - } + if (msg_readcount + 4 > net_message.cursize) { + msg_badread = true; + return -1; + } - c = net_message.data[msg_readcount] - + (net_message.data[msg_readcount+1]<<8) - + (net_message.data[msg_readcount+2]<<16) - + (net_message.data[msg_readcount+3]<<24); + c = net_message.data[msg_readcount] + + (net_message.data[msg_readcount + 1] << 8) + + (net_message.data[msg_readcount + 2] << 16) + + (net_message.data[msg_readcount + 3] << 24); - msg_readcount += 4; + msg_readcount += 4; - return c; + return c; } -float MSG_ReadFloat (void) -{ - union - { - byte b[4]; - float f; - int l; - } dat; +float MSG_ReadFloat(void) { + union { + byte b[4]; + float f; + int l; + } dat; - dat.b[0] = net_message.data[msg_readcount]; - dat.b[1] = net_message.data[msg_readcount+1]; - dat.b[2] = net_message.data[msg_readcount+2]; - dat.b[3] = net_message.data[msg_readcount+3]; - msg_readcount += 4; + dat.b[0] = net_message.data[msg_readcount]; + dat.b[1] = net_message.data[msg_readcount + 1]; + dat.b[2] = net_message.data[msg_readcount + 2]; + dat.b[3] = net_message.data[msg_readcount + 3]; + msg_readcount += 4; - dat.l = LittleLong (dat.l); + dat.l = LittleLong(dat.l); - return dat.f; + return dat.f; } -const char *MSG_ReadString (void) -{ - static char string[2048]; - int c; - size_t l; +const char *MSG_ReadString(void) { + static char string[2048]; + int c; + size_t l; - l = 0; - do - { - c = MSG_ReadByte (); - if (c == -1 || c == 0) - break; - string[l] = c; - l++; - } while (l < sizeof(string) - 1); + l = 0; + do { + c = MSG_ReadByte(); + if (c == -1 || c == 0) + break; + string[l] = c; + l++; + } while (l < sizeof(string) - 1); - string[l] = 0; + string[l] = 0; - return string; + return string; } //johnfitz -- original behavior, 13.3 fixed point coords, max range +-4096 -float MSG_ReadCoord16 (void) -{ - return MSG_ReadShort() * (1.0/8); +float MSG_ReadCoord16(void) { + return MSG_ReadShort() * (1.0 / 8); } //johnfitz -- 16.8 fixed point coords, max range +-32768 -float MSG_ReadCoord24 (void) -{ - return MSG_ReadShort() + MSG_ReadByte() * (1.0/255); +float MSG_ReadCoord24(void) { + return MSG_ReadShort() + MSG_ReadByte() * (1.0 / 255); } //johnfitz -- 32-bit float coords -float MSG_ReadCoord32f (void) -{ - return MSG_ReadFloat(); +float MSG_ReadCoord32f(void) { + return MSG_ReadFloat(); } -float MSG_ReadCoord (unsigned int flags) -{ - if (flags & PRFL_FLOATCOORD) - return MSG_ReadFloat (); - else if (flags & PRFL_INT32COORD) - return MSG_ReadLong () * (1.0 / 16.0); - else if (flags & PRFL_24BITCOORD) - return MSG_ReadCoord24 (); - else return MSG_ReadCoord16 (); +float MSG_ReadCoord(unsigned int flags) { + if (flags & PRFL_FLOATCOORD) + return MSG_ReadFloat(); + else if (flags & PRFL_INT32COORD) + return MSG_ReadLong() * (1.0 / 16.0); + else if (flags & PRFL_24BITCOORD) + return MSG_ReadCoord24(); + else return MSG_ReadCoord16(); } -float MSG_ReadAngle (unsigned int flags) -{ - if (flags & PRFL_FLOATANGLE) - return MSG_ReadFloat (); - else if (flags & PRFL_SHORTANGLE) - return MSG_ReadShort () * (360.0 / 65536); - else return MSG_ReadChar () * (360.0 / 256); +float MSG_ReadAngle(unsigned int flags) { + if (flags & PRFL_FLOATANGLE) + return MSG_ReadFloat(); + else if (flags & PRFL_SHORTANGLE) + return MSG_ReadShort() * (360.0 / 65536); + else return MSG_ReadChar() * (360.0 / 256); } //johnfitz -- for PROTOCOL_FITZQUAKE -float MSG_ReadAngle16 (unsigned int flags) -{ - if (flags & PRFL_FLOATANGLE) - return MSG_ReadFloat (); // make sure - else return MSG_ReadShort () * (360.0 / 65536); +float MSG_ReadAngle16(unsigned int flags) { + if (flags & PRFL_FLOATANGLE) + return MSG_ReadFloat(); // make sure + else return MSG_ReadShort() * (360.0 / 65536); } + //johnfitz //=========================================================================== -void SZ_Alloc (sizebuf_t *buf, int startsize) -{ - if (startsize < 256) - startsize = 256; - buf->data = (byte *) Hunk_AllocName (startsize, "sizebuf"); - buf->maxsize = startsize; - buf->cursize = 0; +void SZ_Alloc(sizebuf_t *buf, int startsize) { + if (startsize < 256) + startsize = 256; + buf->data = (byte *) Hunk_AllocName(startsize, "sizebuf"); + buf->maxsize = startsize; + buf->cursize = 0; } -void SZ_Free (sizebuf_t *buf) -{ -// Z_Free (buf->data); -// buf->data = NULL; -// buf->maxsize = 0; - buf->cursize = 0; +void SZ_Free(sizebuf_t *buf) { + // Z_Free (buf->data); + // buf->data = NULL; + // buf->maxsize = 0; + buf->cursize = 0; } -void SZ_Clear (sizebuf_t *buf) -{ - buf->cursize = 0; +void SZ_Clear(sizebuf_t *buf) { + buf->cursize = 0; } -void *SZ_GetSpace (sizebuf_t *buf, int length) -{ - void *data; +void *SZ_GetSpace(sizebuf_t *buf, int length) { + void *data; - if (buf->cursize + length > buf->maxsize) - { - if (!buf->allowoverflow) - Host_Error ("SZ_GetSpace: overflow without allowoverflow set"); // ericw -- made Host_Error to be less annoying + if (buf->cursize + length > buf->maxsize) { + if (!buf->allowoverflow) + Host_Error("SZ_GetSpace: overflow without allowoverflow set"); + // ericw -- made Host_Error to be less annoying - if (length > buf->maxsize) - Sys_Error ("SZ_GetSpace: %i is > full buffer size", length); + if (length > buf->maxsize) + Sys_Error("SZ_GetSpace: %i is > full buffer size", length); - buf->overflowed = true; - Con_Printf ("SZ_GetSpace: overflow\n"); - SZ_Clear (buf); - } + buf->overflowed = true; + Con_Printf("SZ_GetSpace: overflow\n"); + SZ_Clear(buf); + } - data = buf->data + buf->cursize; - buf->cursize += length; + data = buf->data + buf->cursize; + buf->cursize += length; - return data; + return data; } -void SZ_Write (sizebuf_t *buf, const void *data, int length) -{ - Q_memcpy (SZ_GetSpace(buf,length),data,length); +void SZ_Write(sizebuf_t *buf, const void *data, int length) { + Q_memcpy(SZ_GetSpace(buf, length), data, length); } -void SZ_Print (sizebuf_t *buf, const char *data) -{ - int len = Q_strlen(data) + 1; +void SZ_Print(sizebuf_t *buf, const char *data) { + int len = Q_strlen(data) + 1; - if (buf->data[buf->cursize-1]) - { /* no trailing 0 */ - Q_memcpy ((byte *)SZ_GetSpace(buf, len ) , data, len); - } - else - { /* write over trailing 0 */ - Q_memcpy ((byte *)SZ_GetSpace(buf, len-1)-1, data, len); - } + if (buf->data[buf->cursize - 1]) { + /* no trailing 0 */ + Q_memcpy((byte *) SZ_GetSpace(buf, len), data, len); + } else { + /* write over trailing 0 */ + Q_memcpy((byte *) SZ_GetSpace(buf, len - 1) - 1, data, len); + } } @@ -1044,18 +947,16 @@ void SZ_Print (sizebuf_t *buf, const char *data) COM_SkipPath ============ */ -const char *COM_SkipPath (const char *pathname) -{ - const char *last; +const char *COM_SkipPath(const char *pathname) { + const char *last; - last = pathname; - while (*pathname) - { - if (*pathname == '/') - last = pathname + 1; - pathname++; - } - return last; + last = pathname; + while (*pathname) { + if (*pathname == '/') + last = pathname + 1; + pathname++; + } + return last; } /* @@ -1063,26 +964,23 @@ const char *COM_SkipPath (const char *pathname) COM_StripExtension ============ */ -void COM_StripExtension (const char *in, char *out, size_t outsize) -{ - int length; +void COM_StripExtension(const char *in, char *out, size_t outsize) { + int length; - if (!*in) - { - *out = '\0'; - return; - } - if (in != out) /* copy when not in-place editing */ - q_strlcpy (out, in, outsize); - length = (int)strlen(out) - 1; - while (length > 0 && out[length] != '.') - { - --length; - if (out[length] == '/' || out[length] == '\\') - return; /* no extension */ - } - if (length > 0) - out[length] = '\0'; + if (!*in) { + *out = '\0'; + return; + } + if (in != out) /* copy when not in-place editing */ + q_strlcpy(out, in, outsize); + length = (int) strlen(out) - 1; + while (length > 0 && out[length] != '.') { + --length; + if (out[length] == '/' || out[length] == '\\') + return; /* no extension */ + } + if (length > 0) + out[length] = '\0'; } /* @@ -1090,22 +988,21 @@ void COM_StripExtension (const char *in, char *out, size_t outsize) COM_FileGetExtension - doesn't return NULL ============ */ -const char *COM_FileGetExtension (const char *in) -{ - const char *src; - size_t len; +const char *COM_FileGetExtension(const char *in) { + const char *src; + size_t len; - len = strlen(in); - if (len < 2) /* nothing meaningful */ - return ""; + len = strlen(in); + if (len < 2) /* nothing meaningful */ + return ""; - src = in + len - 1; - while (src != in && src[-1] != '.') - src--; - if (src == in || strchr(src, '/') != NULL || strchr(src, '\\') != NULL) - return ""; /* no extension, or parent directory has a dot */ + src = in + len - 1; + while (src != in && src[-1] != '.') + src--; + if (src == in || strchr(src, '/') != NULL || strchr(src, '\\') != NULL) + return ""; /* no extension, or parent directory has a dot */ - return src; + return src; } /* @@ -1113,13 +1010,12 @@ const char *COM_FileGetExtension (const char *in) COM_ExtractExtension ============ */ -void COM_ExtractExtension (const char *in, char *out, size_t outsize) -{ - const char *ext = COM_FileGetExtension (in); - if (! *ext) - *out = '\0'; - else - q_strlcpy (out, ext, outsize); +void COM_ExtractExtension(const char *in, char *out, size_t outsize) { + const char *ext = COM_FileGetExtension(in); + if (!*ext) + *out = '\0'; + else + q_strlcpy(out, ext, outsize); } /* @@ -1129,34 +1025,31 @@ take 'somedir/otherdir/filename.ext', write only 'filename' to the output ============ */ -void COM_FileBase (const char *in, char *out, size_t outsize) -{ - const char *dot, *slash, *s; +void COM_FileBase(const char *in, char *out, size_t outsize) { + const char *dot, *slash, *s; - s = in; - slash = in; - dot = NULL; - while (*s) - { - if (*s == '/') - slash = s + 1; - if (*s == '.') - dot = s; - s++; - } - if (dot == NULL) - dot = s; + s = in; + slash = in; + dot = NULL; + while (*s) { + if (*s == '/') + slash = s + 1; + if (*s == '.') + dot = s; + s++; + } + if (dot == NULL) + dot = s; - if (dot - slash < 2) - q_strlcpy (out, "?model?", outsize); - else - { - size_t len = dot - slash; - if (len >= outsize) - len = outsize - 1; - memcpy (out, slash, len); - out[len] = '\0'; - } + if (dot - slash < 2) + q_strlcpy(out, "?model?", outsize); + else { + size_t len = dot - slash; + if (len >= outsize) + len = outsize - 1; + memcpy(out, slash, len); + out[len] = '\0'; + } } /* @@ -1167,21 +1060,19 @@ if path doesn't have a .EXT, append extension ================== */ #if 0 /* can be dangerous */ -void COM_DefaultExtension (char *path, const char *extension, size_t len) -{ - char *src; +void COM_DefaultExtension(char *path, const char *extension, size_t len) { + char *src; - if (!*path) return; - src = path + strlen(path) - 1; + if (!*path) return; + src = path + strlen(path) - 1; - while (*src != '/' && *src != '\\' && src != path) - { - if (*src == '.') - return; // it has an extension - src--; - } + while (*src != '/' && *src != '\\' && src != path) { + if (*src == '.') + return; // it has an extension + src--; + } - q_strlcat(path, extension, len); + q_strlcat(path, extension, len); } #endif @@ -1192,125 +1083,134 @@ if path extension doesn't match .EXT, append it (extension should include the leading ".") ================== */ -void COM_AddExtension (char *path, const char *extension, size_t len) -{ - if (strcmp(COM_FileGetExtension(path), extension + 1) != 0) - q_strlcat(path, extension, len); +void COM_AddExtension(char *path, const char *extension, size_t len) { + if (strcmp(COM_FileGetExtension(path), extension + 1) != 0) + q_strlcat(path, extension, len); } -/* -============== -COM_ParseEx +namespace common { + /** + * Parses a single token from a string-stream. + * + * @param ss String-stream containing the data buffer to parse. + * @return A token, if parseable, otherwise \c std::nullopt . + */ + std::optional parse_token(std::istringstream &ss) { + std::string res{}; + skipwhite: + while (ss.peek() <= ' ') { + ss.get(); + if (ss.peek() == '\0') { + return std::nullopt; + } + if (ss.eof()) { + return std::nullopt; + } + } -Parse a token out of a string + if (ss.peek() == '/') { + ss.get(); + switch (ss.peek()) { + case '/': { + std::string _ignore; + std::getline(ss, _ignore); + goto skipwhite; + } + case '*': { + ss.get(); + commentwait: + while (ss.peek() != '*') { + ss.get(); + } + ss.get(); + if (ss.peek() != '/') { + goto commentwait; + } + ss.get(); + goto skipwhite; + } + default: + ss.unget(); + } + } -The mode argument controls how overflow is handled: -- CPE_NOTRUNC: return NULL (abort parsing) -- CPE_ALLOWTRUNC: truncate com_token (ignore the extra characters in this token) -============== -*/ -const char *COM_ParseEx (const char *data, cpe_mode mode) -{ - int c; - int len; + if (ss.peek() == '"') { + ss.get(); + std::getline(ss, res, '"'); + return res; + } - len = 0; - com_token[0] = 0; + if (ss.peek() == '{' || ss.peek() == '}' || ss.peek() == '(' || ss.peek() == ')' || ss.peek() == '\'' || ss. + peek() == ':') { + res += static_cast(ss.get()); + return res; + } - if (!data) - return NULL; + do { + res += static_cast(ss.get()); + if (ss.peek() == '{' || ss.peek() == '}' || ss.peek() == '(' || ss.peek() == ')' || ss.peek() == '\'') { + break; + } + } while (ss.peek() > ' '); -// skip whitespace -skipwhite: - while ((c = *data) <= ' ') - { - if (c == 0) - return NULL; // end of file - data++; - } + return res; + } -// skip // comments - if (c == '/' && data[1] == '/') - { - while (*data && *data != '\n') - data++; - goto skipwhite; - } + /** + * Parses a string of non-whitespace, and then attempts to consume a newline. + * + * N.B. This is implementing the function as \a described, not following the original + * implementation. The original implementation is bugged. + * @param ss + * @return + */ + std::string parse_string_newline(std::istringstream &ss) { + std::string res; -// skip /*..*/ comments - if (c == '/' && data[1] == '*') - { - data += 2; - while (*data && !(*data == '*' && data[1] == '/')) - data++; - if (*data) - data += 2; - goto skipwhite; - } + while (ss.peek() > ' ') { + res += static_cast(ss.get()); + } + if (ss.peek() == '\n') { + ss.get(); + } -// handle quoted strings specially - if (c == '\"') - { - data++; - while (1) - { - if ((c = *data) != 0) - ++data; - if (c == '\"' || !c) - { - com_token[len] = 0; - return data; - } - if (len < Q_COUNTOF(com_token) - 1) - com_token[len++] = c; - else if (mode == CPE_NOTRUNC) - return NULL; - } - } + return res; + } -// parse single characters - if (c == '{' || c == '}'|| c == '('|| c == ')' || c == '\'' || c == ':') - { - if (len < Q_COUNTOF(com_token) - 1) - com_token[len++] = c; - else if (mode == CPE_NOTRUNC) - return NULL; - com_token[len] = 0; - return data+1; - } + /** + * Attempts to parse an int, followed by a newline. + * + * @param ss + * @return + */ + int parse_int_newline(std::istringstream &ss) { + int res; -// parse a regular word - do - { - if (len < Q_COUNTOF(com_token) - 1) - com_token[len++] = c; - else if (mode == CPE_NOTRUNC) - return NULL; - data++; - c = *data; - /* commented out the check for ':' so that ip:port works */ - if (c == '{' || c == '}'|| c == '('|| c == ')' || c == '\''/* || c == ':' */) - break; - } while (c > 32); + ss >> res; + if (ss.peek() == '\n') { + ss.get(); + } - com_token[len] = 0; - return data; -} + return res; + } + /** + * Attempts to parse a float followed by a newline. + * + * @param ss + * @return + */ + float parse_float_newline(std::istringstream &ss) { + float res; -/* -============== -COM_Parse + ss >> res; + if (ss.peek() == '\n') { + ss.get(); + } -Parse a token out of a string - -Return NULL in case of overflow -============== -*/ -const char *COM_Parse (const char *data) -{ - return COM_ParseEx (data, CPE_NOTRUNC); + return res; + } } @@ -1322,19 +1222,17 @@ Returns the position (1 to argc-1) in the program's argument list where the given parameter apears, or 0 if not present ================ */ -int COM_CheckParm (const char *parm) -{ - int i; +int COM_CheckParm(const char *parm) { + int i; - for (i = 1; i < com_argc; i++) - { - if (!com_argv[i]) - continue; // NEXTSTEP sometimes clears appkit vars. - if (!Q_strcmp (parm,com_argv[i])) - return i; - } + for (i = 1; i < com_argc; i++) { + if (!com_argv[i]) + continue; // NEXTSTEP sometimes clears appkit vars. + if (!Q_strcmp(parm, com_argv[i])) + return i; + } - return 0; + return 0; } /* @@ -1347,49 +1245,45 @@ Immediately exits out if an alternate game was attempted to be started without being registered. ================ */ -static void COM_CheckRegistered (void) -{ - int h; - unsigned short check[128]; - int i; +static void COM_CheckRegistered(void) { + int h; + unsigned short check[128]; + int i; - COM_OpenFile("gfx/pop.lmp", &h, NULL); + COM_OpenFile("gfx/pop.lmp", &h, NULL); - if (h == -1) - { - Cvar_SetROM ("registered", "0"); - Con_Printf ("Playing shareware version.\n"); - if (com_modified) - Sys_Error ("You must have the registered version to use modified games.\n\n" - "Basedir is: %s\n\n" - "Check that this has an " GAMENAME " subdirectory containing pak0.pak and pak1.pak, " - "or use the -basedir command-line option to specify another directory.", - com_basedir); - return; - } + if (h == -1) { + convar::set_rom("registered", "0"); + Con_Printf("Playing shareware version.\n"); + if (com_modified) + Sys_Error("You must have the registered version to use modified games.\n\n" + "Basedir is: %s\n\n" + "Check that this has an " GAMENAME " subdirectory containing pak0.pak and pak1.pak, " + "or use the -basedir command-line option to specify another directory.", + com_basedir); + return; + } - i = Sys_FileRead (h, check, sizeof(check)); - COM_CloseFile (h); - if (i != (int) sizeof(check)) - goto corrupt; + i = Sys_FileRead(h, check, sizeof(check)); + COM_CloseFile(h); + if (i != (int) sizeof(check)) + goto corrupt; - for (i = 0; i < 128; i++) - { - if (pop[i] != (unsigned short)BigShort (check[i])) - { corrupt: - Sys_Error ("Corrupted data file."); - } - } + for (i = 0; i < 128; i++) { + if (pop[i] != (unsigned short) BigShort(check[i])) { + corrupt: + Sys_Error("Corrupted data file."); + } + } - for (i = 0; com_cmdline[i]; i++) - { - if (com_cmdline[i]!= ' ') - break; - } + for (i = 0; com_cmdline[i]; i++) { + if (com_cmdline[i] != ' ') + break; + } - Cvar_SetROM ("cmdline", &com_cmdline[i]); - Cvar_SetROM ("registered", "1"); - Con_Printf ("Playing registered version.\n"); + convar::set_rom("cmdline", &com_cmdline[i]); + convar::set_rom("registered", "1"); + Con_Printf("Playing registered version.\n"); } @@ -1398,54 +1292,49 @@ static void COM_CheckRegistered (void) COM_InitArgv ================ */ -void COM_InitArgv (int argc, char **argv) -{ - int i, j, n; +void COM_InitArgv(int argc, char **argv) { + int i, j, n; -// reconstitute the command line for the cmdline externally visible cvar - n = 0; + // reconstitute the command line for the cmdline externally visible cvar + n = 0; - for (j = 0; (j 0 && com_cmdline[n-1] == ' ') - com_cmdline[n-1] = 0; //johnfitz -- kill the trailing space + if (n > 0 && com_cmdline[n - 1] == ' ') + com_cmdline[n - 1] = 0; //johnfitz -- kill the trailing space - Con_Printf("Command line: %s\n", com_cmdline); + Con_Printf("Command line: %s\n", com_cmdline); - for (com_argc = 0; (com_argc < MAX_NUM_ARGVS) && (com_argc < argc); com_argc++) - { - largv[com_argc] = argv[com_argc]; - if (!Q_strcmp ("-safe", argv[com_argc])) - safemode = 1; - } + for (com_argc = 0; (com_argc < MAX_NUM_ARGVS) && (com_argc < argc); com_argc++) { + largv[com_argc] = argv[com_argc]; + if (!Q_strcmp("-safe", argv[com_argc])) + safemode = 1; + } - largv[com_argc] = argvdummy; - com_argv = largv; + largv[com_argc] = argvdummy; + com_argv = largv; - if (COM_CheckParm ("-rogue")) - { - rogue = true; - standard_quake = false; - } + if (COM_CheckParm("-rogue")) { + rogue = true; + standard_quake = false; + } - if (COM_CheckParm ("-hipnotic") || COM_CheckParm ("-quoth")) //johnfitz -- "-quoth" support - { - hipnotic = true; - standard_quake = false; - } + if (COM_CheckParm("-hipnotic") || COM_CheckParm("-quoth")) //johnfitz -- "-quoth" support + { + hipnotic = true; + standard_quake = false; + } } /* @@ -1453,49 +1342,46 @@ void COM_InitArgv (int argc, char **argv) COM_Init ================ */ -void COM_Init (void) -{ - int i = 0x12345678; - /* U N I X */ +void COM_Init(void) { + int i = 0x12345678; + /* U N I X */ - /* - BE_ORDER: 12 34 56 78 - U N I X + /* + BE_ORDER: 12 34 56 78 + U N I X - LE_ORDER: 78 56 34 12 - X I N U + LE_ORDER: 78 56 34 12 + X I N U - PDP_ORDER: 34 12 78 56 - N U X I - */ - if ( *(char *)&i == 0x12 ) - host_bigendian = true; - else if ( *(char *)&i == 0x78 ) - host_bigendian = false; - else /* if ( *(char *)&i == 0x34 ) */ - Sys_Error ("Unsupported endianism."); + PDP_ORDER: 34 12 78 56 + N U X I + */ + if (*(char *) &i == 0x12) + host_bigendian = true; + else if (*(char *) &i == 0x78) + host_bigendian = false; + else /* if ( *(char *)&i == 0x34 ) */ + Sys_Error("Unsupported endianism."); - if (host_bigendian) - { - BigShort = ShortNoSwap; - LittleShort = ShortSwap; - BigLong = LongNoSwap; - LittleLong = LongSwap; - BigFloat = FloatNoSwap; - LittleFloat = FloatSwap; - } - else /* assumed LITTLE_ENDIAN. */ - { - BigShort = ShortSwap; - LittleShort = ShortNoSwap; - BigLong = LongSwap; - LittleLong = LongNoSwap; - BigFloat = FloatSwap; - LittleFloat = FloatNoSwap; - } + if (host_bigendian) { + BigShort = ShortNoSwap; + LittleShort = ShortSwap; + BigLong = LongNoSwap; + LittleLong = LongSwap; + BigFloat = FloatNoSwap; + LittleFloat = FloatSwap; + } else /* assumed LITTLE_ENDIAN. */ + { + BigShort = ShortSwap; + LittleShort = ShortNoSwap; + BigLong = LongSwap; + LittleLong = LongNoSwap; + BigFloat = FloatSwap; + LittleFloat = FloatNoSwap; + } - if (COM_CheckParm("-fitz")) - fitzmode = true; + if (COM_CheckParm("-fitz")) + fitzmode = true; } @@ -1512,25 +1398,23 @@ FIXME: make this buffer size safe someday #define VA_NUM_BUFFS 4 #define VA_BUFFERLEN 1024 -static char *get_va_buffer(void) -{ - static char va_buffers[VA_NUM_BUFFS][VA_BUFFERLEN]; - static int buffer_idx = 0; - buffer_idx = (buffer_idx + 1) & (VA_NUM_BUFFS - 1); - return va_buffers[buffer_idx]; +static char *get_va_buffer(void) { + static char va_buffers[VA_NUM_BUFFS][VA_BUFFERLEN]; + static int buffer_idx = 0; + buffer_idx = (buffer_idx + 1) & (VA_NUM_BUFFS - 1); + return va_buffers[buffer_idx]; } -char *va (const char *format, ...) -{ - va_list argptr; - char *va_buf; +char *va(const char *format, ...) { + va_list argptr; + char *va_buf; - va_buf = get_va_buffer (); - va_start (argptr, format); - q_vsnprintf (va_buf, VA_BUFFERLEN, format, argptr); - va_end (argptr); + va_buf = get_va_buffer(); + va_start(argptr, format); + q_vsnprintf(va_buf, VA_BUFFERLEN, format, argptr); + va_end(argptr); - return va_buf; + return va_buf; } /* @@ -1541,53 +1425,47 @@ QUAKE FILESYSTEM ============================================================================= */ -int com_filesize; +int com_filesize; // // on-disk pakfile // -typedef struct -{ - char name[56]; - int filepos, filelen; +typedef struct { + char name[56]; + int filepos, filelen; } dpackfile_t; -typedef struct -{ - char id[4]; - int dirofs; - int dirlen; +typedef struct { + char id[4]; + int dirofs; + int dirlen; } dpackheader_t; #define MAX_FILES_IN_PACK 2048 -char com_gamedir[MAX_OSPATH]; -char com_basedir[MAX_OSPATH]; -int file_from_pak; // ZOID: global indicating that file came from a pak +char com_gamedir[MAX_OSPATH]; +char com_basedir[MAX_OSPATH]; +int file_from_pak; // ZOID: global indicating that file came from a pak -searchpath_t *com_searchpaths; -searchpath_t *com_base_searchpaths; +searchpath_t *com_searchpaths; +searchpath_t *com_base_searchpaths; /* ============ COM_Path_f ============ */ -static void COM_Path_f (void) -{ - searchpath_t *s; +static void COM_Path_f(void) { + searchpath_t *s; - Con_Printf ("Current search path:\n"); - for (s = com_searchpaths; s; s = s->next) - { - if (s->pack) - { - Con_Printf ("%s (%i files)\n", s->pack->filename, s->pack->numfiles); - } - else - Con_Printf ("%s\n", s->filename); - } + Con_Printf("Current search path:\n"); + for (s = com_searchpaths; s; s = s->next) { + if (s->pack) { + Con_Printf("%s (%i files)\n", s->pack->filename, s->pack->numfiles); + } else + Con_Printf("%s\n", s->filename); + } } /* @@ -1597,25 +1475,23 @@ COM_WriteFile The filename will be prefixed by the current game directory ============ */ -void COM_WriteFile (const char *filename, const void *data, int len) -{ - int handle; - char name[MAX_OSPATH]; +void COM_WriteFile(const char *filename, const void *data, int len) { + int handle; + char name[MAX_OSPATH]; - Sys_mkdir (com_gamedir); //johnfitz -- if we've switched to a nonexistant gamedir, create it now so we don't crash + Sys_mkdir(com_gamedir); //johnfitz -- if we've switched to a nonexistant gamedir, create it now so we don't crash - q_snprintf (name, sizeof(name), "%s/%s", com_gamedir, filename); + q_snprintf(name, sizeof(name), "%s/%s", com_gamedir, filename); - handle = Sys_FileOpenWrite (name); - if (handle == -1) - { - Sys_Printf ("COM_WriteFile: failed on %s\n", name); - return; - } + handle = Sys_FileOpenWrite(name); + if (handle == -1) { + Sys_Printf("COM_WriteFile: failed on %s\n", name); + return; + } - Sys_Printf ("COM_WriteFile: %s\n", name); - Sys_FileWrite (handle, data, len); - Sys_FileClose (handle); + Sys_Printf("COM_WriteFile: %s\n", name); + Sys_FileWrite(handle, data, len); + Sys_FileClose(handle); } /* @@ -1623,19 +1499,17 @@ void COM_WriteFile (const char *filename, const void *data, int len) COM_CreatePath ============ */ -void COM_CreatePath (char *path) -{ - char *ofs; +void COM_CreatePath(char *path) { + char *ofs; - for (ofs = path + 1; *ofs; ofs++) - { - if (*ofs == '/') - { // create the directory - *ofs = 0; - Sys_mkdir (path); - *ofs = '/'; - } - } + for (ofs = path + 1; *ofs; ofs++) { + if (*ofs == '/') { + // create the directory + *ofs = 0; + Sys_mkdir(path); + *ofs = '/'; + } + } } /* @@ -1643,16 +1517,15 @@ void COM_CreatePath (char *path) COM_filelength ================ */ -long COM_filelength (FILE *f) -{ - long pos, end; +long COM_filelength(FILE *f) { + long pos, end; - pos = ftell (f); - fseek (f, 0, SEEK_END); - end = ftell (f); - fseek (f, pos, SEEK_SET); + pos = ftell(f); + fseek(f, 0, SEEK_END); + end = ftell(f); + fseek(f, pos, SEEK_SET); - return end; + return end; } /* @@ -1665,102 +1538,90 @@ If neither of file or handle is set, this can be used for detecting a file's presence. =========== */ -static int COM_FindFile (const char *filename, int *handle, FILE **file, - unsigned int *path_id) -{ - searchpath_t *search; - char netpath[MAX_OSPATH]; - pack_t *pak; - int i; +static int COM_FindFile(const char *filename, int *handle, FILE **file, + unsigned int *path_id) { + searchpath_t *search; + char netpath[MAX_OSPATH]; + pack_t *pak; + int i; - if (file && handle) - Sys_Error ("COM_FindFile: both handle and file set"); + if (file && handle) + Sys_Error("COM_FindFile: both handle and file set"); - file_from_pak = 0; + file_from_pak = 0; -// -// search through the path, one element at a time -// - for (search = com_searchpaths; search; search = search->next) - { - if (search->pack) /* look through all the pak file elements */ - { - pak = search->pack; - for (i = 0; i < pak->numfiles; i++) - { - if (strcmp(pak->files[i].name, filename) != 0) - continue; - // found it! - com_filesize = pak->files[i].filelen; - file_from_pak = 1; - if (path_id) - *path_id = search->path_id; - if (handle) - { - *handle = pak->handle; - Sys_FileSeek (pak->handle, pak->files[i].filepos); - return com_filesize; - } - else if (file) - { /* open a new file on the pakfile */ - *file = fopen (pak->filename, "rb"); - if (*file) - fseek (*file, pak->files[i].filepos, SEEK_SET); - return com_filesize; - } - else /* for COM_FileExists() */ - { - return com_filesize; - } - } - } - else /* check a file in the directory tree */ - { - if (!registered.value) - { /* if not a registered version, don't ever go beyond base */ - if ( strchr (filename, '/') || strchr (filename,'\\')) - continue; - } + // + // search through the path, one element at a time + // + for (search = com_searchpaths; search; search = search->next) { + if (search->pack) /* look through all the pak file elements */ + { + pak = search->pack; + for (i = 0; i < pak->numfiles; i++) { + if (strcmp(pak->files[i].name, filename) != 0) + continue; + // found it! + com_filesize = pak->files[i].filelen; + file_from_pak = 1; + if (path_id) + *path_id = search->path_id; + if (handle) { + *handle = pak->handle; + Sys_FileSeek(pak->handle, pak->files[i].filepos); + return com_filesize; + } else if (file) { + /* open a new file on the pakfile */ + *file = fopen(pak->filename, "rb"); + if (*file) + fseek(*file, pak->files[i].filepos, SEEK_SET); + return com_filesize; + } else /* for COM_FileExists() */ + { + return com_filesize; + } + } + } else /* check a file in the directory tree */ + { + if (!registered.value) { + /* if not a registered version, don't ever go beyond base */ + if (strchr(filename, '/') || strchr(filename, '\\')) + continue; + } - q_snprintf (netpath, sizeof(netpath), "%s/%s",search->filename, filename); - if (! (Sys_FileType(netpath) & FS_ENT_FILE)) - continue; + q_snprintf(netpath, sizeof(netpath), "%s/%s", search->filename, filename); + if (!(Sys_FileType(netpath) & FS_ENT_FILE)) + continue; - if (path_id) - *path_id = search->path_id; - if (handle) - { - com_filesize = Sys_FileOpenRead (netpath, &i); - *handle = i; - return com_filesize; - } - else if (file) - { - *file = fopen (netpath, "rb"); - com_filesize = (*file == NULL) ? -1 : COM_filelength (*file); - return com_filesize; - } - else - { - return 0; /* dummy valid value for COM_FileExists() */ - } - } - } + if (path_id) + *path_id = search->path_id; + if (handle) { + com_filesize = Sys_FileOpenRead(netpath, &i); + *handle = i; + return com_filesize; + } else if (file) { + *file = fopen(netpath, "rb"); + com_filesize = (*file == NULL) ? -1 : COM_filelength(*file); + return com_filesize; + } else { + return 0; /* dummy valid value for COM_FileExists() */ + } + } + } - if (strcmp(COM_FileGetExtension(filename), "pcx") != 0 - && strcmp(COM_FileGetExtension(filename), "tga") != 0 - && strcmp(COM_FileGetExtension(filename), "lit") != 0 - && strcmp(COM_FileGetExtension(filename), "vis") != 0 - && strcmp(COM_FileGetExtension(filename), "ent") != 0) - Con_DPrintf ("FindFile: can't find %s\n", filename); - else Con_DPrintf2("FindFile: can't find %s\n", filename); + if (strcmp(COM_FileGetExtension(filename), "pcx") != 0 + && strcmp(COM_FileGetExtension(filename), "tga") != 0 + && strcmp(COM_FileGetExtension(filename), "lit") != 0 + && strcmp(COM_FileGetExtension(filename), "vis") != 0 + && strcmp(COM_FileGetExtension(filename), "ent") != 0) + Con_DPrintf("FindFile: can't find %s\n", filename); + else Con_DPrintf2("FindFile: can't find %s\n", filename); - if (handle) - *handle = -1; - if (file) - *file = NULL; - com_filesize = -1; - return com_filesize; + if (handle) + *handle = -1; + if (file) + *file = NULL; + com_filesize = -1; + return com_filesize; } @@ -1771,10 +1632,9 @@ COM_FileExists Returns whether the file is found in the quake filesystem. =========== */ -qboolean COM_FileExists (const char *filename, unsigned int *path_id) -{ - int ret = COM_FindFile (filename, NULL, NULL, path_id); - return (ret == -1) ? false : true; +qboolean COM_FileExists(const char *filename, unsigned int *path_id) { + int ret = COM_FindFile(filename, NULL, NULL, path_id); + return (ret == -1) ? false : true; } /* @@ -1786,9 +1646,8 @@ returns a handle and a length it may actually be inside a pak file =========== */ -int COM_OpenFile (const char *filename, int *handle, unsigned int *path_id) -{ - return COM_FindFile (filename, handle, NULL, path_id); +int COM_OpenFile(const char *filename, int *handle, unsigned int *path_id) { + return COM_FindFile(filename, handle, NULL, path_id); } /* @@ -1799,9 +1658,8 @@ If the requested file is inside a packfile, a new FILE * will be opened into the file. =========== */ -int COM_FOpenFile (const char *filename, FILE **file, unsigned int *path_id) -{ - return COM_FindFile (filename, NULL, file, path_id); +int COM_FOpenFile(const char *filename, FILE **file, unsigned int *path_id) { + return COM_FindFile(filename, NULL, file, path_id); } /* @@ -1811,15 +1669,14 @@ COM_CloseFile If it is a pak file handle, don't really close it ============ */ -void COM_CloseFile (int h) -{ - searchpath_t *s; +void COM_CloseFile(int h) { + searchpath_t *s; - for (s = com_searchpaths; s; s = s->next) - if (s->pack && s->pack->handle == h) - return; + for (s = com_searchpaths; s; s = s->next) + if (s->pack && s->pack->handle == h) + return; - Sys_FileClose (h); + Sys_FileClose(h); } @@ -1838,170 +1695,148 @@ Allways appends a 0 byte. #define LOADFILE_STACK 4 #define LOADFILE_MALLOC 5 -static byte *loadbuf; +static byte *loadbuf; static cache_user_t *loadcache; -static int loadsize; +static int loadsize; -byte *COM_LoadFile (const char *path, int usehunk, unsigned int *path_id) -{ - int h; - byte *buf; - char base[32]; - int len, nread; +byte *COM_LoadFile(const char *path, int usehunk, unsigned int *path_id) { + int h; + byte *buf; + char base[32]; + int len, nread; - buf = NULL; // quiet compiler warning + buf = NULL; // quiet compiler warning -// look for it in the filesystem or pack files - len = COM_OpenFile (path, &h, path_id); - if (h == -1) - return NULL; + // look for it in the filesystem or pack files + len = COM_OpenFile(path, &h, path_id); + if (h == -1) + return NULL; -// extract the filename base name for hunk tag - COM_FileBase (path, base, sizeof(base)); + // extract the filename base name for hunk tag + COM_FileBase(path, base, sizeof(base)); - switch (usehunk) - { - case LOADFILE_HUNK: - buf = (byte *) Hunk_AllocName (len+1, base); - break; - case LOADFILE_TEMPHUNK: - buf = (byte *) Hunk_TempAlloc (len+1); - break; - case LOADFILE_ZONE: - buf = (byte *) Z_Malloc (len+1); - break; - case LOADFILE_CACHE: - buf = (byte *) Cache_Alloc (loadcache, len+1, base); - break; - case LOADFILE_STACK: - if (len < loadsize) - buf = loadbuf; - else - buf = (byte *) Hunk_TempAlloc (len+1); - break; - case LOADFILE_MALLOC: - buf = (byte *) malloc (len+1); - break; - default: - Sys_Error ("COM_LoadFile: bad usehunk"); - } + switch (usehunk) { + case LOADFILE_HUNK: + buf = (byte *) Hunk_AllocName(len + 1, base); + break; + case LOADFILE_TEMPHUNK: + buf = (byte *) Hunk_TempAlloc(len + 1); + break; + case LOADFILE_ZONE: + buf = (byte *) Z_Malloc(len + 1); + break; + case LOADFILE_CACHE: + buf = (byte *) Cache_Alloc(loadcache, len + 1, base); + break; + case LOADFILE_STACK: + if (len < loadsize) + buf = loadbuf; + else + buf = (byte *) Hunk_TempAlloc(len + 1); + break; + case LOADFILE_MALLOC: + buf = (byte *) malloc(len + 1); + break; + default: + Sys_Error("COM_LoadFile: bad usehunk"); + } - if (!buf) - Sys_Error ("COM_LoadFile: not enough space for %s", path); + if (!buf) + Sys_Error("COM_LoadFile: not enough space for %s", path); - ((byte *)buf)[len] = 0; + ((byte *) buf)[len] = 0; - nread = Sys_FileRead (h, buf, len); - COM_CloseFile (h); - if (nread != len) - Sys_Error ("COM_LoadFile: Error reading %s", path); + nread = Sys_FileRead(h, buf, len); + COM_CloseFile(h); + if (nread != len) + Sys_Error("COM_LoadFile: Error reading %s", path); - return buf; + return buf; } -byte *COM_LoadHunkFile (const char *path, unsigned int *path_id) -{ - return COM_LoadFile (path, LOADFILE_HUNK, path_id); +byte *COM_LoadHunkFile(const char *path, unsigned int *path_id) { + return COM_LoadFile(path, LOADFILE_HUNK, path_id); } -byte *COM_LoadZoneFile (const char *path, unsigned int *path_id) -{ - return COM_LoadFile (path, LOADFILE_ZONE, path_id); +byte *COM_LoadZoneFile(const char *path, unsigned int *path_id) { + return COM_LoadFile(path, LOADFILE_ZONE, path_id); } -byte *COM_LoadTempFile (const char *path, unsigned int *path_id) -{ - return COM_LoadFile (path, LOADFILE_TEMPHUNK, path_id); +byte *COM_LoadTempFile(const char *path, unsigned int *path_id) { + return COM_LoadFile(path, LOADFILE_TEMPHUNK, path_id); } -void COM_LoadCacheFile (const char *path, struct cache_user_s *cu, unsigned int *path_id) -{ - loadcache = cu; - COM_LoadFile (path, LOADFILE_CACHE, path_id); +void COM_LoadCacheFile(const char *path, struct cache_user_s *cu, unsigned int *path_id) { + loadcache = cu; + COM_LoadFile(path, LOADFILE_CACHE, path_id); } // uses temp hunk if larger than bufsize -byte *COM_LoadStackFile (const char *path, void *buffer, int bufsize, unsigned int *path_id) -{ - byte *buf; +byte *COM_LoadStackFile(const char *path, void *buffer, int bufsize, unsigned int *path_id) { + byte *buf; - loadbuf = (byte *)buffer; - loadsize = bufsize; - buf = COM_LoadFile (path, LOADFILE_STACK, path_id); + loadbuf = (byte *) buffer; + loadsize = bufsize; + buf = COM_LoadFile(path, LOADFILE_STACK, path_id); - return buf; + return buf; } // returns malloc'd memory -byte *COM_LoadMallocFile (const char *path, unsigned int *path_id) -{ - return COM_LoadFile (path, LOADFILE_MALLOC, path_id); +byte *COM_LoadMallocFile(const char *path, unsigned int *path_id) { + return COM_LoadFile(path, LOADFILE_MALLOC, path_id); } -byte *COM_LoadMallocFile_TextMode_OSPath (const char *path, long *len_out) -{ - FILE *f; - byte *data; - long len, actuallen; +byte *COM_LoadMallocFile_TextMode_OSPath(const char *path, long *len_out) { + FILE *f; + byte *data; + long len, actuallen; - // ericw -- this is used by Host_Loadgame_f. Translate CRLF to LF on load games, - // othewise multiline messages have a garbage character at the end of each line. - // TODO: could handle in a way that allows loading CRLF savegames on mac/linux - // without the junk characters appearing. - f = fopen (path, "rt"); - if (f == NULL) - return NULL; + // ericw -- this is used by Host_Loadgame_f. Translate CRLF to LF on load games, + // othewise multiline messages have a garbage character at the end of each line. + // TODO: could handle in a way that allows loading CRLF savegames on mac/linux + // without the junk characters appearing. + f = fopen(path, "rt"); + if (f == NULL) + return NULL; - len = COM_filelength (f); - if (len < 0) - { - fclose (f); - return NULL; - } + len = COM_filelength(f); + if (len < 0) { + fclose(f); + return NULL; + } - data = (byte *) malloc (len + 1); - if (data == NULL) - { - fclose (f); - return NULL; - } + data = (byte *) malloc(len + 1); + if (data == NULL) { + fclose(f); + return NULL; + } - // (actuallen < len) if CRLF to LF translation was performed - actuallen = fread (data, 1, len, f); - if (ferror(f)) - { - fclose (f); - free (data); - return NULL; - } - data[actuallen] = '\0'; + // (actuallen < len) if CRLF to LF translation was performed + actuallen = fread(data, 1, len, f); + if (ferror(f)) { + fclose(f); + free(data); + return NULL; + } + data[actuallen] = '\0'; - if (len_out != NULL) - *len_out = actuallen; - fclose (f); - return data; + if (len_out != NULL) + *len_out = actuallen; + fclose(f); + return data; } -const char *COM_ParseIntNewline(const char *buffer, int *value) -{ - int consumed = 0; - sscanf (buffer, "%i\n%n", value, &consumed); - return buffer + consumed; +const char *COM_ParseIntNewline(const char *buffer, int *value) { + int consumed = 0; + sscanf(buffer, "%i\n%n", value, &consumed); + return buffer + consumed; } -const char *COM_ParseFloatNewline(const char *buffer, float *value) -{ - int consumed = 0; - sscanf (buffer, "%f\n%n", value, &consumed); - return buffer + consumed; -} - -const char *COM_ParseStringNewline(const char *buffer) -{ - int consumed = 0; - com_token[0] = '\0'; - sscanf (buffer, "%1023s\n%n", com_token, &consumed); - return buffer + consumed; +const char *COM_ParseFloatNewline(const char *buffer, float *value) { + int consumed = 0; + sscanf(buffer, "%f\n%n", value, &consumed); + return buffer + consumed; } /* @@ -2014,75 +1849,71 @@ Loads the header and directory, adding the files at the beginning of the list so they override previous pack files. ================= */ -static pack_t *COM_LoadPackFile (const char *packfile) -{ - dpackheader_t header; - int i; - packfile_t *newfiles; - int numpackfiles; - pack_t *pack; - int packhandle; - dpackfile_t info[MAX_FILES_IN_PACK]; - unsigned short crc; +static pack_t *COM_LoadPackFile(const char *packfile) { + dpackheader_t header; + int i; + packfile_t *newfiles; + int numpackfiles; + pack_t *pack; + int packhandle; + dpackfile_t info[MAX_FILES_IN_PACK]; + unsigned short crc; - if (Sys_FileOpenRead (packfile, &packhandle) == -1) - return NULL; + if (Sys_FileOpenRead(packfile, &packhandle) == -1) + return NULL; - if (Sys_FileRead(packhandle, &header, sizeof(header)) != (int) sizeof(header) || - header.id[0] != 'P' || header.id[1] != 'A' || header.id[2] != 'C' || header.id[3] != 'K') - Sys_Error ("%s is not a packfile", packfile); + if (Sys_FileRead(packhandle, &header, sizeof(header)) != (int) sizeof(header) || + header.id[0] != 'P' || header.id[1] != 'A' || header.id[2] != 'C' || header.id[3] != 'K') + Sys_Error("%s is not a packfile", packfile); - header.dirofs = LittleLong (header.dirofs); - header.dirlen = LittleLong (header.dirlen); + header.dirofs = LittleLong(header.dirofs); + header.dirlen = LittleLong(header.dirlen); - numpackfiles = header.dirlen / sizeof(dpackfile_t); + numpackfiles = header.dirlen / sizeof(dpackfile_t); - if (header.dirlen < 0 || header.dirofs < 0) - { - Sys_Error ("Invalid packfile %s (dirlen: %i, dirofs: %i)", - packfile, header.dirlen, header.dirofs); - } - if (!numpackfiles) - { - Sys_Printf ("WARNING: %s has no files, ignored\n", packfile); - Sys_FileClose (packhandle); - return NULL; - } - if (numpackfiles > MAX_FILES_IN_PACK) - Sys_Error ("%s has %i files", packfile, numpackfiles); + if (header.dirlen < 0 || header.dirofs < 0) { + Sys_Error("Invalid packfile %s (dirlen: %i, dirofs: %i)", + packfile, header.dirlen, header.dirofs); + } + if (!numpackfiles) { + Sys_Printf("WARNING: %s has no files, ignored\n", packfile); + Sys_FileClose(packhandle); + return NULL; + } + if (numpackfiles > MAX_FILES_IN_PACK) + Sys_Error("%s has %i files", packfile, numpackfiles); - if (numpackfiles != PAK0_COUNT) - com_modified = true; // not the original file + if (numpackfiles != PAK0_COUNT) + com_modified = true; // not the original file - newfiles = (packfile_t *) Z_Malloc(numpackfiles * sizeof(packfile_t)); + newfiles = (packfile_t *) Z_Malloc(numpackfiles * sizeof(packfile_t)); - Sys_FileSeek (packhandle, header.dirofs); - if (Sys_FileRead(packhandle, info, header.dirlen) != header.dirlen) - Sys_Error ("Error reading %s", packfile); + Sys_FileSeek(packhandle, header.dirofs); + if (Sys_FileRead(packhandle, info, header.dirlen) != header.dirlen) + Sys_Error("Error reading %s", packfile); - // crc the directory to check for modifications - CRC_Init (&crc); - for (i = 0; i < header.dirlen; i++) - CRC_ProcessByte (&crc, ((byte *)info)[i]); - if (crc != PAK0_CRC_V106 && crc != PAK0_CRC_V101 && crc != PAK0_CRC_V100) - com_modified = true; + // crc the directory to check for modifications + CRC_Init(&crc); + for (i = 0; i < header.dirlen; i++) + CRC_ProcessByte(&crc, ((byte *) info)[i]); + if (crc != PAK0_CRC_V106 && crc != PAK0_CRC_V101 && crc != PAK0_CRC_V100) + com_modified = true; - // parse the directory - for (i = 0; i < numpackfiles; i++) - { - q_strlcpy (newfiles[i].name, info[i].name, sizeof(newfiles[i].name)); - newfiles[i].filepos = LittleLong(info[i].filepos); - newfiles[i].filelen = LittleLong(info[i].filelen); - } + // parse the directory + for (i = 0; i < numpackfiles; i++) { + q_strlcpy(newfiles[i].name, info[i].name, sizeof(newfiles[i].name)); + newfiles[i].filepos = LittleLong(info[i].filepos); + newfiles[i].filelen = LittleLong(info[i].filelen); + } - pack = (pack_t *) Z_Malloc (sizeof (pack_t)); - q_strlcpy (pack->filename, packfile, sizeof(pack->filename)); - pack->handle = packhandle; - pack->numfiles = numpackfiles; - pack->files = newfiles; + pack = (pack_t *) Z_Malloc(sizeof(pack_t)); + q_strlcpy(pack->filename, packfile, sizeof(pack->filename)); + pack->handle = packhandle; + pack->numfiles = numpackfiles; + pack->files = newfiles; - //Sys_Printf ("Added packfile %s (%i files)\n", packfile, numpackfiles); - return pack; + //Sys_Printf ("Added packfile %s (%i files)\n", packfile, numpackfiles); + return pack; } /* @@ -2090,215 +1921,199 @@ static pack_t *COM_LoadPackFile (const char *packfile) COM_AddGameDirectory -- johnfitz -- modified based on topaz's tutorial ================= */ -static void COM_AddGameDirectory (const char *base, const char *dir) -{ - int i; - unsigned int path_id; - searchpath_t *search; - pack_t *pak, *qspak; - char pakfile[MAX_OSPATH]; - qboolean been_here = false; +static void COM_AddGameDirectory(const char *base, const char *dir) { + int i; + unsigned int path_id; + searchpath_t *search; + pack_t *pak, *qspak; + char pakfile[MAX_OSPATH]; + qboolean been_here = false; - q_strlcpy (com_gamedir, va("%s/%s", base, dir), sizeof(com_gamedir)); + q_strlcpy(com_gamedir, va("%s/%s", base, dir), sizeof(com_gamedir)); - // assign a path_id to this game directory - if (com_searchpaths) - path_id = com_searchpaths->path_id << 1; - else path_id = 1U; + // assign a path_id to this game directory + if (com_searchpaths) + path_id = com_searchpaths->path_id << 1; + else path_id = 1U; _add_path: - // add the directory to the search path - search = (searchpath_t *) Z_Malloc(sizeof(searchpath_t)); - search->path_id = path_id; - q_strlcpy (search->filename, com_gamedir, sizeof(search->filename)); - search->next = com_searchpaths; - com_searchpaths = search; + // add the directory to the search path + search = (searchpath_t *) Z_Malloc(sizeof(searchpath_t)); + search->path_id = path_id; + q_strlcpy(search->filename, com_gamedir, sizeof(search->filename)); + search->next = com_searchpaths; + com_searchpaths = search; - // add any pak files in the format pak0.pak pak1.pak, ... - for (i = 0; ; i++) - { - q_snprintf (pakfile, sizeof(pakfile), "%s/pak%i.pak", com_gamedir, i); - pak = COM_LoadPackFile (pakfile); - if (i != 0 || path_id != 1 || fitzmode) - qspak = NULL; - else { - qboolean old = com_modified; - if (been_here) base = host_parms->userdir; - q_snprintf (pakfile, sizeof(pakfile), "%s/quakespasm.pak", base); - qspak = COM_LoadPackFile (pakfile); - com_modified = old; - } - if (pak) { - search = (searchpath_t *) Z_Malloc(sizeof(searchpath_t)); - search->path_id = path_id; - search->pack = pak; - search->next = com_searchpaths; - com_searchpaths = search; - } - if (qspak) { - search = (searchpath_t *) Z_Malloc(sizeof(searchpath_t)); - search->path_id = path_id; - search->pack = qspak; - search->next = com_searchpaths; - com_searchpaths = search; - } - if (!pak) break; - } + // add any pak files in the format pak0.pak pak1.pak, ... + for (i = 0; ; i++) { + q_snprintf(pakfile, sizeof(pakfile), "%s/pak%i.pak", com_gamedir, i); + pak = COM_LoadPackFile(pakfile); + if (i != 0 || path_id != 1 || fitzmode) + qspak = NULL; + else { + qboolean old = com_modified; + if (been_here) base = host_parms->userdir; + q_snprintf(pakfile, sizeof(pakfile), "%s/quakespasm.pak", base); + qspak = COM_LoadPackFile(pakfile); + com_modified = old; + } + if (pak) { + search = (searchpath_t *) Z_Malloc(sizeof(searchpath_t)); + search->path_id = path_id; + search->pack = pak; + search->next = com_searchpaths; + com_searchpaths = search; + } + if (qspak) { + search = (searchpath_t *) Z_Malloc(sizeof(searchpath_t)); + search->path_id = path_id; + search->pack = qspak; + search->next = com_searchpaths; + com_searchpaths = search; + } + if (!pak) break; + } - if (!been_here && host_parms->userdir != host_parms->basedir) - { - been_here = true; - q_strlcpy(com_gamedir, va("%s/%s", host_parms->userdir, dir), sizeof(com_gamedir)); - Sys_mkdir(com_gamedir); - goto _add_path; - } + if (!been_here && host_parms->userdir != host_parms->basedir) { + been_here = true; + q_strlcpy(com_gamedir, va("%s/%s", host_parms->userdir, dir), sizeof(com_gamedir)); + Sys_mkdir(com_gamedir); + goto _add_path; + } } //============================================================================== //johnfitz -- dynamic gamedir stuff -- modified by QuakeSpasm team. //============================================================================== -static void COM_Game_f (void) -{ - if (Cmd_Argc() > 1) - { - const char *p = Cmd_Argv(1); - const char *p2 = Cmd_Argv(2); - searchpath_t *search; +static void COM_Game_f(void) { + if (command::argc() > 1) { + const char *p = command::argv(1)->c_str(); + const char *p2 = command::argv(2)->c_str(); + searchpath_t *search; - if (!registered.value) //disable shareware quake - { - Con_Printf("You must have the registered version to use modified games\n"); - return; - } + if (!registered.value) //disable shareware quake + { + Con_Printf("You must have the registered version to use modified games\n"); + return; + } - if (!*p || !strcmp(p, ".") || strstr(p, "..") || strstr(p, "/") || strstr(p, "\\") || strstr(p, ":")) - { - Con_Printf ("gamedir should be a single directory name, not a path\n"); - return; - } + if (!*p || !strcmp(p, ".") || strstr(p, "..") || strstr(p, "/") || strstr(p, "\\") || strstr(p, ":")) { + Con_Printf("gamedir should be a single directory name, not a path\n"); + return; + } - if (*p2) - { - if (strcmp(p2,"-hipnotic") && strcmp(p2,"-rogue") && strcmp(p2,"-quoth")) { - Con_Printf ("invalid mission pack argument to \"game\"\n"); - return; - } - if (!q_strcasecmp(p, GAMENAME)) { - Con_Printf ("no mission pack arguments to %s game\n", GAMENAME); - return; - } - } + if (*p2) { + if (strcmp(p2, "-hipnotic") && strcmp(p2, "-rogue") && strcmp(p2, "-quoth")) { + Con_Printf("invalid mission pack argument to \"game\"\n"); + return; + } + if (!q_strcasecmp(p, GAMENAME)) { + Con_Printf("no mission pack arguments to %s game\n", GAMENAME); + return; + } + } - if (Sys_FileType(va("%s/%s", com_basedir, p)) != FS_ENT_DIRECTORY) - { - if (host_parms->userdir == host_parms->basedir || (Sys_FileType(va("%s/%s", host_parms->userdir, p)) != FS_ENT_DIRECTORY)) - { - Con_Printf ("No such game directory \"%s\"\n", p); - return; - } - } + if (Sys_FileType(va("%s/%s", com_basedir, p)) != FS_ENT_DIRECTORY) { + if (host_parms->userdir == host_parms->basedir || ( + Sys_FileType(va("%s/%s", host_parms->userdir, p)) != FS_ENT_DIRECTORY)) { + Con_Printf("No such game directory \"%s\"\n", p); + return; + } + } - if (!q_strcasecmp(p, COM_SkipPath(com_gamedir))) //no change - { - if (com_searchpaths->path_id > 1) { //current game not id1 - if (*p2 && com_searchpaths->path_id == 2) { - // rely on QuakeSpasm extension treating '-game missionpack' - // as '-missionpack', otherwise would be a mess - if (!q_strcasecmp(p, &p2[1])) - goto _same; - Con_Printf("reloading game \"%s\" with \"%s\" support\n", p, &p2[1]); - } - else if (!*p2 && com_searchpaths->path_id > 2) - Con_Printf("reloading game \"%s\" without mission pack support\n", p); - else goto _same; - } - else { _same: - Con_Printf("\"game\" is already \"%s\"\n", COM_SkipPath(com_gamedir)); - return; - } - } + if (!q_strcasecmp(p, COM_SkipPath(com_gamedir))) //no change + { + if (com_searchpaths->path_id > 1) { + //current game not id1 + if (*p2 && com_searchpaths->path_id == 2) { + // rely on QuakeSpasm extension treating '-game missionpack' + // as '-missionpack', otherwise would be a mess + if (!q_strcasecmp(p, &p2[1])) + goto _same; + Con_Printf("reloading game \"%s\" with \"%s\" support\n", p, &p2[1]); + } else if (!*p2 && com_searchpaths->path_id > 2) + Con_Printf("reloading game \"%s\" without mission pack support\n", p); + else goto _same; + } else { + _same: + Con_Printf("\"game\" is already \"%s\"\n", COM_SkipPath(com_gamedir)); + return; + } + } - com_modified = true; + com_modified = true; - //Kill the server - CL_Disconnect (); - Host_ShutdownServer(true); + //Kill the server + CL_Disconnect(); + Host_ShutdownServer(true); - //Write config file - Host_WriteConfiguration (); + //Write config file + Host_WriteConfiguration(); - //Kill the extra game if it is loaded - while (com_searchpaths != com_base_searchpaths) - { - if (com_searchpaths->pack) - { - Sys_FileClose (com_searchpaths->pack->handle); - Z_Free (com_searchpaths->pack->files); - Z_Free (com_searchpaths->pack); - } - search = com_searchpaths->next; - Z_Free (com_searchpaths); - com_searchpaths = search; - } - hipnotic = false; - rogue = false; - standard_quake = true; + //Kill the extra game if it is loaded + while (com_searchpaths != com_base_searchpaths) { + if (com_searchpaths->pack) { + Sys_FileClose(com_searchpaths->pack->handle); + Z_Free(com_searchpaths->pack->files); + Z_Free(com_searchpaths->pack); + } + search = com_searchpaths->next; + Z_Free(com_searchpaths); + com_searchpaths = search; + } + hipnotic = false; + rogue = false; + standard_quake = true; - if (q_strcasecmp(p, GAMENAME)) //game is not id1 - { - if (*p2) { - COM_AddGameDirectory (com_basedir, &p2[1]); - standard_quake = false; - if (!strcmp(p2,"-hipnotic") || !strcmp(p2,"-quoth")) - hipnotic = true; - else if (!strcmp(p2,"-rogue")) - rogue = true; - if (q_strcasecmp(p, &p2[1])) //don't load twice - COM_AddGameDirectory (com_basedir, p); - } - else { - COM_AddGameDirectory (com_basedir, p); - // QuakeSpasm extension: treat '-game missionpack' as '-missionpack' - if (!q_strcasecmp(p,"hipnotic") || !q_strcasecmp(p,"quoth")) { - hipnotic = true; - standard_quake = false; - } - else if (!q_strcasecmp(p,"rogue")) { - rogue = true; - standard_quake = false; - } - } - } - else // just update com_gamedir - { - q_snprintf (com_gamedir, sizeof(com_gamedir), "%s/%s", - (host_parms->userdir != host_parms->basedir)? - host_parms->userdir : com_basedir, - GAMENAME); - } + if (q_strcasecmp(p, GAMENAME)) //game is not id1 + { + if (*p2) { + COM_AddGameDirectory(com_basedir, &p2[1]); + standard_quake = false; + if (!strcmp(p2, "-hipnotic") || !strcmp(p2, "-quoth")) + hipnotic = true; + else if (!strcmp(p2, "-rogue")) + rogue = true; + if (q_strcasecmp(p, &p2[1])) //don't load twice + COM_AddGameDirectory(com_basedir, p); + } else { + COM_AddGameDirectory(com_basedir, p); + // QuakeSpasm extension: treat '-game missionpack' as '-missionpack' + if (!q_strcasecmp(p, "hipnotic") || !q_strcasecmp(p, "quoth")) { + hipnotic = true; + standard_quake = false; + } else if (!q_strcasecmp(p, "rogue")) { + rogue = true; + standard_quake = false; + } + } + } else // just update com_gamedir + { + q_snprintf(com_gamedir, sizeof(com_gamedir), "%s/%s", + (host_parms->userdir != host_parms->basedir) ? host_parms->userdir : com_basedir, + GAMENAME); + } - //clear out and reload appropriate data - Cache_Flush (); - Mod_ResetAll(); - Sky_ClearAll(); - if (!isDedicated) - { - TexMgr_NewGame (); - Draw_NewGame (); - R_NewGame (); - } - ExtraMaps_NewGame (); - Host_Resetdemos (); - DemoList_Rebuild (); + //clear out and reload appropriate data + Cache_Flush(); + Mod_ResetAll(); + Sky_ClearAll(); + if (!isDedicated) { + TexMgr_NewGame(); + Draw_NewGame(); + R_NewGame(); + } + ExtraMaps_NewGame(); + Host_Resetdemos(); + DemoList_Rebuild(); - Con_Printf("\"game\" changed to \"%s\"\n", COM_SkipPath(com_gamedir)); + Con_Printf("\"game\" changed to \"%s\"\n", COM_SkipPath(com_gamedir)); - VID_Lock (); - Cbuf_AddText ("exec quake.rc\n"); - Cbuf_AddText ("vid_unlock\n"); - } - else //Diplay the current gamedir - Con_Printf("\"game\" is \"%s\"\n", COM_SkipPath(com_gamedir)); + VID_Lock(); + Cbuf_AddText("exec quake.rc\n"); + Cbuf_AddText("vid_unlock\n"); + } else //Diplay the current gamedir + Con_Printf("\"game\" is \"%s\"\n", COM_SkipPath(com_gamedir)); } /* @@ -2306,69 +2121,68 @@ static void COM_Game_f (void) COM_InitFilesystem ================= */ -void COM_InitFilesystem (void) //johnfitz -- modified based on topaz's tutorial +void COM_InitFilesystem(void) //johnfitz -- modified based on topaz's tutorial { - int i, j; + int i, j; - Cvar_RegisterVariable (®istered); - Cvar_RegisterVariable (&cmdline); - Cmd_AddCommand ("path", COM_Path_f); - Cmd_AddCommand ("game", COM_Game_f); //johnfitz + registered.inscribe(); + cmdline.inscribe(); + command::add("path", COM_Path_f); + command::add("game", COM_Game_f); //johnfitz - i = COM_CheckParm ("-basedir"); - if (i && i < com_argc-1) - q_strlcpy (com_basedir, com_argv[i + 1], sizeof(com_basedir)); - else - q_strlcpy (com_basedir, host_parms->basedir, sizeof(com_basedir)); + i = COM_CheckParm("-basedir"); + if (i && i < com_argc - 1) + q_strlcpy(com_basedir, com_argv[i + 1], sizeof(com_basedir)); + else + q_strlcpy(com_basedir, host_parms->basedir, sizeof(com_basedir)); - j = strlen (com_basedir); - if (j < 1) Sys_Error("Bad argument to -basedir"); - if ((com_basedir[j-1] == '\\') || (com_basedir[j-1] == '/')) - com_basedir[j-1] = 0; + j = strlen(com_basedir); + if (j < 1) Sys_Error("Bad argument to -basedir"); + if ((com_basedir[j - 1] == '\\') || (com_basedir[j - 1] == '/')) + com_basedir[j - 1] = 0; - // start up with GAMENAME by default (id1) - COM_AddGameDirectory (com_basedir, GAMENAME); + // start up with GAMENAME by default (id1) + COM_AddGameDirectory(com_basedir, GAMENAME); - /* this is the end of our base searchpath: - * any set gamedirs, such as those from -game command line - * arguments or by the 'game' console command will be freed - * up to here upon a new game command. */ - com_base_searchpaths = com_searchpaths; + /* this is the end of our base searchpath: + * any set gamedirs, such as those from -game command line + * arguments or by the 'game' console command will be freed + * up to here upon a new game command. */ + com_base_searchpaths = com_searchpaths; - // add mission pack requests (only one should be specified) - if (COM_CheckParm ("-rogue")) - COM_AddGameDirectory (com_basedir, "rogue"); - if (COM_CheckParm ("-hipnotic")) - COM_AddGameDirectory (com_basedir, "hipnotic"); - if (COM_CheckParm ("-quoth")) - COM_AddGameDirectory (com_basedir, "quoth"); + // add mission pack requests (only one should be specified) + if (COM_CheckParm("-rogue")) + COM_AddGameDirectory(com_basedir, "rogue"); + if (COM_CheckParm("-hipnotic")) + COM_AddGameDirectory(com_basedir, "hipnotic"); + if (COM_CheckParm("-quoth")) + COM_AddGameDirectory(com_basedir, "quoth"); - i = COM_CheckParm ("-game"); - if (i && i < com_argc-1) - { - const char *p = com_argv[i + 1]; - if (!*p || !strcmp(p, ".") || strstr(p, "..") || strstr(p, "/") || strstr(p, "\\") || strstr(p, ":")) - Sys_Error ("gamedir should be a single directory name, not a path\n"); - com_modified = true; - // don't load mission packs twice - if (COM_CheckParm ("-rogue") && !q_strcasecmp(p, "rogue")) p = NULL; - if (p && COM_CheckParm ("-hipnotic") && !q_strcasecmp(p, "hipnotic")) p = NULL; - if (p && COM_CheckParm ("-quoth") && !q_strcasecmp(p, "quoth")) p = NULL; - if (p != NULL) { - COM_AddGameDirectory (com_basedir, p); - // QuakeSpasm extension: treat '-game missionpack' as '-missionpack' - if (!q_strcasecmp(p,"rogue")) { - rogue = true; - standard_quake = false; - } - if (!q_strcasecmp(p,"hipnotic") || !q_strcasecmp(p,"quoth")) { - hipnotic = true; - standard_quake = false; - } - } - } + i = COM_CheckParm("-game"); + if (i && i < com_argc - 1) { + const char *p = com_argv[i + 1]; + if (!*p || !strcmp(p, ".") || strstr(p, "..") || strstr(p, "/") || strstr(p, "\\") || strstr(p, ":")) + Sys_Error("gamedir should be a single directory name, not a path\n"); + com_modified = true; + // don't load mission packs twice + if (COM_CheckParm("-rogue") && !q_strcasecmp(p, "rogue")) p = NULL; + if (p && COM_CheckParm("-hipnotic") && !q_strcasecmp(p, "hipnotic")) p = NULL; + if (p && COM_CheckParm("-quoth") && !q_strcasecmp(p, "quoth")) p = NULL; + if (p != NULL) { + COM_AddGameDirectory(com_basedir, p); + // QuakeSpasm extension: treat '-game missionpack' as '-missionpack' + if (!q_strcasecmp(p, "rogue")) { + rogue = true; + standard_quake = false; + } + if (!q_strcasecmp(p, "hipnotic") || !q_strcasecmp(p, "quoth")) { + hipnotic = true; + standard_quake = false; + } + } + } - COM_CheckRegistered (); + COM_CheckRegistered(); } @@ -2378,167 +2192,157 @@ void COM_InitFilesystem (void) //johnfitz -- modified based on topaz's tutorial * Allocating and filling in the fshandle_t structure is the users' * responsibility when the file is initially opened. */ -size_t FS_fread(void *ptr, size_t size, size_t nmemb, fshandle_t *fh) -{ - long byte_size; - long bytes_read; - size_t nmemb_read; +size_t FS_fread(void *ptr, size_t size, size_t nmemb, fshandle_t *fh) { + long byte_size; + long bytes_read; + size_t nmemb_read; - if (!fh) { - errno = EBADF; - return 0; - } - if (!ptr) { - errno = EFAULT; - return 0; - } - if (!size || !nmemb) { /* no error, just zero bytes wanted */ - errno = 0; - return 0; - } + if (!fh) { + errno = EBADF; + return 0; + } + if (!ptr) { + errno = EFAULT; + return 0; + } + if (!size || !nmemb) { + /* no error, just zero bytes wanted */ + errno = 0; + return 0; + } - byte_size = nmemb * size; - if (byte_size > fh->length - fh->pos) /* just read to end */ - byte_size = fh->length - fh->pos; - bytes_read = fread(ptr, 1, byte_size, fh->file); - fh->pos += bytes_read; + byte_size = nmemb * size; + if (byte_size > fh->length - fh->pos) /* just read to end */ + byte_size = fh->length - fh->pos; + bytes_read = fread(ptr, 1, byte_size, fh->file); + fh->pos += bytes_read; - /* fread() must return the number of elements read, - * not the total number of bytes. */ - nmemb_read = bytes_read / size; - /* even if the last member is only read partially - * it is counted as a whole in the return value. */ - if (bytes_read % size) - nmemb_read++; + /* fread() must return the number of elements read, + * not the total number of bytes. */ + nmemb_read = bytes_read / size; + /* even if the last member is only read partially + * it is counted as a whole in the return value. */ + if (bytes_read % size) + nmemb_read++; - return nmemb_read; + return nmemb_read; } -int FS_fseek(fshandle_t *fh, long offset, int whence) -{ -/* I don't care about 64 bit off_t or fseeko() here. - * the quake/hexen2 file system is 32 bits, anyway. */ - int ret; +int FS_fseek(fshandle_t *fh, long offset, int whence) { + /* I don't care about 64 bit off_t or fseeko() here. + * the quake/hexen2 file system is 32 bits, anyway. */ + int ret; - if (!fh) { - errno = EBADF; - return -1; - } + if (!fh) { + errno = EBADF; + return -1; + } - /* the relative file position shouldn't be smaller - * than zero or bigger than the filesize. */ - switch (whence) - { - case SEEK_SET: - break; - case SEEK_CUR: - offset += fh->pos; - break; - case SEEK_END: - offset = fh->length + offset; - break; - default: - errno = EINVAL; - return -1; - } + /* the relative file position shouldn't be smaller + * than zero or bigger than the filesize. */ + switch (whence) { + case SEEK_SET: + break; + case SEEK_CUR: + offset += fh->pos; + break; + case SEEK_END: + offset = fh->length + offset; + break; + default: + errno = EINVAL; + return -1; + } - if (offset < 0) { - errno = EINVAL; - return -1; - } + if (offset < 0) { + errno = EINVAL; + return -1; + } - if (offset > fh->length) /* just seek to end */ - offset = fh->length; + if (offset > fh->length) /* just seek to end */ + offset = fh->length; - ret = fseek(fh->file, fh->start + offset, SEEK_SET); - if (ret < 0) - return ret; + ret = fseek(fh->file, fh->start + offset, SEEK_SET); + if (ret < 0) + return ret; - fh->pos = offset; - return 0; + fh->pos = offset; + return 0; } -int FS_fclose(fshandle_t *fh) -{ - if (!fh) { - errno = EBADF; - return -1; - } - return fclose(fh->file); +int FS_fclose(fshandle_t *fh) { + if (!fh) { + errno = EBADF; + return -1; + } + return fclose(fh->file); } -long FS_ftell(fshandle_t *fh) -{ - if (!fh) { - errno = EBADF; - return -1; - } - return fh->pos; +long FS_ftell(fshandle_t *fh) { + if (!fh) { + errno = EBADF; + return -1; + } + return fh->pos; } -void FS_rewind(fshandle_t *fh) -{ - if (!fh) return; - clearerr(fh->file); - fseek(fh->file, fh->start, SEEK_SET); - fh->pos = 0; +void FS_rewind(fshandle_t *fh) { + if (!fh) return; + clearerr(fh->file); + fseek(fh->file, fh->start, SEEK_SET); + fh->pos = 0; } -int FS_feof(fshandle_t *fh) -{ - if (!fh) { - errno = EBADF; - return -1; - } - if (fh->pos >= fh->length) - return -1; - return 0; +int FS_feof(fshandle_t *fh) { + if (!fh) { + errno = EBADF; + return -1; + } + if (fh->pos >= fh->length) + return -1; + return 0; } -int FS_ferror(fshandle_t *fh) -{ - if (!fh) { - errno = EBADF; - return -1; - } - return ferror(fh->file); +int FS_ferror(fshandle_t *fh) { + if (!fh) { + errno = EBADF; + return -1; + } + return ferror(fh->file); } -int FS_fgetc(fshandle_t *fh) -{ - if (!fh) { - errno = EBADF; - return EOF; - } - if (fh->pos >= fh->length) - return EOF; - fh->pos += 1; - return fgetc(fh->file); +int FS_fgetc(fshandle_t *fh) { + if (!fh) { + errno = EBADF; + return EOF; + } + if (fh->pos >= fh->length) + return EOF; + fh->pos += 1; + return fgetc(fh->file); } -char *FS_fgets(char *s, int size, fshandle_t *fh) -{ - char *ret; +char *FS_fgets(char *s, int size, fshandle_t *fh) { + char *ret; - if (FS_feof(fh)) - return NULL; + if (FS_feof(fh)) + return NULL; - if (size > (fh->length - fh->pos) + 1) - size = (fh->length - fh->pos) + 1; + if (size > (fh->length - fh->pos) + 1) + size = (fh->length - fh->pos) + 1; - ret = fgets(s, size, fh->file); - fh->pos = ftell(fh->file) - fh->start; + ret = fgets(s, size, fh->file); + fh->pos = ftell(fh->file) - fh->start; - return ret; + return ret; } -long FS_filelength (fshandle_t *fh) -{ - if (!fh) { - errno = EBADF; - return -1; - } - return fh->length; +long FS_filelength(fshandle_t *fh) { + if (!fh) { + errno = EBADF; + return -1; + } + return fh->length; } /* @@ -2546,20 +2350,18 @@ long FS_filelength (fshandle_t *fh) LOCALIZATION ============================================================================ */ -typedef struct -{ - char *key; - char *value; +typedef struct { + char *key; + char *value; } locentry_t; -typedef struct -{ - int numentries; - int maxnumentries; - int numindices; - unsigned *indices; - locentry_t *entries; - char *text; +typedef struct { + int numentries; + int maxnumentries; + int numindices; + unsigned *indices; + locentry_t *entries; + char *text; } localization_t; static localization_t localization; @@ -2570,38 +2372,35 @@ COM_HashString Computes the FNV-1a hash of string str ================ */ -unsigned COM_HashString (const char *str) -{ - unsigned hash = 0x811c9dc5u; - while (*str) - { - hash ^= *str++; - hash *= 0x01000193u; - } - return hash; +unsigned COM_HashString(const char *str) { + unsigned hash = 0x811c9dc5u; + while (*str) { + hash ^= *str++; + hash *= 0x01000193u; + } + return hash; } -static size_t mz_zip_file_read_func(void *opaque, mz_uint64 ofs, void *buf, size_t n) -{ - if (SDL_RWseek((SDL_RWops*)opaque, (Sint64)ofs, RW_SEEK_SET) < 0) - return 0; - #ifdef USE_SDL2 - return SDL_RWread((SDL_RWops*)opaque, buf, 1, n); - #else - else { - int r = SDL_RWread((SDL_RWops*)opaque, buf, 1, n); - return (r < 0)? 0 : r; - } - #endif +static size_t mz_zip_file_read_func(void *opaque, mz_uint64 ofs, void *buf, size_t n) { + if (SDL_RWseek((SDL_RWops*)opaque, (Sint64)ofs, RW_SEEK_SET) < 0) + return 0; +#ifdef USE_SDL2 + return SDL_RWread((SDL_RWops*)opaque, buf, 1, n); +#else + else { + int r = SDL_RWread((SDL_RWops*)opaque, buf, 1, n); + return (r < 0) ? 0 : r; + } +#endif } #ifndef USE_SDL2 /* no SDL_RWsize in SDL-1.2 */ static Sint32 SDLCALL SDL_RWsize(SDL_RWops *rw) { - Sint32 pos, size; - if ((pos=SDL_RWtell(rw))<0) return -1; - size = SDL_RWseek(rw, 0, RW_SEEK_END); - SDL_RWseek(rw, pos, RW_SEEK_SET); - return size; + Sint32 pos, size; + if ((pos = SDL_RWtell(rw)) < 0) return -1; + size = SDL_RWseek(rw, 0, RW_SEEK_END); + SDL_RWseek(rw, pos, RW_SEEK_SET); + return size; } #endif @@ -2610,237 +2409,226 @@ static Sint32 SDLCALL SDL_RWsize(SDL_RWops *rw) { LOC_LoadFile ================ */ -void LOC_LoadFile (const char *file) -{ - char path[1024]; - int i,lineno; - char *cursor; +void LOC_LoadFile(const char *file) { + char path[1024]; + int i, lineno; + char *cursor; - SDL_RWops *rw = NULL; - Sint64 sz; - mz_zip_archive archive; - size_t size = 0; + SDL_RWops *rw = NULL; + Sint64 sz; + mz_zip_archive archive; + size_t size = 0; - // clear existing data - if (localization.text) - { - free(localization.text); - localization.text = NULL; - } - localization.numentries = 0; - localization.numindices = 0; + // clear existing data + if (localization.text) { + free(localization.text); + localization.text = NULL; + } + localization.numentries = 0; + localization.numindices = 0; - if (!file || !*file) - return; + if (!file || !*file) + return; - Con_Printf("\nLanguage initialization\n"); + Con_Printf("\nLanguage initialization\n"); - memset(&archive, 0, sizeof(archive)); - q_snprintf(path, sizeof(path), "%s/%s", com_basedir, file); - rw = SDL_RWFromFile(path, "rb"); - #if defined(DO_USERDIRS) - if (!rw) { - q_snprintf(path, sizeof(path), "%s/%s", host_parms->userdir, file); - rw = SDL_RWFromFile(path, "rb"); - } - #endif - if (!rw) - { - q_snprintf(path, sizeof(path), "%s/QuakeEX.kpf", com_basedir); - rw = SDL_RWFromFile(path, "rb"); - #if defined(DO_USERDIRS) - if (!rw) { - q_snprintf(path, sizeof(path), "%s/QuakeEX.kpf", host_parms->userdir); - rw = SDL_RWFromFile(path, "rb"); - } - #endif - if (!rw) goto fail; - sz = SDL_RWsize(rw); - if (sz <= 0) goto fail; - archive.m_pRead = mz_zip_file_read_func; - archive.m_pIO_opaque = rw; - if (!mz_zip_reader_init(&archive, sz, 0)) goto fail; - localization.text = (char *) mz_zip_reader_extract_file_to_heap(&archive, file, &size, 0); - if (!localization.text) goto fail; - mz_zip_reader_end(&archive); - SDL_RWclose(rw); - localization.text = (char *) realloc(localization.text, size+1); - localization.text[size] = 0; - } - else - { - sz = SDL_RWsize(rw); - if (sz <= 0) goto fail; - localization.text = (char *) calloc(1, sz+1); - if (!localization.text) - { -fail: mz_zip_reader_end(&archive); - if (rw) SDL_RWclose(rw); - Con_Printf("Couldn't load '%s'\nfrom '%s'\n", file, com_basedir); - return; - } - SDL_RWread(rw, localization.text, 1, sz); - SDL_RWclose(rw); - } + memset(&archive, 0, sizeof(archive)); + q_snprintf(path, sizeof(path), "%s/%s", com_basedir, file); + rw = SDL_RWFromFile(path, "rb"); +#if defined(DO_USERDIRS) + if (!rw) { + q_snprintf(path, sizeof(path), "%s/%s", host_parms->userdir, file); + rw = SDL_RWFromFile(path, "rb"); + } +#endif + if (!rw) { + q_snprintf(path, sizeof(path), "%s/QuakeEX.kpf", com_basedir); + rw = SDL_RWFromFile(path, "rb"); +#if defined(DO_USERDIRS) + if (!rw) { + q_snprintf(path, sizeof(path), "%s/QuakeEX.kpf", host_parms->userdir); + rw = SDL_RWFromFile(path, "rb"); + } +#endif + if (!rw) goto fail; + sz = SDL_RWsize(rw); + if (sz <= 0) goto fail; + archive.m_pRead = mz_zip_file_read_func; + archive.m_pIO_opaque = rw; + if (!mz_zip_reader_init(&archive, sz, 0)) goto fail; + localization.text = (char *) mz_zip_reader_extract_file_to_heap(&archive, file, &size, 0); + if (!localization.text) goto fail; + mz_zip_reader_end(&archive); + SDL_RWclose(rw); + localization.text = (char *) realloc(localization.text, size + 1); + localization.text[size] = 0; + } else { + sz = SDL_RWsize(rw); + if (sz <= 0) goto fail; + localization.text = (char *) calloc(1, sz + 1); + if (!localization.text) { + fail: + mz_zip_reader_end(&archive); + if (rw) + SDL_RWclose(rw); + Con_Printf("Couldn't load '%s'\nfrom '%s'\n", file, com_basedir); + return; + } + SDL_RWread(rw, localization.text, 1, sz); + SDL_RWclose(rw); + } - cursor = localization.text; + cursor = localization.text; - // skip BOM - if ((unsigned char)(cursor[0]) == 0xEF && (unsigned char)(cursor[1]) == 0xBB && (unsigned char)(cursor[2]) == 0xBF) - cursor += 3; + // skip BOM + if ((unsigned char) (cursor[0]) == 0xEF && (unsigned char) (cursor[1]) == 0xBB && (unsigned char) (cursor[2]) == + 0xBF) + cursor += 3; - lineno = 0; - while (*cursor) - { - char *line, *equals; + lineno = 0; + while (*cursor) { + char *line, *equals; - lineno++; + lineno++; - // skip leading whitespace - while (q_isblank(*cursor)) - ++cursor; + // skip leading whitespace + while (q_isblank(*cursor)) + ++cursor; - line = cursor; - equals = NULL; - // find line end and first equals sign, if any - while (*cursor && *cursor != '\n') - { - if (*cursor == '=' && !equals) - equals = cursor; - cursor++; - } + line = cursor; + equals = NULL; + // find line end and first equals sign, if any + while (*cursor && *cursor != '\n') { + if (*cursor == '=' && !equals) + equals = cursor; + cursor++; + } - if (line[0] == '/') - { - if (line[1] != '/') - Con_DPrintf("LOC_LoadFile: malformed comment on line %d\n", lineno); - } - else if (equals) - { - char *key_end = equals; - qboolean leading_quote; - qboolean trailing_quote; - locentry_t *entry; - char *value_src; - char *value_dst; - char *value; + if (line[0] == '/') { + if (line[1] != '/') + Con_DPrintf("LOC_LoadFile: malformed comment on line %d\n", lineno); + } else if (equals) { + char *key_end = equals; + qboolean leading_quote; + qboolean trailing_quote; + locentry_t *entry; + char *value_src; + char *value_dst; + char *value; - // trim whitespace before equals sign - while (key_end != line && q_isspace(key_end[-1])) - key_end--; - *key_end = 0; + // trim whitespace before equals sign + while (key_end != line && q_isspace(key_end[-1])) + key_end--; + *key_end = 0; - value = equals + 1; - // skip whitespace after equals sign - while (value != cursor && q_isspace(*value)) - value++; + value = equals + 1; + // skip whitespace after equals sign + while (value != cursor && q_isspace(*value)) + value++; - leading_quote = (*value == '\"'); - trailing_quote = false; - value += leading_quote; + leading_quote = (*value == '\"'); + trailing_quote = false; + value += leading_quote; - // transform escape sequences in-place - value_src = value; - value_dst = value; - while (value_src != cursor) - { - if (*value_src == '\\' && value_src + 1 != cursor) - { - char c = value_src[1]; - value_src += 2; - switch (c) - { - case 'n': *value_dst++ = '\n'; break; - case 't': *value_dst++ = '\t'; break; - case 'v': *value_dst++ = '\v'; break; - case 'b': *value_dst++ = '\b'; break; - case 'f': *value_dst++ = '\f'; break; + // transform escape sequences in-place + value_src = value; + value_dst = value; + while (value_src != cursor) { + if (*value_src == '\\' && value_src + 1 != cursor) { + char c = value_src[1]; + value_src += 2; + switch (c) { + case 'n': *value_dst++ = '\n'; + break; + case 't': *value_dst++ = '\t'; + break; + case 'v': *value_dst++ = '\v'; + break; + case 'b': *value_dst++ = '\b'; + break; + case 'f': *value_dst++ = '\f'; + break; - case '"': - case '\'': - *value_dst++ = c; - break; + case '"': + case '\'': + *value_dst++ = c; + break; - default: - Con_Printf("LOC_LoadFile: unrecognized escape sequence \\%c on line %d\n", c, lineno); - *value_dst++ = c; - break; - } - continue; - } + default: + Con_Printf("LOC_LoadFile: unrecognized escape sequence \\%c on line %d\n", c, lineno); + *value_dst++ = c; + break; + } + continue; + } - if (*value_src == '\"') - { - trailing_quote = true; - *value_dst = 0; - break; - } + if (*value_src == '\"') { + trailing_quote = true; + *value_dst = 0; + break; + } - *value_dst++ = *value_src++; - } + *value_dst++ = *value_src++; + } - // if not a quoted string, trim trailing whitespace - if (!trailing_quote) - { - while (value_dst != value && q_isblank(value_dst[-1])) - { - *value_dst = 0; - value_dst--; - } - } + // if not a quoted string, trim trailing whitespace + if (!trailing_quote) { + while (value_dst != value && q_isblank(value_dst[-1])) { + *value_dst = 0; + value_dst--; + } + } - if (localization.numentries == localization.maxnumentries) - { - // grow by 50% - localization.maxnumentries += localization.maxnumentries >> 1; - localization.maxnumentries = q_max(localization.maxnumentries, 32); - localization.entries = (locentry_t*) realloc(localization.entries, sizeof(*localization.entries) * localization.maxnumentries); - } + if (localization.numentries == localization.maxnumentries) { + // grow by 50% + localization.maxnumentries += localization.maxnumentries >> 1; + localization.maxnumentries = std::max(localization.maxnumentries, 32); + localization.entries = (locentry_t *) realloc(localization.entries, + sizeof(*localization.entries) * localization. + maxnumentries); + } - entry = &localization.entries[localization.numentries++]; - entry->key = line; - entry->value = value; - } + entry = &localization.entries[localization.numentries++]; + entry->key = line; + entry->value = value; + } - if (*cursor) - *cursor++ = 0; // terminate line and advance to next - } + if (*cursor) + *cursor++ = 0; // terminate line and advance to next + } - // hash all entries + // hash all entries - localization.numindices = localization.numentries * 2; // 50% load factor - if (localization.numindices == 0) - { - Con_Printf("No localized strings in file '%s'\n", file); - return; - } + localization.numindices = localization.numentries * 2; // 50% load factor + if (localization.numindices == 0) { + Con_Printf("No localized strings in file '%s'\n", file); + return; + } - localization.indices = (unsigned*) realloc(localization.indices, localization.numindices * sizeof(*localization.indices)); - memset(localization.indices, 0, localization.numindices * sizeof(*localization.indices)); + localization.indices = (unsigned *) realloc(localization.indices, + localization.numindices * sizeof(*localization.indices)); + memset(localization.indices, 0, localization.numindices * sizeof(*localization.indices)); - for (i = 0; i < localization.numentries; i++) - { - locentry_t *entry = &localization.entries[i]; - unsigned pos = COM_HashString(entry->key) % localization.numindices, end = pos; + for (i = 0; i < localization.numentries; i++) { + locentry_t *entry = &localization.entries[i]; + unsigned pos = COM_HashString(entry->key) % localization.numindices, end = pos; - for (;;) - { - if (!localization.indices[pos]) - { - localization.indices[pos] = i + 1; - break; - } + for (;;) { + if (!localization.indices[pos]) { + localization.indices[pos] = i + 1; + break; + } - ++pos; - if (pos == localization.numindices) - pos = 0; + ++pos; + if (pos == localization.numindices) + pos = 0; - if (pos == end) - Sys_Error("LOC_LoadFile failed"); - } - } + if (pos == end) + Sys_Error("LOC_LoadFile failed"); + } + } - Con_Printf("Loaded %d strings from '%s'\n", localization.numentries, file); + Con_Printf("Loaded %d strings from '%s'\n", localization.numentries, file); } /* @@ -2848,9 +2636,8 @@ fail: mz_zip_reader_end(&archive); LOC_Init ================ */ -void LOC_Init(void) -{ - LOC_LoadFile("localization/loc_english.txt"); +void LOC_Init(void) { + LOC_LoadFile("localization/loc_english.txt"); } /* @@ -2858,11 +2645,10 @@ void LOC_Init(void) LOC_Shutdown ================ */ -void LOC_Shutdown(void) -{ - free(localization.indices); - free(localization.entries); - free(localization.text); +void LOC_Shutdown(void) { + free(localization.indices); + free(localization.entries); + free(localization.text); } /* @@ -2872,34 +2658,32 @@ LOC_GetRawString Returns localized string if available, or NULL otherwise ================ */ -const char* LOC_GetRawString (const char *key) -{ - unsigned pos, end; +const char *LOC_GetRawString(const char *key) { + unsigned pos, end; - if (!localization.numindices || !key || !*key || *key != '$') - return NULL; - key++; + if (!localization.numindices || !key || !*key || *key != '$') + return NULL; + key++; - pos = COM_HashString(key) % localization.numindices; - end = pos; + pos = COM_HashString(key) % localization.numindices; + end = pos; - do - { - unsigned idx = localization.indices[pos]; - locentry_t *entry; - if (!idx) - return NULL; + do { + unsigned idx = localization.indices[pos]; + locentry_t *entry; + if (!idx) + return NULL; - entry = &localization.entries[idx - 1]; - if (!Q_strcmp(entry->key, key)) - return entry->value; + entry = &localization.entries[idx - 1]; + if (!Q_strcmp(entry->key, key)) + return entry->value; - ++pos; - if (pos == localization.numindices) - pos = 0; - } while (pos != end); + ++pos; + if (pos == localization.numindices) + pos = 0; + } while (pos != end); - return NULL; + return NULL; } /* @@ -2909,10 +2693,9 @@ LOC_GetString Returns localized string if available, or input string otherwise ================ */ -const char* LOC_GetString (const char *key) -{ - const char* value = LOC_GetRawString(key); - return value ? value : key; +const char *LOC_GetString(const char *key) { + const char *value = LOC_GetRawString(key); + return value ? value : key; } /* @@ -2923,27 +2706,26 @@ Returns argument index (>= 0) and advances the string if it starts with a placeh otherwise returns a negative value and leaves the pointer unchanged ================ */ -static int LOC_ParseArg (const char **pstr) -{ - int arg; - const char *str = *pstr; +static int LOC_ParseArg(const char **pstr) { + int arg; + const char *str = *pstr; - // opening brace - if (*str != '{') - return -1; - ++str; + // opening brace + if (*str != '{') + return -1; + ++str; - // optional index, defaulting to 0 - arg = 0; - while (q_isdigit(*str)) - arg = arg * 10 + *str++ - '0'; + // optional index, defaulting to 0 + arg = 0; + while (q_isdigit(*str)) + arg = arg * 10 + *str++ - '0'; - // closing brace - if (*str != '}') - return -1; - *pstr = ++str; + // closing brace + if (*str != '}') + return -1; + *pstr = ++str; - return arg; + return arg; } /* @@ -2951,17 +2733,15 @@ static int LOC_ParseArg (const char **pstr) LOC_HasPlaceholders ================ */ -qboolean LOC_HasPlaceholders (const char *str) -{ - if (!localization.numindices) - return false; - while (*str) - { - if (LOC_ParseArg(&str) >= 0) - return true; - str++; - } - return false; +qboolean LOC_HasPlaceholders(const char *str) { + if (!localization.numindices) + return false; + while (*str) { + if (LOC_ParseArg(&str) >= 0) + return true; + str++; + } + return false; } /* @@ -2974,49 +2754,45 @@ Returns number of written chars, excluding the NUL terminator If len > 0, output is always NUL-terminated ================ */ -size_t LOC_Format (const char *format, const char* (*getarg_fn) (int idx, void* userdata), void* userdata, char* out, size_t len) -{ - size_t written = 0; - int numargs = 0; +size_t LOC_Format(const char *format, const char * (*getarg_fn)(int idx, void *userdata), void *userdata, char *out, + size_t len) { + size_t written = 0; + int numargs = 0; - if (!len) - { - Con_DPrintf("LOC_Format: no output space\n"); - return 0; - } - --len; // reserve space for the terminator + if (!len) { + Con_DPrintf("LOC_Format: no output space\n"); + return 0; + } + --len; // reserve space for the terminator - while (*format && written < len) - { - const char* insert; - size_t space_left; - size_t insert_len; - int argindex = LOC_ParseArg(&format); + while (*format && written < len) { + const char *insert; + size_t space_left; + size_t insert_len; + int argindex = LOC_ParseArg(&format); - if (argindex < 0) - { - out[written++] = *format++; - continue; - } + if (argindex < 0) { + out[written++] = *format++; + continue; + } - insert = getarg_fn(argindex, userdata); - space_left = len - written; - insert_len = Q_strlen(insert); + insert = getarg_fn(argindex, userdata); + space_left = len - written; + insert_len = Q_strlen(insert); - if (insert_len > space_left) - { - Con_DPrintf("LOC_Format: overflow at argument #%d\n", numargs); - insert_len = space_left; - } + if (insert_len > space_left) { + Con_DPrintf("LOC_Format: overflow at argument #%d\n", numargs); + insert_len = space_left; + } - Q_memcpy(out + written, insert, insert_len); - written += insert_len; - } + Q_memcpy(out + written, insert, insert_len); + written += insert_len; + } - if (*format) - Con_DPrintf("LOC_Format: overflow\n"); + if (*format) + Con_DPrintf("LOC_Format: overflow\n"); - out[written] = 0; + out[written] = 0; - return written; + return written; } diff --git a/Quake/common.hpp b/Quake/common.hpp index 1fb57b2..27240c3 100644 --- a/Quake/common.hpp +++ b/Quake/common.hpp @@ -22,6 +22,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #ifndef _Q_COMMON_H #define _Q_COMMON_H +#include "convar.hpp" // comndef.h -- general definitions @@ -57,10 +58,10 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #define NO_COMMA #define IMPL_GENERIC_FUNCS(type, suffix) \ -static inline type q_min_##suffix (type a, type b) { \ +static inline type std::min_##suffix (type a, type b) { \ return (a < b) ? a : b; \ } \ -static inline type q_max_##suffix (type a, type b) { \ +static inline type std::max_##suffix (type a, type b) { \ return (a > b) ? a : b; \ } \ static inline type clamp_##suffix (type minval, type val, type maxval) { \ @@ -69,30 +70,17 @@ static inline type clamp_##suffix (type minval, type val, type maxval) { \ GENERIC_TYPES (IMPL_GENERIC_FUNCS, NO_COMMA) -#define SELECT_Q_MIN(type, suffix) type: q_min_##suffix -#define q_min(a, b) _Generic((a) + (b), GENERIC_TYPES (SELECT_Q_MIN, COMMA))(a, b) +#define SELECT_std::min(type, suffix) type: std::min_##suffix +#define std::min(a, b) _Generic((a) + (b), GENERIC_TYPES (SELECT_std::min, COMMA))(a, b) -#define SELECT_Q_MAX(type, suffix) type: q_max_##suffix -#define q_max(a, b) _Generic((a) + (b), GENERIC_TYPES (SELECT_Q_MAX, COMMA))(a, b) +#define SELECT_std::max(type, suffix) type: std::max_##suffix +#define std::max(a, b) _Generic((a) + (b), GENERIC_TYPES (SELECT_std::max, COMMA))(a, b) #define SELECT_CLAMP(type, suffix) type: clamp_##suffix #define CLAMP(minval, val, maxval) _Generic((minval) + (val) + (maxval), \ GENERIC_TYPES (SELECT_CLAMP, COMMA))(minval, val, maxval) #elif defined(__GNUC__) -/* min and max macros with type checking -- based on tyrquake. */ -#define q_max(a,b) ({ \ - const __typeof(a) a_ = (a); \ - const __typeof(b) b_ = (b); \ - (void)(&a_ == &b_); \ - (a_ > b_) ? a_ : b_; \ -}) -#define q_min(a,b) ({ \ - const __typeof(a) a_ = (a); \ - const __typeof(b) b_ = (b); \ - (void)(&a_ == &b_); \ - (a_ < b_) ? a_ : b_; \ -}) #define CLAMP(_minval, x, _maxval) ({ \ const __typeof(x) x_ = (x); \ const __typeof(_minval) valmin_ = (_minval);\ @@ -104,8 +92,8 @@ GENERIC_TYPES (IMPL_GENERIC_FUNCS, NO_COMMA) }) #else -#define q_min(a, b) (((a) < (b)) ? (a) : (b)) -#define q_max(a, b) (((a) > (b)) ? (a) : (b)) +#define std::min(a, b) (((a) < (b)) ? (a) : (b)) +#define std::max(a, b) (((a) > (b)) ? (a) : (b)) #define CLAMP(_minval, x, _maxval) \ ((x) < (_minval) ? (_minval) : \ (x) > (_maxval) ? (_maxval) : (x)) @@ -237,17 +225,16 @@ extern int q_vsnprintf(char *str, size_t size, const char *format, va_list args) //============================================================================ -extern char com_token[1024]; extern qboolean com_eof; -typedef enum -{ - CPE_NOTRUNC, // return parse error in case of overflow - CPE_ALLOWTRUNC // truncate com_token in case of overflow -} cpe_mode; -const char *COM_Parse (const char *data); -const char *COM_ParseEx (const char *data, cpe_mode mode); +namespace common { + std::optional parse_token(std::istringstream &ss); + std::string parse_string_newline(std::istringstream &ss); + + int parse_int_newline(std::istringstream &ss); + float parse_float_newline(std::istringstream &ss); +} extern int com_argc; @@ -358,19 +345,6 @@ byte *COM_LoadMallocFile (const char *path, unsigned int *path_id); // Loads in "t" mode so CRLF to LF translation is performed on Windows. byte *COM_LoadMallocFile_TextMode_OSPath (const char *path, long *len_out); -// Attempts to parse an int, followed by a newline. -// Returns advanced buffer position. -// Doesn't signal parsing failure, but this is not needed for savegame loading. -const char *COM_ParseIntNewline(const char *buffer, int *value); - -// Attempts to parse a float followed by a newline. -// Returns advanced buffer position. -const char *COM_ParseFloatNewline(const char *buffer, float *value); - -// Parse a string of non-whitespace into com_token, then tries to consume a -// newline. Returns advanced buffer position. -const char *COM_ParseStringNewline(const char *buffer); - #define FS_ENT_NONE (0) #define FS_ENT_FILE (1 << 0) @@ -403,7 +377,7 @@ char *FS_fgets(char *s, int size, fshandle_t *fh); long FS_filelength (fshandle_t *fh); -extern struct cvar_s registered; +extern convar registered; extern qboolean standard_quake, rogue, hipnotic; extern qboolean fitzmode; /* if true, run in fitzquake mode disabling custom quakespasm hacks */ diff --git a/Quake/console.cpp b/Quake/console.cpp index 8f5960b..d795591 100644 --- a/Quake/console.cpp +++ b/Quake/console.cpp @@ -50,8 +50,8 @@ int con_current; // where next message will be printed int con_x; // offset in current line for next print char *con_text = NULL; -cvar_t con_notifytime = {"con_notifytime","3",CVAR_NONE}; //seconds -cvar_t con_logcenterprint = {"con_logcenterprint", "1", CVAR_NONE}; //johnfitz +convar con_notifytime{"con_notifytime","3"}; //seconds +convar con_logcenterprint{"con_logcenterprint", "1"}; //johnfitz char con_lastcenterstring[1024]; //johnfitz @@ -78,8 +78,8 @@ const char *Con_Quakebar (int len) static char bar[42]; int i; - len = q_min(len, (int)sizeof(bar) - 2); - len = q_min(len, con_linewidth); + len = std::min(len, (int)sizeof(bar) - 2); + len = std::min(len, con_linewidth); bar[0] = '\35'; for (i = 1; i < len - 1; i++) @@ -331,14 +331,14 @@ void Con_Init (void) Con_Printf ("Console initialized.\n"); - Cvar_RegisterVariable (&con_notifytime); - Cvar_RegisterVariable (&con_logcenterprint); //johnfitz + con_notifytime.inscribe(); + con_logcenterprint.inscribe(); //johnfitz - Cmd_AddCommand ("toggleconsole", Con_ToggleConsole_f); - Cmd_AddCommand ("messagemode", Con_MessageMode_f); - Cmd_AddCommand ("messagemode2", Con_MessageMode2_f); - Cmd_AddCommand ("clear", Con_Clear_f); - Cmd_AddCommand ("condump", Con_Dump_f); //johnfitz + command::add ("toggleconsole", Con_ToggleConsole_f); + command::add ("messagemode", Con_MessageMode_f); + command::add ("messagemode2", Con_MessageMode2_f); + command::add ("clear", Con_Clear_f); + command::add ("condump", Con_Dump_f); //johnfitz con_initialized = true; } @@ -658,7 +658,7 @@ void Con_CenterPrintf (int linewidth, const char *fmt, ...) q_vsnprintf (msg, sizeof(msg), fmt, argptr); va_end (argptr); - linewidth = q_min(linewidth, con_linewidth); + linewidth = std::min(linewidth, con_linewidth); for (src = msg; *src; ) { dst = line; @@ -727,21 +727,7 @@ tab_t *tablist; //defs from elsewhere extern qboolean keydown[256]; -typedef struct cmd_function_s -{ - struct cmd_function_s *next; - const char *name; - xcommand_t function; -} cmd_function_t; -extern cmd_function_t *cmd_functions; #define MAX_ALIAS_NAME 32 -typedef struct cmdalias_s -{ - struct cmdalias_s *next; - char name[MAX_ALIAS_NAME]; - char *value; -} cmdalias_t; -extern cmdalias_t *cmd_alias; /* ============ @@ -897,8 +883,6 @@ BuildTabList -- johnfitz */ void BuildTabList (const char *partial) { - cmdalias_t *alias; - cmd_function_t *cmd; int len; tablist = NULL; @@ -907,17 +891,17 @@ void BuildTabList (const char *partial) bash_partial[0] = 0; bash_singlematch = 1; - for (auto cvar : std::ranges::views::values(CLIENT_VARIABLES)) - if (!Q_strncmp (partial, cvar->name, len)) - AddToTabList (cvar->name, "cvar"); + for (const auto cvar : convar::get_variables()) + if (!Q_strncmp (partial, cvar->name.c_str(), len)) + AddToTabList (cvar->name.c_str(), "cvar"); - for (cmd=cmd_functions ; cmd ; cmd=cmd->next) - if (!Q_strncmp (partial,cmd->name, len)) - AddToTabList (cmd->name, "command"); + for (const auto &ccmd : command::get_commands()) + if (!Q_strncmp (partial,ccmd.name.c_str(), len)) + AddToTabList (ccmd.name.c_str(), "command"); - for (alias=cmd_alias ; alias ; alias=alias->next) - if (!Q_strncmp (partial, alias->name, len)) - AddToTabList (alias->name, "alias"); + for (const auto &alias : command::get_aliases()) + if (!Q_strncmp (partial, alias.name.c_str(), len)) + AddToTabList (alias.name.c_str(), "alias"); } /* diff --git a/Quake/convar.cpp b/Quake/convar.cpp new file mode 100644 index 0000000..a3000b1 --- /dev/null +++ b/Quake/convar.cpp @@ -0,0 +1,540 @@ +/* +Copyright (C) 1996-2001 Id Software, Inc. +Copyright (C) 2002-2009 John Fitzgibbons and others +Copyright (C) 2010-2014 QuakeSpasm developers + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +See the GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +*/ +// cvar.c -- dynamic variable tracking + +#include "quakedef.hpp" + +#include +#include +#include +#include +#include +#include + +std::map CLIENT_VARIABLES{}; + +//============================================================================== +// +// USER COMMANDS +// +//============================================================================== + +/* +============ +Cvar_List_f -- johnfitz +============ +*/ +void Cvar_List_f() { + convar *cvar; + const char *partial; + int len, count; + + if (command::argc() > 1) { + partial = command::argv(1)->c_str(); + len = Q_strlen(partial); + } else { + partial = NULL; + len = 0; + } + + count = 0; + for (const auto &[name, var]: CLIENT_VARIABLES) { + if (partial && Q_strncmp(partial, name.c_str(), len)) { + continue; + } + Con_SafePrintf("%s%s %s \"%s\"\n", + var->flags.archive ? "*" : " ", + var->flags.notify ? "s" : " ", + name.c_str(), + var->string); + count++; + } + + Con_SafePrintf("%i cvars", count); + if (partial) { + Con_SafePrintf(" beginning with \"%s\"", partial); + } + Con_SafePrintf("\n"); +} + +/* +============ +Cvar_Inc_f -- johnfitz +============ +*/ +void Cvar_Inc_f(void) { + switch (command::argc()) { + default: + case 1: + Con_Printf("inc [amount] : increment cvar\n"); + break; + case 2: + convar::set_value(*command::argv(1), convar::variable_value(*command::argv(1)).value_or(0.0) + 1); + break; + case 3: + convar::set_value(*command::argv(1), convar::variable_value(*command::argv(1)).value_or(0.0) + Q_atof(command::argv(2)->c_str())); + break; + } +} + +/* +============ +Cvar_Toggle_f -- johnfitz +============ +*/ +void Cvar_Toggle_f() { + switch (command::argc()) { + default: + case 1: + Con_Printf("toggle : toggle cvar\n"); + break; + case 2: + if (convar::variable_value(*command::argv(1)).value_or(0.0) != 0.0) + convar::set(*command::argv(1), "0"); + else + convar::set(*command::argv(1), "1"); + break; + } +} + +/* +============ +Cvar_Cycle_f -- johnfitz +============ +*/ +void Cvar_Cycle_f() { + int i; + + if (command::argc() < 3) { + Con_Printf("cycle : cycle cvar through a list of values\n"); + return; + } + + //loop through the args until you find one that matches the current cvar value. + //yes, this will get stuck on a list that contains the same value twice. + //it's not worth dealing with, and i'm not even sure it can be dealt with. + for (i = 2; i < command::argc(); i++) { + //zero is assumed to be a string, even though it could actually be zero. The worst case + //is that the first time you call this command, it won't match on zero when it should, but after that, + //it will be comparing strings that all had the same source (the user) so it will work. + if (Q_atof(command::argv(i)->c_str()) == 0) { + if (!strcmp(command::argv(i)->c_str(), convar::variable_string(*command::argv(1)).value_or("").c_str())) + break; + } else { + if (Q_atof(command::argv(i)->c_str()) == convar::variable_value(*command::argv(1)).value_or(0.0)) + break; + } + } + + if (i == command::argc()) + convar::set(*command::argv(1), *command::argv(2)); // no match + else if (i + 1 == command::argc()) + convar::set(*command::argv(1), *command::argv(2)); // matched last value in list + else + convar::set(*command::argv(1), *command::argv(i + 1)); // matched earlier in list +} + +/* +============ +Cvar_Reset_f -- johnfitz +============ +*/ +void Cvar_Reset_f() { + switch (command::argc()) { + default: + case 1: + Con_Printf("reset : reset cvar to default\n"); + break; + case 2: + convar::reset(*command::argv(1)); + break; + } +} + +/* +============ +Cvar_ResetAll_f -- johnfitz +============ +*/ +void Cvar_ResetAll_f(void) { + convar *var; + + for (auto name: std::views::keys(CLIENT_VARIABLES)) + convar::reset(name); +} + +/* +============ +Cvar_ResetCfg_f -- QuakeSpasm +============ +*/ +void Cvar_ResetCfg_f() { + for (const auto &var: std::views::values(CLIENT_VARIABLES)) + if (var->flags.archive) convar::reset(var->name); +} + +//============================================================================== +// +// INIT +// +//============================================================================== + +/* +============ +Cvar_Init -- johnfitz +============ +*/ + +void Cvar_Init() { + command::add("cvarlist", Cvar_List_f); + command::add("toggle", Cvar_Toggle_f); + command::add("cycle", Cvar_Cycle_f); + command::add("inc", Cvar_Inc_f); + command::add("reset", Cvar_Reset_f); + command::add("resetall", Cvar_ResetAll_f); + command::add("resetcfg", Cvar_ResetCfg_f); +} + +std::optional convar::find_var(const std::string_view &desired) { + for (auto &[name, var]: CLIENT_VARIABLES) { + if (name == desired) + return var; + } + + return std::nullopt; +} + +std::optional convar::find_var_after(const std::optional &prev_name, + const std::optional with_flags) { + auto iter = CLIENT_VARIABLES.begin(); + if (prev_name.has_value()) { + iter = CLIENT_VARIABLES.find(prev_name.value()); + if (iter == CLIENT_VARIABLES.end()) + return std::nullopt; + ++iter; + } + + // search for the next cvar matching the needed flags + while (iter != CLIENT_VARIABLES.end()) { + if (!with_flags.has_value() || iter->second->flags.matches_mask(with_flags.value())) + break; + ++iter; + } + + if (iter != CLIENT_VARIABLES.end()) { + return iter->second; + } + + return std::nullopt; +} + +void convar::lock_var(const std::string_view &name) { + if (const auto var = find_var(name); var.has_value()) + var.value()->flags.locked = true; +} + +void convar::unlock_var(const std::string_view &name) { + if (const auto var = find_var(name); var.has_value()) + var.value()->flags.locked = false; +} + +void convar::unlock_all() { + for (const auto &var: std::views::values(CLIENT_VARIABLES)) { + var->flags.locked = false; + } +} + +/** + * Gets a floating-point representation of the `string` value of the `convar` matching `name`. + * + * @param name The name of the variable to retreive + * @return The value of the variable matching `name`, or `std::nullopt` if a variable with + * that name cannot be found. + */ +std::optional convar::variable_value(const std::string_view &name) { + const auto var = find_var(name); + if (!var.has_value()) + return std::nullopt; + return std::strtof(var.value()->string, nullptr); +} + + +/** + * Gets the `string` value of the `convar` matching `name`. + * + * @param name The name of the variable to retreive + * @return The value of the variable matching `name`, or `std::nullopt` if a variable with + * that name cannot be found. + */ +std::optional convar::variable_string(const std::string_view &name) { + const auto var = find_var(name); + if (!var.has_value()) + return std::nullopt; + return var.value()->string; +} + + +/** + * Autocompletes the name of a `convar` starting with `partial`. + * + * @param partial Partial name of a variable to retrieve + * @return The full name of the first variable beginning with `partial`, or `std::nullopt` if + * no matching variable is found. + */ +std::optional convar::complete_variable(const std::string_view &partial) { + if (!partial.empty()) + return std::nullopt; + + // check functions + for (const auto &name: CLIENT_VARIABLES | std::views::keys) { + if (name.starts_with(name)) + return name; + } + + return std::nullopt; +} + +/** + * Resets a `convar`s `string` to its `default_string` value. + * + * @param name Name of the convar to reset + */ +void convar::reset(const std::string &name) { + if (const auto var = find_var(name); !var.has_value()) + Con_Printf("variable \"%s\" not found\n", name.c_str()); + else + var.value()->set(var.value()->default_string); +} + +void convar::set(const std::string &new_value) { + if (this->flags.rom || this->flags.locked) + return; + if (!(this->flags.registered)) + return; + + if (!this->string) + this->string = Z_Strdup(new_value.c_str()); + else { + if (!strcmp(this->string, new_value.c_str())) + return; // no change + + this->flags.changed = true; + + const std::size_t len = new_value.length(); + + if (len != Q_strlen(this->string)) { + Z_Free((void *) this->string); + this->string = (char *) Z_Malloc(len + 1); + } + memcpy((char *) this->string, new_value.c_str(), len + 1); + } + + this->value = Q_atof(this->string); + + //johnfitz -- save initial value for "reset" command + if (!this->default_string) + this->default_string = Z_Strdup(this->string); + //johnfitz -- during initialization, update default too + else if (!host_initialized) { + // Sys_Printf("changing default of %s: %s -> %s\n", + // this->name, this->default_string, this->string); + Z_Free((void *) this->default_string); + this->default_string = Z_Strdup(this->string); + } + //johnfitz + + if (this->callback) + this->callback(this); +} + +void convar::set_value(const float new_value) { + std::string val; + + if (new_value == static_cast(static_cast(new_value))) + val = std::format("{:d}", static_cast(new_value)); + else { + val = std::format("{:f}", new_value); + + // kill trailing zeroes + val.erase(val.find_last_not_of('0') + 1, std::string::npos); + } + + this->set(val); +} + +/* +============ +Cvar_Set +============ +*/ +void convar::set(const std::string &name, const std::string &value) { + const auto var = find_var(name); + if (!var.has_value()) { + // there is an error in C code if this happens + Con_Printf("Cvar_Set: variable %s not found\n", name.c_str()); + return; + } + + var.value()->set(value); +} + +/* +============ +convar::set_value +============ +*/ +void convar::set_value(const std::string &name, const float new_value) { + std::string val; + + if (new_value == static_cast(static_cast(new_value))) + val = std::format("{:d}", static_cast(new_value)); + else { + val = std::format("{:f}", new_value); + + // kill trailing zeroes + val.erase(val.find_last_not_of('0') + 1, std::string::npos); + } + + set(name, val); +} + +/* +============ +Cvar_SetROM +============ +*/ +void convar::set_rom(const std::string_view &name, const std::string value) { + if (const auto var = find_var(name); var.has_value()) { + var.value()->flags.rom = false; + var.value()->set(value); + var.value()->flags.rom = true; + } +} + +void convar::set_value_rom(const std::string_view &name, const float value) { + if (const auto var = find_var(name); var.has_value()) { + var.value()->flags.rom = false; + var.value()->set_value(value); + var.value()->flags.rom = true; + } +} + +convar_view convar::get_variables() { + return std::ranges::views::values(CLIENT_VARIABLES); +} + +convar::convar(const std::string_view name, const char *str) : convar(name, str, {}) { +} + +convar::convar(const std::string_view name, const char *str, const cvar_flags flags) { + this->name = name; + this->string = str; + this->flags = flags; +} + +/** + * Adds a freestanding variable to the variable list. + */ +void convar::inscribe() { + char value[512]; + convar *cursor, *prev; //johnfitz -- sorted list insert + + // first check to see if it has already been defined + if (find_var(this->name)) { + Con_Printf("Can't register variable %s, already defined\n", this->name.c_str()); + return; + } + + // check for overlap with a command + if (command::exists(this->name)) { + Con_Printf("Cvar_RegisterVariable: %s is a command\n", this->name.c_str()); + return; + } + + CLIENT_VARIABLES.emplace(std::string(this->name), this); + + //johnfitz + this->flags.registered = true; + + // copy the value off, because future sets will Z_Free it + std::strncpy(value, this->string, sizeof(value)); + this->string = nullptr; + this->default_string = nullptr; + + if (!this->flags.callback) + this->callback = nullptr; + + // set it through the function to be consistent + const bool set_rom = (this->flags.rom); + this->flags.rom = false; + this->set(value); + if (set_rom) + this->flags.rom = true; +} + +/** + * Set a callback function for the variable + * @param func Callback to be used (or `nullptr` to disable to callback). + */ +void convar::set_callback(const cvarcallback_t func) { + this->callback = func; + this->flags.callback = func != nullptr; +} + +/* +============ +Cvar_Command + +Handles variable inspection and changing from the console +============ +*/ +qboolean Cvar_Command() { + // check variables + auto var = convar::find_var(command::argv(0).value_or("")); + if (!var.has_value()) + return false; + + // perform a variable print or set + if (command::argc() == 1) { + Con_Printf("\"%s\" is \"%s\"\n", var.value()->name.c_str(), var.value()->string); + return true; + } + + convar::set(var.value()->name, *command::argv(1)); + return true; +} + + +/* +============ +Cvar_WriteVariables + +Writes lines containing "set variable value" for all variables +with the archive flag set to true. +============ +*/ +void Cvar_WriteVariables(FILE *f) { + for (const auto &[name, var]: CLIENT_VARIABLES) { + if (var->flags.archive) + fprintf(f, "%s \"%s\"\n", name.c_str(), var->string); + } +} diff --git a/Quake/convar.hpp b/Quake/convar.hpp new file mode 100644 index 0000000..341829b --- /dev/null +++ b/Quake/convar.hpp @@ -0,0 +1,154 @@ +/* +Copyright (C) 1996-2001 Id Software, Inc. +Copyright (C) 2002-2009 John Fitzgibbons and others +Copyright (C) 2010-2014 QuakeSpasm developers + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +See the GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +*/ + +#pragma once + +/* +cvar_t variables are used to hold scalar or string variables that can +be changed or displayed at the console or prog code as well as accessed +directly in C code. + +it is sufficient to initialize a cvar_t with just the first two fields, +or you can add a ,true flag for variables that you want saved to the +configuration file when the game is quit: + +cvar_t r_draworder = {"r_draworder","1"}; +cvar_t scr_screensize = {"screensize","1",true}; + +Cvars must be registered before use, or they will have a 0 value instead +of the float interpretation of the string. +Generally, all cvar_t declarations should be registered in the apropriate +init function before any console commands are executed: + +host_framerate.inscribe(); + +C code usually just references a cvar in place: +if ( r_draworder.value ) + +It could optionally ask for the value to be looked up for a string name: +if (Cvar_VariableValue ("r_draworder")) + +Interpreted prog code can access cvars with the cvar(name) or +cvar_set (name, value) internal functions: +teamplay = cvar("teamplay"); +cvar_set ("registered", "1"); + +The user can access cvars from the console in two ways: +r_draworder prints the current value +r_draworder 0 sets the current value to 0 + +Cvars are restricted from having the same names as commands to keep this +interface from being ambiguous. + +*/ + +#include +#include +#include + +#include "convar.hpp" + +void Cvar_Init(); + +struct cvar_flags { + bool archive{false}; + bool notify{false}; + bool server_info{false}; + bool user_info{false}; + bool changed{false}; + bool rom{false}; + bool locked{false}; + bool registered{false}; + bool callback{false}; + + [[nodiscard]] bool matches_mask(const cvar_flags &rhs) const { + return (!rhs.archive || this->archive) && + (!rhs.notify || this->notify) && + (!rhs.server_info || this->server_info) && + (!rhs.user_info || this->user_info) && + (!rhs.changed || this->changed) && + (!rhs.rom || this->rom) && + (!rhs.locked || this->locked) && + (!rhs.registered || this->registered) && + (!rhs.callback || this->callback); + } +}; + +struct convar; + +typedef void (*cvarcallback_t)(convar *); + +using convar_view = std::ranges::elements_view >, 1>; + +struct convar { + std::string name{}; + const char *string{nullptr}; + cvar_flags flags{}; + float value{}; + const char *default_string{nullptr}; //johnfitz -- remember defaults for reset function + cvarcallback_t callback{nullptr}; + + convar(std::string_view name, const char *str); + + convar(std::string_view name, const char *str, cvar_flags flags); + + void inscribe(); + + void set_callback(cvarcallback_t func); + + void set(const std::string &new_value); + + void set_value(float new_value); + + static std::optional find_var(const std::string_view &desired); + + static std::optional find_var_after(const std::optional &prev_name, + std::optional with_flags); + + static void reset(const std::string &name); + + static void set(const std::string &name, const std::string &new_value); + + static void set_value(const std::string &name, float new_value); + + static std::optional complete_variable(const std::string_view &partial); + + static std::optional variable_value(const std::string_view &name); + + static std::optional variable_string(const std::string_view &name); + + static void lock_var(const std::string_view &name); + + static void unlock_var(const std::string_view &name); + + static void unlock_all(); + + static void set_rom(const std::string_view &name, std::string value); + + static void set_value_rom(const std::string_view &name, float value); + + static convar_view get_variables(); +}; + +qboolean Cvar_Command(void); + +void Cvar_WriteVariables(FILE *f); diff --git a/Quake/cvar.cpp b/Quake/cvar.cpp deleted file mode 100644 index 66a3136..0000000 --- a/Quake/cvar.cpp +++ /dev/null @@ -1,560 +0,0 @@ -/* -Copyright (C) 1996-2001 Id Software, Inc. -Copyright (C) 2002-2009 John Fitzgibbons and others -Copyright (C) 2010-2014 QuakeSpasm developers - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -See the GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - -*/ -// cvar.c -- dynamic variable tracking - -#include "quakedef.hpp" - -#include -#include -#include -#include -#include - -static cvar_t *cvar_vars; -static char cvar_null_string[] = ""; - -std::map CLIENT_VARIABLES{}; - -//============================================================================== -// -// USER COMMANDS -// -//============================================================================== - -void Cvar_Reset(const std::string &name); //johnfitz - -/* -============ -Cvar_List_f -- johnfitz -============ -*/ -void Cvar_List_f() { - cvar_t *cvar; - const char *partial; - int len, count; - - if (Cmd_Argc() > 1) { - partial = Cmd_Argv(1); - len = Q_strlen(partial); - } else { - partial = NULL; - len = 0; - } - - count = 0; - for (const auto &[name, var]: CLIENT_VARIABLES) { - if (partial && Q_strncmp(partial, name.c_str(), len)) { - continue; - } - Con_SafePrintf("%s%s %s \"%s\"\n", - (var->flags & CVAR_ARCHIVE) ? "*" : " ", - (var->flags & CVAR_NOTIFY) ? "s" : " ", - name.c_str(), - var->string); - count++; - } - - Con_SafePrintf("%i cvars", count); - if (partial) { - Con_SafePrintf(" beginning with \"%s\"", partial); - } - Con_SafePrintf("\n"); -} - -/* -============ -Cvar_Inc_f -- johnfitz -============ -*/ -void Cvar_Inc_f(void) { - switch (Cmd_Argc()) { - default: - case 1: - Con_Printf("inc [amount] : increment cvar\n"); - break; - case 2: - Cvar_SetValue(Cmd_Argv(1), Cvar_VariableValue(Cmd_Argv(1)) + 1); - break; - case 3: - Cvar_SetValue(Cmd_Argv(1), Cvar_VariableValue(Cmd_Argv(1)) + Q_atof(Cmd_Argv(2))); - break; - } -} - -/* -============ -Cvar_Toggle_f -- johnfitz -============ -*/ -void Cvar_Toggle_f(void) { - switch (Cmd_Argc()) { - default: - case 1: - Con_Printf("toggle : toggle cvar\n"); - break; - case 2: - if (Cvar_VariableValue(Cmd_Argv(1))) - Cvar_Set(Cmd_Argv(1), "0"); - else - Cvar_Set(Cmd_Argv(1), "1"); - break; - } -} - -/* -============ -Cvar_Cycle_f -- johnfitz -============ -*/ -void Cvar_Cycle_f() { - int i; - - if (Cmd_Argc() < 3) { - Con_Printf("cycle : cycle cvar through a list of values\n"); - return; - } - - //loop through the args until you find one that matches the current cvar value. - //yes, this will get stuck on a list that contains the same value twice. - //it's not worth dealing with, and i'm not even sure it can be dealt with. - for (i = 2; i < Cmd_Argc(); i++) { - //zero is assumed to be a string, even though it could actually be zero. The worst case - //is that the first time you call this command, it won't match on zero when it should, but after that, - //it will be comparing strings that all had the same source (the user) so it will work. - if (Q_atof(Cmd_Argv(i)) == 0) { - if (!strcmp(Cmd_Argv(i), Cvar_VariableString(Cmd_Argv(1)))) - break; - } else { - if (Q_atof(Cmd_Argv(i)) == Cvar_VariableValue(Cmd_Argv(1))) - break; - } - } - - if (i == Cmd_Argc()) - Cvar_Set(Cmd_Argv(1), Cmd_Argv(2)); // no match - else if (i + 1 == Cmd_Argc()) - Cvar_Set(Cmd_Argv(1), Cmd_Argv(2)); // matched last value in list - else - Cvar_Set(Cmd_Argv(1), Cmd_Argv(i + 1)); // matched earlier in list -} - -/* -============ -Cvar_Reset_f -- johnfitz -============ -*/ -void Cvar_Reset_f() { - switch (Cmd_Argc()) { - default: - case 1: - Con_Printf("reset : reset cvar to default\n"); - break; - case 2: - Cvar_Reset(Cmd_Argv(1)); - break; - } -} - -/* -============ -Cvar_ResetAll_f -- johnfitz -============ -*/ -void Cvar_ResetAll_f(void) { - cvar_t *var; - - for (auto name: std::views::keys(CLIENT_VARIABLES)) - Cvar_Reset(name); -} - -/* -============ -Cvar_ResetCfg_f -- QuakeSpasm -============ -*/ -void Cvar_ResetCfg_f() { - for (const auto &var: std::views::values(CLIENT_VARIABLES)) - if (var->flags & CVAR_ARCHIVE) Cvar_Reset(var->name); -} - -//============================================================================== -// -// INIT -// -//============================================================================== - -/* -============ -Cvar_Init -- johnfitz -============ -*/ - -void Cvar_Init() { - Cmd_AddCommand("cvarlist", Cvar_List_f); - Cmd_AddCommand("toggle", Cvar_Toggle_f); - Cmd_AddCommand("cycle", Cvar_Cycle_f); - Cmd_AddCommand("inc", Cvar_Inc_f); - Cmd_AddCommand("reset", Cvar_Reset_f); - Cmd_AddCommand("resetall", Cvar_ResetAll_f); - Cmd_AddCommand("resetcfg", Cvar_ResetCfg_f); -} - -//============================================================================== -// -// CVAR FUNCTIONS -// -//============================================================================== - -/* -============ -Cvar_FindVar -============ -*/ -std::optional Cvar_FindVar(const std::string &desired) { - for (auto &[name, var]: CLIENT_VARIABLES) { - if (name == desired) - return var; - } - - return std::nullopt; -} - -cvar_t *Cvar_FindVarAfter(const char *prev_name, unsigned int with_flags) { - // cvar_t *var; - // - // if (*prev_name) - // { - // var = Cvar_FindVar (prev_name); - // if (!var) - // return NULL; - // var = var->next; - // } - // else - // var = cvar_vars; - // - // // search for the next cvar matching the needed flags - // while (var) - // { - // if ((var->flags & with_flags) || !with_flags) - // break; - // var = var->next; - // } - // return var; - return nullptr; // TODO -} - -/* -============ -Cvar_LockVar -============ -*/ -void Cvar_LockVar(const std::string &name) { - if (const auto var = Cvar_FindVar(name); var.has_value()) - var.value()->flags |= CVAR_LOCKED; -} - -void Cvar_UnlockVar(const std::string &name) { - if (const auto var = Cvar_FindVar(name); var.has_value()) - var.value()->flags &= ~CVAR_LOCKED; -} - -void Cvar_UnlockAll() { - for (const auto &var: std::views::values(CLIENT_VARIABLES)) { - var->flags &= ~CVAR_LOCKED; - } -} - -/* -============ -Cvar_VariableValue -============ -*/ -float Cvar_VariableValue(const char *var_name) { - const auto var = Cvar_FindVar(var_name); - if (!var.has_value()) - return 0; - return std::strtof(var.value()->string, nullptr); -} - - -/* -============ -Cvar_VariableString -============ -*/ -const char *Cvar_VariableString(const char *var_name) { - const auto var = Cvar_FindVar(var_name); - if (!var.has_value()) - return cvar_null_string; - return var.value()->string; -} - - -/* -============ -Cvar_CompleteVariable -============ -*/ -std::optional Cvar_CompleteVariable(const std::string_view &partial) { - if (!partial.empty()) - return std::nullopt; - - // check functions - for (const auto &name: CLIENT_VARIABLES | std::views::keys) { - if (name.contains(name)) - return name; - } - - return std::nullopt; -} - -/* -============ -Cvar_Reset -- johnfitz -============ -*/ -void Cvar_Reset(const std::string &name) { - if (const auto var = Cvar_FindVar(name); !var.has_value()) - Con_Printf("variable \"%s\" not found\n", name.c_str()); - else - Cvar_SetQuick(var.value(), var.value()->default_string); -} - -void Cvar_SetQuick(cvar_t *var, const std::string &value) { - if (var->flags & (CVAR_ROM | CVAR_LOCKED)) - return; - if (!(var->flags & CVAR_REGISTERED)) - return; - - if (!var->string) - var->string = Z_Strdup(value.c_str()); - else { - int len; - - if (!strcmp(var->string, value.c_str())) - return; // no change - - var->flags |= CVAR_CHANGED; - len = value.length(); - if (len != Q_strlen(var->string)) { - Z_Free((void *) var->string); - var->string = (char *) Z_Malloc(len + 1); - } - memcpy((char *) var->string, value.c_str(), len + 1); - } - - var->value = Q_atof(var->string); - - //johnfitz -- save initial value for "reset" command - if (!var->default_string) - var->default_string = Z_Strdup(var->string); - //johnfitz -- during initialization, update default too - else if (!host_initialized) { - // Sys_Printf("changing default of %s: %s -> %s\n", - // var->name, var->default_string, var->string); - Z_Free((void *) var->default_string); - var->default_string = Z_Strdup(var->string); - } - //johnfitz - - if (var->callback) - var->callback(var); -} - -void Cvar_SetValueQuick(cvar_t *var, const float value) { - char val[32], *ptr = val; - - if (value == (float) ((int) value)) - q_snprintf(val, sizeof(val), "%i", (int) value); - else { - q_snprintf(val, sizeof(val), "%f", value); - // kill trailing zeroes - while (*ptr) - ptr++; - while (--ptr > val && *ptr == '0' && ptr[-1] != '.') - *ptr = '\0'; - } - - Cvar_SetQuick(var, val); -} - -/* -============ -Cvar_Set -============ -*/ -void Cvar_Set(const std::string &name, const std::string &value) { - auto var = Cvar_FindVar(name); - if (!var.has_value()) { - // there is an error in C code if this happens - Con_Printf("Cvar_Set: variable %s not found\n", name.c_str()); - return; - } - - Cvar_SetQuick(var.value(), value); -} - -/* -============ -Cvar_SetValue -============ -*/ -void Cvar_SetValue(const char *var_name, const float value) { - char val[32], *ptr = val; - - if (value == (float) ((int) value)) - q_snprintf(val, sizeof(val), "%i", (int) value); - else { - q_snprintf(val, sizeof(val), "%f", value); - // kill trailing zeroes - while (*ptr) - ptr++; - while (--ptr > val && *ptr == '0' && ptr[-1] != '.') - *ptr = '\0'; - } - - Cvar_Set(var_name, val); -} - -/* -============ -Cvar_SetROM -============ -*/ -void Cvar_SetROM(const char *var_name, const char *value) { - if (const auto var = Cvar_FindVar(var_name); var.has_value()) { - var.value()->flags &= ~CVAR_ROM; - Cvar_SetQuick(var.value(), value); - var.value()->flags |= CVAR_ROM; - } -} - -/* -============ -Cvar_SetValueROM -============ -*/ -void Cvar_SetValueROM(const char *var_name, const float value) { - if (const auto var = Cvar_FindVar(var_name); var.has_value()) { - var.value()->flags &= ~CVAR_ROM; - Cvar_SetValueQuick(var.value(), value); - var.value()->flags |= CVAR_ROM; - } -} - -/* -============ -Cvar_RegisterVariable - -Adds a freestanding variable to the variable list. -============ -*/ -void Cvar_RegisterVariable(cvar_t *variable) { - char value[512]; - qboolean set_rom; - cvar_t *cursor, *prev; //johnfitz -- sorted list insert - - // first check to see if it has already been defined - if (Cvar_FindVar(variable->name)) { - Con_Printf("Can't register variable %s, already defined\n", variable->name); - return; - } - - // check for overlap with a command - if (Cmd_Exists(variable->name)) { - Con_Printf("Cvar_RegisterVariable: %s is a command\n", variable->name); - return; - } - - CLIENT_VARIABLES.emplace(std::string(variable->name), variable); - - //johnfitz - variable->flags |= CVAR_REGISTERED; - - // copy the value off, because future sets will Z_Free it - std::strncpy(value, variable->string, sizeof(value)); - variable->string = NULL; - variable->default_string = NULL; - - if (!(variable->flags & CVAR_CALLBACK)) - variable->callback = NULL; - - // set it through the function to be consistent - set_rom = (variable->flags & CVAR_ROM); - variable->flags &= ~CVAR_ROM; - Cvar_SetQuick(variable, value); - if (set_rom) - variable->flags |= CVAR_ROM; -} - -/* -============ -Cvar_SetCallback - -Set a callback function to the var -============ -*/ -void Cvar_SetCallback(cvar_t *var, cvarcallback_t func) { - var->callback = func; - if (func) - var->flags |= CVAR_CALLBACK; - else var->flags &= ~CVAR_CALLBACK; -} - -/* -============ -Cvar_Command - -Handles variable inspection and changing from the console -============ -*/ -qboolean Cvar_Command() { - // check variables - auto var = Cvar_FindVar(Cmd_Argv(0)); - if (!var.has_value()) - return false; - - // perform a variable print or set - if (Cmd_Argc() == 1) { - Con_Printf("\"%s\" is \"%s\"\n", var.value()->name, var.value()->string); - return true; - } - - Cvar_Set(var.value()->name, Cmd_Argv(1)); - return true; -} - - -/* -============ -Cvar_WriteVariables - -Writes lines containing "set variable value" for all variables -with the archive flag set to true. -============ -*/ -void Cvar_WriteVariables(FILE *f) { - for (const auto &[name, var] : CLIENT_VARIABLES) { - if (var->flags & CVAR_ARCHIVE) - fprintf(f, "%s \"%s\"\n", name.c_str(), var->string); - } -} diff --git a/Quake/cvar.hpp b/Quake/cvar.hpp deleted file mode 100644 index 03b7ca9..0000000 --- a/Quake/cvar.hpp +++ /dev/null @@ -1,146 +0,0 @@ -/* -Copyright (C) 1996-2001 Id Software, Inc. -Copyright (C) 2002-2009 John Fitzgibbons and others -Copyright (C) 2010-2014 QuakeSpasm developers - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -See the GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - -*/ - -#ifndef __CVAR_H__ -#define __CVAR_H__ - -/* -cvar_t variables are used to hold scalar or string variables that can -be changed or displayed at the console or prog code as well as accessed -directly in C code. - -it is sufficient to initialize a cvar_t with just the first two fields, -or you can add a ,true flag for variables that you want saved to the -configuration file when the game is quit: - -cvar_t r_draworder = {"r_draworder","1"}; -cvar_t scr_screensize = {"screensize","1",true}; - -Cvars must be registered before use, or they will have a 0 value instead -of the float interpretation of the string. -Generally, all cvar_t declarations should be registered in the apropriate -init function before any console commands are executed: - -Cvar_RegisterVariable (&host_framerate); - - -C code usually just references a cvar in place: -if ( r_draworder.value ) - -It could optionally ask for the value to be looked up for a string name: -if (Cvar_VariableValue ("r_draworder")) - -Interpreted prog code can access cvars with the cvar(name) or -cvar_set (name, value) internal functions: -teamplay = cvar("teamplay"); -cvar_set ("registered", "1"); - -The user can access cvars from the console in two ways: -r_draworder prints the current value -r_draworder 0 sets the current value to 0 - -Cvars are restricted from having the same names as commands to keep this -interface from being ambiguous. - -*/ - -#define CVAR_NONE 0 -#define CVAR_ARCHIVE (1U << 0) // if set, causes it to be saved to config -#define CVAR_NOTIFY (1U << 1) // changes will be broadcasted to all players (q1) -#define CVAR_SERVERINFO (1U << 2) // added to serverinfo will be sent to clients (q1/net_dgrm.c and qwsv) -#define CVAR_USERINFO (1U << 3) // added to userinfo, will be sent to server (qwcl) -#define CVAR_CHANGED (1U << 4) -#define CVAR_ROM (1U << 6) -#define CVAR_LOCKED (1U << 8) // locked temporarily -#define CVAR_REGISTERED (1U << 10) // the var is added to the list of variables -#define CVAR_CALLBACK (1U << 16) // var has a callback - -#include -#include - -typedef void (*cvarcallback_t) (struct cvar_s *); - -typedef struct cvar_s -{ - const char *name; - const char *string; - unsigned int flags; - float value; - const char *default_string; //johnfitz -- remember defaults for reset function - cvarcallback_t callback; -} cvar_t; - -void Cvar_RegisterVariable (cvar_t *variable); -// registers a cvar that already has the name, string, and optionally -// the archive elements set. - -void Cvar_SetCallback (cvar_t *var, cvarcallback_t func); -// set a callback function to the var - -void Cvar_Set(const std::string &name, const std::string &value); -// equivelant to " " typed at the console - -void Cvar_SetValue (const char *var_name, const float value); -// expands value to a string and calls Cvar_Set - -void Cvar_SetROM (const char *var_name, const char *value); -void Cvar_SetValueROM (const char *var_name, const float value); -// sets a CVAR_ROM variable from within the engine - -void Cvar_SetQuick(cvar_t *var, const std::string &value); -void Cvar_SetValueQuick (cvar_t *var, const float value); -// these two accept a cvar pointer instead of a var name, -// but are otherwise identical to the "non-Quick" versions. -// the cvar MUST be registered. - -float Cvar_VariableValue (const char *var_name); -// returns 0 if not defined or non numeric - -const char *Cvar_VariableString (const char *var_name); -// returns an empty string if not defined - -qboolean Cvar_Command (void); -// called by Cmd_ExecuteString when Cmd_Argv(0) doesn't match a known -// command. Returns true if the command was a variable reference that -// was handled. (print or change) - -void Cvar_WriteVariables (FILE *f); -// Writes lines containing "set variable value" for all variables -// with the CVAR_ARCHIVE flag set - -std::optional Cvar_FindVar (const std::string &desired); -cvar_t *Cvar_FindVarAfter (const char *prev_name, unsigned int with_flags); - -void Cvar_LockVar(const std::string &name); -void Cvar_UnlockVar(const std::string &name); -void Cvar_UnlockAll (void); - -void Cvar_Init (void); - -const char *Cvar_CompleteVariable (const char *partial); -// attempts to match a partial variable name for command line completion -// returns NULL if nothing fits - -extern std::map CLIENT_VARIABLES; - -#endif /* __CVAR_H__ */ - diff --git a/Quake/gl_draw.cpp b/Quake/gl_draw.cpp index 2476380..4b59faf 100644 --- a/Quake/gl_draw.cpp +++ b/Quake/gl_draw.cpp @@ -27,7 +27,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. //extern unsigned char d_15to8table[65536]; //johnfitz -- never used -cvar_t scr_conalpha = {"scr_conalpha", "0.5", CVAR_ARCHIVE}; //johnfitz +convar scr_conalpha = {"scr_conalpha", "0.5", {.archive = true}}; //johnfitz qpic_t *draw_disc; qpic_t *draw_backtile; @@ -400,7 +400,7 @@ Draw_Init -- johnfitz -- rewritten */ void Draw_Init (void) { - Cvar_RegisterVariable (&scr_conalpha); + scr_conalpha.inscribe(); // clear scrap and allocate gltextures memset(scrap_allocated, 0, sizeof(scrap_allocated)); @@ -703,7 +703,7 @@ void GL_SetCanvas (canvastype newcanvas) glViewport (glx, gly, glwidth, glheight); break; case CANVAS_MENU: - s = q_min((float)glwidth / 320.0f, (float)glheight / 200.0f); + s = std::min((float)glwidth / 320.0f, (float)glheight / 200.0f); s = CLAMP (1.0f, scr_menuscale.value, s); // ericw -- doubled width to 640 to accommodate long keybindings glOrtho (0, 640, 200, 0, -99999, 99999); diff --git a/Quake/gl_fog.cpp b/Quake/gl_fog.cpp index 6972bc5..2ae42fc 100644 --- a/Quake/gl_fog.cpp +++ b/Quake/gl_fog.cpp @@ -21,6 +21,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //gl_fog.c -- global and volumetric fog +#include + #include "quakedef.hpp" //============================================================================== @@ -52,37 +54,32 @@ Fog_Update update internal variables ============= */ -void Fog_Update (float density, float red, float green, float blue, float time) -{ - //save previous settings for fade - if (time > 0) - { - //check for a fade in progress - if (fade_done > cl.time) - { - float f; +void Fog_Update(float density, float red, float green, float blue, float time) { + //save previous settings for fade + if (time > 0) { + //check for a fade in progress + if (fade_done > cl.time) { + float f; - f = (fade_done - cl.time) / fade_time; - old_density = f * old_density + (1.0 - f) * fog_density; - old_red = f * old_red + (1.0 - f) * fog_red; - old_green = f * old_green + (1.0 - f) * fog_green; - old_blue = f * old_blue + (1.0 - f) * fog_blue; - } - else - { - old_density = fog_density; - old_red = fog_red; - old_green = fog_green; - old_blue = fog_blue; - } - } + f = (fade_done - cl.time) / fade_time; + old_density = f * old_density + (1.0 - f) * fog_density; + old_red = f * old_red + (1.0 - f) * fog_red; + old_green = f * old_green + (1.0 - f) * fog_green; + old_blue = f * old_blue + (1.0 - f) * fog_blue; + } else { + old_density = fog_density; + old_red = fog_red; + old_green = fog_green; + old_blue = fog_blue; + } + } - fog_density = density; - fog_red = red; - fog_green = green; - fog_blue = blue; - fade_time = time; - fade_done = cl.time + time; + fog_density = density; + fog_red = red; + fog_green = green; + fog_blue = blue; + fade_time = time; + fade_done = cl.time + time; } /* @@ -92,18 +89,17 @@ Fog_ParseServerMessage handle an SVC_FOG message from server ============= */ -void Fog_ParseServerMessage (void) -{ - float density, red, green, blue, time; +void Fog_ParseServerMessage(void) { + float density, red, green, blue, time; - density = MSG_ReadByte() / 255.0; - red = MSG_ReadByte() / 255.0; - green = MSG_ReadByte() / 255.0; - blue = MSG_ReadByte() / 255.0; - time = MSG_ReadShort() / 100.0; - if (time < 0.0f) time = 0.0f; + density = MSG_ReadByte() / 255.0; + red = MSG_ReadByte() / 255.0; + green = MSG_ReadByte() / 255.0; + blue = MSG_ReadByte() / 255.0; + time = MSG_ReadShort() / 100.0; + if (time < 0.0f) time = 0.0f; - Fog_Update (density, red, green, blue, time); + Fog_Update(density, red, green, blue, time); } /* @@ -113,69 +109,67 @@ Fog_FogCommand_f handle the 'fog' console command ============= */ -void Fog_FogCommand_f (void) -{ - float d, r, g, b, t; +void Fog_FogCommand_f(void) { + float d, r, g, b, t; - switch (Cmd_Argc()) - { - default: - case 1: - Con_Printf("usage:\n"); - Con_Printf(" fog \n"); - Con_Printf(" fog \n"); - Con_Printf(" fog \n"); - Con_Printf("current values:\n"); - Con_Printf(" \"density\" is \"%f\"\n", fog_density); - Con_Printf(" \"red\" is \"%f\"\n", fog_red); - Con_Printf(" \"green\" is \"%f\"\n", fog_green); - Con_Printf(" \"blue\" is \"%f\"\n", fog_blue); - return; - case 2: - d = Q_atof(Cmd_Argv(1)); - t = 0.0f; - r = fog_red; - g = fog_green; - b = fog_blue; - break; - case 3: //TEST - d = Q_atof(Cmd_Argv(1)); - t = Q_atof(Cmd_Argv(2)); - r = fog_red; - g = fog_green; - b = fog_blue; - break; - case 4: - d = fog_density; - t = 0.0f; - r = Q_atof(Cmd_Argv(1)); - g = Q_atof(Cmd_Argv(2)); - b = Q_atof(Cmd_Argv(3)); - break; - case 5: - d = Q_atof(Cmd_Argv(1)); - r = Q_atof(Cmd_Argv(2)); - g = Q_atof(Cmd_Argv(3)); - b = Q_atof(Cmd_Argv(4)); - t = 0.0f; - break; - case 6: //TEST - d = Q_atof(Cmd_Argv(1)); - r = Q_atof(Cmd_Argv(2)); - g = Q_atof(Cmd_Argv(3)); - b = Q_atof(Cmd_Argv(4)); - t = Q_atof(Cmd_Argv(5)); - break; - } + switch (command::argc()) { + default: + case 1: + Con_Printf("usage:\n"); + Con_Printf(" fog \n"); + Con_Printf(" fog \n"); + Con_Printf(" fog \n"); + Con_Printf("current values:\n"); + Con_Printf(" \"density\" is \"%f\"\n", fog_density); + Con_Printf(" \"red\" is \"%f\"\n", fog_red); + Con_Printf(" \"green\" is \"%f\"\n", fog_green); + Con_Printf(" \"blue\" is \"%f\"\n", fog_blue); + return; + case 2: + d = Q_atof(command::argv(1)->c_str()); + t = 0.0f; + r = fog_red; + g = fog_green; + b = fog_blue; + break; + case 3: //TEST + d = Q_atof(command::argv(1)->c_str()); + t = Q_atof(command::argv(2)->c_str()); + r = fog_red; + g = fog_green; + b = fog_blue; + break; + case 4: + d = fog_density; + t = 0.0f; + r = Q_atof(command::argv(1)->c_str()); + g = Q_atof(command::argv(2)->c_str()); + b = Q_atof(command::argv(3)->c_str()); + break; + case 5: + d = Q_atof(command::argv(1)->c_str()); + r = Q_atof(command::argv(2)->c_str()); + g = Q_atof(command::argv(3)->c_str()); + b = Q_atof(command::argv(4)->c_str()); + t = 0.0f; + break; + case 6: //TEST + d = Q_atof(command::argv(1)->c_str()); + r = Q_atof(command::argv(2)->c_str()); + g = Q_atof(command::argv(3)->c_str()); + b = Q_atof(command::argv(4)->c_str()); + t = Q_atof(command::argv(5)->c_str()); + break; + } - if (d < 0.0f) d = 0.0f; - if (r < 0.0f) r = 0.0f; - else if (r > 1.0f) r = 1.0f; - if (g < 0.0f) g = 0.0f; - else if (g > 1.0f) g = 1.0f; - if (b < 0.0f) b = 0.0f; - else if (b > 1.0f) b = 1.0f; - Fog_Update(d, r, g, b, t); + if (d < 0.0f) d = 0.0f; + if (r < 0.0f) r = 0.0f; + else if (r > 1.0f) r = 1.0f; + if (g < 0.0f) g = 0.0f; + else if (g > 1.0f) g = 1.0f; + if (b < 0.0f) b = 0.0f; + else if (b > 1.0f) b = 1.0f; + Fog_Update(d, r, g, b, t); } /* @@ -185,53 +179,61 @@ Fog_ParseWorldspawn called at map load ============= */ -void Fog_ParseWorldspawn (void) -{ - char key[128], value[4096]; - const char *data; +void Fog_ParseWorldspawn() { + std::string key{}; + std::string value{}; - //initially no fog - fog_density = DEFAULT_DENSITY; - fog_red = DEFAULT_GRAY; - fog_green = DEFAULT_GRAY; - fog_blue = DEFAULT_GRAY; + //initially no fog + fog_density = DEFAULT_DENSITY; + fog_red = DEFAULT_GRAY; + fog_green = DEFAULT_GRAY; + fog_blue = DEFAULT_GRAY; - old_density = DEFAULT_DENSITY; - old_red = DEFAULT_GRAY; - old_green = DEFAULT_GRAY; - old_blue = DEFAULT_GRAY; + old_density = DEFAULT_DENSITY; + old_red = DEFAULT_GRAY; + old_green = DEFAULT_GRAY; + old_blue = DEFAULT_GRAY; - fade_time = 0.0; - fade_done = 0.0; + fade_time = 0.0; + fade_done = 0.0; - data = COM_Parse(cl.worldmodel->entities); - if (!data) - return; // error - if (com_token[0] != '{') - return; // error - while (1) - { - data = COM_Parse(data); - if (!data) - return; // error - if (com_token[0] == '}') - break; // end of worldspawn - if (com_token[0] == '_') - q_strlcpy(key, com_token + 1, sizeof(key)); - else - q_strlcpy(key, com_token, sizeof(key)); - while (key[0] && key[strlen(key)-1] == ' ') // remove trailing spaces - key[strlen(key)-1] = 0; - data = COM_ParseEx(data, CPE_ALLOWTRUNC); - if (!data) - return; // error - q_strlcpy(value, com_token, sizeof(value)); + std::istringstream ss{cl.worldmodel->entities}; - if (!strcmp("fog", key)) - { - sscanf(value, "%f %f %f %f", &fog_density, &fog_red, &fog_green, &fog_blue); - } - } + auto token = common::parse_token(ss); + if (!token.has_value()) { + return; // error + } + if (token->front() != '{') { + return; // error + } + while (true) { + token = common::parse_token(ss); + if (!token.has_value()) { + return; // error + } + if (token->front() == '}') { + break; // end of worldspawn + } + if (token->front() == '_') { + key = token->substr(1); + } else { + key = token.value(); + } + + while (!key.empty() && key.back() == ' ') { + key.pop_back(); + } + + token = common::parse_token(ss); + if (!token.has_value()) { + return; // error + } + value = token.value(); + + if (key == "fog") { + std::sscanf(value.c_str(), "%f %f %f %f", &fog_density, &fog_red, &fog_green, &fog_blue); + } + } } /* @@ -241,38 +243,34 @@ Fog_GetColor calculates fog color for this frame, taking into account fade times ============= */ -float *Fog_GetColor (void) -{ - static float c[4]; - float f; - int i; +float *Fog_GetColor(void) { + static float c[4]; + float f; + int i; - if (fade_done > cl.time) - { - f = (fade_done - cl.time) / fade_time; - c[0] = f * old_red + (1.0 - f) * fog_red; - c[1] = f * old_green + (1.0 - f) * fog_green; - c[2] = f * old_blue + (1.0 - f) * fog_blue; - c[3] = 1.0; - } - else - { - c[0] = fog_red; - c[1] = fog_green; - c[2] = fog_blue; - c[3] = 1.0; - } + if (fade_done > cl.time) { + f = (fade_done - cl.time) / fade_time; + c[0] = f * old_red + (1.0 - f) * fog_red; + c[1] = f * old_green + (1.0 - f) * fog_green; + c[2] = f * old_blue + (1.0 - f) * fog_blue; + c[3] = 1.0; + } else { + c[0] = fog_red; + c[1] = fog_green; + c[2] = fog_blue; + c[3] = 1.0; + } - for (i = 0; i < 3; i++) { - c[i] = CLAMP (0.f, c[i], 1.f); - } + for (i = 0; i < 3; i++) { + c[i] = CLAMP(0.f, c[i], 1.f); + } - //find closest 24-bit RGB value, so solid-colored sky can match the fog perfectly - for (i = 0; i < 3; i++) { - c[i] = (float)(Q_rint(c[i] * 255)) / 255.0f; - } + //find closest 24-bit RGB value, so solid-colored sky can match the fog perfectly + for (i = 0; i < 3; i++) { + c[i] = (float) (Q_rint(c[i] * 255)) / 255.0f; + } - return c; + return c; } /* @@ -282,17 +280,14 @@ Fog_GetDensity returns current density of fog ============= */ -float Fog_GetDensity (void) -{ - float f; +float Fog_GetDensity(void) { + float f; - if (fade_done > cl.time) - { - f = (fade_done - cl.time) / fade_time; - return f * old_density + (1.0 - f) * fog_density; - } - else - return fog_density; + if (fade_done > cl.time) { + f = (fade_done - cl.time) / fade_time; + return f * old_density + (1.0 - f) * fog_density; + } else + return fog_density; } /* @@ -302,10 +297,9 @@ Fog_SetupFrame called at the beginning of each frame ============= */ -void Fog_SetupFrame (void) -{ - glFogfv(GL_FOG_COLOR, Fog_GetColor()); - glFogf(GL_FOG_DENSITY, Fog_GetDensity() / 64.0); +void Fog_SetupFrame(void) { + glFogfv(GL_FOG_COLOR, Fog_GetColor()); + glFogf(GL_FOG_DENSITY, Fog_GetDensity() / 64.0); } /* @@ -315,10 +309,9 @@ Fog_EnableGFog called before drawing stuff that should be fogged ============= */ -void Fog_EnableGFog (void) -{ - if (Fog_GetDensity() > 0) - glEnable(GL_FOG); +void Fog_EnableGFog(void) { + if (Fog_GetDensity() > 0) + glEnable(GL_FOG); } /* @@ -328,10 +321,9 @@ Fog_DisableGFog called after drawing stuff that should be fogged ============= */ -void Fog_DisableGFog (void) -{ - if (Fog_GetDensity() > 0) - glDisable(GL_FOG); +void Fog_DisableGFog(void) { + if (Fog_GetDensity() > 0) + glDisable(GL_FOG); } /* @@ -341,12 +333,11 @@ Fog_StartAdditive called before drawing stuff that is additive blended -- sets fog color to black ============= */ -void Fog_StartAdditive (void) -{ - vec3_t color = {0,0,0}; +void Fog_StartAdditive(void) { + vec3_t color = {0, 0, 0}; - if (Fog_GetDensity() > 0) - glFogfv(GL_FOG_COLOR, color); + if (Fog_GetDensity() > 0) + glFogfv(GL_FOG_COLOR, color); } /* @@ -356,10 +347,9 @@ Fog_StopAdditive called after drawing stuff that is additive blended -- restores fog color ============= */ -void Fog_StopAdditive (void) -{ - if (Fog_GetDensity() > 0) - glFogfv(GL_FOG_COLOR, Fog_GetColor()); +void Fog_StopAdditive(void) { + if (Fog_GetDensity() > 0) + glFogfv(GL_FOG_COLOR, Fog_GetColor()); } //============================================================================== @@ -368,10 +358,13 @@ void Fog_StopAdditive (void) // //============================================================================== -cvar_t r_vfog = {"r_vfog", "1", CVAR_NONE}; +convar r_vfog{"r_vfog", "1"}; -void Fog_DrawVFog (void){} -void Fog_MarkModels (void){} +void Fog_DrawVFog(void) { +} + +void Fog_MarkModels(void) { +} //============================================================================== // @@ -386,10 +379,9 @@ Fog_NewMap called whenever a map is loaded ============= */ -void Fog_NewMap (void) -{ - Fog_ParseWorldspawn (); //for global fog - Fog_MarkModels (); //for volumetric fog +void Fog_NewMap(void) { + Fog_ParseWorldspawn(); //for global fog + Fog_MarkModels(); //for volumetric fog } /* @@ -399,29 +391,27 @@ Fog_Init called when quake initializes ============= */ -void Fog_Init (void) -{ - Cmd_AddCommand ("fog",Fog_FogCommand_f); +void Fog_Init(void) { + command::add("fog", Fog_FogCommand_f); - //Cvar_RegisterVariable (&r_vfog); + //r_vfog.inscribe(); - //set up global fog - fog_density = DEFAULT_DENSITY; - fog_red = DEFAULT_GRAY; - fog_green = DEFAULT_GRAY; - fog_blue = DEFAULT_GRAY; + //set up global fog + fog_density = DEFAULT_DENSITY; + fog_red = DEFAULT_GRAY; + fog_green = DEFAULT_GRAY; + fog_blue = DEFAULT_GRAY; - Fog_SetupState (); + Fog_SetupState(); } /* ============= Fog_SetupState - + ericw -- moved from Fog_Init, state that needs to be setup when a new context is created ============= */ -void Fog_SetupState (void) -{ - glFogi(GL_FOG_MODE, GL_EXP2); +void Fog_SetupState(void) { + glFogi(GL_FOG_MODE, GL_EXP2); } diff --git a/Quake/gl_model.cpp b/Quake/gl_model.cpp index 958928a..1d0f415 100644 --- a/Quake/gl_model.cpp +++ b/Quake/gl_model.cpp @@ -36,8 +36,8 @@ static qmodel_t *Mod_LoadModel (qmodel_t *mod, qboolean crash); static void Mod_Print (void); -static cvar_t external_ents = {"external_ents", "1", CVAR_ARCHIVE}; -static cvar_t external_vis = {"external_vis", "1", CVAR_ARCHIVE}; +static convar external_ents = {"external_ents", "1", {.archive = true}}; +static convar external_vis = {"external_vis", "1", {.archive = true}}; static byte *mod_novis; static int mod_novis_capacity; @@ -59,11 +59,11 @@ Mod_Init */ void Mod_Init (void) { - Cvar_RegisterVariable (&gl_subdivide_size); - Cvar_RegisterVariable (&external_vis); - Cvar_RegisterVariable (&external_ents); + gl_subdivide_size.inscribe(); + external_vis.inscribe(); + external_ents.inscribe(); - Cmd_AddCommand ("mcache", Mod_Print); + command::add ("mcache", Mod_Print); //johnfitz -- create notexture miptex r_notexture_mip = (texture_t *) Hunk_AllocName (sizeof(texture_t), "r_notexture_mip"); @@ -525,7 +525,7 @@ static void Mod_LoadTextures (lump_t *l) if (((byte*)(mt+1) + pixels) > (mod_base + l->fileofs + l->filelen)) { Con_DPrintf("Texture %s extends past end of lump\n", mt->name); - pixels = q_max(0L, (long)((mod_base + l->fileofs + l->filelen) - (byte*)(mt+1))); + pixels = std::max(0L, (long)((mod_base + l->fileofs + l->filelen) - (byte*)(mt+1))); } tx->update_warp = false; //johnfitz @@ -2054,21 +2054,21 @@ static void Mod_BoundsFromClipNode (qmodel_t *mod, int hull, int nodenum) case PLANE_X: if (plane->signbits == 1) - mod->clipmins[0] = q_min(mod->clipmins[0], -plane->dist - mod->hulls[hull].clip_mins[0]); + mod->clipmins[0] = std::min(mod->clipmins[0], -plane->dist - mod->hulls[hull].clip_mins[0]); else - mod->clipmaxs[0] = q_max(mod->clipmaxs[0], plane->dist - mod->hulls[hull].clip_maxs[0]); + mod->clipmaxs[0] = std::max(mod->clipmaxs[0], plane->dist - mod->hulls[hull].clip_maxs[0]); break; case PLANE_Y: if (plane->signbits == 2) - mod->clipmins[1] = q_min(mod->clipmins[1], -plane->dist - mod->hulls[hull].clip_mins[1]); + mod->clipmins[1] = std::min(mod->clipmins[1], -plane->dist - mod->hulls[hull].clip_mins[1]); else - mod->clipmaxs[1] = q_max(mod->clipmaxs[1], plane->dist - mod->hulls[hull].clip_maxs[1]); + mod->clipmaxs[1] = std::max(mod->clipmaxs[1], plane->dist - mod->hulls[hull].clip_maxs[1]); break; case PLANE_Z: if (plane->signbits == 4) - mod->clipmins[2] = q_min(mod->clipmins[2], -plane->dist - mod->hulls[hull].clip_mins[2]); + mod->clipmins[2] = std::min(mod->clipmins[2], -plane->dist - mod->hulls[hull].clip_mins[2]); else - mod->clipmaxs[2] = q_max(mod->clipmaxs[2], plane->dist - mod->hulls[hull].clip_maxs[2]); + mod->clipmaxs[2] = std::max(mod->clipmaxs[2], plane->dist - mod->hulls[hull].clip_maxs[2]); break; default: //skip nonaxial planes; don't need them @@ -2648,8 +2648,8 @@ static void Mod_CalcAliasBounds (aliashdr_t *a) for (k=0; k<3;k++) { - loadmodel->mins[k] = q_min(loadmodel->mins[k], v[k]); - loadmodel->maxs[k] = q_max(loadmodel->maxs[k], v[k]); + loadmodel->mins[k] = std::min(loadmodel->mins[k], v[k]); + loadmodel->maxs[k] = std::max(loadmodel->maxs[k], v[k]); } dist = v[0] * v[0] + v[1] * v[1]; if (yawradius < dist) @@ -2711,7 +2711,7 @@ Mod_SetExtraFlags -- johnfitz -- set up extra flags that aren't in the mdl */ void Mod_SetExtraFlags (qmodel_t *mod) { - extern cvar_t r_nolerp_list, r_noshadow_list; + extern convar r_nolerp_list, r_noshadow_list; if (!mod || mod->type != mod_alias) return; diff --git a/Quake/gl_refrag.cpp b/Quake/gl_refrag.cpp index 6047ee5..7b00857 100644 --- a/Quake/gl_refrag.cpp +++ b/Quake/gl_refrag.cpp @@ -155,7 +155,7 @@ void R_CheckEfrags (void) Con_DWarning ("%i efrags exceeds standard limit of 640.\n", cl.num_efrags); dev_stats.efrags = cl.num_efrags; - dev_peakstats.efrags = q_max(cl.num_efrags, dev_peakstats.efrags); + dev_peakstats.efrags = std::max(cl.num_efrags, dev_peakstats.efrags); } /* diff --git a/Quake/gl_rlight.cpp b/Quake/gl_rlight.cpp index a02a647..4ce9cd9 100644 --- a/Quake/gl_rlight.cpp +++ b/Quake/gl_rlight.cpp @@ -25,7 +25,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. static int r_dlightframecount; -extern cvar_t r_flatlightstyles; //johnfitz +extern convar r_flatlightstyles; //johnfitz /* ================== @@ -359,7 +359,7 @@ loc0: // caused by overlapping surfaces with mixed lighting data. const float nearby = 8.f; dist += nearby; - *maxdist = q_min(*maxdist, dist); + *maxdist = std::min(*maxdist, dist); continue; } diff --git a/Quake/gl_rmain.cpp b/Quake/gl_rmain.cpp index 3a75fc9..a1c59d1 100644 --- a/Quake/gl_rmain.cpp +++ b/Quake/gl_rmain.cpp @@ -23,13 +23,13 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.hpp" -vec3_t modelorg, r_entorigin; -entity_t *currententity; +vec3_t modelorg, r_entorigin; +entity_t *currententity; -int r_visframecount; // bumped when going to a new PVS -int r_framecount; // used for dlight push checking +int r_visframecount; // bumped when going to a new PVS +int r_framecount; // used for dlight push checking -mplane_t frustum[4]; +mplane_t frustum[4]; //johnfitz -- rendering statistics int rs_brushpolys, rs_aliaspolys, rs_skypolys; @@ -38,79 +38,85 @@ int rs_dynamiclightmaps, rs_brushpasses, rs_aliaspasses, rs_skypasses; // // view origin // -vec3_t vup; -vec3_t vpn; -vec3_t vright; -vec3_t r_origin; +vec3_t vup; +vec3_t vpn; +vec3_t vright; +vec3_t r_origin; float r_fovx, r_fovy; //johnfitz -- rendering fov may be different becuase of r_waterwarp and r_stereo // // screen size info // -refdef_t r_refdef; +refdef_t r_refdef; -mleaf_t *r_viewleaf, *r_oldviewleaf; +mleaf_t *r_viewleaf, *r_oldviewleaf; -int d_lightstylevalue[256]; // 8.8 fraction of base light value +int d_lightstylevalue[256]; // 8.8 fraction of base light value -cvar_t r_norefresh = {"r_norefresh","0",CVAR_NONE}; -cvar_t r_drawentities = {"r_drawentities","1",CVAR_NONE}; -cvar_t r_drawviewmodel = {"r_drawviewmodel","1",CVAR_NONE}; -cvar_t r_speeds = {"r_speeds","0",CVAR_NONE}; -cvar_t r_pos = {"r_pos","0",CVAR_NONE}; -cvar_t r_fullbright = {"r_fullbright","0",CVAR_NONE}; -cvar_t r_lightmap = {"r_lightmap","0",CVAR_NONE}; -cvar_t r_shadows = {"r_shadows","0",CVAR_ARCHIVE}; -cvar_t r_wateralpha = {"r_wateralpha","1",CVAR_ARCHIVE}; -cvar_t r_litwater = {"r_litwater","1",CVAR_NONE}; -cvar_t r_dynamic = {"r_dynamic","1",CVAR_ARCHIVE}; -cvar_t r_novis = {"r_novis","0",CVAR_ARCHIVE}; +convar r_norefresh{"r_norefresh", "0"}; +convar r_drawentities{"r_drawentities", "1"}; +convar r_drawviewmodel{"r_drawviewmodel", "1"}; +convar r_speeds{"r_speeds", "0"}; +convar r_pos{"r_pos", "0"}; +convar r_fullbright{"r_fullbright", "0"}; +convar r_lightmap{"r_lightmap", "0"}; +convar r_shadows{"r_shadows", "0", {.archive = true}}; +convar r_wateralpha{"r_wateralpha", "1", {.archive = true}}; +convar r_litwater{"r_litwater", "1"}; +convar r_dynamic{"r_dynamic", "1", {.archive = true}}; +convar r_novis{"r_novis", "0", {.archive = true}}; -cvar_t gl_finish = {"gl_finish","0",CVAR_NONE}; -cvar_t gl_clear = {"gl_clear","1",CVAR_NONE}; -cvar_t gl_cull = {"gl_cull","1",CVAR_NONE}; -cvar_t gl_smoothmodels = {"gl_smoothmodels","1",CVAR_NONE}; -cvar_t gl_affinemodels = {"gl_affinemodels","0",CVAR_NONE}; -cvar_t gl_polyblend = {"gl_polyblend","1",CVAR_NONE}; -cvar_t gl_flashblend = {"gl_flashblend","0",CVAR_ARCHIVE}; -cvar_t gl_playermip = {"gl_playermip","0",CVAR_NONE}; -cvar_t gl_nocolors = {"gl_nocolors","0",CVAR_NONE}; +convar gl_finish{"gl_finish", "0"}; +convar gl_clear{"gl_clear", "1"}; +convar gl_cull{"gl_cull", "1"}; +convar gl_smoothmodels{"gl_smoothmodels", "1"}; +convar gl_affinemodels{"gl_affinemodels", "0"}; +convar gl_polyblend{"gl_polyblend", "1"}; +convar gl_flashblend{"gl_flashblend", "0", {.archive = true}}; +convar gl_playermip{"gl_playermip", "0"}; +convar gl_nocolors{"gl_nocolors", "0"}; //johnfitz -- new cvars -cvar_t r_stereo = {"r_stereo","0",CVAR_NONE}; -cvar_t r_stereodepth = {"r_stereodepth","128",CVAR_NONE}; -cvar_t r_clearcolor = {"r_clearcolor","2",CVAR_ARCHIVE}; -cvar_t r_drawflat = {"r_drawflat","0",CVAR_NONE}; -cvar_t r_flatlightstyles = {"r_flatlightstyles", "0", CVAR_NONE}; -cvar_t gl_fullbrights = {"gl_fullbrights", "1", CVAR_ARCHIVE}; -cvar_t gl_farclip = {"gl_farclip", "65536", CVAR_ARCHIVE}; -cvar_t gl_overbright = {"gl_overbright", "1", CVAR_ARCHIVE}; -cvar_t gl_overbright_models = {"gl_overbright_models", "1", CVAR_ARCHIVE}; -cvar_t r_oldskyleaf = {"r_oldskyleaf", "0", CVAR_NONE}; -cvar_t r_drawworld = {"r_drawworld", "1", CVAR_NONE}; -cvar_t r_showtris = {"r_showtris", "0", CVAR_NONE}; -cvar_t r_showbboxes = {"r_showbboxes", "0", CVAR_NONE}; -cvar_t r_lerpmodels = {"r_lerpmodels", "1", CVAR_NONE}; -cvar_t r_lerpmove = {"r_lerpmove", "1", CVAR_NONE}; -cvar_t r_nolerp_list = {"r_nolerp_list", "progs/flame.mdl,progs/flame2.mdl,progs/braztall.mdl,progs/brazshrt.mdl,progs/longtrch.mdl,progs/flame_pyre.mdl,progs/v_saw.mdl,progs/v_xfist.mdl,progs/h2stuff/newfire.mdl", CVAR_NONE}; -cvar_t r_noshadow_list = {"r_noshadow_list", "progs/flame2.mdl,progs/flame.mdl,progs/bolt1.mdl,progs/bolt2.mdl,progs/bolt3.mdl,progs/laser.mdl", CVAR_NONE}; +convar r_stereo{"r_stereo", "0"}; +convar r_stereodepth{"r_stereodepth", "128"}; +convar r_clearcolor{"r_clearcolor", "2", {.archive = true}}; +convar r_drawflat{"r_drawflat", "0"}; +convar r_flatlightstyles{"r_flatlightstyles", "0"}; +convar gl_fullbrights{"gl_fullbrights", "1", {.archive = true}}; +convar gl_farclip{"gl_farclip", "65536", {.archive = true}}; +convar gl_overbright{"gl_overbright", "1", {.archive = true}}; +convar gl_overbright_models{"gl_overbright_models", "1", {.archive = true}}; +convar r_oldskyleaf{"r_oldskyleaf", "0"}; +convar r_drawworld{"r_drawworld", "1"}; +convar r_showtris{"r_showtris", "0"}; +convar r_showbboxes{"r_showbboxes", "0"}; +convar r_lerpmodels{"r_lerpmodels", "1"}; +convar r_lerpmove{"r_lerpmove", "1"}; +convar r_nolerp_list{ + "r_nolerp_list", + "progs/flame.mdl,progs/flame2.mdl,progs/braztall.mdl,progs/brazshrt.mdl,progs/longtrch.mdl,progs/flame_pyre.mdl,progs/v_saw.mdl,progs/v_xfist.mdl,progs/h2stuff/newfire.mdl" +}; +convar r_noshadow_list{ + "r_noshadow_list", + "progs/flame2.mdl,progs/flame.mdl,progs/bolt1.mdl,progs/bolt2.mdl,progs/bolt3.mdl,progs/laser.mdl" +}; -extern cvar_t r_vfog; +extern convar r_vfog; //johnfitz -cvar_t gl_zfix = {"gl_zfix", "0", CVAR_NONE}; // QuakeSpasm z-fighting fix +convar gl_zfix{"gl_zfix", "0"}; // QuakeSpasm z-fighting fix -cvar_t r_lavaalpha = {"r_lavaalpha","0",CVAR_NONE}; -cvar_t r_telealpha = {"r_telealpha","0",CVAR_NONE}; -cvar_t r_slimealpha = {"r_slimealpha","0",CVAR_NONE}; +convar r_lavaalpha{"r_lavaalpha", "0"}; +convar r_telealpha{"r_telealpha", "0"}; +convar r_slimealpha{"r_slimealpha", "0"}; -float map_wateralpha, map_lavaalpha, map_telealpha, map_slimealpha; +float map_wateralpha, map_lavaalpha, map_telealpha, map_slimealpha; qboolean r_drawflat_cheatsafe, r_fullbright_cheatsafe, r_lightmap_cheatsafe, r_drawworld_cheatsafe; //johnfitz -cvar_t r_scale = {"r_scale", "1", CVAR_ARCHIVE}; +convar r_scale{"r_scale", "1", {.archive = true}}; //============================================================================== // @@ -123,20 +129,19 @@ static GLuint r_gamma_program; static int r_gamma_texture_width, r_gamma_texture_height; // uniforms used in gamma shader -static GLint gammaLoc; -static GLint contrastLoc; -static GLint textureLoc; +static GLint gammaLoc; +static GLint contrastLoc; +static GLint textureLoc; /* ============= GLSLGamma_DeleteTexture ============= */ -void GLSLGamma_DeleteTexture (void) -{ - glDeleteTextures (1, &r_gamma_texture); - r_gamma_texture = 0; - r_gamma_program = 0; // deleted in R_DeleteShaders +void GLSLGamma_DeleteTexture(void) { + glDeleteTextures(1, &r_gamma_texture); + r_gamma_texture = 0; + r_gamma_program = 0; // deleted in R_DeleteShaders } /* @@ -144,38 +149,37 @@ void GLSLGamma_DeleteTexture (void) GLSLGamma_CreateShaders ============= */ -static void GLSLGamma_CreateShaders (void) -{ - const GLchar *vertSource = \ - "#version 110\n" - "\n" - "void main(void) {\n" - " gl_Position = vec4(gl_Vertex.xy, 0.0, 1.0);\n" - " gl_TexCoord[0] = gl_MultiTexCoord0;\n" - "}\n"; +static void GLSLGamma_CreateShaders(void) { + const GLchar *vertSource = + "#version 110\n" + "\n" + "void main(void) {\n" + " gl_Position = vec4(gl_Vertex.xy, 0.0, 1.0);\n" + " gl_TexCoord[0] = gl_MultiTexCoord0;\n" + "}\n"; - const GLchar *fragSource = \ - "#version 110\n" - "\n" - "uniform sampler2D GammaTexture;\n" - "uniform float GammaValue;\n" - "uniform float ContrastValue;\n" - "\n" - "void main(void) {\n" - " vec4 frag = texture2D(GammaTexture, gl_TexCoord[0].xy);\n" - " frag.rgb = frag.rgb * ContrastValue;\n" - " gl_FragColor = vec4(pow(frag.rgb, vec3(GammaValue)), 1.0);\n" - "}\n"; + const GLchar *fragSource = + "#version 110\n" + "\n" + "uniform sampler2D GammaTexture;\n" + "uniform float GammaValue;\n" + "uniform float ContrastValue;\n" + "\n" + "void main(void) {\n" + " vec4 frag = texture2D(GammaTexture, gl_TexCoord[0].xy);\n" + " frag.rgb = frag.rgb * ContrastValue;\n" + " gl_FragColor = vec4(pow(frag.rgb, vec3(GammaValue)), 1.0);\n" + "}\n"; - if (!gl_glsl_gamma_able) - return; + if (!gl_glsl_gamma_able) + return; - r_gamma_program = GL_CreateProgram (vertSource, fragSource, 0, NULL); + r_gamma_program = GL_CreateProgram(vertSource, fragSource, 0, NULL); -// get uniform locations - gammaLoc = GL_GetUniformLocation (&r_gamma_program, "GammaValue"); - contrastLoc = GL_GetUniformLocation (&r_gamma_program, "ContrastValue"); - textureLoc = GL_GetUniformLocation (&r_gamma_program, "GammaTexture"); + // get uniform locations + gammaLoc = GL_GetUniformLocation(&r_gamma_program, "GammaValue"); + contrastLoc = GL_GetUniformLocation(&r_gamma_program, "ContrastValue"); + textureLoc = GL_GetUniformLocation(&r_gamma_program, "GammaTexture"); } /* @@ -183,80 +187,76 @@ static void GLSLGamma_CreateShaders (void) GLSLGamma_GammaCorrect ============= */ -void GLSLGamma_GammaCorrect (void) -{ - float smax, tmax; +void GLSLGamma_GammaCorrect(void) { + float smax, tmax; - if (!gl_glsl_gamma_able) - return; + if (!gl_glsl_gamma_able) + return; - if (vid_gamma.value == 1 && vid_contrast.value == 1) - return; + if (vid_gamma.value == 1 && vid_contrast.value == 1) + return; -// create render-to-texture texture if needed - if (!r_gamma_texture) - { - glGenTextures (1, &r_gamma_texture); - glBindTexture (GL_TEXTURE_2D, r_gamma_texture); + // create render-to-texture texture if needed + if (!r_gamma_texture) { + glGenTextures(1, &r_gamma_texture); + glBindTexture(GL_TEXTURE_2D, r_gamma_texture); - r_gamma_texture_width = glwidth; - r_gamma_texture_height = glheight; + r_gamma_texture_width = glwidth; + r_gamma_texture_height = glheight; - if (!gl_texture_NPOT) - { - r_gamma_texture_width = TexMgr_Pad(r_gamma_texture_width); - r_gamma_texture_height = TexMgr_Pad(r_gamma_texture_height); - } + if (!gl_texture_NPOT) { + r_gamma_texture_width = TexMgr_Pad(r_gamma_texture_width); + r_gamma_texture_height = TexMgr_Pad(r_gamma_texture_height); + } - glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA8, r_gamma_texture_width, r_gamma_texture_height, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, NULL); - glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - } + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, r_gamma_texture_width, r_gamma_texture_height, 0, GL_BGRA, + GL_UNSIGNED_INT_8_8_8_8_REV, NULL); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + } -// create shader if needed - if (!r_gamma_program) - { - GLSLGamma_CreateShaders (); - if (!r_gamma_program) - { - Sys_Error("GLSLGamma_CreateShaders failed"); - } - } + // create shader if needed + if (!r_gamma_program) { + GLSLGamma_CreateShaders(); + if (!r_gamma_program) { + Sys_Error("GLSLGamma_CreateShaders failed"); + } + } -// copy the framebuffer to the texture - GL_DisableMultitexture(); - glBindTexture (GL_TEXTURE_2D, r_gamma_texture); - glCopyTexSubImage2D (GL_TEXTURE_2D, 0, 0, 0, glx, gly, glwidth, glheight); + // copy the framebuffer to the texture + GL_DisableMultitexture(); + glBindTexture(GL_TEXTURE_2D, r_gamma_texture); + glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, glx, gly, glwidth, glheight); -// draw the texture back to the framebuffer with a fragment shader - GL_UseProgramFunc (r_gamma_program); - GL_Uniform1fFunc (gammaLoc, vid_gamma.value); - GL_Uniform1fFunc (contrastLoc, q_min(2.0f, q_max(1.0f, vid_contrast.value))); - GL_Uniform1iFunc (textureLoc, 0); // use texture unit 0 + // draw the texture back to the framebuffer with a fragment shader + GL_UseProgramFunc(r_gamma_program); + GL_Uniform1fFunc(gammaLoc, vid_gamma.value); + GL_Uniform1fFunc(contrastLoc, std::min(2.0f, std::max(1.0f, vid_contrast.value))); + GL_Uniform1iFunc(textureLoc, 0); // use texture unit 0 - glDisable (GL_ALPHA_TEST); - glDisable (GL_DEPTH_TEST); + glDisable(GL_ALPHA_TEST); + glDisable(GL_DEPTH_TEST); - glViewport (glx, gly, glwidth, glheight); + glViewport(glx, gly, glwidth, glheight); - smax = glwidth/(float)r_gamma_texture_width; - tmax = glheight/(float)r_gamma_texture_height; + smax = glwidth / (float) r_gamma_texture_width; + tmax = glheight / (float) r_gamma_texture_height; - glBegin (GL_QUADS); - glTexCoord2f (0, 0); - glVertex2f (-1, -1); - glTexCoord2f (smax, 0); - glVertex2f (1, -1); - glTexCoord2f (smax, tmax); - glVertex2f (1, 1); - glTexCoord2f (0, tmax); - glVertex2f (-1, 1); - glEnd (); + glBegin(GL_QUADS); + glTexCoord2f(0, 0); + glVertex2f(-1, -1); + glTexCoord2f(smax, 0); + glVertex2f(1, -1); + glTexCoord2f(smax, tmax); + glVertex2f(1, 1); + glTexCoord2f(0, tmax); + glVertex2f(-1, 1); + glEnd(); - GL_UseProgramFunc (0); + GL_UseProgramFunc(0); -// clear cached binding - GL_ClearBindings (); + // clear cached binding + GL_ClearBindings(); } /* @@ -266,24 +266,22 @@ R_CullBox -- johnfitz -- replaced with new function from lordhavoc Returns true if the box is completely outside the frustum ================= */ -qboolean R_CullBox (vec3_t emins, vec3_t emaxs) -{ - int i; - mplane_t *p; - byte signbits; - float vec[3]; +qboolean R_CullBox(vec3_t emins, vec3_t emaxs) { + int i; + mplane_t *p; + byte signbits; + float vec[3]; - for (i = 0;i < 4;i++) - { - p = frustum + i; - signbits = p->signbits; - vec[0] = ((signbits & 1) ? emins : emaxs)[0]; - vec[1] = ((signbits & 2) ? emins : emaxs)[1]; - vec[2] = ((signbits & 4) ? emins : emaxs)[2]; - if (p->normal[0]*vec[0] + p->normal[1]*vec[1] + p->normal[2]*vec[2] < p->dist) - return true; - } - return false; + for (i = 0; i < 4; i++) { + p = frustum + i; + signbits = p->signbits; + vec[0] = ((signbits & 1) ? emins : emaxs)[0]; + vec[1] = ((signbits & 2) ? emins : emaxs)[1]; + vec[2] = ((signbits & 4) ? emins : emaxs)[2]; + if (p->normal[0] * vec[0] + p->normal[1] * vec[1] + p->normal[2] * vec[2] < p->dist) + return true; + } + return false; } /* @@ -291,40 +289,34 @@ qboolean R_CullBox (vec3_t emins, vec3_t emaxs) R_CullModelForEntity -- johnfitz -- uses correct bounds based on rotation =============== */ -qboolean R_CullModelForEntity (entity_t *e) -{ - vec3_t mins, maxs; - vec_t scalefactor, *minbounds, *maxbounds; +qboolean R_CullModelForEntity(entity_t *e) { + vec3_t mins, maxs; + vec_t scalefactor, *minbounds, *maxbounds; - if (e->angles[0] || e->angles[2]) //pitch or roll - { - minbounds = e->model->rmins; - maxbounds = e->model->rmaxs; - } - else if (e->angles[1]) //yaw - { - minbounds = e->model->ymins; - maxbounds = e->model->ymaxs; - } - else //no rotation - { - minbounds = e->model->mins; - maxbounds = e->model->maxs; - } + if (e->angles[0] || e->angles[2]) //pitch or roll + { + minbounds = e->model->rmins; + maxbounds = e->model->rmaxs; + } else if (e->angles[1]) //yaw + { + minbounds = e->model->ymins; + maxbounds = e->model->ymaxs; + } else //no rotation + { + minbounds = e->model->mins; + maxbounds = e->model->maxs; + } - scalefactor = ENTSCALE_DECODE(e->scale); - if (scalefactor != 1.0f) - { - VectorMA (e->origin, scalefactor, minbounds, mins); - VectorMA (e->origin, scalefactor, maxbounds, maxs); - } - else - { - VectorAdd (e->origin, minbounds, mins); - VectorAdd (e->origin, maxbounds, maxs); - } + scalefactor = ENTSCALE_DECODE(e->scale); + if (scalefactor != 1.0f) { + VectorMA(e->origin, scalefactor, minbounds, mins); + VectorMA(e->origin, scalefactor, maxbounds, maxs); + } else { + VectorAdd(e->origin, minbounds, mins); + VectorAdd(e->origin, maxbounds, maxs); + } - return R_CullBox (mins, maxs); + return R_CullBox(mins, maxs); } /* @@ -332,15 +324,14 @@ qboolean R_CullModelForEntity (entity_t *e) R_RotateForEntity -- johnfitz -- modified to take origin and angles instead of pointer to entity =============== */ -void R_RotateForEntity (vec3_t origin, vec3_t angles, unsigned char scale) -{ - float scalefactor = ENTSCALE_DECODE(scale); - glTranslatef (origin[0], origin[1], origin[2]); - glRotatef (angles[1], 0, 0, 1); - glRotatef (-angles[0], 0, 1, 0); - glRotatef (angles[2], 1, 0, 0); - if (scalefactor != 1.0f) - glScalef(scalefactor, scalefactor, scalefactor); +void R_RotateForEntity(vec3_t origin, vec3_t angles, unsigned char scale) { + float scalefactor = ENTSCALE_DECODE(scale); + glTranslatef(origin[0], origin[1], origin[2]); + glRotatef(angles[1], 0, 0, 1); + glRotatef(-angles[0], 0, 1, 0); + glRotatef(angles[2], 1, 0, 0); + if (scalefactor != 1.0f) + glScalef(scalefactor, scalefactor, scalefactor); } /* @@ -350,25 +341,19 @@ GL_PolygonOffset -- johnfitz negative offset moves polygon closer to camera ============= */ -void GL_PolygonOffset (int offset) -{ - if (offset > 0) - { - glEnable (GL_POLYGON_OFFSET_FILL); - glEnable (GL_POLYGON_OFFSET_LINE); - glPolygonOffset(1, offset); - } - else if (offset < 0) - { - glEnable (GL_POLYGON_OFFSET_FILL); - glEnable (GL_POLYGON_OFFSET_LINE); - glPolygonOffset(-1, offset); - } - else - { - glDisable (GL_POLYGON_OFFSET_FILL); - glDisable (GL_POLYGON_OFFSET_LINE); - } +void GL_PolygonOffset(int offset) { + if (offset > 0) { + glEnable(GL_POLYGON_OFFSET_FILL); + glEnable(GL_POLYGON_OFFSET_LINE); + glPolygonOffset(1, offset); + } else if (offset < 0) { + glEnable(GL_POLYGON_OFFSET_FILL); + glEnable(GL_POLYGON_OFFSET_LINE); + glPolygonOffset(-1, offset); + } else { + glDisable(GL_POLYGON_OFFSET_FILL); + glDisable(GL_POLYGON_OFFSET_LINE); + } } //============================================================================== @@ -377,19 +362,17 @@ void GL_PolygonOffset (int offset) // //============================================================================== -int SignbitsForPlane (mplane_t *out) -{ - int bits, j; +int SignbitsForPlane(mplane_t *out) { + int bits, j; - // for fast box on planeside test + // for fast box on planeside test - bits = 0; - for (j=0 ; j<3 ; j++) - { - if (out->normal[j] < 0) - bits |= 1<normal[j] < 0) + bits |= 1 << j; + } + return bits; } /* @@ -402,16 +385,15 @@ assumes side and forward are perpendicular, and normalized to turn away from side, use a negative angle =============== */ -void TurnVector (vec3_t out, const vec3_t forward, const vec3_t side, float angle) -{ - float scale_forward, scale_side; +void TurnVector(vec3_t out, const vec3_t forward, const vec3_t side, float angle) { + float scale_forward, scale_side; - scale_forward = cos( DEG2RAD( angle ) ); - scale_side = sin( DEG2RAD( angle ) ); + scale_forward = cos(DEG2RAD(angle)); + scale_side = sin(DEG2RAD(angle)); - out[0] = scale_forward*forward[0] + scale_side*side[0]; - out[1] = scale_forward*forward[1] + scale_side*side[1]; - out[2] = scale_forward*forward[2] + scale_side*side[2]; + out[0] = scale_forward * forward[0] + scale_side * side[0]; + out[1] = scale_forward * forward[1] + scale_side * side[1]; + out[2] = scale_forward * forward[2] + scale_side * side[2]; } /* @@ -419,24 +401,22 @@ void TurnVector (vec3_t out, const vec3_t forward, const vec3_t side, float angl R_SetFrustum -- johnfitz -- rewritten =============== */ -void R_SetFrustum (float fovx, float fovy) -{ - int i; +void R_SetFrustum(float fovx, float fovy) { + int i; - if (r_stereo.value) - fovx += 10; //silly hack so that polygons don't drop out becuase of stereo skew + if (r_stereo.value) + fovx += 10; //silly hack so that polygons don't drop out becuase of stereo skew - TurnVector(frustum[0].normal, vpn, vright, fovx/2 - 90); //left plane - TurnVector(frustum[1].normal, vpn, vright, 90 - fovx/2); //right plane - TurnVector(frustum[2].normal, vpn, vup, 90 - fovy/2); //bottom plane - TurnVector(frustum[3].normal, vpn, vup, fovy/2 - 90); //top plane + TurnVector(frustum[0].normal, vpn, vright, fovx / 2 - 90); //left plane + TurnVector(frustum[1].normal, vpn, vright, 90 - fovx / 2); //right plane + TurnVector(frustum[2].normal, vpn, vup, 90 - fovy / 2); //bottom plane + TurnVector(frustum[3].normal, vpn, vup, fovy / 2 - 90); //top plane - for (i=0 ; i<4 ; i++) - { - frustum[i].type = PLANE_ANYZ; - frustum[i].dist = DotProduct (r_origin, frustum[i].normal); //FIXME: shouldn't this always be zero? - frustum[i].signbits = SignbitsForPlane (&frustum[i]); - } + for (i = 0; i < 4; i++) { + frustum[i].type = PLANE_ANYZ; + frustum[i].dist = DotProduct(r_origin, frustum[i].normal); //FIXME: shouldn't this always be zero? + frustum[i].signbits = SignbitsForPlane(&frustum[i]); + } } /* @@ -446,12 +426,11 @@ GL_SetFrustum -- johnfitz -- written to replace MYgluPerspective */ #define NEARCLIP 4 float frustum_skew = 0.0; //used by r_stereo -void GL_SetFrustum(float fovx, float fovy) -{ - float xmax, ymax; - xmax = NEARCLIP * tan( fovx * M_PI / 360.0 ); - ymax = NEARCLIP * tan( fovy * M_PI / 360.0 ); - glFrustum(-xmax + frustum_skew, xmax + frustum_skew, -ymax, ymax, NEARCLIP, gl_farclip.value); +void GL_SetFrustum(float fovx, float fovy) { + float xmax, ymax; + xmax = NEARCLIP * tan(fovx * M_PI / 360.0); + ymax = NEARCLIP * tan(fovy * M_PI / 360.0); + glFrustum(-xmax + frustum_skew, xmax + frustum_skew, -ymax, ymax, NEARCLIP, gl_farclip.value); } /* @@ -459,45 +438,44 @@ void GL_SetFrustum(float fovx, float fovy) R_SetupGL ============= */ -void R_SetupGL (void) -{ - int scale; +void R_SetupGL(void) { + int scale; - //johnfitz -- rewrote this section - glMatrixMode(GL_PROJECTION); - glLoadIdentity (); - scale = CLAMP(1, (int)r_scale.value, 4); // ericw -- see R_ScaleView - glViewport (glx + r_refdef.vrect.x, - gly + glheight - r_refdef.vrect.y - r_refdef.vrect.height, - r_refdef.vrect.width / scale, - r_refdef.vrect.height / scale); - //johnfitz + //johnfitz -- rewrote this section + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + scale = CLAMP(1, (int)r_scale.value, 4); // ericw -- see R_ScaleView + glViewport(glx + r_refdef.vrect.x, + gly + glheight - r_refdef.vrect.y - r_refdef.vrect.height, + r_refdef.vrect.width / scale, + r_refdef.vrect.height / scale); + //johnfitz - GL_SetFrustum (r_fovx, r_fovy); //johnfitz -- use r_fov* vars + GL_SetFrustum(r_fovx, r_fovy); //johnfitz -- use r_fov* vars -// glCullFace(GL_BACK); //johnfitz -- glquake used CCW with backwards culling -- let's do it right + // glCullFace(GL_BACK); //johnfitz -- glquake used CCW with backwards culling -- let's do it right - glMatrixMode(GL_MODELVIEW); - glLoadIdentity (); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); - glRotatef (-90, 1, 0, 0); // put Z going up - glRotatef (90, 0, 0, 1); // put Z going up - glRotatef (-r_refdef.viewangles[2], 1, 0, 0); - glRotatef (-r_refdef.viewangles[0], 0, 1, 0); - glRotatef (-r_refdef.viewangles[1], 0, 0, 1); - glTranslatef (-r_refdef.vieworg[0], -r_refdef.vieworg[1], -r_refdef.vieworg[2]); + glRotatef(-90, 1, 0, 0); // put Z going up + glRotatef(90, 0, 0, 1); // put Z going up + glRotatef(-r_refdef.viewangles[2], 1, 0, 0); + glRotatef(-r_refdef.viewangles[0], 0, 1, 0); + glRotatef(-r_refdef.viewangles[1], 0, 0, 1); + glTranslatef(-r_refdef.vieworg[0], -r_refdef.vieworg[1], -r_refdef.vieworg[2]); - // - // set drawing parms - // - if (gl_cull.value) - glEnable(GL_CULL_FACE); - else - glDisable(GL_CULL_FACE); + // + // set drawing parms + // + if (gl_cull.value) + glEnable(GL_CULL_FACE); + else + glDisable(GL_CULL_FACE); - glDisable(GL_BLEND); - glDisable(GL_ALPHA_TEST); - glEnable(GL_DEPTH_TEST); + glDisable(GL_BLEND); + glDisable(GL_ALPHA_TEST); + glEnable(GL_DEPTH_TEST); } /* @@ -505,17 +483,16 @@ void R_SetupGL (void) R_Clear -- johnfitz -- rewritten and gutted ============= */ -void R_Clear (void) -{ - unsigned int clearbits; +void R_Clear(void) { + unsigned int clearbits; - clearbits = GL_DEPTH_BUFFER_BIT; - // from mh -- if we get a stencil buffer, we should clear it, even though we don't use it - if (gl_stencilbits) - clearbits |= GL_STENCIL_BUFFER_BIT; - if (gl_clear.value) - clearbits |= GL_COLOR_BUFFER_BIT; - glClear (clearbits); + clearbits = GL_DEPTH_BUFFER_BIT; + // from mh -- if we get a stencil buffer, we should clear it, even though we don't use it + if (gl_stencilbits) + clearbits |= GL_STENCIL_BUFFER_BIT; + if (gl_clear.value) + clearbits |= GL_COLOR_BUFFER_BIT; + glClear(clearbits); } /* @@ -523,9 +500,8 @@ void R_Clear (void) R_SetupScene -- johnfitz -- this is the stuff that needs to be done once per eye in stereo mode =============== */ -void R_SetupScene (void) -{ - R_SetupGL (); +void R_SetupScene(void) { + R_SetupGL(); } /* @@ -533,61 +509,57 @@ void R_SetupScene (void) R_SetupView -- johnfitz -- this is the stuff that needs to be done once per frame, even in stereo mode =============== */ -void R_SetupView (void) -{ - // Need to do those early because we now update dynamic light maps during R_MarkSurfaces - R_PushDlights (); - R_AnimateLight (); - r_framecount++; +void R_SetupView(void) { + // Need to do those early because we now update dynamic light maps during R_MarkSurfaces + R_PushDlights(); + R_AnimateLight(); + r_framecount++; - Fog_SetupFrame (); //johnfitz + Fog_SetupFrame(); //johnfitz -// build the transformation matrix for the given view angles - VectorCopy (r_refdef.vieworg, r_origin); - AngleVectors (r_refdef.viewangles, vpn, vright, vup); + // build the transformation matrix for the given view angles + VectorCopy(r_refdef.vieworg, r_origin); + AngleVectors(r_refdef.viewangles, vpn, vright, vup); -// current viewleaf - r_oldviewleaf = r_viewleaf; - r_viewleaf = Mod_PointInLeaf (r_origin, cl.worldmodel); + // current viewleaf + r_oldviewleaf = r_viewleaf; + r_viewleaf = Mod_PointInLeaf(r_origin, cl.worldmodel); - V_SetContentsColor (r_viewleaf->contents); - V_CalcBlend (); + V_SetContentsColor(r_viewleaf->contents); + V_CalcBlend(); - //johnfitz -- calculate r_fovx and r_fovy here - r_fovx = r_refdef.fov_x; - r_fovy = r_refdef.fov_y; - if (r_waterwarp.value) - { - int contents = Mod_PointInLeaf (r_origin, cl.worldmodel)->contents; - if (contents == CONTENTS_WATER || contents == CONTENTS_SLIME || contents == CONTENTS_LAVA) - { - //variance is a percentage of width, where width = 2 * tan(fov / 2) otherwise the effect is too dramatic at high FOV and too subtle at low FOV. what a mess! - r_fovx = atan(tan(DEG2RAD(r_refdef.fov_x) / 2) * (0.97 + sin(cl.time * 1.5) * 0.03)) * 2 / M_PI_DIV_180; - r_fovy = atan(tan(DEG2RAD(r_refdef.fov_y) / 2) * (1.03 - sin(cl.time * 1.5) * 0.03)) * 2 / M_PI_DIV_180; - } - } - //johnfitz + //johnfitz -- calculate r_fovx and r_fovy here + r_fovx = r_refdef.fov_x; + r_fovy = r_refdef.fov_y; + if (r_waterwarp.value) { + int contents = Mod_PointInLeaf(r_origin, cl.worldmodel)->contents; + if (contents == CONTENTS_WATER || contents == CONTENTS_SLIME || contents == CONTENTS_LAVA) { + //variance is a percentage of width, where width = 2 * tan(fov / 2) otherwise the effect is too dramatic at high FOV and too subtle at low FOV. what a mess! + r_fovx = atan(tan(DEG2RAD(r_refdef.fov_x) / 2) * (0.97 + sin(cl.time * 1.5) * 0.03)) * 2 / M_PI_DIV_180; + r_fovy = atan(tan(DEG2RAD(r_refdef.fov_y) / 2) * (1.03 - sin(cl.time * 1.5) * 0.03)) * 2 / M_PI_DIV_180; + } + } + //johnfitz - R_SetFrustum (r_fovx, r_fovy); //johnfitz -- use r_fov* vars + R_SetFrustum(r_fovx, r_fovy); //johnfitz -- use r_fov* vars - R_MarkSurfaces (); //johnfitz -- create texture chains from PVS + R_MarkSurfaces(); //johnfitz -- create texture chains from PVS - R_UpdateWarpTextures (); //johnfitz -- do this before R_Clear + R_UpdateWarpTextures(); //johnfitz -- do this before R_Clear - R_Clear (); + R_Clear(); - //johnfitz -- cheat-protect some draw modes - r_drawflat_cheatsafe = r_fullbright_cheatsafe = r_lightmap_cheatsafe = false; - r_drawworld_cheatsafe = true; - if (cl.maxclients == 1) - { - if (!r_drawworld.value) r_drawworld_cheatsafe = false; + //johnfitz -- cheat-protect some draw modes + r_drawflat_cheatsafe = r_fullbright_cheatsafe = r_lightmap_cheatsafe = false; + r_drawworld_cheatsafe = true; + if (cl.maxclients == 1) { + if (!r_drawworld.value) r_drawworld_cheatsafe = false; - if (r_drawflat.value) r_drawflat_cheatsafe = true; - else if (r_fullbright.value || !cl.worldmodel->lightdata) r_fullbright_cheatsafe = true; - else if (r_lightmap.value) r_lightmap_cheatsafe = true; - } - //johnfitz + if (r_drawflat.value) r_drawflat_cheatsafe = true; + else if (r_fullbright.value || !cl.worldmodel->lightdata) r_fullbright_cheatsafe = true; + else if (r_lightmap.value) r_lightmap_cheatsafe = true; + } + //johnfitz } //============================================================================== @@ -601,42 +573,40 @@ void R_SetupView (void) R_DrawEntitiesOnList ============= */ -void R_DrawEntitiesOnList (qboolean alphapass) //johnfitz -- added parameter +void R_DrawEntitiesOnList(qboolean alphapass) //johnfitz -- added parameter { - int i; + int i; - if (!r_drawentities.value) - return; + if (!r_drawentities.value) + return; - //johnfitz -- sprites are not a special case - for (i=0 ; ialpha) < 1 && !alphapass) || - (ENTALPHA_DECODE(currententity->alpha) == 1 && alphapass)) - continue; + //johnfitz -- if alphapass is true, draw only alpha entites this time + //if alphapass is false, draw only nonalpha entities this time + if ((ENTALPHA_DECODE(currententity->alpha) < 1 && !alphapass) || + (ENTALPHA_DECODE(currententity->alpha) == 1 && alphapass)) + continue; - //johnfitz -- chasecam - if (currententity == &cl_entities[cl.viewentity]) - currententity->angles[0] *= 0.3; - //johnfitz + //johnfitz -- chasecam + if (currententity == &cl_entities[cl.viewentity]) + currententity->angles[0] *= 0.3; + //johnfitz - switch (currententity->model->type) - { - case mod_alias: - R_DrawAliasModel (currententity); - break; - case mod_brush: - R_DrawBrushModel (currententity); - break; - case mod_sprite: - R_DrawSpriteModel (currententity); - break; - } - } + switch (currententity->model->type) { + case mod_alias: + R_DrawAliasModel(currententity); + break; + case mod_brush: + R_DrawBrushModel(currententity); + break; + case mod_sprite: + R_DrawSpriteModel(currententity); + break; + } + } } /* @@ -644,27 +614,26 @@ void R_DrawEntitiesOnList (qboolean alphapass) //johnfitz -- added parameter R_DrawViewModel -- johnfitz -- gutted ============= */ -void R_DrawViewModel (void) -{ - if (!r_drawviewmodel.value || !r_drawentities.value || chase_active.value) - return; +void R_DrawViewModel(void) { + if (!r_drawviewmodel.value || !r_drawentities.value || chase_active.value) + return; - if (cl.items & IT_INVISIBILITY || cl.stats[STAT_HEALTH] <= 0) - return; + if (cl.items & IT_INVISIBILITY || cl.stats[STAT_HEALTH] <= 0) + return; - currententity = &cl.viewent; - if (!currententity->model) - return; + currententity = &cl.viewent; + if (!currententity->model) + return; - //johnfitz -- this fixes a crash - if (currententity->model->type != mod_alias) - return; - //johnfitz + //johnfitz -- this fixes a crash + if (currententity->model->type != mod_alias) + return; + //johnfitz - // hack the depth range to prevent view model from poking into walls - glDepthRange (0, 0.3); - R_DrawAliasModel (currententity); - glDepthRange (0, 1); + // hack the depth range to prevent view model from poking into walls + glDepthRange(0, 0.3); + R_DrawAliasModel(currententity); + glDepthRange(0, 1); } /* @@ -672,18 +641,17 @@ void R_DrawViewModel (void) R_EmitWirePoint -- johnfitz -- draws a wireframe cross shape for point entities ================ */ -void R_EmitWirePoint (vec3_t origin) -{ - const int size = 8; +void R_EmitWirePoint(vec3_t origin) { + const int size = 8; - glBegin (GL_LINES); - glVertex3f (origin[0]-size, origin[1], origin[2]); - glVertex3f (origin[0]+size, origin[1], origin[2]); - glVertex3f (origin[0], origin[1]-size, origin[2]); - glVertex3f (origin[0], origin[1]+size, origin[2]); - glVertex3f (origin[0], origin[1], origin[2]-size); - glVertex3f (origin[0], origin[1], origin[2]+size); - glEnd (); + glBegin(GL_LINES); + glVertex3f(origin[0] - size, origin[1], origin[2]); + glVertex3f(origin[0] + size, origin[1], origin[2]); + glVertex3f(origin[0], origin[1] - size, origin[2]); + glVertex3f(origin[0], origin[1] + size, origin[2]); + glVertex3f(origin[0], origin[1], origin[2] - size); + glVertex3f(origin[0], origin[1], origin[2] + size); + glEnd(); } /* @@ -691,20 +659,19 @@ void R_EmitWirePoint (vec3_t origin) R_EmitWireBox -- johnfitz -- draws one axis aligned bounding box ================ */ -void R_EmitWireBox (vec3_t mins, vec3_t maxs) -{ - glBegin (GL_QUAD_STRIP); - glVertex3f (mins[0], mins[1], mins[2]); - glVertex3f (mins[0], mins[1], maxs[2]); - glVertex3f (maxs[0], mins[1], mins[2]); - glVertex3f (maxs[0], mins[1], maxs[2]); - glVertex3f (maxs[0], maxs[1], mins[2]); - glVertex3f (maxs[0], maxs[1], maxs[2]); - glVertex3f (mins[0], maxs[1], mins[2]); - glVertex3f (mins[0], maxs[1], maxs[2]); - glVertex3f (mins[0], mins[1], mins[2]); - glVertex3f (mins[0], mins[1], maxs[2]); - glEnd (); +void R_EmitWireBox(vec3_t mins, vec3_t maxs) { + glBegin(GL_QUAD_STRIP); + glVertex3f(mins[0], mins[1], mins[2]); + glVertex3f(mins[0], mins[1], maxs[2]); + glVertex3f(maxs[0], mins[1], mins[2]); + glVertex3f(maxs[0], mins[1], maxs[2]); + glVertex3f(maxs[0], maxs[1], mins[2]); + glVertex3f(maxs[0], maxs[1], maxs[2]); + glVertex3f(mins[0], maxs[1], mins[2]); + glVertex3f(mins[0], maxs[1], maxs[2]); + glVertex3f(mins[0], mins[1], mins[2]); + glVertex3f(mins[0], mins[1], maxs[2]); + glEnd(); } /* @@ -714,54 +681,49 @@ R_ShowBoundingBoxes -- johnfitz draw bounding boxes -- the server-side boxes, not the renderer cullboxes ================ */ -void R_ShowBoundingBoxes (void) -{ - extern edict_t *sv_player; - vec3_t mins,maxs; - edict_t *ed; - int i; +void R_ShowBoundingBoxes(void) { + extern edict_t *sv_player; + vec3_t mins, maxs; + edict_t *ed; + int i; - if (!r_showbboxes.value || cl.maxclients > 1 || !r_drawentities.value || !sv.active) - return; + if (!r_showbboxes.value || cl.maxclients > 1 || !r_drawentities.value || !sv.active) + return; - glDisable (GL_DEPTH_TEST); - glPolygonMode (GL_FRONT_AND_BACK, GL_LINE); - GL_PolygonOffset (OFFSET_SHOWTRIS); - glDisable (GL_TEXTURE_2D); - glDisable (GL_CULL_FACE); - glColor3f (1,1,1); + glDisable(GL_DEPTH_TEST); + glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); + GL_PolygonOffset(OFFSET_SHOWTRIS); + glDisable(GL_TEXTURE_2D); + glDisable(GL_CULL_FACE); + glColor3f(1, 1, 1); - for (i=1, ed=NEXT_EDICT(sv.edicts) ; ifree) - continue; //don't draw player's own bbox or freed edicts + for (i = 1, ed = NEXT_EDICT(sv.edicts); i < sv.num_edicts; i++, ed = NEXT_EDICT(ed)) { + if (ed == sv_player || ed->free) + continue; //don't draw player's own bbox or freed edicts -// if (r_showbboxes.value != 2) -// if (!SV_VisibleToClient (sv_player, ed, sv.worldmodel)) -// continue; //don't draw if not in pvs + // if (r_showbboxes.value != 2) + // if (!SV_VisibleToClient (sv_player, ed, sv.worldmodel)) + // continue; //don't draw if not in pvs - if (ed->v.mins[0] == ed->v.maxs[0] && ed->v.mins[1] == ed->v.maxs[1] && ed->v.mins[2] == ed->v.maxs[2]) - { - //point entity - R_EmitWirePoint (ed->v.origin); - } - else - { - //box entity - VectorAdd (ed->v.mins, ed->v.origin, mins); - VectorAdd (ed->v.maxs, ed->v.origin, maxs); - R_EmitWireBox (mins, maxs); - } - } + if (ed->v.mins[0] == ed->v.maxs[0] && ed->v.mins[1] == ed->v.maxs[1] && ed->v.mins[2] == ed->v.maxs[2]) { + //point entity + R_EmitWirePoint(ed->v.origin); + } else { + //box entity + VectorAdd(ed->v.mins, ed->v.origin, mins); + VectorAdd(ed->v.maxs, ed->v.origin, maxs); + R_EmitWireBox(mins, maxs); + } + } - glColor3f (1,1,1); - glEnable (GL_TEXTURE_2D); - glEnable (GL_CULL_FACE); - glPolygonMode (GL_FRONT_AND_BACK, GL_FILL); - GL_PolygonOffset (OFFSET_NONE); - glEnable (GL_DEPTH_TEST); + glColor3f(1, 1, 1); + glEnable(GL_TEXTURE_2D); + glEnable(GL_CULL_FACE); + glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); + GL_PolygonOffset(OFFSET_NONE); + glEnable(GL_DEPTH_TEST); - Sbar_Changed (); //so we don't get dots collecting on the statusbar + Sbar_Changed(); //so we don't get dots collecting on the statusbar } /* @@ -769,83 +731,76 @@ void R_ShowBoundingBoxes (void) R_ShowTris -- johnfitz ================ */ -void R_ShowTris (void) -{ - extern cvar_t r_particles; - int i; +void R_ShowTris(void) { + extern convar r_particles; + int i; - if (r_showtris.value < 1 || r_showtris.value > 2 || cl.maxclients > 1) - return; + if (r_showtris.value < 1 || r_showtris.value > 2 || cl.maxclients > 1) + return; - if (r_showtris.value == 1) - glDisable (GL_DEPTH_TEST); - glPolygonMode (GL_FRONT_AND_BACK, GL_LINE); - GL_PolygonOffset (OFFSET_SHOWTRIS); - glDisable (GL_TEXTURE_2D); - glColor3f (1,1,1); -// glEnable (GL_BLEND); -// glBlendFunc (GL_ONE, GL_ONE); + if (r_showtris.value == 1) + glDisable(GL_DEPTH_TEST); + glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); + GL_PolygonOffset(OFFSET_SHOWTRIS); + glDisable(GL_TEXTURE_2D); + glColor3f(1, 1, 1); + // glEnable (GL_BLEND); + // glBlendFunc (GL_ONE, GL_ONE); - if (r_drawworld.value) - { - R_DrawWorld_ShowTris (); - } + if (r_drawworld.value) { + R_DrawWorld_ShowTris(); + } - if (r_drawentities.value) - { - for (i=0 ; iangles[0] *= 0.3; + if (currententity == &cl_entities[cl.viewentity]) // chasecam + currententity->angles[0] *= 0.3; - switch (currententity->model->type) - { - case mod_brush: - R_DrawBrushModel_ShowTris (currententity); - break; - case mod_alias: - R_DrawAliasModel_ShowTris (currententity); - break; - case mod_sprite: - R_DrawSpriteModel (currententity); - break; - default: - break; - } - } + switch (currententity->model->type) { + case mod_brush: + R_DrawBrushModel_ShowTris(currententity); + break; + case mod_alias: + R_DrawAliasModel_ShowTris(currententity); + break; + case mod_sprite: + R_DrawSpriteModel(currententity); + break; + default: + break; + } + } - // viewmodel - currententity = &cl.viewent; - if (r_drawviewmodel.value - && !chase_active.value - && cl.stats[STAT_HEALTH] > 0 - && !(cl.items & IT_INVISIBILITY) - && currententity->model - && currententity->model->type == mod_alias) - { - glDepthRange (0, 0.3); - R_DrawAliasModel_ShowTris (currententity); - glDepthRange (0, 1); - } - } + // viewmodel + currententity = &cl.viewent; + if (r_drawviewmodel.value + && !chase_active.value + && cl.stats[STAT_HEALTH] > 0 + && !(cl.items & IT_INVISIBILITY) + && currententity->model + && currententity->model->type == mod_alias) { + glDepthRange(0, 0.3); + R_DrawAliasModel_ShowTris(currententity); + glDepthRange(0, 1); + } + } - if (r_particles.value) - { - R_DrawParticles_ShowTris (); - } + if (r_particles.value) { + R_DrawParticles_ShowTris(); + } -// glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); -// glDisable (GL_BLEND); - glColor3f (1,1,1); - glEnable (GL_TEXTURE_2D); - glPolygonMode (GL_FRONT_AND_BACK, GL_FILL); - GL_PolygonOffset (OFFSET_NONE); - if (r_showtris.value == 1) - glEnable (GL_DEPTH_TEST); + // glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + // glDisable (GL_BLEND); + glColor3f(1, 1, 1); + glEnable(GL_TEXTURE_2D); + glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); + GL_PolygonOffset(OFFSET_NONE); + if (r_showtris.value == 1) + glEnable(GL_DEPTH_TEST); - Sbar_Changed (); //so we don't get dots collecting on the statusbar + Sbar_Changed(); //so we don't get dots collecting on the statusbar } /* @@ -853,39 +808,35 @@ void R_ShowTris (void) R_DrawShadows ================ */ -void R_DrawShadows (void) -{ - int i; +void R_DrawShadows(void) { + int i; - if (!r_shadows.value || !r_drawentities.value || r_drawflat_cheatsafe || r_lightmap_cheatsafe) - return; + if (!r_shadows.value || !r_drawentities.value || r_drawflat_cheatsafe || r_lightmap_cheatsafe) + return; - // Use stencil buffer to prevent self-intersecting shadows, from Baker (MarkV) - if (gl_stencilbits) - { - glClear(GL_STENCIL_BUFFER_BIT); - glStencilFunc(GL_EQUAL, 0, ~0); - glStencilOp(GL_KEEP, GL_KEEP, GL_INCR); - glEnable(GL_STENCIL_TEST); - } + // Use stencil buffer to prevent self-intersecting shadows, from Baker (MarkV) + if (gl_stencilbits) { + glClear(GL_STENCIL_BUFFER_BIT); + glStencilFunc(GL_EQUAL, 0, ~0); + glStencilOp(GL_KEEP, GL_KEEP, GL_INCR); + glEnable(GL_STENCIL_TEST); + } - for (i=0 ; imodel->type != mod_alias) - continue; + if (currententity->model->type != mod_alias) + continue; - if (currententity == &cl.viewent) - return; + if (currententity == &cl.viewent) + return; - GL_DrawAliasShadow (currententity); - } + GL_DrawAliasShadow(currententity); + } - if (gl_stencilbits) - { - glDisable(GL_STENCIL_TEST); - } + if (gl_stencilbits) { + glDisable(GL_STENCIL_TEST); + } } /* @@ -893,37 +844,36 @@ void R_DrawShadows (void) R_RenderScene ================ */ -void R_RenderScene (void) -{ - R_SetupScene (); //johnfitz -- this does everything that should be done once per call to RenderScene +void R_RenderScene(void) { + R_SetupScene(); //johnfitz -- this does everything that should be done once per call to RenderScene - Fog_EnableGFog (); //johnfitz + Fog_EnableGFog(); //johnfitz - Sky_DrawSky (); //johnfitz + Sky_DrawSky(); //johnfitz - R_DrawWorld (); + R_DrawWorld(); - S_ExtraUpdate (); // don't let sound get messed up if going slow + S_ExtraUpdate(); // don't let sound get messed up if going slow - R_DrawShadows (); //johnfitz -- render entity shadows + R_DrawShadows(); //johnfitz -- render entity shadows - R_DrawEntitiesOnList (false); //johnfitz -- false means this is the pass for nonalpha entities + R_DrawEntitiesOnList(false); //johnfitz -- false means this is the pass for nonalpha entities - R_DrawWorld_Water (); //johnfitz -- drawn here since they might have transparency + R_DrawWorld_Water(); //johnfitz -- drawn here since they might have transparency - R_DrawEntitiesOnList (true); //johnfitz -- true means this is the pass for alpha entities + R_DrawEntitiesOnList(true); //johnfitz -- true means this is the pass for alpha entities - R_RenderDlights (); //triangle fan dlights -- johnfitz -- moved after water + R_RenderDlights(); //triangle fan dlights -- johnfitz -- moved after water - R_DrawParticles (); + R_DrawParticles(); - Fog_DisableGFog (); //johnfitz + Fog_DisableGFog(); //johnfitz - R_DrawViewModel (); //johnfitz -- moved here from R_RenderView + R_DrawViewModel(); //johnfitz -- moved here from R_RenderView - R_ShowTris (); //johnfitz + R_ShowTris(); //johnfitz - R_ShowBoundingBoxes (); //johnfitz + R_ShowBoundingBoxes(); //johnfitz } static GLuint r_scaleview_texture; @@ -934,10 +884,9 @@ static int r_scaleview_texture_width, r_scaleview_texture_height; R_ScaleView_DeleteTexture ============= */ -void R_ScaleView_DeleteTexture (void) -{ - glDeleteTextures (1, &r_scaleview_texture); - r_scaleview_texture = 0; +void R_ScaleView_DeleteTexture(void) { + glDeleteTextures(1, &r_scaleview_texture); + r_scaleview_texture = 0; } /* @@ -945,92 +894,89 @@ void R_ScaleView_DeleteTexture (void) R_ScaleView The r_scale cvar allows rendering the 3D view at 1/2, 1/3, or 1/4 resolution. -This function scales the reduced resolution 3D view back up to fill +This function scales the reduced resolution 3D view back up to fill r_refdef.vrect. This is for emulating a low-resolution pixellated look, or possibly as a perforance boost on slow graphics cards. ================ */ -void R_ScaleView (void) -{ - float smax, tmax; - int scale; - int srcx, srcy, srcw, srch; +void R_ScaleView(void) { + float smax, tmax; + int scale; + int srcx, srcy, srcw, srch; - // copied from R_SetupGL() - scale = CLAMP(1, (int)r_scale.value, 4); - srcx = glx + r_refdef.vrect.x; - srcy = gly + glheight - r_refdef.vrect.y - r_refdef.vrect.height; - srcw = r_refdef.vrect.width / scale; - srch = r_refdef.vrect.height / scale; + // copied from R_SetupGL() + scale = CLAMP(1, (int)r_scale.value, 4); + srcx = glx + r_refdef.vrect.x; + srcy = gly + glheight - r_refdef.vrect.y - r_refdef.vrect.height; + srcw = r_refdef.vrect.width / scale; + srch = r_refdef.vrect.height / scale; - if (scale == 1) - return; + if (scale == 1) + return; - // make sure texture unit 0 is selected - GL_DisableMultitexture (); + // make sure texture unit 0 is selected + GL_DisableMultitexture(); - // create (if needed) and bind the render-to-texture texture - if (!r_scaleview_texture) - { - glGenTextures (1, &r_scaleview_texture); + // create (if needed) and bind the render-to-texture texture + if (!r_scaleview_texture) { + glGenTextures(1, &r_scaleview_texture); - r_scaleview_texture_width = 0; - r_scaleview_texture_height = 0; - } - glBindTexture (GL_TEXTURE_2D, r_scaleview_texture); + r_scaleview_texture_width = 0; + r_scaleview_texture_height = 0; + } + glBindTexture(GL_TEXTURE_2D, r_scaleview_texture); - // resize render-to-texture texture if needed - if (r_scaleview_texture_width < srcw - || r_scaleview_texture_height < srch) - { - r_scaleview_texture_width = srcw; - r_scaleview_texture_height = srch; + // resize render-to-texture texture if needed + if (r_scaleview_texture_width < srcw + || r_scaleview_texture_height < srch) { + r_scaleview_texture_width = srcw; + r_scaleview_texture_height = srch; - if (!gl_texture_NPOT) - { - r_scaleview_texture_width = TexMgr_Pad(r_scaleview_texture_width); - r_scaleview_texture_height = TexMgr_Pad(r_scaleview_texture_height); - } + if (!gl_texture_NPOT) { + r_scaleview_texture_width = TexMgr_Pad(r_scaleview_texture_width); + r_scaleview_texture_height = TexMgr_Pad(r_scaleview_texture_height); + } - glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, r_scaleview_texture_width, r_scaleview_texture_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); - glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - } + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, r_scaleview_texture_width, r_scaleview_texture_height, 0, GL_RGBA, + GL_UNSIGNED_BYTE, NULL); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + } - // copy the framebuffer to the texture - glBindTexture (GL_TEXTURE_2D, r_scaleview_texture); - glCopyTexSubImage2D (GL_TEXTURE_2D, 0, 0, 0, srcx, srcy, srcw, srch); + // copy the framebuffer to the texture + glBindTexture(GL_TEXTURE_2D, r_scaleview_texture); + glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, srcx, srcy, srcw, srch); - // draw the texture back to the framebuffer - glDisable (GL_ALPHA_TEST); - glDisable (GL_DEPTH_TEST); - glDisable (GL_CULL_FACE); - glDisable (GL_BLEND); + // draw the texture back to the framebuffer + glDisable(GL_ALPHA_TEST); + glDisable(GL_DEPTH_TEST); + glDisable(GL_CULL_FACE); + glDisable(GL_BLEND); - glViewport (srcx, srcy, r_refdef.vrect.width, r_refdef.vrect.height); + glViewport(srcx, srcy, r_refdef.vrect.width, r_refdef.vrect.height); - glMatrixMode(GL_PROJECTION); - glLoadIdentity (); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity (); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); - // correction factor if we lack NPOT textures, normally these are 1.0f - smax = srcw/(float)r_scaleview_texture_width; - tmax = srch/(float)r_scaleview_texture_height; + // correction factor if we lack NPOT textures, normally these are 1.0f + smax = srcw / (float) r_scaleview_texture_width; + tmax = srch / (float) r_scaleview_texture_height; - glBegin (GL_QUADS); - glTexCoord2f (0, 0); - glVertex2f (-1, -1); - glTexCoord2f (smax, 0); - glVertex2f (1, -1); - glTexCoord2f (smax, tmax); - glVertex2f (1, 1); - glTexCoord2f (0, tmax); - glVertex2f (-1, 1); - glEnd (); + glBegin(GL_QUADS); + glTexCoord2f(0, 0); + glVertex2f(-1, -1); + glTexCoord2f(smax, 0); + glVertex2f(1, -1); + glTexCoord2f(smax, tmax); + glVertex2f(1, 1); + glTexCoord2f(0, tmax); + glVertex2f(-1, 1); + glEnd(); - // clear cached binding - GL_ClearBindings (); + // clear cached binding + GL_ClearBindings(); } /* @@ -1038,96 +984,89 @@ void R_ScaleView (void) R_RenderView ================ */ -void R_RenderView (void) -{ - double time1, time2; +void R_RenderView(void) { + double time1, time2; - if (r_norefresh.value) - return; + if (r_norefresh.value) + return; - if (!cl.worldmodel) - Sys_Error ("R_RenderView: NULL worldmodel"); + if (!cl.worldmodel) + Sys_Error("R_RenderView: NULL worldmodel"); - time1 = 0; /* avoid compiler warning */ - if (r_speeds.value) - { - glFinish (); - time1 = Sys_DoubleTime (); + time1 = 0; /* avoid compiler warning */ + if (r_speeds.value) { + glFinish(); + time1 = Sys_DoubleTime(); - //johnfitz -- rendering statistics - rs_brushpolys = rs_aliaspolys = rs_skypolys = - rs_dynamiclightmaps = rs_aliaspasses = rs_skypasses = rs_brushpasses = 0; - } - else if (gl_finish.value) - glFinish (); + //johnfitz -- rendering statistics + rs_brushpolys = rs_aliaspolys = rs_skypolys = + rs_dynamiclightmaps = rs_aliaspasses = rs_skypasses = rs_brushpasses = 0; + } else if (gl_finish.value) + glFinish(); - R_SetupView (); //johnfitz -- this does everything that should be done once per frame + R_SetupView(); //johnfitz -- this does everything that should be done once per frame - //johnfitz -- stereo rendering -- full of hacky goodness - if (r_stereo.value) - { - float eyesep = CLAMP(-8.0f, r_stereo.value, 8.0f); - float fdepth = CLAMP(32.0f, r_stereodepth.value, 1024.0f); + //johnfitz -- stereo rendering -- full of hacky goodness + if (r_stereo.value) { + float eyesep = CLAMP(-8.0f, r_stereo.value, 8.0f); + float fdepth = CLAMP(32.0f, r_stereodepth.value, 1024.0f); - AngleVectors (r_refdef.viewangles, vpn, vright, vup); + AngleVectors(r_refdef.viewangles, vpn, vright, vup); - //render left eye (red) - glColorMask(1, 0, 0, 1); - VectorMA (r_refdef.vieworg, -0.5f * eyesep, vright, r_refdef.vieworg); - frustum_skew = 0.5 * eyesep * NEARCLIP / fdepth; - srand((int) (cl.time * 1000)); //sync random stuff between eyes + //render left eye (red) + glColorMask(1, 0, 0, 1); + VectorMA(r_refdef.vieworg, -0.5f * eyesep, vright, r_refdef.vieworg); + frustum_skew = 0.5 * eyesep * NEARCLIP / fdepth; + srand((int) (cl.time * 1000)); //sync random stuff between eyes - R_RenderScene (); + R_RenderScene(); - //render right eye (cyan) - glClear (GL_DEPTH_BUFFER_BIT); - glColorMask(0, 1, 1, 1); - VectorMA (r_refdef.vieworg, 1.0f * eyesep, vright, r_refdef.vieworg); - frustum_skew = -frustum_skew; - srand((int) (cl.time * 1000)); //sync random stuff between eyes + //render right eye (cyan) + glClear(GL_DEPTH_BUFFER_BIT); + glColorMask(0, 1, 1, 1); + VectorMA(r_refdef.vieworg, 1.0f * eyesep, vright, r_refdef.vieworg); + frustum_skew = -frustum_skew; + srand((int) (cl.time * 1000)); //sync random stuff between eyes - R_RenderScene (); + R_RenderScene(); - //restore - glColorMask(1, 1, 1, 1); - VectorMA (r_refdef.vieworg, -0.5f * eyesep, vright, r_refdef.vieworg); - frustum_skew = 0.0f; - } - else - { - R_RenderScene (); - } - //johnfitz + //restore + glColorMask(1, 1, 1, 1); + VectorMA(r_refdef.vieworg, -0.5f * eyesep, vright, r_refdef.vieworg); + frustum_skew = 0.0f; + } else { + R_RenderScene(); + } + //johnfitz - R_ScaleView (); + R_ScaleView(); - //johnfitz -- modified r_speeds output - time2 = Sys_DoubleTime (); - if (r_pos.value) - Con_Printf ("x %i y %i z %i (pitch %i yaw %i roll %i)\n", - (int)cl_entities[cl.viewentity].origin[0], - (int)cl_entities[cl.viewentity].origin[1], - (int)cl_entities[cl.viewentity].origin[2], - (int)cl.viewangles[PITCH], - (int)cl.viewangles[YAW], - (int)cl.viewangles[ROLL]); - else if (r_speeds.value == 2) - Con_Printf ("%3i ms %4i/%4i wpoly %4i/%4i epoly %3i lmap %4i/%4i sky %1.1f mtex\n", - (int)((time2-time1)*1000), - rs_brushpolys, - rs_brushpasses, - rs_aliaspolys, - rs_aliaspasses, - rs_dynamiclightmaps, - rs_skypolys, - rs_skypasses, - TexMgr_FrameUsage ()); - else if (r_speeds.value) - Con_Printf ("%3i ms %4i wpoly %4i epoly %3i lmap\n", - (int)((time2-time1)*1000), - rs_brushpolys, - rs_aliaspolys, - rs_dynamiclightmaps); - //johnfitz + //johnfitz -- modified r_speeds output + time2 = Sys_DoubleTime(); + if (r_pos.value) + Con_Printf("x %i y %i z %i (pitch %i yaw %i roll %i)\n", + (int) cl_entities[cl.viewentity].origin[0], + (int) cl_entities[cl.viewentity].origin[1], + (int) cl_entities[cl.viewentity].origin[2], + (int) cl.viewangles[PITCH], + (int) cl.viewangles[YAW], + (int) cl.viewangles[ROLL]); + else if (r_speeds.value == 2) + Con_Printf("%3i ms %4i/%4i wpoly %4i/%4i epoly %3i lmap %4i/%4i sky %1.1f mtex\n", + (int) ((time2 - time1) * 1000), + rs_brushpolys, + rs_brushpasses, + rs_aliaspolys, + rs_aliaspasses, + rs_dynamiclightmaps, + rs_skypolys, + rs_skypasses, + TexMgr_FrameUsage()); + else if (r_speeds.value) + Con_Printf("%3i ms %4i wpoly %4i epoly %3i lmap\n", + (int) ((time2 - time1) * 1000), + rs_brushpolys, + rs_aliaspolys, + rs_dynamiclightmaps); + //johnfitz } - diff --git a/Quake/gl_rmisc.cpp b/Quake/gl_rmisc.cpp index 81a0900..74b7c3f 100644 --- a/Quake/gl_rmisc.cpp +++ b/Quake/gl_rmisc.cpp @@ -22,35 +22,37 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // r_misc.c +#include + #include "quakedef.hpp" //johnfitz -- new cvars -extern cvar_t r_stereo; -extern cvar_t r_stereodepth; -extern cvar_t r_clearcolor; -extern cvar_t r_drawflat; -extern cvar_t r_flatlightstyles; -extern cvar_t gl_fullbrights; -extern cvar_t gl_farclip; -extern cvar_t gl_overbright; -extern cvar_t gl_overbright_models; -extern cvar_t r_waterquality; -extern cvar_t r_oldwater; -extern cvar_t r_waterwarp; -extern cvar_t r_oldskyleaf; -extern cvar_t r_drawworld; -extern cvar_t r_showtris; -extern cvar_t r_showbboxes; -extern cvar_t r_lerpmodels; -extern cvar_t r_lerpmove; -extern cvar_t r_nolerp_list; -extern cvar_t r_noshadow_list; +extern convar r_stereo; +extern convar r_stereodepth; +extern convar r_clearcolor; +extern convar r_drawflat; +extern convar r_flatlightstyles; +extern convar gl_fullbrights; +extern convar gl_farclip; +extern convar gl_overbright; +extern convar gl_overbright_models; +extern convar r_waterquality; +extern convar r_oldwater; +extern convar r_waterwarp; +extern convar r_oldskyleaf; +extern convar r_drawworld; +extern convar r_showtris; +extern convar r_showbboxes; +extern convar r_lerpmodels; +extern convar r_lerpmove; +extern convar r_nolerp_list; +extern convar r_noshadow_list; //johnfitz -extern cvar_t gl_zfix; // QuakeSpasm z-fighting fix +extern convar gl_zfix; // QuakeSpasm z-fighting fix extern gltexture_t *playertextures[MAX_SCOREBOARD]; //johnfitz -cvar_t r_lightmapwide = {"r_lightmapwide","0",CVAR_ROM}; +convar r_lightmapwide = {"r_lightmapwide", "0", {.rom = true}}; /* @@ -58,9 +60,8 @@ cvar_t r_lightmapwide = {"r_lightmapwide","0",CVAR_ROM}; GL_Overbright_f -- johnfitz ==================== */ -static void GL_Overbright_f (cvar_t *var) -{ - R_RebuildAllLightmaps (); +static void GL_Overbright_f(convar *var) { + R_RebuildAllLightmaps(); } /* @@ -68,9 +69,8 @@ static void GL_Overbright_f (cvar_t *var) GL_Fullbrights_f -- johnfitz ==================== */ -static void GL_Fullbrights_f (cvar_t *var) -{ - TexMgr_ReloadNobrightImages (); +static void GL_Fullbrights_f(convar *var) { + TexMgr_ReloadNobrightImages(); } /* @@ -78,14 +78,13 @@ static void GL_Fullbrights_f (cvar_t *var) R_SetClearColor_f -- johnfitz ==================== */ -static void R_SetClearColor_f (cvar_t *var) -{ - byte *rgb; - int s; +static void R_SetClearColor_f(convar *var) { + byte *rgb; + int s; - s = (int)r_clearcolor.value & 0xFF; - rgb = (byte*)(d_8to24table + s); - glClearColor (rgb[0]/255.0,rgb[1]/255.0,rgb[2]/255.0,0); + s = (int) r_clearcolor.value & 0xFF; + rgb = (byte *) (d_8to24table + s); + glClearColor(rgb[0] / 255.0, rgb[1] / 255.0, rgb[2] / 255.0, 0); } /* @@ -93,11 +92,10 @@ static void R_SetClearColor_f (cvar_t *var) R_Model_ExtraFlags_List_f -- johnfitz -- called when r_nolerp_list or r_noshadow_list cvar changes =============== */ -static void R_Model_ExtraFlags_List_f (cvar_t *var) -{ - int i; - for (i=0; i < MAX_MODELS; i++) - Mod_SetExtraFlags (cl.model_precache[i]); +static void R_Model_ExtraFlags_List_f(convar *var) { + int i; + for (i = 0; i < MAX_MODELS; i++) + Mod_SetExtraFlags(cl.model_precache[i]); } /* @@ -105,9 +103,8 @@ static void R_Model_ExtraFlags_List_f (cvar_t *var) R_SetWateralpha_f -- ericw ==================== */ -static void R_SetWateralpha_f (cvar_t *var) -{ - map_wateralpha = var->value; +static void R_SetWateralpha_f(convar *var) { + map_wateralpha = var->value; } /* @@ -115,9 +112,8 @@ static void R_SetWateralpha_f (cvar_t *var) R_SetLavaalpha_f -- ericw ==================== */ -static void R_SetLavaalpha_f (cvar_t *var) -{ - map_lavaalpha = var->value; +static void R_SetLavaalpha_f(convar *var) { + map_lavaalpha = var->value; } /* @@ -125,9 +121,8 @@ static void R_SetLavaalpha_f (cvar_t *var) R_SetTelealpha_f -- ericw ==================== */ -static void R_SetTelealpha_f (cvar_t *var) -{ - map_telealpha = var->value; +static void R_SetTelealpha_f(convar *var) { + map_telealpha = var->value; } /* @@ -135,9 +130,8 @@ static void R_SetTelealpha_f (cvar_t *var) R_SetSlimealpha_f -- ericw ==================== */ -static void R_SetSlimealpha_f (cvar_t *var) -{ - map_slimealpha = var->value; +static void R_SetSlimealpha_f(convar *var) { + map_slimealpha = var->value; } /* @@ -145,16 +139,15 @@ static void R_SetSlimealpha_f (cvar_t *var) GL_WaterAlphaForSurfface -- ericw ==================== */ -float GL_WaterAlphaForSurface (msurface_t *fa) -{ - if (fa->flags & SURF_DRAWLAVA) - return map_lavaalpha > 0 ? map_lavaalpha : map_wateralpha; - else if (fa->flags & SURF_DRAWTELE) - return map_telealpha > 0 ? map_telealpha : map_wateralpha; - else if (fa->flags & SURF_DRAWSLIME) - return map_slimealpha > 0 ? map_slimealpha : map_wateralpha; - else - return map_wateralpha; +float GL_WaterAlphaForSurface(msurface_t *fa) { + if (fa->flags & SURF_DRAWLAVA) + return map_lavaalpha > 0 ? map_lavaalpha : map_wateralpha; + else if (fa->flags & SURF_DRAWTELE) + return map_telealpha > 0 ? map_telealpha : map_wateralpha; + else if (fa->flags & SURF_DRAWSLIME) + return map_slimealpha > 0 ? map_slimealpha : map_wateralpha; + else + return map_wateralpha; } @@ -163,79 +156,78 @@ float GL_WaterAlphaForSurface (msurface_t *fa) R_Init =============== */ -void R_Init (void) -{ - Cmd_AddCommand ("timerefresh", R_TimeRefresh_f); - Cmd_AddCommand ("pointfile", R_ReadPointFile_f); +void R_Init(void) { + command::add("timerefresh", R_TimeRefresh_f); + command::add("pointfile", R_ReadPointFile_f); - Cvar_RegisterVariable (&r_norefresh); - Cvar_RegisterVariable (&r_lightmap); - Cvar_RegisterVariable (&r_fullbright); - Cvar_RegisterVariable (&r_drawentities); - Cvar_RegisterVariable (&r_drawviewmodel); - Cvar_RegisterVariable (&r_shadows); - Cvar_RegisterVariable (&r_wateralpha); - Cvar_SetCallback (&r_wateralpha, R_SetWateralpha_f); - Cvar_RegisterVariable (&r_litwater); - Cvar_RegisterVariable (&r_dynamic); - Cvar_RegisterVariable (&r_novis); - Cvar_RegisterVariable (&r_speeds); - Cvar_RegisterVariable (&r_pos); + r_norefresh.inscribe(); + r_lightmap.inscribe(); + r_fullbright.inscribe(); + r_drawentities.inscribe(); + r_drawviewmodel.inscribe(); + r_shadows.inscribe(); + r_wateralpha.inscribe(); + r_wateralpha.set_callback(R_SetWateralpha_f); + r_litwater.inscribe(); + r_dynamic.inscribe(); + r_novis.inscribe(); + r_speeds.inscribe(); + r_pos.inscribe(); - Cvar_RegisterVariable (&gl_finish); - Cvar_RegisterVariable (&gl_clear); - Cvar_RegisterVariable (&gl_cull); - Cvar_RegisterVariable (&gl_smoothmodels); - Cvar_RegisterVariable (&gl_affinemodels); - Cvar_RegisterVariable (&gl_polyblend); - Cvar_RegisterVariable (&gl_flashblend); - Cvar_RegisterVariable (&gl_playermip); - Cvar_RegisterVariable (&gl_nocolors); + gl_finish.inscribe(); + gl_clear.inscribe(); + gl_cull.inscribe(); + gl_smoothmodels.inscribe(); + gl_affinemodels.inscribe(); + gl_polyblend.inscribe(); + gl_flashblend.inscribe(); + gl_playermip.inscribe(); + gl_nocolors.inscribe(); - //johnfitz -- new cvars - Cvar_RegisterVariable (&r_stereo); - Cvar_RegisterVariable (&r_stereodepth); - Cvar_RegisterVariable (&r_clearcolor); - Cvar_SetCallback (&r_clearcolor, R_SetClearColor_f); - Cvar_RegisterVariable (&r_waterquality); - Cvar_RegisterVariable (&r_oldwater); - Cvar_RegisterVariable (&r_waterwarp); - Cvar_RegisterVariable (&r_drawflat); - Cvar_RegisterVariable (&r_flatlightstyles); - Cvar_RegisterVariable (&r_oldskyleaf); - Cvar_RegisterVariable (&r_drawworld); - Cvar_RegisterVariable (&r_showtris); - Cvar_RegisterVariable (&r_showbboxes); - Cvar_RegisterVariable (&gl_farclip); - Cvar_RegisterVariable (&gl_fullbrights); - Cvar_RegisterVariable (&gl_overbright); - Cvar_SetCallback (&gl_fullbrights, GL_Fullbrights_f); - Cvar_SetCallback (&gl_overbright, GL_Overbright_f); - Cvar_RegisterVariable (&gl_overbright_models); - Cvar_RegisterVariable (&r_lerpmodels); - Cvar_RegisterVariable (&r_lerpmove); - Cvar_RegisterVariable (&r_nolerp_list); - Cvar_SetCallback (&r_nolerp_list, R_Model_ExtraFlags_List_f); - Cvar_RegisterVariable (&r_noshadow_list); - Cvar_SetCallback (&r_noshadow_list, R_Model_ExtraFlags_List_f); - //johnfitz - Cvar_RegisterVariable (&r_lightmapwide); - Cvar_SetROM ("r_lightmapwide", gl_packed_pixels ? "1" : "0"); + //johnfitz -- new cvars + r_stereo.inscribe(); + r_stereodepth.inscribe(); + r_clearcolor.inscribe(); + r_clearcolor.set_callback(R_SetClearColor_f); + r_waterquality.inscribe(); + r_oldwater.inscribe(); + r_waterwarp.inscribe(); + r_drawflat.inscribe(); + r_flatlightstyles.inscribe(); + r_oldskyleaf.inscribe(); + r_drawworld.inscribe(); + r_showtris.inscribe(); + r_showbboxes.inscribe(); + gl_farclip.inscribe(); + gl_fullbrights.inscribe(); + gl_overbright.inscribe(); + gl_fullbrights.set_callback(GL_Fullbrights_f); + gl_overbright.set_callback(GL_Overbright_f); + gl_overbright_models.inscribe(); + r_lerpmodels.inscribe(); + r_lerpmove.inscribe(); + r_nolerp_list.inscribe(); + r_nolerp_list.set_callback(R_Model_ExtraFlags_List_f); + r_noshadow_list.inscribe(); + r_noshadow_list.set_callback(R_Model_ExtraFlags_List_f); + //johnfitz + r_lightmapwide.inscribe(); + convar::set_rom("r_lightmapwide", gl_packed_pixels ? "1" : "0"); - Cvar_RegisterVariable (&gl_zfix); // QuakeSpasm z-fighting fix - Cvar_RegisterVariable (&r_lavaalpha); - Cvar_RegisterVariable (&r_telealpha); - Cvar_RegisterVariable (&r_slimealpha); - Cvar_RegisterVariable (&r_scale); - Cvar_SetCallback (&r_lavaalpha, R_SetLavaalpha_f); - Cvar_SetCallback (&r_telealpha, R_SetTelealpha_f); - Cvar_SetCallback (&r_slimealpha, R_SetSlimealpha_f); + gl_zfix.inscribe(); // QuakeSpasm z-fighting fix + r_lavaalpha.inscribe(); + r_telealpha.inscribe(); + r_slimealpha.inscribe(); + r_scale.inscribe(); + r_lavaalpha.set_callback(R_SetLavaalpha_f); + r_telealpha.set_callback(R_SetTelealpha_f); + r_slimealpha.set_callback(R_SetSlimealpha_f); - R_InitParticles (); - R_SetClearColor_f (&r_clearcolor); //johnfitz + R_InitParticles(); + R_SetClearColor_f(&r_clearcolor); //johnfitz - Sky_Init (); //johnfitz - Fog_Init (); //johnfitz + Sky_Init(); //johnfitz + Fog_Init(); //johnfitz } /* @@ -243,19 +235,17 @@ void R_Init (void) R_TranslatePlayerSkin -- johnfitz -- rewritten. also, only handles new colors, not new skins =============== */ -void R_TranslatePlayerSkin (int playernum) -{ - int top, bottom; +void R_TranslatePlayerSkin(int playernum) { + int top, bottom; - top = (cl.scores[playernum].colors & 0xf0)>>4; - bottom = cl.scores[playernum].colors &15; + top = (cl.scores[playernum].colors & 0xf0) >> 4; + bottom = cl.scores[playernum].colors & 15; - //FIXME: if gl_nocolors is on, then turned off, the textures may be out of sync with the scoreboard colors. - if (!gl_nocolors.value) - { - if (playertextures[playernum]) - TexMgr_ReloadImage (playertextures[playernum], top, bottom); - } + //FIXME: if gl_nocolors is on, then turned off, the textures may be out of sync with the scoreboard colors. + if (!gl_nocolors.value) { + if (playertextures[playernum]) + TexMgr_ReloadImage(playertextures[playernum], top, bottom); + } } /* @@ -265,39 +255,40 @@ the skin or model actually changes, instead of just new colors added bug fix from bengt jardup =============== */ -void R_TranslateNewPlayerSkin (int playernum) -{ - char name[64]; - byte *pixels; - aliashdr_t *paliashdr; - int skinnum; +void R_TranslateNewPlayerSkin(int playernum) { + char name[64]; + byte *pixels; + aliashdr_t *paliashdr; + int skinnum; -//get correct texture pixels - currententity = &cl_entities[1+playernum]; + //get correct texture pixels + currententity = &cl_entities[1 + playernum]; - if (!currententity->model || currententity->model->type != mod_alias) - return; + if (!currententity->model || currententity->model->type != mod_alias) + return; - paliashdr = (aliashdr_t *)Mod_Extradata (currententity->model); + paliashdr = (aliashdr_t *) Mod_Extradata(currententity->model); - skinnum = currententity->skinnum; + skinnum = currententity->skinnum; - //TODO: move these tests to the place where skinnum gets received from the server - if (skinnum < 0 || skinnum >= paliashdr->numskins) - { - Con_DPrintf("(%d): Invalid player skin #%d\n", playernum, skinnum); - skinnum = 0; - } + //TODO: move these tests to the place where skinnum gets received from the server + if (skinnum < 0 || skinnum >= paliashdr->numskins) { + Con_DPrintf("(%d): Invalid player skin #%d\n", playernum, skinnum); + skinnum = 0; + } - pixels = (byte *)paliashdr + paliashdr->texels[skinnum]; // This is not a persistent place! + pixels = (byte *) paliashdr + paliashdr->texels[skinnum]; // This is not a persistent place! -//upload new image - q_snprintf(name, sizeof(name), "player_%i", playernum); - playertextures[playernum] = TexMgr_LoadImage (currententity->model, name, paliashdr->skinwidth, paliashdr->skinheight, - SRC_INDEXED, pixels, paliashdr->gltextures[skinnum][0]->source_file, paliashdr->gltextures[skinnum][0]->source_offset, TEXPREF_PAD | TEXPREF_OVERWRITE); + //upload new image + q_snprintf(name, sizeof(name), "player_%i", playernum); + playertextures[playernum] = TexMgr_LoadImage(currententity->model, name, paliashdr->skinwidth, + paliashdr->skinheight, + SRC_INDEXED, pixels, paliashdr->gltextures[skinnum][0]->source_file, + paliashdr->gltextures[skinnum][0]->source_offset, + TEXPREF_PAD | TEXPREF_OVERWRITE); -//now recolor it - R_TranslatePlayerSkin (playernum); + //now recolor it + R_TranslatePlayerSkin(playernum); } /* @@ -305,13 +296,12 @@ void R_TranslateNewPlayerSkin (int playernum) R_NewGame -- johnfitz -- handle a game switch =============== */ -void R_NewGame (void) -{ - int i; +void R_NewGame(void) { + int i; - //clear playertexture pointers (the textures themselves were freed by texmgr_newgame) - for (i=0; ientities}; - data = COM_Parse(cl.worldmodel->entities); - if (!data) - return; // error - if (com_token[0] != '{') - return; // error + auto token = common::parse_token(ss); + if (!token.has_value()) + return; // error + if ((*token)[0] != '{') + return; // error - while (1) - { - data = COM_Parse(data); - if (!data) - return; // error - if (com_token[0] == '}') - break; // end of worldspawn - if (com_token[0] == '_') - q_strlcpy(key, com_token + 1, sizeof(key)); - else - q_strlcpy(key, com_token, sizeof(key)); - while (key[0] && key[strlen(key)-1] == ' ') // remove trailing spaces - key[strlen(key)-1] = 0; - data = COM_ParseEx(data, CPE_ALLOWTRUNC); - if (!data) - return; // error - q_strlcpy(value, com_token, sizeof(value)); + while (true) { + token = common::parse_token(ss); + if (!token.has_value()) { + return; // error + } + if ((*token)[0] == '}') { + break; // end of worldspawn + } + if ((*token)[0] == '_') { + key = token->substr(1); + } else { + key = *token; + } + while (!key.empty() && key.back() == ' ') { + // remove trailing spaces + key.pop_back(); + } + token = common::parse_token(ss); + if (!token.has_value()) { + return; // error + } + value = *token; - if (!strcmp("wateralpha", key)) - map_wateralpha = atof(value); + if (key == "wateralpha") { + map_wateralpha = std::strtof(value.c_str(), nullptr); + } - if (!strcmp("lavaalpha", key)) - map_lavaalpha = atof(value); + if (key == "lavaalpha") { + map_lavaalpha = std::strtof(value.c_str(), nullptr); + } - if (!strcmp("telealpha", key)) - map_telealpha = atof(value); + if (key == "telealpha") { + map_telealpha = std::strtof(value.c_str(), nullptr); + } - if (!strcmp("slimealpha", key)) - map_slimealpha = atof(value); - } + if (key == "slimealpha") { + map_slimealpha = std::strtof(value.c_str(), nullptr); + } + } } @@ -375,33 +374,32 @@ static void R_ParseWorldspawn (void) R_NewMap =============== */ -void R_NewMap (void) -{ - int i; +void R_NewMap(void) { + int i; - for (i=0 ; i<256 ; i++) - d_lightstylevalue[i] = 264; // normal light value + for (i = 0; i < 256; i++) + d_lightstylevalue[i] = 264; // normal light value -// clear out efrags in case the level hasn't been reloaded -// FIXME: is this one short? - for (i=0 ; inumleafs ; i++) - cl.worldmodel->leafs[i].efrags = NULL; + // clear out efrags in case the level hasn't been reloaded + // FIXME: is this one short? + for (i = 0; i < cl.worldmodel->numleafs; i++) + cl.worldmodel->leafs[i].efrags = NULL; - r_viewleaf = NULL; - R_ClearParticles (); + r_viewleaf = NULL; + R_ClearParticles(); - GL_BuildLightmaps (); - GL_BuildBModelVertexBuffer (); - //ericw -- no longer load alias models into a VBO here, it's done in Mod_LoadAliasModel + GL_BuildLightmaps(); + GL_BuildBModelVertexBuffer(); + //ericw -- no longer load alias models into a VBO here, it's done in Mod_LoadAliasModel - r_framecount = 0; //johnfitz -- paranoid? - r_visframecount = 0; //johnfitz -- paranoid? + r_framecount = 0; //johnfitz -- paranoid? + r_visframecount = 0; //johnfitz -- paranoid? - Sky_NewMap (); //johnfitz -- skybox in worldspawn - Fog_NewMap (); //johnfitz -- global fog in worldspawn - R_ParseWorldspawn (); //ericw -- wateralpha, lavaalpha, telealpha, slimealpha in worldspawn + Sky_NewMap(); //johnfitz -- skybox in worldspawn + Fog_NewMap(); //johnfitz -- global fog in worldspawn + R_ParseWorldspawn(); //ericw -- wateralpha, lavaalpha, telealpha, slimealpha in worldspawn - load_subdivide_size = gl_subdivide_size.value; //johnfitz -- is this the right place to set this? + load_subdivide_size = gl_subdivide_size.value; //johnfitz -- is this the right place to set this? } /* @@ -411,75 +409,67 @@ R_TimeRefresh_f For program optimization ==================== */ -void R_TimeRefresh_f (void) -{ - int i; - float start, stop, time; +void R_TimeRefresh_f(void) { + int i; + float start, stop, time; - if (cls.state != ca_connected) - { - Con_Printf("Not connected to a server\n"); - return; - } + if (cls.state != ca_connected) { + Con_Printf("Not connected to a server\n"); + return; + } - start = Sys_DoubleTime (); - for (i = 0; i < 128; i++) - { - GL_BeginRendering(&glx, &gly, &glwidth, &glheight); - r_refdef.viewangles[1] = i/128.0*360.0; - R_RenderView (); - GL_EndRendering (); - } + start = Sys_DoubleTime(); + for (i = 0; i < 128; i++) { + GL_BeginRendering(&glx, &gly, &glwidth, &glheight); + r_refdef.viewangles[1] = i / 128.0 * 360.0; + R_RenderView(); + GL_EndRendering(); + } - glFinish (); - stop = Sys_DoubleTime (); - time = stop-start; - Con_Printf ("%f seconds (%f fps)\n", time, 128/time); + glFinish(); + stop = Sys_DoubleTime(); + time = stop - start; + Con_Printf("%f seconds (%f fps)\n", time, 128 / time); } -void D_FlushCaches (void) -{ +void D_FlushCaches(void) { } static GLuint gl_programs[16]; static int gl_num_programs; -static qboolean GL_CheckShader (GLuint shader) -{ - GLint status; - GL_GetShaderivFunc (shader, GL_COMPILE_STATUS, &status); +static qboolean GL_CheckShader(GLuint shader) { + GLint status; + GL_GetShaderivFunc(shader, GL_COMPILE_STATUS, &status); - if (status != GL_TRUE) - { - char infolog[1024]; + if (status != GL_TRUE) { + char infolog[1024]; - memset(infolog, 0, sizeof(infolog)); - GL_GetShaderInfoLogFunc (shader, sizeof(infolog), NULL, infolog); + memset(infolog, 0, sizeof(infolog)); + GL_GetShaderInfoLogFunc(shader, sizeof(infolog), NULL, infolog); - Con_Warning ("GLSL program failed to compile: %s", infolog); + Con_Warning("GLSL program failed to compile: %s", infolog); - return false; - } - return true; + return false; + } + return true; } -static qboolean GL_CheckProgram (GLuint program) -{ - GLint status; - GL_GetProgramivFunc (program, GL_LINK_STATUS, &status); +static qboolean GL_CheckProgram(GLuint program) { + GLint status; + GL_GetProgramivFunc(program, GL_LINK_STATUS, &status); - if (status != GL_TRUE) - { - char infolog[1024]; + if (status != GL_TRUE) { + char infolog[1024]; - memset(infolog, 0, sizeof(infolog)); - GL_GetProgramInfoLogFunc (program, sizeof(infolog), NULL, infolog); + memset(infolog, 0, sizeof(infolog)); + GL_GetProgramInfoLogFunc(program, sizeof(infolog), NULL, infolog); - Con_Warning ("GLSL program failed to link: %s", infolog); + Con_Warning("GLSL program failed to link: %s", infolog); - return false; - } - return true; + return false; + } + return true; } /* @@ -487,20 +477,18 @@ static qboolean GL_CheckProgram (GLuint program) GL_GetUniformLocation ============= */ -GLint GL_GetUniformLocation (GLuint *programPtr, const char *name) -{ - GLint location; +GLint GL_GetUniformLocation(GLuint *programPtr, const char *name) { + GLint location; - if (!programPtr) - return -1; + if (!programPtr) + return -1; - location = GL_GetUniformLocationFunc(*programPtr, name); - if (location == -1) - { - Con_Warning("GL_GetUniformLocationFunc %s failed\n", name); - *programPtr = 0; - } - return location; + location = GL_GetUniformLocationFunc(*programPtr, name); + if (location == -1) { + Con_Warning("GL_GetUniformLocationFunc %s failed\n", name); + *programPtr = 0; + } + return location; } /* @@ -510,61 +498,55 @@ GL_CreateProgram Compiles and returns GLSL program. ==================== */ -GLuint GL_CreateProgram (const GLchar *vertSource, const GLchar *fragSource, int numbindings, const glsl_attrib_binding_t *bindings) -{ - int i; - GLuint program, vertShader, fragShader; +GLuint GL_CreateProgram(const GLchar *vertSource, const GLchar *fragSource, int numbindings, + const glsl_attrib_binding_t *bindings) { + int i; + GLuint program, vertShader, fragShader; - if (!gl_glsl_able) - return 0; + if (!gl_glsl_able) + return 0; - vertShader = GL_CreateShaderFunc (GL_VERTEX_SHADER); - GL_ShaderSourceFunc (vertShader, 1, &vertSource, NULL); - GL_CompileShaderFunc (vertShader); - if (!GL_CheckShader (vertShader)) - { - GL_DeleteShaderFunc (vertShader); - return 0; - } + vertShader = GL_CreateShaderFunc(GL_VERTEX_SHADER); + GL_ShaderSourceFunc(vertShader, 1, &vertSource, NULL); + GL_CompileShaderFunc(vertShader); + if (!GL_CheckShader(vertShader)) { + GL_DeleteShaderFunc(vertShader); + return 0; + } - fragShader = GL_CreateShaderFunc (GL_FRAGMENT_SHADER); - GL_ShaderSourceFunc (fragShader, 1, &fragSource, NULL); - GL_CompileShaderFunc (fragShader); - if (!GL_CheckShader (fragShader)) - { - GL_DeleteShaderFunc (vertShader); - GL_DeleteShaderFunc (fragShader); - return 0; - } + fragShader = GL_CreateShaderFunc(GL_FRAGMENT_SHADER); + GL_ShaderSourceFunc(fragShader, 1, &fragSource, NULL); + GL_CompileShaderFunc(fragShader); + if (!GL_CheckShader(fragShader)) { + GL_DeleteShaderFunc(vertShader); + GL_DeleteShaderFunc(fragShader); + return 0; + } - program = GL_CreateProgramFunc (); - GL_AttachShaderFunc (program, vertShader); - GL_DeleteShaderFunc (vertShader); - GL_AttachShaderFunc (program, fragShader); - GL_DeleteShaderFunc (fragShader); + program = GL_CreateProgramFunc(); + GL_AttachShaderFunc(program, vertShader); + GL_DeleteShaderFunc(vertShader); + GL_AttachShaderFunc(program, fragShader); + GL_DeleteShaderFunc(fragShader); - for (i = 0; i < numbindings; i++) - { - GL_BindAttribLocationFunc (program, bindings[i].attrib, bindings[i].name); - } + for (i = 0; i < numbindings; i++) { + GL_BindAttribLocationFunc(program, bindings[i].attrib, bindings[i].name); + } - GL_LinkProgramFunc (program); + GL_LinkProgramFunc(program); - if (!GL_CheckProgram (program)) - { - GL_DeleteProgramFunc (program); - return 0; - } - else - { - if (gl_num_programs == Q_COUNTOF(gl_programs)) - Host_Error ("gl_programs overflow"); + if (!GL_CheckProgram(program)) { + GL_DeleteProgramFunc(program); + return 0; + } else { + if (gl_num_programs == Q_COUNTOF(gl_programs)) + Host_Error("gl_programs overflow"); - gl_programs[gl_num_programs] = program; - gl_num_programs++; + gl_programs[gl_num_programs] = program; + gl_num_programs++; - return program; - } + return program; + } } /* @@ -574,19 +556,17 @@ R_DeleteShaders Deletes any GLSL programs that have been created. ==================== */ -void R_DeleteShaders (void) -{ - int i; +void R_DeleteShaders(void) { + int i; - if (!gl_glsl_able) - return; + if (!gl_glsl_able) + return; - for (i = 0; i < gl_num_programs; i++) - { - GL_DeleteProgramFunc (gl_programs[i]); - gl_programs[i] = 0; - } - gl_num_programs = 0; + for (i = 0; i < gl_num_programs; i++) { + GL_DeleteProgramFunc(gl_programs[i]); + gl_programs[i] = 0; + } + gl_num_programs = 0; } static GLuint current_array_buffer, current_element_array_buffer; @@ -598,31 +578,28 @@ GL_BindBuffer glBindBuffer wrapper ==================== */ -void GL_BindBuffer (GLenum target, GLuint buffer) -{ - GLuint *cache; +void GL_BindBuffer(GLenum target, GLuint buffer) { + GLuint *cache; - if (!gl_vbo_able) - return; + if (!gl_vbo_able) + return; - switch (target) - { - case GL_ARRAY_BUFFER: - cache = ¤t_array_buffer; - break; - case GL_ELEMENT_ARRAY_BUFFER: - cache = ¤t_element_array_buffer; - break; - default: - Host_Error("GL_BindBuffer: unsupported target %d", (int)target); - return; - } + switch (target) { + case GL_ARRAY_BUFFER: + cache = ¤t_array_buffer; + break; + case GL_ELEMENT_ARRAY_BUFFER: + cache = ¤t_element_array_buffer; + break; + default: + Host_Error("GL_BindBuffer: unsupported target %d", (int) target); + return; + } - if (*cache != buffer) - { - *cache = buffer; - GL_BindBufferFunc (target, *cache); - } + if (*cache != buffer) { + *cache = buffer; + GL_BindBufferFunc(target, *cache); + } } /* @@ -633,13 +610,12 @@ This must be called if you do anything that could make the cached bindings invalid (e.g. manually binding, destroying the context). ==================== */ -void GL_ClearBufferBindings (void) -{ - if (!gl_vbo_able) - return; +void GL_ClearBufferBindings(void) { + if (!gl_vbo_able) + return; - current_array_buffer = 0; - current_element_array_buffer = 0; - GL_BindBufferFunc (GL_ARRAY_BUFFER, 0); - GL_BindBufferFunc (GL_ELEMENT_ARRAY_BUFFER, 0); + current_array_buffer = 0; + current_element_array_buffer = 0; + GL_BindBufferFunc(GL_ARRAY_BUFFER, 0); + GL_BindBufferFunc(GL_ELEMENT_ARRAY_BUFFER, 0); } diff --git a/Quake/gl_screen.cpp b/Quake/gl_screen.cpp index 8e4b4df..bb38400 100644 --- a/Quake/gl_screen.cpp +++ b/Quake/gl_screen.cpp @@ -78,30 +78,30 @@ float scr_con_current; float scr_conlines; // lines of console to display //johnfitz -- new cvars -cvar_t scr_menuscale = {"scr_menuscale", "1", CVAR_ARCHIVE}; -cvar_t scr_sbarscale = {"scr_sbarscale", "1", CVAR_ARCHIVE}; -cvar_t scr_sbaralpha = {"scr_sbaralpha", "0.75", CVAR_ARCHIVE}; -cvar_t scr_conwidth = {"scr_conwidth", "0", CVAR_ARCHIVE}; -cvar_t scr_conscale = {"scr_conscale", "1", CVAR_ARCHIVE}; -cvar_t scr_crosshairscale = {"scr_crosshairscale", "1", CVAR_ARCHIVE}; -cvar_t scr_showfps = {"scr_showfps", "0", CVAR_NONE}; -cvar_t scr_clock = {"scr_clock", "0", CVAR_NONE}; +convar scr_menuscale = {"scr_menuscale", "1", {.archive = true}}; +convar scr_sbarscale = {"scr_sbarscale", "1", {.archive = true}}; +convar scr_sbaralpha = {"scr_sbaralpha", "0.75", {.archive = true}}; +convar scr_conwidth = {"scr_conwidth", "0", {.archive = true}}; +convar scr_conscale = {"scr_conscale", "1", {.archive = true}}; +convar scr_crosshairscale = {"scr_crosshairscale", "1", {.archive = true}}; +convar scr_showfps = {"scr_showfps", "0"}; +convar scr_clock = {"scr_clock", "0"}; //johnfitz -cvar_t scr_usekfont = {"scr_usekfont", "0", CVAR_NONE}; // 2021 re-release +convar scr_usekfont = {"scr_usekfont", "0"}; // 2021 re-release -cvar_t scr_viewsize = {"viewsize","100", CVAR_ARCHIVE}; -cvar_t scr_fov = {"fov","90",CVAR_NONE}; // 10 - 170 -cvar_t scr_fov_adapt = {"fov_adapt","1",CVAR_ARCHIVE}; -cvar_t scr_conspeed = {"scr_conspeed","500",CVAR_ARCHIVE}; -cvar_t scr_centertime = {"scr_centertime","2",CVAR_NONE}; -cvar_t scr_showturtle = {"showturtle","0",CVAR_NONE}; -cvar_t scr_showpause = {"showpause","1",CVAR_NONE}; -cvar_t scr_printspeed = {"scr_printspeed","8",CVAR_NONE}; -cvar_t gl_triplebuffer = {"gl_triplebuffer", "1", CVAR_ARCHIVE}; +convar scr_viewsize = {"viewsize","100", {.archive = true}}; +convar scr_fov = {"fov","90"}; // 10 - 170 +convar scr_fov_adapt = {"fov_adapt","1",{.archive = true}}; +convar scr_conspeed = {"scr_conspeed","500",{.archive = true}}; +convar scr_centertime = {"scr_centertime","2"}; +convar scr_showturtle = {"showturtle","0"}; +convar scr_showpause = {"showpause","1"}; +convar scr_printspeed = {"scr_printspeed","8"}; +convar gl_triplebuffer = {"gl_triplebuffer", "1", {.archive = true}}; -cvar_t cl_gun_fovscale = {"cl_gun_fovscale","1",CVAR_ARCHIVE}; // Qrack +convar cl_gun_fovscale = {"cl_gun_fovscale","1",{.archive = true}}; // Qrack -extern cvar_t crosshair; +extern convar crosshair; qboolean scr_initialized; // ready to draw @@ -291,15 +291,15 @@ static void SCR_CalcRefdef (void) // bound viewsize if (scr_viewsize.value < 30) - Cvar_SetQuick (&scr_viewsize, "30"); + scr_viewsize.set("30"); if (scr_viewsize.value > 120) - Cvar_SetQuick (&scr_viewsize, "120"); + scr_viewsize.set("120"); // bound fov if (scr_fov.value < 10) - Cvar_SetQuick (&scr_fov, "10"); + scr_fov.set("10"); if (scr_fov.value > 170) - Cvar_SetQuick (&scr_fov, "170"); + scr_fov.set("170"); vid.recalc_refdef = 0; @@ -314,12 +314,12 @@ static void SCR_CalcRefdef (void) else sb_lines = 48 * scale; - size = q_min(scr_viewsize.value, 100.f) / 100; + size = std::min(scr_viewsize.value, 100.f) / 100; //johnfitz //johnfitz -- rewrote this section - r_refdef.vrect.width = q_max(glwidth * size, 96.0f); //no smaller than 96, for icons - r_refdef.vrect.height = q_min((int)(glheight * size), glheight - sb_lines); //make room for sbar + r_refdef.vrect.width = std::max(glwidth * size, 96.0f); //no smaller than 96, for icons + r_refdef.vrect.height = std::min((int)(glheight * size), glheight - sb_lines); //make room for sbar r_refdef.vrect.x = (glwidth - r_refdef.vrect.width)/2; r_refdef.vrect.y = (glheight - sb_lines - r_refdef.vrect.height)/2; //johnfitz @@ -340,7 +340,7 @@ Keybinding command */ void SCR_SizeUp_f (void) { - Cvar_SetValueQuick (&scr_viewsize, scr_viewsize.value+10); + scr_viewsize.set_value(scr_viewsize.value+10); } @@ -353,10 +353,10 @@ Keybinding command */ void SCR_SizeDown_f (void) { - Cvar_SetValueQuick (&scr_viewsize, scr_viewsize.value-10); + scr_viewsize.set_value(scr_viewsize.value-10); } -static void SCR_Callback_refdef (cvar_t *var) +static void SCR_Callback_refdef (convar *var) { vid.recalc_refdef = 1; } @@ -366,7 +366,7 @@ static void SCR_Callback_refdef (cvar_t *var) SCR_Conwidth_f -- johnfitz -- called when scr_conwidth or scr_conscale changes ================== */ -void SCR_Conwidth_f (cvar_t *var) +void SCR_Conwidth_f (convar *var) { vid.recalc_refdef = 1; vid.conwidth = (scr_conwidth.value > 0) ? (int)scr_conwidth.value : (scr_conscale.value > 0) ? (int)(vid.width/scr_conscale.value) : vid.width; @@ -396,36 +396,36 @@ SCR_Init void SCR_Init (void) { //johnfitz -- new cvars - Cvar_RegisterVariable (&scr_menuscale); - Cvar_RegisterVariable (&scr_sbarscale); - Cvar_SetCallback (&scr_sbaralpha, SCR_Callback_refdef); - Cvar_RegisterVariable (&scr_sbaralpha); - Cvar_SetCallback (&scr_conwidth, &SCR_Conwidth_f); - Cvar_SetCallback (&scr_conscale, &SCR_Conwidth_f); - Cvar_RegisterVariable (&scr_conwidth); - Cvar_RegisterVariable (&scr_conscale); - Cvar_RegisterVariable (&scr_crosshairscale); - Cvar_RegisterVariable (&scr_showfps); - Cvar_RegisterVariable (&scr_clock); + scr_menuscale.inscribe(); + scr_sbarscale.inscribe(); + scr_sbaralpha.set_callback(SCR_Callback_refdef); + scr_sbaralpha.inscribe(); + scr_conwidth.set_callback(&SCR_Conwidth_f); + scr_conscale.set_callback(&SCR_Conwidth_f); + scr_conwidth.inscribe(); + scr_conscale.inscribe(); + scr_crosshairscale.inscribe(); + scr_showfps.inscribe(); + scr_clock.inscribe(); //johnfitz - Cvar_RegisterVariable (&scr_usekfont); // 2021 re-release - Cvar_SetCallback (&scr_fov, SCR_Callback_refdef); - Cvar_SetCallback (&scr_fov_adapt, SCR_Callback_refdef); - Cvar_SetCallback (&scr_viewsize, SCR_Callback_refdef); - Cvar_RegisterVariable (&scr_fov); - Cvar_RegisterVariable (&scr_fov_adapt); - Cvar_RegisterVariable (&scr_viewsize); - Cvar_RegisterVariable (&scr_conspeed); - Cvar_RegisterVariable (&scr_showturtle); - Cvar_RegisterVariable (&scr_showpause); - Cvar_RegisterVariable (&scr_centertime); - Cvar_RegisterVariable (&scr_printspeed); - Cvar_RegisterVariable (&gl_triplebuffer); - Cvar_RegisterVariable (&cl_gun_fovscale); + scr_usekfont.inscribe(); // 2021 re-release + scr_fov.set_callback(SCR_Callback_refdef); + scr_fov_adapt.set_callback(SCR_Callback_refdef); + scr_viewsize.set_callback(SCR_Callback_refdef); + scr_fov.inscribe(); + scr_fov_adapt.inscribe(); + scr_viewsize.inscribe(); + scr_conspeed.inscribe(); + scr_showturtle.inscribe(); + scr_showpause.inscribe(); + scr_centertime.inscribe(); + scr_printspeed.inscribe(); + gl_triplebuffer.inscribe(); + cl_gun_fovscale.inscribe(); - Cmd_AddCommand ("screenshot",SCR_ScreenShot_f); - Cmd_AddCommand ("sizeup",SCR_SizeUp_f); - Cmd_AddCommand ("sizedown",SCR_SizeDown_f); + command::add ("screenshot",SCR_ScreenShot_f); + command::add ("sizeup",SCR_SizeUp_f); + command::add ("sizedown",SCR_SizeDown_f); SCR_LoadPics (); //johnfitz @@ -666,7 +666,7 @@ SCR_SetUpToDrawConsole void SCR_SetUpToDrawConsole (void) { //johnfitz -- let's hack away the problem of slow console when host_timescale is <0 - extern cvar_t host_timescale; + extern convar host_timescale; float timescale, conspeed; //johnfitz @@ -765,9 +765,9 @@ void SCR_ScreenShot_f (void) Q_strncpy (ext, "png", sizeof(ext)); - if (Cmd_Argc () >= 2) + if (command::argc () >= 2) { - const char *requested_ext = Cmd_Argv (1); + const char *requested_ext = command::argv (1)->c_str(); if (!q_strcasecmp ("png", requested_ext) || !q_strcasecmp ("tga", requested_ext) @@ -782,8 +782,8 @@ void SCR_ScreenShot_f (void) // read quality as the 3rd param (only used for JPG) quality = 90; - if (Cmd_Argc () >= 3) - quality = Q_atoi (Cmd_Argv(2)); + if (command::argc () >= 3) + quality = Q_atoi (command::argv(2)->c_str()); if (quality < 1 || quality > 100) { SCR_ScreenShot_Usage (); diff --git a/Quake/gl_sky.cpp b/Quake/gl_sky.cpp index 28956ca..4141e43 100644 --- a/Quake/gl_sky.cpp +++ b/Quake/gl_sky.cpp @@ -22,6 +22,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //gl_sky.c +#include + #include "quakedef.hpp" #define MAX_CLIP_VERTS 64 @@ -40,11 +42,11 @@ static char skybox_name[1024]; //name of current skybox, or "" if no skybox static gltexture_t *skybox_textures[6]; static gltexture_t *solidskytexture, *alphaskytexture; -extern cvar_t gl_farclip; -static cvar_t r_fastsky = {"r_fastsky", "0", CVAR_NONE}; -static cvar_t r_sky_quality = {"r_sky_quality", "12", CVAR_NONE}; -static cvar_t r_skyalpha = {"r_skyalpha", "1", CVAR_NONE}; -static cvar_t r_skyfog = {"r_skyfog","0.5",CVAR_NONE}; +extern convar gl_farclip; +static convar r_fastsky{"r_fastsky", "0"}; +static convar r_sky_quality{"r_sky_quality", "12"}; +static convar r_skyalpha{"r_skyalpha", "1"}; +static convar r_skyfog{"r_skyfog","0.5"}; static const int skytexorder[6] = {0,2,1,3,4,5}; //for skybox @@ -298,53 +300,60 @@ Sky_NewMap */ void Sky_NewMap (void) { - char key[128], value[4096]; - const char *data; - skyfog = r_skyfog.value; + std::string key{}; + std::string value{}; + // // read worldspawn (this is so ugly, and shouldn't it be done on the server?) // - data = cl.worldmodel->entities; - if (!data) + std::istringstream ss{cl.worldmodel->entities}; + if (ss.eof()) return; //FIXME: how could this possibly ever happen? -- if there's no // worldspawn then the sever wouldn't send the loadmap message to the client - data = COM_Parse(data); - if (!data) //should never happen + auto token = common::parse_token(ss); + if (!token.has_value()) { + //should never happen return; // error - if (com_token[0] != '{') //should never happen + } + if (token->front() != '{') { + //should never happen return; // error - while (1) + } + while (true) { - data = COM_Parse(data); - if (!data) + token = common::parse_token(ss); + if (!token.has_value()) { return; // error - if (com_token[0] == '}') + } + if (token->front() == '}') { break; // end of worldspawn - if (com_token[0] == '_') - q_strlcpy(key, com_token + 1, sizeof(key)); - else - q_strlcpy(key, com_token, sizeof(key)); - while (key[0] && key[strlen(key)-1] == ' ') // remove trailing spaces - key[strlen(key)-1] = 0; - data = COM_ParseEx(data, CPE_ALLOWTRUNC); - if (!data) + } + if (token->front() == '_') { + key = token->substr(1); + } + else { + key = token.value(); + } + while (!key.empty() && key.back() == ' ') { + key.pop_back(); + } + + token = common::parse_token(ss); + if (!token.has_value()) { return; // error - q_strlcpy(value, com_token, sizeof(value)); + } + value = token.value(); - if (!strcmp("sky", key)) - Sky_LoadSkyBox(value); + if (key == "sky" || key == "skyname" || key == "qlsky") { + Sky_LoadSkyBox(value.c_str()); + } - if (!strcmp("skyfog", key)) - skyfog = atof(value); -#if 1 /* also accept non-standard keys */ - else if (!strcmp("skyname", key)) //half-life - Sky_LoadSkyBox(value); - else if (!strcmp("qlsky", key)) //quake lives - Sky_LoadSkyBox(value); -#endif + if (key == "skyfog") { + skyfog = std::strtof(value.c_str(), nullptr); + } } } @@ -355,13 +364,13 @@ Sky_SkyCommand_f */ void Sky_SkyCommand_f (void) { - switch (Cmd_Argc()) + switch (command::argc()) { case 1: Con_Printf("\"sky\" is \"%s\"\n", skybox_name); break; case 2: - Sky_LoadSkyBox(Cmd_Argv(1)); + Sky_LoadSkyBox(command::argv(1)->c_str()); break; default: Con_Printf("usage: sky \n"); @@ -373,7 +382,7 @@ void Sky_SkyCommand_f (void) R_SetSkyfog_f -- ericw ==================== */ -static void R_SetSkyfog_f (cvar_t *var) +static void R_SetSkyfog_f (convar *var) { // clear any skyfog setting from worldspawn skyfog = var->value; @@ -388,13 +397,13 @@ void Sky_Init (void) { int i; - Cvar_RegisterVariable (&r_fastsky); - Cvar_RegisterVariable (&r_sky_quality); - Cvar_RegisterVariable (&r_skyalpha); - Cvar_RegisterVariable (&r_skyfog); - Cvar_SetCallback (&r_skyfog, R_SetSkyfog_f); + r_fastsky.inscribe(); + r_sky_quality.inscribe(); + r_skyalpha.inscribe(); + r_skyfog.inscribe(); + r_skyfog.set_callback(R_SetSkyfog_f); - Cmd_AddCommand ("sky",Sky_SkyCommand_f); + command::add ("sky",Sky_SkyCommand_f); skybox_name[0] = 0; for (i=0; i<6; i++) @@ -1020,7 +1029,7 @@ void Sky_DrawFace (int axis) VectorSubtract(verts[2],verts[3],up); VectorSubtract(verts[2],verts[1],right); - di = q_max((int)r_sky_quality.value, 1); + di = std::max((int)r_sky_quality.value, 1); qi = 1.0 / di; dj = (axis < 4) ? di*2 : di; //subdivide vertically more than horizontally on skybox sides qj = 1.0 / dj; diff --git a/Quake/gl_texmgr.cpp b/Quake/gl_texmgr.cpp index 6e4c531..7aa37a9 100644 --- a/Quake/gl_texmgr.cpp +++ b/Quake/gl_texmgr.cpp @@ -24,19 +24,20 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.hpp" -static const int gl_solid_format = 3; -static const int gl_alpha_format = 4; +static const int gl_solid_format = 3; +static const int gl_alpha_format = 4; -static cvar_t gl_texturemode = {"gl_texturemode", "", CVAR_ARCHIVE}; -static cvar_t gl_texture_anisotropy = {"gl_texture_anisotropy", "1", CVAR_ARCHIVE}; -static cvar_t gl_max_size = {"gl_max_size", "0", CVAR_NONE}; -static cvar_t gl_picmip = {"gl_picmip", "0", CVAR_NONE}; -static GLint gl_hardware_maxsize; +static convar gl_texturemode{"gl_texturemode", "", {.archive = true}}; +static convar gl_texture_anisotropy{"gl_texture_anisotropy", "1", {.archive = true}}; +static convar gl_max_size{"gl_max_size", "0"}; +static convar gl_picmip{"gl_picmip", "0"}; + +static GLint gl_hardware_maxsize; #define MAX_GLTEXTURES 4096 static int numgltextures; -static gltexture_t *active_gltextures, *free_gltextures; -gltexture_t *notexture, *nulltexture; +static gltexture_t *active_gltextures, *free_gltextures; +gltexture_t *notexture, *nulltexture; unsigned int d_8to24table[256]; unsigned int d_8to24table_fbright[256]; @@ -53,19 +54,19 @@ unsigned int d_8to24table_conchars[256]; ================================================================================ */ -typedef struct -{ - int magfilter; - int minfilter; - const char *name; +typedef struct { + int magfilter; + int minfilter; + const char *name; } glmode_t; + static glmode_t glmodes[] = { - {GL_NEAREST, GL_NEAREST, "GL_NEAREST"}, - {GL_NEAREST, GL_NEAREST_MIPMAP_NEAREST, "GL_NEAREST_MIPMAP_NEAREST"}, - {GL_NEAREST, GL_NEAREST_MIPMAP_LINEAR, "GL_NEAREST_MIPMAP_LINEAR"}, - {GL_LINEAR, GL_LINEAR, "GL_LINEAR"}, - {GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, "GL_LINEAR_MIPMAP_NEAREST"}, - {GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, "GL_LINEAR_MIPMAP_LINEAR"}, + {GL_NEAREST, GL_NEAREST, "GL_NEAREST"}, + {GL_NEAREST, GL_NEAREST_MIPMAP_NEAREST, "GL_NEAREST_MIPMAP_NEAREST"}, + {GL_NEAREST, GL_NEAREST_MIPMAP_LINEAR, "GL_NEAREST_MIPMAP_LINEAR"}, + {GL_LINEAR, GL_LINEAR, "GL_LINEAR"}, + {GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, "GL_LINEAR_MIPMAP_NEAREST"}, + {GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, "GL_LINEAR_MIPMAP_LINEAR"}, }; #define NUM_GLMODES (int)Q_COUNTOF(glmodes) static int glmode_idx = NUM_GLMODES - 1; /* trilinear */ @@ -75,12 +76,11 @@ static int glmode_idx = NUM_GLMODES - 1; /* trilinear */ TexMgr_DescribeTextureModes_f -- report available texturemodes =============== */ -static void TexMgr_DescribeTextureModes_f (void) -{ - int i; - for (i = 0; i < NUM_GLMODES; i++) - Con_SafePrintf (" %2i: %s\n", i + 1, glmodes[i].name); - Con_Printf ("%i modes\n", i); +static void TexMgr_DescribeTextureModes_f(void) { + int i; + for (i = 0; i < NUM_GLMODES; i++) + Con_SafePrintf(" %2i: %s\n", i + 1, glmodes[i].name); + Con_Printf("%i modes\n", i); } /* @@ -88,31 +88,23 @@ static void TexMgr_DescribeTextureModes_f (void) TexMgr_SetFilterModes =============== */ -static void TexMgr_SetFilterModes (gltexture_t *glt) -{ - GL_Bind (glt); +static void TexMgr_SetFilterModes(gltexture_t *glt) { + GL_Bind(glt); - if (glt->flags & TEXPREF_NEAREST) - { - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - } - else if (glt->flags & TEXPREF_LINEAR) - { - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - } - else if (glt->flags & TEXPREF_MIPMAP) - { - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, glmodes[glmode_idx].magfilter); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, glmodes[glmode_idx].minfilter); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, gl_texture_anisotropy.value); - } - else - { - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, glmodes[glmode_idx].magfilter); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, glmodes[glmode_idx].magfilter); - } + if (glt->flags & TEXPREF_NEAREST) { + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + } else if (glt->flags & TEXPREF_LINEAR) { + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + } else if (glt->flags & TEXPREF_MIPMAP) { + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, glmodes[glmode_idx].magfilter); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, glmodes[glmode_idx].minfilter); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, gl_texture_anisotropy.value); + } else { + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, glmodes[glmode_idx].magfilter); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, glmodes[glmode_idx].magfilter); + } } /* @@ -120,45 +112,38 @@ static void TexMgr_SetFilterModes (gltexture_t *glt) TexMgr_TextureMode_f -- called when gl_texturemode changes =============== */ -static void TexMgr_TextureMode_f (cvar_t *var) -{ - gltexture_t *glt; - int i; +static void TexMgr_TextureMode_f(convar *var) { + gltexture_t *glt; + int i; - for (i = 0; i < NUM_GLMODES; i++) - { - if (!Q_strcmp (glmodes[i].name, gl_texturemode.string)) - { - if (glmode_idx != i) - { - glmode_idx = i; - for (glt = active_gltextures; glt; glt = glt->next) - TexMgr_SetFilterModes (glt); - Sbar_Changed (); //sbar graphics need to be redrawn with new filter mode - //FIXME: warpimages need to be redrawn, too. - } - return; - } - } + for (i = 0; i < NUM_GLMODES; i++) { + if (!Q_strcmp(glmodes[i].name, gl_texturemode.string)) { + if (glmode_idx != i) { + glmode_idx = i; + for (glt = active_gltextures; glt; glt = glt->next) + TexMgr_SetFilterModes(glt); + Sbar_Changed(); //sbar graphics need to be redrawn with new filter mode + //FIXME: warpimages need to be redrawn, too. + } + return; + } + } - for (i = 0; i < NUM_GLMODES; i++) - { - if (!q_strcasecmp (glmodes[i].name, gl_texturemode.string)) - { - Cvar_SetQuick (&gl_texturemode, glmodes[i].name); - return; - } - } + for (i = 0; i < NUM_GLMODES; i++) { + if (!q_strcasecmp(glmodes[i].name, gl_texturemode.string)) { + gl_texturemode.set(glmodes[i].name); + return; + } + } - i = atoi(gl_texturemode.string); - if (i >= 1 && i <= NUM_GLMODES) - { - Cvar_SetQuick (&gl_texturemode, glmodes[i-1].name); - return; - } + i = atoi(gl_texturemode.string); + if (i >= 1 && i <= NUM_GLMODES) { + gl_texturemode.set(glmodes[i - 1].name); + return; + } - Con_Printf ("\"%s\" is not a valid texturemode\n", gl_texturemode.string); - Cvar_SetQuick (&gl_texturemode, glmodes[glmode_idx].name); + Con_Printf("\"%s\" is not a valid texturemode\n", gl_texturemode.string); + gl_texturemode.set(glmodes[glmode_idx].name); } /* @@ -166,30 +151,23 @@ static void TexMgr_TextureMode_f (cvar_t *var) TexMgr_Anisotropy_f -- called when gl_texture_anisotropy changes =============== */ -static void TexMgr_Anisotropy_f (cvar_t *var) -{ - if (gl_texture_anisotropy.value < 1) - { - Cvar_SetQuick (&gl_texture_anisotropy, "1"); - } - else if (gl_texture_anisotropy.value > gl_max_anisotropy) - { - Cvar_SetValueQuick (&gl_texture_anisotropy, gl_max_anisotropy); - } - else - { - gltexture_t *glt; - for (glt = active_gltextures; glt; glt = glt->next) - { - /* TexMgr_SetFilterModes (glt);*/ - if (glt->flags & TEXPREF_MIPMAP) { - GL_Bind (glt); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, glmodes[glmode_idx].magfilter); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, glmodes[glmode_idx].minfilter); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, gl_texture_anisotropy.value); - } - } - } +static void TexMgr_Anisotropy_f(convar *var) { + if (gl_texture_anisotropy.value < 1) { + gl_texture_anisotropy.set("1"); + } else if (gl_texture_anisotropy.value > gl_max_anisotropy) { + gl_texture_anisotropy.set_value(gl_max_anisotropy); + } else { + gltexture_t *glt; + for (glt = active_gltextures; glt; glt = glt->next) { + /* TexMgr_SetFilterModes (glt);*/ + if (glt->flags & TEXPREF_MIPMAP) { + GL_Bind(glt); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, glmodes[glmode_idx].magfilter); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, glmodes[glmode_idx].minfilter); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, gl_texture_anisotropy.value); + } + } + } } /* @@ -197,23 +175,21 @@ static void TexMgr_Anisotropy_f (cvar_t *var) TexMgr_Imagelist_f -- report loaded textures =============== */ -static void TexMgr_Imagelist_f (void) -{ - float mb; - float texels = 0; - gltexture_t *glt; +static void TexMgr_Imagelist_f(void) { + float mb; + float texels = 0; + gltexture_t *glt; - for (glt = active_gltextures; glt; glt = glt->next) - { - Con_SafePrintf (" %4i x%4i %s\n", glt->width, glt->height, glt->name); - if (glt->flags & TEXPREF_MIPMAP) - texels += glt->width * glt->height * 4.0f / 3.0f; - else - texels += (glt->width * glt->height); - } + for (glt = active_gltextures; glt; glt = glt->next) { + Con_SafePrintf(" %4i x%4i %s\n", glt->width, glt->height, glt->name); + if (glt->flags & TEXPREF_MIPMAP) + texels += glt->width * glt->height * 4.0f / 3.0f; + else + texels += (glt->width * glt->height); + } - mb = texels * (Cvar_VariableValue("vid_bpp") / 8.0f) / 0x100000; - Con_Printf ("%i textures %i pixels %1.1f megabytes\n", numgltextures, (int)texels, mb); + mb = texels * (convar::variable_value("vid_bpp").value_or(0.0) / 8.0f) / 0x100000; + Con_Printf("%i textures %i pixels %1.1f megabytes\n", numgltextures, (int) texels, mb); } /* @@ -221,45 +197,40 @@ static void TexMgr_Imagelist_f (void) TexMgr_Imagedump_f -- dump all current textures to TGA files =============== */ -static void TexMgr_Imagedump_f (void) -{ - char tganame[MAX_OSPATH], tempname[MAX_OSPATH], dirname[MAX_OSPATH]; - gltexture_t *glt; - byte *buffer; - char *c; +static void TexMgr_Imagedump_f(void) { + char tganame[MAX_OSPATH], tempname[MAX_OSPATH], dirname[MAX_OSPATH]; + gltexture_t *glt; + byte *buffer; + char *c; - //create directory - q_snprintf(dirname, sizeof(dirname), "%s/imagedump", com_gamedir); - Sys_mkdir (dirname); + //create directory + q_snprintf(dirname, sizeof(dirname), "%s/imagedump", com_gamedir); + Sys_mkdir(dirname); - //loop through textures - for (glt = active_gltextures; glt; glt = glt->next) - { - q_strlcpy (tempname, glt->name, sizeof(tempname)); - while ((c = strchr(tempname, ':')) != NULL) *c = '_'; - while ((c = strchr(tempname, '/')) != NULL) *c = '_'; - while ((c = strchr(tempname, '*')) != NULL) *c = '_'; - q_snprintf(tganame, sizeof(tganame), "imagedump/%s.tga", tempname); + //loop through textures + for (glt = active_gltextures; glt; glt = glt->next) { + q_strlcpy(tempname, glt->name, sizeof(tempname)); + while ((c = strchr(tempname, ':')) != NULL) *c = '_'; + while ((c = strchr(tempname, '/')) != NULL) *c = '_'; + while ((c = strchr(tempname, '*')) != NULL) *c = '_'; + q_snprintf(tganame, sizeof(tganame), "imagedump/%s.tga", tempname); - GL_Bind (glt); - glPixelStorei (GL_PACK_ALIGNMENT, 1);/* for widths that aren't a multiple of 4 */ + GL_Bind(glt); + glPixelStorei(GL_PACK_ALIGNMENT, 1); /* for widths that aren't a multiple of 4 */ - if (glt->flags & TEXPREF_ALPHA) - { - buffer = (byte *) malloc(glt->width*glt->height*4); - glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); - Image_WriteTGA (tganame, buffer, glt->width, glt->height, 32, true); - } - else - { - buffer = (byte *) malloc(glt->width*glt->height*3); - glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_BYTE, buffer); - Image_WriteTGA (tganame, buffer, glt->width, glt->height, 24, true); - } - free (buffer); - } + if (glt->flags & TEXPREF_ALPHA) { + buffer = (byte *) malloc(glt->width * glt->height * 4); + glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); + Image_WriteTGA(tganame, buffer, glt->width, glt->height, 32, true); + } else { + buffer = (byte *) malloc(glt->width * glt->height * 3); + glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_BYTE, buffer); + Image_WriteTGA(tganame, buffer, glt->width, glt->height, 24, true); + } + free(buffer); + } - Con_Printf ("dumped %i textures to %s\n", numgltextures, dirname); + Con_Printf("dumped %i textures to %s\n", numgltextures, dirname); } /* @@ -267,25 +238,22 @@ static void TexMgr_Imagedump_f (void) TexMgr_FrameUsage -- report texture memory usage for this frame =============== */ -float TexMgr_FrameUsage (void) -{ - float mb; - float texels = 0; - gltexture_t *glt; +float TexMgr_FrameUsage(void) { + float mb; + float texels = 0; + gltexture_t *glt; - for (glt = active_gltextures; glt; glt = glt->next) - { - if (glt->visframe == r_framecount) - { - if (glt->flags & TEXPREF_MIPMAP) - texels += glt->width * glt->height * 4.0f / 3.0f; - else - texels += (glt->width * glt->height); - } - } + for (glt = active_gltextures; glt; glt = glt->next) { + if (glt->visframe == r_framecount) { + if (glt->flags & TEXPREF_MIPMAP) + texels += glt->width * glt->height * 4.0f / 3.0f; + else + texels += (glt->width * glt->height); + } + } - mb = texels * (Cvar_VariableValue("vid_bpp") / 8.0f) / 0x100000; - return mb; + mb = texels * (convar::variable_value("vid_bpp").value_or(0.0) / 8.0f) / 0x100000; + return mb; } /* @@ -301,20 +269,17 @@ float TexMgr_FrameUsage (void) TexMgr_FindTexture ================ */ -gltexture_t *TexMgr_FindTexture (qmodel_t *owner, const char *name) -{ - gltexture_t *glt; +gltexture_t *TexMgr_FindTexture(qmodel_t *owner, const char *name) { + gltexture_t *glt; - if (name) - { - for (glt = active_gltextures; glt; glt = glt->next) - { - if (glt->owner == owner && !strcmp (glt->name, name)) - return glt; - } - } + if (name) { + for (glt = active_gltextures; glt; glt = glt->next) { + if (glt->owner == owner && !strcmp(glt->name, name)) + return glt; + } + } - return NULL; + return NULL; } /* @@ -322,24 +287,23 @@ gltexture_t *TexMgr_FindTexture (qmodel_t *owner, const char *name) TexMgr_NewTexture ================ */ -gltexture_t *TexMgr_NewTexture (void) -{ - gltexture_t *glt; +gltexture_t *TexMgr_NewTexture(void) { + gltexture_t *glt; - if (numgltextures == MAX_GLTEXTURES) - Sys_Error("numgltextures == MAX_GLTEXTURES\n"); + if (numgltextures == MAX_GLTEXTURES) + Sys_Error("numgltextures == MAX_GLTEXTURES\n"); - glt = free_gltextures; - free_gltextures = glt->next; - glt->next = active_gltextures; - active_gltextures = glt; + glt = free_gltextures; + free_gltextures = glt->next; + glt->next = active_gltextures; + active_gltextures = glt; - glGenTextures(1, &glt->texnum); - numgltextures++; - return glt; + glGenTextures(1, &glt->texnum); + numgltextures++; + return glt; } -static void GL_DeleteTexture (gltexture_t *texture); +static void GL_DeleteTexture(gltexture_t *texture); //ericw -- workaround for preventing TexMgr_FreeTexture during TexMgr_ReloadImages static qboolean in_reload_images; @@ -349,45 +313,40 @@ static qboolean in_reload_images; TexMgr_FreeTexture ================ */ -void TexMgr_FreeTexture (gltexture_t *kill) -{ - gltexture_t *glt; +void TexMgr_FreeTexture(gltexture_t *kill) { + gltexture_t *glt; - if (in_reload_images) - return; + if (in_reload_images) + return; - if (kill == NULL) - { - Con_Printf ("TexMgr_FreeTexture: NULL texture\n"); - return; - } + if (kill == NULL) { + Con_Printf("TexMgr_FreeTexture: NULL texture\n"); + return; + } - if (active_gltextures == kill) - { - active_gltextures = kill->next; - kill->next = free_gltextures; - free_gltextures = kill; + if (active_gltextures == kill) { + active_gltextures = kill->next; + kill->next = free_gltextures; + free_gltextures = kill; - GL_DeleteTexture(kill); - numgltextures--; - return; - } + GL_DeleteTexture(kill); + numgltextures--; + return; + } - for (glt = active_gltextures; glt; glt = glt->next) - { - if (glt->next == kill) - { - glt->next = kill->next; - kill->next = free_gltextures; - free_gltextures = kill; + for (glt = active_gltextures; glt; glt = glt->next) { + if (glt->next == kill) { + glt->next = kill->next; + kill->next = free_gltextures; + free_gltextures = kill; - GL_DeleteTexture(kill); - numgltextures--; - return; - } - } + GL_DeleteTexture(kill); + numgltextures--; + return; + } + } - Con_Printf ("TexMgr_FreeTexture: not found\n"); + Con_Printf("TexMgr_FreeTexture: not found\n"); } /* @@ -397,16 +356,14 @@ TexMgr_FreeTextures compares each bit in "flags" to the one in glt->flags only if that bit is active in "mask" ================ */ -void TexMgr_FreeTextures (unsigned int flags, unsigned int mask) -{ - gltexture_t *glt, *next; +void TexMgr_FreeTextures(unsigned int flags, unsigned int mask) { + gltexture_t *glt, *next; - for (glt = active_gltextures; glt; glt = next) - { - next = glt->next; - if ((glt->flags & mask) == (flags & mask)) - TexMgr_FreeTexture (glt); - } + for (glt = active_gltextures; glt; glt = next) { + next = glt->next; + if ((glt->flags & mask) == (flags & mask)) + TexMgr_FreeTexture(glt); + } } /* @@ -414,16 +371,14 @@ void TexMgr_FreeTextures (unsigned int flags, unsigned int mask) TexMgr_FreeTexturesForOwner ================ */ -void TexMgr_FreeTexturesForOwner (qmodel_t *owner) -{ - gltexture_t *glt, *next; +void TexMgr_FreeTexturesForOwner(qmodel_t *owner) { + gltexture_t *glt, *next; - for (glt = active_gltextures; glt; glt = next) - { - next = glt->next; - if (glt && glt->owner == owner) - TexMgr_FreeTexture (glt); - } + for (glt = active_gltextures; glt; glt = next) { + next = glt->next; + if (glt && glt->owner == owner) + TexMgr_FreeTexture(glt); + } } /* @@ -431,14 +386,12 @@ void TexMgr_FreeTexturesForOwner (qmodel_t *owner) TexMgr_DeleteTextureObjects ================ */ -void TexMgr_DeleteTextureObjects (void) -{ - gltexture_t *glt; +void TexMgr_DeleteTextureObjects(void) { + gltexture_t *glt; - for (glt = active_gltextures; glt; glt = glt->next) - { - GL_DeleteTexture (glt); - } + for (glt = active_gltextures; glt; glt = glt->next) { + GL_DeleteTexture(glt); + } } /* @@ -454,81 +407,75 @@ void TexMgr_DeleteTextureObjects (void) TexMgr_LoadPalette -- johnfitz -- was VID_SetPalette, moved here, renamed, rewritten ================= */ -void TexMgr_LoadPalette (void) -{ - byte *pal, *src, *dst; - int i, mark; - FILE *f; +void TexMgr_LoadPalette(void) { + byte *pal, *src, *dst; + int i, mark; + FILE *f; - COM_FOpenFile ("gfx/palette.lmp", &f, NULL); - if (!f) - Sys_Error ("Couldn't load gfx/palette.lmp"); + COM_FOpenFile("gfx/palette.lmp", &f, NULL); + if (!f) + Sys_Error("Couldn't load gfx/palette.lmp"); - mark = Hunk_LowMark (); - pal = (byte *) Hunk_Alloc (768); - if (!fread(pal, 768, 1, f)) - Sys_Error ("Failed reading gfx/palette.lmp"); - fclose(f); + mark = Hunk_LowMark(); + pal = (byte *) Hunk_Alloc(768); + if (!fread(pal, 768, 1, f)) + Sys_Error("Failed reading gfx/palette.lmp"); + fclose(f); - //standard palette, 255 is transparent - dst = (byte *)d_8to24table; - src = pal; - for (i = 0; i < 256; i++) - { - *dst++ = *src++; - *dst++ = *src++; - *dst++ = *src++; - *dst++ = 255; - } - ((byte *) &d_8to24table[255]) [3] = 0; + //standard palette, 255 is transparent + dst = (byte *) d_8to24table; + src = pal; + for (i = 0; i < 256; i++) { + *dst++ = *src++; + *dst++ = *src++; + *dst++ = *src++; + *dst++ = 255; + } + ((byte *) &d_8to24table[255])[3] = 0; - //fullbright palette, 0-223 are black (for additive blending) - src = pal + 224*3; - dst = (byte *) &d_8to24table_fbright[224]; - for (i = 224; i < 256; i++) - { - *dst++ = *src++; - *dst++ = *src++; - *dst++ = *src++; - *dst++ = 255; - } - for (i = 0; i < 224; i++) - { - dst = (byte *) &d_8to24table_fbright[i]; - dst[3] = 255; - dst[2] = dst[1] = dst[0] = 0; - } + //fullbright palette, 0-223 are black (for additive blending) + src = pal + 224 * 3; + dst = (byte *) &d_8to24table_fbright[224]; + for (i = 224; i < 256; i++) { + *dst++ = *src++; + *dst++ = *src++; + *dst++ = *src++; + *dst++ = 255; + } + for (i = 0; i < 224; i++) { + dst = (byte *) &d_8to24table_fbright[i]; + dst[3] = 255; + dst[2] = dst[1] = dst[0] = 0; + } - //nobright palette, 224-255 are black (for additive blending) - dst = (byte *)d_8to24table_nobright; - src = pal; - for (i = 0; i < 256; i++) - { - *dst++ = *src++; - *dst++ = *src++; - *dst++ = *src++; - *dst++ = 255; - } - for (i = 224; i < 256; i++) - { - dst = (byte *) &d_8to24table_nobright[i]; - dst[3] = 255; - dst[2] = dst[1] = dst[0] = 0; - } + //nobright palette, 224-255 are black (for additive blending) + dst = (byte *) d_8to24table_nobright; + src = pal; + for (i = 0; i < 256; i++) { + *dst++ = *src++; + *dst++ = *src++; + *dst++ = *src++; + *dst++ = 255; + } + for (i = 224; i < 256; i++) { + dst = (byte *) &d_8to24table_nobright[i]; + dst[3] = 255; + dst[2] = dst[1] = dst[0] = 0; + } - //fullbright palette, for fence textures - memcpy(d_8to24table_fbright_fence, d_8to24table_fbright, 256*4); - d_8to24table_fbright_fence[255] = 0; // Alpha of zero. + //fullbright palette, for fence textures + memcpy(d_8to24table_fbright_fence, d_8to24table_fbright, 256 * 4); + d_8to24table_fbright_fence[255] = 0; // Alpha of zero. - //nobright palette, for fence textures - memcpy(d_8to24table_nobright_fence, d_8to24table_nobright, 256*4); - d_8to24table_nobright_fence[255] = 0; // Alpha of zero. + //nobright palette, for fence textures + memcpy(d_8to24table_nobright_fence, d_8to24table_nobright, 256 * 4); + d_8to24table_nobright_fence[255] = 0; // Alpha of zero. - //conchars palette, 0 and 255 are transparent - memcpy(d_8to24table_conchars, d_8to24table, 256*4); - ((byte *) &d_8to24table_conchars[0]) [3] = 0; + //conchars palette, 0 and 255 are transparent + memcpy(d_8to24table_conchars, d_8to24table, 256 * 4); + ((byte *) &d_8to24table_conchars[0])[3] = 0; - Hunk_FreeToLowMark (mark); + Hunk_FreeToLowMark(mark); } /* @@ -536,10 +483,9 @@ void TexMgr_LoadPalette (void) TexMgr_NewGame ================ */ -void TexMgr_NewGame (void) -{ - TexMgr_FreeTextures (0, TEXPREF_PERSIST); //deletes all textures where TEXPREF_PERSIST is unset - TexMgr_LoadPalette (); +void TexMgr_NewGame(void) { + TexMgr_FreeTextures(0, TEXPREF_PERSIST); //deletes all textures where TEXPREF_PERSIST is unset + TexMgr_LoadPalette(); } /* @@ -549,45 +495,43 @@ TexMgr_RecalcWarpImageSize -- called during init, and after a vid_restart choose safe warpimage size and resize existing warpimage textures ============= */ -void TexMgr_RecalcWarpImageSize (void) -{ -// int oldsize = gl_warpimagesize; - int mark; - gltexture_t *glt; - byte *dummy; +void TexMgr_RecalcWarpImageSize(void) { + // int oldsize = gl_warpimagesize; + int mark; + gltexture_t *glt; + byte *dummy; - // - // find the new correct size - // - gl_warpimagesize = TexMgr_SafeTextureSize (512); + // + // find the new correct size + // + gl_warpimagesize = TexMgr_SafeTextureSize(512); - while (gl_warpimagesize > vid.width) - gl_warpimagesize >>= 1; - while (gl_warpimagesize > vid.height) - gl_warpimagesize >>= 1; + while (gl_warpimagesize > vid.width) + gl_warpimagesize >>= 1; + while (gl_warpimagesize > vid.height) + gl_warpimagesize >>= 1; - // ericw -- removed early exit if (gl_warpimagesize == oldsize). - // after vid_restart TexMgr_ReloadImage reloads textures - // to tx->source_width/source_height, which might not match oldsize. - // fixes: https://sourceforge.net/p/quakespasm/bugs/13/ - - // - // resize the textures in opengl - // - mark = Hunk_LowMark(); - dummy = (byte *) Hunk_Alloc (gl_warpimagesize*gl_warpimagesize*4); + // ericw -- removed early exit if (gl_warpimagesize == oldsize). + // after vid_restart TexMgr_ReloadImage reloads textures + // to tx->source_width/source_height, which might not match oldsize. + // fixes: https://sourceforge.net/p/quakespasm/bugs/13/ - for (glt = active_gltextures; glt; glt = glt->next) - { - if (glt->flags & TEXPREF_WARPIMAGE) - { - GL_Bind (glt); - glTexImage2D (GL_TEXTURE_2D, 0, gl_solid_format, gl_warpimagesize, gl_warpimagesize, 0, GL_RGBA, GL_UNSIGNED_BYTE, dummy); - glt->width = glt->height = gl_warpimagesize; - } - } + // + // resize the textures in opengl + // + mark = Hunk_LowMark(); + dummy = (byte *) Hunk_Alloc(gl_warpimagesize * gl_warpimagesize * 4); - Hunk_FreeToLowMark (mark); + for (glt = active_gltextures; glt; glt = glt->next) { + if (glt->flags & TEXPREF_WARPIMAGE) { + GL_Bind(glt); + glTexImage2D(GL_TEXTURE_2D, 0, gl_solid_format, gl_warpimagesize, gl_warpimagesize, 0, GL_RGBA, + GL_UNSIGNED_BYTE, dummy); + glt->width = glt->height = gl_warpimagesize; + } + } + + Hunk_FreeToLowMark(mark); } /* @@ -597,47 +541,51 @@ TexMgr_Init must be called before any texture loading ================ */ -void TexMgr_Init (void) -{ - int i; - static byte notexture_data[16] = {159,91,83,255,0,0,0,255,0,0,0,255,159,91,83,255}; //black and pink checker - static byte nulltexture_data[16] = {127,191,255,255,0,0,0,255,0,0,0,255,127,191,255,255}; //black and blue checker +void TexMgr_Init(void) { + int i; + static byte notexture_data[16] = {159, 91, 83, 255, 0, 0, 0, 255, 0, 0, 0, 255, 159, 91, 83, 255}; + //black and pink checker + static byte nulltexture_data[16] = {127, 191, 255, 255, 0, 0, 0, 255, 0, 0, 0, 255, 127, 191, 255, 255}; + //black and blue checker - // init texture list - free_gltextures = (gltexture_t *) Hunk_AllocName (MAX_GLTEXTURES * sizeof(gltexture_t), "gltextures"); - active_gltextures = NULL; - for (i = 0; i < MAX_GLTEXTURES - 1; i++) - free_gltextures[i].next = &free_gltextures[i+1]; - free_gltextures[i].next = NULL; - numgltextures = 0; + // init texture list + free_gltextures = (gltexture_t *) Hunk_AllocName(MAX_GLTEXTURES * sizeof(gltexture_t), "gltextures"); + active_gltextures = NULL; + for (i = 0; i < MAX_GLTEXTURES - 1; i++) + free_gltextures[i].next = &free_gltextures[i + 1]; + free_gltextures[i].next = NULL; + numgltextures = 0; - // palette - TexMgr_LoadPalette (); + // palette + TexMgr_LoadPalette(); - Cvar_RegisterVariable (&gl_max_size); - Cvar_RegisterVariable (&gl_picmip); - Cvar_RegisterVariable (&gl_texture_anisotropy); - Cvar_SetCallback (&gl_texture_anisotropy, &TexMgr_Anisotropy_f); - gl_texturemode.string = glmodes[glmode_idx].name; - Cvar_RegisterVariable (&gl_texturemode); - Cvar_SetCallback (&gl_texturemode, &TexMgr_TextureMode_f); - Cmd_AddCommand ("gl_describetexturemodes", &TexMgr_DescribeTextureModes_f); - Cmd_AddCommand ("imagelist", &TexMgr_Imagelist_f); - Cmd_AddCommand ("imagedump", &TexMgr_Imagedump_f); + gl_max_size.inscribe(); + gl_picmip.inscribe(); + gl_texture_anisotropy.inscribe(); + gl_texture_anisotropy.set_callback(&TexMgr_Anisotropy_f); + gl_texturemode.string = glmodes[glmode_idx].name; + gl_texturemode.inscribe(); + gl_texturemode.set_callback(&TexMgr_TextureMode_f); + command::add("gl_describetexturemodes", &TexMgr_DescribeTextureModes_f); + command::add("imagelist", &TexMgr_Imagelist_f); + command::add("imagedump", &TexMgr_Imagedump_f); - // poll max size from hardware - glGetIntegerv (GL_MAX_TEXTURE_SIZE, &gl_hardware_maxsize); + // poll max size from hardware + glGetIntegerv(GL_MAX_TEXTURE_SIZE, &gl_hardware_maxsize); - // load notexture images - notexture = TexMgr_LoadImage (NULL, "notexture", 2, 2, SRC_RGBA, notexture_data, "", (src_offset_t)notexture_data, TEXPREF_NEAREST | TEXPREF_PERSIST | TEXPREF_NOPICMIP); - nulltexture = TexMgr_LoadImage (NULL, "nulltexture", 2, 2, SRC_RGBA, nulltexture_data, "", (src_offset_t)nulltexture_data, TEXPREF_NEAREST | TEXPREF_PERSIST | TEXPREF_NOPICMIP); + // load notexture images + notexture = TexMgr_LoadImage(NULL, "notexture", 2, 2, SRC_RGBA, notexture_data, "", (src_offset_t) notexture_data, + TEXPREF_NEAREST | TEXPREF_PERSIST | TEXPREF_NOPICMIP); + nulltexture = TexMgr_LoadImage(NULL, "nulltexture", 2, 2, SRC_RGBA, nulltexture_data, "", + (src_offset_t) nulltexture_data, + TEXPREF_NEAREST | TEXPREF_PERSIST | TEXPREF_NOPICMIP); - //have to assign these here becuase Mod_Init is called before TexMgr_Init - r_notexture_mip->gltexture = r_notexture_mip2->gltexture = notexture; + //have to assign these here becuase Mod_Init is called before TexMgr_Init + r_notexture_mip->gltexture = r_notexture_mip2->gltexture = notexture; - //set safe size for warpimages - gl_warpimagesize = 0; - TexMgr_RecalcWarpImageSize (); + //set safe size for warpimages + gl_warpimagesize = 0; + TexMgr_RecalcWarpImageSize(); } /* @@ -653,12 +601,10 @@ void TexMgr_Init (void) TexMgr_Pad -- return smallest power of two greater than or equal to s ================ */ -int TexMgr_Pad (int s) -{ - int i; - for (i = 1; i < s; i<<=1) - ; - return i; +int TexMgr_Pad(int s) { + int i; + for (i = 1; i < s; i <<= 1); + return i; } /* @@ -666,18 +612,17 @@ int TexMgr_Pad (int s) TexMgr_SafeTextureSize -- return a size with hardware and user prefs in mind =============== */ -int TexMgr_SafeTextureSize (int s) -{ - int p = (int)gl_max_size.value; - if (!gl_texture_NPOT) - s = TexMgr_Pad(s); - if (p > 0) { - p = TexMgr_Pad(p); - if (p < s) s = p; - } - if (s > gl_hardware_maxsize) - s = gl_hardware_maxsize; - return s; +int TexMgr_SafeTextureSize(int s) { + int p = (int) gl_max_size.value; + if (!gl_texture_NPOT) + s = TexMgr_Pad(s); + if (p > 0) { + p = TexMgr_Pad(p); + if (p < s) s = p; + } + if (s > gl_hardware_maxsize) + s = gl_hardware_maxsize; + return s; } /* @@ -685,11 +630,10 @@ int TexMgr_SafeTextureSize (int s) TexMgr_PadConditional -- only pad if a texture of that size would be padded. (used for tex coords) ================ */ -int TexMgr_PadConditional (int s) -{ - if (s < TexMgr_SafeTextureSize(s)) - return TexMgr_Pad(s); - return s; +int TexMgr_PadConditional(int s) { + if (s < TexMgr_SafeTextureSize(s)) + return TexMgr_Pad(s); + return s; } /* @@ -697,23 +641,21 @@ int TexMgr_PadConditional (int s) TexMgr_MipMapW ================ */ -static unsigned *TexMgr_MipMapW (unsigned *data, int width, int height) -{ - int i, size; - byte *out, *in; +static unsigned *TexMgr_MipMapW(unsigned *data, int width, int height) { + int i, size; + byte *out, *in; - out = in = (byte *)data; - size = (width*height)>>1; + out = in = (byte *) data; + size = (width * height) >> 1; - for (i = 0; i < size; i++, out += 4, in += 8) - { - out[0] = (in[0] + in[4])>>1; - out[1] = (in[1] + in[5])>>1; - out[2] = (in[2] + in[6])>>1; - out[3] = (in[3] + in[7])>>1; - } + for (i = 0; i < size; i++, out += 4, in += 8) { + out[0] = (in[0] + in[4]) >> 1; + out[1] = (in[1] + in[5]) >> 1; + out[2] = (in[2] + in[6]) >> 1; + out[3] = (in[3] + in[7]) >> 1; + } - return data; + return data; } /* @@ -721,27 +663,24 @@ static unsigned *TexMgr_MipMapW (unsigned *data, int width, int height) TexMgr_MipMapH ================ */ -static unsigned *TexMgr_MipMapH (unsigned *data, int width, int height) -{ - int i, j; - byte *out, *in; +static unsigned *TexMgr_MipMapH(unsigned *data, int width, int height) { + int i, j; + byte *out, *in; - out = in = (byte *)data; - height>>=1; - width<<=2; + out = in = (byte *) data; + height >>= 1; + width <<= 2; - for (i = 0; i < height; i++, in += width) - { - for (j = 0; j < width; j += 4, out += 4, in += 4) - { - out[0] = (in[0] + in[width+0])>>1; - out[1] = (in[1] + in[width+1])>>1; - out[2] = (in[2] + in[width+2])>>1; - out[3] = (in[3] + in[width+3])>>1; - } - } + for (i = 0; i < height; i++, in += width) { + for (j = 0; j < width; j += 4, out += 4, in += 4) { + out[0] = (in[0] + in[width + 0]) >> 1; + out[1] = (in[1] + in[width + 1]) >> 1; + out[2] = (in[2] + in[width + 2]) >> 1; + out[3] = (in[3] + in[width + 3]) >> 1; + } + } - return data; + return data; } /* @@ -749,58 +688,59 @@ static unsigned *TexMgr_MipMapH (unsigned *data, int width, int height) TexMgr_ResampleTexture -- bilinear resample ================ */ -static unsigned *TexMgr_ResampleTexture (unsigned *in, int inwidth, int inheight, qboolean alpha) -{ - byte *nwpx, *nepx, *swpx, *sepx, *dest; - unsigned xfrac, yfrac, x, y, modx, mody, imodx, imody, injump, outjump; - unsigned *out; - int i, j, outwidth, outheight; +static unsigned *TexMgr_ResampleTexture(unsigned *in, int inwidth, int inheight, qboolean alpha) { + byte *nwpx, *nepx, *swpx, *sepx, *dest; + unsigned xfrac, yfrac, x, y, modx, mody, imodx, imody, injump, outjump; + unsigned *out; + int i, j, outwidth, outheight; - if (inwidth == TexMgr_Pad(inwidth) && inheight == TexMgr_Pad(inheight)) - return in; + if (inwidth == TexMgr_Pad(inwidth) && inheight == TexMgr_Pad(inheight)) + return in; - outwidth = TexMgr_Pad(inwidth); - outheight = TexMgr_Pad(inheight); - out = (unsigned *) Hunk_Alloc(outwidth*outheight*4); + outwidth = TexMgr_Pad(inwidth); + outheight = TexMgr_Pad(inheight); + out = (unsigned *) Hunk_Alloc(outwidth * outheight * 4); - xfrac = ((inwidth-1) << 16) / (outwidth-1); - yfrac = ((inheight-1) << 16) / (outheight-1); - y = outjump = 0; + xfrac = ((inwidth - 1) << 16) / (outwidth - 1); + yfrac = ((inheight - 1) << 16) / (outheight - 1); + y = outjump = 0; - for (i = 0; i < outheight; i++) - { - mody = (y>>8) & 0xFF; - imody = 256 - mody; - injump = (y>>16) * inwidth; - x = 0; + for (i = 0; i < outheight; i++) { + mody = (y >> 8) & 0xFF; + imody = 256 - mody; + injump = (y >> 16) * inwidth; + x = 0; - for (j = 0; j < outwidth; j++) - { - modx = (x>>8) & 0xFF; - imodx = 256 - modx; + for (j = 0; j < outwidth; j++) { + modx = (x >> 8) & 0xFF; + imodx = 256 - modx; - nwpx = (byte *)(in + (x>>16) + injump); - nepx = nwpx + 4; - swpx = nwpx + inwidth*4; - sepx = swpx + 4; + nwpx = (byte *) (in + (x >> 16) + injump); + nepx = nwpx + 4; + swpx = nwpx + inwidth * 4; + sepx = swpx + 4; - dest = (byte *)(out + outjump + j); + dest = (byte *) (out + outjump + j); - dest[0] = (nwpx[0]*imodx*imody + nepx[0]*modx*imody + swpx[0]*imodx*mody + sepx[0]*modx*mody)>>16; - dest[1] = (nwpx[1]*imodx*imody + nepx[1]*modx*imody + swpx[1]*imodx*mody + sepx[1]*modx*mody)>>16; - dest[2] = (nwpx[2]*imodx*imody + nepx[2]*modx*imody + swpx[2]*imodx*mody + sepx[2]*modx*mody)>>16; - if (alpha) - dest[3] = (nwpx[3]*imodx*imody + nepx[3]*modx*imody + swpx[3]*imodx*mody + sepx[3]*modx*mody)>>16; - else - dest[3] = 255; + dest[0] = (nwpx[0] * imodx * imody + nepx[0] * modx * imody + swpx[0] * imodx * mody + sepx[0] * modx * + mody) >> 16; + dest[1] = (nwpx[1] * imodx * imody + nepx[1] * modx * imody + swpx[1] * imodx * mody + sepx[1] * modx * + mody) >> 16; + dest[2] = (nwpx[2] * imodx * imody + nepx[2] * modx * imody + swpx[2] * imodx * mody + sepx[2] * modx * + mody) >> 16; + if (alpha) + dest[3] = (nwpx[3] * imodx * imody + nepx[3] * modx * imody + swpx[3] * imodx * mody + sepx[3] * modx * + mody) >> 16; + else + dest[3] = 255; - x += xfrac; - } - outjump += outwidth; - y += yfrac; - } + x += xfrac; + } + outjump += outwidth; + y += yfrac; + } - return out; + return out; } /* @@ -811,48 +751,92 @@ eliminate pink edges on sprites, etc. operates in place on 32bit data =============== */ -static void TexMgr_AlphaEdgeFix (byte *data, int width, int height) -{ - int i, j, n = 0, b, c[3] = {0,0,0}, - lastrow, thisrow, nextrow, - lastpix, thispix, nextpix; - byte *dest = data; +static void TexMgr_AlphaEdgeFix(byte *data, int width, int height) { + int i, j, n = 0, b, c[3] = {0, 0, 0}, + lastrow, thisrow, nextrow, + lastpix, thispix, nextpix; + byte *dest = data; - for (i = 0; i < height; i++) - { - lastrow = width * 4 * ((i == 0) ? height-1 : i-1); - thisrow = width * 4 * i; - nextrow = width * 4 * ((i == height-1) ? 0 : i+1); + for (i = 0; i < height; i++) { + lastrow = width * 4 * ((i == 0) ? height - 1 : i - 1); + thisrow = width * 4 * i; + nextrow = width * 4 * ((i == height - 1) ? 0 : i + 1); - for (j = 0; j < width; j++, dest += 4) - { - if (dest[3]) //not transparent - continue; + for (j = 0; j < width; j++, dest += 4) { + if (dest[3]) //not transparent + continue; - lastpix = 4 * ((j == 0) ? width-1 : j-1); - thispix = 4 * j; - nextpix = 4 * ((j == width-1) ? 0 : j+1); + lastpix = 4 * ((j == 0) ? width - 1 : j - 1); + thispix = 4 * j; + nextpix = 4 * ((j == width - 1) ? 0 : j + 1); - b = lastrow + lastpix; if (data[b+3]) {c[0] += data[b]; c[1] += data[b+1]; c[2] += data[b+2]; n++;} - b = thisrow + lastpix; if (data[b+3]) {c[0] += data[b]; c[1] += data[b+1]; c[2] += data[b+2]; n++;} - b = nextrow + lastpix; if (data[b+3]) {c[0] += data[b]; c[1] += data[b+1]; c[2] += data[b+2]; n++;} - b = lastrow + thispix; if (data[b+3]) {c[0] += data[b]; c[1] += data[b+1]; c[2] += data[b+2]; n++;} - b = nextrow + thispix; if (data[b+3]) {c[0] += data[b]; c[1] += data[b+1]; c[2] += data[b+2]; n++;} - b = lastrow + nextpix; if (data[b+3]) {c[0] += data[b]; c[1] += data[b+1]; c[2] += data[b+2]; n++;} - b = thisrow + nextpix; if (data[b+3]) {c[0] += data[b]; c[1] += data[b+1]; c[2] += data[b+2]; n++;} - b = nextrow + nextpix; if (data[b+3]) {c[0] += data[b]; c[1] += data[b+1]; c[2] += data[b+2]; n++;} + b = lastrow + lastpix; + if (data[b + 3]) { + c[0] += data[b]; + c[1] += data[b + 1]; + c[2] += data[b + 2]; + n++; + } + b = thisrow + lastpix; + if (data[b + 3]) { + c[0] += data[b]; + c[1] += data[b + 1]; + c[2] += data[b + 2]; + n++; + } + b = nextrow + lastpix; + if (data[b + 3]) { + c[0] += data[b]; + c[1] += data[b + 1]; + c[2] += data[b + 2]; + n++; + } + b = lastrow + thispix; + if (data[b + 3]) { + c[0] += data[b]; + c[1] += data[b + 1]; + c[2] += data[b + 2]; + n++; + } + b = nextrow + thispix; + if (data[b + 3]) { + c[0] += data[b]; + c[1] += data[b + 1]; + c[2] += data[b + 2]; + n++; + } + b = lastrow + nextpix; + if (data[b + 3]) { + c[0] += data[b]; + c[1] += data[b + 1]; + c[2] += data[b + 2]; + n++; + } + b = thisrow + nextpix; + if (data[b + 3]) { + c[0] += data[b]; + c[1] += data[b + 1]; + c[2] += data[b + 2]; + n++; + } + b = nextrow + nextpix; + if (data[b + 3]) { + c[0] += data[b]; + c[1] += data[b + 1]; + c[2] += data[b + 2]; + n++; + } - //average all non-transparent neighbors - if (n) - { - dest[0] = (byte)(c[0]/n); - dest[1] = (byte)(c[1]/n); - dest[2] = (byte)(c[2]/n); + //average all non-transparent neighbors + if (n) { + dest[0] = (byte) (c[0] / n); + dest[1] = (byte) (c[1] / n); + dest[2] = (byte) (c[2] / n); - n = c[0] = c[1] = c[2] = 0; - } - } - } + n = c[0] = c[1] = c[2] = 0; + } + } + } } /* @@ -862,35 +846,32 @@ TexMgr_PadEdgeFixW -- special case of AlphaEdgeFix for textures that only need i operates in place on 32bit data, and expects unpadded height and width values =============== */ -static void TexMgr_PadEdgeFixW (byte *data, int width, int height) -{ - byte *src, *dst; - int i, padw, padh; +static void TexMgr_PadEdgeFixW(byte *data, int width, int height) { + byte *src, *dst; + int i, padw, padh; - padw = TexMgr_PadConditional(width); - padh = TexMgr_PadConditional(height); + padw = TexMgr_PadConditional(width); + padh = TexMgr_PadConditional(height); - //copy last full column to first empty column, leaving alpha byte at zero - src = data + (width - 1) * 4; - for (i = 0; i < padh; i++) - { - src[4] = src[0]; - src[5] = src[1]; - src[6] = src[2]; - src += padw * 4; - } + //copy last full column to first empty column, leaving alpha byte at zero + src = data + (width - 1) * 4; + for (i = 0; i < padh; i++) { + src[4] = src[0]; + src[5] = src[1]; + src[6] = src[2]; + src += padw * 4; + } - //copy first full column to last empty column, leaving alpha byte at zero - src = data; - dst = data + (padw - 1) * 4; - for (i = 0; i < padh; i++) - { - dst[0] = src[0]; - dst[1] = src[1]; - dst[2] = src[2]; - src += padw * 4; - dst += padw * 4; - } + //copy first full column to last empty column, leaving alpha byte at zero + src = data; + dst = data + (padw - 1) * 4; + for (i = 0; i < padh; i++) { + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[2]; + src += padw * 4; + dst += padw * 4; + } } /* @@ -900,37 +881,34 @@ TexMgr_PadEdgeFixH -- special case of AlphaEdgeFix for textures that only need i operates in place on 32bit data, and expects unpadded height and width values =============== */ -static void TexMgr_PadEdgeFixH (byte *data, int width, int height) -{ - byte *src, *dst; - int i, padw, padh; +static void TexMgr_PadEdgeFixH(byte *data, int width, int height) { + byte *src, *dst; + int i, padw, padh; - padw = TexMgr_PadConditional(width); - padh = TexMgr_PadConditional(height); + padw = TexMgr_PadConditional(width); + padh = TexMgr_PadConditional(height); - //copy last full row to first empty row, leaving alpha byte at zero - dst = data + height * padw * 4; - src = dst - padw * 4; - for (i = 0; i < padw; i++) - { - dst[0] = src[0]; - dst[1] = src[1]; - dst[2] = src[2]; - src += 4; - dst += 4; - } + //copy last full row to first empty row, leaving alpha byte at zero + dst = data + height * padw * 4; + src = dst - padw * 4; + for (i = 0; i < padw; i++) { + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[2]; + src += 4; + dst += 4; + } - //copy first full row to last empty row, leaving alpha byte at zero - dst = data + (padh - 1) * padw * 4; - src = data; - for (i = 0; i < padw; i++) - { - dst[0] = src[0]; - dst[1] = src[1]; - dst[2] = src[2]; - src += 4; - dst += 4; - } + //copy first full row to last empty row, leaving alpha byte at zero + dst = data + (padh - 1) * padw * 4; + src = data; + for (i = 0; i < padw; i++) { + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[2]; + src += 4; + dst += 4; + } } /* @@ -938,17 +916,16 @@ static void TexMgr_PadEdgeFixH (byte *data, int width, int height) TexMgr_8to32 ================ */ -static unsigned *TexMgr_8to32 (byte *in, int pixels, unsigned int *usepal) -{ - int i; - unsigned *out, *data; +static unsigned *TexMgr_8to32(byte *in, int pixels, unsigned int *usepal) { + int i; + unsigned *out, *data; - out = data = (unsigned *) Hunk_Alloc(pixels*4); + out = data = (unsigned *) Hunk_Alloc(pixels * 4); - for (i = 0; i < pixels; i++) - *out++ = usepal[*in++]; + for (i = 0; i < pixels; i++) + *out++ = usepal[*in++]; - return data; + return data; } /* @@ -956,27 +933,25 @@ static unsigned *TexMgr_8to32 (byte *in, int pixels, unsigned int *usepal) TexMgr_PadImageW -- return image with width padded up to power-of-two dimentions ================ */ -static byte *TexMgr_PadImageW (byte *in, int width, int height, byte padbyte) -{ - int i, j, outwidth; - byte *out, *data; +static byte *TexMgr_PadImageW(byte *in, int width, int height, byte padbyte) { + int i, j, outwidth; + byte *out, *data; - if (width == TexMgr_Pad(width)) - return in; + if (width == TexMgr_Pad(width)) + return in; - outwidth = TexMgr_Pad(width); + outwidth = TexMgr_Pad(width); - out = data = (byte *) Hunk_Alloc(outwidth*height); + out = data = (byte *) Hunk_Alloc(outwidth * height); - for (i = 0; i < height; i++) - { - for (j = 0; j < width; j++) - *out++ = *in++; - for ( ; j < outwidth; j++) - *out++ = padbyte; - } + for (i = 0; i < height; i++) { + for (j = 0; j < width; j++) + *out++ = *in++; + for (; j < outwidth; j++) + *out++ = padbyte; + } - return data; + return data; } /* @@ -984,25 +959,24 @@ static byte *TexMgr_PadImageW (byte *in, int width, int height, byte padbyte) TexMgr_PadImageH -- return image with height padded up to power-of-two dimentions ================ */ -static byte *TexMgr_PadImageH (byte *in, int width, int height, byte padbyte) -{ - int i, srcpix, dstpix; - byte *data, *out; +static byte *TexMgr_PadImageH(byte *in, int width, int height, byte padbyte) { + int i, srcpix, dstpix; + byte *data, *out; - if (height == TexMgr_Pad(height)) - return in; + if (height == TexMgr_Pad(height)) + return in; - srcpix = width * height; - dstpix = width * TexMgr_Pad(height); + srcpix = width * height; + dstpix = width * TexMgr_Pad(height); - out = data = (byte *) Hunk_Alloc(dstpix); + out = data = (byte *) Hunk_Alloc(dstpix); - for (i = 0; i < srcpix; i++) - *out++ = *in++; - for ( ; i < dstpix; i++) - *out++ = padbyte; + for (i = 0; i < srcpix; i++) + *out++ = *in++; + for (; i < dstpix; i++) + *out++ = padbyte; - return data; + return data; } /* @@ -1010,66 +984,60 @@ static byte *TexMgr_PadImageH (byte *in, int width, int height, byte padbyte) TexMgr_LoadImage32 -- handles 32bit source data ================ */ -static void TexMgr_LoadImage32 (gltexture_t *glt, unsigned *data) -{ - int internalformat, miplevel, mipwidth, mipheight, picmip; +static void TexMgr_LoadImage32(gltexture_t *glt, unsigned *data) { + int internalformat, miplevel, mipwidth, mipheight, picmip; - if (!gl_texture_NPOT) - { - // resample up - data = TexMgr_ResampleTexture (data, glt->width, glt->height, glt->flags & TEXPREF_ALPHA); - glt->width = TexMgr_Pad(glt->width); - glt->height = TexMgr_Pad(glt->height); - } + if (!gl_texture_NPOT) { + // resample up + data = TexMgr_ResampleTexture(data, glt->width, glt->height, glt->flags & TEXPREF_ALPHA); + glt->width = TexMgr_Pad(glt->width); + glt->height = TexMgr_Pad(glt->height); + } - // mipmap down - picmip = (glt->flags & TEXPREF_NOPICMIP) ? 0 : q_max((int)gl_picmip.value, 0); - mipwidth = TexMgr_SafeTextureSize (glt->width >> picmip); - mipheight = TexMgr_SafeTextureSize (glt->height >> picmip); - while ((int) glt->width > mipwidth) - { - TexMgr_MipMapW (data, glt->width, glt->height); - glt->width >>= 1; - if (glt->flags & TEXPREF_ALPHA) - TexMgr_AlphaEdgeFix ((byte *)data, glt->width, glt->height); - } - while ((int) glt->height > mipheight) - { - TexMgr_MipMapH (data, glt->width, glt->height); - glt->height >>= 1; - if (glt->flags & TEXPREF_ALPHA) - TexMgr_AlphaEdgeFix ((byte *)data, glt->width, glt->height); - } + // mipmap down + picmip = (glt->flags & TEXPREF_NOPICMIP) ? 0 : std::max((int)gl_picmip.value, 0); + mipwidth = TexMgr_SafeTextureSize(glt->width >> picmip); + mipheight = TexMgr_SafeTextureSize(glt->height >> picmip); + while ((int) glt->width > mipwidth) { + TexMgr_MipMapW(data, glt->width, glt->height); + glt->width >>= 1; + if (glt->flags & TEXPREF_ALPHA) + TexMgr_AlphaEdgeFix((byte *) data, glt->width, glt->height); + } + while ((int) glt->height > mipheight) { + TexMgr_MipMapH(data, glt->width, glt->height); + glt->height >>= 1; + if (glt->flags & TEXPREF_ALPHA) + TexMgr_AlphaEdgeFix((byte *) data, glt->width, glt->height); + } - // upload - GL_Bind (glt); - internalformat = (glt->flags & TEXPREF_ALPHA) ? gl_alpha_format : gl_solid_format; - glTexImage2D (GL_TEXTURE_2D, 0, internalformat, glt->width, glt->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); + // upload + GL_Bind(glt); + internalformat = (glt->flags & TEXPREF_ALPHA) ? gl_alpha_format : gl_solid_format; + glTexImage2D(GL_TEXTURE_2D, 0, internalformat, glt->width, glt->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); - // upload mipmaps - if (glt->flags & TEXPREF_MIPMAP && !(glt->flags & TEXPREF_WARPIMAGE)) // warp image mipmaps are generated later - { - mipwidth = glt->width; - mipheight = glt->height; + // upload mipmaps + if (glt->flags & TEXPREF_MIPMAP && !(glt->flags & TEXPREF_WARPIMAGE)) // warp image mipmaps are generated later + { + mipwidth = glt->width; + mipheight = glt->height; - for (miplevel = 1; mipwidth > 1 || mipheight > 1; miplevel++) - { - if (mipwidth > 1) - { - TexMgr_MipMapW (data, mipwidth, mipheight); - mipwidth >>= 1; - } - if (mipheight > 1) - { - TexMgr_MipMapH (data, mipwidth, mipheight); - mipheight >>= 1; - } - glTexImage2D (GL_TEXTURE_2D, miplevel, internalformat, mipwidth, mipheight, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); - } - } + for (miplevel = 1; mipwidth > 1 || mipheight > 1; miplevel++) { + if (mipwidth > 1) { + TexMgr_MipMapW(data, mipwidth, mipheight); + mipwidth >>= 1; + } + if (mipheight > 1) { + TexMgr_MipMapH(data, mipwidth, mipheight); + mipheight >>= 1; + } + glTexImage2D(GL_TEXTURE_2D, miplevel, internalformat, mipwidth, mipheight, 0, GL_RGBA, GL_UNSIGNED_BYTE, + data); + } + } - // set filter modes - TexMgr_SetFilterModes (glt); + // set filter modes + TexMgr_SetFilterModes(glt); } /* @@ -1077,96 +1045,82 @@ static void TexMgr_LoadImage32 (gltexture_t *glt, unsigned *data) TexMgr_LoadImage8 -- handles 8bit source data, then passes it to LoadImage32 ================ */ -static void TexMgr_LoadImage8 (gltexture_t *glt, byte *data) -{ - extern cvar_t gl_fullbrights; - qboolean padw = false, padh = false; - byte padbyte; - unsigned int *usepal; - int i; +static void TexMgr_LoadImage8(gltexture_t *glt, byte *data) { + extern convar gl_fullbrights; + qboolean padw = false, padh = false; + byte padbyte; + unsigned int *usepal; + int i; - // HACK HACK HACK -- taken from tomazquake - if (strstr(glt->name, "shot1sid") && - glt->width == 32 && glt->height == 32 && - CRC_Block(data, 1024) == 65393) - { - // This texture in b_shell1.bsp has some of the first 32 pixels painted white. - // They are invisible in software, but look really ugly in GL. So we just copy - // 32 pixels from the bottom to make it look nice. - memcpy (data, data + 32*31, 32); - } + // HACK HACK HACK -- taken from tomazquake + if (strstr(glt->name, "shot1sid") && + glt->width == 32 && glt->height == 32 && + CRC_Block(data, 1024) == 65393) { + // This texture in b_shell1.bsp has some of the first 32 pixels painted white. + // They are invisible in software, but look really ugly in GL. So we just copy + // 32 pixels from the bottom to make it look nice. + memcpy(data, data + 32 * 31, 32); + } - // detect false alpha cases - if (glt->flags & TEXPREF_ALPHA && !(glt->flags & TEXPREF_CONCHARS)) - { - for (i = 0; i < (int) (glt->width * glt->height); i++) - if (data[i] == 255) //transparent index - break; - if (i == (int) (glt->width * glt->height)) - glt->flags -= TEXPREF_ALPHA; - } + // detect false alpha cases + if (glt->flags & TEXPREF_ALPHA && !(glt->flags & TEXPREF_CONCHARS)) { + for (i = 0; i < (int) (glt->width * glt->height); i++) + if (data[i] == 255) //transparent index + break; + if (i == (int) (glt->width * glt->height)) + glt->flags -= TEXPREF_ALPHA; + } - // choose palette and padbyte - if (glt->flags & TEXPREF_FULLBRIGHT) - { - if (glt->flags & TEXPREF_ALPHA) - usepal = d_8to24table_fbright_fence; - else - usepal = d_8to24table_fbright; - padbyte = 0; - } - else if (glt->flags & TEXPREF_NOBRIGHT && gl_fullbrights.value) - { - if (glt->flags & TEXPREF_ALPHA) - usepal = d_8to24table_nobright_fence; - else - usepal = d_8to24table_nobright; - padbyte = 0; - } - else if (glt->flags & TEXPREF_CONCHARS) - { - usepal = d_8to24table_conchars; - padbyte = 0; - } - else - { - usepal = d_8to24table; - padbyte = 255; - } + // choose palette and padbyte + if (glt->flags & TEXPREF_FULLBRIGHT) { + if (glt->flags & TEXPREF_ALPHA) + usepal = d_8to24table_fbright_fence; + else + usepal = d_8to24table_fbright; + padbyte = 0; + } else if (glt->flags & TEXPREF_NOBRIGHT && gl_fullbrights.value) { + if (glt->flags & TEXPREF_ALPHA) + usepal = d_8to24table_nobright_fence; + else + usepal = d_8to24table_nobright; + padbyte = 0; + } else if (glt->flags & TEXPREF_CONCHARS) { + usepal = d_8to24table_conchars; + padbyte = 0; + } else { + usepal = d_8to24table; + padbyte = 255; + } - // pad each dimention, but only if it's not going to be downsampled later - if (glt->flags & TEXPREF_PAD) - { - if ((int) glt->width < TexMgr_SafeTextureSize(glt->width)) - { - data = TexMgr_PadImageW (data, glt->width, glt->height, padbyte); - glt->width = TexMgr_Pad(glt->width); - padw = true; - } - if ((int) glt->height < TexMgr_SafeTextureSize(glt->height)) - { - data = TexMgr_PadImageH (data, glt->width, glt->height, padbyte); - glt->height = TexMgr_Pad(glt->height); - padh = true; - } - } + // pad each dimention, but only if it's not going to be downsampled later + if (glt->flags & TEXPREF_PAD) { + if ((int) glt->width < TexMgr_SafeTextureSize(glt->width)) { + data = TexMgr_PadImageW(data, glt->width, glt->height, padbyte); + glt->width = TexMgr_Pad(glt->width); + padw = true; + } + if ((int) glt->height < TexMgr_SafeTextureSize(glt->height)) { + data = TexMgr_PadImageH(data, glt->width, glt->height, padbyte); + glt->height = TexMgr_Pad(glt->height); + padh = true; + } + } - // convert to 32bit - data = (byte *)TexMgr_8to32(data, glt->width * glt->height, usepal); + // convert to 32bit + data = (byte *) TexMgr_8to32(data, glt->width * glt->height, usepal); - // fix edges - if (glt->flags & TEXPREF_ALPHA) - TexMgr_AlphaEdgeFix (data, glt->width, glt->height); - else - { - if (padw) - TexMgr_PadEdgeFixW (data, glt->source_width, glt->source_height); - if (padh) - TexMgr_PadEdgeFixH (data, glt->source_width, glt->source_height); - } + // fix edges + if (glt->flags & TEXPREF_ALPHA) + TexMgr_AlphaEdgeFix(data, glt->width, glt->height); + else { + if (padw) + TexMgr_PadEdgeFixW(data, glt->source_width, glt->source_height); + if (padh) + TexMgr_PadEdgeFixH(data, glt->source_width, glt->source_height); + } - // upload it - TexMgr_LoadImage32 (glt, (unsigned *)data); + // upload it + TexMgr_LoadImage32(glt, (unsigned *) data); } /* @@ -1174,18 +1128,17 @@ static void TexMgr_LoadImage8 (gltexture_t *glt, byte *data) TexMgr_LoadLightmap -- handles lightmap data ================ */ -static void TexMgr_LoadLightmap (gltexture_t *glt, byte *data) -{ - const qboolean wide10bits = !!r_lightmapwide.value; - const GLenum type = wide10bits ? GL_UNSIGNED_INT_10_10_10_2 : GL_UNSIGNED_BYTE; - const GLint internalfmt = wide10bits ? GL_RGB10_A2 : lightmap_bytes; +static void TexMgr_LoadLightmap(gltexture_t *glt, byte *data) { + const qboolean wide10bits = !!r_lightmapwide.value; + const GLenum type = wide10bits ? GL_UNSIGNED_INT_10_10_10_2 : GL_UNSIGNED_BYTE; + const GLint internalfmt = wide10bits ? GL_RGB10_A2 : lightmap_bytes; - // upload it - GL_Bind (glt); - glTexImage2D (GL_TEXTURE_2D, 0, internalfmt, glt->width, glt->height, 0, gl_lightmap_format, type, data); + // upload it + GL_Bind(glt); + glTexImage2D(GL_TEXTURE_2D, 0, internalfmt, glt->width, glt->height, 0, gl_lightmap_format, type, data); - // set filter modes - TexMgr_SetFilterModes (glt); + // set filter modes + TexMgr_SetFilterModes(glt); } /* @@ -1193,73 +1146,68 @@ static void TexMgr_LoadLightmap (gltexture_t *glt, byte *data) TexMgr_LoadImage -- the one entry point for loading all textures ================ */ -gltexture_t *TexMgr_LoadImage (qmodel_t *owner, const char *name, int width, int height, enum srcformat format, - byte *data, const char *source_file, src_offset_t source_offset, unsigned flags) -{ - unsigned short crc; - gltexture_t *glt; - int mark; +gltexture_t *TexMgr_LoadImage(qmodel_t *owner, const char *name, int width, int height, enum srcformat format, + byte *data, const char *source_file, src_offset_t source_offset, unsigned flags) { + unsigned short crc; + gltexture_t *glt; + int mark; - if (isDedicated) - return NULL; + if (isDedicated) + return NULL; - // cache check - switch (format) - { - case SRC_INDEXED: - crc = CRC_Block(data, width * height); - break; - case SRC_LIGHTMAP: - crc = CRC_Block(data, width * height * lightmap_bytes); - break; - case SRC_RGBA: - crc = CRC_Block(data, width * height * 4); - break; - default: /* not reachable but avoids compiler warnings */ - crc = 0; - } - if ((flags & TEXPREF_OVERWRITE) && (glt = TexMgr_FindTexture (owner, name))) - { - if (glt->source_crc == crc) - return glt; - } - else - glt = TexMgr_NewTexture (); + // cache check + switch (format) { + case SRC_INDEXED: + crc = CRC_Block(data, width * height); + break; + case SRC_LIGHTMAP: + crc = CRC_Block(data, width * height * lightmap_bytes); + break; + case SRC_RGBA: + crc = CRC_Block(data, width * height * 4); + break; + default: /* not reachable but avoids compiler warnings */ + crc = 0; + } + if ((flags & TEXPREF_OVERWRITE) && (glt = TexMgr_FindTexture(owner, name))) { + if (glt->source_crc == crc) + return glt; + } else + glt = TexMgr_NewTexture(); - // copy data - glt->owner = owner; - q_strlcpy (glt->name, name, sizeof(glt->name)); - glt->width = width; - glt->height = height; - glt->flags = flags; - glt->shirt = -1; - glt->pants = -1; - q_strlcpy (glt->source_file, source_file, sizeof(glt->source_file)); - glt->source_offset = source_offset; - glt->source_format = format; - glt->source_width = width; - glt->source_height = height; - glt->source_crc = crc; + // copy data + glt->owner = owner; + q_strlcpy(glt->name, name, sizeof(glt->name)); + glt->width = width; + glt->height = height; + glt->flags = flags; + glt->shirt = -1; + glt->pants = -1; + q_strlcpy(glt->source_file, source_file, sizeof(glt->source_file)); + glt->source_offset = source_offset; + glt->source_format = format; + glt->source_width = width; + glt->source_height = height; + glt->source_crc = crc; - //upload it - mark = Hunk_LowMark(); + //upload it + mark = Hunk_LowMark(); - switch (glt->source_format) - { - case SRC_INDEXED: - TexMgr_LoadImage8 (glt, data); - break; - case SRC_LIGHTMAP: - TexMgr_LoadLightmap (glt, data); - break; - case SRC_RGBA: - TexMgr_LoadImage32 (glt, (unsigned *)data); - break; - } + switch (glt->source_format) { + case SRC_INDEXED: + TexMgr_LoadImage8(glt, data); + break; + case SRC_LIGHTMAP: + TexMgr_LoadLightmap(glt, data); + break; + case SRC_RGBA: + TexMgr_LoadImage32(glt, (unsigned *) data); + break; + } - Hunk_FreeToLowMark(mark); + Hunk_FreeToLowMark(mark); - return glt; + return glt; } /* @@ -1275,126 +1223,112 @@ gltexture_t *TexMgr_LoadImage (qmodel_t *owner, const char *name, int width, int TexMgr_ReloadImage -- reloads a texture, and colormaps it if needed ================ */ -void TexMgr_ReloadImage (gltexture_t *glt, int shirt, int pants) -{ - byte translation[256]; - byte *src, *dst, *data = NULL, *translated; - int mark, size, i; +void TexMgr_ReloadImage(gltexture_t *glt, int shirt, int pants) { + byte translation[256]; + byte *src, *dst, *data = NULL, *translated; + int mark, size, i; -// -// get source data -// - mark = Hunk_LowMark (); + // + // get source data + // + mark = Hunk_LowMark(); - if (glt->source_file[0] && glt->source_offset) { - //lump inside file - FILE *f; - int sz; - COM_FOpenFile(glt->source_file, &f, NULL); - if (!f) goto invalid; - fseek (f, glt->source_offset, SEEK_CUR); - size = glt->source_width * glt->source_height; - /* should be SRC_INDEXED, but no harm being paranoid: */ - if (glt->source_format == SRC_RGBA) { - size *= 4; - } - else if (glt->source_format == SRC_LIGHTMAP) { - size *= lightmap_bytes; - } - data = (byte *) Hunk_Alloc (size); - sz = (int) fread (data, 1, size, f); - fclose (f); - if (sz != size) { - Hunk_FreeToLowMark(mark); - Host_Error("Read error for %s", glt->name); - } - } - else if (glt->source_file[0] && !glt->source_offset) { - data = Image_LoadImage (glt->source_file, (int *)&glt->source_width, (int *)&glt->source_height); //simple file - } - else if (!glt->source_file[0] && glt->source_offset) { - data = (byte *) glt->source_offset; //image in memory - } - if (!data) { -invalid: Con_Printf ("TexMgr_ReloadImage: invalid source for %s\n", glt->name); - Hunk_FreeToLowMark(mark); - return; - } + if (glt->source_file[0] && glt->source_offset) { + //lump inside file + FILE *f; + int sz; + COM_FOpenFile(glt->source_file, &f, NULL); + if (!f) goto invalid; + fseek(f, glt->source_offset, SEEK_CUR); + size = glt->source_width * glt->source_height; + /* should be SRC_INDEXED, but no harm being paranoid: */ + if (glt->source_format == SRC_RGBA) { + size *= 4; + } else if (glt->source_format == SRC_LIGHTMAP) { + size *= lightmap_bytes; + } + data = (byte *) Hunk_Alloc(size); + sz = (int) fread(data, 1, size, f); + fclose(f); + if (sz != size) { + Hunk_FreeToLowMark(mark); + Host_Error("Read error for %s", glt->name); + } + } else if (glt->source_file[0] && !glt->source_offset) { + data = Image_LoadImage(glt->source_file, (int *) &glt->source_width, (int *) &glt->source_height); //simple file + } else if (!glt->source_file[0] && glt->source_offset) { + data = (byte *) glt->source_offset; //image in memory + } + if (!data) { + invalid: + Con_Printf("TexMgr_ReloadImage: invalid source for %s\n", glt->name); + Hunk_FreeToLowMark(mark); + return; + } - glt->width = glt->source_width; - glt->height = glt->source_height; -// -// apply shirt and pants colors -// -// if shirt and pants are -1,-1, use existing shirt and pants colors -// if existing shirt and pants colors are -1,-1, don't bother colormapping - if (shirt > -1 && pants > -1) - { - if (glt->source_format == SRC_INDEXED) - { - glt->shirt = shirt; - glt->pants = pants; - } - else - Con_Printf ("TexMgr_ReloadImage: can't colormap a non SRC_INDEXED texture: %s\n", glt->name); - } - if (glt->shirt > -1 && glt->pants > -1) - { - //create new translation table - for (i = 0; i < 256; i++) - translation[i] = i; + glt->width = glt->source_width; + glt->height = glt->source_height; + // + // apply shirt and pants colors + // + // if shirt and pants are -1,-1, use existing shirt and pants colors + // if existing shirt and pants colors are -1,-1, don't bother colormapping + if (shirt > -1 && pants > -1) { + if (glt->source_format == SRC_INDEXED) { + glt->shirt = shirt; + glt->pants = pants; + } else + Con_Printf("TexMgr_ReloadImage: can't colormap a non SRC_INDEXED texture: %s\n", glt->name); + } + if (glt->shirt > -1 && glt->pants > -1) { + //create new translation table + for (i = 0; i < 256; i++) + translation[i] = i; - shirt = glt->shirt * 16; - if (shirt < 128) - { - for (i = 0; i < 16; i++) - translation[TOP_RANGE+i] = shirt + i; - } - else - { - for (i = 0; i < 16; i++) - translation[TOP_RANGE+i] = shirt+15-i; - } + shirt = glt->shirt * 16; + if (shirt < 128) { + for (i = 0; i < 16; i++) + translation[TOP_RANGE + i] = shirt + i; + } else { + for (i = 0; i < 16; i++) + translation[TOP_RANGE + i] = shirt + 15 - i; + } - pants = glt->pants * 16; - if (pants < 128) - { - for (i = 0; i < 16; i++) - translation[BOTTOM_RANGE+i] = pants + i; - } - else - { - for (i = 0; i < 16; i++) - translation[BOTTOM_RANGE+i] = pants+15-i; - } + pants = glt->pants * 16; + if (pants < 128) { + for (i = 0; i < 16; i++) + translation[BOTTOM_RANGE + i] = pants + i; + } else { + for (i = 0; i < 16; i++) + translation[BOTTOM_RANGE + i] = pants + 15 - i; + } - //translate texture - size = glt->width * glt->height; - dst = translated = (byte *) Hunk_Alloc (size); - src = data; + //translate texture + size = glt->width * glt->height; + dst = translated = (byte *) Hunk_Alloc(size); + src = data; - for (i = 0; i < size; i++) - *dst++ = translation[*src++]; + for (i = 0; i < size; i++) + *dst++ = translation[*src++]; - data = translated; - } -// -// upload it -// - switch (glt->source_format) - { - case SRC_INDEXED: - TexMgr_LoadImage8 (glt, data); - break; - case SRC_LIGHTMAP: - TexMgr_LoadLightmap (glt, data); - break; - case SRC_RGBA: - TexMgr_LoadImage32 (glt, (unsigned *)data); - break; - } + data = translated; + } + // + // upload it + // + switch (glt->source_format) { + case SRC_INDEXED: + TexMgr_LoadImage8(glt, data); + break; + case SRC_LIGHTMAP: + TexMgr_LoadLightmap(glt, data); + break; + case SRC_RGBA: + TexMgr_LoadImage32(glt, (unsigned *) data); + break; + } - Hunk_FreeToLowMark(mark); + Hunk_FreeToLowMark(mark); } /* @@ -1402,27 +1336,25 @@ invalid: Con_Printf ("TexMgr_ReloadImage: invalid source for %s\n", glt->name); TexMgr_ReloadImages -- reloads all texture images. called only by vid_restart ================ */ -void TexMgr_ReloadImages (void) -{ - gltexture_t *glt; +void TexMgr_ReloadImages(void) { + gltexture_t *glt; -// ericw -- tricky bug: if the hunk is almost full, an allocation in TexMgr_ReloadImage -// triggers cache items to be freed, which calls back into TexMgr to free the -// texture. If this frees 'glt' in the loop below, the active_gltextures -// list gets corrupted. -// A test case is jam3_tronyn.bsp with -heapsize 65536, and do several mode -// switches/fullscreen toggles -// 2015-09-04 -- Cache_Flush workaround was causing issues (http://sourceforge.net/p/quakespasm/bugs/10/) -// switching to a boolean flag. - in_reload_images = true; + // ericw -- tricky bug: if the hunk is almost full, an allocation in TexMgr_ReloadImage + // triggers cache items to be freed, which calls back into TexMgr to free the + // texture. If this frees 'glt' in the loop below, the active_gltextures + // list gets corrupted. + // A test case is jam3_tronyn.bsp with -heapsize 65536, and do several mode + // switches/fullscreen toggles + // 2015-09-04 -- Cache_Flush workaround was causing issues (http://sourceforge.net/p/quakespasm/bugs/10/) + // switching to a boolean flag. + in_reload_images = true; - for (glt = active_gltextures; glt; glt = glt->next) - { - glGenTextures(1, &glt->texnum); - TexMgr_ReloadImage (glt, -1, -1); - } + for (glt = active_gltextures; glt; glt = glt->next) { + glGenTextures(1, &glt->texnum); + TexMgr_ReloadImage(glt, -1, -1); + } - in_reload_images = false; + in_reload_images = false; } /* @@ -1430,13 +1362,12 @@ void TexMgr_ReloadImages (void) TexMgr_ReloadNobrightImages -- reloads all texture that were loaded with the nobright palette. called when gl_fullbrights changes ================ */ -void TexMgr_ReloadNobrightImages (void) -{ - gltexture_t *glt; +void TexMgr_ReloadNobrightImages(void) { + gltexture_t *glt; - for (glt = active_gltextures; glt; glt = glt->next) - if (glt->flags & TEXPREF_NOBRIGHT) - TexMgr_ReloadImage(glt, -1, -1); + for (glt = active_gltextures; glt; glt = glt->next) + if (glt->flags & TEXPREF_NOBRIGHT) + TexMgr_ReloadImage(glt, -1, -1); } /* @@ -1447,22 +1378,22 @@ void TexMgr_ReloadNobrightImages (void) ================================================================================ */ -static GLuint currenttexture[3] = {GL_UNUSED_TEXTURE, GL_UNUSED_TEXTURE, GL_UNUSED_TEXTURE}; // to avoid unnecessary texture sets -static GLenum currenttarget = GL_TEXTURE0_ARB; -qboolean mtexenabled = false; +static GLuint currenttexture[3] = {GL_UNUSED_TEXTURE, GL_UNUSED_TEXTURE, GL_UNUSED_TEXTURE}; +// to avoid unnecessary texture sets +static GLenum currenttarget = GL_TEXTURE0_ARB; +qboolean mtexenabled = false; /* ================ GL_SelectTexture -- johnfitz -- rewritten ================ */ -void GL_SelectTexture (GLenum target) -{ - if (target == currenttarget) - return; +void GL_SelectTexture(GLenum target) { + if (target == currenttarget) + return; - GL_SelectTextureFunc(target); - currenttarget = target; + GL_SelectTextureFunc(target); + currenttarget = target; } /* @@ -1470,14 +1401,12 @@ void GL_SelectTexture (GLenum target) GL_DisableMultitexture -- selects texture unit 0 ================ */ -void GL_DisableMultitexture(void) -{ - if (mtexenabled) - { - glDisable(GL_TEXTURE_2D); - GL_SelectTexture(GL_TEXTURE0_ARB); - mtexenabled = false; - } +void GL_DisableMultitexture(void) { + if (mtexenabled) { + glDisable(GL_TEXTURE_2D); + GL_SelectTexture(GL_TEXTURE0_ARB); + mtexenabled = false; + } } /* @@ -1485,14 +1414,12 @@ void GL_DisableMultitexture(void) GL_EnableMultitexture -- selects texture unit 1 ================ */ -void GL_EnableMultitexture(void) -{ - if (gl_mtexable) - { - GL_SelectTexture(GL_TEXTURE1_ARB); - glEnable(GL_TEXTURE_2D); - mtexenabled = true; - } +void GL_EnableMultitexture(void) { + if (gl_mtexable) { + GL_SelectTexture(GL_TEXTURE1_ARB); + glEnable(GL_TEXTURE_2D); + mtexenabled = true; + } } /* @@ -1500,17 +1427,15 @@ void GL_EnableMultitexture(void) GL_Bind -- johnfitz -- heavy revision ================ */ -void GL_Bind (gltexture_t *texture) -{ - if (!texture) - texture = nulltexture; +void GL_Bind(gltexture_t *texture) { + if (!texture) + texture = nulltexture; - if (texture->texnum != currenttexture[currenttarget - GL_TEXTURE0_ARB]) - { - currenttexture[currenttarget - GL_TEXTURE0_ARB] = texture->texnum; - glBindTexture (GL_TEXTURE_2D, texture->texnum); - texture->visframe = r_framecount; - } + if (texture->texnum != currenttexture[currenttarget - GL_TEXTURE0_ARB]) { + currenttexture[currenttarget - GL_TEXTURE0_ARB] = texture->texnum; + glBindTexture(GL_TEXTURE_2D, texture->texnum); + texture->visframe = r_framecount; + } } /* @@ -1521,15 +1446,14 @@ Wrapper around glDeleteTextures that also clears the given texture number from our per-TMU cached texture binding table. ================ */ -static void GL_DeleteTexture (gltexture_t *texture) -{ - glDeleteTextures (1, &texture->texnum); +static void GL_DeleteTexture(gltexture_t *texture) { + glDeleteTextures(1, &texture->texnum); - if (texture->texnum == currenttexture[0]) currenttexture[0] = GL_UNUSED_TEXTURE; - if (texture->texnum == currenttexture[1]) currenttexture[1] = GL_UNUSED_TEXTURE; - if (texture->texnum == currenttexture[2]) currenttexture[2] = GL_UNUSED_TEXTURE; + if (texture->texnum == currenttexture[0]) currenttexture[0] = GL_UNUSED_TEXTURE; + if (texture->texnum == currenttexture[1]) currenttexture[1] = GL_UNUSED_TEXTURE; + if (texture->texnum == currenttexture[2]) currenttexture[2] = GL_UNUSED_TEXTURE; - texture->texnum = 0; + texture->texnum = 0; } /* @@ -1541,11 +1465,9 @@ make real glBindTexture calls. Call this after changing the binding outside of GL_Bind. ================ */ -void GL_ClearBindings(void) -{ - int i; - for (i = 0; i < 3; i++) - { - currenttexture[i] = GL_UNUSED_TEXTURE; - } +void GL_ClearBindings(void) { + int i; + for (i = 0; i < 3; i++) { + currenttexture[i] = GL_UNUSED_TEXTURE; + } } diff --git a/Quake/gl_vidsdl.cpp b/Quake/gl_vidsdl.cpp index 6218d93..e861900 100644 --- a/Quake/gl_vidsdl.cpp +++ b/Quake/gl_vidsdl.cpp @@ -54,10 +54,10 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #define DEFAULT_REFRESHRATE 60 typedef struct { - int width; - int height; - int refreshrate; - int bpp; + int width; + int height; + int refreshrate; + int bpp; } vmode_t; static const char *gl_vendor; @@ -66,35 +66,38 @@ static const char *gl_version; static int gl_version_major; static int gl_version_minor; static const char *gl_extensions; -static char * gl_extensions_nice; +static char *gl_extensions_nice; -static vmode_t modelist[MAX_MODE_LIST]; -static int nummodes; +static vmode_t modelist[MAX_MODE_LIST]; +static int nummodes; -static qboolean vid_initialized = false; +static qboolean vid_initialized = false; #if defined(USE_SDL2) -static SDL_Window *draw_context; -static SDL_GLContext gl_context; +static SDL_Window *draw_context; +static SDL_GLContext gl_context; #else -static SDL_Surface *draw_context; +static SDL_Surface *draw_context; #endif -static qboolean vid_locked = false; //johnfitz -static qboolean vid_changed = false; +static qboolean vid_locked = false; //johnfitz +static qboolean vid_changed = false; -static void VID_Menu_Init (void); //johnfitz -static void VID_Menu_f (void); //johnfitz -static void VID_MenuDraw (void); -static void VID_MenuKey (int key); +static void VID_Menu_Init(void); //johnfitz +static void VID_Menu_f(void); //johnfitz +static void VID_MenuDraw(void); -static void ClearAllStates (void); -static void GL_Init (void); -static void GL_SetupState (void); //johnfitz +static void VID_MenuKey(int key); -viddef_t vid; // global video state -modestate_t modestate = MS_UNINIT; -qboolean scr_skipupdate; +static void ClearAllStates(void); + +static void GL_Init(void); + +static void GL_SetupState(void); //johnfitz + +viddef_t vid; // global video state +modestate_t modestate = MS_UNINIT; +qboolean scr_skipupdate; qboolean gl_mtexable = false; qboolean gl_packed_pixels = false; @@ -149,19 +152,19 @@ QS_PFNGENERATEMIPMAP GL_GenerateMipmap = NULL; //==================================== //johnfitz -- new cvars -static cvar_t vid_fullscreen = {"vid_fullscreen", "0", CVAR_ARCHIVE}; // QuakeSpasm, was "1" -static cvar_t vid_width = {"vid_width", "800", CVAR_ARCHIVE}; // QuakeSpasm, was 640 -static cvar_t vid_height = {"vid_height", "600", CVAR_ARCHIVE}; // QuakeSpasm, was 480 -static cvar_t vid_bpp = {"vid_bpp", "16", CVAR_ARCHIVE}; -static cvar_t vid_refreshrate = {"vid_refreshrate", "60", CVAR_ARCHIVE}; -static cvar_t vid_vsync = {"vid_vsync", "0", CVAR_ARCHIVE}; -static cvar_t vid_fsaa = {"vid_fsaa", "0", CVAR_ARCHIVE}; // QuakeSpasm -static cvar_t vid_desktopfullscreen = {"vid_desktopfullscreen", "0", CVAR_ARCHIVE}; // QuakeSpasm -static cvar_t vid_borderless = {"vid_borderless", "0", CVAR_ARCHIVE}; // QuakeSpasm +static convar vid_fullscreen{"vid_fullscreen", "0", {.archive = true}}; // QuakeSpasm, was "1" +static convar vid_width{"vid_width", "800", {.archive = true}}; // QuakeSpasm, was 640 +static convar vid_height{"vid_height", "600", {.archive = true}}; // QuakeSpasm, was 480 +static convar vid_bpp{"vid_bpp", "16", {.archive = true}}; +static convar vid_refreshrate{"vid_refreshrate", "60", {.archive = true}}; +static convar vid_vsync{"vid_vsync", "0", {.archive = true}}; +static convar vid_fsaa{"vid_fsaa", "0", {.archive = true}}; // QuakeSpasm +static convar vid_desktopfullscreen{"vid_desktopfullscreen", "0", {.archive = true}}; // QuakeSpasm +static convar vid_borderless{"vid_borderless", "0", {.archive = true}}; // QuakeSpasm //johnfitz -cvar_t vid_gamma = {"gamma", "1", CVAR_ARCHIVE}; //johnfitz -- moved here from view.c -cvar_t vid_contrast = {"contrast", "1", CVAR_ARCHIVE}; //QuakeSpasm, MarkV +convar vid_gamma = {"gamma", "1", {.archive = true}}; //johnfitz -- moved here from view.c +convar vid_contrast = {"contrast", "1", {.archive = true}}; //QuakeSpasm, MarkV //========================================================================== // @@ -181,7 +184,7 @@ static unsigned short vid_sysgamma_green[256]; static unsigned short vid_sysgamma_blue[256]; #endif -static qboolean gammaworks = false; // whether hw-gamma works +static qboolean gammaworks = false; // whether hw-gamma works static int fsaa; /* @@ -189,38 +192,36 @@ static int fsaa; VID_Gamma_SetGamma -- apply gamma correction ================ */ -static void VID_Gamma_SetGamma (void) -{ - if (gl_glsl_gamma_able) - return; +static void VID_Gamma_SetGamma(void) { + if (gl_glsl_gamma_able) + return; - if (draw_context && gammaworks) - { - float value; + if (draw_context && gammaworks) { + float value; - if (vid_gamma.value > (1.0f / GAMMA_MAX)) - value = 1.0f / vid_gamma.value; - else - value = GAMMA_MAX; + if (vid_gamma.value > (1.0f / GAMMA_MAX)) + value = 1.0f / vid_gamma.value; + else + value = GAMMA_MAX; #if defined(USE_SDL2) # if USE_GAMMA_RAMPS - if (SDL_SetWindowGammaRamp(draw_context, vid_gamma_red, vid_gamma_green, vid_gamma_blue) != 0) - Con_Printf ("VID_Gamma_SetGamma: failed on SDL_SetWindowGammaRamp\n"); + if (SDL_SetWindowGammaRamp(draw_context, vid_gamma_red, vid_gamma_green, vid_gamma_blue) != 0) + Con_Printf("VID_Gamma_SetGamma: failed on SDL_SetWindowGammaRamp\n"); # else - if (SDL_SetWindowBrightness(draw_context, value) != 0) - Con_Printf ("VID_Gamma_SetGamma: failed on SDL_SetWindowBrightness\n"); + if (SDL_SetWindowBrightness(draw_context, value) != 0) + Con_Printf("VID_Gamma_SetGamma: failed on SDL_SetWindowBrightness\n"); # endif #else /* USE_SDL2 */ # if USE_GAMMA_RAMPS - if (SDL_SetGammaRamp(vid_gamma_red, vid_gamma_green, vid_gamma_blue) == -1) - Con_Printf ("VID_Gamma_SetGamma: failed on SDL_SetGammaRamp\n"); + if (SDL_SetGammaRamp(vid_gamma_red, vid_gamma_green, vid_gamma_blue) == -1) + Con_Printf("VID_Gamma_SetGamma: failed on SDL_SetGammaRamp\n"); # else - if (SDL_SetGamma(value,value,value) == -1) - Con_Printf ("VID_Gamma_SetGamma: failed on SDL_SetGamma\n"); + if (SDL_SetGamma(value, value, value) == -1) + Con_Printf("VID_Gamma_SetGamma: failed on SDL_SetGamma\n"); # endif #endif /* USE_SDL2 */ - } + } } /* @@ -228,31 +229,29 @@ static void VID_Gamma_SetGamma (void) VID_Gamma_Restore -- restore system gamma ================ */ -static void VID_Gamma_Restore (void) -{ - if (gl_glsl_gamma_able) - return; +static void VID_Gamma_Restore(void) { + if (gl_glsl_gamma_able) + return; - if (draw_context && gammaworks) - { + if (draw_context && gammaworks) { #if defined(USE_SDL2) # if USE_GAMMA_RAMPS - if (SDL_SetWindowGammaRamp(draw_context, vid_sysgamma_red, vid_sysgamma_green, vid_sysgamma_blue) != 0) - Con_Printf ("VID_Gamma_Restore: failed on SDL_SetWindowGammaRamp\n"); + if (SDL_SetWindowGammaRamp(draw_context, vid_sysgamma_red, vid_sysgamma_green, vid_sysgamma_blue) != 0) + Con_Printf("VID_Gamma_Restore: failed on SDL_SetWindowGammaRamp\n"); # else - if (SDL_SetWindowBrightness(draw_context, 1) != 0) - Con_Printf ("VID_Gamma_Restore: failed on SDL_SetWindowBrightness\n"); + if (SDL_SetWindowBrightness(draw_context, 1) != 0) + Con_Printf("VID_Gamma_Restore: failed on SDL_SetWindowBrightness\n"); # endif #else /* USE_SDL2 */ # if USE_GAMMA_RAMPS - if (SDL_SetGammaRamp(vid_sysgamma_red, vid_sysgamma_green, vid_sysgamma_blue) == -1) - Con_Printf ("VID_Gamma_Restore: failed on SDL_SetGammaRamp\n"); + if (SDL_SetGammaRamp(vid_sysgamma_red, vid_sysgamma_green, vid_sysgamma_blue) == -1) + Con_Printf("VID_Gamma_Restore: failed on SDL_SetGammaRamp\n"); # else - if (SDL_SetGamma(1, 1, 1) == -1) - Con_Printf ("VID_Gamma_Restore: failed on SDL_SetGamma\n"); + if (SDL_SetGamma(1, 1, 1) == -1) + Con_Printf("VID_Gamma_Restore: failed on SDL_SetGamma\n"); # endif #endif /* USE_SDL2 */ - } + } } /* @@ -260,9 +259,8 @@ static void VID_Gamma_Restore (void) VID_Gamma_Shutdown -- called on exit ================ */ -static void VID_Gamma_Shutdown (void) -{ - VID_Gamma_Restore (); +static void VID_Gamma_Shutdown(void) { + VID_Gamma_Restore(); } /* @@ -270,23 +268,21 @@ static void VID_Gamma_Shutdown (void) VID_Gamma_f -- callback when the cvar changes ================ */ -static void VID_Gamma_f (cvar_t *var) -{ - if (gl_glsl_gamma_able) - return; +static void VID_Gamma_f(convar *var) { + if (gl_glsl_gamma_able) + return; #if USE_GAMMA_RAMPS - int i; + int i; - for (i = 0; i < 256; i++) - { - vid_gamma_red[i] = - CLAMP(0, (int) ((255 * pow((i + 0.5)/255.5, vid_gamma.value) + 0.5) * vid_contrast.value), 255) << 8; - vid_gamma_green[i] = vid_gamma_red[i]; - vid_gamma_blue[i] = vid_gamma_red[i]; - } + for (i = 0; i < 256; i++) { + vid_gamma_red[i] = + CLAMP(0, (int) ((255 * pow((i + 0.5)/255.5, vid_gamma.value) + 0.5) * vid_contrast.value), 255) << 8; + vid_gamma_green[i] = vid_gamma_red[i]; + vid_gamma_blue[i] = vid_gamma_red[i]; + } #endif - VID_Gamma_SetGamma (); + VID_Gamma_SetGamma(); } /* @@ -294,36 +290,36 @@ static void VID_Gamma_f (cvar_t *var) VID_Gamma_Init -- call on init ================ */ -static void VID_Gamma_Init (void) -{ - Cvar_RegisterVariable (&vid_gamma); - Cvar_RegisterVariable (&vid_contrast); - Cvar_SetCallback (&vid_gamma, VID_Gamma_f); - Cvar_SetCallback (&vid_contrast, VID_Gamma_f); +static void VID_Gamma_Init(void) { + vid_gamma.inscribe(); + vid_contrast.inscribe(); + vid_gamma.set_callback(VID_Gamma_f); + vid_contrast.set_callback(VID_Gamma_f); - if (gl_glsl_gamma_able) - return; + if (gl_glsl_gamma_able) + return; #if defined(USE_SDL2) # if USE_GAMMA_RAMPS - gammaworks = (SDL_GetWindowGammaRamp(draw_context, vid_sysgamma_red, vid_sysgamma_green, vid_sysgamma_blue) == 0); - if (gammaworks) - gammaworks = (SDL_SetWindowGammaRamp(draw_context, vid_sysgamma_red, vid_sysgamma_green, vid_sysgamma_blue) == 0); + gammaworks = (SDL_GetWindowGammaRamp(draw_context, vid_sysgamma_red, vid_sysgamma_green, vid_sysgamma_blue) == 0); + if (gammaworks) + gammaworks = (SDL_SetWindowGammaRamp(draw_context, vid_sysgamma_red, vid_sysgamma_green, vid_sysgamma_blue) == + 0); # else - gammaworks = (SDL_SetWindowBrightness(draw_context, 1) == 0); + gammaworks = (SDL_SetWindowBrightness(draw_context, 1) == 0); # endif #else /* USE_SDL2 */ # if USE_GAMMA_RAMPS - gammaworks = (SDL_GetGammaRamp(vid_sysgamma_red, vid_sysgamma_green, vid_sysgamma_blue) == 0); - if (gammaworks) - gammaworks = (SDL_SetGammaRamp(vid_sysgamma_red, vid_sysgamma_green, vid_sysgamma_blue) == 0); + gammaworks = (SDL_GetGammaRamp(vid_sysgamma_red, vid_sysgamma_green, vid_sysgamma_blue) == 0); + if (gammaworks) + gammaworks = (SDL_SetGammaRamp(vid_sysgamma_red, vid_sysgamma_green, vid_sysgamma_blue) == 0); # else - gammaworks = (SDL_SetGamma(1, 1, 1) == 0); + gammaworks = (SDL_SetGamma(1, 1, 1) == 0); # endif #endif /* USE_SDL2 */ - if (!gammaworks) - Con_SafePrintf("gamma adjustment not available\n"); + if (!gammaworks) + Con_SafePrintf("gamma adjustment not available\n"); } /* @@ -331,14 +327,13 @@ static void VID_Gamma_Init (void) VID_GetCurrentWidth ====================== */ -static int VID_GetCurrentWidth (void) -{ +static int VID_GetCurrentWidth(void) { #if defined(USE_SDL2) - int w = 0, h = 0; - SDL_GetWindowSize(draw_context, &w, &h); - return w; + int w = 0, h = 0; + SDL_GetWindowSize(draw_context, &w, &h); + return w; #else - return draw_context->w; + return draw_context->w; #endif } @@ -347,14 +342,13 @@ static int VID_GetCurrentWidth (void) VID_GetCurrentHeight ======================= */ -static int VID_GetCurrentHeight (void) -{ +static int VID_GetCurrentHeight(void) { #if defined(USE_SDL2) - int w = 0, h = 0; - SDL_GetWindowSize(draw_context, &w, &h); - return h; + int w = 0, h = 0; + SDL_GetWindowSize(draw_context, &w, &h); + return h; #else - return draw_context->h; + return draw_context->h; #endif } @@ -363,21 +357,20 @@ static int VID_GetCurrentHeight (void) VID_GetCurrentRefreshRate ==================== */ -static int VID_GetCurrentRefreshRate (void) -{ +static int VID_GetCurrentRefreshRate(void) { #if defined(USE_SDL2) - SDL_DisplayMode mode; - int current_display; + SDL_DisplayMode mode; + int current_display; - current_display = SDL_GetWindowDisplayIndex(draw_context); + current_display = SDL_GetWindowDisplayIndex(draw_context); - if (0 != SDL_GetCurrentDisplayMode(current_display, &mode)) - return DEFAULT_REFRESHRATE; + if (0 != SDL_GetCurrentDisplayMode(current_display, &mode)) + return DEFAULT_REFRESHRATE; - return mode.refresh_rate; + return mode.refresh_rate; #else - // SDL1.2 doesn't support refresh rates - return DEFAULT_REFRESHRATE; + // SDL1.2 doesn't support refresh rates + return DEFAULT_REFRESHRATE; #endif } @@ -387,45 +380,42 @@ static int VID_GetCurrentRefreshRate (void) VID_GetCurrentBPP ==================== */ -static int VID_GetCurrentBPP (void) -{ +static int VID_GetCurrentBPP(void) { #if defined(USE_SDL2) - const Uint32 pixelFormat = SDL_GetWindowPixelFormat(draw_context); - return SDL_BITSPERPIXEL(pixelFormat); + const Uint32 pixelFormat = SDL_GetWindowPixelFormat(draw_context); + return SDL_BITSPERPIXEL(pixelFormat); #else - return draw_context->format->BitsPerPixel; + return draw_context->format->BitsPerPixel; #endif } /* ==================== VID_GetFullscreen - + returns true if we are in regular fullscreen or "desktop fullscren" ==================== */ -static qboolean VID_GetFullscreen (void) -{ +static qboolean VID_GetFullscreen(void) { #if defined(USE_SDL2) - return (SDL_GetWindowFlags(draw_context) & SDL_WINDOW_FULLSCREEN) != 0; + return (SDL_GetWindowFlags(draw_context) & SDL_WINDOW_FULLSCREEN) != 0; #else - return (draw_context->flags & SDL_FULLSCREEN) != 0; + return (draw_context->flags & SDL_FULLSCREEN) != 0; #endif } /* ==================== VID_GetDesktopFullscreen - + returns true if we are specifically in "desktop fullscreen" mode ==================== */ -static qboolean VID_GetDesktopFullscreen (void) -{ +static qboolean VID_GetDesktopFullscreen(void) { #if defined(USE_SDL2) - return (SDL_GetWindowFlags(draw_context) & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN_DESKTOP; + return (SDL_GetWindowFlags(draw_context) & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN_DESKTOP; #else - return false; + return false; #endif } @@ -434,15 +424,14 @@ static qboolean VID_GetDesktopFullscreen (void) VID_GetVSync ==================== */ -static qboolean VID_GetVSync (void) -{ +static qboolean VID_GetVSync(void) { #if defined(USE_SDL2) - return SDL_GL_GetSwapInterval() == 1; + return SDL_GL_GetSwapInterval() == 1; #else - int swap_control; - if (SDL_GL_GetAttribute(SDL_GL_SWAP_CONTROL, &swap_control) == 0) - return swap_control > 0; - return false; + int swap_control; + if (SDL_GL_GetAttribute(SDL_GL_SWAP_CONTROL, &swap_control) == 0) + return swap_control > 0; + return false; #endif } @@ -453,12 +442,11 @@ VID_GetWindow used by pl_win.c ==================== */ -void *VID_GetWindow (void) -{ +void *VID_GetWindow(void) { #if defined(USE_SDL2) - return draw_context; + return draw_context; #else - return NULL; + return NULL; #endif } @@ -467,12 +455,11 @@ void *VID_GetWindow (void) VID_HasMouseOrInputFocus ==================== */ -qboolean VID_HasMouseOrInputFocus (void) -{ +qboolean VID_HasMouseOrInputFocus(void) { #if defined(USE_SDL2) - return (SDL_GetWindowFlags(draw_context) & (SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_INPUT_FOCUS)) != 0; + return (SDL_GetWindowFlags(draw_context) & (SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_INPUT_FOCUS)) != 0; #else - return (SDL_GetAppState() & (SDL_APPMOUSEFOCUS | SDL_APPINPUTFOCUS)) != 0; + return (SDL_GetAppState() & (SDL_APPMOUSEFOCUS | SDL_APPINPUTFOCUS)) != 0; #endif } @@ -481,13 +468,12 @@ qboolean VID_HasMouseOrInputFocus (void) VID_IsMinimized ==================== */ -qboolean VID_IsMinimized (void) -{ +qboolean VID_IsMinimized(void) { #if defined(USE_SDL2) - return !(SDL_GetWindowFlags(draw_context) & SDL_WINDOW_SHOWN); + return !(SDL_GetWindowFlags(draw_context) & SDL_WINDOW_SHOWN); #else - /* SDL_APPACTIVE in SDL 1.x means "not minimized" */ - return !(SDL_GetAppState() & SDL_APPACTIVE); + /* SDL_APPACTIVE in SDL 1.x means "not minimized" */ + return !(SDL_GetAppState() & SDL_APPACTIVE); #endif } @@ -504,25 +490,22 @@ This is passed to SDL_SetWindowDisplayMode to specify a pixel format with the requested bpp. If we didn't care about bpp we could just pass NULL. ================ */ -static SDL_DisplayMode *VID_SDL2_GetDisplayMode(int width, int height, int refreshrate, int bpp) -{ - static SDL_DisplayMode mode; - const int sdlmodes = SDL_GetNumDisplayModes(0); - int i; +static SDL_DisplayMode *VID_SDL2_GetDisplayMode(int width, int height, int refreshrate, int bpp) { + static SDL_DisplayMode mode; + const int sdlmodes = SDL_GetNumDisplayModes(0); + int i; - for (i = 0; i < sdlmodes; i++) - { - if (SDL_GetDisplayMode(0, i, &mode) != 0) - continue; + for (i = 0; i < sdlmodes; i++) { + if (SDL_GetDisplayMode(0, i, &mode) != 0) + continue; - if (mode.w == width && mode.h == height - && SDL_BITSPERPIXEL(mode.format) == bpp - && mode.refresh_rate == refreshrate) - { - return &mode; - } - } - return NULL; + if (mode.w == width && mode.h == height + && SDL_BITSPERPIXEL(mode.format) == bpp + && mode.refresh_rate == refreshrate) { + return &mode; + } + } + return NULL; } #endif /* USE_SDL2 */ @@ -531,42 +514,40 @@ static SDL_DisplayMode *VID_SDL2_GetDisplayMode(int width, int height, int refre VID_ValidMode ================ */ -static qboolean VID_ValidMode (int width, int height, int refreshrate, int bpp, qboolean fullscreen) -{ -// ignore width / height / bpp if vid_desktopfullscreen is enabled - if (fullscreen && vid_desktopfullscreen.value) - return true; +static qboolean VID_ValidMode(int width, int height, int refreshrate, int bpp, qboolean fullscreen) { + // ignore width / height / bpp if vid_desktopfullscreen is enabled + if (fullscreen && vid_desktopfullscreen.value) + return true; - if (width < 320) - return false; + if (width < 320) + return false; - if (height < 200) - return false; + if (height < 200) + return false; #if defined(USE_SDL2) - if (fullscreen && VID_SDL2_GetDisplayMode(width, height, refreshrate, bpp) == NULL) - bpp = 0; + if (fullscreen && VID_SDL2_GetDisplayMode(width, height, refreshrate, bpp) == NULL) + bpp = 0; #else - { - Uint32 flags = DEFAULT_SDL_FLAGS; - if (fullscreen) - flags |= SDL_FULLSCREEN; + { + Uint32 flags = DEFAULT_SDL_FLAGS; + if (fullscreen) + flags |= SDL_FULLSCREEN; - bpp = SDL_VideoModeOK(width, height, bpp, flags); - } + bpp = SDL_VideoModeOK(width, height, bpp, flags); + } #endif - switch (bpp) - { - case 16: - case 24: - case 32: - break; - default: - return false; - } + switch (bpp) { + case 16: + case 24: + case 32: + break; + default: + return false; + } - return true; + return true; } /* @@ -574,191 +555,193 @@ static qboolean VID_ValidMode (int width, int height, int refreshrate, int bpp, VID_SetMode ================ */ -static qboolean VID_SetMode (int width, int height, int refreshrate, int bpp, qboolean fullscreen) -{ - int temp; - Uint32 flags; - char caption[50]; - int depthbits, stencilbits; - int fsaa_obtained; +static qboolean VID_SetMode(int width, int height, int refreshrate, int bpp, qboolean fullscreen) { + int temp; + Uint32 flags; + char caption[50]; + int depthbits, stencilbits; + int fsaa_obtained; #if defined(USE_SDL2) - int previous_display; + int previous_display; #endif - // so Con_Printfs don't mess us up by forcing vid and snd updates - temp = scr_disabled_for_loading; - scr_disabled_for_loading = true; + // so Con_Printfs don't mess us up by forcing vid and snd updates + temp = scr_disabled_for_loading; + scr_disabled_for_loading = true; - CDAudio_Pause (); - BGM_Pause (); + CDAudio_Pause(); + BGM_Pause(); - /* z-buffer depth */ - if (bpp == 16) - { - depthbits = 16; - stencilbits = 0; - } - else - { - depthbits = 24; - stencilbits = 8; - } - SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, depthbits); - SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, stencilbits); + /* z-buffer depth */ + if (bpp == 16) { + depthbits = 16; + stencilbits = 0; + } else { + depthbits = 24; + stencilbits = 8; + } + SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, depthbits); + SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, stencilbits); - /* fsaa */ - SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, fsaa > 0 ? 1 : 0); - SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, fsaa); + /* fsaa */ + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, fsaa > 0 ? 1 : 0); + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, fsaa); - q_snprintf(caption, sizeof(caption), "QuakeSpasm " QUAKESPASM_VER_STRING); + q_snprintf(caption, sizeof(caption), "QuakeSpasm " QUAKESPASM_VER_STRING); #if defined(USE_SDL2) - /* Create the window if needed, hidden */ - if (!draw_context) - { - flags = SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN; + /* Create the window if needed, hidden */ + if (!draw_context) { + flags = SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN; - if (vid_borderless.value) - flags |= SDL_WINDOW_BORDERLESS; + if (vid_borderless.value) + flags |= SDL_WINDOW_BORDERLESS; - draw_context = SDL_CreateWindow (caption, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, flags); - if (!draw_context) { // scale back fsaa - SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); - SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); - draw_context = SDL_CreateWindow (caption, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, flags); - } - if (!draw_context) { // scale back SDL_GL_DEPTH_SIZE - SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); - draw_context = SDL_CreateWindow (caption, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, flags); - } - if (!draw_context) { // scale back SDL_GL_STENCIL_SIZE - SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0); - draw_context = SDL_CreateWindow (caption, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, flags); - } - if (!draw_context) - Sys_Error ("Couldn't create window"); + draw_context = SDL_CreateWindow(caption, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, + flags); + if (!draw_context) { + // scale back fsaa + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); + draw_context = SDL_CreateWindow(caption, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, + flags); + } + if (!draw_context) { + // scale back SDL_GL_DEPTH_SIZE + SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); + draw_context = SDL_CreateWindow(caption, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, + flags); + } + if (!draw_context) { + // scale back SDL_GL_STENCIL_SIZE + SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0); + draw_context = SDL_CreateWindow(caption, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, + flags); + } + if (!draw_context) + Sys_Error("Couldn't create window"); - previous_display = -1; - } - else - { - previous_display = SDL_GetWindowDisplayIndex(draw_context); - } + previous_display = -1; + } else { + previous_display = SDL_GetWindowDisplayIndex(draw_context); + } - /* Ensure the window is not fullscreen */ - if (VID_GetFullscreen ()) - { - if (SDL_SetWindowFullscreen (draw_context, 0) != 0) - Sys_Error("Couldn't set fullscreen state mode"); - } + /* Ensure the window is not fullscreen */ + if (VID_GetFullscreen()) { + if (SDL_SetWindowFullscreen(draw_context, 0) != 0) + Sys_Error("Couldn't set fullscreen state mode"); + } - /* Set window size and display mode */ - SDL_SetWindowSize (draw_context, width, height); - if (previous_display >= 0) - SDL_SetWindowPosition (draw_context, SDL_WINDOWPOS_CENTERED_DISPLAY(previous_display), SDL_WINDOWPOS_CENTERED_DISPLAY(previous_display)); - else - SDL_SetWindowPosition(draw_context, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); - SDL_SetWindowDisplayMode (draw_context, VID_SDL2_GetDisplayMode(width, height, refreshrate, bpp)); - SDL_SetWindowBordered (draw_context, vid_borderless.value ? SDL_FALSE : SDL_TRUE); + /* Set window size and display mode */ + SDL_SetWindowSize(draw_context, width, height); + if (previous_display >= 0) + SDL_SetWindowPosition(draw_context, SDL_WINDOWPOS_CENTERED_DISPLAY(previous_display), + SDL_WINDOWPOS_CENTERED_DISPLAY(previous_display)); + else + SDL_SetWindowPosition(draw_context, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); + SDL_SetWindowDisplayMode(draw_context, VID_SDL2_GetDisplayMode(width, height, refreshrate, bpp)); + SDL_SetWindowBordered(draw_context, vid_borderless.value ? SDL_FALSE : SDL_TRUE); - /* Make window fullscreen if needed, and show the window */ + /* Make window fullscreen if needed, and show the window */ - if (fullscreen) { - const Uint32 flag = vid_desktopfullscreen.value ? - SDL_WINDOW_FULLSCREEN_DESKTOP : SDL_WINDOW_FULLSCREEN; - if (SDL_SetWindowFullscreen (draw_context, flag) != 0) - Sys_Error ("Couldn't set fullscreen state mode"); - } + if (fullscreen) { + const Uint32 flag = vid_desktopfullscreen.value ? SDL_WINDOW_FULLSCREEN_DESKTOP : SDL_WINDOW_FULLSCREEN; + if (SDL_SetWindowFullscreen(draw_context, flag) != 0) + Sys_Error("Couldn't set fullscreen state mode"); + } - SDL_ShowWindow (draw_context); - SDL_RaiseWindow (draw_context); + SDL_ShowWindow(draw_context); + SDL_RaiseWindow(draw_context); - /* Create GL context if needed */ - if (!gl_context) { - gl_context = SDL_GL_CreateContext(draw_context); - if (!gl_context) - Sys_Error("Couldn't create GL context"); - } + /* Create GL context if needed */ + if (!gl_context) { + gl_context = SDL_GL_CreateContext(draw_context); + if (!gl_context) + Sys_Error("Couldn't create GL context"); + } - gl_swap_control = true; - if (SDL_GL_SetSwapInterval ((vid_vsync.value) ? 1 : 0) == -1) - gl_swap_control = false; + gl_swap_control = true; + if (SDL_GL_SetSwapInterval((vid_vsync.value) ? 1 : 0) == -1) + gl_swap_control = false; #else /* !defined(USE_SDL2) */ - flags = DEFAULT_SDL_FLAGS; - if (fullscreen) - flags |= SDL_FULLSCREEN; - if (vid_borderless.value) - flags |= SDL_NOFRAME; + flags = DEFAULT_SDL_FLAGS; + if (fullscreen) + flags |= SDL_FULLSCREEN; + if (vid_borderless.value) + flags |= SDL_NOFRAME; - gl_swap_control = true; - if (SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, (vid_vsync.value) ? 1 : 0) == -1) - gl_swap_control = false; + gl_swap_control = true; + if (SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, (vid_vsync.value) ? 1 : 0) == -1) + gl_swap_control = false; - bpp = SDL_VideoModeOK(width, height, bpp, flags); + bpp = SDL_VideoModeOK(width, height, bpp, flags); - draw_context = SDL_SetVideoMode(width, height, bpp, flags); - if (!draw_context) { // scale back fsaa - SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); - SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); - draw_context = SDL_SetVideoMode(width, height, bpp, flags); - } - if (!draw_context) { // scale back SDL_GL_DEPTH_SIZE - SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); - draw_context = SDL_SetVideoMode(width, height, bpp, flags); - } - if (!draw_context) { // scale back SDL_GL_STENCIL_SIZE - SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0); - draw_context = SDL_SetVideoMode(width, height, bpp, flags); - if (!draw_context) - Sys_Error ("Couldn't set video mode"); - } + draw_context = SDL_SetVideoMode(width, height, bpp, flags); + if (!draw_context) { + // scale back fsaa + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); + draw_context = SDL_SetVideoMode(width, height, bpp, flags); + } + if (!draw_context) { + // scale back SDL_GL_DEPTH_SIZE + SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); + draw_context = SDL_SetVideoMode(width, height, bpp, flags); + } + if (!draw_context) { + // scale back SDL_GL_STENCIL_SIZE + SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0); + draw_context = SDL_SetVideoMode(width, height, bpp, flags); + if (!draw_context) + Sys_Error("Couldn't set video mode"); + } - SDL_WM_SetCaption(caption, caption); + SDL_WM_SetCaption(caption, caption); #endif /* !defined(USE_SDL2) */ - vid.width = VID_GetCurrentWidth(); - vid.height = VID_GetCurrentHeight(); - vid.conwidth = vid.width & 0xFFFFFFF8; - vid.conheight = vid.conwidth * vid.height / vid.width; - vid.numpages = 2; + vid.width = VID_GetCurrentWidth(); + vid.height = VID_GetCurrentHeight(); + vid.conwidth = vid.width & 0xFFFFFFF8; + vid.conheight = vid.conwidth * vid.height / vid.width; + vid.numpages = 2; -// read the obtained z-buffer depth - if (SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &depthbits) == -1) - depthbits = 0; + // read the obtained z-buffer depth + if (SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &depthbits) == -1) + depthbits = 0; -// read obtained fsaa samples - if (SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &fsaa_obtained) == -1) - fsaa_obtained = 0; + // read obtained fsaa samples + if (SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &fsaa_obtained) == -1) + fsaa_obtained = 0; -// read stencil bits - if (SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &gl_stencilbits) == -1) - gl_stencilbits = 0; + // read stencil bits + if (SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &gl_stencilbits) == -1) + gl_stencilbits = 0; - modestate = VID_GetFullscreen() ? MS_FULLSCREEN : MS_WINDOWED; + modestate = VID_GetFullscreen() ? MS_FULLSCREEN : MS_WINDOWED; - CDAudio_Resume (); - BGM_Resume (); - scr_disabled_for_loading = temp; + CDAudio_Resume(); + BGM_Resume(); + scr_disabled_for_loading = temp; -// fix the leftover Alt from any Alt-Tab or the like that switched us away - ClearAllStates (); + // fix the leftover Alt from any Alt-Tab or the like that switched us away + ClearAllStates(); - Con_SafePrintf ("Video mode %dx%dx%d %dHz (%d-bit z-buffer, %dx FSAA) initialized\n", - VID_GetCurrentWidth(), - VID_GetCurrentHeight(), - VID_GetCurrentBPP(), - VID_GetCurrentRefreshRate(), - depthbits, - fsaa_obtained); + Con_SafePrintf("Video mode %dx%dx%d %dHz (%d-bit z-buffer, %dx FSAA) initialized\n", + VID_GetCurrentWidth(), + VID_GetCurrentHeight(), + VID_GetCurrentBPP(), + VID_GetCurrentRefreshRate(), + depthbits, + fsaa_obtained); - vid.recalc_refdef = 1; + vid.recalc_refdef = 1; -// no pending changes - vid_changed = false; + // no pending changes + vid_changed = false; - return true; + return true; } /* @@ -766,9 +749,8 @@ static qboolean VID_SetMode (int width, int height, int refreshrate, int bpp, qb VID_Changed_f -- kristian -- notify us that a value has changed that requires a vid_restart =================== */ -static void VID_Changed_f (cvar_t *var) -{ - vid_changed = true; +static void VID_Changed_f(convar *var) { + vid_changed = true; } /* @@ -776,78 +758,79 @@ static void VID_Changed_f (cvar_t *var) VID_Restart -- johnfitz -- change video modes on the fly =================== */ -static void VID_Restart (void) -{ - int width, height, refreshrate, bpp; - qboolean fullscreen; +static void VID_Restart(void) { + int width, height, refreshrate, bpp; + qboolean fullscreen; - if (vid_locked || !vid_changed) - return; + if (vid_locked || !vid_changed) + return; - width = (int)vid_width.value; - height = (int)vid_height.value; - refreshrate = (int)vid_refreshrate.value; - bpp = (int)vid_bpp.value; - fullscreen = vid_fullscreen.value ? true : false; + width = (int) vid_width.value; + height = (int) vid_height.value; + refreshrate = (int) vid_refreshrate.value; + bpp = (int) vid_bpp.value; + fullscreen = vid_fullscreen.value ? true : false; -// -// validate new mode -// - if (!VID_ValidMode (width, height, refreshrate, bpp, fullscreen)) - { - Con_Printf ("%dx%dx%d %dHz %s is not a valid mode\n", - width, height, bpp, refreshrate, fullscreen? "fullscreen" : "windowed"); - return; - } + // + // validate new mode + // + if (!VID_ValidMode(width, height, refreshrate, bpp, fullscreen)) { + Con_Printf("%dx%dx%d %dHz %s is not a valid mode\n", + width, height, bpp, refreshrate, fullscreen ? "fullscreen" : "windowed"); + return; + } -// ericw -- OS X, SDL1: textures, VBO's invalid after mode change -// OS X, SDL2: still valid after mode change -// To handle both cases, delete all GL objects (textures, VBO, GLSL) now. -// We must not interleave deleting the old objects with creating new ones, because -// one of the new objects could be given the same ID as an invalid handle -// which is later deleted. + // ericw -- OS X, SDL1: textures, VBO's invalid after mode change + // OS X, SDL2: still valid after mode change + // To handle both cases, delete all GL objects (textures, VBO, GLSL) now. + // We must not interleave deleting the old objects with creating new ones, because + // one of the new objects could be given the same ID as an invalid handle + // which is later deleted. - TexMgr_DeleteTextureObjects (); - GLSLGamma_DeleteTexture (); - R_ScaleView_DeleteTexture (); - R_DeleteShaders (); - GL_DeleteBModelVertexBuffer (); - GLMesh_DeleteVertexBuffers (); + TexMgr_DeleteTextureObjects(); + GLSLGamma_DeleteTexture(); + R_ScaleView_DeleteTexture(); + R_DeleteShaders(); + GL_DeleteBModelVertexBuffer(); + GLMesh_DeleteVertexBuffers(); -// -// set new mode -// - VID_SetMode (width, height, refreshrate, bpp, fullscreen); + // + // set new mode + // + VID_SetMode(width, height, refreshrate, bpp, fullscreen); - GL_Init (); - TexMgr_ReloadImages (); - GL_BuildBModelVertexBuffer (); - GLMesh_LoadVertexBuffers (); - GL_SetupState (); - Fog_SetupState (); + GL_Init(); + TexMgr_ReloadImages(); + GL_BuildBModelVertexBuffer(); + GLMesh_LoadVertexBuffers(); + GL_SetupState(); + Fog_SetupState(); - //warpimages needs to be recalculated - TexMgr_RecalcWarpImageSize (); + //warpimages needs to be recalculated + TexMgr_RecalcWarpImageSize(); - //conwidth and conheight need to be recalculated - vid.conwidth = (scr_conwidth.value > 0) ? (int)scr_conwidth.value : (scr_conscale.value > 0) ? (int)(vid.width/scr_conscale.value) : vid.width; - vid.conwidth = CLAMP (320, vid.conwidth, vid.width); - vid.conwidth &= 0xFFFFFFF8; - vid.conheight = vid.conwidth * vid.height / vid.width; -// -// keep cvars in line with actual mode -// - VID_SyncCvars(); -// -// update mouse grab -// - if (key_dest == key_console || key_dest == key_menu) - { - if (modestate == MS_WINDOWED) - IN_Deactivate(true); - else if (modestate == MS_FULLSCREEN) - IN_Activate(); - } + //conwidth and conheight need to be recalculated + vid.conwidth = (scr_conwidth.value > 0) + ? (int) scr_conwidth.value + : (scr_conscale.value > 0) + ? (int) (vid.width / scr_conscale.value) + : vid.width; + vid.conwidth = CLAMP(320, vid.conwidth, vid.width); + vid.conwidth &= 0xFFFFFFF8; + vid.conheight = vid.conwidth * vid.height / vid.width; + // + // keep cvars in line with actual mode + // + VID_SyncCvars(); + // + // update mouse grab + // + if (key_dest == key_console || key_dest == key_menu) { + if (modestate == MS_WINDOWED) + IN_Deactivate(true); + else if (modestate == MS_FULLSCREEN) + IN_Activate(); + } } /* @@ -855,34 +838,32 @@ static void VID_Restart (void) VID_Test -- johnfitz -- like vid_restart, but asks for confirmation after switching modes ================ */ -static void VID_Test (void) -{ - int old_width, old_height, old_refreshrate, old_bpp, old_fullscreen; +static void VID_Test(void) { + int old_width, old_height, old_refreshrate, old_bpp, old_fullscreen; - if (vid_locked || !vid_changed) - return; -// -// now try the switch -// - old_width = VID_GetCurrentWidth(); - old_height = VID_GetCurrentHeight(); - old_refreshrate = VID_GetCurrentRefreshRate(); - old_bpp = VID_GetCurrentBPP(); - old_fullscreen = VID_GetFullscreen() ? true : false; + if (vid_locked || !vid_changed) + return; + // + // now try the switch + // + old_width = VID_GetCurrentWidth(); + old_height = VID_GetCurrentHeight(); + old_refreshrate = VID_GetCurrentRefreshRate(); + old_bpp = VID_GetCurrentBPP(); + old_fullscreen = VID_GetFullscreen() ? true : false; - VID_Restart (); + VID_Restart(); - //pop up confirmation dialoge - if (!SCR_ModalMessage("Would you like to keep this\nvideo mode? (y/n)\n", 5.0f)) - { - //revert cvars and mode - Cvar_SetValueQuick (&vid_width, old_width); - Cvar_SetValueQuick (&vid_height, old_height); - Cvar_SetValueQuick (&vid_refreshrate, old_refreshrate); - Cvar_SetValueQuick (&vid_bpp, old_bpp); - Cvar_SetQuick (&vid_fullscreen, old_fullscreen ? "1" : "0"); - VID_Restart (); - } + //pop up confirmation dialoge + if (!SCR_ModalMessage("Would you like to keep this\nvideo mode? (y/n)\n", 5.0f)) { + //revert cvars and mode + vid_width.set_value(old_width); + vid_height.set_value(old_height); + vid_refreshrate.set_value(old_refreshrate); + vid_bpp.set_value(old_bpp); + vid_fullscreen.set(old_fullscreen ? "1" : "0"); + VID_Restart(); + } } /* @@ -890,10 +871,9 @@ static void VID_Test (void) VID_Unlock -- johnfitz ================ */ -static void VID_Unlock (void) -{ - vid_locked = false; - VID_SyncCvars(); +static void VID_Unlock(void) { + vid_locked = false; + VID_SyncCvars(); } /* @@ -907,9 +887,8 @@ Used when changing gamedirs so the current settings override what was saved in the config.cfg. ================ */ -void VID_Lock (void) -{ - vid_locked = true; +void VID_Lock(void) { + vid_locked = true; } //============================================================================== @@ -923,32 +902,29 @@ void VID_Lock (void) GL_MakeNiceExtensionsList -- johnfitz =============== */ -static char *GL_MakeNiceExtensionsList (const char *in) -{ - char *copy, *token, *out; - int i, count; +static char *GL_MakeNiceExtensionsList(const char *in) { + char *copy, *token, *out; + int i, count; - if (!in) return Z_Strdup("(none)"); + if (!in) return Z_Strdup("(none)"); - //each space will be replaced by 4 chars, so count the spaces before we malloc - for (i = 0, count = 1; i < (int) strlen(in); i++) - { - if (in[i] == ' ') - count++; - } + //each space will be replaced by 4 chars, so count the spaces before we malloc + for (i = 0, count = 1; i < (int) strlen(in); i++) { + if (in[i] == ' ') + count++; + } - out = (char *) Z_Malloc (strlen(in) + count*3 + 1); //usually about 1-2k - out[0] = 0; + out = (char *) Z_Malloc(strlen(in) + count * 3 + 1); //usually about 1-2k + out[0] = 0; - copy = (char *) Z_Strdup(in); - for (token = strtok(copy, " "); token; token = strtok(NULL, " ")) - { - strcat(out, "\n "); - strcat(out, token); - } + copy = (char *) Z_Strdup(in); + for (token = strtok(copy, " "); token; token = strtok(NULL, " ")) { + strcat(out, "\n "); + strcat(out, token); + } - Z_Free (copy); - return out; + Z_Free(copy); + return out; } /* @@ -956,12 +932,11 @@ static char *GL_MakeNiceExtensionsList (const char *in) GL_Info_f -- johnfitz =============== */ -static void GL_Info_f (void) -{ - Con_SafePrintf ("GL_VENDOR: %s\n", gl_vendor); - Con_SafePrintf ("GL_RENDERER: %s\n", gl_renderer); - Con_SafePrintf ("GL_VERSION: %s\n", gl_version); - Con_Printf ("GL_EXTENSIONS: %s\n", gl_extensions_nice); +static void GL_Info_f(void) { + Con_SafePrintf("GL_VENDOR: %s\n", gl_vendor); + Con_SafePrintf("GL_RENDERER: %s\n", gl_renderer); + Con_SafePrintf("GL_VERSION: %s\n", gl_version); + Con_Printf("GL_EXTENSIONS: %s\n", gl_extensions_nice); } /* @@ -969,355 +944,300 @@ static void GL_Info_f (void) GL_CheckExtensions =============== */ -static qboolean GL_ParseExtensionList (const char *list, const char *name) -{ - const char *start; - const char *where, *terminator; +static qboolean GL_ParseExtensionList(const char *list, const char *name) { + const char *start; + const char *where, *terminator; - if (!list || !name || !*name) - return false; - if (strchr(name, ' ') != NULL) - return false; // extension names must not have spaces + if (!list || !name || !*name) + return false; + if (strchr(name, ' ') != NULL) + return false; // extension names must not have spaces - start = list; - while (1) { - where = strstr (start, name); - if (!where) - break; - terminator = where + strlen (name); - if (where == start || where[-1] == ' ') - if (*terminator == ' ' || *terminator == '\0') - return true; - start = terminator; - } - return false; + start = list; + while (1) { + where = strstr(start, name); + if (!where) + break; + terminator = where + strlen(name); + if (where == start || where[-1] == ' ') + if (*terminator == ' ' || *terminator == '\0') + return true; + start = terminator; + } + return false; } -static void GL_CheckExtensions (void) -{ - int swap_control; +static void GL_CheckExtensions(void) { + int swap_control; - // ARB_vertex_buffer_object - // - if (COM_CheckParm("-novbo")) - Con_Warning ("Vertex buffer objects disabled at command line\n"); - else if (gl_version_major < 1 || (gl_version_major == 1 && gl_version_minor < 5)) - Con_Warning ("OpenGL version < 1.5, skipping ARB_vertex_buffer_object check\n"); - else - { - GL_BindBufferFunc = (PFNGLBINDBUFFERARBPROC) SDL_GL_GetProcAddress("glBindBufferARB"); - GL_BufferDataFunc = (PFNGLBUFFERDATAARBPROC) SDL_GL_GetProcAddress("glBufferDataARB"); - GL_BufferSubDataFunc = (PFNGLBUFFERSUBDATAARBPROC) SDL_GL_GetProcAddress("glBufferSubDataARB"); - GL_DeleteBuffersFunc = (PFNGLDELETEBUFFERSARBPROC) SDL_GL_GetProcAddress("glDeleteBuffersARB"); - GL_GenBuffersFunc = (PFNGLGENBUFFERSARBPROC) SDL_GL_GetProcAddress("glGenBuffersARB"); - if (GL_BindBufferFunc && GL_BufferDataFunc && GL_BufferSubDataFunc && GL_DeleteBuffersFunc && GL_GenBuffersFunc) - { - Con_Printf("FOUND: ARB_vertex_buffer_object\n"); - gl_vbo_able = true; - } - else - { - Con_Warning ("ARB_vertex_buffer_object not available\n"); - } - } + // ARB_vertex_buffer_object + // + if (COM_CheckParm("-novbo")) + Con_Warning("Vertex buffer objects disabled at command line\n"); + else if (gl_version_major < 1 || (gl_version_major == 1 && gl_version_minor < 5)) + Con_Warning("OpenGL version < 1.5, skipping ARB_vertex_buffer_object check\n"); + else { + GL_BindBufferFunc = (PFNGLBINDBUFFERARBPROC) SDL_GL_GetProcAddress("glBindBufferARB"); + GL_BufferDataFunc = (PFNGLBUFFERDATAARBPROC) SDL_GL_GetProcAddress("glBufferDataARB"); + GL_BufferSubDataFunc = (PFNGLBUFFERSUBDATAARBPROC) SDL_GL_GetProcAddress("glBufferSubDataARB"); + GL_DeleteBuffersFunc = (PFNGLDELETEBUFFERSARBPROC) SDL_GL_GetProcAddress("glDeleteBuffersARB"); + GL_GenBuffersFunc = (PFNGLGENBUFFERSARBPROC) SDL_GL_GetProcAddress("glGenBuffersARB"); + if (GL_BindBufferFunc && GL_BufferDataFunc && GL_BufferSubDataFunc && GL_DeleteBuffersFunc && + GL_GenBuffersFunc) { + Con_Printf("FOUND: ARB_vertex_buffer_object\n"); + gl_vbo_able = true; + } else { + Con_Warning("ARB_vertex_buffer_object not available\n"); + } + } - // multitexture - // - if (COM_CheckParm("-nomtex")) - Con_Warning ("Mutitexture disabled at command line\n"); - else if (GL_ParseExtensionList(gl_extensions, "GL_ARB_multitexture")) - { - GL_MTexCoord2fFunc = (PFNGLMULTITEXCOORD2FARBPROC) SDL_GL_GetProcAddress("glMultiTexCoord2fARB"); - GL_SelectTextureFunc = (PFNGLACTIVETEXTUREARBPROC) SDL_GL_GetProcAddress("glActiveTextureARB"); - GL_ClientActiveTextureFunc = (PFNGLCLIENTACTIVETEXTUREARBPROC) SDL_GL_GetProcAddress("glClientActiveTextureARB"); - if (GL_MTexCoord2fFunc && GL_SelectTextureFunc && GL_ClientActiveTextureFunc) - { - Con_Printf("FOUND: ARB_multitexture\n"); - gl_mtexable = true; - - glGetIntegerv(GL_MAX_TEXTURE_UNITS, &gl_max_texture_units); - Con_Printf("GL_MAX_TEXTURE_UNITS: %d\n", (int)gl_max_texture_units); - } - else - { - Con_Warning ("Couldn't link to multitexture functions\n"); - } - } - else - { - Con_Warning ("multitexture not supported (extension not found)\n"); - } + // multitexture + // + if (COM_CheckParm("-nomtex")) + Con_Warning("Mutitexture disabled at command line\n"); + else if (GL_ParseExtensionList(gl_extensions, "GL_ARB_multitexture")) { + GL_MTexCoord2fFunc = (PFNGLMULTITEXCOORD2FARBPROC) SDL_GL_GetProcAddress("glMultiTexCoord2fARB"); + GL_SelectTextureFunc = (PFNGLACTIVETEXTUREARBPROC) SDL_GL_GetProcAddress("glActiveTextureARB"); + GL_ClientActiveTextureFunc = (PFNGLCLIENTACTIVETEXTUREARBPROC) + SDL_GL_GetProcAddress("glClientActiveTextureARB"); + if (GL_MTexCoord2fFunc && GL_SelectTextureFunc && GL_ClientActiveTextureFunc) { + Con_Printf("FOUND: ARB_multitexture\n"); + gl_mtexable = true; - // texture_env_combine - // - if (COM_CheckParm("-nocombine")) - Con_Warning ("texture_env_combine disabled at command line\n"); - else if (GL_ParseExtensionList(gl_extensions, "GL_ARB_texture_env_combine")) - { - Con_Printf("FOUND: ARB_texture_env_combine\n"); - gl_texture_env_combine = true; - } - else if (GL_ParseExtensionList(gl_extensions, "GL_EXT_texture_env_combine")) - { - Con_Printf("FOUND: EXT_texture_env_combine\n"); - gl_texture_env_combine = true; - } - else - { - Con_Warning ("texture_env_combine not supported\n"); - } + glGetIntegerv(GL_MAX_TEXTURE_UNITS, &gl_max_texture_units); + Con_Printf("GL_MAX_TEXTURE_UNITS: %d\n", (int) gl_max_texture_units); + } else { + Con_Warning("Couldn't link to multitexture functions\n"); + } + } else { + Con_Warning("multitexture not supported (extension not found)\n"); + } - // texture_env_add - // - if (COM_CheckParm("-noadd")) - Con_Warning ("texture_env_add disabled at command line\n"); - else if (GL_ParseExtensionList(gl_extensions, "GL_ARB_texture_env_add")) - { - Con_Printf("FOUND: ARB_texture_env_add\n"); - gl_texture_env_add = true; - } - else if (GL_ParseExtensionList(gl_extensions, "GL_EXT_texture_env_add")) - { - Con_Printf("FOUND: EXT_texture_env_add\n"); - gl_texture_env_add = true; - } - else - { - Con_Warning ("texture_env_add not supported\n"); - } + // texture_env_combine + // + if (COM_CheckParm("-nocombine")) + Con_Warning("texture_env_combine disabled at command line\n"); + else if (GL_ParseExtensionList(gl_extensions, "GL_ARB_texture_env_combine")) { + Con_Printf("FOUND: ARB_texture_env_combine\n"); + gl_texture_env_combine = true; + } else if (GL_ParseExtensionList(gl_extensions, "GL_EXT_texture_env_combine")) { + Con_Printf("FOUND: EXT_texture_env_combine\n"); + gl_texture_env_combine = true; + } else { + Con_Warning("texture_env_combine not supported\n"); + } - // swap control - // - if (!gl_swap_control) - { + // texture_env_add + // + if (COM_CheckParm("-noadd")) + Con_Warning("texture_env_add disabled at command line\n"); + else if (GL_ParseExtensionList(gl_extensions, "GL_ARB_texture_env_add")) { + Con_Printf("FOUND: ARB_texture_env_add\n"); + gl_texture_env_add = true; + } else if (GL_ParseExtensionList(gl_extensions, "GL_EXT_texture_env_add")) { + Con_Printf("FOUND: EXT_texture_env_add\n"); + gl_texture_env_add = true; + } else { + Con_Warning("texture_env_add not supported\n"); + } + + // swap control + // + if (!gl_swap_control) { #if defined(USE_SDL2) - Con_Warning ("vertical sync not supported (SDL_GL_SetSwapInterval failed)\n"); + Con_Warning("vertical sync not supported (SDL_GL_SetSwapInterval failed)\n"); #else - Con_Warning ("vertical sync not supported (SDL_GL_SetAttribute failed)\n"); + Con_Warning("vertical sync not supported (SDL_GL_SetAttribute failed)\n"); #endif - } + } #if defined(USE_SDL2) else if ((swap_control = SDL_GL_GetSwapInterval()) == -1) #else - else if (SDL_GL_GetAttribute(SDL_GL_SWAP_CONTROL, &swap_control) == -1) + else if (SDL_GL_GetAttribute(SDL_GL_SWAP_CONTROL, &swap_control) == -1) #endif - { - gl_swap_control = false; + { + gl_swap_control = false; #if defined(USE_SDL2) - Con_Warning ("vertical sync not supported (SDL_GL_GetSwapInterval failed)\n"); + Con_Warning("vertical sync not supported (SDL_GL_GetSwapInterval failed)\n"); #else - Con_Warning ("vertical sync not supported (SDL_GL_GetAttribute failed)\n"); + Con_Warning("vertical sync not supported (SDL_GL_GetAttribute failed)\n"); #endif - } - else if ((vid_vsync.value && swap_control != 1) || (!vid_vsync.value && swap_control != 0)) - { - gl_swap_control = false; - Con_Warning ("vertical sync not supported (swap_control doesn't match vid_vsync)\n"); - } - else - { + } else if ((vid_vsync.value && swap_control != 1) || (!vid_vsync.value && swap_control != 0)) { + gl_swap_control = false; + Con_Warning("vertical sync not supported (swap_control doesn't match vid_vsync)\n"); + } else { #if defined(USE_SDL2) - Con_Printf("FOUND: SDL_GL_SetSwapInterval\n"); + Con_Printf("FOUND: SDL_GL_SetSwapInterval\n"); #else - Con_Printf("FOUND: SDL_GL_SWAP_CONTROL\n"); + Con_Printf("FOUND: SDL_GL_SWAP_CONTROL\n"); #endif - } + } - // anisotropic filtering - // - if (GL_ParseExtensionList(gl_extensions, "GL_EXT_texture_filter_anisotropic")) - { - float test1,test2; - GLuint tex; + // anisotropic filtering + // + if (GL_ParseExtensionList(gl_extensions, "GL_EXT_texture_filter_anisotropic")) { + float test1, test2; + GLuint tex; - // test to make sure we really have control over it - // 1.0 and 2.0 should always be legal values - glGenTextures(1, &tex); - glBindTexture (GL_TEXTURE_2D, tex); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); - glGetTexParameterfv (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, &test1); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 2.0f); - glGetTexParameterfv (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, &test2); - glDeleteTextures(1, &tex); + // test to make sure we really have control over it + // 1.0 and 2.0 should always be legal values + glGenTextures(1, &tex); + glBindTexture(GL_TEXTURE_2D, tex); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); + glGetTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, &test1); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 2.0f); + glGetTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, &test2); + glDeleteTextures(1, &tex); - if (test1 == 1 && test2 == 2) - { - Con_Printf("FOUND: EXT_texture_filter_anisotropic\n"); - gl_anisotropy_able = true; - } - else - { - Con_Warning ("anisotropic filtering locked by driver. Current driver setting is %f\n", test1); - } + if (test1 == 1 && test2 == 2) { + Con_Printf("FOUND: EXT_texture_filter_anisotropic\n"); + gl_anisotropy_able = true; + } else { + Con_Warning("anisotropic filtering locked by driver. Current driver setting is %f\n", test1); + } - //get max value either way, so the menu and stuff know it - glGetFloatv (GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &gl_max_anisotropy); - if (gl_max_anisotropy < 2) - { - gl_anisotropy_able = false; - gl_max_anisotropy = 1; - Con_Warning ("anisotropic filtering broken: disabled\n"); - } - } - else - { - gl_max_anisotropy = 1; - Con_Warning ("texture_filter_anisotropic not supported\n"); - } + //get max value either way, so the menu and stuff know it + glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &gl_max_anisotropy); + if (gl_max_anisotropy < 2) { + gl_anisotropy_able = false; + gl_max_anisotropy = 1; + Con_Warning("anisotropic filtering broken: disabled\n"); + } + } else { + gl_max_anisotropy = 1; + Con_Warning("texture_filter_anisotropic not supported\n"); + } - // texture_non_power_of_two - // - if (COM_CheckParm("-notexturenpot")) - Con_Warning ("texture_non_power_of_two disabled at command line\n"); - else if (GL_ParseExtensionList(gl_extensions, "GL_ARB_texture_non_power_of_two")) - { - Con_Printf("FOUND: ARB_texture_non_power_of_two\n"); - gl_texture_NPOT = true; - } - else - { - Con_Warning ("texture_non_power_of_two not supported\n"); - } + // texture_non_power_of_two + // + if (COM_CheckParm("-notexturenpot")) + Con_Warning("texture_non_power_of_two disabled at command line\n"); + else if (GL_ParseExtensionList(gl_extensions, "GL_ARB_texture_non_power_of_two")) { + Con_Printf("FOUND: ARB_texture_non_power_of_two\n"); + gl_texture_NPOT = true; + } else { + Con_Warning("texture_non_power_of_two not supported\n"); + } - // GLSL - // - if (COM_CheckParm("-noglsl")) - Con_Warning ("GLSL disabled at command line\n"); - else if (gl_version_major >= 2) - { - GL_CreateShaderFunc = (QS_PFNGLCREATESHADERPROC) SDL_GL_GetProcAddress("glCreateShader"); - GL_DeleteShaderFunc = (QS_PFNGLDELETESHADERPROC) SDL_GL_GetProcAddress("glDeleteShader"); - GL_DeleteProgramFunc = (QS_PFNGLDELETEPROGRAMPROC) SDL_GL_GetProcAddress("glDeleteProgram"); - GL_ShaderSourceFunc = (QS_PFNGLSHADERSOURCEPROC) SDL_GL_GetProcAddress("glShaderSource"); - GL_CompileShaderFunc = (QS_PFNGLCOMPILESHADERPROC) SDL_GL_GetProcAddress("glCompileShader"); - GL_GetShaderivFunc = (QS_PFNGLGETSHADERIVPROC) SDL_GL_GetProcAddress("glGetShaderiv"); - GL_GetShaderInfoLogFunc = (QS_PFNGLGETSHADERINFOLOGPROC) SDL_GL_GetProcAddress("glGetShaderInfoLog"); - GL_GetProgramivFunc = (QS_PFNGLGETPROGRAMIVPROC) SDL_GL_GetProcAddress("glGetProgramiv"); - GL_GetProgramInfoLogFunc = (QS_PFNGLGETPROGRAMINFOLOGPROC) SDL_GL_GetProcAddress("glGetProgramInfoLog"); - GL_CreateProgramFunc = (QS_PFNGLCREATEPROGRAMPROC) SDL_GL_GetProcAddress("glCreateProgram"); - GL_AttachShaderFunc = (QS_PFNGLATTACHSHADERPROC) SDL_GL_GetProcAddress("glAttachShader"); - GL_LinkProgramFunc = (QS_PFNGLLINKPROGRAMPROC) SDL_GL_GetProcAddress("glLinkProgram"); - GL_BindAttribLocationFunc = (QS_PFNGLBINDATTRIBLOCATIONFUNC) SDL_GL_GetProcAddress("glBindAttribLocation"); - GL_UseProgramFunc = (QS_PFNGLUSEPROGRAMPROC) SDL_GL_GetProcAddress("glUseProgram"); - GL_GetAttribLocationFunc = (QS_PFNGLGETATTRIBLOCATIONPROC) SDL_GL_GetProcAddress("glGetAttribLocation"); - GL_VertexAttribPointerFunc = (QS_PFNGLVERTEXATTRIBPOINTERPROC) SDL_GL_GetProcAddress("glVertexAttribPointer"); - GL_EnableVertexAttribArrayFunc = (QS_PFNGLENABLEVERTEXATTRIBARRAYPROC) SDL_GL_GetProcAddress("glEnableVertexAttribArray"); - GL_DisableVertexAttribArrayFunc = (QS_PFNGLDISABLEVERTEXATTRIBARRAYPROC) SDL_GL_GetProcAddress("glDisableVertexAttribArray"); - GL_GetUniformLocationFunc = (QS_PFNGLGETUNIFORMLOCATIONPROC) SDL_GL_GetProcAddress("glGetUniformLocation"); - GL_Uniform1iFunc = (QS_PFNGLUNIFORM1IPROC) SDL_GL_GetProcAddress("glUniform1i"); - GL_Uniform1fFunc = (QS_PFNGLUNIFORM1FPROC) SDL_GL_GetProcAddress("glUniform1f"); - GL_Uniform3fFunc = (QS_PFNGLUNIFORM3FPROC) SDL_GL_GetProcAddress("glUniform3f"); - GL_Uniform4fFunc = (QS_PFNGLUNIFORM4FPROC) SDL_GL_GetProcAddress("glUniform4f"); + // GLSL + // + if (COM_CheckParm("-noglsl")) + Con_Warning("GLSL disabled at command line\n"); + else if (gl_version_major >= 2) { + GL_CreateShaderFunc = (QS_PFNGLCREATESHADERPROC) SDL_GL_GetProcAddress("glCreateShader"); + GL_DeleteShaderFunc = (QS_PFNGLDELETESHADERPROC) SDL_GL_GetProcAddress("glDeleteShader"); + GL_DeleteProgramFunc = (QS_PFNGLDELETEPROGRAMPROC) SDL_GL_GetProcAddress("glDeleteProgram"); + GL_ShaderSourceFunc = (QS_PFNGLSHADERSOURCEPROC) SDL_GL_GetProcAddress("glShaderSource"); + GL_CompileShaderFunc = (QS_PFNGLCOMPILESHADERPROC) SDL_GL_GetProcAddress("glCompileShader"); + GL_GetShaderivFunc = (QS_PFNGLGETSHADERIVPROC) SDL_GL_GetProcAddress("glGetShaderiv"); + GL_GetShaderInfoLogFunc = (QS_PFNGLGETSHADERINFOLOGPROC) SDL_GL_GetProcAddress("glGetShaderInfoLog"); + GL_GetProgramivFunc = (QS_PFNGLGETPROGRAMIVPROC) SDL_GL_GetProcAddress("glGetProgramiv"); + GL_GetProgramInfoLogFunc = (QS_PFNGLGETPROGRAMINFOLOGPROC) SDL_GL_GetProcAddress("glGetProgramInfoLog"); + GL_CreateProgramFunc = (QS_PFNGLCREATEPROGRAMPROC) SDL_GL_GetProcAddress("glCreateProgram"); + GL_AttachShaderFunc = (QS_PFNGLATTACHSHADERPROC) SDL_GL_GetProcAddress("glAttachShader"); + GL_LinkProgramFunc = (QS_PFNGLLINKPROGRAMPROC) SDL_GL_GetProcAddress("glLinkProgram"); + GL_BindAttribLocationFunc = (QS_PFNGLBINDATTRIBLOCATIONFUNC) SDL_GL_GetProcAddress("glBindAttribLocation"); + GL_UseProgramFunc = (QS_PFNGLUSEPROGRAMPROC) SDL_GL_GetProcAddress("glUseProgram"); + GL_GetAttribLocationFunc = (QS_PFNGLGETATTRIBLOCATIONPROC) SDL_GL_GetProcAddress("glGetAttribLocation"); + GL_VertexAttribPointerFunc = (QS_PFNGLVERTEXATTRIBPOINTERPROC) SDL_GL_GetProcAddress("glVertexAttribPointer"); + GL_EnableVertexAttribArrayFunc = (QS_PFNGLENABLEVERTEXATTRIBARRAYPROC) SDL_GL_GetProcAddress( + "glEnableVertexAttribArray"); + GL_DisableVertexAttribArrayFunc = (QS_PFNGLDISABLEVERTEXATTRIBARRAYPROC) SDL_GL_GetProcAddress( + "glDisableVertexAttribArray"); + GL_GetUniformLocationFunc = (QS_PFNGLGETUNIFORMLOCATIONPROC) SDL_GL_GetProcAddress("glGetUniformLocation"); + GL_Uniform1iFunc = (QS_PFNGLUNIFORM1IPROC) SDL_GL_GetProcAddress("glUniform1i"); + GL_Uniform1fFunc = (QS_PFNGLUNIFORM1FPROC) SDL_GL_GetProcAddress("glUniform1f"); + GL_Uniform3fFunc = (QS_PFNGLUNIFORM3FPROC) SDL_GL_GetProcAddress("glUniform3f"); + GL_Uniform4fFunc = (QS_PFNGLUNIFORM4FPROC) SDL_GL_GetProcAddress("glUniform4f"); - if (GL_CreateShaderFunc && - GL_DeleteShaderFunc && - GL_DeleteProgramFunc && - GL_ShaderSourceFunc && - GL_CompileShaderFunc && - GL_GetShaderivFunc && - GL_GetShaderInfoLogFunc && - GL_GetProgramivFunc && - GL_GetProgramInfoLogFunc && - GL_CreateProgramFunc && - GL_AttachShaderFunc && - GL_LinkProgramFunc && - GL_BindAttribLocationFunc && - GL_UseProgramFunc && - GL_GetAttribLocationFunc && - GL_VertexAttribPointerFunc && - GL_EnableVertexAttribArrayFunc && - GL_DisableVertexAttribArrayFunc && - GL_GetUniformLocationFunc && - GL_Uniform1iFunc && - GL_Uniform1fFunc && - GL_Uniform3fFunc && - GL_Uniform4fFunc) - { - Con_Printf("FOUND: GLSL\n"); - gl_glsl_able = true; - } - else - { - Con_Warning ("GLSL not available\n"); - } - } - else - { - Con_Warning ("OpenGL version < 2, GLSL not available\n"); - } - // GLSL gamma - // - if (COM_CheckParm("-noglslgamma")) - Con_Warning ("GLSL gamma disabled at command line\n"); - else if (gl_glsl_able) - { - gl_glsl_gamma_able = true; - Con_Printf("Enabled: GLSL gamma\n"); - } - else - { - Con_Warning ("GLSL gamma not available, using hardware gamma\n"); - } - // GLSL alias model rendering - // - if (COM_CheckParm("-noglslalias")) - Con_Warning ("GLSL alias model rendering disabled at command line\n"); - else if (gl_glsl_able && gl_vbo_able && gl_max_texture_units >= 3) - { - gl_glsl_alias_able = true; - Con_Printf("Enabled: GLSL alias model rendering\n"); - } - else - { - Con_Warning ("GLSL alias model rendering not available, using Fitz renderer\n"); - } + if (GL_CreateShaderFunc && + GL_DeleteShaderFunc && + GL_DeleteProgramFunc && + GL_ShaderSourceFunc && + GL_CompileShaderFunc && + GL_GetShaderivFunc && + GL_GetShaderInfoLogFunc && + GL_GetProgramivFunc && + GL_GetProgramInfoLogFunc && + GL_CreateProgramFunc && + GL_AttachShaderFunc && + GL_LinkProgramFunc && + GL_BindAttribLocationFunc && + GL_UseProgramFunc && + GL_GetAttribLocationFunc && + GL_VertexAttribPointerFunc && + GL_EnableVertexAttribArrayFunc && + GL_DisableVertexAttribArrayFunc && + GL_GetUniformLocationFunc && + GL_Uniform1iFunc && + GL_Uniform1fFunc && + GL_Uniform3fFunc && + GL_Uniform4fFunc) { + Con_Printf("FOUND: GLSL\n"); + gl_glsl_able = true; + } else { + Con_Warning("GLSL not available\n"); + } + } else { + Con_Warning("OpenGL version < 2, GLSL not available\n"); + } + // GLSL gamma + // + if (COM_CheckParm("-noglslgamma")) + Con_Warning("GLSL gamma disabled at command line\n"); + else if (gl_glsl_able) { + gl_glsl_gamma_able = true; + Con_Printf("Enabled: GLSL gamma\n"); + } else { + Con_Warning("GLSL gamma not available, using hardware gamma\n"); + } + // GLSL alias model rendering + // + if (COM_CheckParm("-noglslalias")) + Con_Warning("GLSL alias model rendering disabled at command line\n"); + else if (gl_glsl_able && gl_vbo_able && gl_max_texture_units >= 3) { + gl_glsl_alias_able = true; + Con_Printf("Enabled: GLSL alias model rendering\n"); + } else { + Con_Warning("GLSL alias model rendering not available, using Fitz renderer\n"); + } - // packed_pixels - // - if (COM_CheckParm("-nopackedpixels")) - Con_Warning ("EXT_packed_pixels disabled at command line\n"); - else if (gl_glsl_alias_able) - { - gl_packed_pixels = true; - Con_Printf("Enabled: EXT_packed_pixels\n"); - } - #if 0 /* Disabling for non-GLSL path, needs more surgery. */ - else if (GL_ParseExtensionList(gl_extensions, "GL_APPLE_packed_pixels")) - { - Con_Printf("FOUND: APPLE_packed_pixels\n"); - gl_packed_pixels = true; - } - else if (GL_ParseExtensionList(gl_extensions, "GL_EXT_packed_pixels")) - { - Con_Printf("FOUND: EXT_packed_pixels\n"); - gl_packed_pixels = true; - } - else - { - Con_Warning ("packed_pixels not supported\n"); - } - #endif + // packed_pixels + // + if (COM_CheckParm("-nopackedpixels")) + Con_Warning("EXT_packed_pixels disabled at command line\n"); + else if (gl_glsl_alias_able) { + gl_packed_pixels = true; + Con_Printf("Enabled: EXT_packed_pixels\n"); + } +#if 0 /* Disabling for non-GLSL path, needs more surgery. */ + else if (GL_ParseExtensionList(gl_extensions, "GL_APPLE_packed_pixels")) { + Con_Printf("FOUND: APPLE_packed_pixels\n"); + gl_packed_pixels = true; + } else if (GL_ParseExtensionList(gl_extensions, "GL_EXT_packed_pixels")) { + Con_Printf("FOUND: EXT_packed_pixels\n"); + gl_packed_pixels = true; + } else { + Con_Warning("packed_pixels not supported\n"); + } +#endif - // glGenerateMipmap for warp textures - if (COM_CheckParm("-nowarpmipmaps")) - Con_Warning ("glGenerateMipmap disabled at command line\n"); - else - { - if (gl_version_major >= 3 || GL_ParseExtensionList(gl_extensions, "GL_ARB_framebuffer_object")) - { - GL_GenerateMipmap = (QS_PFNGENERATEMIPMAP) SDL_GL_GetProcAddress("glGenerateMipmap"); - if (GL_GenerateMipmap != NULL) - Con_Printf ("FOUND: glGenerateMipmap\n"); - } - else if (GL_ParseExtensionList(gl_extensions, "GL_EXT_framebuffer_object")) - { - GL_GenerateMipmap = (QS_PFNGENERATEMIPMAP) SDL_GL_GetProcAddress("glGenerateMipmapEXT"); - if (GL_GenerateMipmap != NULL) - Con_Printf ("FOUND: glGenerateMipmapEXT\n"); - } - if (GL_GenerateMipmap == NULL) - Con_Warning ("glGenerateMipmap not available, liquids won't have mipmaps\n"); - } + // glGenerateMipmap for warp textures + if (COM_CheckParm("-nowarpmipmaps")) + Con_Warning("glGenerateMipmap disabled at command line\n"); + else { + if (gl_version_major >= 3 || GL_ParseExtensionList(gl_extensions, "GL_ARB_framebuffer_object")) { + GL_GenerateMipmap = (QS_PFNGENERATEMIPMAP) SDL_GL_GetProcAddress("glGenerateMipmap"); + if (GL_GenerateMipmap != NULL) + Con_Printf("FOUND: glGenerateMipmap\n"); + } else if (GL_ParseExtensionList(gl_extensions, "GL_EXT_framebuffer_object")) { + GL_GenerateMipmap = (QS_PFNGENERATEMIPMAP) SDL_GL_GetProcAddress("glGenerateMipmapEXT"); + if (GL_GenerateMipmap != NULL) + Con_Printf("FOUND: glGenerateMipmapEXT\n"); + } + if (GL_GenerateMipmap == NULL) + Con_Warning("glGenerateMipmap not available, liquids won't have mipmaps\n"); + } } /* @@ -1327,25 +1247,24 @@ GL_SetupState -- johnfitz does all the stuff from GL_Init that needs to be done every time a new GL render context is created =============== */ -static void GL_SetupState (void) -{ - glClearColor (0.15,0.15,0.15,0); //johnfitz -- originally 1,0,0,0 - glCullFace(GL_BACK); //johnfitz -- glquake used CCW with backwards culling -- let's do it right - glFrontFace(GL_CW); //johnfitz -- glquake used CCW with backwards culling -- let's do it right - glEnable(GL_TEXTURE_2D); - glEnable(GL_ALPHA_TEST); - glAlphaFunc(GL_GREATER, 0.666); - glPolygonMode (GL_FRONT_AND_BACK, GL_FILL); - glShadeModel (GL_FLAT); - glHint (GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); //johnfitz - glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - glDepthRange (0, 1); //johnfitz -- moved here becuase gl_ztrick is gone. - glDepthFunc (GL_LEQUAL); //johnfitz -- moved here becuase gl_ztrick is gone. +static void GL_SetupState(void) { + glClearColor(0.15, 0.15, 0.15, 0); //johnfitz -- originally 1,0,0,0 + glCullFace(GL_BACK); //johnfitz -- glquake used CCW with backwards culling -- let's do it right + glFrontFace(GL_CW); //johnfitz -- glquake used CCW with backwards culling -- let's do it right + glEnable(GL_TEXTURE_2D); + glEnable(GL_ALPHA_TEST); + glAlphaFunc(GL_GREATER, 0.666); + glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); + glShadeModel(GL_FLAT); + glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); //johnfitz + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glDepthRange(0, 1); //johnfitz -- moved here becuase gl_ztrick is gone. + glDepthFunc(GL_LEQUAL); //johnfitz -- moved here becuase gl_ztrick is gone. } /* @@ -1353,50 +1272,46 @@ static void GL_SetupState (void) GL_Init =============== */ -static void GL_Init (void) -{ - gl_vendor = (const char *) glGetString (GL_VENDOR); - gl_renderer = (const char *) glGetString (GL_RENDERER); - gl_version = (const char *) glGetString (GL_VERSION); - gl_extensions = (const char *) glGetString (GL_EXTENSIONS); +static void GL_Init(void) { + gl_vendor = (const char *) glGetString(GL_VENDOR); + gl_renderer = (const char *) glGetString(GL_RENDERER); + gl_version = (const char *) glGetString(GL_VERSION); + gl_extensions = (const char *) glGetString(GL_EXTENSIONS); - Con_SafePrintf ("GL_VENDOR: %s\n", gl_vendor); - Con_SafePrintf ("GL_RENDERER: %s\n", gl_renderer); - Con_SafePrintf ("GL_VERSION: %s\n", gl_version); - - if (gl_version == NULL || sscanf(gl_version, "%d.%d", &gl_version_major, &gl_version_minor) < 2) - { - gl_version_major = 0; - gl_version_minor = 0; - } + Con_SafePrintf("GL_VENDOR: %s\n", gl_vendor); + Con_SafePrintf("GL_RENDERER: %s\n", gl_renderer); + Con_SafePrintf("GL_VERSION: %s\n", gl_version); - if (gl_extensions_nice != NULL) - Z_Free (gl_extensions_nice); - gl_extensions_nice = GL_MakeNiceExtensionsList (gl_extensions); + if (gl_version == NULL || sscanf(gl_version, "%d.%d", &gl_version_major, &gl_version_minor) < 2) { + gl_version_major = 0; + gl_version_minor = 0; + } - GL_CheckExtensions (); //johnfitz + if (gl_extensions_nice != NULL) + Z_Free(gl_extensions_nice); + gl_extensions_nice = GL_MakeNiceExtensionsList(gl_extensions); + + GL_CheckExtensions(); //johnfitz #ifdef __APPLE__ - // ericw -- enable multi-threaded OpenGL, gives a decent FPS boost. - // https://developer.apple.com/library/mac/technotes/tn2085/ - if (host_parms->numcpus > 1 && - kCGLNoError != CGLEnable(CGLGetCurrentContext(), kCGLCEMPEngine)) - { - Con_Warning ("Couldn't enable multi-threaded OpenGL"); - } + // ericw -- enable multi-threaded OpenGL, gives a decent FPS boost. + // https://developer.apple.com/library/mac/technotes/tn2085/ + if (host_parms->numcpus > 1 && + kCGLNoError != CGLEnable(CGLGetCurrentContext(), kCGLCEMPEngine)) { + Con_Warning("Couldn't enable multi-threaded OpenGL"); + } #endif - //johnfitz -- intel video workarounds from Baker - if (!strcmp(gl_vendor, "Intel")) - { - Con_Printf ("Intel Display Adapter detected, enabling gl_clear\n"); - Cbuf_AddText ("gl_clear 1"); - } - //johnfitz + //johnfitz -- intel video workarounds from Baker + if (!strcmp(gl_vendor, "Intel")) { + Con_Printf("Intel Display Adapter detected, enabling gl_clear\n"); + Cbuf_AddText("gl_clear 1"); + } + //johnfitz - GLAlias_CreateShaders (); - GLWorld_CreateShaders (); - GL_ClearBufferBindings (); + GLAlias_CreateShaders(); + GLWorld_CreateShaders(); + GL_ClearBufferBindings(); } /* @@ -1404,11 +1319,10 @@ static void GL_Init (void) GL_BeginRendering -- sets values of glx, gly, glwidth, glheight ================= */ -void GL_BeginRendering (int *x, int *y, int *width, int *height) -{ - *x = *y = 0; - *width = vid.width; - *height = vid.height; +void GL_BeginRendering(int *x, int *y, int *width, int *height) { + *x = *y = 0; + *width = vid.width; + *height = vid.height; } /* @@ -1416,33 +1330,29 @@ void GL_BeginRendering (int *x, int *y, int *width, int *height) GL_EndRendering ================= */ -void GL_EndRendering (void) -{ - if (!scr_skipupdate) - { +void GL_EndRendering(void) { + if (!scr_skipupdate) { #if defined(USE_SDL2) - SDL_GL_SwapWindow(draw_context); + SDL_GL_SwapWindow(draw_context); #else - SDL_GL_SwapBuffers(); + SDL_GL_SwapBuffers(); #endif - } + } } -void VID_Shutdown (void) -{ - if (vid_initialized) - { - VID_Gamma_Shutdown (); //johnfitz +void VID_Shutdown(void) { + if (vid_initialized) { + VID_Gamma_Shutdown(); //johnfitz #if defined(USE_SDL2) - SDL_GL_DeleteContext(gl_context); - gl_context = NULL; - SDL_DestroyWindow(draw_context); + SDL_GL_DeleteContext(gl_context); + gl_context = NULL; + SDL_DestroyWindow(draw_context); #endif - SDL_QuitSubSystem(SDL_INIT_VIDEO); - draw_context = NULL; - PL_VID_Shutdown(); - } + SDL_QuitSubSystem(SDL_INIT_VIDEO); + draw_context = NULL; + PL_VID_Shutdown(); + } } /* @@ -1458,10 +1368,9 @@ MAIN WINDOW ClearAllStates ================ */ -static void ClearAllStates (void) -{ - Key_ClearStates (); - IN_ClearStates (); +static void ClearAllStates(void) { + Key_ClearStates(); + IN_ClearStates(); } @@ -1476,15 +1385,14 @@ static void ClearAllStates (void) VID_DescribeCurrentMode_f ================= */ -static void VID_DescribeCurrentMode_f (void) -{ - if (draw_context) - Con_Printf("%dx%dx%d %dHz %s\n", - VID_GetCurrentWidth(), - VID_GetCurrentHeight(), - VID_GetCurrentBPP(), - VID_GetCurrentRefreshRate(), - VID_GetFullscreen() ? "fullscreen" : "windowed"); +static void VID_DescribeCurrentMode_f(void) { + if (draw_context) + Con_Printf("%dx%dx%d %dHz %s\n", + VID_GetCurrentWidth(), + VID_GetCurrentHeight(), + VID_GetCurrentBPP(), + VID_GetCurrentRefreshRate(), + VID_GetFullscreen() ? "fullscreen" : "windowed"); } /* @@ -1492,27 +1400,25 @@ static void VID_DescribeCurrentMode_f (void) VID_DescribeModes_f -- johnfitz -- changed formatting, and added refresh rates after each mode. ================= */ -static void VID_DescribeModes_f (void) -{ - int i; - int lastwidth, lastheight, lastbpp, count; +static void VID_DescribeModes_f(void) { + int i; + int lastwidth, lastheight, lastbpp, count; - lastwidth = lastheight = lastbpp = count = 0; + lastwidth = lastheight = lastbpp = count = 0; - for (i = 0; i < nummodes; i++) - { - if (lastwidth != modelist[i].width || lastheight != modelist[i].height || lastbpp != modelist[i].bpp) - { - if (count > 0) - Con_SafePrintf ("\n"); - Con_SafePrintf (" %4i x %4i x %i : %i", modelist[i].width, modelist[i].height, modelist[i].bpp, modelist[i].refreshrate); - lastwidth = modelist[i].width; - lastheight = modelist[i].height; - lastbpp = modelist[i].bpp; - count++; - } - } - Con_Printf ("\n%i modes\n", count); + for (i = 0; i < nummodes; i++) { + if (lastwidth != modelist[i].width || lastheight != modelist[i].height || lastbpp != modelist[i].bpp) { + if (count > 0) + Con_SafePrintf("\n"); + Con_SafePrintf(" %4i x %4i x %i : %i", modelist[i].width, modelist[i].height, modelist[i].bpp, + modelist[i].refreshrate); + lastwidth = modelist[i].width; + lastheight = modelist[i].height; + lastbpp = modelist[i].bpp; + count++; + } + } + Con_Printf("\n%i modes\n", count); } /* @@ -1520,11 +1426,10 @@ static void VID_DescribeModes_f (void) VID_FSAA_f -- ericw -- warn that vid_fsaa requires engine restart =================== */ -static void VID_FSAA_f (cvar_t *var) -{ - // don't print the warning if vid_fsaa is set during startup - if (vid_initialized) - Con_Printf("%s %d requires engine restart to take effect\n", var->name, (int)var->value); +static void VID_FSAA_f(convar *var) { + // don't print the warning if vid_fsaa is set during startup + if (vid_initialized) + Con_Printf("%s %d requires engine restart to take effect\n", var->name.c_str(), (int) var->value); } //========================================================================== @@ -1538,81 +1443,73 @@ static void VID_FSAA_f (cvar_t *var) VID_InitModelist ================= */ -static void VID_InitModelist (void) -{ +static void VID_InitModelist(void) { #if defined(USE_SDL2) - const int sdlmodes = SDL_GetNumDisplayModes(0); - int i; + const int sdlmodes = SDL_GetNumDisplayModes(0); + int i; - nummodes = 0; - for (i = 0; i < sdlmodes; i++) - { - SDL_DisplayMode mode; + nummodes = 0; + for (i = 0; i < sdlmodes; i++) { + SDL_DisplayMode mode; - if (nummodes >= MAX_MODE_LIST) - break; - if (SDL_GetDisplayMode(0, i, &mode) == 0) - { - modelist[nummodes].width = mode.w; - modelist[nummodes].height = mode.h; - modelist[nummodes].bpp = SDL_BITSPERPIXEL(mode.format); - modelist[nummodes].refreshrate = mode.refresh_rate; - nummodes++; - } - } + if (nummodes >= MAX_MODE_LIST) + break; + if (SDL_GetDisplayMode(0, i, &mode) == 0) { + modelist[nummodes].width = mode.w; + modelist[nummodes].height = mode.h; + modelist[nummodes].bpp = SDL_BITSPERPIXEL(mode.format); + modelist[nummodes].refreshrate = mode.refresh_rate; + nummodes++; + } + } #else /* !defined(USE_SDL2) */ - SDL_PixelFormat format; - SDL_Rect **modes; - Uint32 flags; - int i, j, k, originalnummodes, existingmode; - int bpps[] = {16, 24, 32}; // enumerate >8 bpp modes + SDL_PixelFormat format; + SDL_Rect **modes; + Uint32 flags; + int i, j, k, originalnummodes, existingmode; + int bpps[] = {16, 24, 32}; // enumerate >8 bpp modes - originalnummodes = nummodes = 0; - memset(&format, 0, sizeof(format)); + originalnummodes = nummodes = 0; + memset(&format, 0, sizeof(format)); - // enumerate fullscreen modes - flags = DEFAULT_SDL_FLAGS | SDL_FULLSCREEN; - for (i = 0; i < (int)Q_COUNTOF(bpps); i++) - { - if (nummodes >= MAX_MODE_LIST) - break; + // enumerate fullscreen modes + flags = DEFAULT_SDL_FLAGS | SDL_FULLSCREEN; + for (i = 0; i < (int) Q_COUNTOF(bpps); i++) { + if (nummodes >= MAX_MODE_LIST) + break; - format.BitsPerPixel = bpps[i]; - modes = SDL_ListModes(&format, flags); + format.BitsPerPixel = bpps[i]; + modes = SDL_ListModes(&format, flags); - if (modes == (SDL_Rect **)0 || modes == (SDL_Rect **)-1) - continue; + if (modes == (SDL_Rect **) 0 || modes == (SDL_Rect **) -1) + continue; - for (j = 0; modes[j]; j++) - { - if (modes[j]->w > MAXWIDTH || modes[j]->h > MAXHEIGHT || nummodes >= MAX_MODE_LIST) - continue; + for (j = 0; modes[j]; j++) { + if (modes[j]->w > MAXWIDTH || modes[j]->h > MAXHEIGHT || nummodes >= MAX_MODE_LIST) + continue; - modelist[nummodes].width = modes[j]->w; - modelist[nummodes].height = modes[j]->h; - modelist[nummodes].bpp = bpps[i]; - modelist[nummodes].refreshrate = DEFAULT_REFRESHRATE; + modelist[nummodes].width = modes[j]->w; + modelist[nummodes].height = modes[j]->h; + modelist[nummodes].bpp = bpps[i]; + modelist[nummodes].refreshrate = DEFAULT_REFRESHRATE; - for (k=originalnummodes, existingmode = 0 ; k < nummodes ; k++) - { - if ((modelist[nummodes].width == modelist[k].width) && - (modelist[nummodes].height == modelist[k].height) && - (modelist[nummodes].bpp == modelist[k].bpp)) - { - existingmode = 1; - break; - } - } + for (k = originalnummodes, existingmode = 0; k < nummodes; k++) { + if ((modelist[nummodes].width == modelist[k].width) && + (modelist[nummodes].height == modelist[k].height) && + (modelist[nummodes].bpp == modelist[k].bpp)) { + existingmode = 1; + break; + } + } - if (!existingmode) - { - nummodes++; - } - } - } + if (!existingmode) { + nummodes++; + } + } + } - if (nummodes == originalnummodes) - Con_SafePrintf ("No fullscreen DIB modes found\n"); + if (nummodes == originalnummodes) + Con_SafePrintf("No fullscreen DIB modes found\n"); #endif /* !defined(USE_SDL2) */ } @@ -1621,259 +1518,246 @@ static void VID_InitModelist (void) VID_Init =================== */ -void VID_Init (void) -{ - static char vid_center[] = "SDL_VIDEO_CENTERED=center"; - int p, width, height, refreshrate, bpp; - int display_width, display_height, display_refreshrate, display_bpp; - qboolean fullscreen; - const char *read_vars[] = { "vid_fullscreen", - "vid_width", - "vid_height", - "vid_refreshrate", - "vid_bpp", - "vid_vsync", - "vid_fsaa", - "vid_desktopfullscreen", - "vid_borderless"}; +void VID_Init(void) { + static char vid_center[] = "SDL_VIDEO_CENTERED=center"; + int p, width, height, refreshrate, bpp; + int display_width, display_height, display_refreshrate, display_bpp; + qboolean fullscreen; + const char *read_vars[] = { + "vid_fullscreen", + "vid_width", + "vid_height", + "vid_refreshrate", + "vid_bpp", + "vid_vsync", + "vid_fsaa", + "vid_desktopfullscreen", + "vid_borderless" + }; #define num_readvars Q_COUNTOF(read_vars) - Cvar_RegisterVariable (&vid_fullscreen); //johnfitz - Cvar_RegisterVariable (&vid_width); //johnfitz - Cvar_RegisterVariable (&vid_height); //johnfitz - Cvar_RegisterVariable (&vid_refreshrate); //johnfitz - Cvar_RegisterVariable (&vid_bpp); //johnfitz - Cvar_RegisterVariable (&vid_vsync); //johnfitz - Cvar_RegisterVariable (&vid_fsaa); //QuakeSpasm - Cvar_RegisterVariable (&vid_desktopfullscreen); //QuakeSpasm - Cvar_RegisterVariable (&vid_borderless); //QuakeSpasm - Cvar_SetCallback (&vid_fullscreen, VID_Changed_f); - Cvar_SetCallback (&vid_width, VID_Changed_f); - Cvar_SetCallback (&vid_height, VID_Changed_f); - Cvar_SetCallback (&vid_refreshrate, VID_Changed_f); - Cvar_SetCallback (&vid_bpp, VID_Changed_f); - Cvar_SetCallback (&vid_vsync, VID_Changed_f); - Cvar_SetCallback (&vid_fsaa, VID_FSAA_f); - Cvar_SetCallback (&vid_desktopfullscreen, VID_Changed_f); - Cvar_SetCallback (&vid_borderless, VID_Changed_f); + vid_fullscreen.inscribe(); //johnfitz + vid_width.inscribe(); //johnfitz + vid_height.inscribe(); //johnfitz + vid_refreshrate.inscribe(); //johnfitz + vid_bpp.inscribe(); //johnfitz + vid_vsync.inscribe(); //johnfitz + vid_fsaa.inscribe(); //QuakeSpasm + vid_desktopfullscreen.inscribe(); //QuakeSpasm + vid_borderless.inscribe(); //QuakeSpasm + vid_fullscreen.set_callback(VID_Changed_f); + vid_width.set_callback(VID_Changed_f); + vid_height.set_callback(VID_Changed_f); + vid_refreshrate.set_callback(VID_Changed_f); + vid_bpp.set_callback(VID_Changed_f); + vid_vsync.set_callback(VID_Changed_f); + vid_fsaa.set_callback(VID_FSAA_f); + vid_desktopfullscreen.set_callback(VID_Changed_f); + vid_borderless.set_callback(VID_Changed_f); - Cmd_AddCommand ("vid_unlock", VID_Unlock); //johnfitz - Cmd_AddCommand ("vid_restart", VID_Restart); //johnfitz - Cmd_AddCommand ("vid_test", VID_Test); //johnfitz - Cmd_AddCommand ("vid_describecurrentmode", VID_DescribeCurrentMode_f); - Cmd_AddCommand ("vid_describemodes", VID_DescribeModes_f); + command::add("vid_unlock", VID_Unlock); //johnfitz + command::add("vid_restart", VID_Restart); //johnfitz + command::add("vid_test", VID_Test); //johnfitz + command::add("vid_describecurrentmode", VID_DescribeCurrentMode_f); + command::add("vid_describemodes", VID_DescribeModes_f); - putenv (vid_center); /* SDL_putenv is problematic in versions <= 1.2.9 */ + putenv(vid_center); /* SDL_putenv is problematic in versions <= 1.2.9 */ - if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) - Sys_Error("Couldn't init SDL video: %s", SDL_GetError()); + if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) + Sys_Error("Couldn't init SDL video: %s", SDL_GetError()); #if defined(USE_SDL2) - { - SDL_DisplayMode mode; - if (SDL_GetDesktopDisplayMode(0, &mode) != 0) - Sys_Error("Could not get desktop display mode"); + { + SDL_DisplayMode mode; + if (SDL_GetDesktopDisplayMode(0, &mode) != 0) + Sys_Error("Could not get desktop display mode"); - display_width = mode.w; - display_height = mode.h; - display_refreshrate = mode.refresh_rate; - display_bpp = SDL_BITSPERPIXEL(mode.format); - } + display_width = mode.w; + display_height = mode.h; + display_refreshrate = mode.refresh_rate; + display_bpp = SDL_BITSPERPIXEL(mode.format); + } #else - { - const SDL_VideoInfo *info = SDL_GetVideoInfo(); - display_width = info->current_w; - display_height = info->current_h; - display_refreshrate = DEFAULT_REFRESHRATE; - display_bpp = info->vfmt->BitsPerPixel; - } + { + const SDL_VideoInfo *info = SDL_GetVideoInfo(); + display_width = info->current_w; + display_height = info->current_h; + display_refreshrate = DEFAULT_REFRESHRATE; + display_bpp = info->vfmt->BitsPerPixel; + } #endif - Cvar_SetValueQuick (&vid_bpp, (float)display_bpp); + vid_bpp.set_value((float) display_bpp); - if (CFG_OpenConfig("config.cfg") == 0) - { - CFG_ReadCvars(read_vars, num_readvars); - CFG_CloseConfig(); - } - CFG_ReadCvarOverrides(read_vars, num_readvars); + if (CFG_OpenConfig("config.cfg") == 0) { + CFG_ReadCvars(read_vars, num_readvars); + CFG_CloseConfig(); + } + CFG_ReadCvarOverrides(read_vars, num_readvars); - VID_InitModelist(); + VID_InitModelist(); - width = (int)vid_width.value; - height = (int)vid_height.value; - refreshrate = (int)vid_refreshrate.value; - bpp = (int)vid_bpp.value; - fullscreen = (int)vid_fullscreen.value; - fsaa = (int)vid_fsaa.value; + width = (int) vid_width.value; + height = (int) vid_height.value; + refreshrate = (int) vid_refreshrate.value; + bpp = (int) vid_bpp.value; + fullscreen = (int) vid_fullscreen.value; + fsaa = (int) vid_fsaa.value; - if (COM_CheckParm("-current")) - { - width = display_width; - height = display_height; - refreshrate = display_refreshrate; - bpp = display_bpp; - fullscreen = true; - } - else - { - p = COM_CheckParm("-width"); - if (p && p < com_argc-1) - { - width = Q_atoi(com_argv[p+1]); + if (COM_CheckParm("-current")) { + width = display_width; + height = display_height; + refreshrate = display_refreshrate; + bpp = display_bpp; + fullscreen = true; + } else { + p = COM_CheckParm("-width"); + if (p && p < com_argc - 1) { + width = Q_atoi(com_argv[p + 1]); - if(!COM_CheckParm("-height")) - height = width * 3 / 4; - } + if (!COM_CheckParm("-height")) + height = width * 3 / 4; + } - p = COM_CheckParm("-height"); - if (p && p < com_argc-1) - { - height = Q_atoi(com_argv[p+1]); + p = COM_CheckParm("-height"); + if (p && p < com_argc - 1) { + height = Q_atoi(com_argv[p + 1]); - if(!COM_CheckParm("-width")) - width = height * 4 / 3; - } + if (!COM_CheckParm("-width")) + width = height * 4 / 3; + } - p = COM_CheckParm("-refreshrate"); - if (p && p < com_argc-1) - refreshrate = Q_atoi(com_argv[p+1]); + p = COM_CheckParm("-refreshrate"); + if (p && p < com_argc - 1) + refreshrate = Q_atoi(com_argv[p + 1]); - p = COM_CheckParm("-bpp"); - if (p && p < com_argc-1) - bpp = Q_atoi(com_argv[p+1]); + p = COM_CheckParm("-bpp"); + if (p && p < com_argc - 1) + bpp = Q_atoi(com_argv[p + 1]); - if (COM_CheckParm("-window") || COM_CheckParm("-w")) - fullscreen = false; - else if (COM_CheckParm("-fullscreen") || COM_CheckParm("-f")) - fullscreen = true; - } + if (COM_CheckParm("-window") || COM_CheckParm("-w")) + fullscreen = false; + else if (COM_CheckParm("-fullscreen") || COM_CheckParm("-f")) + fullscreen = true; + } - p = COM_CheckParm ("-fsaa"); - if (p && p < com_argc-1) - fsaa = atoi(com_argv[p+1]); + p = COM_CheckParm("-fsaa"); + if (p && p < com_argc - 1) + fsaa = atoi(com_argv[p + 1]); - if (!VID_ValidMode(width, height, refreshrate, bpp, fullscreen)) - { - width = (int)vid_width.value; - height = (int)vid_height.value; - refreshrate = (int)vid_refreshrate.value; - bpp = (int)vid_bpp.value; - fullscreen = (int)vid_fullscreen.value; - } + if (!VID_ValidMode(width, height, refreshrate, bpp, fullscreen)) { + width = (int) vid_width.value; + height = (int) vid_height.value; + refreshrate = (int) vid_refreshrate.value; + bpp = (int) vid_bpp.value; + fullscreen = (int) vid_fullscreen.value; + } - if (!VID_ValidMode(width, height, refreshrate, bpp, fullscreen)) - { - width = 640; - height = 480; - refreshrate = display_refreshrate; - bpp = display_bpp; - fullscreen = false; - } + if (!VID_ValidMode(width, height, refreshrate, bpp, fullscreen)) { + width = 640; + height = 480; + refreshrate = display_refreshrate; + bpp = display_bpp; + fullscreen = false; + } - vid_initialized = true; + vid_initialized = true; - vid.maxwarpwidth = WARP_WIDTH; - vid.maxwarpheight = WARP_HEIGHT; - vid.colormap = host_colormap; - vid.fullbright = 256 - LittleLong (*((int *)vid.colormap + 2048)); + vid.maxwarpwidth = WARP_WIDTH; + vid.maxwarpheight = WARP_HEIGHT; + vid.colormap = host_colormap; + vid.fullbright = 256 - LittleLong(*((int *) vid.colormap + 2048)); #if !defined(USE_SDL2) - // set window icon - PL_SetWindowIcon(); + // set window icon + PL_SetWindowIcon(); #endif - VID_SetMode (width, height, refreshrate, bpp, fullscreen); + VID_SetMode(width, height, refreshrate, bpp, fullscreen); #if defined(USE_SDL2) - // set window icon - PL_SetWindowIcon(); + // set window icon + PL_SetWindowIcon(); #endif - GL_Init (); - GL_SetupState (); - Cmd_AddCommand ("gl_info", GL_Info_f); //johnfitz + GL_Init(); + GL_SetupState(); + command::add("gl_info", GL_Info_f); //johnfitz - //johnfitz -- removed code creating "glquake" subdirectory + //johnfitz -- removed code creating "glquake" subdirectory - vid_menucmdfn = VID_Menu_f; //johnfitz - vid_menudrawfn = VID_MenuDraw; - vid_menukeyfn = VID_MenuKey; + vid_menucmdfn = VID_Menu_f; //johnfitz + vid_menudrawfn = VID_MenuDraw; + vid_menukeyfn = VID_MenuKey; - VID_Gamma_Init(); //johnfitz - VID_Menu_Init(); //johnfitz + VID_Gamma_Init(); //johnfitz + VID_Menu_Init(); //johnfitz - //QuakeSpasm: current vid settings should override config file settings. - //so we have to lock the vid mode from now until after all config files are read. - vid_locked = true; + //QuakeSpasm: current vid settings should override config file settings. + //so we have to lock the vid mode from now until after all config files are read. + vid_locked = true; } // new proc by S.A., called by alt-return key binding. -void VID_Toggle (void) -{ - // disabling the fast path completely because SDL_SetWindowFullscreen was changing - // the window size on SDL2/WinXP and we weren't set up to handle it. --ericw - // - // TODO: Clear out the dead code, reinstate the fast path using SDL_SetWindowFullscreen - // inside VID_SetMode, check window size to fix WinXP issue. This will - // keep all the mode changing code in one place. - static qboolean vid_toggle_works = false; - qboolean toggleWorked; +void VID_Toggle(void) { + // disabling the fast path completely because SDL_SetWindowFullscreen was changing + // the window size on SDL2/WinXP and we weren't set up to handle it. --ericw + // + // TODO: Clear out the dead code, reinstate the fast path using SDL_SetWindowFullscreen + // inside VID_SetMode, check window size to fix WinXP issue. This will + // keep all the mode changing code in one place. + static qboolean vid_toggle_works = false; + qboolean toggleWorked; #if defined(USE_SDL2) - Uint32 flags = 0; + Uint32 flags = 0; #endif - S_ClearBuffer (); + S_ClearBuffer(); - if (!vid_toggle_works) - goto vrestart; - else if (gl_vbo_able) - { - // disabling the fast path because with SDL 1.2 it invalidates VBOs (using them - // causes a crash, sugesting that the fullscreen toggle created a new GL context, - // although texture objects remain valid for some reason). - // - // SDL2 does promise window resizes / fullscreen changes preserve the GL context, - // so we could use the fast path with SDL2. --ericw - vid_toggle_works = false; - goto vrestart; - } + if (!vid_toggle_works) + goto vrestart; + else if (gl_vbo_able) { + // disabling the fast path because with SDL 1.2 it invalidates VBOs (using them + // causes a crash, sugesting that the fullscreen toggle created a new GL context, + // although texture objects remain valid for some reason). + // + // SDL2 does promise window resizes / fullscreen changes preserve the GL context, + // so we could use the fast path with SDL2. --ericw + vid_toggle_works = false; + goto vrestart; + } #if defined(USE_SDL2) - if (!VID_GetFullscreen()) { - flags = vid_desktopfullscreen.value ? SDL_WINDOW_FULLSCREEN_DESKTOP : SDL_WINDOW_FULLSCREEN; - } + if (!VID_GetFullscreen()) { + flags = vid_desktopfullscreen.value ? SDL_WINDOW_FULLSCREEN_DESKTOP : SDL_WINDOW_FULLSCREEN; + } - toggleWorked = SDL_SetWindowFullscreen(draw_context, flags) == 0; + toggleWorked = SDL_SetWindowFullscreen(draw_context, flags) == 0; #else - toggleWorked = SDL_WM_ToggleFullScreen(draw_context) == 1; + toggleWorked = SDL_WM_ToggleFullScreen(draw_context) == 1; #endif - if (toggleWorked) - { - Sbar_Changed (); // Sbar seems to need refreshing + if (toggleWorked) { + Sbar_Changed(); // Sbar seems to need refreshing - modestate = VID_GetFullscreen() ? MS_FULLSCREEN : MS_WINDOWED; + modestate = VID_GetFullscreen() ? MS_FULLSCREEN : MS_WINDOWED; - VID_SyncCvars(); + VID_SyncCvars(); - // update mouse grab - if (key_dest == key_console || key_dest == key_menu) - { - if (modestate == MS_WINDOWED) - IN_Deactivate(true); - else if (modestate == MS_FULLSCREEN) - IN_Activate(); - } - } - else - { - vid_toggle_works = false; - Con_DPrintf ("SDL_WM_ToggleFullScreen failed, attempting VID_Restart\n"); - vrestart: - Cvar_SetQuick (&vid_fullscreen, VID_GetFullscreen() ? "0" : "1"); - Cbuf_AddText ("vid_restart\n"); - } + // update mouse grab + if (key_dest == key_console || key_dest == key_menu) { + if (modestate == MS_WINDOWED) + IN_Deactivate(true); + else if (modestate == MS_FULLSCREEN) + IN_Activate(); + } + } else { + vid_toggle_works = false; + Con_DPrintf("SDL_WM_ToggleFullScreen failed, attempting VID_Restart\n"); + vrestart: + vid_fullscreen.set(VID_GetFullscreen() ? "0" : "1"); + Cbuf_AddText("vid_restart\n"); + } } /* @@ -1881,24 +1765,21 @@ void VID_Toggle (void) VID_SyncCvars -- johnfitz -- set vid cvars to match current video mode ================ */ -void VID_SyncCvars (void) -{ - if (draw_context) - { - if (!VID_GetDesktopFullscreen()) - { - Cvar_SetValueQuick (&vid_width, VID_GetCurrentWidth()); - Cvar_SetValueQuick (&vid_height, VID_GetCurrentHeight()); - } - Cvar_SetValueQuick (&vid_refreshrate, VID_GetCurrentRefreshRate()); - Cvar_SetValueQuick (&vid_bpp, VID_GetCurrentBPP()); - Cvar_SetQuick (&vid_fullscreen, VID_GetFullscreen() ? "1" : "0"); - // don't sync vid_desktopfullscreen, it's a user preference that - // should persist even if we are in windowed mode. - Cvar_SetQuick (&vid_vsync, VID_GetVSync() ? "1" : "0"); - } +void VID_SyncCvars(void) { + if (draw_context) { + if (!VID_GetDesktopFullscreen()) { + vid_width.set_value(VID_GetCurrentWidth()); + vid_height.set_value(VID_GetCurrentHeight()); + } + vid_refreshrate.set_value(VID_GetCurrentRefreshRate()); + vid_bpp.set_value(VID_GetCurrentBPP()); + vid_fullscreen.set(VID_GetFullscreen() ? "1" : "0"); + // don't sync vid_desktopfullscreen, it's a user preference that + // should persist even if we are in windowed mode. + vid_vsync.set(VID_GetVSync() ? "1" : "0"); + } - vid_changed = false; + vid_changed = false; } //========================================================================== @@ -1908,20 +1789,20 @@ void VID_SyncCvars (void) //========================================================================== enum { - VID_OPT_MODE, - VID_OPT_BPP, - VID_OPT_REFRESHRATE, - VID_OPT_FULLSCREEN, - VID_OPT_VSYNC, - VID_OPT_TEST, - VID_OPT_APPLY, - VIDEO_OPTIONS_ITEMS + VID_OPT_MODE, + VID_OPT_BPP, + VID_OPT_REFRESHRATE, + VID_OPT_FULLSCREEN, + VID_OPT_VSYNC, + VID_OPT_TEST, + VID_OPT_APPLY, + VIDEO_OPTIONS_ITEMS }; -static int video_options_cursor = 0; +static int video_options_cursor = 0; typedef struct { - int width,height; + int width, height; } vid_menu_mode; //TODO: replace these fixed-length arrays with hunk_allocated buffers @@ -1932,36 +1813,32 @@ static int vid_menu_bpps[MAX_BPPS_LIST]; static int vid_menu_numbpps = 0; static int vid_menu_rates[MAX_RATES_LIST]; -static int vid_menu_numrates=0; +static int vid_menu_numrates = 0; /* ================ VID_Menu_Init ================ */ -static void VID_Menu_Init (void) -{ - int i, j, h, w; +static void VID_Menu_Init(void) { + int i, j, h, w; - for (i = 0; i < nummodes; i++) - { - w = modelist[i].width; - h = modelist[i].height; + for (i = 0; i < nummodes; i++) { + w = modelist[i].width; + h = modelist[i].height; - for (j = 0; j < vid_menu_nummodes; j++) - { - if (vid_menu_modes[j].width == w && - vid_menu_modes[j].height == h) - break; - } + for (j = 0; j < vid_menu_nummodes; j++) { + if (vid_menu_modes[j].width == w && + vid_menu_modes[j].height == h) + break; + } - if (j == vid_menu_nummodes) - { - vid_menu_modes[j].width = w; - vid_menu_modes[j].height = h; - vid_menu_nummodes++; - } - } + if (j == vid_menu_nummodes) { + vid_menu_modes[j].width = w; + vid_menu_modes[j].height = h; + vid_menu_nummodes++; + } + } } /* @@ -1971,51 +1848,46 @@ VID_Menu_RebuildBppList regenerates bpp list based on current vid_width and vid_height ================ */ -static void VID_Menu_RebuildBppList (void) -{ - int i, j, b; +static void VID_Menu_RebuildBppList(void) { + int i, j, b; - vid_menu_numbpps = 0; + vid_menu_numbpps = 0; - for (i = 0; i < nummodes; i++) - { - if (vid_menu_numbpps >= MAX_BPPS_LIST) - break; + for (i = 0; i < nummodes; i++) { + if (vid_menu_numbpps >= MAX_BPPS_LIST) + break; - //bpp list is limited to bpps available with current width/height - if (modelist[i].width != vid_width.value || - modelist[i].height != vid_height.value) - continue; + //bpp list is limited to bpps available with current width/height + if (modelist[i].width != vid_width.value || + modelist[i].height != vid_height.value) + continue; - b = modelist[i].bpp; + b = modelist[i].bpp; - for (j = 0; j < vid_menu_numbpps; j++) - { - if (vid_menu_bpps[j] == b) - break; - } + for (j = 0; j < vid_menu_numbpps; j++) { + if (vid_menu_bpps[j] == b) + break; + } - if (j == vid_menu_numbpps) - { - vid_menu_bpps[j] = b; - vid_menu_numbpps++; - } - } + if (j == vid_menu_numbpps) { + vid_menu_bpps[j] = b; + vid_menu_numbpps++; + } + } - //if there are no valid fullscreen bpps for this width/height, just pick one - if (vid_menu_numbpps == 0) - { - Cvar_SetValueQuick (&vid_bpp, (float)modelist[0].bpp); - return; - } + //if there are no valid fullscreen bpps for this width/height, just pick one + if (vid_menu_numbpps == 0) { + vid_bpp.set_value((float) modelist[0].bpp); + return; + } - //if vid_bpp is not in the new list, change vid_bpp - for (i = 0; i < vid_menu_numbpps; i++) - if (vid_menu_bpps[i] == (int)(vid_bpp.value)) - break; + //if vid_bpp is not in the new list, change vid_bpp + for (i = 0; i < vid_menu_numbpps; i++) + if (vid_menu_bpps[i] == (int) (vid_bpp.value)) + break; - if (i == vid_menu_numbpps) - Cvar_SetValueQuick (&vid_bpp, (float)vid_menu_bpps[0]); + if (i == vid_menu_numbpps) + vid_bpp.set_value((float) vid_menu_bpps[0]); } /* @@ -2025,49 +1897,44 @@ VID_Menu_RebuildRateList regenerates rate list based on current vid_width, vid_height and vid_bpp ================ */ -static void VID_Menu_RebuildRateList (void) -{ - int i, j, r; +static void VID_Menu_RebuildRateList(void) { + int i, j, r; - vid_menu_numrates = 0; + vid_menu_numrates = 0; - for (i = 0; i < nummodes; i++) - { - //rate list is limited to rates available with current width/height/bpp - if (modelist[i].width != vid_width.value || - modelist[i].height != vid_height.value || - modelist[i].bpp != vid_bpp.value) - continue; + for (i = 0; i < nummodes; i++) { + //rate list is limited to rates available with current width/height/bpp + if (modelist[i].width != vid_width.value || + modelist[i].height != vid_height.value || + modelist[i].bpp != vid_bpp.value) + continue; - r = modelist[i].refreshrate; + r = modelist[i].refreshrate; - for (j = 0; j < vid_menu_numrates; j++) - { - if (vid_menu_rates[j] == r) - break; - } + for (j = 0; j < vid_menu_numrates; j++) { + if (vid_menu_rates[j] == r) + break; + } - if (j == vid_menu_numrates) - { - vid_menu_rates[j] = r; - vid_menu_numrates++; - } - } + if (j == vid_menu_numrates) { + vid_menu_rates[j] = r; + vid_menu_numrates++; + } + } - //if there are no valid fullscreen refreshrates for this width/height, just pick one - if (vid_menu_numrates == 0) - { - Cvar_SetValue ("vid_refreshrate",(float)modelist[0].refreshrate); - return; - } + //if there are no valid fullscreen refreshrates for this width/height, just pick one + if (vid_menu_numrates == 0) { + convar::set_value("vid_refreshrate", (float) modelist[0].refreshrate); + return; + } - //if vid_refreshrate is not in the new list, change vid_refreshrate - for (i = 0; i < vid_menu_numrates; i++) - if (vid_menu_rates[i] == (int)(vid_refreshrate.value)) - break; + //if vid_refreshrate is not in the new list, change vid_refreshrate + for (i = 0; i < vid_menu_numrates; i++) + if (vid_menu_rates[i] == (int) (vid_refreshrate.value)) + break; - if (i == vid_menu_numrates) - Cvar_SetValue ("vid_refreshrate",(float)vid_menu_rates[0]); + if (i == vid_menu_numrates) + convar::set_value("vid_refreshrate", (float) vid_menu_rates[0]); } /* @@ -2078,37 +1945,32 @@ chooses next resolution in order, then updates vid_width and vid_height cvars, then updates bpp and refreshrate lists ================ */ -static void VID_Menu_ChooseNextMode (int dir) -{ - int i; +static void VID_Menu_ChooseNextMode(int dir) { + int i; - if (vid_menu_nummodes) - { - for (i = 0; i < vid_menu_nummodes; i++) - { - if (vid_menu_modes[i].width == vid_width.value && - vid_menu_modes[i].height == vid_height.value) - break; - } + if (vid_menu_nummodes) { + for (i = 0; i < vid_menu_nummodes; i++) { + if (vid_menu_modes[i].width == vid_width.value && + vid_menu_modes[i].height == vid_height.value) + break; + } - if (i == vid_menu_nummodes) //can't find it in list, so it must be a custom windowed res - { - i = 0; - } - else - { - i += dir; - if (i >= vid_menu_nummodes) - i = 0; - else if (i < 0) - i = vid_menu_nummodes-1; - } + if (i == vid_menu_nummodes) //can't find it in list, so it must be a custom windowed res + { + i = 0; + } else { + i += dir; + if (i >= vid_menu_nummodes) + i = 0; + else if (i < 0) + i = vid_menu_nummodes - 1; + } - Cvar_SetValueQuick (&vid_width, (float)vid_menu_modes[i].width); - Cvar_SetValueQuick (&vid_height, (float)vid_menu_modes[i].height); - VID_Menu_RebuildBppList (); - VID_Menu_RebuildRateList (); - } + vid_width.set_value((float) vid_menu_modes[i].width); + vid_height.set_value((float) vid_menu_modes[i].height); + VID_Menu_RebuildBppList(); + VID_Menu_RebuildRateList(); + } } /* @@ -2118,33 +1980,28 @@ VID_Menu_ChooseNextBpp chooses next bpp in order, then updates vid_bpp cvar ================ */ -static void VID_Menu_ChooseNextBpp (int dir) -{ - int i; +static void VID_Menu_ChooseNextBpp(int dir) { + int i; - if (vid_menu_numbpps) - { - for (i = 0; i < vid_menu_numbpps; i++) - { - if (vid_menu_bpps[i] == vid_bpp.value) - break; - } + if (vid_menu_numbpps) { + for (i = 0; i < vid_menu_numbpps; i++) { + if (vid_menu_bpps[i] == vid_bpp.value) + break; + } - if (i == vid_menu_numbpps) //can't find it in list - { - i = 0; - } - else - { - i += dir; - if (i >= vid_menu_numbpps) - i = 0; - else if (i < 0) - i = vid_menu_numbpps-1; - } + if (i == vid_menu_numbpps) //can't find it in list + { + i = 0; + } else { + i += dir; + if (i >= vid_menu_numbpps) + i = 0; + else if (i < 0) + i = vid_menu_numbpps - 1; + } - Cvar_SetValueQuick (&vid_bpp, (float)vid_menu_bpps[i]); - } + vid_bpp.set_value((float) vid_menu_bpps[i]); + } } /* @@ -2154,30 +2011,26 @@ VID_Menu_ChooseNextRate chooses next refresh rate in order, then updates vid_refreshrate cvar ================ */ -static void VID_Menu_ChooseNextRate (int dir) -{ - int i; +static void VID_Menu_ChooseNextRate(int dir) { + int i; - for (i = 0; i < vid_menu_numrates; i++) - { - if (vid_menu_rates[i] == vid_refreshrate.value) - break; - } + for (i = 0; i < vid_menu_numrates; i++) { + if (vid_menu_rates[i] == vid_refreshrate.value) + break; + } - if (i == vid_menu_numrates) //can't find it in list - { - i = 0; - } - else - { - i += dir; - if (i >= vid_menu_numrates) - i = 0; - else if (i < 0) - i = vid_menu_numrates-1; - } + if (i == vid_menu_numrates) //can't find it in list + { + i = 0; + } else { + i += dir; + if (i >= vid_menu_numrates) + i = 0; + else if (i < 0) + i = vid_menu_numrates - 1; + } - Cvar_SetValue ("vid_refreshrate",(float)vid_menu_rates[i]); + convar::set_value("vid_refreshrate", (float) vid_menu_rates[i]); } /* @@ -2185,117 +2038,112 @@ static void VID_Menu_ChooseNextRate (int dir) VID_MenuKey ================ */ -static void VID_MenuKey (int key) -{ - switch (key) - { - case K_ESCAPE: - case K_BBUTTON: - VID_SyncCvars (); //sync cvars before leaving menu. FIXME: there are other ways to leave menu - S_LocalSound ("misc/menu1.wav"); - M_Menu_Options_f (); - break; +static void VID_MenuKey(int key) { + switch (key) { + case K_ESCAPE: + case K_BBUTTON: + VID_SyncCvars(); //sync cvars before leaving menu. FIXME: there are other ways to leave menu + S_LocalSound("misc/menu1.wav"); + M_Menu_Options_f(); + break; - case K_UPARROW: - S_LocalSound ("misc/menu1.wav"); - video_options_cursor--; - if (video_options_cursor < 0) - video_options_cursor = VIDEO_OPTIONS_ITEMS-1; - break; + case K_UPARROW: + S_LocalSound("misc/menu1.wav"); + video_options_cursor--; + if (video_options_cursor < 0) + video_options_cursor = VIDEO_OPTIONS_ITEMS - 1; + break; - case K_DOWNARROW: - S_LocalSound ("misc/menu1.wav"); - video_options_cursor++; - if (video_options_cursor >= VIDEO_OPTIONS_ITEMS) - video_options_cursor = 0; - break; + case K_DOWNARROW: + S_LocalSound("misc/menu1.wav"); + video_options_cursor++; + if (video_options_cursor >= VIDEO_OPTIONS_ITEMS) + video_options_cursor = 0; + break; - case K_LEFTARROW: - S_LocalSound ("misc/menu3.wav"); - switch (video_options_cursor) - { - case VID_OPT_MODE: - VID_Menu_ChooseNextMode (1); - break; - case VID_OPT_BPP: - VID_Menu_ChooseNextBpp (1); - break; - case VID_OPT_REFRESHRATE: - VID_Menu_ChooseNextRate (1); - break; - case VID_OPT_FULLSCREEN: - Cbuf_AddText ("toggle vid_fullscreen\n"); - break; - case VID_OPT_VSYNC: - Cbuf_AddText ("toggle vid_vsync\n"); // kristian - break; - default: - break; - } - break; + case K_LEFTARROW: + S_LocalSound("misc/menu3.wav"); + switch (video_options_cursor) { + case VID_OPT_MODE: + VID_Menu_ChooseNextMode(1); + break; + case VID_OPT_BPP: + VID_Menu_ChooseNextBpp(1); + break; + case VID_OPT_REFRESHRATE: + VID_Menu_ChooseNextRate(1); + break; + case VID_OPT_FULLSCREEN: + Cbuf_AddText("toggle vid_fullscreen\n"); + break; + case VID_OPT_VSYNC: + Cbuf_AddText("toggle vid_vsync\n"); // kristian + break; + default: + break; + } + break; - case K_RIGHTARROW: - S_LocalSound ("misc/menu3.wav"); - switch (video_options_cursor) - { - case VID_OPT_MODE: - VID_Menu_ChooseNextMode (-1); - break; - case VID_OPT_BPP: - VID_Menu_ChooseNextBpp (-1); - break; - case VID_OPT_REFRESHRATE: - VID_Menu_ChooseNextRate (-1); - break; - case VID_OPT_FULLSCREEN: - Cbuf_AddText ("toggle vid_fullscreen\n"); - break; - case VID_OPT_VSYNC: - Cbuf_AddText ("toggle vid_vsync\n"); - break; - default: - break; - } - break; + case K_RIGHTARROW: + S_LocalSound("misc/menu3.wav"); + switch (video_options_cursor) { + case VID_OPT_MODE: + VID_Menu_ChooseNextMode(-1); + break; + case VID_OPT_BPP: + VID_Menu_ChooseNextBpp(-1); + break; + case VID_OPT_REFRESHRATE: + VID_Menu_ChooseNextRate(-1); + break; + case VID_OPT_FULLSCREEN: + Cbuf_AddText("toggle vid_fullscreen\n"); + break; + case VID_OPT_VSYNC: + Cbuf_AddText("toggle vid_vsync\n"); + break; + default: + break; + } + break; - case K_ENTER: - case K_KP_ENTER: - case K_ABUTTON: - m_entersound = true; - switch (video_options_cursor) - { - case VID_OPT_MODE: - VID_Menu_ChooseNextMode (1); - break; - case VID_OPT_BPP: - VID_Menu_ChooseNextBpp (1); - break; - case VID_OPT_REFRESHRATE: - VID_Menu_ChooseNextRate (1); - break; - case VID_OPT_FULLSCREEN: - Cbuf_AddText ("toggle vid_fullscreen\n"); - break; - case VID_OPT_VSYNC: - Cbuf_AddText ("toggle vid_vsync\n"); - break; - case VID_OPT_TEST: - Cbuf_AddText ("vid_test\n"); - break; - case VID_OPT_APPLY: - Cbuf_AddText ("vid_restart\n"); - key_dest = key_game; - m_state = m_none; - IN_Activate(); - break; - default: - break; - } - break; + case K_ENTER: + case K_KP_ENTER: + case K_ABUTTON: + m_entersound = true; + switch (video_options_cursor) { + case VID_OPT_MODE: + VID_Menu_ChooseNextMode(1); + break; + case VID_OPT_BPP: + VID_Menu_ChooseNextBpp(1); + break; + case VID_OPT_REFRESHRATE: + VID_Menu_ChooseNextRate(1); + break; + case VID_OPT_FULLSCREEN: + Cbuf_AddText("toggle vid_fullscreen\n"); + break; + case VID_OPT_VSYNC: + Cbuf_AddText("toggle vid_vsync\n"); + break; + case VID_OPT_TEST: + Cbuf_AddText("vid_test\n"); + break; + case VID_OPT_APPLY: + Cbuf_AddText("vid_restart\n"); + key_dest = key_game; + m_state = m_none; + IN_Activate(); + break; + default: + break; + } + break; - default: - break; - } + default: + break; + } } /* @@ -2303,72 +2151,69 @@ static void VID_MenuKey (int key) VID_MenuDraw ================ */ -static void VID_MenuDraw (void) -{ - int i, y; - qpic_t *p; - const char *title; +static void VID_MenuDraw(void) { + int i, y; + qpic_t *p; + const char *title; - y = 4; + y = 4; - // plaque - p = Draw_CachePic ("gfx/qplaque.lmp"); - M_DrawTransPic (16, y, p); + // plaque + p = Draw_CachePic("gfx/qplaque.lmp"); + M_DrawTransPic(16, y, p); - //p = Draw_CachePic ("gfx/vidmodes.lmp"); - p = Draw_CachePic ("gfx/p_option.lmp"); - M_DrawPic ( (320-p->width)/2, y, p); + //p = Draw_CachePic ("gfx/vidmodes.lmp"); + p = Draw_CachePic("gfx/p_option.lmp"); + M_DrawPic((320 - p->width) / 2, y, p); - y += 28; + y += 28; - // title - title = "Video Options"; - M_PrintWhite ((320-8*strlen(title))/2, y, title); + // title + title = "Video Options"; + M_PrintWhite((320 - 8 * strlen(title)) / 2, y, title); - y += 16; + y += 16; - // options - for (i = 0; i < VIDEO_OPTIONS_ITEMS; i++) - { - switch (i) - { - case VID_OPT_MODE: - M_Print (16, y, " Video mode"); - M_Print (184, y, va("%ix%i", (int)vid_width.value, (int)vid_height.value)); - break; - case VID_OPT_BPP: - M_Print (16, y, " Color depth"); - M_Print (184, y, va("%i", (int)vid_bpp.value)); - break; - case VID_OPT_REFRESHRATE: - M_Print (16, y, " Refresh rate"); - M_Print (184, y, va("%i", (int)vid_refreshrate.value)); - break; - case VID_OPT_FULLSCREEN: - M_Print (16, y, " Fullscreen"); - M_DrawCheckbox (184, y, (int)vid_fullscreen.value); - break; - case VID_OPT_VSYNC: - M_Print (16, y, " Vertical sync"); - if (gl_swap_control) - M_DrawCheckbox (184, y, (int)vid_vsync.value); - else - M_Print (184, y, "N/A"); - break; - case VID_OPT_TEST: - y += 8; //separate the test and apply items - M_Print (16, y, " Test changes"); - break; - case VID_OPT_APPLY: - M_Print (16, y, " Apply changes"); - break; - } + // options + for (i = 0; i < VIDEO_OPTIONS_ITEMS; i++) { + switch (i) { + case VID_OPT_MODE: + M_Print(16, y, " Video mode"); + M_Print(184, y, va("%ix%i", (int) vid_width.value, (int) vid_height.value)); + break; + case VID_OPT_BPP: + M_Print(16, y, " Color depth"); + M_Print(184, y, va("%i", (int) vid_bpp.value)); + break; + case VID_OPT_REFRESHRATE: + M_Print(16, y, " Refresh rate"); + M_Print(184, y, va("%i", (int) vid_refreshrate.value)); + break; + case VID_OPT_FULLSCREEN: + M_Print(16, y, " Fullscreen"); + M_DrawCheckbox(184, y, (int) vid_fullscreen.value); + break; + case VID_OPT_VSYNC: + M_Print(16, y, " Vertical sync"); + if (gl_swap_control) + M_DrawCheckbox(184, y, (int) vid_vsync.value); + else + M_Print(184, y, "N/A"); + break; + case VID_OPT_TEST: + y += 8; //separate the test and apply items + M_Print(16, y, " Test changes"); + break; + case VID_OPT_APPLY: + M_Print(16, y, " Apply changes"); + break; + } - if (video_options_cursor == i) - M_DrawCharacter (168, y, 12+((int)(realtime*4)&1)); + if (video_options_cursor == i) + M_DrawCharacter(168, y, 12 + ((int) (realtime * 4) & 1)); - y += 8; - } + y += 8; + } } /* @@ -2376,17 +2221,16 @@ static void VID_MenuDraw (void) VID_Menu_f ================ */ -static void VID_Menu_f (void) -{ - IN_Deactivate(modestate == MS_WINDOWED); - key_dest = key_menu; - m_state = m_video; - m_entersound = true; +static void VID_Menu_f(void) { + IN_Deactivate(modestate == MS_WINDOWED); + key_dest = key_menu; + m_state = m_video; + m_entersound = true; - //set all the cvars to match the current mode when entering the menu - VID_SyncCvars (); + //set all the cvars to match the current mode when entering the menu + VID_SyncCvars(); - //set up bpp and rate lists based on current cvars - VID_Menu_RebuildBppList (); - VID_Menu_RebuildRateList (); + //set up bpp and rate lists based on current cvars + VID_Menu_RebuildBppList(); + VID_Menu_RebuildRateList(); } diff --git a/Quake/gl_warp.cpp b/Quake/gl_warp.cpp index 4ff327f..aa34be7 100644 --- a/Quake/gl_warp.cpp +++ b/Quake/gl_warp.cpp @@ -22,11 +22,11 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.hpp" -extern cvar_t r_drawflat; +extern convar r_drawflat; -cvar_t r_oldwater = {"r_oldwater", "0", CVAR_ARCHIVE}; -cvar_t r_waterquality = {"r_waterquality", "8", CVAR_NONE}; -cvar_t r_waterwarp = {"r_waterwarp", "1", CVAR_NONE}; +convar r_oldwater{"r_oldwater", "0", {.archive = true}}; +convar r_waterquality{"r_waterquality", "8"}; +convar r_waterwarp{"r_waterwarp", "1"}; int gl_warpimagesize; float load_subdivide_size; //johnfitz -- remember what subdivide_size value was when this map was loaded @@ -46,7 +46,7 @@ static const float turbsin[] = { static msurface_t *warpface; -cvar_t gl_subdivide_size = {"gl_subdivide_size", "128", CVAR_ARCHIVE}; +convar gl_subdivide_size{"gl_subdivide_size", "128", {.archive = true}}; static void BoundPoly (int numverts, float *verts, vec3_t mins, vec3_t maxs) { diff --git a/Quake/glquake.hpp b/Quake/glquake.hpp index 49f918d..ecfb3fc 100644 --- a/Quake/glquake.hpp +++ b/Quake/glquake.hpp @@ -125,38 +125,38 @@ extern refdef_t r_refdef; extern mleaf_t *r_viewleaf, *r_oldviewleaf; extern int d_lightstylevalue[256]; // 8.8 fraction of base light value -extern cvar_t r_norefresh; -extern cvar_t r_drawentities; -extern cvar_t r_drawworld; -extern cvar_t r_drawviewmodel; -extern cvar_t r_speeds; -extern cvar_t r_pos; -extern cvar_t r_waterwarp; -extern cvar_t r_fullbright; -extern cvar_t r_lightmap; -extern cvar_t r_lightmapwide; -extern cvar_t r_shadows; -extern cvar_t r_wateralpha; -extern cvar_t r_lavaalpha; -extern cvar_t r_telealpha; -extern cvar_t r_slimealpha; -extern cvar_t r_litwater; -extern cvar_t r_dynamic; -extern cvar_t r_novis; -extern cvar_t r_scale; +extern convar r_norefresh; +extern convar r_drawentities; +extern convar r_drawworld; +extern convar r_drawviewmodel; +extern convar r_speeds; +extern convar r_pos; +extern convar r_waterwarp; +extern convar r_fullbright; +extern convar r_lightmap; +extern convar r_lightmapwide; +extern convar r_shadows; +extern convar r_wateralpha; +extern convar r_lavaalpha; +extern convar r_telealpha; +extern convar r_slimealpha; +extern convar r_litwater; +extern convar r_dynamic; +extern convar r_novis; +extern convar r_scale; -extern cvar_t gl_clear; -extern cvar_t gl_cull; -extern cvar_t gl_smoothmodels; -extern cvar_t gl_affinemodels; -extern cvar_t gl_polyblend; -extern cvar_t gl_flashblend; -extern cvar_t gl_nocolors; -extern cvar_t gl_finish; +extern convar gl_clear; +extern convar gl_cull; +extern convar gl_smoothmodels; +extern convar gl_affinemodels; +extern convar gl_polyblend; +extern convar gl_flashblend; +extern convar gl_nocolors; +extern convar gl_finish; -extern cvar_t gl_playermip; +extern convar gl_playermip; -extern cvar_t gl_subdivide_size; +extern convar gl_subdivide_size; extern float load_subdivide_size; //johnfitz -- remember what subdivide_size value was when this map was loaded extern int gl_stencilbits; @@ -281,7 +281,7 @@ extern int rs_brushpolys, rs_aliaspolys, rs_skypolys; extern int rs_dynamiclightmaps, rs_brushpasses, rs_aliaspasses, rs_skypasses; //johnfitz -- track developer statistics that vary every frame -extern cvar_t devstats; +extern convar devstats; typedef struct { int packetsize; int edicts; diff --git a/Quake/host.cpp b/Quake/host.cpp index 7cf73f4..d2e799e 100644 --- a/Quake/host.cpp +++ b/Quake/host.cpp @@ -57,35 +57,35 @@ jmp_buf host_abortserver; byte *host_colormap; -cvar_t host_framerate = {"host_framerate","0",CVAR_NONE}; // set for slow motion -cvar_t host_speeds = {"host_speeds","0",CVAR_NONE}; // set for running times -cvar_t host_maxfps = {"host_maxfps", "72", CVAR_ARCHIVE}; //johnfitz -cvar_t host_timescale = {"host_timescale", "0", CVAR_NONE}; //johnfitz -cvar_t max_edicts = {"max_edicts", "8192", CVAR_NONE}; //johnfitz //ericw -- changed from 2048 to 8192, removed CVAR_ARCHIVE +convar host_framerate = {"host_framerate","0"}; // set for slow motion +convar host_speeds = {"host_speeds","0"}; // set for running times +convar host_maxfps = {"host_maxfps", "72", {.archive = true}}; //johnfitz +convar host_timescale = {"host_timescale", "0"}; //johnfitz +convar max_edicts = {"max_edicts", "8192"}; //johnfitz //ericw -- changed from 2048 to 8192, removed CVAR_ARCHIVE -cvar_t sys_ticrate = {"sys_ticrate","0.05",CVAR_NONE}; // dedicated server -cvar_t serverprofile = {"serverprofile","0",CVAR_NONE}; +convar sys_ticrate = {"sys_ticrate","0.05"}; // dedicated server +convar serverprofile = {"serverprofile","0"}; -cvar_t fraglimit = {"fraglimit","0",CVAR_NOTIFY|CVAR_SERVERINFO}; -cvar_t timelimit = {"timelimit","0",CVAR_NOTIFY|CVAR_SERVERINFO}; -cvar_t teamplay = {"teamplay","0",CVAR_NOTIFY|CVAR_SERVERINFO}; -cvar_t samelevel = {"samelevel","0",CVAR_NONE}; -cvar_t noexit = {"noexit","0",CVAR_NOTIFY|CVAR_SERVERINFO}; -cvar_t skill = {"skill","1",CVAR_NONE}; // 0 - 3 -cvar_t deathmatch = {"deathmatch","0",CVAR_NONE}; // 0, 1, or 2 -cvar_t coop = {"coop","0",CVAR_NONE}; // 0 or 1 +convar fraglimit = {"fraglimit","0",{.notify = true, .server_info = true}}; +convar timelimit = {"timelimit","0", {.notify = true, .server_info = true}}; +convar teamplay = {"teamplay","0",{.notify = true, .server_info = true}}; +convar samelevel = {"samelevel","0"}; +convar noexit = {"noexit","0",{.notify = true, .server_info = true}}; +convar skill = {"skill","1"}; // 0 - 3 +convar deathmatch = {"deathmatch","0"}; // 0, 1, or 2 +convar coop = {"coop","0"}; // 0 or 1 -cvar_t pausable = {"pausable","1",CVAR_NONE}; +convar pausable = {"pausable","1"}; -cvar_t developer = {"developer","0",CVAR_NONE}; +convar developer = {"developer","0"}; -cvar_t temp1 = {"temp1","0",CVAR_NONE}; +convar temp1 = {"temp1","0"}; -cvar_t devstats = {"devstats","0",CVAR_NONE}; //johnfitz -- track developer statistics that vary every frame +convar devstats = {"devstats","0"}; //johnfitz -- track developer statistics that vary every frame -cvar_t campaign = {"campaign","0",CVAR_NONE}; // for the 2021 rerelease -cvar_t horde = {"horde","0",CVAR_NONE}; // for the 2021 rerelease -cvar_t sv_cheats = {"sv_cheats","0",CVAR_NONE}; // for the 2021 rerelease +convar campaign = {"campaign","0"}; // for the 2021 rerelease +convar horde = {"horde","0"}; // for the 2021 rerelease +convar sv_cheats = {"sv_cheats","0"}; // for the 2021 rerelease devstats_t dev_stats, dev_peakstats; overflowtimes_t dev_overflows; //this stores the last time overflow messages were displayed, not the last time overflows occured @@ -95,7 +95,7 @@ overflowtimes_t dev_overflows; //this stores the last time overflow messages wer Max_Edicts_f -- johnfitz ================ */ -static void Max_Edicts_f (cvar_t *var) +static void Max_Edicts_f (convar *var) { //TODO: clamp it here? if (cls.state == ca_connected || sv.active) @@ -107,7 +107,7 @@ static void Max_Edicts_f (cvar_t *var) Max_Fps_f -- ericw ================ */ -static void Max_Fps_f (cvar_t *var) +static void Max_Fps_f (convar *var) { if (var->value > 72) Con_Warning ("host_maxfps above 72 breaks physics.\n"); @@ -227,9 +227,9 @@ void Host_FindMaxClients (void) svs.clients = (struct client_s *) Hunk_AllocName (svs.maxclientslimit*sizeof(client_t), "clients"); if (svs.maxclients > 1) - Cvar_SetQuick (&deathmatch, "1"); + deathmatch.set("1"); else - Cvar_SetQuick (&deathmatch, "0"); + deathmatch.set("0"); } void Host_Version_f (void) @@ -240,10 +240,10 @@ void Host_Version_f (void) } /* cvar callback functions : */ -void Host_Callback_Notify (cvar_t *var) +void Host_Callback_Notify (convar *var) { if (sv.active) - SV_BroadcastPrintf ("\"%s\" changed to \"%s\"\n", var->name, var->string); + SV_BroadcastPrintf ("\"%s\" changed to \"%s\"\n", var->name.c_str(), var->string); } /* @@ -253,45 +253,45 @@ Host_InitLocal */ void Host_InitLocal (void) { - Cmd_AddCommand ("version", Host_Version_f); + command::add ("version", Host_Version_f); Host_InitCommands (); - Cvar_RegisterVariable (&host_framerate); - Cvar_RegisterVariable (&host_speeds); - Cvar_RegisterVariable (&host_maxfps); //johnfitz - Cvar_SetCallback (&host_maxfps, Max_Fps_f); - Cvar_RegisterVariable (&host_timescale); //johnfitz + host_framerate.inscribe(); + host_speeds.inscribe(); + host_maxfps.inscribe(); //johnfitz + host_maxfps.set_callback(Max_Fps_f); + host_timescale.inscribe(); //johnfitz - Cvar_RegisterVariable (&max_edicts); //johnfitz - Cvar_SetCallback (&max_edicts, Max_Edicts_f); - Cvar_RegisterVariable (&devstats); //johnfitz + max_edicts.inscribe(); //johnfitz + max_edicts.set_callback(Max_Edicts_f); + devstats.inscribe(); //johnfitz - Cvar_RegisterVariable (&sys_ticrate); - Cvar_RegisterVariable (&sys_throttle); - Cvar_RegisterVariable (&serverprofile); + sys_ticrate.inscribe(); + sys_throttle.inscribe(); + serverprofile.inscribe(); - Cvar_RegisterVariable (&fraglimit); - Cvar_RegisterVariable (&timelimit); - Cvar_RegisterVariable (&teamplay); - Cvar_SetCallback (&fraglimit, Host_Callback_Notify); - Cvar_SetCallback (&timelimit, Host_Callback_Notify); - Cvar_SetCallback (&teamplay, Host_Callback_Notify); - Cvar_RegisterVariable (&samelevel); - Cvar_RegisterVariable (&noexit); - Cvar_SetCallback (&noexit, Host_Callback_Notify); - Cvar_RegisterVariable (&skill); - Cvar_RegisterVariable (&developer); - Cvar_RegisterVariable (&coop); - Cvar_RegisterVariable (&deathmatch); + fraglimit.inscribe(); + timelimit.inscribe(); + teamplay.inscribe(); + fraglimit.set_callback(Host_Callback_Notify); + timelimit.set_callback(Host_Callback_Notify); + teamplay.set_callback(Host_Callback_Notify); + samelevel.inscribe(); + noexit.inscribe(); + noexit.set_callback(Host_Callback_Notify); + skill.inscribe(); + developer.inscribe(); + coop.inscribe(); + deathmatch.inscribe(); - Cvar_RegisterVariable (&campaign); - Cvar_RegisterVariable (&horde); - Cvar_RegisterVariable (&sv_cheats); + campaign.inscribe(); + horde.inscribe(); + sv_cheats.inscribe(); - Cvar_RegisterVariable (&pausable); + pausable.inscribe(); - Cvar_RegisterVariable (&temp1); + temp1.inscribe(); Host_FindMaxClients (); } @@ -661,7 +661,7 @@ void Host_ServerFrame (void) if (active > 600 && dev_peakstats.edicts <= 600) Con_DWarning ("%i edicts exceeds standard limit of 600 (max = %d).\n", active, sv.max_edicts); dev_stats.edicts = active; - dev_peakstats.edicts = q_max(active, dev_peakstats.edicts); + dev_peakstats.edicts = std::max(active, dev_peakstats.edicts); } //johnfitz @@ -832,7 +832,7 @@ void Host_Init (void) Memory_Init (host_parms->membase, host_parms->memsize); Cbuf_Init (); - Cmd_Init (); + command::init (); LOG_Init (host_parms); Cvar_Init (); //johnfitz COM_Init (); diff --git a/Quake/host_cmd.cpp b/Quake/host_cmd.cpp index f1f3013..71edfca 100644 --- a/Quake/host_cmd.cpp +++ b/Quake/host_cmd.cpp @@ -21,12 +21,14 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ +#include + #include "quakedef.hpp" #ifndef _WIN32 #include #endif -extern cvar_t pausable; +extern convar pausable; int current_skill; @@ -425,11 +427,11 @@ static void Host_Status_f (void) int hours = 0; int j; - if (cmd_source == src_command) + if (command::last_source == command::source::command) { if (!sv.active) { - Cmd_ForwardToServer (); + command::forward_to_server (); return; } print_fn = Con_Printf; @@ -437,7 +439,7 @@ static void Host_Status_f (void) else print_fn = SV_ClientPrintf; - print_fn ("host: %s\n", Cvar_VariableString ("hostname")); + print_fn ("host: %s\n", convar::variable_string("hostname").value_or("").c_str()); print_fn ("version: %4.2f\n", VERSION); if (tcpipAvailable) print_fn ("tcp/ip: %s\n", my_tcpip_address); @@ -474,9 +476,9 @@ Sets client to godmode */ static void Host_God_f (void) { - if (cmd_source == src_command) + if (command::last_source == command::source::command) { - Cmd_ForwardToServer (); + command::forward_to_server(); return; } @@ -484,7 +486,7 @@ static void Host_God_f (void) return; //johnfitz -- allow user to explicitly set god mode to on or off - switch (Cmd_Argc()) + switch (command::argc()) { case 1: sv_player->v.flags = (int)sv_player->v.flags ^ FL_GODMODE; @@ -493,8 +495,8 @@ static void Host_God_f (void) else SV_ClientPrintf ("godmode ON\n"); break; - case 2: - if (Q_atof(Cmd_Argv(1))) + case 2: + if (Q_atof(command::argv(1)->c_str())) { sv_player->v.flags = (int)sv_player->v.flags | FL_GODMODE; SV_ClientPrintf ("godmode ON\n"); @@ -513,9 +515,9 @@ static void Host_God_f (void) } static void Host_Buddha_f (void) { - if (cmd_source == src_command) + if (command::last_source == command::source::command) { - Cmd_ForwardToServer (); + command::forward_to_server(); return; } @@ -536,9 +538,9 @@ Host_Notarget_f */ static void Host_Notarget_f (void) { - if (cmd_source == src_command) + if (command::last_source == command::source::command) { - Cmd_ForwardToServer (); + command::forward_to_server(); return; } @@ -546,7 +548,7 @@ static void Host_Notarget_f (void) return; //johnfitz -- allow user to explicitly set notarget to on or off - switch (Cmd_Argc()) + switch (command::argc()) { case 1: sv_player->v.flags = (int)sv_player->v.flags ^ FL_NOTARGET; @@ -555,8 +557,8 @@ static void Host_Notarget_f (void) else SV_ClientPrintf ("notarget ON\n"); break; - case 2: - if (Q_atof(Cmd_Argv(1))) + case 2: + if (Q_atof(command::argv(1)->c_str())) { sv_player->v.flags = (int)sv_player->v.flags | FL_NOTARGET; SV_ClientPrintf ("notarget ON\n"); @@ -583,9 +585,9 @@ Host_Noclip_f */ static void Host_Noclip_f (void) { - if (cmd_source == src_command) + if (command::last_source == command::source::command) { - Cmd_ForwardToServer (); + command::forward_to_server(); return; } @@ -593,7 +595,7 @@ static void Host_Noclip_f (void) return; //johnfitz -- allow user to explicitly set noclip to on or off - switch (Cmd_Argc()) + switch (command::argc()) { case 1: if (sv_player->v.movetype != MOVETYPE_NOCLIP) @@ -609,8 +611,8 @@ static void Host_Noclip_f (void) SV_ClientPrintf ("noclip OFF\n"); } break; - case 2: - if (Q_atof(Cmd_Argv(1))) + case 2: + if (Q_atof(command::argv(1)->c_str())) { noclip_anglehack = true; sv_player->v.movetype = MOVETYPE_NOCLIP; @@ -639,16 +641,15 @@ adapted from fteqw, originally by Alex Shadowalker */ static void Host_SetPos_f(void) { - if (cmd_source == src_command) + if (command::last_source == command::source::command) { - Cmd_ForwardToServer (); + command::forward_to_server(); return; } - if (pr_global_struct->deathmatch) return; - if (Cmd_Argc() != 7 && Cmd_Argc() != 4) + if (command::argc() != 7 && command::argc() != 4) { SV_ClientPrintf("usage:\n"); SV_ClientPrintf(" setpos \n"); @@ -676,15 +677,15 @@ static void Host_SetPos_f(void) sv_player->v.velocity[1] = 0; sv_player->v.velocity[2] = 0; - sv_player->v.origin[0] = atof(Cmd_Argv(1)); - sv_player->v.origin[1] = atof(Cmd_Argv(2)); - sv_player->v.origin[2] = atof(Cmd_Argv(3)); + sv_player->v.origin[0] = atof(command::argv(1)->c_str()); + sv_player->v.origin[1] = atof(command::argv(2)->c_str()); + sv_player->v.origin[2] = atof(command::argv(3)->c_str()); - if (Cmd_Argc() == 7) + if (command::argc() == 7) { - sv_player->v.angles[0] = atof(Cmd_Argv(4)); - sv_player->v.angles[1] = atof(Cmd_Argv(5)); - sv_player->v.angles[2] = atof(Cmd_Argv(6)); + sv_player->v.angles[0] = atof(command::argv(4)->c_str()); + sv_player->v.angles[1] = atof(command::argv(5)->c_str()); + sv_player->v.angles[2] = atof(command::argv(6)->c_str()); sv_player->v.fixangle = 1; } @@ -700,9 +701,9 @@ Sets client to flymode */ static void Host_Fly_f (void) { - if (cmd_source == src_command) + if (command::last_source == command::source::command) { - Cmd_ForwardToServer (); + command::forward_to_server(); return; } @@ -710,7 +711,7 @@ static void Host_Fly_f (void) return; //johnfitz -- allow user to explicitly set noclip to on or off - switch (Cmd_Argc()) + switch (command::argc()) { case 1: if (sv_player->v.movetype != MOVETYPE_FLY) @@ -724,8 +725,8 @@ static void Host_Fly_f (void) SV_ClientPrintf ("flymode OFF\n"); } break; - case 2: - if (Q_atof(Cmd_Argv(1))) + case 2: + if (Q_atof(command::argv(1)->c_str())) { sv_player->v.movetype = MOVETYPE_FLY; SV_ClientPrintf ("flymode ON\n"); @@ -755,9 +756,9 @@ static void Host_Ping_f (void) float total; client_t *client; - if (cmd_source == src_command) + if (command::last_source == command::source::command) { - Cmd_ForwardToServer (); + command::forward_to_server(); return; } @@ -796,7 +797,7 @@ static void Host_Map_f (void) int i; char name[MAX_QPATH], *p; - if (Cmd_Argc() < 2) //no map name given + if (command::argc() < 2) //no map name given { if (cls.state == ca_dedicated) { @@ -816,8 +817,10 @@ static void Host_Map_f (void) return; } - if (cmd_source != src_command) + if (command::last_source != command::source::command) + { return; + } cls.demonum = -1; // stop demo loop in case this fails @@ -830,7 +833,7 @@ static void Host_Map_f (void) SCR_BeginLoadingPlaque (); svs.serverflags = 0; // haven't completed an episode yet - q_strlcpy (name, Cmd_Argv(1), sizeof(name)); + q_strlcpy (name, command::argv(1)->c_str(), sizeof(name)); // remove (any) trailing ".bsp" from mapname -- S.A. p = strstr(name, ".bsp"); if (p && p[4] == '\0') @@ -842,13 +845,13 @@ static void Host_Map_f (void) if (cls.state != ca_dedicated) { memset (cls.spawnparms, 0, MAX_MAPSTRING); - for (i = 2; i < Cmd_Argc(); i++) + for (i = 2; i < command::argc(); i++) { - q_strlcat (cls.spawnparms, Cmd_Argv(i), MAX_MAPSTRING); + q_strlcat (cls.spawnparms, command::argv(i)->c_str(), MAX_MAPSTRING); q_strlcat (cls.spawnparms, " ", MAX_MAPSTRING); } - Cmd_ExecuteString ("connect local", src_command); + command::execute_string ("connect local", command::source::command); } } @@ -864,7 +867,7 @@ static void Host_Randmap_f (void) int i, randlevel, numlevels; filelist_item_t *level; - if (cmd_source != src_command) + if (command::last_source != command::source::command) return; for (level = extralevels, numlevels = 0; level; level = level->next) @@ -900,7 +903,7 @@ static void Host_Changelevel_f (void) { char level[MAX_QPATH]; - if (Cmd_Argc() != 2) + if (command::argc() != 2) { Con_Printf ("changelevel : continue game on a new level\n"); return; @@ -912,7 +915,7 @@ static void Host_Changelevel_f (void) } //johnfitz -- check for client having map before anything else - q_snprintf (level, sizeof(level), "maps/%s.bsp", Cmd_Argv(1)); + q_snprintf (level, sizeof(level), "maps/%s.bsp", command::argv(1)->c_str()); if (!COM_FileExists(level, NULL)) Host_Error ("cannot find map %s", level); //johnfitz @@ -921,7 +924,7 @@ static void Host_Changelevel_f (void) IN_Activate(); // -- S.A. key_dest = key_game; // remove console or menu SV_SaveSpawnparms (); - q_strlcpy (level, Cmd_Argv(1), sizeof(level)); + q_strlcpy (level, command::argv(1)->c_str(), sizeof(level)); SV_SpawnServer (level); // also issue an error if spawn failed -- O.S. if (!sv.active) @@ -942,7 +945,7 @@ static void Host_Restart_f (void) if (cls.demoplayback || !sv.active) return; - if (cmd_source != src_command) + if (command::last_source != command::source::command) return; q_strlcpy (mapname, sv.name, sizeof(mapname)); // mapname gets cleared in spawnserver SV_SpawnServer (mapname); @@ -984,7 +987,7 @@ static void Host_Connect_f (void) CL_StopPlayback (); CL_Disconnect (); } - q_strlcpy (name, Cmd_Argv(1), sizeof(name)); + q_strlcpy (name, command::argv(1).value_or("").c_str(), sizeof(name)); CL_EstablishConnection (name); Host_Reconnect_f (); } @@ -1051,7 +1054,7 @@ static void Host_Savegame_f (void) int i; char comment[SAVEGAME_COMMENT_LENGTH+1]; - if (cmd_source != src_command) + if (command::last_source != command::source::command) return; if (!sv.active) @@ -1072,13 +1075,13 @@ static void Host_Savegame_f (void) return; } - if (Cmd_Argc() != 2) + if (command::argc() != 2) { Con_Printf ("save : save a game\n"); return; } - if (strstr(Cmd_Argv(1), "..")) + if (strstr(command::argv(1)->c_str(), "..")) { Con_Printf ("Relative pathnames are not allowed.\n"); return; @@ -1093,7 +1096,7 @@ static void Host_Savegame_f (void) } } - q_snprintf (name, sizeof(name), "%s/%s", com_gamedir, Cmd_Argv(1)); + q_snprintf (name, sizeof(name), "%s/%s", com_gamedir, command::argv(1)->c_str()); COM_AddExtension (name, ".sav", sizeof(name)); Con_Printf ("Saving game to %s...\n", name); @@ -1143,24 +1146,22 @@ static void Host_Loadgame_f (void) char name[MAX_OSPATH]; char mapname[MAX_QPATH]; - float time, tfloat; - const char *data; int i; edict_t *ent; int entnum; int version; float spawn_parms[NUM_SPAWN_PARMS]; - if (cmd_source != src_command) + if (command::last_source != command::source::command) return; - if (Cmd_Argc() != 2) + if (command::argc() != 2) { Con_Printf ("load : load a game\n"); return; } - if (strstr(Cmd_Argv(1), "..")) + if (strstr(command::argv(1)->c_str(), "..")) { Con_Printf ("Relative pathnames are not allowed.\n"); return; @@ -1168,7 +1169,7 @@ static void Host_Loadgame_f (void) cls.demonum = -1; // stop demo loop in case this fails - q_snprintf (name, sizeof(name), "%s/%s", com_gamedir, Cmd_Argv(1)); + q_snprintf (name, sizeof(name), "%s/%s", com_gamedir, command::argv(1)->c_str()); COM_AddExtension (name, ".sav", sizeof(name)); // we can't call SCR_BeginLoadingPlaque, because too much stack space has @@ -1188,8 +1189,8 @@ static void Host_Loadgame_f (void) return; } - data = start; - data = COM_ParseIntNewline (data, &version); + std::istringstream ss{start}; + version = common::parse_int_newline(ss); if (version != SAVEGAME_VERSION) { free (start); @@ -1197,17 +1198,17 @@ static void Host_Loadgame_f (void) Host_Error ("Savegame is version %i, not %i", version, SAVEGAME_VERSION); return; } - data = COM_ParseStringNewline (data); + auto strr = common::parse_string_newline (ss); for (i = 0; i < NUM_SPAWN_PARMS; i++) - data = COM_ParseFloatNewline (data, &spawn_parms[i]); + spawn_parms[i] = common::parse_float_newline(ss); // this silliness is so we can load 1.06 save files, which have float skill values - data = COM_ParseFloatNewline(data, &tfloat); + const float tfloat = common::parse_float_newline(ss); current_skill = (int)(tfloat + 0.1); - Cvar_SetValue ("skill", (float)current_skill); + convar::set_value ("skill", (float)current_skill); - data = COM_ParseStringNewline (data); - q_strlcpy (mapname, com_token, sizeof(mapname)); - data = COM_ParseFloatNewline (data, &time); + strr = common::parse_string_newline(ss); + q_strlcpy (mapname, strr.c_str(), sizeof(mapname)); + const float time = common::parse_float_newline(ss); CL_Disconnect_f (); @@ -1227,25 +1228,25 @@ static void Host_Loadgame_f (void) // load the light styles for (i = 0; i < MAX_LIGHTSTYLES; i++) { - data = COM_ParseStringNewline (data); - sv.lightstyles[i] = (const char *)Hunk_Strdup (com_token, "lightstyles"); + strr = common::parse_string_newline(ss); + sv.lightstyles[i] = (const char *)Hunk_Strdup (strr.c_str(), "lightstyles"); } // load the edicts out of the savegame file entnum = -1; // -1 is the globals - while (*data) + while (!ss.eof()) { - data = COM_Parse (data); - if (!com_token[0]) + auto token = common::parse_token(ss); + if (!token.has_value()) break; // end of file - if (strcmp(com_token,"{")) + if (token->front() != '{') { Host_Error ("First token isn't a brace"); } if (entnum == -1) { // parse the global vars - data = ED_ParseGlobals (data); + ED_ParseGlobals (ss); } else { // parse an edict @@ -1258,7 +1259,7 @@ static void Host_Loadgame_f (void) memset (ent, 0, pr_edict_size); ent->baseline.scale = ENTSCALE_DEFAULT; } - data = ED_ParseEdict (data, ent); + ED_ParseEdict (ss, ent); // link it into the bsp tree if (!ent->free) @@ -1302,24 +1303,24 @@ static void Host_Name_f (void) { char newName[32]; - if (Cmd_Argc () == 1) + if (command::argc () == 1) { Con_Printf ("\"name\" is \"%s\"\n", cl_name.string); return; } - if (Cmd_Argc () == 2) - q_strlcpy(newName, Cmd_Argv(1), sizeof(newName)); + if (command::argc () == 2) + q_strlcpy(newName, command::argv(1)->c_str(), sizeof(newName)); else - q_strlcpy(newName, Cmd_Args(), sizeof(newName)); + q_strlcpy(newName, command::args().c_str(), sizeof(newName)); newName[15] = 0; // client_t structure actually says name[32]. - if (cmd_source == src_command) + if (command::last_source == command::source::command) { if (Q_strcmp(cl_name.string, newName) == 0) return; - Cvar_Set ("_cl_name", newName); + convar::set("_cl_name", newName); if (cls.state == ca_connected) - Cmd_ForwardToServer (); + command::forward_to_server (); return; } @@ -1342,28 +1343,28 @@ static void Host_Say(qboolean teamonly) int j; client_t *client; client_t *save; - const char *p; char text[MAXCMDLINE], *p2; qboolean quoted; qboolean fromServer = false; - if (cmd_source == src_command) + if (command::last_source == command::source::command) { if (cls.state != ca_dedicated) { - Cmd_ForwardToServer (); + command::forward_to_server (); return; } fromServer = true; teamonly = false; } - if (Cmd_Argc () < 2) + if (command::argc () < 2) return; save = host_client; - p = Cmd_Args(); + auto args = command::args(); + auto p = args.c_str(); // remove quotes if present quoted = false; if (*p == '\"') @@ -1433,16 +1434,17 @@ static void Host_Tell_f(void) char text[MAXCMDLINE], *p2; qboolean quoted; - if (cmd_source == src_command) + if (command::last_source == command::source::command) { - Cmd_ForwardToServer (); + command::forward_to_server(); return; } - if (Cmd_Argc () < 3) + if (command::argc () < 3) return; - p = Cmd_Args(); + auto args = command::args(); + p = args.c_str(); // remove quotes if present quoted = false; if (*p == '\"') @@ -1479,7 +1481,7 @@ static void Host_Tell_f(void) { if (!client->active || !client->spawned) continue; - if (q_strcasecmp(client->name, Cmd_Argv(1))) + if (q_strcasecmp(client->name, command::argv(1)->c_str())) continue; host_client = client; SV_ClientPrintf("%s", text); @@ -1498,19 +1500,19 @@ static void Host_Color_f(void) int top, bottom; int playercolor; - if (Cmd_Argc() == 1) + if (command::argc() == 1) { Con_Printf ("\"color\" is \"%i %i\"\n", ((int)cl_color.value) >> 4, ((int)cl_color.value) & 0x0f); Con_Printf ("color <0-13> [0-13]\n"); return; } - if (Cmd_Argc() == 2) - top = bottom = atoi(Cmd_Argv(1)); + if (command::argc() == 2) + top = bottom = atoi(command::argv(1)->c_str()); else { - top = atoi(Cmd_Argv(1)); - bottom = atoi(Cmd_Argv(2)); + top = atoi(command::argv(1)->c_str()); + bottom = atoi(command::argv(2)->c_str()); } top &= 15; @@ -1522,11 +1524,11 @@ static void Host_Color_f(void) playercolor = top*16 + bottom; - if (cmd_source == src_command) + if (command::last_source == command::source::command) { - Cvar_SetValue ("_cl_color", playercolor); + convar::set_value ("_cl_color", playercolor); if (cls.state == ca_connected) - Cmd_ForwardToServer (); + command::forward_to_server (); return; } @@ -1546,9 +1548,9 @@ Host_Kill_f */ static void Host_Kill_f (void) { - if (cmd_source == src_command) + if (command::last_source == command::source::command) { - Cmd_ForwardToServer (); + command::forward_to_server(); return; } @@ -1578,9 +1580,9 @@ static void Host_Pause_f (void) return; } - if (cmd_source == src_command) + if (command::last_source == command::source::command) { - Cmd_ForwardToServer (); + command::forward_to_server(); return; } if (!pausable.value) @@ -1613,7 +1615,7 @@ Host_PreSpawn_f */ static void Host_PreSpawn_f (void) { - if (cmd_source == src_command) + if (command::last_source == command::source::command) { Con_Printf ("prespawn is not valid from the console\n"); return; @@ -1640,7 +1642,7 @@ static void Host_Spawn_f (void) client_t *client; edict_t *ent; - if (cmd_source == src_command) + if (command::last_source == command::source::command) { Con_Printf ("spawn is not valid from the console\n"); return; @@ -1755,7 +1757,7 @@ Host_Begin_f */ static void Host_Begin_f (void) { - if (cmd_source == src_command) + if (command::last_source == command::source::command) { Con_Printf ("begin is not valid from the console\n"); return; @@ -1776,16 +1778,15 @@ Kicks a user off of the server static void Host_Kick_f (void) { const char *who; - const char *message = NULL; client_t *save; int i; qboolean byNumber = false; - if (cmd_source == src_command) + if (command::last_source == command::source::command) { if (!sv.active) { - Cmd_ForwardToServer (); + command::forward_to_server (); return; } } @@ -1794,9 +1795,9 @@ static void Host_Kick_f (void) save = host_client; - if (Cmd_Argc() > 2 && Q_strcmp(Cmd_Argv(1), "#") == 0) + if (command::argc() > 2 && Q_strcmp(command::argv(1)->c_str(), "#") == 0) { - i = Q_atof(Cmd_Argv(2)) - 1; + i = Q_atof(command::argv(2)->c_str()) - 1; if (i < 0 || i >= svs.maxclients) return; if (!svs.clients[i].active) @@ -1810,14 +1811,14 @@ static void Host_Kick_f (void) { if (!host_client->active) continue; - if (q_strcasecmp(host_client->name, Cmd_Argv(1)) == 0) + if (q_strcasecmp(host_client->name, command::argv(1).value_or("").c_str()) == 0) break; } } if (i < svs.maxclients) { - if (cmd_source == src_command) + if (command::last_source == command::source::command) if (cls.state == ca_dedicated) who = "Console"; else @@ -1829,21 +1830,25 @@ static void Host_Kick_f (void) if (host_client == save) return; - if (Cmd_Argc() > 2) + std::string message{}; + if (command::argc() > 2) { - message = COM_Parse(Cmd_Args()); + std::istringstream ss{command::args()}; + auto token = common::parse_token(ss); if (byNumber) { - message++; // skip the # - while (*message == ' ') // skip white space - message++; - message += strlen(Cmd_Argv(2)); // skip the number + ss.get(); + while (ss.peek() == ' ') // skip white space + ss.get(); + ss.seekg(command::argv(2)->length(), std::ios_base::seekdir::_S_cur); // skip the number } - while (*message && *message == ' ') - message++; + while (!ss.eof() && ss.peek() == ' ') + ss.get(); + + message += ss.str().substr(ss.tellg()); } - if (message) - SV_ClientPrintf ("Kicked by %s: %s\n", who, message); + if (!message.empty()) + SV_ClientPrintf ("Kicked by %s: %s\n", who, message.c_str()); else SV_ClientPrintf ("Kicked by %s\n", who); SV_DropClient (false); @@ -1871,17 +1876,18 @@ static void Host_Give_f (void) int v; eval_t *val; - if (cmd_source == src_command) + if (command::last_source == command::source::command) { - Cmd_ForwardToServer (); + command::forward_to_server(); return; } if (pr_global_struct->deathmatch) return; - t = Cmd_Argv(1); - v = atoi (Cmd_Argv(2)); + auto arg1 = command::argv(1).value_or(""); + t = arg1.c_str(); + v = atoi (command::argv(2).value_or("").c_str()); switch (t[0]) { @@ -2119,10 +2125,10 @@ static void Host_Viewmodel_f (void) if (!e) return; - m = Mod_ForName (Cmd_Argv(1), false); + m = Mod_ForName (command::argv(1).value_or("").c_str(), false); if (!m) { - Con_Printf ("Can't load %s\n", Cmd_Argv(1)); + Con_Printf ("Can't load %s\n", command::argv(1).value_or("").c_str()); return; } @@ -2146,7 +2152,7 @@ static void Host_Viewframe_f (void) return; m = cl.model_precache[(int)e->v.modelindex]; - f = atoi(Cmd_Argv(1)); + f = atoi(command::argv(1).value_or("").c_str()); if (f >= m->numframes) f = m->numframes - 1; @@ -2231,7 +2237,7 @@ static void Host_Startdemos_f (void) if (cls.state == ca_dedicated) return; - c = Cmd_Argc() - 1; + c = command::argc() - 1; if (c > MAX_DEMOS) { Con_Printf ("Max %i demos in demoloop\n", MAX_DEMOS); @@ -2240,7 +2246,7 @@ static void Host_Startdemos_f (void) Con_Printf ("%i demo(s) in loop\n", c); for (i = 1; i < c + 1; i++) - q_strlcpy (cls.demos[i-1], Cmd_Argv(i), sizeof(cls.demos[0])); + q_strlcpy (cls.demos[i-1], command::argv(i)->c_str(), sizeof(cls.demos[0])); if (!sv.active && cls.demonum != -1 && !cls.demoplayback) { @@ -2316,49 +2322,49 @@ Host_InitCommands */ void Host_InitCommands (void) { - Cmd_AddCommand ("maps", Host_Maps_f); //johnfitz - Cmd_AddCommand ("mods", Host_Mods_f); //johnfitz - Cmd_AddCommand ("games", Host_Mods_f); // as an alias to "mods" -- S.A. / QuakeSpasm - Cmd_AddCommand ("mapname", Host_Mapname_f); //johnfitz - Cmd_AddCommand ("randmap", Host_Randmap_f); //ericw + command::add ("maps", Host_Maps_f); //johnfitz + command::add ("mods", Host_Mods_f); //johnfitz + command::add ("games", Host_Mods_f); // as an alias to "mods" -- S.A. / QuakeSpasm + command::add ("mapname", Host_Mapname_f); //johnfitz + command::add ("randmap", Host_Randmap_f); //ericw - Cmd_AddCommand ("status", Host_Status_f); - Cmd_AddCommand ("quit", Host_Quit_f); - Cmd_AddCommand ("god", Host_God_f); - Cmd_AddCommand("buddha", Host_Buddha_f); - Cmd_AddCommand ("notarget", Host_Notarget_f); - Cmd_AddCommand ("fly", Host_Fly_f); - Cmd_AddCommand ("map", Host_Map_f); - Cmd_AddCommand ("restart", Host_Restart_f); - Cmd_AddCommand ("changelevel", Host_Changelevel_f); - Cmd_AddCommand ("connect", Host_Connect_f); - Cmd_AddCommand ("reconnect", Host_Reconnect_f); - Cmd_AddCommand ("name", Host_Name_f); - Cmd_AddCommand ("noclip", Host_Noclip_f); - Cmd_AddCommand ("setpos", Host_SetPos_f); //QuakeSpasm + command::add ("status", Host_Status_f); + command::add ("quit", Host_Quit_f); + command::add ("god", Host_God_f); + command::add("buddha", Host_Buddha_f); + command::add ("notarget", Host_Notarget_f); + command::add ("fly", Host_Fly_f); + command::add ("map", Host_Map_f); + command::add ("restart", Host_Restart_f); + command::add ("changelevel", Host_Changelevel_f); + command::add ("connect", Host_Connect_f); + command::add ("reconnect", Host_Reconnect_f); + command::add ("name", Host_Name_f); + command::add ("noclip", Host_Noclip_f); + command::add ("setpos", Host_SetPos_f); //QuakeSpasm - Cmd_AddCommand ("say", Host_Say_f); - Cmd_AddCommand ("say_team", Host_Say_Team_f); - Cmd_AddCommand ("tell", Host_Tell_f); - Cmd_AddCommand ("color", Host_Color_f); - Cmd_AddCommand ("kill", Host_Kill_f); - Cmd_AddCommand ("pause", Host_Pause_f); - Cmd_AddCommand ("spawn", Host_Spawn_f); - Cmd_AddCommand ("begin", Host_Begin_f); - Cmd_AddCommand ("prespawn", Host_PreSpawn_f); - Cmd_AddCommand ("kick", Host_Kick_f); - Cmd_AddCommand ("ping", Host_Ping_f); - Cmd_AddCommand ("load", Host_Loadgame_f); - Cmd_AddCommand ("save", Host_Savegame_f); - Cmd_AddCommand ("give", Host_Give_f); + command::add ("say", Host_Say_f); + command::add ("say_team", Host_Say_Team_f); + command::add ("tell", Host_Tell_f); + command::add ("color", Host_Color_f); + command::add ("kill", Host_Kill_f); + command::add ("pause", Host_Pause_f); + command::add ("spawn", Host_Spawn_f); + command::add ("begin", Host_Begin_f); + command::add ("prespawn", Host_PreSpawn_f); + command::add ("kick", Host_Kick_f); + command::add ("ping", Host_Ping_f); + command::add ("load", Host_Loadgame_f); + command::add ("save", Host_Savegame_f); + command::add ("give", Host_Give_f); - Cmd_AddCommand ("startdemos", Host_Startdemos_f); - Cmd_AddCommand ("demos", Host_Demos_f); - Cmd_AddCommand ("stopdemo", Host_Stopdemo_f); + command::add ("startdemos", Host_Startdemos_f); + command::add ("demos", Host_Demos_f); + command::add ("stopdemo", Host_Stopdemo_f); - Cmd_AddCommand ("viewmodel", Host_Viewmodel_f); - Cmd_AddCommand ("viewframe", Host_Viewframe_f); - Cmd_AddCommand ("viewnext", Host_Viewnext_f); - Cmd_AddCommand ("viewprev", Host_Viewprev_f); + command::add ("viewmodel", Host_Viewmodel_f); + command::add ("viewframe", Host_Viewframe_f); + command::add ("viewnext", Host_Viewnext_f); + command::add ("viewprev", Host_Viewprev_f); } diff --git a/Quake/in_sdl.cpp b/Quake/in_sdl.cpp index 84dfb7f..53db149 100644 --- a/Quake/in_sdl.cpp +++ b/Quake/in_sdl.cpp @@ -32,10 +32,10 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "SDL.h" #endif -static qboolean windowhasfocus = true; //just in case sdl fails to tell us... -static qboolean textmode; +static qboolean windowhasfocus = true; //just in case sdl fails to tell us... +static qboolean textmode; -static cvar_t in_debugkeys = {"in_debugkeys", "0", CVAR_NONE}; +static convar in_debugkeys{"in_debugkeys", "0"}; #ifdef __APPLE__ /* Mouse acceleration needs to be disabled on OS X */ @@ -50,384 +50,342 @@ static cvar_t in_debugkeys = {"in_debugkeys", "0", CVAR_NONE}; #endif // SDL2 Game Controller cvars -cvar_t joy_deadzone_look = { "joy_deadzone_look", "0.175", CVAR_ARCHIVE }; -cvar_t joy_deadzone_move = { "joy_deadzone_move", "0.175", CVAR_ARCHIVE }; -cvar_t joy_outer_threshold_look = { "joy_outer_threshold_look", "0.02", CVAR_ARCHIVE }; -cvar_t joy_outer_threshold_move = { "joy_outer_threshold_move", "0.02", CVAR_ARCHIVE }; -cvar_t joy_deadzone_trigger = { "joy_deadzone_trigger", "0.2", CVAR_ARCHIVE }; -cvar_t joy_sensitivity_yaw = { "joy_sensitivity_yaw", "240", CVAR_ARCHIVE }; -cvar_t joy_sensitivity_pitch = { "joy_sensitivity_pitch", "130", CVAR_ARCHIVE }; -cvar_t joy_invert = { "joy_invert", "0", CVAR_ARCHIVE }; -cvar_t joy_exponent = { "joy_exponent", "2", CVAR_ARCHIVE }; -cvar_t joy_exponent_move = { "joy_exponent_move", "2", CVAR_ARCHIVE }; -cvar_t joy_swapmovelook = { "joy_swapmovelook", "0", CVAR_ARCHIVE }; -cvar_t joy_enable = { "joy_enable", "1", CVAR_ARCHIVE }; +convar joy_deadzone_look{"joy_deadzone_look", "0.175", {.archive = true}}; +convar joy_deadzone_move{"joy_deadzone_move", "0.175", {.archive = true}}; +convar joy_outer_threshold_look{"joy_outer_threshold_look", "0.02", {.archive = true}}; +convar joy_outer_threshold_move{"joy_outer_threshold_move", "0.02", {.archive = true}}; +convar joy_deadzone_trigger{"joy_deadzone_trigger", "0.2", {.archive = true}}; +convar joy_sensitivity_yaw{"joy_sensitivity_yaw", "240", {.archive = true}}; +convar joy_sensitivity_pitch{"joy_sensitivity_pitch", "130", {.archive = true}}; +convar joy_invert{"joy_invert", "0", {.archive = true}}; +convar joy_exponent{"joy_exponent", "2", {.archive = true}}; +convar joy_exponent_move{"joy_exponent_move", "2", {.archive = true}}; +convar joy_swapmovelook{"joy_swapmovelook", "0", {.archive = true}}; +convar joy_enable{"joy_enable", "1", {.archive = true}}; #if defined(USE_SDL2) static SDL_JoystickID joy_active_instaceid = -1; static SDL_GameController *joy_active_controller = NULL; #endif -static qboolean no_mouse = false; +static qboolean no_mouse = false; static int buttonremap[] = { - K_MOUSE1, - K_MOUSE3, /* right button */ - K_MOUSE2, /* middle button */ + K_MOUSE1, + K_MOUSE3, /* right button */ + K_MOUSE2, /* middle button */ #if !defined(USE_SDL2) /* mousewheel up/down not counted as buttons in SDL2 */ - K_MWHEELUP, - K_MWHEELDOWN, + K_MWHEELUP, + K_MWHEELDOWN, #endif - K_MOUSE4, - K_MOUSE5 + K_MOUSE4, + K_MOUSE5 }; /* total accumulated mouse movement since last frame */ -static int total_dx, total_dy = 0; +static int total_dx, total_dy = 0; -static int SDLCALL IN_FilterMouseEvents (const SDL_Event *event) -{ - switch (event->type) - { - case SDL_MOUSEMOTION: - // case SDL_MOUSEBUTTONDOWN: - // case SDL_MOUSEBUTTONUP: - return 0; - } +static int SDLCALL IN_FilterMouseEvents(const SDL_Event *event) { + switch (event->type) { + case SDL_MOUSEMOTION: + // case SDL_MOUSEBUTTONDOWN: + // case SDL_MOUSEBUTTONUP: + return 0; + } - return 1; + return 1; } #if defined(USE_SDL2) -static int SDLCALL IN_SDL2_FilterMouseEvents (void *userdata, SDL_Event *event) -{ - return IN_FilterMouseEvents (event); +static int SDLCALL IN_SDL2_FilterMouseEvents(void *userdata, SDL_Event *event) { + return IN_FilterMouseEvents(event); } #endif -static void IN_BeginIgnoringMouseEvents(void) -{ +static void IN_BeginIgnoringMouseEvents(void) { #if defined(USE_SDL2) - SDL_EventFilter currentFilter = NULL; - void *currentUserdata = NULL; - SDL_GetEventFilter(¤tFilter, ¤tUserdata); + SDL_EventFilter currentFilter = NULL; + void *currentUserdata = NULL; + SDL_GetEventFilter(¤tFilter, ¤tUserdata); - if (currentFilter != IN_SDL2_FilterMouseEvents) - SDL_SetEventFilter(IN_SDL2_FilterMouseEvents, NULL); + if (currentFilter != IN_SDL2_FilterMouseEvents) + SDL_SetEventFilter(IN_SDL2_FilterMouseEvents, NULL); #else - if (SDL_GetEventFilter() != IN_FilterMouseEvents) - SDL_SetEventFilter(IN_FilterMouseEvents); + if (SDL_GetEventFilter() != IN_FilterMouseEvents) + SDL_SetEventFilter(IN_FilterMouseEvents); #endif } -static void IN_EndIgnoringMouseEvents(void) -{ +static void IN_EndIgnoringMouseEvents(void) { #if defined(USE_SDL2) - SDL_EventFilter currentFilter; - void *currentUserdata; - if (SDL_GetEventFilter(¤tFilter, ¤tUserdata) == SDL_TRUE) - SDL_SetEventFilter(NULL, NULL); + SDL_EventFilter currentFilter; + void *currentUserdata; + if (SDL_GetEventFilter(¤tFilter, ¤tUserdata) == SDL_TRUE) + SDL_SetEventFilter(NULL, NULL); #else - if (SDL_GetEventFilter() != NULL) - SDL_SetEventFilter(NULL); + if (SDL_GetEventFilter() != NULL) + SDL_SetEventFilter(NULL); #endif } #ifdef MACOS_X_ACCELERATION_HACK -static cvar_t in_disablemacosxmouseaccel = {"in_disablemacosxmouseaccel", "1", CVAR_ARCHIVE}; +static convar in_disablemacosxmouseaccel = {"in_disablemacosxmouseaccel", "1", CVAR_ARCHIVE}; static double originalMouseSpeed = -1.0; -static io_connect_t IN_GetIOHandle(void) -{ - io_connect_t iohandle = MACH_PORT_NULL; - io_service_t iohidsystem = MACH_PORT_NULL; - mach_port_t masterport; - kern_return_t status; +static io_connect_t IN_GetIOHandle(void) { + io_connect_t iohandle = MACH_PORT_NULL; + io_service_t iohidsystem = MACH_PORT_NULL; + mach_port_t masterport; + kern_return_t status; - status = IOMasterPort(MACH_PORT_NULL, &masterport); - if (status != KERN_SUCCESS) - return 0; + status = IOMasterPort(MACH_PORT_NULL, &masterport); + if (status != KERN_SUCCESS) + return 0; - iohidsystem = IORegistryEntryFromPath(masterport, kIOServicePlane ":/IOResources/IOHIDSystem"); - if (!iohidsystem) - return 0; + iohidsystem = IORegistryEntryFromPath(masterport, kIOServicePlane ":/IOResources/IOHIDSystem"); + if (!iohidsystem) + return 0; - status = IOServiceOpen(iohidsystem, mach_task_self(), kIOHIDParamConnectType, &iohandle); - IOObjectRelease(iohidsystem); + status = IOServiceOpen(iohidsystem, mach_task_self(), kIOHIDParamConnectType, &iohandle); + IOObjectRelease(iohidsystem); - return iohandle; + return iohandle; } -static void IN_DisableOSXMouseAccel (void) -{ - io_connect_t mouseDev = IN_GetIOHandle(); - if (mouseDev != 0) - { - if (IOHIDGetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), &originalMouseSpeed) == kIOReturnSuccess) - { - if (IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), -1.0) != kIOReturnSuccess) - { - Cvar_Set("in_disablemacosxmouseaccel", "0"); - Con_Printf("WARNING: Could not disable mouse acceleration (failed at IOHIDSetAccelerationWithKey).\n"); - } - } - else - { - Cvar_Set("in_disablemacosxmouseaccel", "0"); - Con_Printf("WARNING: Could not disable mouse acceleration (failed at IOHIDGetAccelerationWithKey).\n"); - } - IOServiceClose(mouseDev); - } - else - { - Cvar_Set("in_disablemacosxmouseaccel", "0"); - Con_Printf("WARNING: Could not disable mouse acceleration (failed at IO_GetIOHandle).\n"); - } +static void IN_DisableOSXMouseAccel(void) { + io_connect_t mouseDev = IN_GetIOHandle(); + if (mouseDev != 0) { + if (IOHIDGetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), &originalMouseSpeed) == + kIOReturnSuccess) { + if (IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), -1.0) != kIOReturnSuccess) { + convar::set("in_disablemacosxmouseaccel", "0"); + Con_Printf("WARNING: Could not disable mouse acceleration (failed at IOHIDSetAccelerationWithKey).\n"); + } + } else { + convar::set("in_disablemacosxmouseaccel", "0"); + Con_Printf("WARNING: Could not disable mouse acceleration (failed at IOHIDGetAccelerationWithKey).\n"); + } + IOServiceClose(mouseDev); + } else { + convar::set("in_disablemacosxmouseaccel", "0"); + Con_Printf("WARNING: Could not disable mouse acceleration (failed at IO_GetIOHandle).\n"); + } } -static void IN_ReenableOSXMouseAccel (void) -{ - io_connect_t mouseDev = IN_GetIOHandle(); - if (mouseDev != 0) - { - if (IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), originalMouseSpeed) != kIOReturnSuccess) - Con_Printf("WARNING: Could not re-enable mouse acceleration (failed at IOHIDSetAccelerationWithKey).\n"); - IOServiceClose(mouseDev); - } - else - { - Con_Printf("WARNING: Could not re-enable mouse acceleration (failed at IO_GetIOHandle).\n"); - } - originalMouseSpeed = -1; +static void IN_ReenableOSXMouseAccel(void) { + io_connect_t mouseDev = IN_GetIOHandle(); + if (mouseDev != 0) { + if (IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), originalMouseSpeed) != + kIOReturnSuccess) + Con_Printf("WARNING: Could not re-enable mouse acceleration (failed at IOHIDSetAccelerationWithKey).\n"); + IOServiceClose(mouseDev); + } else { + Con_Printf("WARNING: Could not re-enable mouse acceleration (failed at IO_GetIOHandle).\n"); + } + originalMouseSpeed = -1; } #endif /* MACOS_X_ACCELERATION_HACK */ -void IN_Activate (void) -{ - if (no_mouse) - return; +void IN_Activate(void) { + if (no_mouse) + return; #ifdef MACOS_X_ACCELERATION_HACK - /* Save the status of mouse acceleration */ - if (originalMouseSpeed == -1 && in_disablemacosxmouseaccel.value) - IN_DisableOSXMouseAccel(); + /* Save the status of mouse acceleration */ + if (originalMouseSpeed == -1 && in_disablemacosxmouseaccel.value) + IN_DisableOSXMouseAccel(); #endif #if defined(USE_SDL2) #ifdef __APPLE__ - { - // Work around https://github.com/sezero/quakespasm/issues/48 - int width, height; - SDL_GetWindowSize((SDL_Window*) VID_GetWindow(), &width, &height); - SDL_WarpMouseInWindow((SDL_Window*) VID_GetWindow(), width / 2, height / 2); - } + { + // Work around https://github.com/sezero/quakespasm/issues/48 + int width, height; + SDL_GetWindowSize((SDL_Window *) VID_GetWindow(), &width, &height); + SDL_WarpMouseInWindow((SDL_Window *) VID_GetWindow(), width / 2, height / 2); + } #endif - if (SDL_SetRelativeMouseMode(SDL_TRUE) != 0) - { - Con_Printf("WARNING: SDL_SetRelativeMouseMode(SDL_TRUE) failed.\n"); - } + if (SDL_SetRelativeMouseMode(SDL_TRUE) != 0) { + Con_Printf("WARNING: SDL_SetRelativeMouseMode(SDL_TRUE) failed.\n"); + } #else - if (SDL_WM_GrabInput(SDL_GRAB_QUERY) != SDL_GRAB_ON) - { - SDL_WM_GrabInput(SDL_GRAB_ON); - if (SDL_WM_GrabInput(SDL_GRAB_QUERY) != SDL_GRAB_ON) - Con_Printf("WARNING: SDL_WM_GrabInput(SDL_GRAB_ON) failed.\n"); - } + if (SDL_WM_GrabInput(SDL_GRAB_QUERY) != SDL_GRAB_ON) { + SDL_WM_GrabInput(SDL_GRAB_ON); + if (SDL_WM_GrabInput(SDL_GRAB_QUERY) != SDL_GRAB_ON) + Con_Printf("WARNING: SDL_WM_GrabInput(SDL_GRAB_ON) failed.\n"); + } - if (SDL_ShowCursor(SDL_QUERY) != SDL_DISABLE) - { - SDL_ShowCursor(SDL_DISABLE); - if (SDL_ShowCursor(SDL_QUERY) != SDL_DISABLE) - Con_Printf("WARNING: SDL_ShowCursor(SDL_DISABLE) failed.\n"); - } + if (SDL_ShowCursor(SDL_QUERY) != SDL_DISABLE) { + SDL_ShowCursor(SDL_DISABLE); + if (SDL_ShowCursor(SDL_QUERY) != SDL_DISABLE) + Con_Printf("WARNING: SDL_ShowCursor(SDL_DISABLE) failed.\n"); + } #endif - IN_EndIgnoringMouseEvents(); + IN_EndIgnoringMouseEvents(); - total_dx = 0; - total_dy = 0; + total_dx = 0; + total_dy = 0; } -void IN_Deactivate (qboolean free_cursor) -{ - if (no_mouse) - return; +void IN_Deactivate(qboolean free_cursor) { + if (no_mouse) + return; #ifdef MACOS_X_ACCELERATION_HACK - if (originalMouseSpeed != -1) - IN_ReenableOSXMouseAccel(); + if (originalMouseSpeed != -1) + IN_ReenableOSXMouseAccel(); #endif - if (free_cursor) - { + if (free_cursor) { #if defined(USE_SDL2) - SDL_SetRelativeMouseMode(SDL_FALSE); + SDL_SetRelativeMouseMode(SDL_FALSE); #else - if (SDL_WM_GrabInput(SDL_GRAB_QUERY) != SDL_GRAB_OFF) - { - SDL_WM_GrabInput(SDL_GRAB_OFF); - if (SDL_WM_GrabInput(SDL_GRAB_QUERY) != SDL_GRAB_OFF) - Con_Printf("WARNING: SDL_WM_GrabInput(SDL_GRAB_OFF) failed.\n"); - } + if (SDL_WM_GrabInput(SDL_GRAB_QUERY) != SDL_GRAB_OFF) { + SDL_WM_GrabInput(SDL_GRAB_OFF); + if (SDL_WM_GrabInput(SDL_GRAB_QUERY) != SDL_GRAB_OFF) + Con_Printf("WARNING: SDL_WM_GrabInput(SDL_GRAB_OFF) failed.\n"); + } - if (SDL_ShowCursor(SDL_QUERY) != SDL_ENABLE) - { - SDL_ShowCursor(SDL_ENABLE); - if (SDL_ShowCursor(SDL_QUERY) != SDL_ENABLE) - Con_Printf("WARNING: SDL_ShowCursor(SDL_ENABLE) failed.\n"); - } + if (SDL_ShowCursor(SDL_QUERY) != SDL_ENABLE) { + SDL_ShowCursor(SDL_ENABLE); + if (SDL_ShowCursor(SDL_QUERY) != SDL_ENABLE) + Con_Printf("WARNING: SDL_ShowCursor(SDL_ENABLE) failed.\n"); + } #endif - } + } - /* discard all mouse events when input is deactivated */ - IN_BeginIgnoringMouseEvents(); + /* discard all mouse events when input is deactivated */ + IN_BeginIgnoringMouseEvents(); } -void IN_StartupJoystick (void) -{ +void IN_StartupJoystick(void) { #if defined(USE_SDL2) - int i; - int nummappings; - char controllerdb[MAX_OSPATH]; - SDL_GameController *gamecontroller; - - if (COM_CheckParm("-nojoy")) - return; - - if (SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) == -1 ) - { - Con_Warning("could not initialize SDL Game Controller\n"); - return; - } - - // Load additional SDL2 controller definitions from gamecontrollerdb.txt - q_snprintf (controllerdb, sizeof(controllerdb), "%s/gamecontrollerdb.txt", com_basedir); - nummappings = SDL_GameControllerAddMappingsFromFile(controllerdb); - if (nummappings > 0) - Con_Printf("%d mappings loaded from gamecontrollerdb.txt\n", nummappings); - - // Also try host_parms->userdir - if (host_parms->userdir != host_parms->basedir) - { - q_snprintf (controllerdb, sizeof(controllerdb), "%s/gamecontrollerdb.txt", host_parms->userdir); - nummappings = SDL_GameControllerAddMappingsFromFile(controllerdb); - if (nummappings > 0) - Con_Printf("%d mappings loaded from gamecontrollerdb.txt\n", nummappings); - } + int i; + int nummappings; + char controllerdb[MAX_OSPATH]; + SDL_GameController *gamecontroller; - for (i = 0; i < SDL_NumJoysticks(); i++) - { - const char *joyname = SDL_JoystickNameForIndex(i); - if ( SDL_IsGameController(i) ) - { - const char *controllername = SDL_GameControllerNameForIndex(i); - gamecontroller = SDL_GameControllerOpen(i); - if (gamecontroller) - { - Con_Printf("detected controller: %s\n", controllername != NULL ? controllername : "NULL"); - - joy_active_instaceid = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(gamecontroller)); - joy_active_controller = gamecontroller; - break; - } - else - { - Con_Warning("failed to open controller: %s\n", controllername != NULL ? controllername : "NULL"); - } - } - else - { - Con_Warning("joystick missing controller mappings: %s\n", joyname != NULL ? joyname : "NULL" ); - } - } + if (COM_CheckParm("-nojoy")) + return; + + if (SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) == -1) { + Con_Warning("could not initialize SDL Game Controller\n"); + return; + } + + // Load additional SDL2 controller definitions from gamecontrollerdb.txt + q_snprintf(controllerdb, sizeof(controllerdb), "%s/gamecontrollerdb.txt", com_basedir); + nummappings = SDL_GameControllerAddMappingsFromFile(controllerdb); + if (nummappings > 0) + Con_Printf("%d mappings loaded from gamecontrollerdb.txt\n", nummappings); + + // Also try host_parms->userdir + if (host_parms->userdir != host_parms->basedir) { + q_snprintf(controllerdb, sizeof(controllerdb), "%s/gamecontrollerdb.txt", host_parms->userdir); + nummappings = SDL_GameControllerAddMappingsFromFile(controllerdb); + if (nummappings > 0) + Con_Printf("%d mappings loaded from gamecontrollerdb.txt\n", nummappings); + } + + for (i = 0; i < SDL_NumJoysticks(); i++) { + const char *joyname = SDL_JoystickNameForIndex(i); + if (SDL_IsGameController(i)) { + const char *controllername = SDL_GameControllerNameForIndex(i); + gamecontroller = SDL_GameControllerOpen(i); + if (gamecontroller) { + Con_Printf("detected controller: %s\n", controllername != NULL ? controllername : "NULL"); + + joy_active_instaceid = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(gamecontroller)); + joy_active_controller = gamecontroller; + break; + } else { + Con_Warning("failed to open controller: %s\n", controllername != NULL ? controllername : "NULL"); + } + } else { + Con_Warning("joystick missing controller mappings: %s\n", joyname != NULL ? joyname : "NULL"); + } + } #endif } -void IN_ShutdownJoystick (void) -{ +void IN_ShutdownJoystick(void) { #if defined(USE_SDL2) - SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER); + SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER); #endif } -void IN_Init (void) -{ - textmode = Key_TextEntry(); +void IN_Init(void) { + textmode = Key_TextEntry(); #if !defined(USE_SDL2) - SDL_EnableUNICODE (textmode); - if (SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL) == -1) - Con_Printf("Warning: SDL_EnableKeyRepeat() failed.\n"); + SDL_EnableUNICODE(textmode); + if (SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL) == -1) + Con_Printf("Warning: SDL_EnableKeyRepeat() failed.\n"); #else - if (textmode) - SDL_StartTextInput(); - else - SDL_StopTextInput(); + if (textmode) + SDL_StartTextInput(); + else + SDL_StopTextInput(); #endif - if (safemode || COM_CheckParm("-nomouse")) - { - no_mouse = true; - /* discard all mouse events when input is deactivated */ - IN_BeginIgnoringMouseEvents(); - } + if (safemode || COM_CheckParm("-nomouse")) { + no_mouse = true; + /* discard all mouse events when input is deactivated */ + IN_BeginIgnoringMouseEvents(); + } #ifdef MACOS_X_ACCELERATION_HACK - Cvar_RegisterVariable(&in_disablemacosxmouseaccel); + in_disablemacosxmouseaccel.inscribe(); #endif - Cvar_RegisterVariable(&in_debugkeys); - Cvar_RegisterVariable(&joy_sensitivity_yaw); - Cvar_RegisterVariable(&joy_sensitivity_pitch); - Cvar_RegisterVariable(&joy_deadzone_look); - Cvar_RegisterVariable(&joy_deadzone_move); - Cvar_RegisterVariable(&joy_outer_threshold_look); - Cvar_RegisterVariable(&joy_outer_threshold_move); - Cvar_RegisterVariable(&joy_deadzone_trigger); - Cvar_RegisterVariable(&joy_invert); - Cvar_RegisterVariable(&joy_exponent); - Cvar_RegisterVariable(&joy_exponent_move); - Cvar_RegisterVariable(&joy_swapmovelook); - Cvar_RegisterVariable(&joy_enable); + in_debugkeys.inscribe(); + joy_sensitivity_yaw.inscribe(); + joy_sensitivity_pitch.inscribe(); + joy_deadzone_look.inscribe(); + joy_deadzone_move.inscribe(); + joy_outer_threshold_look.inscribe(); + joy_outer_threshold_move.inscribe(); + joy_deadzone_trigger.inscribe(); + joy_invert.inscribe(); + joy_exponent.inscribe(); + joy_exponent_move.inscribe(); + joy_swapmovelook.inscribe(); + joy_enable.inscribe(); - IN_Activate(); - IN_StartupJoystick(); + IN_Activate(); + IN_StartupJoystick(); } -void IN_Shutdown (void) -{ - IN_Deactivate(true); - IN_ShutdownJoystick(); +void IN_Shutdown(void) { + IN_Deactivate(true); + IN_ShutdownJoystick(); } -extern cvar_t cl_maxpitch; /* johnfitz -- variable pitch clamping */ -extern cvar_t cl_minpitch; /* johnfitz -- variable pitch clamping */ +extern convar cl_maxpitch; /* johnfitz -- variable pitch clamping */ +extern convar cl_minpitch; /* johnfitz -- variable pitch clamping */ -void IN_MouseMotion(int dx, int dy) -{ - if (!windowhasfocus) - dx = dy = 0; //don't change view angles etc while unfocused. - total_dx += dx; - total_dy += dy; +void IN_MouseMotion(int dx, int dy) { + if (!windowhasfocus) + dx = dy = 0; //don't change view angles etc while unfocused. + total_dx += dx; + total_dy += dy; } #if defined(USE_SDL2) -typedef struct joyaxis_s -{ - float x; - float y; +typedef struct joyaxis_s { + float x; + float y; } joyaxis_t; -typedef struct joy_buttonstate_s -{ - qboolean buttondown[SDL_CONTROLLER_BUTTON_MAX]; +typedef struct joy_buttonstate_s { + qboolean buttondown[SDL_CONTROLLER_BUTTON_MAX]; } joybuttonstate_t; -typedef struct axisstate_s -{ - float axisvalue[SDL_CONTROLLER_AXIS_MAX]; // normalized to +-1 +typedef struct axisstate_s { + float axisvalue[SDL_CONTROLLER_AXIS_MAX]; // normalized to +-1 } joyaxisstate_t; static joybuttonstate_t joy_buttonstate; @@ -448,10 +406,9 @@ IN_AxisMagnitude Returns the vector length of the given joystick axis ================ */ -static vec_t IN_AxisMagnitude(joyaxis_t axis) -{ - vec_t magnitude = sqrtf((axis.x * axis.x) + (axis.y * axis.y)); - return magnitude; +static vec_t IN_AxisMagnitude(joyaxis_t axis) { + vec_t magnitude = sqrtf((axis.x * axis.x) + (axis.y * axis.y)); + return magnitude; } /* @@ -462,20 +419,19 @@ assumes axis values are in [-1, 1] and the vector magnitude has been clamped at Raises the axis values to the given exponent, keeping signs. ================ */ -static joyaxis_t IN_ApplyEasing(joyaxis_t axis, float exponent) -{ - joyaxis_t result = {0}; - vec_t eased_magnitude; - vec_t magnitude = IN_AxisMagnitude(axis); - - if (magnitude == 0) - return result; - - eased_magnitude = powf(magnitude, exponent); - - result.x = axis.x * (eased_magnitude / magnitude); - result.y = axis.y * (eased_magnitude / magnitude); - return result; +static joyaxis_t IN_ApplyEasing(joyaxis_t axis, float exponent) { + joyaxis_t result = {0}; + vec_t eased_magnitude; + vec_t magnitude = IN_AxisMagnitude(axis); + + if (magnitude == 0) + return result; + + eased_magnitude = powf(magnitude, exponent); + + result.x = axis.x * (eased_magnitude / magnitude); + result.y = axis.y * (eased_magnitude / magnitude); + return result; } /* @@ -493,20 +449,19 @@ from https://github.com/jeremiah-sypult/Quakespasm-Rift and adapted from http://www.third-helix.com/2013/04/12/doing-thumbstick-dead-zones-right.html ================ */ -static joyaxis_t IN_ApplyDeadzone(joyaxis_t axis, float deadzone, float outer_threshold) -{ - joyaxis_t result = {0}; - vec_t magnitude = IN_AxisMagnitude(axis); - - if ( magnitude > deadzone ) { - // rescale the magnitude so deadzone becomes 0, and 1-outer_threshold becomes 1 - const vec_t new_magnitude = q_min(1.0, (magnitude - deadzone) / (1.0 - deadzone - outer_threshold)); - const vec_t scale = new_magnitude / magnitude; - result.x = axis.x * scale; - result.y = axis.y * scale; - } - - return result; +static joyaxis_t IN_ApplyDeadzone(joyaxis_t axis, float deadzone, float outer_threshold) { + joyaxis_t result = {0}; + vec_t magnitude = IN_AxisMagnitude(axis); + + if (magnitude > deadzone) { + // rescale the magnitude so deadzone becomes 0, and 1-outer_threshold becomes 1 + const vec_t new_magnitude = std::min(1.0, (magnitude - deadzone) / (1.0 - deadzone - outer_threshold)); + const vec_t scale = new_magnitude / magnitude; + result.x = axis.x * scale; + result.y = axis.y * scale; + } + + return result; } /* @@ -514,26 +469,24 @@ static joyaxis_t IN_ApplyDeadzone(joyaxis_t axis, float deadzone, float outer_th IN_KeyForControllerButton ================ */ -static int IN_KeyForControllerButton(SDL_GameControllerButton button) -{ - switch (button) - { - case SDL_CONTROLLER_BUTTON_A: return K_ABUTTON; - case SDL_CONTROLLER_BUTTON_B: return K_BBUTTON; - case SDL_CONTROLLER_BUTTON_X: return K_XBUTTON; - case SDL_CONTROLLER_BUTTON_Y: return K_YBUTTON; - case SDL_CONTROLLER_BUTTON_BACK: return K_TAB; - case SDL_CONTROLLER_BUTTON_START: return K_ESCAPE; - case SDL_CONTROLLER_BUTTON_LEFTSTICK: return K_LTHUMB; - case SDL_CONTROLLER_BUTTON_RIGHTSTICK: return K_RTHUMB; - case SDL_CONTROLLER_BUTTON_LEFTSHOULDER: return K_LSHOULDER; - case SDL_CONTROLLER_BUTTON_RIGHTSHOULDER: return K_RSHOULDER; - case SDL_CONTROLLER_BUTTON_DPAD_UP: return K_UPARROW; - case SDL_CONTROLLER_BUTTON_DPAD_DOWN: return K_DOWNARROW; - case SDL_CONTROLLER_BUTTON_DPAD_LEFT: return K_LEFTARROW; - case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: return K_RIGHTARROW; - default: return 0; - } +static int IN_KeyForControllerButton(SDL_GameControllerButton button) { + switch (button) { + case SDL_CONTROLLER_BUTTON_A: return K_ABUTTON; + case SDL_CONTROLLER_BUTTON_B: return K_BBUTTON; + case SDL_CONTROLLER_BUTTON_X: return K_XBUTTON; + case SDL_CONTROLLER_BUTTON_Y: return K_YBUTTON; + case SDL_CONTROLLER_BUTTON_BACK: return K_TAB; + case SDL_CONTROLLER_BUTTON_START: return K_ESCAPE; + case SDL_CONTROLLER_BUTTON_LEFTSTICK: return K_LTHUMB; + case SDL_CONTROLLER_BUTTON_RIGHTSTICK: return K_RTHUMB; + case SDL_CONTROLLER_BUTTON_LEFTSHOULDER: return K_LSHOULDER; + case SDL_CONTROLLER_BUTTON_RIGHTSHOULDER: return K_RSHOULDER; + case SDL_CONTROLLER_BUTTON_DPAD_UP: return K_UPARROW; + case SDL_CONTROLLER_BUTTON_DPAD_DOWN: return K_DOWNARROW; + case SDL_CONTROLLER_BUTTON_DPAD_LEFT: return K_LEFTARROW; + case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: return K_RIGHTARROW; + default: return 0; + } } /* @@ -546,35 +499,26 @@ and generates key repeats if the button is held down. Adapted from DarkPlaces by lordhavoc ================ */ -static void IN_JoyKeyEvent(qboolean wasdown, qboolean isdown, int key, double *timer) -{ - // we can't use `realtime` for key repeats because it is not monotomic - const double currenttime = Sys_DoubleTime(); - - if (wasdown) - { - if (isdown) - { - if (currenttime >= *timer) - { - *timer = currenttime + 0.1; - Key_Event(key, true); - } - } - else - { - *timer = 0; - Key_Event(key, false); - } - } - else - { - if (isdown) - { - *timer = currenttime + 0.5; - Key_Event(key, true); - } - } +static void IN_JoyKeyEvent(qboolean wasdown, qboolean isdown, int key, double *timer) { + // we can't use `realtime` for key repeats because it is not monotomic + const double currenttime = Sys_DoubleTime(); + + if (wasdown) { + if (isdown) { + if (currenttime >= *timer) { + *timer = currenttime + 0.1; + Key_Event(key, true); + } + } else { + *timer = 0; + Key_Event(key, false); + } + } else { + if (isdown) { + *timer = currenttime + 0.5; + Key_Event(key, true); + } + } } #endif @@ -585,51 +529,61 @@ IN_Commands Emit key events for game controller buttons, including emulated buttons for analog sticks/triggers ================ */ -void IN_Commands (void) -{ +void IN_Commands(void) { #if defined(USE_SDL2) - joyaxisstate_t newaxisstate; - int i; - const float stickthreshold = 0.9; - const float triggerthreshold = joy_deadzone_trigger.value; - - if (!joy_enable.value) - return; - - if (!joy_active_controller) - return; + joyaxisstate_t newaxisstate; + int i; + const float stickthreshold = 0.9; + const float triggerthreshold = joy_deadzone_trigger.value; - // emit key events for controller buttons - for (i = 0; i < SDL_CONTROLLER_BUTTON_MAX; i++) - { - qboolean newstate = SDL_GameControllerGetButton(joy_active_controller, (SDL_GameControllerButton)i); - qboolean oldstate = joy_buttonstate.buttondown[i]; - - joy_buttonstate.buttondown[i] = newstate; - - // NOTE: This can cause a reentrant call of IN_Commands, via SCR_ModalMessage when confirming a new game. - IN_JoyKeyEvent(oldstate, newstate, IN_KeyForControllerButton((SDL_GameControllerButton)i), &joy_buttontimer[i]); - } - - for (i = 0; i < SDL_CONTROLLER_AXIS_MAX; i++) - { - newaxisstate.axisvalue[i] = SDL_GameControllerGetAxis(joy_active_controller, (SDL_GameControllerAxis)i) / 32768.0f; - } - - // emit emulated arrow keys so the analog sticks can be used in the menu - if (key_dest != key_game) - { - IN_JoyKeyEvent(joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTX] < -stickthreshold, newaxisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTX] < -stickthreshold, K_LEFTARROW, &joy_emulatedkeytimer[0]); - IN_JoyKeyEvent(joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTX] > stickthreshold, newaxisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTX] > stickthreshold, K_RIGHTARROW, &joy_emulatedkeytimer[1]); - IN_JoyKeyEvent(joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTY] < -stickthreshold, newaxisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTY] < -stickthreshold, K_UPARROW, &joy_emulatedkeytimer[2]); - IN_JoyKeyEvent(joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTY] > stickthreshold, newaxisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTY] > stickthreshold, K_DOWNARROW, &joy_emulatedkeytimer[3]); - } - - // emit emulated keys for the analog triggers - IN_JoyKeyEvent(joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_TRIGGERLEFT] > triggerthreshold, newaxisstate.axisvalue[SDL_CONTROLLER_AXIS_TRIGGERLEFT] > triggerthreshold, K_LTRIGGER, &joy_emulatedkeytimer[4]); - IN_JoyKeyEvent(joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_TRIGGERRIGHT] > triggerthreshold, newaxisstate.axisvalue[SDL_CONTROLLER_AXIS_TRIGGERRIGHT] > triggerthreshold, K_RTRIGGER, &joy_emulatedkeytimer[5]); - - joy_axisstate = newaxisstate; + if (!joy_enable.value) + return; + + if (!joy_active_controller) + return; + + // emit key events for controller buttons + for (i = 0; i < SDL_CONTROLLER_BUTTON_MAX; i++) { + qboolean newstate = SDL_GameControllerGetButton(joy_active_controller, (SDL_GameControllerButton) i); + qboolean oldstate = joy_buttonstate.buttondown[i]; + + joy_buttonstate.buttondown[i] = newstate; + + // NOTE: This can cause a reentrant call of IN_Commands, via SCR_ModalMessage when confirming a new game. + IN_JoyKeyEvent(oldstate, newstate, IN_KeyForControllerButton((SDL_GameControllerButton) i), + &joy_buttontimer[i]); + } + + for (i = 0; i < SDL_CONTROLLER_AXIS_MAX; i++) { + newaxisstate.axisvalue[i] = SDL_GameControllerGetAxis(joy_active_controller, (SDL_GameControllerAxis) i) / + 32768.0f; + } + + // emit emulated arrow keys so the analog sticks can be used in the menu + if (key_dest != key_game) { + IN_JoyKeyEvent(joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTX] < -stickthreshold, + newaxisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTX] < -stickthreshold, K_LEFTARROW, + &joy_emulatedkeytimer[0]); + IN_JoyKeyEvent(joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTX] > stickthreshold, + newaxisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTX] > stickthreshold, K_RIGHTARROW, + &joy_emulatedkeytimer[1]); + IN_JoyKeyEvent(joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTY] < -stickthreshold, + newaxisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTY] < -stickthreshold, K_UPARROW, + &joy_emulatedkeytimer[2]); + IN_JoyKeyEvent(joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTY] > stickthreshold, + newaxisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTY] > stickthreshold, K_DOWNARROW, + &joy_emulatedkeytimer[3]); + } + + // emit emulated keys for the analog triggers + IN_JoyKeyEvent(joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_TRIGGERLEFT] > triggerthreshold, + newaxisstate.axisvalue[SDL_CONTROLLER_AXIS_TRIGGERLEFT] > triggerthreshold, K_LTRIGGER, + &joy_emulatedkeytimer[4]); + IN_JoyKeyEvent(joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_TRIGGERRIGHT] > triggerthreshold, + newaxisstate.axisvalue[SDL_CONTROLLER_AXIS_TRIGGERRIGHT] > triggerthreshold, K_RTRIGGER, + &joy_emulatedkeytimer[5]); + + joy_axisstate = newaxisstate; #endif } @@ -638,523 +592,484 @@ void IN_Commands (void) IN_JoyMove ================ */ -void IN_JoyMove (usercmd_t *cmd) -{ +void IN_JoyMove(usercmd_t *cmd) { #if defined(USE_SDL2) - float speed; - joyaxis_t moveRaw, moveDeadzone, moveEased; - joyaxis_t lookRaw, lookDeadzone, lookEased; - extern cvar_t sv_maxspeed; + float speed; + joyaxis_t moveRaw, moveDeadzone, moveEased; + joyaxis_t lookRaw, lookDeadzone, lookEased; + extern convar sv_maxspeed; - if (!joy_enable.value) - return; - - if (!joy_active_controller) - return; + if (!joy_enable.value) + return; - if (cl.paused || key_dest != key_game) - return; - - moveRaw.x = joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTX]; - moveRaw.y = joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTY]; - lookRaw.x = joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_RIGHTX]; - lookRaw.y = joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_RIGHTY]; - - if (joy_swapmovelook.value) - { - joyaxis_t temp = moveRaw; - moveRaw = lookRaw; - lookRaw = temp; - } - - moveDeadzone = IN_ApplyDeadzone(moveRaw, joy_deadzone_move.value, joy_outer_threshold_move.value); - lookDeadzone = IN_ApplyDeadzone(lookRaw, joy_deadzone_look.value, joy_outer_threshold_look.value); + if (!joy_active_controller) + return; - moveEased = IN_ApplyEasing(moveDeadzone, joy_exponent_move.value); - lookEased = IN_ApplyEasing(lookDeadzone, joy_exponent.value); + if (cl.paused || key_dest != key_game) + return; - if ((in_speed.state & 1) ^ (cl_alwaysrun.value != 0.0 || cl_forwardspeed.value >= sv_maxspeed.value)) - // running - speed = sv_maxspeed.value; - else if (cl_forwardspeed.value >= sv_maxspeed.value) - // not running, with always run = vanilla - speed = q_min(sv_maxspeed.value, cl_forwardspeed.value / cl_movespeedkey.value); - else - // not running, with always run = off or quakespasm - speed = cl_forwardspeed.value; + moveRaw.x = joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTX]; + moveRaw.y = joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTY]; + lookRaw.x = joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_RIGHTX]; + lookRaw.y = joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_RIGHTY]; - cmd->sidemove += speed * moveEased.x; - cmd->forwardmove -= speed * moveEased.y; + if (joy_swapmovelook.value) { + joyaxis_t temp = moveRaw; + moveRaw = lookRaw; + lookRaw = temp; + } - cl.viewangles[YAW] -= lookEased.x * joy_sensitivity_yaw.value * host_frametime; - cl.viewangles[PITCH] += lookEased.y * joy_sensitivity_pitch.value * (joy_invert.value ? -1.0 : 1.0) * host_frametime; + moveDeadzone = IN_ApplyDeadzone(moveRaw, joy_deadzone_move.value, joy_outer_threshold_move.value); + lookDeadzone = IN_ApplyDeadzone(lookRaw, joy_deadzone_look.value, joy_outer_threshold_look.value); - if (lookEased.x != 0 || lookEased.y != 0) - V_StopPitchDrift(); + moveEased = IN_ApplyEasing(moveDeadzone, joy_exponent_move.value); + lookEased = IN_ApplyEasing(lookDeadzone, joy_exponent.value); - /* johnfitz -- variable pitch clamping */ - if (cl.viewangles[PITCH] > cl_maxpitch.value) - cl.viewangles[PITCH] = cl_maxpitch.value; - if (cl.viewangles[PITCH] < cl_minpitch.value) - cl.viewangles[PITCH] = cl_minpitch.value; + if ((in_speed.state & 1) ^ (cl_alwaysrun.value != 0.0 || cl_forwardspeed.value >= sv_maxspeed.value)) + // running + speed = sv_maxspeed.value; + else if (cl_forwardspeed.value >= sv_maxspeed.value) + // not running, with always run = vanilla + speed = std::min(sv_maxspeed.value, cl_forwardspeed.value / cl_movespeedkey.value); + else + // not running, with always run = off or quakespasm + speed = cl_forwardspeed.value; + + cmd->sidemove += speed * moveEased.x; + cmd->forwardmove -= speed * moveEased.y; + + cl.viewangles[YAW] -= lookEased.x * joy_sensitivity_yaw.value * host_frametime; + cl.viewangles[PITCH] += lookEased.y * joy_sensitivity_pitch.value * (joy_invert.value ? -1.0 : 1.0) * + host_frametime; + + if (lookEased.x != 0 || lookEased.y != 0) + V_StopPitchDrift(); + + /* johnfitz -- variable pitch clamping */ + if (cl.viewangles[PITCH] > cl_maxpitch.value) + cl.viewangles[PITCH] = cl_maxpitch.value; + if (cl.viewangles[PITCH] < cl_minpitch.value) + cl.viewangles[PITCH] = cl_minpitch.value; #endif } -void IN_MouseMove(usercmd_t *cmd) -{ - float dmx, dmy; +void IN_MouseMove(usercmd_t *cmd) { + float dmx, dmy; - dmx = total_dx * sensitivity.value; - dmy = total_dy * sensitivity.value; + dmx = total_dx * sensitivity.value; + dmy = total_dy * sensitivity.value; - total_dx = 0; - total_dy = 0; + total_dx = 0; + total_dy = 0; - // do pause check after resetting total_d* so mouse movements during pause don't accumulate - if (cl.paused || key_dest != key_game) - return; + // do pause check after resetting total_d* so mouse movements during pause don't accumulate + if (cl.paused || key_dest != key_game) + return; - if ( (in_strafe.state & 1) || (lookstrafe.value && (in_mlook.state & 1) )) - cmd->sidemove += m_side.value * dmx; - else - cl.viewangles[YAW] -= m_yaw.value * dmx; + if ((in_strafe.state & 1) || (lookstrafe.value && (in_mlook.state & 1))) + cmd->sidemove += m_side.value * dmx; + else + cl.viewangles[YAW] -= m_yaw.value * dmx; - if (in_mlook.state & 1) - { - if (dmx || dmy) - V_StopPitchDrift (); - } + if (in_mlook.state & 1) { + if (dmx || dmy) + V_StopPitchDrift(); + } - if ( (in_mlook.state & 1) && !(in_strafe.state & 1)) - { - cl.viewangles[PITCH] += m_pitch.value * dmy; - /* johnfitz -- variable pitch clamping */ - if (cl.viewangles[PITCH] > cl_maxpitch.value) - cl.viewangles[PITCH] = cl_maxpitch.value; - if (cl.viewangles[PITCH] < cl_minpitch.value) - cl.viewangles[PITCH] = cl_minpitch.value; - } - else - { - if ((in_strafe.state & 1) && noclip_anglehack) - cmd->upmove -= m_forward.value * dmy; - else - cmd->forwardmove -= m_forward.value * dmy; - } + if ((in_mlook.state & 1) && !(in_strafe.state & 1)) { + cl.viewangles[PITCH] += m_pitch.value * dmy; + /* johnfitz -- variable pitch clamping */ + if (cl.viewangles[PITCH] > cl_maxpitch.value) + cl.viewangles[PITCH] = cl_maxpitch.value; + if (cl.viewangles[PITCH] < cl_minpitch.value) + cl.viewangles[PITCH] = cl_minpitch.value; + } else { + if ((in_strafe.state & 1) && noclip_anglehack) + cmd->upmove -= m_forward.value * dmy; + else + cmd->forwardmove -= m_forward.value * dmy; + } } -void IN_Move(usercmd_t *cmd) -{ - IN_JoyMove(cmd); - IN_MouseMove(cmd); +void IN_Move(usercmd_t *cmd) { + IN_JoyMove(cmd); + IN_MouseMove(cmd); } -void IN_ClearStates (void) -{ +void IN_ClearStates(void) { } -void IN_UpdateInputMode (void) -{ - qboolean want_textmode = Key_TextEntry(); - if (textmode != want_textmode) - { - textmode = want_textmode; +void IN_UpdateInputMode(void) { + qboolean want_textmode = Key_TextEntry(); + if (textmode != want_textmode) { + textmode = want_textmode; #if !defined(USE_SDL2) - SDL_EnableUNICODE(textmode); - if (in_debugkeys.value) - Con_Printf("SDL_EnableUNICODE %d time: %g\n", textmode, Sys_DoubleTime()); + SDL_EnableUNICODE(textmode); + if (in_debugkeys.value) + Con_Printf("SDL_EnableUNICODE %d time: %g\n", textmode, Sys_DoubleTime()); #else - if (textmode) - { - SDL_StartTextInput(); - if (in_debugkeys.value) - Con_Printf("SDL_StartTextInput time: %g\n", Sys_DoubleTime()); - } - else - { - SDL_StopTextInput(); - if (in_debugkeys.value) - Con_Printf("SDL_StopTextInput time: %g\n", Sys_DoubleTime()); - } + if (textmode) { + SDL_StartTextInput(); + if (in_debugkeys.value) + Con_Printf("SDL_StartTextInput time: %g\n", Sys_DoubleTime()); + } else { + SDL_StopTextInput(); + if (in_debugkeys.value) + Con_Printf("SDL_StopTextInput time: %g\n", Sys_DoubleTime()); + } #endif - } + } } #if !defined(USE_SDL2) -static inline int IN_SDL_KeysymToQuakeKey(SDLKey sym) -{ - if (sym > SDLK_SPACE && sym < SDLK_DELETE) - return sym; +static inline int IN_SDL_KeysymToQuakeKey(SDLKey sym) { + if (sym > SDLK_SPACE && sym < SDLK_DELETE) + return sym; - switch (sym) - { - case SDLK_TAB: return K_TAB; - case SDLK_RETURN: return K_ENTER; - case SDLK_ESCAPE: return K_ESCAPE; - case SDLK_SPACE: return K_SPACE; + switch (sym) { + case SDLK_TAB: return K_TAB; + case SDLK_RETURN: return K_ENTER; + case SDLK_ESCAPE: return K_ESCAPE; + case SDLK_SPACE: return K_SPACE; - case SDLK_BACKSPACE: return K_BACKSPACE; - case SDLK_UP: return K_UPARROW; - case SDLK_DOWN: return K_DOWNARROW; - case SDLK_LEFT: return K_LEFTARROW; - case SDLK_RIGHT: return K_RIGHTARROW; + case SDLK_BACKSPACE: return K_BACKSPACE; + case SDLK_UP: return K_UPARROW; + case SDLK_DOWN: return K_DOWNARROW; + case SDLK_LEFT: return K_LEFTARROW; + case SDLK_RIGHT: return K_RIGHTARROW; - case SDLK_LALT: return K_ALT; - case SDLK_RALT: return K_ALT; - case SDLK_LCTRL: return K_CTRL; - case SDLK_RCTRL: return K_CTRL; - case SDLK_LSHIFT: return K_SHIFT; - case SDLK_RSHIFT: return K_SHIFT; + case SDLK_LALT: return K_ALT; + case SDLK_RALT: return K_ALT; + case SDLK_LCTRL: return K_CTRL; + case SDLK_RCTRL: return K_CTRL; + case SDLK_LSHIFT: return K_SHIFT; + case SDLK_RSHIFT: return K_SHIFT; - case SDLK_F1: return K_F1; - case SDLK_F2: return K_F2; - case SDLK_F3: return K_F3; - case SDLK_F4: return K_F4; - case SDLK_F5: return K_F5; - case SDLK_F6: return K_F6; - case SDLK_F7: return K_F7; - case SDLK_F8: return K_F8; - case SDLK_F9: return K_F9; - case SDLK_F10: return K_F10; - case SDLK_F11: return K_F11; - case SDLK_F12: return K_F12; - case SDLK_INSERT: return K_INS; - case SDLK_DELETE: return K_DEL; - case SDLK_PAGEDOWN: return K_PGDN; - case SDLK_PAGEUP: return K_PGUP; - case SDLK_HOME: return K_HOME; - case SDLK_END: return K_END; + case SDLK_F1: return K_F1; + case SDLK_F2: return K_F2; + case SDLK_F3: return K_F3; + case SDLK_F4: return K_F4; + case SDLK_F5: return K_F5; + case SDLK_F6: return K_F6; + case SDLK_F7: return K_F7; + case SDLK_F8: return K_F8; + case SDLK_F9: return K_F9; + case SDLK_F10: return K_F10; + case SDLK_F11: return K_F11; + case SDLK_F12: return K_F12; + case SDLK_INSERT: return K_INS; + case SDLK_DELETE: return K_DEL; + case SDLK_PAGEDOWN: return K_PGDN; + case SDLK_PAGEUP: return K_PGUP; + case SDLK_HOME: return K_HOME; + case SDLK_END: return K_END; - case SDLK_NUMLOCK: return K_KP_NUMLOCK; - case SDLK_KP_DIVIDE: return K_KP_SLASH; - case SDLK_KP_MULTIPLY: return K_KP_STAR; - case SDLK_KP_MINUS:return K_KP_MINUS; - case SDLK_KP7: return K_KP_HOME; - case SDLK_KP8: return K_KP_UPARROW; - case SDLK_KP9: return K_KP_PGUP; - case SDLK_KP_PLUS: return K_KP_PLUS; - case SDLK_KP4: return K_KP_LEFTARROW; - case SDLK_KP5: return K_KP_5; - case SDLK_KP6: return K_KP_RIGHTARROW; - case SDLK_KP1: return K_KP_END; - case SDLK_KP2: return K_KP_DOWNARROW; - case SDLK_KP3: return K_KP_PGDN; - case SDLK_KP_ENTER: return K_KP_ENTER; - case SDLK_KP0: return K_KP_INS; - case SDLK_KP_PERIOD: return K_KP_DEL; + case SDLK_NUMLOCK: return K_KP_NUMLOCK; + case SDLK_KP_DIVIDE: return K_KP_SLASH; + case SDLK_KP_MULTIPLY: return K_KP_STAR; + case SDLK_KP_MINUS: return K_KP_MINUS; + case SDLK_KP7: return K_KP_HOME; + case SDLK_KP8: return K_KP_UPARROW; + case SDLK_KP9: return K_KP_PGUP; + case SDLK_KP_PLUS: return K_KP_PLUS; + case SDLK_KP4: return K_KP_LEFTARROW; + case SDLK_KP5: return K_KP_5; + case SDLK_KP6: return K_KP_RIGHTARROW; + case SDLK_KP1: return K_KP_END; + case SDLK_KP2: return K_KP_DOWNARROW; + case SDLK_KP3: return K_KP_PGDN; + case SDLK_KP_ENTER: return K_KP_ENTER; + case SDLK_KP0: return K_KP_INS; + case SDLK_KP_PERIOD: return K_KP_DEL; - case SDLK_LMETA: return K_COMMAND; - case SDLK_RMETA: return K_COMMAND; + case SDLK_LMETA: return K_COMMAND; + case SDLK_RMETA: return K_COMMAND; - case SDLK_BREAK: return K_PAUSE; - case SDLK_PAUSE: return K_PAUSE; + case SDLK_BREAK: return K_PAUSE; + case SDLK_PAUSE: return K_PAUSE; - case SDLK_WORLD_18: return '~'; // the '�' key + case SDLK_WORLD_18: return '~'; // the '�' key - default: return 0; - } + default: return 0; + } } #endif #if defined(USE_SDL2) -static inline int IN_SDL2_ScancodeToQuakeKey(SDL_Scancode scancode) -{ - switch (scancode) - { - case SDL_SCANCODE_TAB: return K_TAB; - case SDL_SCANCODE_RETURN: return K_ENTER; - case SDL_SCANCODE_RETURN2: return K_ENTER; - case SDL_SCANCODE_ESCAPE: return K_ESCAPE; - case SDL_SCANCODE_SPACE: return K_SPACE; +static inline int IN_SDL2_ScancodeToQuakeKey(SDL_Scancode scancode) { + switch (scancode) { + case SDL_SCANCODE_TAB: return K_TAB; + case SDL_SCANCODE_RETURN: return K_ENTER; + case SDL_SCANCODE_RETURN2: return K_ENTER; + case SDL_SCANCODE_ESCAPE: return K_ESCAPE; + case SDL_SCANCODE_SPACE: return K_SPACE; - case SDL_SCANCODE_A: return 'a'; - case SDL_SCANCODE_B: return 'b'; - case SDL_SCANCODE_C: return 'c'; - case SDL_SCANCODE_D: return 'd'; - case SDL_SCANCODE_E: return 'e'; - case SDL_SCANCODE_F: return 'f'; - case SDL_SCANCODE_G: return 'g'; - case SDL_SCANCODE_H: return 'h'; - case SDL_SCANCODE_I: return 'i'; - case SDL_SCANCODE_J: return 'j'; - case SDL_SCANCODE_K: return 'k'; - case SDL_SCANCODE_L: return 'l'; - case SDL_SCANCODE_M: return 'm'; - case SDL_SCANCODE_N: return 'n'; - case SDL_SCANCODE_O: return 'o'; - case SDL_SCANCODE_P: return 'p'; - case SDL_SCANCODE_Q: return 'q'; - case SDL_SCANCODE_R: return 'r'; - case SDL_SCANCODE_S: return 's'; - case SDL_SCANCODE_T: return 't'; - case SDL_SCANCODE_U: return 'u'; - case SDL_SCANCODE_V: return 'v'; - case SDL_SCANCODE_W: return 'w'; - case SDL_SCANCODE_X: return 'x'; - case SDL_SCANCODE_Y: return 'y'; - case SDL_SCANCODE_Z: return 'z'; + case SDL_SCANCODE_A: return 'a'; + case SDL_SCANCODE_B: return 'b'; + case SDL_SCANCODE_C: return 'c'; + case SDL_SCANCODE_D: return 'd'; + case SDL_SCANCODE_E: return 'e'; + case SDL_SCANCODE_F: return 'f'; + case SDL_SCANCODE_G: return 'g'; + case SDL_SCANCODE_H: return 'h'; + case SDL_SCANCODE_I: return 'i'; + case SDL_SCANCODE_J: return 'j'; + case SDL_SCANCODE_K: return 'k'; + case SDL_SCANCODE_L: return 'l'; + case SDL_SCANCODE_M: return 'm'; + case SDL_SCANCODE_N: return 'n'; + case SDL_SCANCODE_O: return 'o'; + case SDL_SCANCODE_P: return 'p'; + case SDL_SCANCODE_Q: return 'q'; + case SDL_SCANCODE_R: return 'r'; + case SDL_SCANCODE_S: return 's'; + case SDL_SCANCODE_T: return 't'; + case SDL_SCANCODE_U: return 'u'; + case SDL_SCANCODE_V: return 'v'; + case SDL_SCANCODE_W: return 'w'; + case SDL_SCANCODE_X: return 'x'; + case SDL_SCANCODE_Y: return 'y'; + case SDL_SCANCODE_Z: return 'z'; - case SDL_SCANCODE_1: return '1'; - case SDL_SCANCODE_2: return '2'; - case SDL_SCANCODE_3: return '3'; - case SDL_SCANCODE_4: return '4'; - case SDL_SCANCODE_5: return '5'; - case SDL_SCANCODE_6: return '6'; - case SDL_SCANCODE_7: return '7'; - case SDL_SCANCODE_8: return '8'; - case SDL_SCANCODE_9: return '9'; - case SDL_SCANCODE_0: return '0'; + case SDL_SCANCODE_1: return '1'; + case SDL_SCANCODE_2: return '2'; + case SDL_SCANCODE_3: return '3'; + case SDL_SCANCODE_4: return '4'; + case SDL_SCANCODE_5: return '5'; + case SDL_SCANCODE_6: return '6'; + case SDL_SCANCODE_7: return '7'; + case SDL_SCANCODE_8: return '8'; + case SDL_SCANCODE_9: return '9'; + case SDL_SCANCODE_0: return '0'; - case SDL_SCANCODE_MINUS: return '-'; - case SDL_SCANCODE_EQUALS: return '='; - case SDL_SCANCODE_LEFTBRACKET: return '['; - case SDL_SCANCODE_RIGHTBRACKET: return ']'; - case SDL_SCANCODE_BACKSLASH: return '\\'; - case SDL_SCANCODE_NONUSHASH: return '#'; - case SDL_SCANCODE_SEMICOLON: return ';'; - case SDL_SCANCODE_APOSTROPHE: return '\''; - case SDL_SCANCODE_GRAVE: return '`'; - case SDL_SCANCODE_COMMA: return ','; - case SDL_SCANCODE_PERIOD: return '.'; - case SDL_SCANCODE_SLASH: return '/'; - case SDL_SCANCODE_NONUSBACKSLASH: return '\\'; + case SDL_SCANCODE_MINUS: return '-'; + case SDL_SCANCODE_EQUALS: return '='; + case SDL_SCANCODE_LEFTBRACKET: return '['; + case SDL_SCANCODE_RIGHTBRACKET: return ']'; + case SDL_SCANCODE_BACKSLASH: return '\\'; + case SDL_SCANCODE_NONUSHASH: return '#'; + case SDL_SCANCODE_SEMICOLON: return ';'; + case SDL_SCANCODE_APOSTROPHE: return '\''; + case SDL_SCANCODE_GRAVE: return '`'; + case SDL_SCANCODE_COMMA: return ','; + case SDL_SCANCODE_PERIOD: return '.'; + case SDL_SCANCODE_SLASH: return '/'; + case SDL_SCANCODE_NONUSBACKSLASH: return '\\'; - case SDL_SCANCODE_BACKSPACE: return K_BACKSPACE; - case SDL_SCANCODE_UP: return K_UPARROW; - case SDL_SCANCODE_DOWN: return K_DOWNARROW; - case SDL_SCANCODE_LEFT: return K_LEFTARROW; - case SDL_SCANCODE_RIGHT: return K_RIGHTARROW; + case SDL_SCANCODE_BACKSPACE: return K_BACKSPACE; + case SDL_SCANCODE_UP: return K_UPARROW; + case SDL_SCANCODE_DOWN: return K_DOWNARROW; + case SDL_SCANCODE_LEFT: return K_LEFTARROW; + case SDL_SCANCODE_RIGHT: return K_RIGHTARROW; - case SDL_SCANCODE_LALT: return K_ALT; - case SDL_SCANCODE_RALT: return K_ALT; - case SDL_SCANCODE_LCTRL: return K_CTRL; - case SDL_SCANCODE_RCTRL: return K_CTRL; - case SDL_SCANCODE_LSHIFT: return K_SHIFT; - case SDL_SCANCODE_RSHIFT: return K_SHIFT; + case SDL_SCANCODE_LALT: return K_ALT; + case SDL_SCANCODE_RALT: return K_ALT; + case SDL_SCANCODE_LCTRL: return K_CTRL; + case SDL_SCANCODE_RCTRL: return K_CTRL; + case SDL_SCANCODE_LSHIFT: return K_SHIFT; + case SDL_SCANCODE_RSHIFT: return K_SHIFT; - case SDL_SCANCODE_F1: return K_F1; - case SDL_SCANCODE_F2: return K_F2; - case SDL_SCANCODE_F3: return K_F3; - case SDL_SCANCODE_F4: return K_F4; - case SDL_SCANCODE_F5: return K_F5; - case SDL_SCANCODE_F6: return K_F6; - case SDL_SCANCODE_F7: return K_F7; - case SDL_SCANCODE_F8: return K_F8; - case SDL_SCANCODE_F9: return K_F9; - case SDL_SCANCODE_F10: return K_F10; - case SDL_SCANCODE_F11: return K_F11; - case SDL_SCANCODE_F12: return K_F12; - case SDL_SCANCODE_INSERT: return K_INS; - case SDL_SCANCODE_DELETE: return K_DEL; - case SDL_SCANCODE_PAGEDOWN: return K_PGDN; - case SDL_SCANCODE_PAGEUP: return K_PGUP; - case SDL_SCANCODE_HOME: return K_HOME; - case SDL_SCANCODE_END: return K_END; + case SDL_SCANCODE_F1: return K_F1; + case SDL_SCANCODE_F2: return K_F2; + case SDL_SCANCODE_F3: return K_F3; + case SDL_SCANCODE_F4: return K_F4; + case SDL_SCANCODE_F5: return K_F5; + case SDL_SCANCODE_F6: return K_F6; + case SDL_SCANCODE_F7: return K_F7; + case SDL_SCANCODE_F8: return K_F8; + case SDL_SCANCODE_F9: return K_F9; + case SDL_SCANCODE_F10: return K_F10; + case SDL_SCANCODE_F11: return K_F11; + case SDL_SCANCODE_F12: return K_F12; + case SDL_SCANCODE_INSERT: return K_INS; + case SDL_SCANCODE_DELETE: return K_DEL; + case SDL_SCANCODE_PAGEDOWN: return K_PGDN; + case SDL_SCANCODE_PAGEUP: return K_PGUP; + case SDL_SCANCODE_HOME: return K_HOME; + case SDL_SCANCODE_END: return K_END; - case SDL_SCANCODE_NUMLOCKCLEAR: return K_KP_NUMLOCK; - case SDL_SCANCODE_KP_DIVIDE: return K_KP_SLASH; - case SDL_SCANCODE_KP_MULTIPLY: return K_KP_STAR; - case SDL_SCANCODE_KP_MINUS: return K_KP_MINUS; - case SDL_SCANCODE_KP_7: return K_KP_HOME; - case SDL_SCANCODE_KP_8: return K_KP_UPARROW; - case SDL_SCANCODE_KP_9: return K_KP_PGUP; - case SDL_SCANCODE_KP_PLUS: return K_KP_PLUS; - case SDL_SCANCODE_KP_4: return K_KP_LEFTARROW; - case SDL_SCANCODE_KP_5: return K_KP_5; - case SDL_SCANCODE_KP_6: return K_KP_RIGHTARROW; - case SDL_SCANCODE_KP_1: return K_KP_END; - case SDL_SCANCODE_KP_2: return K_KP_DOWNARROW; - case SDL_SCANCODE_KP_3: return K_KP_PGDN; - case SDL_SCANCODE_KP_ENTER: return K_KP_ENTER; - case SDL_SCANCODE_KP_0: return K_KP_INS; - case SDL_SCANCODE_KP_PERIOD: return K_KP_DEL; + case SDL_SCANCODE_NUMLOCKCLEAR: return K_KP_NUMLOCK; + case SDL_SCANCODE_KP_DIVIDE: return K_KP_SLASH; + case SDL_SCANCODE_KP_MULTIPLY: return K_KP_STAR; + case SDL_SCANCODE_KP_MINUS: return K_KP_MINUS; + case SDL_SCANCODE_KP_7: return K_KP_HOME; + case SDL_SCANCODE_KP_8: return K_KP_UPARROW; + case SDL_SCANCODE_KP_9: return K_KP_PGUP; + case SDL_SCANCODE_KP_PLUS: return K_KP_PLUS; + case SDL_SCANCODE_KP_4: return K_KP_LEFTARROW; + case SDL_SCANCODE_KP_5: return K_KP_5; + case SDL_SCANCODE_KP_6: return K_KP_RIGHTARROW; + case SDL_SCANCODE_KP_1: return K_KP_END; + case SDL_SCANCODE_KP_2: return K_KP_DOWNARROW; + case SDL_SCANCODE_KP_3: return K_KP_PGDN; + case SDL_SCANCODE_KP_ENTER: return K_KP_ENTER; + case SDL_SCANCODE_KP_0: return K_KP_INS; + case SDL_SCANCODE_KP_PERIOD: return K_KP_DEL; - case SDL_SCANCODE_LGUI: return K_COMMAND; - case SDL_SCANCODE_RGUI: return K_COMMAND; + case SDL_SCANCODE_LGUI: return K_COMMAND; + case SDL_SCANCODE_RGUI: return K_COMMAND; - case SDL_SCANCODE_PAUSE: return K_PAUSE; + case SDL_SCANCODE_PAUSE: return K_PAUSE; - default: return 0; - } + default: return 0; + } } #endif #if defined(USE_SDL2) -static void IN_DebugTextEvent(SDL_Event *event) -{ - Con_Printf ("SDL_TEXTINPUT '%s' time: %g\n", event->text.text, Sys_DoubleTime()); +static void IN_DebugTextEvent(SDL_Event *event) { + Con_Printf("SDL_TEXTINPUT '%s' time: %g\n", event->text.text, Sys_DoubleTime()); } #endif -static void IN_DebugKeyEvent(SDL_Event *event) -{ - const char *eventtype = (event->key.state == SDL_PRESSED) ? "SDL_KEYDOWN" : "SDL_KEYUP"; +static void IN_DebugKeyEvent(SDL_Event *event) { + const char *eventtype = (event->key.state == SDL_PRESSED) ? "SDL_KEYDOWN" : "SDL_KEYUP"; #if defined(USE_SDL2) - Con_Printf ("%s scancode: '%s' keycode: '%s' time: %g\n", - eventtype, - SDL_GetScancodeName(event->key.keysym.scancode), - SDL_GetKeyName(event->key.keysym.sym), - Sys_DoubleTime()); + Con_Printf("%s scancode: '%s' keycode: '%s' time: %g\n", + eventtype, + SDL_GetScancodeName(event->key.keysym.scancode), + SDL_GetKeyName(event->key.keysym.sym), + Sys_DoubleTime()); #else - Con_Printf ("%s sym: '%s' unicode: %04x time: %g\n", - eventtype, - SDL_GetKeyName(event->key.keysym.sym), - (int)event->key.keysym.unicode, - Sys_DoubleTime()); + Con_Printf("%s sym: '%s' unicode: %04x time: %g\n", + eventtype, + SDL_GetKeyName(event->key.keysym.sym), + (int) event->key.keysym.unicode, + Sys_DoubleTime()); #endif } -void IN_SendKeyEvents (void) -{ - SDL_Event event; - int key; - qboolean down; +void IN_SendKeyEvents(void) { + SDL_Event event; + int key; + qboolean down; - while (SDL_PollEvent(&event)) - { - switch (event.type) - { + while (SDL_PollEvent(&event)) { + switch (event.type) { #if defined(USE_SDL2) - case SDL_WINDOWEVENT: - if (event.window.event == SDL_WINDOWEVENT_FOCUS_GAINED) - { - windowhasfocus = true; - S_UnblockSound(); - } - else if (event.window.event == SDL_WINDOWEVENT_FOCUS_LOST) - { - windowhasfocus = false; - S_BlockSound(); - } - break; + case SDL_WINDOWEVENT: + if (event.window.event == SDL_WINDOWEVENT_FOCUS_GAINED) { + windowhasfocus = true; + S_UnblockSound(); + } else if (event.window.event == SDL_WINDOWEVENT_FOCUS_LOST) { + windowhasfocus = false; + S_BlockSound(); + } + break; #else - case SDL_ACTIVEEVENT: - if (event.active.state & (SDL_APPINPUTFOCUS|SDL_APPACTIVE)) - { - if (event.active.gain) - { - windowhasfocus = true; - S_UnblockSound(); - } - else - { - windowhasfocus = false; - S_BlockSound(); - } - } - break; + case SDL_ACTIVEEVENT: + if (event.active.state & (SDL_APPINPUTFOCUS | SDL_APPACTIVE)) { + if (event.active.gain) { + windowhasfocus = true; + S_UnblockSound(); + } else { + windowhasfocus = false; + S_BlockSound(); + } + } + break; #endif #if defined(USE_SDL2) - case SDL_TEXTINPUT: - if (in_debugkeys.value) - IN_DebugTextEvent(&event); + case SDL_TEXTINPUT: + if (in_debugkeys.value) + IN_DebugTextEvent(&event); - // SDL2: We use SDL_TEXTINPUT for typing in the console / chat. - // SDL2 uses the local keyboard layout and handles modifiers - // (shift for uppercase, etc.) for us. - { - unsigned char *ch; - for (ch = (unsigned char *)event.text.text; *ch; ch++) - if ((*ch & ~0x7F) == 0) - Char_Event (*ch); - } - break; + // SDL2: We use SDL_TEXTINPUT for typing in the console / chat. + // SDL2 uses the local keyboard layout and handles modifiers + // (shift for uppercase, etc.) for us. + { + unsigned char *ch; + for (ch = (unsigned char *) event.text.text; *ch; ch++) + if ((*ch & ~0x7F) == 0) + Char_Event(*ch); + } + break; #endif - case SDL_KEYDOWN: - case SDL_KEYUP: - down = (event.key.state == SDL_PRESSED); + case SDL_KEYDOWN: + case SDL_KEYUP: + down = (event.key.state == SDL_PRESSED); - if (in_debugkeys.value) - IN_DebugKeyEvent(&event); + if (in_debugkeys.value) + IN_DebugKeyEvent(&event); #if defined(USE_SDL2) - // SDL2: we interpret the keyboard as the US layout, so keybindings - // are based on key position, not the label on the key cap. - key = IN_SDL2_ScancodeToQuakeKey(event.key.keysym.scancode); + // SDL2: we interpret the keyboard as the US layout, so keybindings + // are based on key position, not the label on the key cap. + key = IN_SDL2_ScancodeToQuakeKey(event.key.keysym.scancode); #else - key = IN_SDL_KeysymToQuakeKey(event.key.keysym.sym); + key = IN_SDL_KeysymToQuakeKey(event.key.keysym.sym); #endif - // also pass along the underlying keycode using the proper current layout for Y/N prompts. - Key_EventWithKeycode (key, down, event.key.keysym.sym); + // also pass along the underlying keycode using the proper current layout for Y/N prompts. + Key_EventWithKeycode(key, down, event.key.keysym.sym); #if !defined(USE_SDL2) - if (down && (event.key.keysym.unicode & ~0x7F) == 0) - Char_Event (event.key.keysym.unicode); + if (down && (event.key.keysym.unicode & ~0x7F) == 0) + Char_Event(event.key.keysym.unicode); #endif - break; + break; - case SDL_MOUSEBUTTONDOWN: - case SDL_MOUSEBUTTONUP: - if (event.button.button < 1 || - event.button.button > Q_COUNTOF(buttonremap)) - { - Con_Printf ("Ignored event for mouse button %d\n", - event.button.button); - break; - } - Key_Event(buttonremap[event.button.button - 1], event.button.state == SDL_PRESSED); - break; + case SDL_MOUSEBUTTONDOWN: + case SDL_MOUSEBUTTONUP: + if (event.button.button < 1 || + event.button.button > Q_COUNTOF(buttonremap)) { + Con_Printf("Ignored event for mouse button %d\n", + event.button.button); + break; + } + Key_Event(buttonremap[event.button.button - 1], event.button.state == SDL_PRESSED); + break; #if defined(USE_SDL2) - case SDL_MOUSEWHEEL: - if (event.wheel.y > 0) - { - Key_Event(K_MWHEELUP, true); - Key_Event(K_MWHEELUP, false); - } - else if (event.wheel.y < 0) - { - Key_Event(K_MWHEELDOWN, true); - Key_Event(K_MWHEELDOWN, false); - } - break; + case SDL_MOUSEWHEEL: + if (event.wheel.y > 0) { + Key_Event(K_MWHEELUP, true); + Key_Event(K_MWHEELUP, false); + } else if (event.wheel.y < 0) { + Key_Event(K_MWHEELDOWN, true); + Key_Event(K_MWHEELDOWN, false); + } + break; #endif - case SDL_MOUSEMOTION: - IN_MouseMotion(event.motion.xrel, event.motion.yrel); - break; + case SDL_MOUSEMOTION: + IN_MouseMotion(event.motion.xrel, event.motion.yrel); + break; #if defined(USE_SDL2) - case SDL_CONTROLLERDEVICEADDED: - if (joy_active_instaceid == -1) - { - joy_active_controller = SDL_GameControllerOpen(event.cdevice.which); - if (joy_active_controller == NULL) - Con_DPrintf("Couldn't open game controller\n"); - else - { - SDL_Joystick *joy; - joy = SDL_GameControllerGetJoystick(joy_active_controller); - joy_active_instaceid = SDL_JoystickInstanceID(joy); - } - } - else - Con_DPrintf("Ignoring SDL_CONTROLLERDEVICEADDED\n"); - break; - case SDL_CONTROLLERDEVICEREMOVED: - if (joy_active_instaceid != -1 && event.cdevice.which == joy_active_instaceid) - { - SDL_GameControllerClose(joy_active_controller); - joy_active_controller = NULL; - joy_active_instaceid = -1; - } - else - Con_DPrintf("Ignoring SDL_CONTROLLERDEVICEREMOVED\n"); - break; - case SDL_CONTROLLERDEVICEREMAPPED: - Con_DPrintf("Ignoring SDL_CONTROLLERDEVICEREMAPPED\n"); - break; + case SDL_CONTROLLERDEVICEADDED: + if (joy_active_instaceid == -1) { + joy_active_controller = SDL_GameControllerOpen(event.cdevice.which); + if (joy_active_controller == NULL) + Con_DPrintf("Couldn't open game controller\n"); + else { + SDL_Joystick *joy; + joy = SDL_GameControllerGetJoystick(joy_active_controller); + joy_active_instaceid = SDL_JoystickInstanceID(joy); + } + } else + Con_DPrintf("Ignoring SDL_CONTROLLERDEVICEADDED\n"); + break; + case SDL_CONTROLLERDEVICEREMOVED: + if (joy_active_instaceid != -1 && event.cdevice.which == joy_active_instaceid) { + SDL_GameControllerClose(joy_active_controller); + joy_active_controller = NULL; + joy_active_instaceid = -1; + } else + Con_DPrintf("Ignoring SDL_CONTROLLERDEVICEREMOVED\n"); + break; + case SDL_CONTROLLERDEVICEREMAPPED: + Con_DPrintf("Ignoring SDL_CONTROLLERDEVICEREMAPPED\n"); + break; #endif - - case SDL_QUIT: - CL_Disconnect (); - Sys_Quit (); - break; - default: - break; - } - } + case SDL_QUIT: + CL_Disconnect(); + Sys_Quit(); + break; + + default: + break; + } + } } - diff --git a/Quake/keys.cpp b/Quake/keys.cpp index 2a5e076..78e42db 100644 --- a/Quake/keys.cpp +++ b/Quake/keys.cpp @@ -628,6 +628,7 @@ void Key_SetBinding (int keynum, const char *binding) // allocate memory for new binding if (binding) keybindings[keynum] = Z_Strdup(binding); + printf("%d is now %s\n", keynum, keybindings[keynum]); } /* @@ -639,16 +640,16 @@ void Key_Unbind_f (void) { int b; - if (Cmd_Argc() != 2) + if (command::argc() != 2) { Con_Printf ("unbind : remove commands from a key\n"); return; } - b = Key_StringToKeynum (Cmd_Argv(1)); + b = Key_StringToKeynum (command::argv(1)->c_str()); if (b == -1) { - Con_Printf ("\"%s\" isn't a valid key\n", Cmd_Argv(1)); + Con_Printf ("\"%s\" isn't a valid key\n", command::argv(1)->c_str()); return; } @@ -697,26 +698,26 @@ void Key_Bind_f (void) int i, c, b; char cmd[1024]; - c = Cmd_Argc(); + c = command::argc(); if (c != 2 && c != 3) { Con_Printf ("bind [command] : attach a command to a key\n"); return; } - b = Key_StringToKeynum (Cmd_Argv(1)); + b = Key_StringToKeynum (command::argv(1)->c_str()); if (b == -1) { - Con_Printf ("\"%s\" isn't a valid key\n", Cmd_Argv(1)); + Con_Printf ("\"%s\" isn't a valid key\n", command::argv(1)->c_str()); return; } if (c == 2) { if (keybindings[b]) - Con_Printf ("\"%s\" = \"%s\"\n", Cmd_Argv(1), keybindings[b] ); + Con_Printf ("\"%s\" = \"%s\"\n", command::argv(1)->c_str(), keybindings[b] ); else - Con_Printf ("\"%s\" is not bound\n", Cmd_Argv(1) ); + Con_Printf ("\"%s\" is not bound\n", command::argv(1)->c_str() ); return; } @@ -724,7 +725,7 @@ void Key_Bind_f (void) cmd[0] = 0; for (i = 2; i < c; i++) { - q_strlcat (cmd, Cmd_Argv(i), sizeof(cmd)); + q_strlcat (cmd, command::argv(i)->c_str(), sizeof(cmd)); if (i != (c-1)) q_strlcat (cmd, " ", sizeof(cmd)); } @@ -890,10 +891,10 @@ void Key_Init (void) // // register our functions // - Cmd_AddCommand ("bindlist",Key_Bindlist_f); //johnfitz - Cmd_AddCommand ("bind",Key_Bind_f); - Cmd_AddCommand ("unbind",Key_Unbind_f); - Cmd_AddCommand ("unbindall",Key_Unbindall_f); + command::add ("bindlist",Key_Bindlist_f); //johnfitz + command::add ("bind",Key_Bind_f); + command::add ("unbind",Key_Unbind_f); + command::add ("unbindall",Key_Unbindall_f); } static struct { diff --git a/Quake/menu.cpp b/Quake/menu.cpp index 0d746e7..1c71445 100644 --- a/Quake/menu.cpp +++ b/Quake/menu.cpp @@ -25,68 +25,114 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. void (*vid_menucmdfn)(void); //johnfitz void (*vid_menudrawfn)(void); + void (*vid_menukeyfn)(int key); enum m_state_e m_state; -void M_Menu_Main_f (void); - void M_Menu_SinglePlayer_f (void); - void M_Menu_Load_f (void); - void M_Menu_Save_f (void); - void M_Menu_MultiPlayer_f (void); - void M_Menu_Setup_f (void); - void M_Menu_Net_f (void); - void M_Menu_LanConfig_f (void); - void M_Menu_GameOptions_f (void); - void M_Menu_Search_f (void); - void M_Menu_ServerList_f (void); - void M_Menu_Options_f (void); - void M_Menu_Keys_f (void); - void M_Menu_Video_f (void); - void M_Menu_Help_f (void); - void M_Menu_Quit_f (void); +void M_Menu_Main_f(void); -void M_Main_Draw (void); - void M_SinglePlayer_Draw (void); - void M_Load_Draw (void); - void M_Save_Draw (void); - void M_MultiPlayer_Draw (void); - void M_Setup_Draw (void); - void M_Net_Draw (void); - void M_LanConfig_Draw (void); - void M_GameOptions_Draw (void); - void M_Search_Draw (void); - void M_ServerList_Draw (void); - void M_Options_Draw (void); - void M_Keys_Draw (void); - void M_Video_Draw (void); - void M_Help_Draw (void); - void M_Quit_Draw (void); +void M_Menu_SinglePlayer_f(void); -void M_Main_Key (int key); - void M_SinglePlayer_Key (int key); - void M_Load_Key (int key); - void M_Save_Key (int key); - void M_MultiPlayer_Key (int key); - void M_Setup_Key (int key); - void M_Net_Key (int key); - void M_LanConfig_Key (int key); - void M_GameOptions_Key (int key); - void M_Search_Key (int key); - void M_ServerList_Key (int key); - void M_Options_Key (int key); - void M_Keys_Key (int key); - void M_Video_Key (int key); - void M_Help_Key (int key); - void M_Quit_Key (int key); +void M_Menu_Load_f(void); -qboolean m_entersound; // play after drawing a frame, so caching - // won't disrupt the sound -qboolean m_recursiveDraw; +void M_Menu_Save_f(void); -enum m_state_e m_return_state; -qboolean m_return_onerror; -char m_return_reason [32]; +void M_Menu_MultiPlayer_f(void); + +void M_Menu_Setup_f(void); + +void M_Menu_Net_f(void); + +void M_Menu_LanConfig_f(void); + +void M_Menu_GameOptions_f(void); + +void M_Menu_Search_f(void); + +void M_Menu_ServerList_f(void); + +void M_Menu_Options_f(void); + +void M_Menu_Keys_f(void); + +void M_Menu_Video_f(void); + +void M_Menu_Help_f(void); + +void M_Menu_Quit_f(void); + +void M_Main_Draw(void); + +void M_SinglePlayer_Draw(void); + +void M_Load_Draw(void); + +void M_Save_Draw(void); + +void M_MultiPlayer_Draw(void); + +void M_Setup_Draw(void); + +void M_Net_Draw(void); + +void M_LanConfig_Draw(void); + +void M_GameOptions_Draw(void); + +void M_Search_Draw(void); + +void M_ServerList_Draw(void); + +void M_Options_Draw(void); + +void M_Keys_Draw(void); + +void M_Video_Draw(void); + +void M_Help_Draw(void); + +void M_Quit_Draw(void); + +void M_Main_Key(int key); + +void M_SinglePlayer_Key(int key); + +void M_Load_Key(int key); + +void M_Save_Key(int key); + +void M_MultiPlayer_Key(int key); + +void M_Setup_Key(int key); + +void M_Net_Key(int key); + +void M_LanConfig_Key(int key); + +void M_GameOptions_Key(int key); + +void M_Search_Key(int key); + +void M_ServerList_Key(int key); + +void M_Options_Key(int key); + +void M_Keys_Key(int key); + +void M_Video_Key(int key); + +void M_Help_Key(int key); + +void M_Quit_Key(int key); + +qboolean m_entersound; // play after drawing a frame, so caching +// won't disrupt the sound +qboolean m_recursiveDraw; + +enum m_state_e m_return_state; +qboolean m_return_onerror; +char m_return_reason[32]; #define StartingGame (m_multiplayer_cursor == 1) #define JoiningGame (m_multiplayer_cursor == 0) @@ -102,99 +148,87 @@ M_DrawCharacter Draws one solid graphics character ================ */ -void M_DrawCharacter (int cx, int line, int num) -{ - Draw_Character (cx, line, num); +void M_DrawCharacter(int cx, int line, int num) { + Draw_Character(cx, line, num); } -void M_Print (int cx, int cy, const char *str) -{ - while (*str) - { - M_DrawCharacter (cx, cy, (*str)+128); - str++; - cx += 8; - } +void M_Print(int cx, int cy, const char *str) { + while (*str) { + M_DrawCharacter(cx, cy, (*str) + 128); + str++; + cx += 8; + } } -void M_PrintWhite (int cx, int cy, const char *str) -{ - while (*str) - { - M_DrawCharacter (cx, cy, *str); - str++; - cx += 8; - } +void M_PrintWhite(int cx, int cy, const char *str) { + while (*str) { + M_DrawCharacter(cx, cy, *str); + str++; + cx += 8; + } } -void M_DrawTransPic (int x, int y, qpic_t *pic) -{ - Draw_Pic (x, y, pic); //johnfitz -- simplified becuase centering is handled elsewhere +void M_DrawTransPic(int x, int y, qpic_t *pic) { + Draw_Pic(x, y, pic); //johnfitz -- simplified becuase centering is handled elsewhere } -void M_DrawPic (int x, int y, qpic_t *pic) -{ - Draw_Pic (x, y, pic); //johnfitz -- simplified becuase centering is handled elsewhere +void M_DrawPic(int x, int y, qpic_t *pic) { + Draw_Pic(x, y, pic); //johnfitz -- simplified becuase centering is handled elsewhere } -void M_DrawTransPicTranslate (int x, int y, qpic_t *pic, int top, int bottom) //johnfitz -- more parameters +void M_DrawTransPicTranslate(int x, int y, qpic_t *pic, int top, int bottom) //johnfitz -- more parameters { - Draw_TransPicTranslate (x, y, pic, top, bottom); //johnfitz -- simplified becuase centering is handled elsewhere + Draw_TransPicTranslate(x, y, pic, top, bottom); //johnfitz -- simplified becuase centering is handled elsewhere } -void M_DrawTextBox (int x, int y, int width, int lines) -{ - qpic_t *p; - int cx, cy; - int n; +void M_DrawTextBox(int x, int y, int width, int lines) { + qpic_t *p; + int cx, cy; + int n; - // draw left side - cx = x; - cy = y; - p = Draw_CachePic ("gfx/box_tl.lmp"); - M_DrawTransPic (cx, cy, p); - p = Draw_CachePic ("gfx/box_ml.lmp"); - for (n = 0; n < lines; n++) - { - cy += 8; - M_DrawTransPic (cx, cy, p); - } - p = Draw_CachePic ("gfx/box_bl.lmp"); - M_DrawTransPic (cx, cy+8, p); + // draw left side + cx = x; + cy = y; + p = Draw_CachePic("gfx/box_tl.lmp"); + M_DrawTransPic(cx, cy, p); + p = Draw_CachePic("gfx/box_ml.lmp"); + for (n = 0; n < lines; n++) { + cy += 8; + M_DrawTransPic(cx, cy, p); + } + p = Draw_CachePic("gfx/box_bl.lmp"); + M_DrawTransPic(cx, cy + 8, p); - // draw middle - cx += 8; - while (width > 0) - { - cy = y; - p = Draw_CachePic ("gfx/box_tm.lmp"); - M_DrawTransPic (cx, cy, p); - p = Draw_CachePic ("gfx/box_mm.lmp"); - for (n = 0; n < lines; n++) - { - cy += 8; - if (n == 1) - p = Draw_CachePic ("gfx/box_mm2.lmp"); - M_DrawTransPic (cx, cy, p); - } - p = Draw_CachePic ("gfx/box_bm.lmp"); - M_DrawTransPic (cx, cy+8, p); - width -= 2; - cx += 16; - } + // draw middle + cx += 8; + while (width > 0) { + cy = y; + p = Draw_CachePic("gfx/box_tm.lmp"); + M_DrawTransPic(cx, cy, p); + p = Draw_CachePic("gfx/box_mm.lmp"); + for (n = 0; n < lines; n++) { + cy += 8; + if (n == 1) + p = Draw_CachePic("gfx/box_mm2.lmp"); + M_DrawTransPic(cx, cy, p); + } + p = Draw_CachePic("gfx/box_bm.lmp"); + M_DrawTransPic(cx, cy + 8, p); + width -= 2; + cx += 16; + } - // draw right side - cy = y; - p = Draw_CachePic ("gfx/box_tr.lmp"); - M_DrawTransPic (cx, cy, p); - p = Draw_CachePic ("gfx/box_mr.lmp"); - for (n = 0; n < lines; n++) - { - cy += 8; - M_DrawTransPic (cx, cy, p); - } - p = Draw_CachePic ("gfx/box_br.lmp"); - M_DrawTransPic (cx, cy+8, p); + // draw right side + cy = y; + p = Draw_CachePic("gfx/box_tr.lmp"); + M_DrawTransPic(cx, cy, p); + p = Draw_CachePic("gfx/box_mr.lmp"); + for (n = 0; n < lines; n++) { + cy += 8; + M_DrawTransPic(cx, cy, p); + } + p = Draw_CachePic("gfx/box_br.lmp"); + M_DrawTransPic(cx, cy + 8, p); } //============================================================================= @@ -206,1134 +240,1071 @@ int m_save_demonum; M_ToggleMenu_f ================ */ -void M_ToggleMenu_f (void) -{ - m_entersound = true; +void M_ToggleMenu_f(void) { + m_entersound = true; - if (key_dest == key_menu) - { - if (m_state != m_main) - { - M_Menu_Main_f (); - return; - } + if (key_dest == key_menu) { + if (m_state != m_main) { + M_Menu_Main_f(); + return; + } - IN_Activate(); - key_dest = key_game; - m_state = m_none; - return; - } - if (key_dest == key_console) - { - Con_ToggleConsole_f (); - } - else - { - M_Menu_Main_f (); - } + IN_Activate(); + key_dest = key_game; + m_state = m_none; + return; + } + if (key_dest == key_console) { + Con_ToggleConsole_f(); + } else { + M_Menu_Main_f(); + } } //============================================================================= /* MAIN MENU */ -int m_main_cursor; +int m_main_cursor; #define MAIN_ITEMS 5 -void M_Menu_Main_f (void) -{ - if (key_dest != key_menu) - { - m_save_demonum = cls.demonum; - cls.demonum = -1; - } - IN_Deactivate(modestate == MS_WINDOWED); - key_dest = key_menu; - m_state = m_main; - m_entersound = true; +void M_Menu_Main_f(void) { + if (key_dest != key_menu) { + m_save_demonum = cls.demonum; + cls.demonum = -1; + } + IN_Deactivate(modestate == MS_WINDOWED); + key_dest = key_menu; + m_state = m_main; + m_entersound = true; } -void M_Main_Draw (void) -{ - int f; - qpic_t *p; +void M_Main_Draw(void) { + int f; + qpic_t *p; - M_DrawTransPic (16, 4, Draw_CachePic ("gfx/qplaque.lmp") ); - p = Draw_CachePic ("gfx/ttl_main.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); - M_DrawTransPic (72, 32, Draw_CachePic ("gfx/mainmenu.lmp") ); + M_DrawTransPic(16, 4, Draw_CachePic("gfx/qplaque.lmp")); + p = Draw_CachePic("gfx/ttl_main.lmp"); + M_DrawPic((320 - p->width) / 2, 4, p); + M_DrawTransPic(72, 32, Draw_CachePic("gfx/mainmenu.lmp")); - f = (int)(realtime * 10)%6; + f = (int) (realtime * 10) % 6; - M_DrawTransPic (54, 32 + m_main_cursor * 20,Draw_CachePic( va("gfx/menudot%i.lmp", f+1 ) ) ); + M_DrawTransPic(54, 32 + m_main_cursor * 20, Draw_CachePic(va("gfx/menudot%i.lmp", f + 1))); } -void M_Main_Key (int key) -{ - switch (key) - { - case K_ESCAPE: - case K_BBUTTON: - IN_Activate(); - key_dest = key_game; - m_state = m_none; - cls.demonum = m_save_demonum; - if (!fitzmode && !cl_startdemos.value) /* QuakeSpasm customization: */ - break; - if (cls.demonum != -1 && !cls.demoplayback && cls.state != ca_connected) - CL_NextDemo (); - break; +void M_Main_Key(int key) { + switch (key) { + case K_ESCAPE: + case K_BBUTTON: + IN_Activate(); + key_dest = key_game; + m_state = m_none; + cls.demonum = m_save_demonum; + if (!fitzmode && !cl_startdemos.value) /* QuakeSpasm customization: */ + break; + if (cls.demonum != -1 && !cls.demoplayback && cls.state != ca_connected) + CL_NextDemo(); + break; - case K_DOWNARROW: - S_LocalSound ("misc/menu1.wav"); - if (++m_main_cursor >= MAIN_ITEMS) - m_main_cursor = 0; - break; + case K_DOWNARROW: + S_LocalSound("misc/menu1.wav"); + if (++m_main_cursor >= MAIN_ITEMS) + m_main_cursor = 0; + break; - case K_UPARROW: - S_LocalSound ("misc/menu1.wav"); - if (--m_main_cursor < 0) - m_main_cursor = MAIN_ITEMS - 1; - break; + case K_UPARROW: + S_LocalSound("misc/menu1.wav"); + if (--m_main_cursor < 0) + m_main_cursor = MAIN_ITEMS - 1; + break; - case K_ENTER: - case K_KP_ENTER: - case K_ABUTTON: - m_entersound = true; + case K_ENTER: + case K_KP_ENTER: + case K_ABUTTON: + m_entersound = true; - switch (m_main_cursor) - { - case 0: - M_Menu_SinglePlayer_f (); - break; + switch (m_main_cursor) { + case 0: + M_Menu_SinglePlayer_f(); + break; - case 1: - M_Menu_MultiPlayer_f (); - break; + case 1: + M_Menu_MultiPlayer_f(); + break; - case 2: - M_Menu_Options_f (); - break; + case 2: + M_Menu_Options_f(); + break; - case 3: - M_Menu_Help_f (); - break; + case 3: + M_Menu_Help_f(); + break; - case 4: - M_Menu_Quit_f (); - break; - } - } + case 4: + M_Menu_Quit_f(); + break; + } + } } //============================================================================= /* SINGLE PLAYER MENU */ -int m_singleplayer_cursor; +int m_singleplayer_cursor; #define SINGLEPLAYER_ITEMS 3 -void M_Menu_SinglePlayer_f (void) -{ - IN_Deactivate(modestate == MS_WINDOWED); - key_dest = key_menu; - m_state = m_singleplayer; - m_entersound = true; +void M_Menu_SinglePlayer_f(void) { + IN_Deactivate(modestate == MS_WINDOWED); + key_dest = key_menu; + m_state = m_singleplayer; + m_entersound = true; } -void M_SinglePlayer_Draw (void) -{ - int f; - qpic_t *p; +void M_SinglePlayer_Draw(void) { + int f; + qpic_t *p; - M_DrawTransPic (16, 4, Draw_CachePic ("gfx/qplaque.lmp") ); - p = Draw_CachePic ("gfx/ttl_sgl.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); - M_DrawTransPic (72, 32, Draw_CachePic ("gfx/sp_menu.lmp") ); + M_DrawTransPic(16, 4, Draw_CachePic("gfx/qplaque.lmp")); + p = Draw_CachePic("gfx/ttl_sgl.lmp"); + M_DrawPic((320 - p->width) / 2, 4, p); + M_DrawTransPic(72, 32, Draw_CachePic("gfx/sp_menu.lmp")); - f = (int)(realtime * 10)%6; + f = (int) (realtime * 10) % 6; - M_DrawTransPic (54, 32 + m_singleplayer_cursor * 20,Draw_CachePic( va("gfx/menudot%i.lmp", f+1 ) ) ); + M_DrawTransPic(54, 32 + m_singleplayer_cursor * 20, Draw_CachePic(va("gfx/menudot%i.lmp", f + 1))); } -void M_SinglePlayer_Key (int key) -{ - switch (key) - { - case K_ESCAPE: - case K_BBUTTON: - M_Menu_Main_f (); - break; +void M_SinglePlayer_Key(int key) { + switch (key) { + case K_ESCAPE: + case K_BBUTTON: + M_Menu_Main_f(); + break; - case K_DOWNARROW: - S_LocalSound ("misc/menu1.wav"); - if (++m_singleplayer_cursor >= SINGLEPLAYER_ITEMS) - m_singleplayer_cursor = 0; - break; + case K_DOWNARROW: + S_LocalSound("misc/menu1.wav"); + if (++m_singleplayer_cursor >= SINGLEPLAYER_ITEMS) + m_singleplayer_cursor = 0; + break; - case K_UPARROW: - S_LocalSound ("misc/menu1.wav"); - if (--m_singleplayer_cursor < 0) - m_singleplayer_cursor = SINGLEPLAYER_ITEMS - 1; - break; + case K_UPARROW: + S_LocalSound("misc/menu1.wav"); + if (--m_singleplayer_cursor < 0) + m_singleplayer_cursor = SINGLEPLAYER_ITEMS - 1; + break; - case K_ENTER: - case K_KP_ENTER: - case K_ABUTTON: - m_entersound = true; + case K_ENTER: + case K_KP_ENTER: + case K_ABUTTON: + m_entersound = true; - switch (m_singleplayer_cursor) - { - case 0: - if (sv.active) - if (!SCR_ModalMessage("Are you sure you want to\nstart a new game? (y/n)\n", 0.0f)) - break; - IN_Activate(); - key_dest = key_game; - if (sv.active) - Cbuf_AddText ("disconnect\n"); - Cbuf_AddText ("maxplayers 1\n"); - Cbuf_AddText ("deathmatch 0\n"); //johnfitz - Cbuf_AddText ("coop 0\n"); //johnfitz - Cbuf_AddText ("map start\n"); - break; + switch (m_singleplayer_cursor) { + case 0: + if (sv.active) + if (!SCR_ModalMessage("Are you sure you want to\nstart a new game? (y/n)\n", 0.0f)) + break; + IN_Activate(); + key_dest = key_game; + if (sv.active) + Cbuf_AddText("disconnect\n"); + Cbuf_AddText("maxplayers 1\n"); + Cbuf_AddText("deathmatch 0\n"); //johnfitz + Cbuf_AddText("coop 0\n"); //johnfitz + Cbuf_AddText("map start\n"); + break; - case 1: - M_Menu_Load_f (); - break; + case 1: + M_Menu_Load_f(); + break; - case 2: - M_Menu_Save_f (); - break; - } - } + case 2: + M_Menu_Save_f(); + break; + } + } } //============================================================================= /* LOAD/SAVE MENU */ -int load_cursor; // 0 < load_cursor < MAX_SAVEGAMES +int load_cursor; // 0 < load_cursor < MAX_SAVEGAMES #define MAX_SAVEGAMES 20 /* johnfitz -- increased from 12 */ -char m_filenames[MAX_SAVEGAMES][SAVEGAME_COMMENT_LENGTH+1]; -int loadable[MAX_SAVEGAMES]; +char m_filenames[MAX_SAVEGAMES][SAVEGAME_COMMENT_LENGTH + 1]; +int loadable[MAX_SAVEGAMES]; -void M_ScanSaves (void) -{ - int i, j; - char name[MAX_OSPATH]; - FILE *f; - int version; +void M_ScanSaves(void) { + int i, j; + char name[MAX_OSPATH]; + FILE *f; + int version; - for (i = 0; i < MAX_SAVEGAMES; i++) - { - strcpy (m_filenames[i], "--- UNUSED SLOT ---"); - loadable[i] = false; - q_snprintf (name, sizeof(name), "%s/s%i.sav", com_gamedir, i); - f = fopen (name, "r"); - if (!f) { - continue; - } - if (fscanf(f, "%i\n", &version) != 1 || - fscanf(f, "%79s\n", name) != 1) { - fclose(f); - continue; - } - q_strlcpy (m_filenames[i], name, SAVEGAME_COMMENT_LENGTH+1); + for (i = 0; i < MAX_SAVEGAMES; i++) { + strcpy(m_filenames[i], "--- UNUSED SLOT ---"); + loadable[i] = false; + q_snprintf(name, sizeof(name), "%s/s%i.sav", com_gamedir, i); + f = fopen(name, "r"); + if (!f) { + continue; + } + if (fscanf(f, "%i\n", &version) != 1 || + fscanf(f, "%79s\n", name) != 1) { + fclose(f); + continue; + } + q_strlcpy(m_filenames[i], name, SAVEGAME_COMMENT_LENGTH + 1); - // change _ back to space - for (j = 0; j < SAVEGAME_COMMENT_LENGTH; j++) - { - if (m_filenames[i][j] == '_') - m_filenames[i][j] = ' '; - } - loadable[i] = true; - fclose (f); - } + // change _ back to space + for (j = 0; j < SAVEGAME_COMMENT_LENGTH; j++) { + if (m_filenames[i][j] == '_') + m_filenames[i][j] = ' '; + } + loadable[i] = true; + fclose(f); + } } -void M_Menu_Load_f (void) -{ - m_entersound = true; - m_state = m_load; +void M_Menu_Load_f(void) { + m_entersound = true; + m_state = m_load; - IN_Deactivate(modestate == MS_WINDOWED); - key_dest = key_menu; - M_ScanSaves (); + IN_Deactivate(modestate == MS_WINDOWED); + key_dest = key_menu; + M_ScanSaves(); } -void M_Menu_Save_f (void) -{ - if (!sv.active) - return; - if (cl.intermission) - return; - if (svs.maxclients != 1) - return; - m_entersound = true; - m_state = m_save; +void M_Menu_Save_f(void) { + if (!sv.active) + return; + if (cl.intermission) + return; + if (svs.maxclients != 1) + return; + m_entersound = true; + m_state = m_save; - IN_Deactivate(modestate == MS_WINDOWED); - key_dest = key_menu; - M_ScanSaves (); + IN_Deactivate(modestate == MS_WINDOWED); + key_dest = key_menu; + M_ScanSaves(); } -void M_Load_Draw (void) -{ - int i; - qpic_t *p; +void M_Load_Draw(void) { + int i; + qpic_t *p; - p = Draw_CachePic ("gfx/p_load.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); + p = Draw_CachePic("gfx/p_load.lmp"); + M_DrawPic((320 - p->width) / 2, 4, p); - for (i = 0; i < MAX_SAVEGAMES; i++) - M_Print (16, 32 + 8*i, m_filenames[i]); + for (i = 0; i < MAX_SAVEGAMES; i++) + M_Print(16, 32 + 8 * i, m_filenames[i]); -// line cursor - M_DrawCharacter (8, 32 + load_cursor*8, 12+((int)(realtime*4)&1)); + // line cursor + M_DrawCharacter(8, 32 + load_cursor * 8, 12 + ((int) (realtime * 4) & 1)); } -void M_Save_Draw (void) -{ - int i; - qpic_t *p; +void M_Save_Draw(void) { + int i; + qpic_t *p; - p = Draw_CachePic ("gfx/p_save.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); + p = Draw_CachePic("gfx/p_save.lmp"); + M_DrawPic((320 - p->width) / 2, 4, p); - for (i = 0; i < MAX_SAVEGAMES; i++) - M_Print (16, 32 + 8*i, m_filenames[i]); + for (i = 0; i < MAX_SAVEGAMES; i++) + M_Print(16, 32 + 8 * i, m_filenames[i]); -// line cursor - M_DrawCharacter (8, 32 + load_cursor*8, 12+((int)(realtime*4)&1)); + // line cursor + M_DrawCharacter(8, 32 + load_cursor * 8, 12 + ((int) (realtime * 4) & 1)); } -void M_Load_Key (int k) -{ - switch (k) - { - case K_ESCAPE: - case K_BBUTTON: - M_Menu_SinglePlayer_f (); - break; +void M_Load_Key(int k) { + switch (k) { + case K_ESCAPE: + case K_BBUTTON: + M_Menu_SinglePlayer_f(); + break; - case K_ENTER: - case K_KP_ENTER: - case K_ABUTTON: - S_LocalSound ("misc/menu2.wav"); - if (!loadable[load_cursor]) - return; - m_state = m_none; - key_dest = key_game; + case K_ENTER: + case K_KP_ENTER: + case K_ABUTTON: + S_LocalSound("misc/menu2.wav"); + if (!loadable[load_cursor]) + return; + m_state = m_none; + key_dest = key_game; - // Host_Loadgame_f can't bring up the loading plaque because too much - // stack space has been used, so do it now - SCR_BeginLoadingPlaque (); + // Host_Loadgame_f can't bring up the loading plaque because too much + // stack space has been used, so do it now + SCR_BeginLoadingPlaque(); - // issue the load command - Cbuf_AddText (va ("load s%i\n", load_cursor) ); - return; + // issue the load command + Cbuf_AddText(va("load s%i\n", load_cursor)); + return; - case K_UPARROW: - case K_LEFTARROW: - S_LocalSound ("misc/menu1.wav"); - load_cursor--; - if (load_cursor < 0) - load_cursor = MAX_SAVEGAMES-1; - break; + case K_UPARROW: + case K_LEFTARROW: + S_LocalSound("misc/menu1.wav"); + load_cursor--; + if (load_cursor < 0) + load_cursor = MAX_SAVEGAMES - 1; + break; - case K_DOWNARROW: - case K_RIGHTARROW: - S_LocalSound ("misc/menu1.wav"); - load_cursor++; - if (load_cursor >= MAX_SAVEGAMES) - load_cursor = 0; - break; - } + case K_DOWNARROW: + case K_RIGHTARROW: + S_LocalSound("misc/menu1.wav"); + load_cursor++; + if (load_cursor >= MAX_SAVEGAMES) + load_cursor = 0; + break; + } } -void M_Save_Key (int k) -{ - switch (k) - { - case K_ESCAPE: - case K_BBUTTON: - M_Menu_SinglePlayer_f (); - break; +void M_Save_Key(int k) { + switch (k) { + case K_ESCAPE: + case K_BBUTTON: + M_Menu_SinglePlayer_f(); + break; - case K_ENTER: - case K_KP_ENTER: - case K_ABUTTON: - m_state = m_none; - IN_Activate(); - key_dest = key_game; - Cbuf_AddText (va("save s%i\n", load_cursor)); - return; + case K_ENTER: + case K_KP_ENTER: + case K_ABUTTON: + m_state = m_none; + IN_Activate(); + key_dest = key_game; + Cbuf_AddText(va("save s%i\n", load_cursor)); + return; - case K_UPARROW: - case K_LEFTARROW: - S_LocalSound ("misc/menu1.wav"); - load_cursor--; - if (load_cursor < 0) - load_cursor = MAX_SAVEGAMES-1; - break; + case K_UPARROW: + case K_LEFTARROW: + S_LocalSound("misc/menu1.wav"); + load_cursor--; + if (load_cursor < 0) + load_cursor = MAX_SAVEGAMES - 1; + break; - case K_DOWNARROW: - case K_RIGHTARROW: - S_LocalSound ("misc/menu1.wav"); - load_cursor++; - if (load_cursor >= MAX_SAVEGAMES) - load_cursor = 0; - break; - } + case K_DOWNARROW: + case K_RIGHTARROW: + S_LocalSound("misc/menu1.wav"); + load_cursor++; + if (load_cursor >= MAX_SAVEGAMES) + load_cursor = 0; + break; + } } //============================================================================= /* MULTIPLAYER MENU */ -int m_multiplayer_cursor; +int m_multiplayer_cursor; #define MULTIPLAYER_ITEMS 3 -void M_Menu_MultiPlayer_f (void) -{ - IN_Deactivate(modestate == MS_WINDOWED); - key_dest = key_menu; - m_state = m_multiplayer; - m_entersound = true; +void M_Menu_MultiPlayer_f(void) { + IN_Deactivate(modestate == MS_WINDOWED); + key_dest = key_menu; + m_state = m_multiplayer; + m_entersound = true; } -void M_MultiPlayer_Draw (void) -{ - int f; - qpic_t *p; +void M_MultiPlayer_Draw(void) { + int f; + qpic_t *p; - M_DrawTransPic (16, 4, Draw_CachePic ("gfx/qplaque.lmp") ); - p = Draw_CachePic ("gfx/p_multi.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); - M_DrawTransPic (72, 32, Draw_CachePic ("gfx/mp_menu.lmp") ); + M_DrawTransPic(16, 4, Draw_CachePic("gfx/qplaque.lmp")); + p = Draw_CachePic("gfx/p_multi.lmp"); + M_DrawPic((320 - p->width) / 2, 4, p); + M_DrawTransPic(72, 32, Draw_CachePic("gfx/mp_menu.lmp")); - f = (int)(realtime * 10)%6; + f = (int) (realtime * 10) % 6; - M_DrawTransPic (54, 32 + m_multiplayer_cursor * 20,Draw_CachePic( va("gfx/menudot%i.lmp", f+1 ) ) ); + M_DrawTransPic(54, 32 + m_multiplayer_cursor * 20, Draw_CachePic(va("gfx/menudot%i.lmp", f + 1))); - if (ipxAvailable || tcpipAvailable) - return; - M_PrintWhite ((320/2) - ((27*8)/2), 148, "No Communications Available"); + if (ipxAvailable || tcpipAvailable) + return; + M_PrintWhite((320 / 2) - ((27 * 8) / 2), 148, "No Communications Available"); } -void M_MultiPlayer_Key (int key) -{ - switch (key) - { - case K_ESCAPE: - case K_BBUTTON: - M_Menu_Main_f (); - break; +void M_MultiPlayer_Key(int key) { + switch (key) { + case K_ESCAPE: + case K_BBUTTON: + M_Menu_Main_f(); + break; - case K_DOWNARROW: - S_LocalSound ("misc/menu1.wav"); - if (++m_multiplayer_cursor >= MULTIPLAYER_ITEMS) - m_multiplayer_cursor = 0; - break; + case K_DOWNARROW: + S_LocalSound("misc/menu1.wav"); + if (++m_multiplayer_cursor >= MULTIPLAYER_ITEMS) + m_multiplayer_cursor = 0; + break; - case K_UPARROW: - S_LocalSound ("misc/menu1.wav"); - if (--m_multiplayer_cursor < 0) - m_multiplayer_cursor = MULTIPLAYER_ITEMS - 1; - break; + case K_UPARROW: + S_LocalSound("misc/menu1.wav"); + if (--m_multiplayer_cursor < 0) + m_multiplayer_cursor = MULTIPLAYER_ITEMS - 1; + break; - case K_ENTER: - case K_KP_ENTER: - case K_ABUTTON: - m_entersound = true; - switch (m_multiplayer_cursor) - { - case 0: - if (ipxAvailable || tcpipAvailable) - M_Menu_Net_f (); - break; + case K_ENTER: + case K_KP_ENTER: + case K_ABUTTON: + m_entersound = true; + switch (m_multiplayer_cursor) { + case 0: + if (ipxAvailable || tcpipAvailable) + M_Menu_Net_f(); + break; - case 1: - if (ipxAvailable || tcpipAvailable) - M_Menu_Net_f (); - break; + case 1: + if (ipxAvailable || tcpipAvailable) + M_Menu_Net_f(); + break; - case 2: - M_Menu_Setup_f (); - break; - } - } + case 2: + M_Menu_Setup_f(); + break; + } + } } //============================================================================= /* SETUP MENU */ -int setup_cursor = 4; -int setup_cursor_table[] = {40, 56, 80, 104, 140}; +int setup_cursor = 4; +int setup_cursor_table[] = {40, 56, 80, 104, 140}; -char setup_hostname[16]; -char setup_myname[16]; -int setup_oldtop; -int setup_oldbottom; -int setup_top; -int setup_bottom; +char setup_hostname[16]; +char setup_myname[16]; +int setup_oldtop; +int setup_oldbottom; +int setup_top; +int setup_bottom; #define NUM_SETUP_CMDS 5 -void M_Menu_Setup_f (void) -{ - IN_Deactivate(modestate == MS_WINDOWED); - key_dest = key_menu; - m_state = m_setup; - m_entersound = true; - Q_strcpy(setup_myname, cl_name.string); - Q_strcpy(setup_hostname, hostname.string); - setup_top = setup_oldtop = ((int)cl_color.value) >> 4; - setup_bottom = setup_oldbottom = ((int)cl_color.value) & 15; +void M_Menu_Setup_f(void) { + IN_Deactivate(modestate == MS_WINDOWED); + key_dest = key_menu; + m_state = m_setup; + m_entersound = true; + Q_strcpy(setup_myname, cl_name.string); + Q_strcpy(setup_hostname, hostname.string); + setup_top = setup_oldtop = ((int) cl_color.value) >> 4; + setup_bottom = setup_oldbottom = ((int) cl_color.value) & 15; } -void M_Setup_Draw (void) -{ - qpic_t *p; +void M_Setup_Draw(void) { + qpic_t *p; - M_DrawTransPic (16, 4, Draw_CachePic ("gfx/qplaque.lmp") ); - p = Draw_CachePic ("gfx/p_multi.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); + M_DrawTransPic(16, 4, Draw_CachePic("gfx/qplaque.lmp")); + p = Draw_CachePic("gfx/p_multi.lmp"); + M_DrawPic((320 - p->width) / 2, 4, p); - M_Print (64, 40, "Hostname"); - M_DrawTextBox (160, 32, 16, 1); - M_Print (168, 40, setup_hostname); + M_Print(64, 40, "Hostname"); + M_DrawTextBox(160, 32, 16, 1); + M_Print(168, 40, setup_hostname); - M_Print (64, 56, "Your name"); - M_DrawTextBox (160, 48, 16, 1); - M_Print (168, 56, setup_myname); + M_Print(64, 56, "Your name"); + M_DrawTextBox(160, 48, 16, 1); + M_Print(168, 56, setup_myname); - M_Print (64, 80, "Shirt color"); - M_Print (64, 104, "Pants color"); + M_Print(64, 80, "Shirt color"); + M_Print(64, 104, "Pants color"); - M_DrawTextBox (64, 140-8, 14, 1); - M_Print (72, 140, "Accept Changes"); + M_DrawTextBox(64, 140 - 8, 14, 1); + M_Print(72, 140, "Accept Changes"); - p = Draw_CachePic ("gfx/bigbox.lmp"); - M_DrawTransPic (160, 64, p); - p = Draw_CachePic ("gfx/menuplyr.lmp"); - M_DrawTransPicTranslate (172, 72, p, setup_top, setup_bottom); + p = Draw_CachePic("gfx/bigbox.lmp"); + M_DrawTransPic(160, 64, p); + p = Draw_CachePic("gfx/menuplyr.lmp"); + M_DrawTransPicTranslate(172, 72, p, setup_top, setup_bottom); - M_DrawCharacter (56, setup_cursor_table [setup_cursor], 12+((int)(realtime*4)&1)); + M_DrawCharacter(56, setup_cursor_table[setup_cursor], 12 + ((int) (realtime * 4) & 1)); - if (setup_cursor == 0) - M_DrawCharacter (168 + 8*strlen(setup_hostname), setup_cursor_table [setup_cursor], 10+((int)(realtime*4)&1)); + if (setup_cursor == 0) + M_DrawCharacter(168 + 8 * strlen(setup_hostname), setup_cursor_table[setup_cursor], + 10 + ((int) (realtime * 4) & 1)); - if (setup_cursor == 1) - M_DrawCharacter (168 + 8*strlen(setup_myname), setup_cursor_table [setup_cursor], 10+((int)(realtime*4)&1)); + if (setup_cursor == 1) + M_DrawCharacter(168 + 8 * strlen(setup_myname), setup_cursor_table[setup_cursor], + 10 + ((int) (realtime * 4) & 1)); } -void M_Setup_Key (int k) -{ - switch (k) - { - case K_ESCAPE: - case K_BBUTTON: - M_Menu_MultiPlayer_f (); - break; +void M_Setup_Key(int k) { + switch (k) { + case K_ESCAPE: + case K_BBUTTON: + M_Menu_MultiPlayer_f(); + break; - case K_UPARROW: - S_LocalSound ("misc/menu1.wav"); - setup_cursor--; - if (setup_cursor < 0) - setup_cursor = NUM_SETUP_CMDS-1; - break; + case K_UPARROW: + S_LocalSound("misc/menu1.wav"); + setup_cursor--; + if (setup_cursor < 0) + setup_cursor = NUM_SETUP_CMDS - 1; + break; - case K_DOWNARROW: - S_LocalSound ("misc/menu1.wav"); - setup_cursor++; - if (setup_cursor >= NUM_SETUP_CMDS) - setup_cursor = 0; - break; + case K_DOWNARROW: + S_LocalSound("misc/menu1.wav"); + setup_cursor++; + if (setup_cursor >= NUM_SETUP_CMDS) + setup_cursor = 0; + break; - case K_LEFTARROW: - if (setup_cursor < 2) - return; - S_LocalSound ("misc/menu3.wav"); - if (setup_cursor == 2) - setup_top = setup_top - 1; - if (setup_cursor == 3) - setup_bottom = setup_bottom - 1; - break; - case K_RIGHTARROW: - if (setup_cursor < 2) - return; -forward: - S_LocalSound ("misc/menu3.wav"); - if (setup_cursor == 2) - setup_top = setup_top + 1; - if (setup_cursor == 3) - setup_bottom = setup_bottom + 1; - break; + case K_LEFTARROW: + if (setup_cursor < 2) + return; + S_LocalSound("misc/menu3.wav"); + if (setup_cursor == 2) + setup_top = setup_top - 1; + if (setup_cursor == 3) + setup_bottom = setup_bottom - 1; + break; + case K_RIGHTARROW: + if (setup_cursor < 2) + return; + forward: + S_LocalSound("misc/menu3.wav"); + if (setup_cursor == 2) + setup_top = setup_top + 1; + if (setup_cursor == 3) + setup_bottom = setup_bottom + 1; + break; - case K_ENTER: - case K_KP_ENTER: - case K_ABUTTON: - if (setup_cursor == 0 || setup_cursor == 1) - return; + case K_ENTER: + case K_KP_ENTER: + case K_ABUTTON: + if (setup_cursor == 0 || setup_cursor == 1) + return; - if (setup_cursor == 2 || setup_cursor == 3) - goto forward; + if (setup_cursor == 2 || setup_cursor == 3) + goto forward; - // setup_cursor == 4 (OK) - if (Q_strcmp(cl_name.string, setup_myname) != 0) - Cbuf_AddText ( va ("name \"%s\"\n", setup_myname) ); - if (Q_strcmp(hostname.string, setup_hostname) != 0) - Cvar_Set("hostname", setup_hostname); - if (setup_top != setup_oldtop || setup_bottom != setup_oldbottom) - Cbuf_AddText( va ("color %i %i\n", setup_top, setup_bottom) ); - m_entersound = true; - M_Menu_MultiPlayer_f (); - break; + // setup_cursor == 4 (OK) + if (Q_strcmp(cl_name.string, setup_myname) != 0) + Cbuf_AddText(va("name \"%s\"\n", setup_myname)); + if (Q_strcmp(hostname.string, setup_hostname) != 0) + convar::set("hostname", setup_hostname); + if (setup_top != setup_oldtop || setup_bottom != setup_oldbottom) + Cbuf_AddText(va("color %i %i\n", setup_top, setup_bottom)); + m_entersound = true; + M_Menu_MultiPlayer_f(); + break; - case K_BACKSPACE: - if (setup_cursor == 0) - { - if (strlen(setup_hostname)) - setup_hostname[strlen(setup_hostname)-1] = 0; - } + case K_BACKSPACE: + if (setup_cursor == 0) { + if (strlen(setup_hostname)) + setup_hostname[strlen(setup_hostname) - 1] = 0; + } - if (setup_cursor == 1) - { - if (strlen(setup_myname)) - setup_myname[strlen(setup_myname)-1] = 0; - } - break; - } + if (setup_cursor == 1) { + if (strlen(setup_myname)) + setup_myname[strlen(setup_myname) - 1] = 0; + } + break; + } - if (setup_top > 13) - setup_top = 0; - if (setup_top < 0) - setup_top = 13; - if (setup_bottom > 13) - setup_bottom = 0; - if (setup_bottom < 0) - setup_bottom = 13; + if (setup_top > 13) + setup_top = 0; + if (setup_top < 0) + setup_top = 13; + if (setup_bottom > 13) + setup_bottom = 0; + if (setup_bottom < 0) + setup_bottom = 13; } -void M_Setup_Char (int k) -{ - int l; +void M_Setup_Char(int k) { + int l; - switch (setup_cursor) - { - case 0: - l = strlen(setup_hostname); - if (l < 15) - { - setup_hostname[l+1] = 0; - setup_hostname[l] = k; - } - break; - case 1: - l = strlen(setup_myname); - if (l < 15) - { - setup_myname[l+1] = 0; - setup_myname[l] = k; - } - break; - } + switch (setup_cursor) { + case 0: + l = strlen(setup_hostname); + if (l < 15) { + setup_hostname[l + 1] = 0; + setup_hostname[l] = k; + } + break; + case 1: + l = strlen(setup_myname); + if (l < 15) { + setup_myname[l + 1] = 0; + setup_myname[l] = k; + } + break; + } } -qboolean M_Setup_TextEntry (void) -{ - return (setup_cursor == 0 || setup_cursor == 1); +qboolean M_Setup_TextEntry(void) { + return (setup_cursor == 0 || setup_cursor == 1); } //============================================================================= /* NET MENU */ -int m_net_cursor; +int m_net_cursor; int m_net_items; -const char *net_helpMessage [] = +const char *net_helpMessage[] = { -/* .........1.........2.... */ - " Novell network LANs ", - " or Windows 95 DOS-box. ", - " ", - "(LAN=Local Area Network)", + /* .........1.........2.... */ + " Novell network LANs ", + " or Windows 95 DOS-box. ", + " ", + "(LAN=Local Area Network)", - " Commonly used to play ", - " over the Internet, but ", - " also used on a Local ", - " Area Network. " + " Commonly used to play ", + " over the Internet, but ", + " also used on a Local ", + " Area Network. " }; -void M_Menu_Net_f (void) -{ - IN_Deactivate(modestate == MS_WINDOWED); - key_dest = key_menu; - m_state = m_net; - m_entersound = true; - m_net_items = 2; +void M_Menu_Net_f(void) { + IN_Deactivate(modestate == MS_WINDOWED); + key_dest = key_menu; + m_state = m_net; + m_entersound = true; + m_net_items = 2; - if (m_net_cursor >= m_net_items) - m_net_cursor = 0; - m_net_cursor--; - M_Net_Key (K_DOWNARROW); + if (m_net_cursor >= m_net_items) + m_net_cursor = 0; + m_net_cursor--; + M_Net_Key(K_DOWNARROW); } -void M_Net_Draw (void) -{ - int f; - qpic_t *p; +void M_Net_Draw(void) { + int f; + qpic_t *p; - M_DrawTransPic (16, 4, Draw_CachePic ("gfx/qplaque.lmp") ); - p = Draw_CachePic ("gfx/p_multi.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); + M_DrawTransPic(16, 4, Draw_CachePic("gfx/qplaque.lmp")); + p = Draw_CachePic("gfx/p_multi.lmp"); + M_DrawPic((320 - p->width) / 2, 4, p); - f = 32; + f = 32; - if (ipxAvailable) - p = Draw_CachePic ("gfx/netmen3.lmp"); - else - p = Draw_CachePic ("gfx/dim_ipx.lmp"); - M_DrawTransPic (72, f, p); + if (ipxAvailable) + p = Draw_CachePic("gfx/netmen3.lmp"); + else + p = Draw_CachePic("gfx/dim_ipx.lmp"); + M_DrawTransPic(72, f, p); - f += 19; - if (tcpipAvailable) - p = Draw_CachePic ("gfx/netmen4.lmp"); - else - p = Draw_CachePic ("gfx/dim_tcp.lmp"); - M_DrawTransPic (72, f, p); + f += 19; + if (tcpipAvailable) + p = Draw_CachePic("gfx/netmen4.lmp"); + else + p = Draw_CachePic("gfx/dim_tcp.lmp"); + M_DrawTransPic(72, f, p); - f = (320-26*8)/2; - M_DrawTextBox (f, 96, 24, 4); - f += 8; - M_Print (f, 104, net_helpMessage[m_net_cursor*4+0]); - M_Print (f, 112, net_helpMessage[m_net_cursor*4+1]); - M_Print (f, 120, net_helpMessage[m_net_cursor*4+2]); - M_Print (f, 128, net_helpMessage[m_net_cursor*4+3]); + f = (320 - 26 * 8) / 2; + M_DrawTextBox(f, 96, 24, 4); + f += 8; + M_Print(f, 104, net_helpMessage[m_net_cursor * 4 + 0]); + M_Print(f, 112, net_helpMessage[m_net_cursor * 4 + 1]); + M_Print(f, 120, net_helpMessage[m_net_cursor * 4 + 2]); + M_Print(f, 128, net_helpMessage[m_net_cursor * 4 + 3]); - f = (int)(realtime * 10)%6; - M_DrawTransPic (54, 32 + m_net_cursor * 20,Draw_CachePic( va("gfx/menudot%i.lmp", f+1 ) ) ); + f = (int) (realtime * 10) % 6; + M_DrawTransPic(54, 32 + m_net_cursor * 20, Draw_CachePic(va("gfx/menudot%i.lmp", f + 1))); } -void M_Net_Key (int k) -{ +void M_Net_Key(int k) { again: - switch (k) - { - case K_ESCAPE: - case K_BBUTTON: - M_Menu_MultiPlayer_f (); - break; + switch (k) { + case K_ESCAPE: + case K_BBUTTON: + M_Menu_MultiPlayer_f(); + break; - case K_DOWNARROW: - S_LocalSound ("misc/menu1.wav"); - if (++m_net_cursor >= m_net_items) - m_net_cursor = 0; - break; + case K_DOWNARROW: + S_LocalSound("misc/menu1.wav"); + if (++m_net_cursor >= m_net_items) + m_net_cursor = 0; + break; - case K_UPARROW: - S_LocalSound ("misc/menu1.wav"); - if (--m_net_cursor < 0) - m_net_cursor = m_net_items - 1; - break; + case K_UPARROW: + S_LocalSound("misc/menu1.wav"); + if (--m_net_cursor < 0) + m_net_cursor = m_net_items - 1; + break; - case K_ENTER: - case K_KP_ENTER: - case K_ABUTTON: - m_entersound = true; - M_Menu_LanConfig_f (); - break; - } + case K_ENTER: + case K_KP_ENTER: + case K_ABUTTON: + m_entersound = true; + M_Menu_LanConfig_f(); + break; + } - if (m_net_cursor == 0 && !ipxAvailable) - goto again; - if (m_net_cursor == 1 && !tcpipAvailable) - goto again; + if (m_net_cursor == 0 && !ipxAvailable) + goto again; + if (m_net_cursor == 1 && !tcpipAvailable) + goto again; } //============================================================================= /* OPTIONS MENU */ -enum -{ - OPT_CUSTOMIZE = 0, - OPT_CONSOLE, // 1 - OPT_DEFAULTS, // 2 - OPT_SCALE, - OPT_SCRSIZE, - OPT_GAMMA, - OPT_CONTRAST, - OPT_MOUSESPEED, - OPT_SBALPHA, - OPT_SNDVOL, - OPT_MUSICVOL, - OPT_MUSICEXT, - OPT_ALWAYRUN, - OPT_INVMOUSE, - OPT_ALWAYSMLOOK, - OPT_LOOKSPRING, - OPT_LOOKSTRAFE, -//#ifdef _WIN32 -// OPT_USEMOUSE, -//#endif - OPT_VIDEO, // This is the last before OPTIONS_ITEMS - OPTIONS_ITEMS +enum { + OPT_CUSTOMIZE = 0, + OPT_CONSOLE, // 1 + OPT_DEFAULTS, // 2 + OPT_SCALE, + OPT_SCRSIZE, + OPT_GAMMA, + OPT_CONTRAST, + OPT_MOUSESPEED, + OPT_SBALPHA, + OPT_SNDVOL, + OPT_MUSICVOL, + OPT_MUSICEXT, + OPT_ALWAYRUN, + OPT_INVMOUSE, + OPT_ALWAYSMLOOK, + OPT_LOOKSPRING, + OPT_LOOKSTRAFE, + //#ifdef _WIN32 + // OPT_USEMOUSE, + //#endif + OPT_VIDEO, // This is the last before OPTIONS_ITEMS + OPTIONS_ITEMS }; -enum -{ - ALWAYSRUN_OFF = 0, - ALWAYSRUN_VANILLA, - ALWAYSRUN_QUAKESPASM, - ALWAYSRUN_ITEMS +enum { + ALWAYSRUN_OFF = 0, + ALWAYSRUN_VANILLA, + ALWAYSRUN_QUAKESPASM, + ALWAYSRUN_ITEMS }; #define SLIDER_RANGE 10 -int options_cursor; +int options_cursor; -void M_Menu_Options_f (void) -{ - IN_Deactivate(modestate == MS_WINDOWED); - key_dest = key_menu; - m_state = m_options; - m_entersound = true; +void M_Menu_Options_f(void) { + IN_Deactivate(modestate == MS_WINDOWED); + key_dest = key_menu; + m_state = m_options; + m_entersound = true; } -void M_AdjustSliders (int dir) -{ - int curr_alwaysrun, target_alwaysrun; - float f, l; +void M_AdjustSliders(int dir) { + int curr_alwaysrun, target_alwaysrun; + float f, l; - S_LocalSound ("misc/menu3.wav"); + S_LocalSound("misc/menu3.wav"); - switch (options_cursor) - { - case OPT_SCALE: // console and menu scale - l = ((vid.width + 31) / 32) / 10.0; - f = scr_conscale.value + dir * .1; - if (f < 1) f = 1; - else if(f > l) f = l; - Cvar_SetValue ("scr_conscale", f); - Cvar_SetValue ("scr_menuscale", f); - Cvar_SetValue ("scr_sbarscale", f); - break; - case OPT_SCRSIZE: // screen size - f = scr_viewsize.value + dir * 10; - if (f > 120) f = 120; - else if(f < 30) f = 30; - Cvar_SetValue ("viewsize", f); - break; - case OPT_GAMMA: // gamma - f = vid_gamma.value - dir * 0.05; - if (f < 0.5) f = 0.5; - else if (f > 1) f = 1; - Cvar_SetValue ("gamma", f); - break; - case OPT_CONTRAST: // contrast - f = vid_contrast.value + dir * 0.1; - if (f < 1) f = 1; - else if (f > 2) f = 2; - Cvar_SetValue ("contrast", f); - break; - case OPT_MOUSESPEED: // mouse speed - f = sensitivity.value + dir * 0.5; - if (f > 11) f = 11; - else if (f < 1) f = 1; - Cvar_SetValue ("sensitivity", f); - break; - case OPT_SBALPHA: // statusbar alpha - f = scr_sbaralpha.value - dir * 0.05; - if (f < 0) f = 0; - else if (f > 1) f = 1; - Cvar_SetValue ("scr_sbaralpha", f); - break; - case OPT_MUSICVOL: // music volume - f = bgmvolume.value + dir * 0.1; - if (f < 0) f = 0; - else if (f > 1) f = 1; - Cvar_SetValue ("bgmvolume", f); - break; - case OPT_MUSICEXT: // enable external music vs cdaudio - Cvar_Set ("bgm_extmusic", bgm_extmusic.value ? "0" : "1"); - break; - case OPT_SNDVOL: // sfx volume - f = sfxvolume.value + dir * 0.1; - if (f < 0) f = 0; - else if (f > 1) f = 1; - Cvar_SetValue ("volume", f); - break; + switch (options_cursor) { + case OPT_SCALE: // console and menu scale + l = ((vid.width + 31) / 32) / 10.0; + f = scr_conscale.value + dir * .1; + if (f < 1) f = 1; + else if (f > l) f = l; + convar::set_value("scr_conscale", f); + convar::set_value("scr_menuscale", f); + convar::set_value("scr_sbarscale", f); + break; + case OPT_SCRSIZE: // screen size + f = scr_viewsize.value + dir * 10; + if (f > 120) f = 120; + else if (f < 30) f = 30; + convar::set_value("viewsize", f); + break; + case OPT_GAMMA: // gamma + f = vid_gamma.value - dir * 0.05; + if (f < 0.5) f = 0.5; + else if (f > 1) f = 1; + convar::set_value("gamma", f); + break; + case OPT_CONTRAST: // contrast + f = vid_contrast.value + dir * 0.1; + if (f < 1) f = 1; + else if (f > 2) f = 2; + convar::set_value("contrast", f); + break; + case OPT_MOUSESPEED: // mouse speed + f = sensitivity.value + dir * 0.5; + if (f > 11) f = 11; + else if (f < 1) f = 1; + convar::set_value("sensitivity", f); + break; + case OPT_SBALPHA: // statusbar alpha + f = scr_sbaralpha.value - dir * 0.05; + if (f < 0) f = 0; + else if (f > 1) f = 1; + convar::set_value("scr_sbaralpha", f); + break; + case OPT_MUSICVOL: // music volume + f = bgmvolume.value + dir * 0.1; + if (f < 0) f = 0; + else if (f > 1) f = 1; + convar::set_value("bgmvolume", f); + break; + case OPT_MUSICEXT: // enable external music vs cdaudio + convar::set("bgm_extmusic", bgm_extmusic.value ? "0" : "1"); + break; + case OPT_SNDVOL: // sfx volume + f = sfxvolume.value + dir * 0.1; + if (f < 0) f = 0; + else if (f > 1) f = 1; + convar::set_value("volume", f); + break; - case OPT_ALWAYRUN: // always run - if (cl_alwaysrun.value) - curr_alwaysrun = ALWAYSRUN_QUAKESPASM; - else if (cl_forwardspeed.value > 200) - curr_alwaysrun = ALWAYSRUN_VANILLA; - else - curr_alwaysrun = ALWAYSRUN_OFF; - - target_alwaysrun = (ALWAYSRUN_ITEMS + curr_alwaysrun + dir) % ALWAYSRUN_ITEMS; - - if (target_alwaysrun == ALWAYSRUN_VANILLA) - { - Cvar_SetValue ("cl_alwaysrun", 0); - Cvar_SetValue ("cl_forwardspeed", 400); - Cvar_SetValue ("cl_backspeed", 400); - } - else if (target_alwaysrun == ALWAYSRUN_QUAKESPASM) - { - Cvar_SetValue ("cl_alwaysrun", 1); - Cvar_SetValue ("cl_forwardspeed", 200); - Cvar_SetValue ("cl_backspeed", 200); - } - else // ALWAYSRUN_OFF - { - Cvar_SetValue ("cl_alwaysrun", 0); - Cvar_SetValue ("cl_forwardspeed", 200); - Cvar_SetValue ("cl_backspeed", 200); - } - break; + case OPT_ALWAYRUN: // always run + if (cl_alwaysrun.value) + curr_alwaysrun = ALWAYSRUN_QUAKESPASM; + else if (cl_forwardspeed.value > 200) + curr_alwaysrun = ALWAYSRUN_VANILLA; + else + curr_alwaysrun = ALWAYSRUN_OFF; - case OPT_INVMOUSE: // invert mouse - Cvar_SetValue ("m_pitch", -m_pitch.value); - break; + target_alwaysrun = (ALWAYSRUN_ITEMS + curr_alwaysrun + dir) % ALWAYSRUN_ITEMS; - case OPT_ALWAYSMLOOK: - if (in_mlook.state & 1) - Cbuf_AddText("-mlook"); - else - Cbuf_AddText("+mlook"); - break; + if (target_alwaysrun == ALWAYSRUN_VANILLA) { + convar::set_value("cl_alwaysrun", 0); + convar::set_value("cl_forwardspeed", 400); + convar::set_value("cl_backspeed", 400); + } else if (target_alwaysrun == ALWAYSRUN_QUAKESPASM) { + convar::set_value("cl_alwaysrun", 1); + convar::set_value("cl_forwardspeed", 200); + convar::set_value("cl_backspeed", 200); + } else // ALWAYSRUN_OFF + { + convar::set_value("cl_alwaysrun", 0); + convar::set_value("cl_forwardspeed", 200); + convar::set_value("cl_backspeed", 200); + } + break; - case OPT_LOOKSPRING: // lookspring - Cvar_Set ("lookspring", lookspring.value ? "0" : "1"); - break; + case OPT_INVMOUSE: // invert mouse + convar::set_value("m_pitch", -m_pitch.value); + break; - case OPT_LOOKSTRAFE: // lookstrafe - Cvar_Set ("lookstrafe", lookstrafe.value ? "0" : "1"); - break; - } + case OPT_ALWAYSMLOOK: + if (in_mlook.state & 1) + Cbuf_AddText("-mlook"); + else + Cbuf_AddText("+mlook"); + break; + + case OPT_LOOKSPRING: // lookspring + convar::set("lookspring", lookspring.value ? "0" : "1"); + break; + + case OPT_LOOKSTRAFE: // lookstrafe + convar::set("lookstrafe", lookstrafe.value ? "0" : "1"); + break; + } } -void M_DrawSlider (int x, int y, float range, float value, const char *format) -{ - int i; - char buffer[5]; +void M_DrawSlider(int x, int y, float range, float value, const char *format) { + int i; + char buffer[5]; - if (range < 0) - range = 0; - if (range > 1) - range = 1; - M_DrawCharacter (x-8, y, 128); - for (i = 0; i < SLIDER_RANGE; i++) - M_DrawCharacter (x + i*8, y, 129); - M_DrawCharacter (x+i*8, y, 130); - M_DrawCharacter (x + (SLIDER_RANGE-1)*8 * range, y, 131); - q_snprintf(buffer, 5, format, value); - M_Print (x + (SLIDER_RANGE + 1) * 8, y, buffer); + if (range < 0) + range = 0; + if (range > 1) + range = 1; + M_DrawCharacter(x - 8, y, 128); + for (i = 0; i < SLIDER_RANGE; i++) + M_DrawCharacter(x + i * 8, y, 129); + M_DrawCharacter(x + i * 8, y, 130); + M_DrawCharacter(x + (SLIDER_RANGE - 1) * 8 * range, y, 131); + q_snprintf(buffer, 5, format, value); + M_Print(x + (SLIDER_RANGE + 1) * 8, y, buffer); } -void M_DrawCheckbox (int x, int y, int on) -{ +void M_DrawCheckbox(int x, int y, int on) { #if 0 - if (on) - M_DrawCharacter (x, y, 131); - else - M_DrawCharacter (x, y, 129); + if (on) + M_DrawCharacter(x, y, 131); + else + M_DrawCharacter(x, y, 129); #endif - if (on) - M_Print (x, y, "on"); - else - M_Print (x, y, "off"); + if (on) + M_Print(x, y, "on"); + else + M_Print(x, y, "off"); } -void M_Options_Draw (void) -{ - float r, l; - qpic_t *p; +void M_Options_Draw(void) { + float r, l; + qpic_t *p; - M_DrawTransPic (16, 4, Draw_CachePic ("gfx/qplaque.lmp") ); - p = Draw_CachePic ("gfx/p_option.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); + M_DrawTransPic(16, 4, Draw_CachePic("gfx/qplaque.lmp")); + p = Draw_CachePic("gfx/p_option.lmp"); + M_DrawPic((320 - p->width) / 2, 4, p); - // Draw the items in the order of the enum defined above: - // OPT_CUSTOMIZE: - M_Print (16, 32, " Controls"); - // OPT_CONSOLE: - M_Print (16, 32 + 8*OPT_CONSOLE, " Goto console"); - // OPT_DEFAULTS: - M_Print (16, 32 + 8*OPT_DEFAULTS, " Reset config"); + // Draw the items in the order of the enum defined above: + // OPT_CUSTOMIZE: + M_Print(16, 32, " Controls"); + // OPT_CONSOLE: + M_Print(16, 32 + 8 * OPT_CONSOLE, " Goto console"); + // OPT_DEFAULTS: + M_Print(16, 32 + 8 * OPT_DEFAULTS, " Reset config"); - // OPT_SCALE: - M_Print (16, 32 + 8*OPT_SCALE, " Scale"); - l = (vid.width / 320.0) - 1; - r = l > 0 ? (scr_conscale.value - 1) / l : 0; - M_DrawSlider (220, 32 + 8*OPT_SCALE, r, scr_conscale.value, "%.1f"); + // OPT_SCALE: + M_Print(16, 32 + 8 * OPT_SCALE, " Scale"); + l = (vid.width / 320.0) - 1; + r = l > 0 ? (scr_conscale.value - 1) / l : 0; + M_DrawSlider(220, 32 + 8 * OPT_SCALE, r, scr_conscale.value, "%.1f"); - // OPT_SCRSIZE: - M_Print (16, 32 + 8*OPT_SCRSIZE, " Screen size"); - r = (scr_viewsize.value - 30) / (120 - 30); - M_DrawSlider (220, 32 + 8*OPT_SCRSIZE, r, scr_viewsize.value, "%.0f"); + // OPT_SCRSIZE: + M_Print(16, 32 + 8 * OPT_SCRSIZE, " Screen size"); + r = (scr_viewsize.value - 30) / (120 - 30); + M_DrawSlider(220, 32 + 8 * OPT_SCRSIZE, r, scr_viewsize.value, "%.0f"); - // OPT_GAMMA: - M_Print (16, 32 + 8*OPT_GAMMA, " Brightness"); - r = (1.0 - vid_gamma.value) / 0.5; - M_DrawSlider (220, 32 + 8*OPT_GAMMA, r, vid_gamma.value, "%.2f"); + // OPT_GAMMA: + M_Print(16, 32 + 8 * OPT_GAMMA, " Brightness"); + r = (1.0 - vid_gamma.value) / 0.5; + M_DrawSlider(220, 32 + 8 * OPT_GAMMA, r, vid_gamma.value, "%.2f"); - // OPT_CONTRAST: - M_Print (16, 32 + 8*OPT_CONTRAST, " Contrast"); - r = vid_contrast.value - 1.0; - M_DrawSlider (220, 32 + 8*OPT_CONTRAST, r, vid_contrast.value, "%.1f"); - - // OPT_MOUSESPEED: - M_Print (16, 32 + 8*OPT_MOUSESPEED, " Mouse Speed"); - r = (sensitivity.value - 1)/10; - M_DrawSlider (220, 32 + 8*OPT_MOUSESPEED, r, sensitivity.value, "%.1f"); + // OPT_CONTRAST: + M_Print(16, 32 + 8 * OPT_CONTRAST, " Contrast"); + r = vid_contrast.value - 1.0; + M_DrawSlider(220, 32 + 8 * OPT_CONTRAST, r, vid_contrast.value, "%.1f"); - // OPT_SBALPHA: - M_Print (16, 32 + 8*OPT_SBALPHA, " Statusbar alpha"); - r = (1.0 - scr_sbaralpha.value) ; // scr_sbaralpha range is 1.0 to 0.0 - M_DrawSlider (220, 32 + 8*OPT_SBALPHA, r, scr_sbaralpha.value, "%.2f"); + // OPT_MOUSESPEED: + M_Print(16, 32 + 8 * OPT_MOUSESPEED, " Mouse Speed"); + r = (sensitivity.value - 1) / 10; + M_DrawSlider(220, 32 + 8 * OPT_MOUSESPEED, r, sensitivity.value, "%.1f"); - // OPT_SNDVOL: - M_Print (16, 32 + 8*OPT_SNDVOL, " Sound Volume"); - r = sfxvolume.value; - M_DrawSlider (220, 32 + 8*OPT_SNDVOL, r, sfxvolume.value, "%.1f"); + // OPT_SBALPHA: + M_Print(16, 32 + 8 * OPT_SBALPHA, " Statusbar alpha"); + r = (1.0 - scr_sbaralpha.value); // scr_sbaralpha range is 1.0 to 0.0 + M_DrawSlider(220, 32 + 8 * OPT_SBALPHA, r, scr_sbaralpha.value, "%.2f"); - // OPT_MUSICVOL: - M_Print (16, 32 + 8*OPT_MUSICVOL, " Music Volume"); - r = bgmvolume.value; - M_DrawSlider (220, 32 + 8*OPT_MUSICVOL, r, bgmvolume.value, "%.1f"); + // OPT_SNDVOL: + M_Print(16, 32 + 8 * OPT_SNDVOL, " Sound Volume"); + r = sfxvolume.value; + M_DrawSlider(220, 32 + 8 * OPT_SNDVOL, r, sfxvolume.value, "%.1f"); - // OPT_MUSICEXT: - M_Print (16, 32 + 8*OPT_MUSICEXT, " External Music"); - M_DrawCheckbox (220, 32 + 8*OPT_MUSICEXT, bgm_extmusic.value); + // OPT_MUSICVOL: + M_Print(16, 32 + 8 * OPT_MUSICVOL, " Music Volume"); + r = bgmvolume.value; + M_DrawSlider(220, 32 + 8 * OPT_MUSICVOL, r, bgmvolume.value, "%.1f"); - // OPT_ALWAYRUN: - M_Print (16, 32 + 8*OPT_ALWAYRUN, " Always Run"); - if (cl_alwaysrun.value) - M_Print (220, 32 + 8*OPT_ALWAYRUN, "quakespasm"); - else if (cl_forwardspeed.value > 200.0) - M_Print (220, 32 + 8*OPT_ALWAYRUN, "vanilla"); - else - M_Print (220, 32 + 8*OPT_ALWAYRUN, "off"); + // OPT_MUSICEXT: + M_Print(16, 32 + 8 * OPT_MUSICEXT, " External Music"); + M_DrawCheckbox(220, 32 + 8 * OPT_MUSICEXT, bgm_extmusic.value); - // OPT_INVMOUSE: - M_Print (16, 32 + 8*OPT_INVMOUSE, " Invert Mouse"); - M_DrawCheckbox (220, 32 + 8*OPT_INVMOUSE, m_pitch.value < 0); + // OPT_ALWAYRUN: + M_Print(16, 32 + 8 * OPT_ALWAYRUN, " Always Run"); + if (cl_alwaysrun.value) + M_Print(220, 32 + 8 * OPT_ALWAYRUN, "quakespasm"); + else if (cl_forwardspeed.value > 200.0) + M_Print(220, 32 + 8 * OPT_ALWAYRUN, "vanilla"); + else + M_Print(220, 32 + 8 * OPT_ALWAYRUN, "off"); - // OPT_ALWAYSMLOOK: - M_Print (16, 32 + 8*OPT_ALWAYSMLOOK, " Mouse Look"); - M_DrawCheckbox (220, 32 + 8*OPT_ALWAYSMLOOK, in_mlook.state & 1); + // OPT_INVMOUSE: + M_Print(16, 32 + 8 * OPT_INVMOUSE, " Invert Mouse"); + M_DrawCheckbox(220, 32 + 8 * OPT_INVMOUSE, m_pitch.value < 0); - // OPT_LOOKSPRING: - M_Print (16, 32 + 8*OPT_LOOKSPRING, " Lookspring"); - M_DrawCheckbox (220, 32 + 8*OPT_LOOKSPRING, lookspring.value); + // OPT_ALWAYSMLOOK: + M_Print(16, 32 + 8 * OPT_ALWAYSMLOOK, " Mouse Look"); + M_DrawCheckbox(220, 32 + 8 * OPT_ALWAYSMLOOK, in_mlook.state & 1); - // OPT_LOOKSTRAFE: - M_Print (16, 32 + 8*OPT_LOOKSTRAFE, " Lookstrafe"); - M_DrawCheckbox (220, 32 + 8*OPT_LOOKSTRAFE, lookstrafe.value); + // OPT_LOOKSPRING: + M_Print(16, 32 + 8 * OPT_LOOKSPRING, " Lookspring"); + M_DrawCheckbox(220, 32 + 8 * OPT_LOOKSPRING, lookspring.value); - // OPT_VIDEO: - if (vid_menudrawfn) - M_Print (16, 32 + 8*OPT_VIDEO, " Video Options"); + // OPT_LOOKSTRAFE: + M_Print(16, 32 + 8 * OPT_LOOKSTRAFE, " Lookstrafe"); + M_DrawCheckbox(220, 32 + 8 * OPT_LOOKSTRAFE, lookstrafe.value); -// cursor - M_DrawCharacter (200, 32 + options_cursor*8, 12+((int)(realtime*4)&1)); + // OPT_VIDEO: + if (vid_menudrawfn) + M_Print(16, 32 + 8 * OPT_VIDEO, " Video Options"); + + // cursor + M_DrawCharacter(200, 32 + options_cursor * 8, 12 + ((int) (realtime * 4) & 1)); } -void M_Options_Key (int k) -{ - switch (k) - { - case K_ESCAPE: - case K_BBUTTON: - M_Menu_Main_f (); - break; +void M_Options_Key(int k) { + switch (k) { + case K_ESCAPE: + case K_BBUTTON: + M_Menu_Main_f(); + break; - case K_ENTER: - case K_KP_ENTER: - case K_ABUTTON: - m_entersound = true; - switch (options_cursor) - { - case OPT_CUSTOMIZE: - M_Menu_Keys_f (); - break; - case OPT_CONSOLE: - m_state = m_none; - Con_ToggleConsole_f (); - break; - case OPT_DEFAULTS: - if (SCR_ModalMessage("This will reset all controls\n" - "and stored cvars. Continue? (y/n)\n", 15.0f)) - { - Cbuf_AddText ("resetcfg\n"); - Cbuf_AddText ("exec default.cfg\n"); - } - break; - case OPT_VIDEO: - M_Menu_Video_f (); - break; - default: - M_AdjustSliders (1); - break; - } - return; + case K_ENTER: + case K_KP_ENTER: + case K_ABUTTON: + m_entersound = true; + switch (options_cursor) { + case OPT_CUSTOMIZE: + M_Menu_Keys_f(); + break; + case OPT_CONSOLE: + m_state = m_none; + Con_ToggleConsole_f(); + break; + case OPT_DEFAULTS: + if (SCR_ModalMessage("This will reset all controls\n" + "and stored cvars. Continue? (y/n)\n", 15.0f)) { + Cbuf_AddText("resetcfg\n"); + Cbuf_AddText("exec default.cfg\n"); + } + break; + case OPT_VIDEO: + M_Menu_Video_f(); + break; + default: + M_AdjustSliders(1); + break; + } + return; - case K_UPARROW: - S_LocalSound ("misc/menu1.wav"); - options_cursor--; - if (options_cursor < 0) - options_cursor = OPTIONS_ITEMS-1; - break; + case K_UPARROW: + S_LocalSound("misc/menu1.wav"); + options_cursor--; + if (options_cursor < 0) + options_cursor = OPTIONS_ITEMS - 1; + break; - case K_DOWNARROW: - S_LocalSound ("misc/menu1.wav"); - options_cursor++; - if (options_cursor >= OPTIONS_ITEMS) - options_cursor = 0; - break; + case K_DOWNARROW: + S_LocalSound("misc/menu1.wav"); + options_cursor++; + if (options_cursor >= OPTIONS_ITEMS) + options_cursor = 0; + break; - case K_LEFTARROW: - M_AdjustSliders (-1); - break; + case K_LEFTARROW: + M_AdjustSliders(-1); + break; - case K_RIGHTARROW: - M_AdjustSliders (1); - break; - } + case K_RIGHTARROW: + M_AdjustSliders(1); + break; + } - if (options_cursor == OPTIONS_ITEMS - 1 && vid_menudrawfn == NULL) - { - if (k == K_UPARROW) - options_cursor = OPTIONS_ITEMS - 2; - else - options_cursor = 0; - } + if (options_cursor == OPTIONS_ITEMS - 1 && vid_menudrawfn == NULL) { + if (k == K_UPARROW) + options_cursor = OPTIONS_ITEMS - 2; + else + options_cursor = 0; + } } //============================================================================= @@ -1341,1454 +1312,1355 @@ void M_Options_Key (int k) const char *bindnames[][2] = { - {"+attack", "attack"}, - {"impulse 10", "next weapon"}, - {"impulse 12", "prev weapon"}, - {"+jump", "jump / swim up"}, - {"+forward", "walk forward"}, - {"+back", "backpedal"}, - {"+left", "turn left"}, - {"+right", "turn right"}, - {"+speed", "run"}, - {"+moveleft", "step left"}, - {"+moveright", "step right"}, - {"+strafe", "sidestep"}, - {"+lookup", "look up"}, - {"+lookdown", "look down"}, - {"centerview", "center view"}, - {"+mlook", "mouse look"}, - {"+klook", "keyboard look"}, - {"+moveup", "swim up"}, - {"+movedown", "swim down"} + {"+attack", "attack"}, + {"impulse 10", "next weapon"}, + {"impulse 12", "prev weapon"}, + {"+jump", "jump / swim up"}, + {"+forward", "walk forward"}, + {"+back", "backpedal"}, + {"+left", "turn left"}, + {"+right", "turn right"}, + {"+speed", "run"}, + {"+moveleft", "step left"}, + {"+moveright", "step right"}, + {"+strafe", "sidestep"}, + {"+lookup", "look up"}, + {"+lookdown", "look down"}, + {"centerview", "center view"}, + {"+mlook", "mouse look"}, + {"+klook", "keyboard look"}, + {"+moveup", "swim up"}, + {"+movedown", "swim down"} }; #define NUMCOMMANDS Q_COUNTOF(bindnames) -static int keys_cursor; -static qboolean bind_grab; +static int keys_cursor; +static qboolean bind_grab; -void M_Menu_Keys_f (void) -{ - IN_Deactivate(modestate == MS_WINDOWED); - key_dest = key_menu; - m_state = m_keys; - m_entersound = true; +void M_Menu_Keys_f(void) { + IN_Deactivate(modestate == MS_WINDOWED); + key_dest = key_menu; + m_state = m_keys; + m_entersound = true; } -void M_FindKeysForCommand (const char *command, int *threekeys) -{ - int count; - int j; - int l; - char *b; +void M_FindKeysForCommand(const char *command, int *threekeys) { + int count; + int j; + int l; + char *b; - threekeys[0] = threekeys[1] = threekeys[2] = -1; - l = strlen(command); - count = 0; + threekeys[0] = threekeys[1] = threekeys[2] = -1; + l = strlen(command); + count = 0; - for (j = 0; j < MAX_KEYS; j++) - { - b = keybindings[j]; - if (!b) - continue; - if (!strncmp (b, command, l) ) - { - threekeys[count] = j; - count++; - if (count == 3) - break; - } - } + for (j = 0; j < MAX_KEYS; j++) { + b = keybindings[j]; + if (!b) + continue; + if (!strncmp(b, command, l)) { + threekeys[count] = j; + count++; + if (count == 3) + break; + } + } } -void M_UnbindCommand (const char *command) -{ - int j; - int l; - char *b; +void M_UnbindCommand(const char *command) { + int j; + int l; + char *b; - l = strlen(command); + l = strlen(command); - for (j = 0; j < MAX_KEYS; j++) - { - b = keybindings[j]; - if (!b) - continue; - if (!strncmp (b, command, l) ) - Key_SetBinding (j, NULL); - } + for (j = 0; j < MAX_KEYS; j++) { + b = keybindings[j]; + if (!b) + continue; + if (!strncmp(b, command, l)) + Key_SetBinding(j, NULL); + } } -extern qpic_t *pic_up, *pic_down; +extern qpic_t *pic_up, *pic_down; -void M_Keys_Draw (void) -{ - int i, x, y; - int keys[3]; - const char *name; - qpic_t *p; +void M_Keys_Draw(void) { + int i, x, y; + int keys[3]; + const char *name; + qpic_t *p; - p = Draw_CachePic ("gfx/ttl_cstm.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); + p = Draw_CachePic("gfx/ttl_cstm.lmp"); + M_DrawPic((320 - p->width) / 2, 4, p); - if (bind_grab) - M_Print (12, 32, "Press a key or button for this action"); - else - M_Print (18, 32, "Enter to change, backspace to clear"); + if (bind_grab) + M_Print(12, 32, "Press a key or button for this action"); + else + M_Print(18, 32, "Enter to change, backspace to clear"); -// search for known bindings - for (i = 0; i < (int)NUMCOMMANDS; i++) - { - y = 48 + 8*i; + // search for known bindings + for (i = 0; i < (int) NUMCOMMANDS; i++) { + y = 48 + 8 * i; - M_Print (16, y, bindnames[i][1]); + M_Print(16, y, bindnames[i][1]); - M_FindKeysForCommand (bindnames[i][0], keys); + M_FindKeysForCommand(bindnames[i][0], keys); - if (keys[0] == -1) - { - M_Print (140, y, "???"); - } - else - { - name = Key_KeynumToString (keys[0]); - M_Print (140, y, name); - x = strlen(name) * 8; - if (keys[1] != -1) - { - name = Key_KeynumToString (keys[1]); - M_Print (140 + x + 8, y, "or"); - M_Print (140 + x + 32, y, name); - x = x + 32 + strlen(name) * 8; - if (keys[2] != -1) - { - M_Print (140 + x + 8, y, "or"); - M_Print (140 + x + 32, y, Key_KeynumToString (keys[2])); - } - } - } - } + if (keys[0] == -1) { + M_Print(140, y, "???"); + } else { + name = Key_KeynumToString(keys[0]); + M_Print(140, y, name); + x = strlen(name) * 8; + if (keys[1] != -1) { + name = Key_KeynumToString(keys[1]); + M_Print(140 + x + 8, y, "or"); + M_Print(140 + x + 32, y, name); + x = x + 32 + strlen(name) * 8; + if (keys[2] != -1) { + M_Print(140 + x + 8, y, "or"); + M_Print(140 + x + 32, y, Key_KeynumToString(keys[2])); + } + } + } + } - if (bind_grab) - M_DrawCharacter (130, 48 + keys_cursor*8, '='); - else - M_DrawCharacter (130, 48 + keys_cursor*8, 12+((int)(realtime*4)&1)); + if (bind_grab) + M_DrawCharacter(130, 48 + keys_cursor * 8, '='); + else + M_DrawCharacter(130, 48 + keys_cursor * 8, 12 + ((int) (realtime * 4) & 1)); } -void M_Keys_Key (int k) -{ - char cmd[80]; - int keys[3]; +void M_Keys_Key(int k) { + char cmd[80]; + int keys[3]; - if (bind_grab) - { // defining a key - S_LocalSound ("misc/menu1.wav"); - if ((k != K_ESCAPE) && (k != '`')) - { - sprintf (cmd, "bind \"%s\" \"%s\"\n", Key_KeynumToString (k), bindnames[keys_cursor][0]); - Cbuf_InsertText (cmd); - } + if (bind_grab) { + // defining a key + S_LocalSound("misc/menu1.wav"); + if ((k != K_ESCAPE) && (k != '`')) { + sprintf(cmd, "bind \"%s\" \"%s\"\n", Key_KeynumToString(k), bindnames[keys_cursor][0]); + Cbuf_InsertText(cmd); + } - bind_grab = false; - IN_Deactivate(modestate == MS_WINDOWED); // deactivate because we're returning to the menu - return; - } + bind_grab = false; + IN_Deactivate(modestate == MS_WINDOWED); // deactivate because we're returning to the menu + return; + } - switch (k) - { - case K_ESCAPE: - case K_BBUTTON: - M_Menu_Options_f (); - break; + switch (k) { + case K_ESCAPE: + case K_BBUTTON: + M_Menu_Options_f(); + break; - case K_LEFTARROW: - case K_UPARROW: - S_LocalSound ("misc/menu1.wav"); - keys_cursor--; - if (keys_cursor < 0) - keys_cursor = NUMCOMMANDS-1; - break; + case K_LEFTARROW: + case K_UPARROW: + S_LocalSound("misc/menu1.wav"); + keys_cursor--; + if (keys_cursor < 0) + keys_cursor = NUMCOMMANDS - 1; + break; - case K_DOWNARROW: - case K_RIGHTARROW: - S_LocalSound ("misc/menu1.wav"); - keys_cursor++; - if (keys_cursor >= (int)NUMCOMMANDS) - keys_cursor = 0; - break; + case K_DOWNARROW: + case K_RIGHTARROW: + S_LocalSound("misc/menu1.wav"); + keys_cursor++; + if (keys_cursor >= (int) NUMCOMMANDS) + keys_cursor = 0; + break; - case K_ENTER: // go into bind mode - case K_KP_ENTER: - case K_ABUTTON: - M_FindKeysForCommand (bindnames[keys_cursor][0], keys); - S_LocalSound ("misc/menu2.wav"); - if (keys[2] != -1) - M_UnbindCommand (bindnames[keys_cursor][0]); - bind_grab = true; - IN_Activate(); // activate to allow mouse key binding - break; + case K_ENTER: // go into bind mode + case K_KP_ENTER: + case K_ABUTTON: + M_FindKeysForCommand(bindnames[keys_cursor][0], keys); + S_LocalSound("misc/menu2.wav"); + if (keys[2] != -1) + M_UnbindCommand(bindnames[keys_cursor][0]); + bind_grab = true; + IN_Activate(); // activate to allow mouse key binding + break; - case K_BACKSPACE: // delete bindings - case K_DEL: - S_LocalSound ("misc/menu2.wav"); - M_UnbindCommand (bindnames[keys_cursor][0]); - break; - } + case K_BACKSPACE: // delete bindings + case K_DEL: + S_LocalSound("misc/menu2.wav"); + M_UnbindCommand(bindnames[keys_cursor][0]); + break; + } } //============================================================================= /* VIDEO MENU */ -void M_Menu_Video_f (void) -{ - (*vid_menucmdfn) (); //johnfitz +void M_Menu_Video_f(void) { + (*vid_menucmdfn)(); //johnfitz } -void M_Video_Draw (void) -{ - (*vid_menudrawfn) (); +void M_Video_Draw(void) { + (*vid_menudrawfn)(); } -void M_Video_Key (int key) -{ - (*vid_menukeyfn) (key); +void M_Video_Key(int key) { + (*vid_menukeyfn)(key); } //============================================================================= /* HELP MENU */ -int help_page; +int help_page; #define NUM_HELP_PAGES 6 -void M_Menu_Help_f (void) -{ - IN_Deactivate(modestate == MS_WINDOWED); - key_dest = key_menu; - m_state = m_help; - m_entersound = true; - help_page = 0; +void M_Menu_Help_f(void) { + IN_Deactivate(modestate == MS_WINDOWED); + key_dest = key_menu; + m_state = m_help; + m_entersound = true; + help_page = 0; } - -void M_Help_Draw (void) -{ - M_DrawPic (0, 0, Draw_CachePic ( va("gfx/help%i.lmp", help_page)) ); +void M_Help_Draw(void) { + M_DrawPic(0, 0, Draw_CachePic(va("gfx/help%i.lmp", help_page))); } -void M_Help_Key (int key) -{ - switch (key) - { - case K_ESCAPE: - case K_BBUTTON: - M_Menu_Main_f (); - break; +void M_Help_Key(int key) { + switch (key) { + case K_ESCAPE: + case K_BBUTTON: + M_Menu_Main_f(); + break; - case K_UPARROW: - case K_RIGHTARROW: - m_entersound = true; - if (++help_page >= NUM_HELP_PAGES) - help_page = 0; - break; - - case K_DOWNARROW: - case K_LEFTARROW: - m_entersound = true; - if (--help_page < 0) - help_page = NUM_HELP_PAGES-1; - break; - } + case K_UPARROW: + case K_RIGHTARROW: + m_entersound = true; + if (++help_page >= NUM_HELP_PAGES) + help_page = 0; + break; + case K_DOWNARROW: + case K_LEFTARROW: + m_entersound = true; + if (--help_page < 0) + help_page = NUM_HELP_PAGES - 1; + break; + } } //============================================================================= /* QUIT MENU */ -int msgNumber; -enum m_state_e m_quit_prevstate; -qboolean wasInMenus; +int msgNumber; +enum m_state_e m_quit_prevstate; +qboolean wasInMenus; -void M_Menu_Quit_f (void) -{ - if (m_state == m_quit) - return; - wasInMenus = (key_dest == key_menu); - IN_Deactivate(modestate == MS_WINDOWED); - key_dest = key_menu; - m_quit_prevstate = m_state; - m_state = m_quit; - m_entersound = true; - msgNumber = rand()&7; +void M_Menu_Quit_f(void) { + if (m_state == m_quit) + return; + wasInMenus = (key_dest == key_menu); + IN_Deactivate(modestate == MS_WINDOWED); + key_dest = key_menu; + m_quit_prevstate = m_state; + m_state = m_quit; + m_entersound = true; + msgNumber = rand() & 7; } -void M_Quit_Key (int key) -{ - if (key == K_ESCAPE) - { - if (wasInMenus) - { - m_state = m_quit_prevstate; - m_entersound = true; - } - else - { - IN_Activate(); - key_dest = key_game; - m_state = m_none; - } - } +void M_Quit_Key(int key) { + if (key == K_ESCAPE) { + if (wasInMenus) { + m_state = m_quit_prevstate; + m_entersound = true; + } else { + IN_Activate(); + key_dest = key_game; + m_state = m_none; + } + } } -void M_Quit_Char (int key) -{ - switch (key) - { - case 'n': - case 'N': - if (wasInMenus) - { - m_state = m_quit_prevstate; - m_entersound = true; - } - else - { - IN_Activate(); - key_dest = key_game; - m_state = m_none; - } - break; +void M_Quit_Char(int key) { + switch (key) { + case 'n': + case 'N': + if (wasInMenus) { + m_state = m_quit_prevstate; + m_entersound = true; + } else { + IN_Activate(); + key_dest = key_game; + m_state = m_none; + } + break; - case 'y': - case 'Y': - IN_Deactivate(modestate == MS_WINDOWED); - key_dest = key_console; - Host_Quit_f (); - break; - - default: - break; - } + case 'y': + case 'Y': + IN_Deactivate(modestate == MS_WINDOWED); + key_dest = key_console; + Host_Quit_f(); + break; + default: + break; + } } -qboolean M_Quit_TextEntry (void) -{ - return true; +qboolean M_Quit_TextEntry(void) { + return true; } -void M_Quit_Draw (void) //johnfitz -- modified for new quit message +void M_Quit_Draw(void) //johnfitz -- modified for new quit message { - char msg1[] = "QuakeSpasm " QUAKESPASM_VER_STRING; - char msg2[] = "by Ozkan Sezer,Eric Wasylishen,others"; /* msg2/msg3 are [38] at most */ - char msg3[] = "Press y to quit"; - int boxlen; + char msg1[] = "QuakeSpasm " QUAKESPASM_VER_STRING; + char msg2[] = "by Ozkan Sezer,Eric Wasylishen,others"; /* msg2/msg3 are [38] at most */ + char msg3[] = "Press y to quit"; + int boxlen; - if (wasInMenus) - { - m_state = m_quit_prevstate; - m_recursiveDraw = true; - M_Draw (); - m_state = m_quit; - } + if (wasInMenus) { + m_state = m_quit_prevstate; + m_recursiveDraw = true; + M_Draw(); + m_state = m_quit; + } - //okay, this is kind of fucked up. M_DrawTextBox will always act as if - //width is even. Also, the width and lines values are for the interior of the box, - //but the x and y values include the border. - boxlen = (q_max(sizeof(msg1), q_max(sizeof(msg2),sizeof(msg3))) + 1) & ~1; - M_DrawTextBox (160-4*(boxlen+2), 76, boxlen, 4); + //okay, this is kind of fucked up. M_DrawTextBox will always act as if + //width is even. Also, the width and lines values are for the interior of the box, + //but the x and y values include the border. + boxlen = (std::max(sizeof(msg1), std::max(sizeof(msg2),sizeof(msg3))) + 1) & ~1; + M_DrawTextBox(160 - 4 * (boxlen + 2), 76, boxlen, 4); - //now do the text - M_Print (160-4*(sizeof(msg1)-1), 88, msg1); - M_Print (160-4*(sizeof(msg2)-1), 96, msg2); - M_PrintWhite (160-4*(sizeof(msg3)-1), 104, msg3); + //now do the text + M_Print(160 - 4 * (sizeof(msg1) - 1), 88, msg1); + M_Print(160 - 4 * (sizeof(msg2) - 1), 96, msg2); + M_PrintWhite(160 - 4 * (sizeof(msg3) - 1), 104, msg3); } //============================================================================= /* LAN CONFIG MENU */ -int lanConfig_cursor = -1; -int lanConfig_cursor_table [] = {72, 92, 124}; +int lanConfig_cursor = -1; +int lanConfig_cursor_table[] = {72, 92, 124}; #define NUM_LANCONFIG_CMDS 3 -int lanConfig_port; -char lanConfig_portname[6]; -char lanConfig_joinname[22]; +int lanConfig_port; +char lanConfig_portname[6]; +char lanConfig_joinname[22]; -void M_Menu_LanConfig_f (void) -{ - IN_Deactivate(modestate == MS_WINDOWED); - key_dest = key_menu; - m_state = m_lanconfig; - m_entersound = true; - if (lanConfig_cursor == -1) - { - if (JoiningGame && TCPIPConfig) - lanConfig_cursor = 2; - else - lanConfig_cursor = 1; - } - if (StartingGame && lanConfig_cursor == 2) - lanConfig_cursor = 1; - lanConfig_port = DEFAULTnet_hostport; - sprintf(lanConfig_portname, "%u", lanConfig_port); +void M_Menu_LanConfig_f(void) { + IN_Deactivate(modestate == MS_WINDOWED); + key_dest = key_menu; + m_state = m_lanconfig; + m_entersound = true; + if (lanConfig_cursor == -1) { + if (JoiningGame && TCPIPConfig) + lanConfig_cursor = 2; + else + lanConfig_cursor = 1; + } + if (StartingGame && lanConfig_cursor == 2) + lanConfig_cursor = 1; + lanConfig_port = DEFAULTnet_hostport; + sprintf(lanConfig_portname, "%u", lanConfig_port); - m_return_onerror = false; - m_return_reason[0] = 0; + m_return_onerror = false; + m_return_reason[0] = 0; } -void M_LanConfig_Draw (void) -{ - qpic_t *p; - int basex; - const char *startJoin; - const char *protocol; +void M_LanConfig_Draw(void) { + qpic_t *p; + int basex; + const char *startJoin; + const char *protocol; - M_DrawTransPic (16, 4, Draw_CachePic ("gfx/qplaque.lmp") ); - p = Draw_CachePic ("gfx/p_multi.lmp"); - basex = (320-p->width)/2; - M_DrawPic (basex, 4, p); + M_DrawTransPic(16, 4, Draw_CachePic("gfx/qplaque.lmp")); + p = Draw_CachePic("gfx/p_multi.lmp"); + basex = (320 - p->width) / 2; + M_DrawPic(basex, 4, p); - basex = 72; /* Arcane Dimensions has an oversized gfx/p_multi.lmp */ + basex = 72; /* Arcane Dimensions has an oversized gfx/p_multi.lmp */ - if (StartingGame) - startJoin = "New Game"; - else - startJoin = "Join Game"; - if (IPXConfig) - protocol = "IPX"; - else - protocol = "TCP/IP"; - M_Print (basex, 32, va ("%s - %s", startJoin, protocol)); - basex += 8; + if (StartingGame) + startJoin = "New Game"; + else + startJoin = "Join Game"; + if (IPXConfig) + protocol = "IPX"; + else + protocol = "TCP/IP"; + M_Print(basex, 32, va("%s - %s", startJoin, protocol)); + basex += 8; - M_Print (basex, 52, "Address:"); - if (IPXConfig) - M_Print (basex+9*8, 52, my_ipx_address); - else - M_Print (basex+9*8, 52, my_tcpip_address); + M_Print(basex, 52, "Address:"); + if (IPXConfig) + M_Print(basex + 9 * 8, 52, my_ipx_address); + else + M_Print(basex + 9 * 8, 52, my_tcpip_address); - M_Print (basex, lanConfig_cursor_table[0], "Port"); - M_DrawTextBox (basex+8*8, lanConfig_cursor_table[0]-8, 6, 1); - M_Print (basex+9*8, lanConfig_cursor_table[0], lanConfig_portname); + M_Print(basex, lanConfig_cursor_table[0], "Port"); + M_DrawTextBox(basex + 8 * 8, lanConfig_cursor_table[0] - 8, 6, 1); + M_Print(basex + 9 * 8, lanConfig_cursor_table[0], lanConfig_portname); - if (JoiningGame) - { - M_Print (basex, lanConfig_cursor_table[1], "Search for local games..."); - M_Print (basex, 108, "Join game at:"); - M_DrawTextBox (basex+8, lanConfig_cursor_table[2]-8, 22, 1); - M_Print (basex+16, lanConfig_cursor_table[2], lanConfig_joinname); - } - else - { - M_DrawTextBox (basex, lanConfig_cursor_table[1]-8, 2, 1); - M_Print (basex+8, lanConfig_cursor_table[1], "OK"); - } + if (JoiningGame) { + M_Print(basex, lanConfig_cursor_table[1], "Search for local games..."); + M_Print(basex, 108, "Join game at:"); + M_DrawTextBox(basex + 8, lanConfig_cursor_table[2] - 8, 22, 1); + M_Print(basex + 16, lanConfig_cursor_table[2], lanConfig_joinname); + } else { + M_DrawTextBox(basex, lanConfig_cursor_table[1] - 8, 2, 1); + M_Print(basex + 8, lanConfig_cursor_table[1], "OK"); + } - M_DrawCharacter (basex-8, lanConfig_cursor_table [lanConfig_cursor], 12+((int)(realtime*4)&1)); + M_DrawCharacter(basex - 8, lanConfig_cursor_table[lanConfig_cursor], 12 + ((int) (realtime * 4) & 1)); - if (lanConfig_cursor == 0) - M_DrawCharacter (basex+9*8 + 8*strlen(lanConfig_portname), lanConfig_cursor_table [0], 10+((int)(realtime*4)&1)); + if (lanConfig_cursor == 0) + M_DrawCharacter(basex + 9 * 8 + 8 * strlen(lanConfig_portname), lanConfig_cursor_table[0], + 10 + ((int) (realtime * 4) & 1)); - if (lanConfig_cursor == 2) - M_DrawCharacter (basex+16 + 8*strlen(lanConfig_joinname), lanConfig_cursor_table [2], 10+((int)(realtime*4)&1)); + if (lanConfig_cursor == 2) + M_DrawCharacter(basex + 16 + 8 * strlen(lanConfig_joinname), lanConfig_cursor_table[2], + 10 + ((int) (realtime * 4) & 1)); - if (*m_return_reason) - M_PrintWhite (basex, 148, m_return_reason); + if (*m_return_reason) + M_PrintWhite(basex, 148, m_return_reason); } -void M_LanConfig_Key (int key) -{ - int l; +void M_LanConfig_Key(int key) { + int l; - switch (key) - { - case K_ESCAPE: - case K_BBUTTON: - M_Menu_Net_f (); - break; + switch (key) { + case K_ESCAPE: + case K_BBUTTON: + M_Menu_Net_f(); + break; - case K_UPARROW: - S_LocalSound ("misc/menu1.wav"); - lanConfig_cursor--; - if (lanConfig_cursor < 0) - lanConfig_cursor = NUM_LANCONFIG_CMDS-1; - break; + case K_UPARROW: + S_LocalSound("misc/menu1.wav"); + lanConfig_cursor--; + if (lanConfig_cursor < 0) + lanConfig_cursor = NUM_LANCONFIG_CMDS - 1; + break; - case K_DOWNARROW: - S_LocalSound ("misc/menu1.wav"); - lanConfig_cursor++; - if (lanConfig_cursor >= NUM_LANCONFIG_CMDS) - lanConfig_cursor = 0; - break; + case K_DOWNARROW: + S_LocalSound("misc/menu1.wav"); + lanConfig_cursor++; + if (lanConfig_cursor >= NUM_LANCONFIG_CMDS) + lanConfig_cursor = 0; + break; - case K_ENTER: - case K_KP_ENTER: - case K_ABUTTON: - if (lanConfig_cursor == 0) - break; + case K_ENTER: + case K_KP_ENTER: + case K_ABUTTON: + if (lanConfig_cursor == 0) + break; - m_entersound = true; + m_entersound = true; - M_ConfigureNetSubsystem (); + M_ConfigureNetSubsystem(); - if (lanConfig_cursor == 1) - { - if (StartingGame) - { - M_Menu_GameOptions_f (); - break; - } - M_Menu_Search_f(); - break; - } + if (lanConfig_cursor == 1) { + if (StartingGame) { + M_Menu_GameOptions_f(); + break; + } + M_Menu_Search_f(); + break; + } - if (lanConfig_cursor == 2) - { - m_return_state = m_state; - m_return_onerror = true; - IN_Activate(); - key_dest = key_game; - m_state = m_none; - Cbuf_AddText ( va ("connect \"%s\"\n", lanConfig_joinname) ); - break; - } + if (lanConfig_cursor == 2) { + m_return_state = m_state; + m_return_onerror = true; + IN_Activate(); + key_dest = key_game; + m_state = m_none; + Cbuf_AddText(va("connect \"%s\"\n", lanConfig_joinname)); + break; + } - break; + break; - case K_BACKSPACE: - if (lanConfig_cursor == 0) - { - if (strlen(lanConfig_portname)) - lanConfig_portname[strlen(lanConfig_portname)-1] = 0; - } + case K_BACKSPACE: + if (lanConfig_cursor == 0) { + if (strlen(lanConfig_portname)) + lanConfig_portname[strlen(lanConfig_portname) - 1] = 0; + } - if (lanConfig_cursor == 2) - { - if (strlen(lanConfig_joinname)) - lanConfig_joinname[strlen(lanConfig_joinname)-1] = 0; - } - break; - } + if (lanConfig_cursor == 2) { + if (strlen(lanConfig_joinname)) + lanConfig_joinname[strlen(lanConfig_joinname) - 1] = 0; + } + break; + } - if (StartingGame && lanConfig_cursor == 2) - { - if (key == K_UPARROW) - lanConfig_cursor = 1; - else - lanConfig_cursor = 0; - } + if (StartingGame && lanConfig_cursor == 2) { + if (key == K_UPARROW) + lanConfig_cursor = 1; + else + lanConfig_cursor = 0; + } - l = Q_atoi(lanConfig_portname); - if (l > 65535) - l = lanConfig_port; - else - lanConfig_port = l; - sprintf(lanConfig_portname, "%u", lanConfig_port); + l = Q_atoi(lanConfig_portname); + if (l > 65535) + l = lanConfig_port; + else + lanConfig_port = l; + sprintf(lanConfig_portname, "%u", lanConfig_port); } -void M_LanConfig_Char (int key) -{ - int l; +void M_LanConfig_Char(int key) { + int l; - switch (lanConfig_cursor) - { - case 0: - if (key < '0' || key > '9') - return; - l = strlen(lanConfig_portname); - if (l < 5) - { - lanConfig_portname[l+1] = 0; - lanConfig_portname[l] = key; - } - break; - case 2: - l = strlen(lanConfig_joinname); - if (l < 21) - { - lanConfig_joinname[l+1] = 0; - lanConfig_joinname[l] = key; - } - break; - } + switch (lanConfig_cursor) { + case 0: + if (key < '0' || key > '9') + return; + l = strlen(lanConfig_portname); + if (l < 5) { + lanConfig_portname[l + 1] = 0; + lanConfig_portname[l] = key; + } + break; + case 2: + l = strlen(lanConfig_joinname); + if (l < 21) { + lanConfig_joinname[l + 1] = 0; + lanConfig_joinname[l] = key; + } + break; + } } -qboolean M_LanConfig_TextEntry (void) -{ - return (lanConfig_cursor == 0 || lanConfig_cursor == 2); +qboolean M_LanConfig_TextEntry(void) { + return (lanConfig_cursor == 0 || lanConfig_cursor == 2); } //============================================================================= /* GAME OPTIONS MENU */ -typedef struct -{ - const char *name; - const char *description; +typedef struct { + const char *name; + const char *description; } level_t; -level_t levels[] = +level_t levels[] = { - {"start", "Entrance"}, // 0 + {"start", "Entrance"}, // 0 - {"e1m1", "Slipgate Complex"}, // 1 - {"e1m2", "Castle of the Damned"}, - {"e1m3", "The Necropolis"}, - {"e1m4", "The Grisly Grotto"}, - {"e1m5", "Gloom Keep"}, - {"e1m6", "The Door To Chthon"}, - {"e1m7", "The House of Chthon"}, - {"e1m8", "Ziggurat Vertigo"}, + {"e1m1", "Slipgate Complex"}, // 1 + {"e1m2", "Castle of the Damned"}, + {"e1m3", "The Necropolis"}, + {"e1m4", "The Grisly Grotto"}, + {"e1m5", "Gloom Keep"}, + {"e1m6", "The Door To Chthon"}, + {"e1m7", "The House of Chthon"}, + {"e1m8", "Ziggurat Vertigo"}, - {"e2m1", "The Installation"}, // 9 - {"e2m2", "Ogre Citadel"}, - {"e2m3", "Crypt of Decay"}, - {"e2m4", "The Ebon Fortress"}, - {"e2m5", "The Wizard's Manse"}, - {"e2m6", "The Dismal Oubliette"}, - {"e2m7", "Underearth"}, + {"e2m1", "The Installation"}, // 9 + {"e2m2", "Ogre Citadel"}, + {"e2m3", "Crypt of Decay"}, + {"e2m4", "The Ebon Fortress"}, + {"e2m5", "The Wizard's Manse"}, + {"e2m6", "The Dismal Oubliette"}, + {"e2m7", "Underearth"}, - {"e3m1", "Termination Central"}, // 16 - {"e3m2", "The Vaults of Zin"}, - {"e3m3", "The Tomb of Terror"}, - {"e3m4", "Satan's Dark Delight"}, - {"e3m5", "Wind Tunnels"}, - {"e3m6", "Chambers of Torment"}, - {"e3m7", "The Haunted Halls"}, + {"e3m1", "Termination Central"}, // 16 + {"e3m2", "The Vaults of Zin"}, + {"e3m3", "The Tomb of Terror"}, + {"e3m4", "Satan's Dark Delight"}, + {"e3m5", "Wind Tunnels"}, + {"e3m6", "Chambers of Torment"}, + {"e3m7", "The Haunted Halls"}, - {"e4m1", "The Sewage System"}, // 23 - {"e4m2", "The Tower of Despair"}, - {"e4m3", "The Elder God Shrine"}, - {"e4m4", "The Palace of Hate"}, - {"e4m5", "Hell's Atrium"}, - {"e4m6", "The Pain Maze"}, - {"e4m7", "Azure Agony"}, - {"e4m8", "The Nameless City"}, + {"e4m1", "The Sewage System"}, // 23 + {"e4m2", "The Tower of Despair"}, + {"e4m3", "The Elder God Shrine"}, + {"e4m4", "The Palace of Hate"}, + {"e4m5", "Hell's Atrium"}, + {"e4m6", "The Pain Maze"}, + {"e4m7", "Azure Agony"}, + {"e4m8", "The Nameless City"}, - {"end", "Shub-Niggurath's Pit"}, // 31 + {"end", "Shub-Niggurath's Pit"}, // 31 - {"dm1", "Place of Two Deaths"}, // 32 - {"dm2", "Claustrophobopolis"}, - {"dm3", "The Abandoned Base"}, - {"dm4", "The Bad Place"}, - {"dm5", "The Cistern"}, - {"dm6", "The Dark Zone"} + {"dm1", "Place of Two Deaths"}, // 32 + {"dm2", "Claustrophobopolis"}, + {"dm3", "The Abandoned Base"}, + {"dm4", "The Bad Place"}, + {"dm5", "The Cistern"}, + {"dm6", "The Dark Zone"} }; //MED 01/06/97 added hipnotic levels -level_t hipnoticlevels[] = +level_t hipnoticlevels[] = { - {"start", "Command HQ"}, // 0 + {"start", "Command HQ"}, // 0 - {"hip1m1", "The Pumping Station"}, // 1 - {"hip1m2", "Storage Facility"}, - {"hip1m3", "The Lost Mine"}, - {"hip1m4", "Research Facility"}, - {"hip1m5", "Military Complex"}, + {"hip1m1", "The Pumping Station"}, // 1 + {"hip1m2", "Storage Facility"}, + {"hip1m3", "The Lost Mine"}, + {"hip1m4", "Research Facility"}, + {"hip1m5", "Military Complex"}, - {"hip2m1", "Ancient Realms"}, // 6 - {"hip2m2", "The Black Cathedral"}, - {"hip2m3", "The Catacombs"}, - {"hip2m4", "The Crypt"}, - {"hip2m5", "Mortum's Keep"}, - {"hip2m6", "The Gremlin's Domain"}, + {"hip2m1", "Ancient Realms"}, // 6 + {"hip2m2", "The Black Cathedral"}, + {"hip2m3", "The Catacombs"}, + {"hip2m4", "The Crypt"}, + {"hip2m5", "Mortum's Keep"}, + {"hip2m6", "The Gremlin's Domain"}, - {"hip3m1", "Tur Torment"}, // 12 - {"hip3m2", "Pandemonium"}, - {"hip3m3", "Limbo"}, - {"hip3m4", "The Gauntlet"}, + {"hip3m1", "Tur Torment"}, // 12 + {"hip3m2", "Pandemonium"}, + {"hip3m3", "Limbo"}, + {"hip3m4", "The Gauntlet"}, - {"hipend", "Armagon's Lair"}, // 16 + {"hipend", "Armagon's Lair"}, // 16 - {"hipdm1", "The Edge of Oblivion"} // 17 + {"hipdm1", "The Edge of Oblivion"} // 17 }; //PGM 01/07/97 added rogue levels //PGM 03/02/97 added dmatch level -level_t roguelevels[] = +level_t roguelevels[] = { - {"start", "Split Decision"}, - {"r1m1", "Deviant's Domain"}, - {"r1m2", "Dread Portal"}, - {"r1m3", "Judgement Call"}, - {"r1m4", "Cave of Death"}, - {"r1m5", "Towers of Wrath"}, - {"r1m6", "Temple of Pain"}, - {"r1m7", "Tomb of the Overlord"}, - {"r2m1", "Tempus Fugit"}, - {"r2m2", "Elemental Fury I"}, - {"r2m3", "Elemental Fury II"}, - {"r2m4", "Curse of Osiris"}, - {"r2m5", "Wizard's Keep"}, - {"r2m6", "Blood Sacrifice"}, - {"r2m7", "Last Bastion"}, - {"r2m8", "Source of Evil"}, - {"ctf1", "Division of Change"} + {"start", "Split Decision"}, + {"r1m1", "Deviant's Domain"}, + {"r1m2", "Dread Portal"}, + {"r1m3", "Judgement Call"}, + {"r1m4", "Cave of Death"}, + {"r1m5", "Towers of Wrath"}, + {"r1m6", "Temple of Pain"}, + {"r1m7", "Tomb of the Overlord"}, + {"r2m1", "Tempus Fugit"}, + {"r2m2", "Elemental Fury I"}, + {"r2m3", "Elemental Fury II"}, + {"r2m4", "Curse of Osiris"}, + {"r2m5", "Wizard's Keep"}, + {"r2m6", "Blood Sacrifice"}, + {"r2m7", "Last Bastion"}, + {"r2m8", "Source of Evil"}, + {"ctf1", "Division of Change"} }; -typedef struct -{ - const char *description; - int firstLevel; - int levels; +typedef struct { + const char *description; + int firstLevel; + int levels; } episode_t; -episode_t episodes[] = +episode_t episodes[] = { - {"Welcome to Quake", 0, 1}, - {"Doomed Dimension", 1, 8}, - {"Realm of Black Magic", 9, 7}, - {"Netherworld", 16, 7}, - {"The Elder World", 23, 8}, - {"Final Level", 31, 1}, - {"Deathmatch Arena", 32, 6} + {"Welcome to Quake", 0, 1}, + {"Doomed Dimension", 1, 8}, + {"Realm of Black Magic", 9, 7}, + {"Netherworld", 16, 7}, + {"The Elder World", 23, 8}, + {"Final Level", 31, 1}, + {"Deathmatch Arena", 32, 6} }; //MED 01/06/97 added hipnotic episodes -episode_t hipnoticepisodes[] = +episode_t hipnoticepisodes[] = { - {"Scourge of Armagon", 0, 1}, - {"Fortress of the Dead", 1, 5}, - {"Dominion of Darkness", 6, 6}, - {"The Rift", 12, 4}, - {"Final Level", 16, 1}, - {"Deathmatch Arena", 17, 1} + {"Scourge of Armagon", 0, 1}, + {"Fortress of the Dead", 1, 5}, + {"Dominion of Darkness", 6, 6}, + {"The Rift", 12, 4}, + {"Final Level", 16, 1}, + {"Deathmatch Arena", 17, 1} }; //PGM 01/07/97 added rogue episodes //PGM 03/02/97 added dmatch episode -episode_t rogueepisodes[] = +episode_t rogueepisodes[] = { - {"Introduction", 0, 1}, - {"Hell's Fortress", 1, 7}, - {"Corridors of Time", 8, 8}, - {"Deathmatch Arena", 16, 1} + {"Introduction", 0, 1}, + {"Hell's Fortress", 1, 7}, + {"Corridors of Time", 8, 8}, + {"Deathmatch Arena", 16, 1} }; -int startepisode; -int startlevel; +int startepisode; +int startlevel; int maxplayers; qboolean m_serverInfoMessage = false; double m_serverInfoMessageTime; -void M_Menu_GameOptions_f (void) -{ - IN_Deactivate(modestate == MS_WINDOWED); - key_dest = key_menu; - m_state = m_gameoptions; - m_entersound = true; - if (maxplayers == 0) - maxplayers = svs.maxclients; - if (maxplayers < 2) - maxplayers = svs.maxclientslimit; +void M_Menu_GameOptions_f(void) { + IN_Deactivate(modestate == MS_WINDOWED); + key_dest = key_menu; + m_state = m_gameoptions; + m_entersound = true; + if (maxplayers == 0) + maxplayers = svs.maxclients; + if (maxplayers < 2) + maxplayers = svs.maxclientslimit; } int gameoptions_cursor_table[] = {40, 56, 64, 72, 80, 88, 96, 112, 120}; #define NUM_GAMEOPTIONS 9 -int gameoptions_cursor; +int gameoptions_cursor; -void M_GameOptions_Draw (void) -{ - qpic_t *p; - int x; +void M_GameOptions_Draw(void) { + qpic_t *p; + int x; - M_DrawTransPic (16, 4, Draw_CachePic ("gfx/qplaque.lmp") ); - p = Draw_CachePic ("gfx/p_multi.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); + M_DrawTransPic(16, 4, Draw_CachePic("gfx/qplaque.lmp")); + p = Draw_CachePic("gfx/p_multi.lmp"); + M_DrawPic((320 - p->width) / 2, 4, p); - M_DrawTextBox (152, 32, 10, 1); - M_Print (160, 40, "begin game"); + M_DrawTextBox(152, 32, 10, 1); + M_Print(160, 40, "begin game"); - M_Print (0, 56, " Max players"); - M_Print (160, 56, va("%i", maxplayers) ); + M_Print(0, 56, " Max players"); + M_Print(160, 56, va("%i", maxplayers)); - M_Print (0, 64, " Game Type"); - if (coop.value) - M_Print (160, 64, "Cooperative"); - else - M_Print (160, 64, "Deathmatch"); + M_Print(0, 64, " Game Type"); + if (coop.value) + M_Print(160, 64, "Cooperative"); + else + M_Print(160, 64, "Deathmatch"); - M_Print (0, 72, " Teamplay"); - if (rogue) - { - const char *msg; + M_Print(0, 72, " Teamplay"); + if (rogue) { + const char *msg; - switch((int)teamplay.value) - { - case 1: msg = "No Friendly Fire"; break; - case 2: msg = "Friendly Fire"; break; - case 3: msg = "Tag"; break; - case 4: msg = "Capture the Flag"; break; - case 5: msg = "One Flag CTF"; break; - case 6: msg = "Three Team CTF"; break; - default: msg = "Off"; break; - } - M_Print (160, 72, msg); - } - else - { - const char *msg; + switch ((int) teamplay.value) { + case 1: msg = "No Friendly Fire"; + break; + case 2: msg = "Friendly Fire"; + break; + case 3: msg = "Tag"; + break; + case 4: msg = "Capture the Flag"; + break; + case 5: msg = "One Flag CTF"; + break; + case 6: msg = "Three Team CTF"; + break; + default: msg = "Off"; + break; + } + M_Print(160, 72, msg); + } else { + const char *msg; - switch((int)teamplay.value) - { - case 1: msg = "No Friendly Fire"; break; - case 2: msg = "Friendly Fire"; break; - default: msg = "Off"; break; - } - M_Print (160, 72, msg); - } + switch ((int) teamplay.value) { + case 1: msg = "No Friendly Fire"; + break; + case 2: msg = "Friendly Fire"; + break; + default: msg = "Off"; + break; + } + M_Print(160, 72, msg); + } - M_Print (0, 80, " Skill"); - if (skill.value == 0) - M_Print (160, 80, "Easy difficulty"); - else if (skill.value == 1) - M_Print (160, 80, "Normal difficulty"); - else if (skill.value == 2) - M_Print (160, 80, "Hard difficulty"); - else - M_Print (160, 80, "Nightmare difficulty"); + M_Print(0, 80, " Skill"); + if (skill.value == 0) + M_Print(160, 80, "Easy difficulty"); + else if (skill.value == 1) + M_Print(160, 80, "Normal difficulty"); + else if (skill.value == 2) + M_Print(160, 80, "Hard difficulty"); + else + M_Print(160, 80, "Nightmare difficulty"); - M_Print (0, 88, " Frag Limit"); - if (fraglimit.value == 0) - M_Print (160, 88, "none"); - else - M_Print (160, 88, va("%i frags", (int)fraglimit.value)); + M_Print(0, 88, " Frag Limit"); + if (fraglimit.value == 0) + M_Print(160, 88, "none"); + else + M_Print(160, 88, va("%i frags", (int) fraglimit.value)); - M_Print (0, 96, " Time Limit"); - if (timelimit.value == 0) - M_Print (160, 96, "none"); - else - M_Print (160, 96, va("%i minutes", (int)timelimit.value)); + M_Print(0, 96, " Time Limit"); + if (timelimit.value == 0) + M_Print(160, 96, "none"); + else + M_Print(160, 96, va("%i minutes", (int) timelimit.value)); - M_Print (0, 112, " Episode"); - // MED 01/06/97 added hipnotic episodes - if (hipnotic) - M_Print (160, 112, hipnoticepisodes[startepisode].description); - // PGM 01/07/97 added rogue episodes - else if (rogue) - M_Print (160, 112, rogueepisodes[startepisode].description); - else - M_Print (160, 112, episodes[startepisode].description); + M_Print(0, 112, " Episode"); + // MED 01/06/97 added hipnotic episodes + if (hipnotic) + M_Print(160, 112, hipnoticepisodes[startepisode].description); + // PGM 01/07/97 added rogue episodes + else if (rogue) + M_Print(160, 112, rogueepisodes[startepisode].description); + else + M_Print(160, 112, episodes[startepisode].description); - M_Print (0, 120, " Level"); - // MED 01/06/97 added hipnotic episodes - if (hipnotic) - { - M_Print (160, 120, hipnoticlevels[hipnoticepisodes[startepisode].firstLevel + startlevel].description); - M_Print (160, 128, hipnoticlevels[hipnoticepisodes[startepisode].firstLevel + startlevel].name); - } - // PGM 01/07/97 added rogue episodes - else if (rogue) - { - M_Print (160, 120, roguelevels[rogueepisodes[startepisode].firstLevel + startlevel].description); - M_Print (160, 128, roguelevels[rogueepisodes[startepisode].firstLevel + startlevel].name); - } - else - { - M_Print (160, 120, levels[episodes[startepisode].firstLevel + startlevel].description); - M_Print (160, 128, levels[episodes[startepisode].firstLevel + startlevel].name); - } + M_Print(0, 120, " Level"); + // MED 01/06/97 added hipnotic episodes + if (hipnotic) { + M_Print(160, 120, hipnoticlevels[hipnoticepisodes[startepisode].firstLevel + startlevel].description); + M_Print(160, 128, hipnoticlevels[hipnoticepisodes[startepisode].firstLevel + startlevel].name); + } + // PGM 01/07/97 added rogue episodes + else if (rogue) { + M_Print(160, 120, roguelevels[rogueepisodes[startepisode].firstLevel + startlevel].description); + M_Print(160, 128, roguelevels[rogueepisodes[startepisode].firstLevel + startlevel].name); + } else { + M_Print(160, 120, levels[episodes[startepisode].firstLevel + startlevel].description); + M_Print(160, 128, levels[episodes[startepisode].firstLevel + startlevel].name); + } -// line cursor - M_DrawCharacter (144, gameoptions_cursor_table[gameoptions_cursor], 12+((int)(realtime*4)&1)); + // line cursor + M_DrawCharacter(144, gameoptions_cursor_table[gameoptions_cursor], 12 + ((int) (realtime * 4) & 1)); - if (m_serverInfoMessage) - { - if ((realtime - m_serverInfoMessageTime) < 5.0) - { - x = (320-26*8)/2; - M_DrawTextBox (x, 138, 24, 4); - x += 8; - M_Print (x, 146, " More than 4 players "); - M_Print (x, 154, " requires using command "); - M_Print (x, 162, "line parameters; please "); - M_Print (x, 170, " see techinfo.txt. "); - } - else - { - m_serverInfoMessage = false; - } - } + if (m_serverInfoMessage) { + if ((realtime - m_serverInfoMessageTime) < 5.0) { + x = (320 - 26 * 8) / 2; + M_DrawTextBox(x, 138, 24, 4); + x += 8; + M_Print(x, 146, " More than 4 players "); + M_Print(x, 154, " requires using command "); + M_Print(x, 162, "line parameters; please "); + M_Print(x, 170, " see techinfo.txt. "); + } else { + m_serverInfoMessage = false; + } + } } -void M_NetStart_Change (int dir) -{ - int count; - float f; +void M_NetStart_Change(int dir) { + int count; + float f; - switch (gameoptions_cursor) - { - case 1: - maxplayers += dir; - if (maxplayers > svs.maxclientslimit) - { - maxplayers = svs.maxclientslimit; - m_serverInfoMessage = true; - m_serverInfoMessageTime = realtime; - } - if (maxplayers < 2) - maxplayers = 2; - break; + switch (gameoptions_cursor) { + case 1: + maxplayers += dir; + if (maxplayers > svs.maxclientslimit) { + maxplayers = svs.maxclientslimit; + m_serverInfoMessage = true; + m_serverInfoMessageTime = realtime; + } + if (maxplayers < 2) + maxplayers = 2; + break; - case 2: - Cvar_Set ("coop", coop.value ? "0" : "1"); - break; + case 2: + convar::set("coop", coop.value ? "0" : "1"); + break; - case 3: - count = (rogue) ? 6 : 2; - f = teamplay.value + dir; - if (f > count) f = 0; - else if (f < 0) f = count; - Cvar_SetValue ("teamplay", f); - break; + case 3: + count = (rogue) ? 6 : 2; + f = teamplay.value + dir; + if (f > count) f = 0; + else if (f < 0) f = count; + convar::set_value("teamplay", f); + break; - case 4: - f = skill.value + dir; - if (f > 3) f = 0; - else if (f < 0) f = 3; - Cvar_SetValue ("skill", f); - break; + case 4: + f = skill.value + dir; + if (f > 3) f = 0; + else if (f < 0) f = 3; + convar::set_value("skill", f); + break; - case 5: - f = fraglimit.value + dir * 10; - if (f > 100) f = 0; - else if (f < 0) f = 100; - Cvar_SetValue ("fraglimit", f); - break; + case 5: + f = fraglimit.value + dir * 10; + if (f > 100) f = 0; + else if (f < 0) f = 100; + convar::set_value("fraglimit", f); + break; - case 6: - f = timelimit.value + dir * 5; - if (f > 60) f = 0; - else if (f < 0) f = 60; - Cvar_SetValue ("timelimit", f); - break; + case 6: + f = timelimit.value + dir * 5; + if (f > 60) f = 0; + else if (f < 0) f = 60; + convar::set_value("timelimit", f); + break; - case 7: - startepisode += dir; - //MED 01/06/97 added hipnotic count - if (hipnotic) - count = 6; - //PGM 01/07/97 added rogue count - //PGM 03/02/97 added 1 for dmatch episode - else if (rogue) - count = 4; - else if (registered.value) - count = 7; - else - count = 2; + case 7: + startepisode += dir; + //MED 01/06/97 added hipnotic count + if (hipnotic) + count = 6; + //PGM 01/07/97 added rogue count + //PGM 03/02/97 added 1 for dmatch episode + else if (rogue) + count = 4; + else if (registered.value) + count = 7; + else + count = 2; - if (startepisode < 0) - startepisode = count - 1; + if (startepisode < 0) + startepisode = count - 1; - if (startepisode >= count) - startepisode = 0; + if (startepisode >= count) + startepisode = 0; - startlevel = 0; - break; + startlevel = 0; + break; - case 8: - startlevel += dir; - //MED 01/06/97 added hipnotic episodes - if (hipnotic) - count = hipnoticepisodes[startepisode].levels; - //PGM 01/06/97 added hipnotic episodes - else if (rogue) - count = rogueepisodes[startepisode].levels; - else - count = episodes[startepisode].levels; + case 8: + startlevel += dir; + //MED 01/06/97 added hipnotic episodes + if (hipnotic) + count = hipnoticepisodes[startepisode].levels; + //PGM 01/06/97 added hipnotic episodes + else if (rogue) + count = rogueepisodes[startepisode].levels; + else + count = episodes[startepisode].levels; - if (startlevel < 0) - startlevel = count - 1; + if (startlevel < 0) + startlevel = count - 1; - if (startlevel >= count) - startlevel = 0; - break; - } + if (startlevel >= count) + startlevel = 0; + break; + } } -void M_GameOptions_Key (int key) -{ - switch (key) - { - case K_ESCAPE: - case K_BBUTTON: - M_Menu_Net_f (); - break; +void M_GameOptions_Key(int key) { + switch (key) { + case K_ESCAPE: + case K_BBUTTON: + M_Menu_Net_f(); + break; - case K_UPARROW: - S_LocalSound ("misc/menu1.wav"); - gameoptions_cursor--; - if (gameoptions_cursor < 0) - gameoptions_cursor = NUM_GAMEOPTIONS-1; - break; + case K_UPARROW: + S_LocalSound("misc/menu1.wav"); + gameoptions_cursor--; + if (gameoptions_cursor < 0) + gameoptions_cursor = NUM_GAMEOPTIONS - 1; + break; - case K_DOWNARROW: - S_LocalSound ("misc/menu1.wav"); - gameoptions_cursor++; - if (gameoptions_cursor >= NUM_GAMEOPTIONS) - gameoptions_cursor = 0; - break; + case K_DOWNARROW: + S_LocalSound("misc/menu1.wav"); + gameoptions_cursor++; + if (gameoptions_cursor >= NUM_GAMEOPTIONS) + gameoptions_cursor = 0; + break; - case K_LEFTARROW: - if (gameoptions_cursor == 0) - break; - S_LocalSound ("misc/menu3.wav"); - M_NetStart_Change (-1); - break; + case K_LEFTARROW: + if (gameoptions_cursor == 0) + break; + S_LocalSound("misc/menu3.wav"); + M_NetStart_Change(-1); + break; - case K_RIGHTARROW: - if (gameoptions_cursor == 0) - break; - S_LocalSound ("misc/menu3.wav"); - M_NetStart_Change (1); - break; + case K_RIGHTARROW: + if (gameoptions_cursor == 0) + break; + S_LocalSound("misc/menu3.wav"); + M_NetStart_Change(1); + break; - case K_ENTER: - case K_KP_ENTER: - case K_ABUTTON: - S_LocalSound ("misc/menu2.wav"); - if (gameoptions_cursor == 0) - { - if (sv.active) - Cbuf_AddText ("disconnect\n"); - Cbuf_AddText ("listen 0\n"); // so host_netport will be re-examined - Cbuf_AddText ( va ("maxplayers %u\n", maxplayers) ); - SCR_BeginLoadingPlaque (); + case K_ENTER: + case K_KP_ENTER: + case K_ABUTTON: + S_LocalSound("misc/menu2.wav"); + if (gameoptions_cursor == 0) { + if (sv.active) + Cbuf_AddText("disconnect\n"); + Cbuf_AddText("listen 0\n"); // so host_netport will be re-examined + Cbuf_AddText(va("maxplayers %u\n", maxplayers)); + SCR_BeginLoadingPlaque(); - if (hipnotic) - Cbuf_AddText ( va ("map %s\n", hipnoticlevels[hipnoticepisodes[startepisode].firstLevel + startlevel].name) ); - else if (rogue) - Cbuf_AddText ( va ("map %s\n", roguelevels[rogueepisodes[startepisode].firstLevel + startlevel].name) ); - else - Cbuf_AddText ( va ("map %s\n", levels[episodes[startepisode].firstLevel + startlevel].name) ); + if (hipnotic) + Cbuf_AddText(va( + "map %s\n", hipnoticlevels[hipnoticepisodes[startepisode].firstLevel + startlevel].name)); + else if (rogue) + Cbuf_AddText(va("map %s\n", roguelevels[rogueepisodes[startepisode].firstLevel + startlevel].name)); + else + Cbuf_AddText(va("map %s\n", levels[episodes[startepisode].firstLevel + startlevel].name)); - return; - } + return; + } - M_NetStart_Change (1); - break; - } + M_NetStart_Change(1); + break; + } } //============================================================================= /* SEARCH MENU */ -qboolean searchComplete = false; -double searchCompleteTime; - -void M_Menu_Search_f (void) -{ - IN_Deactivate(modestate == MS_WINDOWED); - key_dest = key_menu; - m_state = m_search; - m_entersound = false; - slistSilent = true; - slistLocal = false; - searchComplete = false; - NET_Slist_f(); +qboolean searchComplete = false; +double searchCompleteTime; +void M_Menu_Search_f(void) { + IN_Deactivate(modestate == MS_WINDOWED); + key_dest = key_menu; + m_state = m_search; + m_entersound = false; + slistSilent = true; + slistLocal = false; + searchComplete = false; + NET_Slist_f(); } -void M_Search_Draw (void) -{ - qpic_t *p; - int x; +void M_Search_Draw(void) { + qpic_t *p; + int x; - p = Draw_CachePic ("gfx/p_multi.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); - x = (320/2) - ((12*8)/2) + 4; - M_DrawTextBox (x-8, 32, 12, 1); - M_Print (x, 40, "Searching..."); + p = Draw_CachePic("gfx/p_multi.lmp"); + M_DrawPic((320 - p->width) / 2, 4, p); + x = (320 / 2) - ((12 * 8) / 2) + 4; + M_DrawTextBox(x - 8, 32, 12, 1); + M_Print(x, 40, "Searching..."); - if(slistInProgress) - { - NET_Poll(); - return; - } + if (slistInProgress) { + NET_Poll(); + return; + } - if (! searchComplete) - { - searchComplete = true; - searchCompleteTime = realtime; - } + if (!searchComplete) { + searchComplete = true; + searchCompleteTime = realtime; + } - if (hostCacheCount) - { - M_Menu_ServerList_f (); - return; - } + if (hostCacheCount) { + M_Menu_ServerList_f(); + return; + } - M_PrintWhite ((320/2) - ((22*8)/2), 64, "No Quake servers found"); - if ((realtime - searchCompleteTime) < 3.0) - return; + M_PrintWhite((320 / 2) - ((22 * 8) / 2), 64, "No Quake servers found"); + if ((realtime - searchCompleteTime) < 3.0) + return; - M_Menu_LanConfig_f (); + M_Menu_LanConfig_f(); } -void M_Search_Key (int key) -{ +void M_Search_Key(int key) { } //============================================================================= /* SLIST MENU */ -int slist_cursor; +int slist_cursor; qboolean slist_sorted; -void M_Menu_ServerList_f (void) -{ - IN_Deactivate(modestate == MS_WINDOWED); - key_dest = key_menu; - m_state = m_slist; - m_entersound = true; - slist_cursor = 0; - m_return_onerror = false; - m_return_reason[0] = 0; - slist_sorted = false; +void M_Menu_ServerList_f(void) { + IN_Deactivate(modestate == MS_WINDOWED); + key_dest = key_menu; + m_state = m_slist; + m_entersound = true; + slist_cursor = 0; + m_return_onerror = false; + m_return_reason[0] = 0; + slist_sorted = false; } -void M_ServerList_Draw (void) -{ - int n; - qpic_t *p; +void M_ServerList_Draw(void) { + int n; + qpic_t *p; - if (!slist_sorted) - { - slist_sorted = true; - NET_SlistSort (); - } + if (!slist_sorted) { + slist_sorted = true; + NET_SlistSort(); + } - p = Draw_CachePic ("gfx/p_multi.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); - for (n = 0; n < hostCacheCount; n++) - M_Print (16, 32 + 8*n, NET_SlistPrintServer (n)); - M_DrawCharacter (0, 32 + slist_cursor*8, 12+((int)(realtime*4)&1)); + p = Draw_CachePic("gfx/p_multi.lmp"); + M_DrawPic((320 - p->width) / 2, 4, p); + for (n = 0; n < hostCacheCount; n++) + M_Print(16, 32 + 8 * n, NET_SlistPrintServer(n)); + M_DrawCharacter(0, 32 + slist_cursor * 8, 12 + ((int) (realtime * 4) & 1)); - if (*m_return_reason) - M_PrintWhite (16, 148, m_return_reason); + if (*m_return_reason) + M_PrintWhite(16, 148, m_return_reason); } -void M_ServerList_Key (int k) -{ - switch (k) - { - case K_ESCAPE: - case K_BBUTTON: - M_Menu_LanConfig_f (); - break; +void M_ServerList_Key(int k) { + switch (k) { + case K_ESCAPE: + case K_BBUTTON: + M_Menu_LanConfig_f(); + break; - case K_SPACE: - M_Menu_Search_f (); - break; + case K_SPACE: + M_Menu_Search_f(); + break; - case K_UPARROW: - case K_LEFTARROW: - S_LocalSound ("misc/menu1.wav"); - slist_cursor--; - if (slist_cursor < 0) - slist_cursor = hostCacheCount - 1; - break; + case K_UPARROW: + case K_LEFTARROW: + S_LocalSound("misc/menu1.wav"); + slist_cursor--; + if (slist_cursor < 0) + slist_cursor = hostCacheCount - 1; + break; - case K_DOWNARROW: - case K_RIGHTARROW: - S_LocalSound ("misc/menu1.wav"); - slist_cursor++; - if (slist_cursor >= hostCacheCount) - slist_cursor = 0; - break; + case K_DOWNARROW: + case K_RIGHTARROW: + S_LocalSound("misc/menu1.wav"); + slist_cursor++; + if (slist_cursor >= hostCacheCount) + slist_cursor = 0; + break; - case K_ENTER: - case K_KP_ENTER: - case K_ABUTTON: - S_LocalSound ("misc/menu2.wav"); - m_return_state = m_state; - m_return_onerror = true; - slist_sorted = false; - IN_Activate(); - key_dest = key_game; - m_state = m_none; - Cbuf_AddText ( va ("connect \"%s\"\n", NET_SlistPrintServerName(slist_cursor)) ); - break; - - default: - break; - } + case K_ENTER: + case K_KP_ENTER: + case K_ABUTTON: + S_LocalSound("misc/menu2.wav"); + m_return_state = m_state; + m_return_onerror = true; + slist_sorted = false; + IN_Activate(); + key_dest = key_game; + m_state = m_none; + Cbuf_AddText(va("connect \"%s\"\n", NET_SlistPrintServerName(slist_cursor))); + break; + default: + break; + } } //============================================================================= /* Credits menu -- used by the 2021 re-release */ -void M_Menu_Credits_f (void) -{ +void M_Menu_Credits_f(void) { } //============================================================================= /* Menu Subsystem */ -void M_Init (void) -{ - Cmd_AddCommand ("togglemenu", M_ToggleMenu_f); - - Cmd_AddCommand ("menu_main", M_Menu_Main_f); - Cmd_AddCommand ("menu_singleplayer", M_Menu_SinglePlayer_f); - Cmd_AddCommand ("menu_load", M_Menu_Load_f); - Cmd_AddCommand ("menu_save", M_Menu_Save_f); - Cmd_AddCommand ("menu_multiplayer", M_Menu_MultiPlayer_f); - Cmd_AddCommand ("menu_setup", M_Menu_Setup_f); - Cmd_AddCommand ("menu_options", M_Menu_Options_f); - Cmd_AddCommand ("menu_keys", M_Menu_Keys_f); - Cmd_AddCommand ("menu_video", M_Menu_Video_f); - Cmd_AddCommand ("help", M_Menu_Help_f); - Cmd_AddCommand ("menu_quit", M_Menu_Quit_f); - Cmd_AddCommand ("menu_credits", M_Menu_Credits_f); // needed by the 2021 re-release +void M_Init(void) { + command::add("togglemenu", M_ToggleMenu_f); + command::add("menu_main", M_Menu_Main_f); + command::add("menu_singleplayer", M_Menu_SinglePlayer_f); + command::add("menu_load", M_Menu_Load_f); + command::add("menu_save", M_Menu_Save_f); + command::add("menu_multiplayer", M_Menu_MultiPlayer_f); + command::add("menu_setup", M_Menu_Setup_f); + command::add("menu_options", M_Menu_Options_f); + command::add("menu_keys", M_Menu_Keys_f); + command::add("menu_video", M_Menu_Video_f); + command::add("help", M_Menu_Help_f); + command::add("menu_quit", M_Menu_Quit_f); + command::add("menu_credits", M_Menu_Credits_f); // needed by the 2021 re-release } -void M_Draw (void) -{ - if (m_state == m_none || key_dest != key_menu) - return; +void M_Draw(void) { + if (m_state == m_none || key_dest != key_menu) + return; - if (!m_recursiveDraw) - { - if (scr_con_current) - { - Draw_ConsoleBackground (); - S_ExtraUpdate (); - } + if (!m_recursiveDraw) { + if (scr_con_current) { + Draw_ConsoleBackground(); + S_ExtraUpdate(); + } - Draw_FadeScreen (); //johnfitz -- fade even if console fills screen - } - else - { - m_recursiveDraw = false; - } + Draw_FadeScreen(); //johnfitz -- fade even if console fills screen + } else { + m_recursiveDraw = false; + } - GL_SetCanvas (CANVAS_MENU); //johnfitz + GL_SetCanvas(CANVAS_MENU); //johnfitz - switch (m_state) - { - case m_none: - break; + switch (m_state) { + case m_none: + break; - case m_main: - M_Main_Draw (); - break; + case m_main: + M_Main_Draw(); + break; - case m_singleplayer: - M_SinglePlayer_Draw (); - break; + case m_singleplayer: + M_SinglePlayer_Draw(); + break; - case m_load: - M_Load_Draw (); - break; + case m_load: + M_Load_Draw(); + break; - case m_save: - M_Save_Draw (); - break; + case m_save: + M_Save_Draw(); + break; - case m_multiplayer: - M_MultiPlayer_Draw (); - break; + case m_multiplayer: + M_MultiPlayer_Draw(); + break; - case m_setup: - M_Setup_Draw (); - break; + case m_setup: + M_Setup_Draw(); + break; - case m_net: - M_Net_Draw (); - break; + case m_net: + M_Net_Draw(); + break; - case m_options: - M_Options_Draw (); - break; + case m_options: + M_Options_Draw(); + break; - case m_keys: - M_Keys_Draw (); - break; + case m_keys: + M_Keys_Draw(); + break; - case m_video: - M_Video_Draw (); - break; + case m_video: + M_Video_Draw(); + break; - case m_help: - M_Help_Draw (); - break; + case m_help: + M_Help_Draw(); + break; - case m_quit: - if (!fitzmode) - { /* QuakeSpasm customization: */ - /* Quit now! S.A. */ - key_dest = key_console; - Host_Quit_f (); - } - M_Quit_Draw (); - break; + case m_quit: + if (!fitzmode) { + /* QuakeSpasm customization: */ + /* Quit now! S.A. */ + key_dest = key_console; + Host_Quit_f(); + } + M_Quit_Draw(); + break; - case m_lanconfig: - M_LanConfig_Draw (); - break; + case m_lanconfig: + M_LanConfig_Draw(); + break; - case m_gameoptions: - M_GameOptions_Draw (); - break; + case m_gameoptions: + M_GameOptions_Draw(); + break; - case m_search: - M_Search_Draw (); - break; + case m_search: + M_Search_Draw(); + break; - case m_slist: - M_ServerList_Draw (); - break; - } + case m_slist: + M_ServerList_Draw(); + break; + } - if (m_entersound) - { - S_LocalSound ("misc/menu2.wav"); - m_entersound = false; - } + if (m_entersound) { + S_LocalSound("misc/menu2.wav"); + m_entersound = false; + } - S_ExtraUpdate (); + S_ExtraUpdate(); } -void M_Keydown (int key) -{ - switch (m_state) - { - case m_none: - return; +void M_Keydown(int key) { + switch (m_state) { + case m_none: + return; - case m_main: - M_Main_Key (key); - return; + case m_main: + M_Main_Key(key); + return; - case m_singleplayer: - M_SinglePlayer_Key (key); - return; + case m_singleplayer: + M_SinglePlayer_Key(key); + return; - case m_load: - M_Load_Key (key); - return; + case m_load: + M_Load_Key(key); + return; - case m_save: - M_Save_Key (key); - return; + case m_save: + M_Save_Key(key); + return; - case m_multiplayer: - M_MultiPlayer_Key (key); - return; + case m_multiplayer: + M_MultiPlayer_Key(key); + return; - case m_setup: - M_Setup_Key (key); - return; + case m_setup: + M_Setup_Key(key); + return; - case m_net: - M_Net_Key (key); - return; + case m_net: + M_Net_Key(key); + return; - case m_options: - M_Options_Key (key); - return; + case m_options: + M_Options_Key(key); + return; - case m_keys: - M_Keys_Key (key); - return; + case m_keys: + M_Keys_Key(key); + return; - case m_video: - M_Video_Key (key); - return; + case m_video: + M_Video_Key(key); + return; - case m_help: - M_Help_Key (key); - return; + case m_help: + M_Help_Key(key); + return; - case m_quit: - M_Quit_Key (key); - return; + case m_quit: + M_Quit_Key(key); + return; - case m_lanconfig: - M_LanConfig_Key (key); - return; + case m_lanconfig: + M_LanConfig_Key(key); + return; - case m_gameoptions: - M_GameOptions_Key (key); - return; + case m_gameoptions: + M_GameOptions_Key(key); + return; - case m_search: - M_Search_Key (key); - break; + case m_search: + M_Search_Key(key); + break; - case m_slist: - M_ServerList_Key (key); - return; - } + case m_slist: + M_ServerList_Key(key); + return; + } } -void M_Charinput (int key) -{ - switch (m_state) - { - case m_setup: - M_Setup_Char (key); - return; - case m_quit: - M_Quit_Char (key); - return; - case m_lanconfig: - M_LanConfig_Char (key); - return; - default: - return; - } +void M_Charinput(int key) { + switch (m_state) { + case m_setup: + M_Setup_Char(key); + return; + case m_quit: + M_Quit_Char(key); + return; + case m_lanconfig: + M_LanConfig_Char(key); + return; + default: + return; + } } -qboolean M_TextEntry (void) -{ - switch (m_state) - { - case m_setup: - return M_Setup_TextEntry (); - case m_quit: - return M_Quit_TextEntry (); - case m_lanconfig: - return M_LanConfig_TextEntry (); - default: - return false; - } +qboolean M_TextEntry(void) { + switch (m_state) { + case m_setup: + return M_Setup_TextEntry(); + case m_quit: + return M_Quit_TextEntry(); + case m_lanconfig: + return M_LanConfig_TextEntry(); + default: + return false; + } } -void M_ConfigureNetSubsystem(void) -{ -// enable/disable net systems to match desired config - Cbuf_AddText ("stopdemo\n"); +void M_ConfigureNetSubsystem(void) { + // enable/disable net systems to match desired config + Cbuf_AddText("stopdemo\n"); - if (IPXConfig || TCPIPConfig) - net_hostport = lanConfig_port; + if (IPXConfig || TCPIPConfig) + net_hostport = lanConfig_port; } - diff --git a/Quake/miniz.hpp b/Quake/miniz.hpp index 362a8ca..bd2a35c 100644 --- a/Quake/miniz.hpp +++ b/Quake/miniz.hpp @@ -5,6 +5,7 @@ #define MINIZ_EXPORT #endif + /* miniz.c 2.2.0 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing See "unlicense" statement at the end of this file. Rich Geldreich , last updated Oct. 13, 2013 diff --git a/Quake/net.hpp b/Quake/net.hpp index a078490..91295bf 100644 --- a/Quake/net.hpp +++ b/Quake/net.hpp @@ -39,7 +39,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. extern int DEFAULTnet_hostport; extern int net_hostport; -extern cvar_t hostname; +extern convar hostname; extern double net_time; extern sizebuf_t net_message; diff --git a/Quake/net_dgrm.cpp b/Quake/net_dgrm.cpp index 76f619b..f1ca4c3 100644 --- a/Quake/net_dgrm.cpp +++ b/Quake/net_dgrm.cpp @@ -43,11 +43,10 @@ static int receivedDuplicateCount = 0; static int shortPacketCount = 0; static int droppedDatagrams; -static struct -{ - unsigned int length; - unsigned int sequence; - byte data[MAX_DATAGRAM]; +static struct { + unsigned int length; + unsigned int sequence; + byte data[MAX_DATAGRAM]; } packetBuffer; static int myDriverLevel; @@ -56,1366 +55,1234 @@ extern qboolean m_return_onerror; extern char m_return_reason[32]; -static char *StrAddr (struct qsockaddr *addr) -{ - static char buf[34]; - byte *p = (byte *)addr; - int n; +static char *StrAddr(struct qsockaddr *addr) { + static char buf[34]; + byte *p = (byte *) addr; + int n; - for (n = 0; n < 16; n++) - sprintf (buf + n * 2, "%02x", *p++); - return buf; + for (n = 0; n < 16; n++) + sprintf(buf + n * 2, "%02x", *p++); + return buf; } #ifdef BAN_TEST -static struct in_addr banAddr; -static struct in_addr banMask; +static struct in_addr banAddr; +static struct in_addr banMask; -static void NET_Ban_f (void) -{ - char addrStr [32]; - char maskStr [32]; - void (*print_fn)(const char *fmt, ...) FUNCP_PRINTF(1,2); +static void NET_Ban_f(void) { + char addrStr[32]; + char maskStr[32]; + void (*print_fn)(const char *fmt, ...) FUNCP_PRINTF(1, 2); - if (cmd_source == src_command) - { - if (!sv.active) - { - Cmd_ForwardToServer (); - return; - } - print_fn = Con_Printf; - } - else - { - if (pr_global_struct->deathmatch) - return; - print_fn = SV_ClientPrintf; - } + if (command::last_source == command::source::command) { + if (!sv.active) { + command::forward_to_server(); + return; + } + print_fn = Con_Printf; + } else { + if (pr_global_struct->deathmatch) + return; + print_fn = SV_ClientPrintf; + } - switch (Cmd_Argc ()) - { - case 1: - if (banAddr.s_addr != INADDR_ANY) - { - Q_strcpy(addrStr, inet_ntoa(banAddr)); - Q_strcpy(maskStr, inet_ntoa(banMask)); - print_fn("Banning %s [%s]\n", addrStr, maskStr); - } - else - print_fn("Banning not active\n"); - break; + switch (command::argc()) { + case 1: + if (banAddr.s_addr != INADDR_ANY) { + Q_strcpy(addrStr, inet_ntoa(banAddr)); + Q_strcpy(maskStr, inet_ntoa(banMask)); + print_fn("Banning %s [%s]\n", addrStr, maskStr); + } else + print_fn("Banning not active\n"); + break; - case 2: - if (q_strcasecmp(Cmd_Argv(1), "off") == 0) - banAddr.s_addr = INADDR_ANY; - else - banAddr.s_addr = inet_addr(Cmd_Argv(1)); - banMask.s_addr = INADDR_NONE; - break; + case 2: + if (q_strcasecmp(command::argv(1)->c_str(), "off") == 0) + banAddr.s_addr = INADDR_ANY; + else + banAddr.s_addr = inet_addr(command::argv(1)->c_str()); + banMask.s_addr = INADDR_NONE; + break; - case 3: - banAddr.s_addr = inet_addr(Cmd_Argv(1)); - banMask.s_addr = inet_addr(Cmd_Argv(2)); - break; + case 3: + banAddr.s_addr = inet_addr(command::argv(1)->c_str()); + banMask.s_addr = inet_addr(command::argv(2)->c_str()); + break; - default: - print_fn("BAN ip_address [mask]\n"); - break; - } + default: + print_fn("BAN ip_address [mask]\n"); + break; + } } #endif // BAN_TEST -int Datagram_SendMessage (qsocket_t *sock, sizebuf_t *data) -{ - unsigned int packetLen; - unsigned int dataLen; - unsigned int eom; +int Datagram_SendMessage(qsocket_t *sock, sizebuf_t *data) { + unsigned int packetLen; + unsigned int dataLen; + unsigned int eom; #ifdef DEBUG - if (data->cursize == 0) - Sys_Error("Datagram_SendMessage: zero length message"); + if (data->cursize == 0) + Sys_Error("Datagram_SendMessage: zero length message"); - if (data->cursize > NET_MAXMESSAGE) - Sys_Error("Datagram_SendMessage: message too big: %u", data->cursize); + if (data->cursize > NET_MAXMESSAGE) + Sys_Error("Datagram_SendMessage: message too big: %u", data->cursize); - if (sock->canSend == false) - Sys_Error("SendMessage: called with canSend == false"); + if (sock->canSend == false) + Sys_Error("SendMessage: called with canSend == false"); #endif - Q_memcpy(sock->sendMessage, data->data, data->cursize); - sock->sendMessageLength = data->cursize; + Q_memcpy(sock->sendMessage, data->data, data->cursize); + sock->sendMessageLength = data->cursize; - if (data->cursize <= MAX_DATAGRAM) - { - dataLen = data->cursize; - eom = NETFLAG_EOM; - } - else - { - dataLen = MAX_DATAGRAM; - eom = 0; - } - packetLen = NET_HEADERSIZE + dataLen; + if (data->cursize <= MAX_DATAGRAM) { + dataLen = data->cursize; + eom = NETFLAG_EOM; + } else { + dataLen = MAX_DATAGRAM; + eom = 0; + } + packetLen = NET_HEADERSIZE + dataLen; - packetBuffer.length = BigLong(packetLen | (NETFLAG_DATA | eom)); - packetBuffer.sequence = BigLong(sock->sendSequence++); - Q_memcpy (packetBuffer.data, sock->sendMessage, dataLen); + packetBuffer.length = BigLong(packetLen | (NETFLAG_DATA | eom)); + packetBuffer.sequence = BigLong(sock->sendSequence++); + Q_memcpy(packetBuffer.data, sock->sendMessage, dataLen); - sock->canSend = false; + sock->canSend = false; - if (sfunc.Write (sock->socket, (byte *)&packetBuffer, packetLen, &sock->addr) == -1) - return -1; + if (sfunc.Write(sock->socket, (byte *) &packetBuffer, packetLen, &sock->addr) == -1) + return -1; - sock->lastSendTime = net_time; - packetsSent++; - return 1; + sock->lastSendTime = net_time; + packetsSent++; + return 1; } -static int SendMessageNext (qsocket_t *sock) -{ - unsigned int packetLen; - unsigned int dataLen; - unsigned int eom; +static int SendMessageNext(qsocket_t *sock) { + unsigned int packetLen; + unsigned int dataLen; + unsigned int eom; - if (sock->sendMessageLength <= MAX_DATAGRAM) - { - dataLen = sock->sendMessageLength; - eom = NETFLAG_EOM; - } - else - { - dataLen = MAX_DATAGRAM; - eom = 0; - } - packetLen = NET_HEADERSIZE + dataLen; + if (sock->sendMessageLength <= MAX_DATAGRAM) { + dataLen = sock->sendMessageLength; + eom = NETFLAG_EOM; + } else { + dataLen = MAX_DATAGRAM; + eom = 0; + } + packetLen = NET_HEADERSIZE + dataLen; - packetBuffer.length = BigLong(packetLen | (NETFLAG_DATA | eom)); - packetBuffer.sequence = BigLong(sock->sendSequence++); - Q_memcpy (packetBuffer.data, sock->sendMessage, dataLen); + packetBuffer.length = BigLong(packetLen | (NETFLAG_DATA | eom)); + packetBuffer.sequence = BigLong(sock->sendSequence++); + Q_memcpy(packetBuffer.data, sock->sendMessage, dataLen); - sock->sendNext = false; + sock->sendNext = false; - if (sfunc.Write (sock->socket, (byte *)&packetBuffer, packetLen, &sock->addr) == -1) - return -1; + if (sfunc.Write(sock->socket, (byte *) &packetBuffer, packetLen, &sock->addr) == -1) + return -1; - sock->lastSendTime = net_time; - packetsSent++; - return 1; + sock->lastSendTime = net_time; + packetsSent++; + return 1; } -static int ReSendMessage (qsocket_t *sock) -{ - unsigned int packetLen; - unsigned int dataLen; - unsigned int eom; +static int ReSendMessage(qsocket_t *sock) { + unsigned int packetLen; + unsigned int dataLen; + unsigned int eom; - if (sock->sendMessageLength <= MAX_DATAGRAM) - { - dataLen = sock->sendMessageLength; - eom = NETFLAG_EOM; - } - else - { - dataLen = MAX_DATAGRAM; - eom = 0; - } - packetLen = NET_HEADERSIZE + dataLen; + if (sock->sendMessageLength <= MAX_DATAGRAM) { + dataLen = sock->sendMessageLength; + eom = NETFLAG_EOM; + } else { + dataLen = MAX_DATAGRAM; + eom = 0; + } + packetLen = NET_HEADERSIZE + dataLen; - packetBuffer.length = BigLong(packetLen | (NETFLAG_DATA | eom)); - packetBuffer.sequence = BigLong(sock->sendSequence - 1); - Q_memcpy (packetBuffer.data, sock->sendMessage, dataLen); + packetBuffer.length = BigLong(packetLen | (NETFLAG_DATA | eom)); + packetBuffer.sequence = BigLong(sock->sendSequence - 1); + Q_memcpy(packetBuffer.data, sock->sendMessage, dataLen); - sock->sendNext = false; + sock->sendNext = false; - if (sfunc.Write (sock->socket, (byte *)&packetBuffer, packetLen, &sock->addr) == -1) - return -1; + if (sfunc.Write(sock->socket, (byte *) &packetBuffer, packetLen, &sock->addr) == -1) + return -1; - sock->lastSendTime = net_time; - packetsReSent++; - return 1; + sock->lastSendTime = net_time; + packetsReSent++; + return 1; } -qboolean Datagram_CanSendMessage (qsocket_t *sock) -{ - if (sock->sendNext) - SendMessageNext (sock); +qboolean Datagram_CanSendMessage(qsocket_t *sock) { + if (sock->sendNext) + SendMessageNext(sock); - return sock->canSend; + return sock->canSend; } -qboolean Datagram_CanSendUnreliableMessage (qsocket_t *sock) -{ - return true; +qboolean Datagram_CanSendUnreliableMessage(qsocket_t *sock) { + return true; } -int Datagram_SendUnreliableMessage (qsocket_t *sock, sizebuf_t *data) -{ - int packetLen; +int Datagram_SendUnreliableMessage(qsocket_t *sock, sizebuf_t *data) { + int packetLen; #ifdef DEBUG - if (data->cursize == 0) - Sys_Error("Datagram_SendUnreliableMessage: zero length message"); + if (data->cursize == 0) + Sys_Error("Datagram_SendUnreliableMessage: zero length message"); - if (data->cursize > MAX_DATAGRAM) - Sys_Error("Datagram_SendUnreliableMessage: message too big: %u", data->cursize); + if (data->cursize > MAX_DATAGRAM) + Sys_Error("Datagram_SendUnreliableMessage: message too big: %u", data->cursize); #endif - packetLen = NET_HEADERSIZE + data->cursize; + packetLen = NET_HEADERSIZE + data->cursize; - packetBuffer.length = BigLong(packetLen | NETFLAG_UNRELIABLE); - packetBuffer.sequence = BigLong(sock->unreliableSendSequence++); - Q_memcpy (packetBuffer.data, data->data, data->cursize); + packetBuffer.length = BigLong(packetLen | NETFLAG_UNRELIABLE); + packetBuffer.sequence = BigLong(sock->unreliableSendSequence++); + Q_memcpy(packetBuffer.data, data->data, data->cursize); - if (sfunc.Write (sock->socket, (byte *)&packetBuffer, packetLen, &sock->addr) == -1) - return -1; + if (sfunc.Write(sock->socket, (byte *) &packetBuffer, packetLen, &sock->addr) == -1) + return -1; - packetsSent++; - return 1; + packetsSent++; + return 1; } -int Datagram_GetMessage (qsocket_t *sock) -{ - unsigned int length; - unsigned int flags; - int ret = 0; - struct qsockaddr readaddr; - unsigned int sequence; - unsigned int count; +int Datagram_GetMessage(qsocket_t *sock) { + unsigned int length; + unsigned int flags; + int ret = 0; + struct qsockaddr readaddr; + unsigned int sequence; + unsigned int count; - if (!sock->canSend) - if ((net_time - sock->lastSendTime) > 1.0) - ReSendMessage (sock); + if (!sock->canSend) + if ((net_time - sock->lastSendTime) > 1.0) + ReSendMessage(sock); - while (1) - { - length = (unsigned int) sfunc.Read(sock->socket, (byte *)&packetBuffer, - NET_DATAGRAMSIZE, &readaddr); + while (1) { + length = (unsigned int) sfunc.Read(sock->socket, (byte *) &packetBuffer, + NET_DATAGRAMSIZE, &readaddr); - // if ((rand() & 255) > 220) - // continue; + // if ((rand() & 255) > 220) + // continue; - if (length == 0) - break; + if (length == 0) + break; - if (length == (unsigned int)-1) - { - Con_Printf("Read error\n"); - return -1; - } + if (length == (unsigned int) -1) { + Con_Printf("Read error\n"); + return -1; + } - if (sfunc.AddrCompare(&readaddr, &sock->addr) != 0) - { - Con_Printf("Forged packet received\n"); - Con_Printf("Expected: %s\n", StrAddr (&sock->addr)); - Con_Printf("Received: %s\n", StrAddr (&readaddr)); - continue; - } + if (sfunc.AddrCompare(&readaddr, &sock->addr) != 0) { + Con_Printf("Forged packet received\n"); + Con_Printf("Expected: %s\n", StrAddr(&sock->addr)); + Con_Printf("Received: %s\n", StrAddr(&readaddr)); + continue; + } - if (length < NET_HEADERSIZE) - { - shortPacketCount++; - continue; - } + if (length < NET_HEADERSIZE) { + shortPacketCount++; + continue; + } - length = BigLong(packetBuffer.length); - flags = length & (~NETFLAG_LENGTH_MASK); - length &= NETFLAG_LENGTH_MASK; + length = BigLong(packetBuffer.length); + flags = length & (~NETFLAG_LENGTH_MASK); + length &= NETFLAG_LENGTH_MASK; - if (flags & NETFLAG_CTL) - continue; + if (flags & NETFLAG_CTL) + continue; - sequence = BigLong(packetBuffer.sequence); - packetsReceived++; + sequence = BigLong(packetBuffer.sequence); + packetsReceived++; - if (flags & NETFLAG_UNRELIABLE) - { - if (sequence < sock->unreliableReceiveSequence) - { - Con_DPrintf("Got a stale datagram\n"); - ret = 0; - break; - } - if (sequence != sock->unreliableReceiveSequence) - { - count = sequence - sock->unreliableReceiveSequence; - droppedDatagrams += count; - Con_DPrintf("Dropped %u datagram(s)\n", count); - } - sock->unreliableReceiveSequence = sequence + 1; + if (flags & NETFLAG_UNRELIABLE) { + if (sequence < sock->unreliableReceiveSequence) { + Con_DPrintf("Got a stale datagram\n"); + ret = 0; + break; + } + if (sequence != sock->unreliableReceiveSequence) { + count = sequence - sock->unreliableReceiveSequence; + droppedDatagrams += count; + Con_DPrintf("Dropped %u datagram(s)\n", count); + } + sock->unreliableReceiveSequence = sequence + 1; - length -= NET_HEADERSIZE; + length -= NET_HEADERSIZE; - SZ_Clear (&net_message); - SZ_Write (&net_message, packetBuffer.data, length); + SZ_Clear(&net_message); + SZ_Write(&net_message, packetBuffer.data, length); - ret = 2; - break; - } + ret = 2; + break; + } - if (flags & NETFLAG_ACK) - { - if (sequence != (sock->sendSequence - 1)) - { - Con_DPrintf("Stale ACK received\n"); - continue; - } - if (sequence == sock->ackSequence) - { - sock->ackSequence++; - if (sock->ackSequence != sock->sendSequence) - Con_DPrintf("ack sequencing error\n"); - } - else - { - Con_DPrintf("Duplicate ACK received\n"); - continue; - } - sock->sendMessageLength -= MAX_DATAGRAM; - if (sock->sendMessageLength > 0) - { - memmove (sock->sendMessage, sock->sendMessage + MAX_DATAGRAM, sock->sendMessageLength); - sock->sendNext = true; - } - else - { - sock->sendMessageLength = 0; - sock->canSend = true; - } - continue; - } + if (flags & NETFLAG_ACK) { + if (sequence != (sock->sendSequence - 1)) { + Con_DPrintf("Stale ACK received\n"); + continue; + } + if (sequence == sock->ackSequence) { + sock->ackSequence++; + if (sock->ackSequence != sock->sendSequence) + Con_DPrintf("ack sequencing error\n"); + } else { + Con_DPrintf("Duplicate ACK received\n"); + continue; + } + sock->sendMessageLength -= MAX_DATAGRAM; + if (sock->sendMessageLength > 0) { + memmove(sock->sendMessage, sock->sendMessage + MAX_DATAGRAM, sock->sendMessageLength); + sock->sendNext = true; + } else { + sock->sendMessageLength = 0; + sock->canSend = true; + } + continue; + } - if (flags & NETFLAG_DATA) - { - packetBuffer.length = BigLong(NET_HEADERSIZE | NETFLAG_ACK); - packetBuffer.sequence = BigLong(sequence); - sfunc.Write (sock->socket, (byte *)&packetBuffer, NET_HEADERSIZE, &readaddr); + if (flags & NETFLAG_DATA) { + packetBuffer.length = BigLong(NET_HEADERSIZE | NETFLAG_ACK); + packetBuffer.sequence = BigLong(sequence); + sfunc.Write(sock->socket, (byte *) &packetBuffer, NET_HEADERSIZE, &readaddr); - if (sequence != sock->receiveSequence) - { - receivedDuplicateCount++; - continue; - } - sock->receiveSequence++; + if (sequence != sock->receiveSequence) { + receivedDuplicateCount++; + continue; + } + sock->receiveSequence++; - length -= NET_HEADERSIZE; + length -= NET_HEADERSIZE; - if (flags & NETFLAG_EOM) - { - SZ_Clear(&net_message); - SZ_Write(&net_message, sock->receiveMessage, sock->receiveMessageLength); - SZ_Write(&net_message, packetBuffer.data, length); - sock->receiveMessageLength = 0; + if (flags & NETFLAG_EOM) { + SZ_Clear(&net_message); + SZ_Write(&net_message, sock->receiveMessage, sock->receiveMessageLength); + SZ_Write(&net_message, packetBuffer.data, length); + sock->receiveMessageLength = 0; - ret = 1; - break; - } + ret = 1; + break; + } - Q_memcpy(sock->receiveMessage + sock->receiveMessageLength, packetBuffer.data, length); - sock->receiveMessageLength += length; - continue; - } - } + Q_memcpy(sock->receiveMessage + sock->receiveMessageLength, packetBuffer.data, length); + sock->receiveMessageLength += length; + continue; + } + } - if (sock->sendNext) - SendMessageNext (sock); + if (sock->sendNext) + SendMessageNext(sock); - return ret; + return ret; } -static void PrintStats(qsocket_t *s) -{ - Con_Printf("canSend = %4u \n", s->canSend); - Con_Printf("sendSeq = %4u ", s->sendSequence); - Con_Printf("recvSeq = %4u \n", s->receiveSequence); - Con_Printf("\n"); +static void PrintStats(qsocket_t *s) { + Con_Printf("canSend = %4u \n", s->canSend); + Con_Printf("sendSeq = %4u ", s->sendSequence); + Con_Printf("recvSeq = %4u \n", s->receiveSequence); + Con_Printf("\n"); } -static void NET_Stats_f (void) -{ - qsocket_t *s; +static void NET_Stats_f(void) { + qsocket_t *s; - if (Cmd_Argc () == 1) - { - Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent); - Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived); - Con_Printf("reliable messages sent = %i\n", messagesSent); - Con_Printf("reliable messages received = %i\n", messagesReceived); - Con_Printf("packetsSent = %i\n", packetsSent); - Con_Printf("packetsReSent = %i\n", packetsReSent); - Con_Printf("packetsReceived = %i\n", packetsReceived); - Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount); - Con_Printf("shortPacketCount = %i\n", shortPacketCount); - Con_Printf("droppedDatagrams = %i\n", droppedDatagrams); - } - else if (Q_strcmp(Cmd_Argv(1), "*") == 0) - { - for (s = net_activeSockets; s; s = s->next) - PrintStats(s); - for (s = net_freeSockets; s; s = s->next) - PrintStats(s); - } - else - { - for (s = net_activeSockets; s; s = s->next) - { - if (q_strcasecmp(Cmd_Argv(1), s->address) == 0) - break; - } + if (command::argc() == 1) { + Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent); + Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived); + Con_Printf("reliable messages sent = %i\n", messagesSent); + Con_Printf("reliable messages received = %i\n", messagesReceived); + Con_Printf("packetsSent = %i\n", packetsSent); + Con_Printf("packetsReSent = %i\n", packetsReSent); + Con_Printf("packetsReceived = %i\n", packetsReceived); + Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount); + Con_Printf("shortPacketCount = %i\n", shortPacketCount); + Con_Printf("droppedDatagrams = %i\n", droppedDatagrams); + } else if (Q_strcmp(command::argv(1)->c_str(), "*") == 0) { + for (s = net_activeSockets; s; s = s->next) + PrintStats(s); + for (s = net_freeSockets; s; s = s->next) + PrintStats(s); + } else { + for (s = net_activeSockets; s; s = s->next) { + if (q_strcasecmp(command::argv(1)->c_str(), s->address) == 0) + break; + } - if (s == NULL) - { - for (s = net_freeSockets; s; s = s->next) - { - if (q_strcasecmp(Cmd_Argv(1), s->address) == 0) - break; - } - } + if (s == NULL) { + for (s = net_freeSockets; s; s = s->next) { + if (q_strcasecmp(command::argv(1)->c_str(), s->address) == 0) + break; + } + } - if (s == NULL) - return; + if (s == NULL) + return; - PrintStats(s); - } + PrintStats(s); + } } // recognize ip:port (based on ProQuake) -static const char *Strip_Port (const char *host) -{ - static char noport[MAX_QPATH]; - /* array size as in Host_Connect_f() */ - char *p; - int port; +static const char *Strip_Port(const char *host) { + static char noport[MAX_QPATH]; + /* array size as in Host_Connect_f() */ + char *p; + int port; - if (!host || !*host) - return host; - q_strlcpy (noport, host, sizeof(noport)); - if ((p = Q_strrchr(noport, ':')) == NULL) - return host; - *p++ = '\0'; - port = Q_atoi (p); - if (port > 0 && port < 65536 && port != net_hostport) - { - net_hostport = port; - Con_Printf("Port set to %d\n", net_hostport); - } - return noport; + if (!host || !*host) + return host; + q_strlcpy(noport, host, sizeof(noport)); + if ((p = Q_strrchr(noport, ':')) == NULL) + return host; + *p++ = '\0'; + port = Q_atoi(p); + if (port > 0 && port < 65536 && port != net_hostport) { + net_hostport = port; + Con_Printf("Port set to %d\n", net_hostport); + } + return noport; } static qboolean testInProgress = false; -static int testPollCount; -static int testDriver; -static sys_socket_t testSocket; +static int testPollCount; +static int testDriver; +static sys_socket_t testSocket; -static void Test_Poll (void *); -static PollProcedure testPollProcedure = {NULL, 0.0, Test_Poll}; +static void Test_Poll(void *); -static void Test_Poll (void *unused) -{ - struct qsockaddr clientaddr; - int control; - int len; - char name[32]; - char address[64]; - int colors; - int frags; - int connectTime; +static PollProcedure testPollProcedure = {NULL, 0.0, Test_Poll}; - net_landriverlevel = testDriver; +static void Test_Poll(void *unused) { + struct qsockaddr clientaddr; + int control; + int len; + char name[32]; + char address[64]; + int colors; + int frags; + int connectTime; - while (1) - { - len = dfunc.Read (testSocket, net_message.data, net_message.maxsize, &clientaddr); - if (len < (int) sizeof(int)) - break; + net_landriverlevel = testDriver; - net_message.cursize = len; + while (1) { + len = dfunc.Read(testSocket, net_message.data, net_message.maxsize, &clientaddr); + if (len < (int) sizeof(int)) + break; - MSG_BeginReading (); - control = BigLong(*((int *)net_message.data)); - MSG_ReadLong(); - if (control == -1) - break; - if ((control & (~NETFLAG_LENGTH_MASK)) != (int)NETFLAG_CTL) - break; - if ((control & NETFLAG_LENGTH_MASK) != len) - break; + net_message.cursize = len; - if (MSG_ReadByte() != CCREP_PLAYER_INFO) - Sys_Error("Unexpected response to Player Info request\n"); + MSG_BeginReading(); + control = BigLong(*((int *) net_message.data)); + MSG_ReadLong(); + if (control == -1) + break; + if ((control & (~NETFLAG_LENGTH_MASK)) != (int) NETFLAG_CTL) + break; + if ((control & NETFLAG_LENGTH_MASK) != len) + break; - MSG_ReadByte(); /* playerNumber */ - Q_strcpy(name, MSG_ReadString()); - colors = MSG_ReadLong(); - frags = MSG_ReadLong(); - connectTime = MSG_ReadLong(); - Q_strcpy(address, MSG_ReadString()); + if (MSG_ReadByte() != CCREP_PLAYER_INFO) + Sys_Error("Unexpected response to Player Info request\n"); - Con_Printf("%s\n frags:%3i colors:%d %d time:%d\n %s\n", name, frags, colors >> 4, colors & 0x0f, connectTime / 60, address); - } + MSG_ReadByte(); /* playerNumber */ + Q_strcpy(name, MSG_ReadString()); + colors = MSG_ReadLong(); + frags = MSG_ReadLong(); + connectTime = MSG_ReadLong(); + Q_strcpy(address, MSG_ReadString()); - testPollCount--; - if (testPollCount) - { - SchedulePollProcedure(&testPollProcedure, 0.1); - } - else - { - dfunc.Close_Socket(testSocket); - testInProgress = false; - } + Con_Printf("%s\n frags:%3i colors:%d %d time:%d\n %s\n", name, frags, colors >> 4, colors & 0x0f, + connectTime / 60, address); + } + + testPollCount--; + if (testPollCount) { + SchedulePollProcedure(&testPollProcedure, 0.1); + } else { + dfunc.Close_Socket(testSocket); + testInProgress = false; + } } -static void Test_f (void) -{ - const char *host; - int n; - int maxusers = MAX_SCOREBOARD; - struct qsockaddr sendaddr; +static void Test_f(void) { + const char *host; + int n; + int maxusers = MAX_SCOREBOARD; + struct qsockaddr sendaddr; - if (testInProgress) - return; + if (testInProgress) + return; - host = Strip_Port (Cmd_Argv(1)); + host = Strip_Port(command::argv(1).value_or("").c_str()); - if (host && hostCacheCount) - { - for (n = 0; n < hostCacheCount; n++) - { - if (q_strcasecmp (host, hostcache[n].name) == 0) - { - if (hostcache[n].driver != myDriverLevel) - continue; - net_landriverlevel = hostcache[n].ldriver; - maxusers = hostcache[n].maxusers; - Q_memcpy(&sendaddr, &hostcache[n].addr, sizeof(struct qsockaddr)); - break; - } - } + if (host && hostCacheCount) { + for (n = 0; n < hostCacheCount; n++) { + if (q_strcasecmp(host, hostcache[n].name) == 0) { + if (hostcache[n].driver != myDriverLevel) + continue; + net_landriverlevel = hostcache[n].ldriver; + maxusers = hostcache[n].maxusers; + Q_memcpy(&sendaddr, &hostcache[n].addr, sizeof(struct qsockaddr)); + break; + } + } - if (n < hostCacheCount) - goto JustDoIt; - } + if (n < hostCacheCount) + goto JustDoIt; + } - for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) - { - if (!net_landrivers[net_landriverlevel].initialized) - continue; + for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) { + if (!net_landrivers[net_landriverlevel].initialized) + continue; - // see if we can resolve the host name - if (dfunc.GetAddrFromName(host, &sendaddr) != -1) - break; - } + // see if we can resolve the host name + if (dfunc.GetAddrFromName(host, &sendaddr) != -1) + break; + } - if (net_landriverlevel == net_numlandrivers) - { - Con_Printf("Could not resolve %s\n", host); - return; - } + if (net_landriverlevel == net_numlandrivers) { + Con_Printf("Could not resolve %s\n", host); + return; + } JustDoIt: - testSocket = dfunc.Open_Socket(0); - if (testSocket == INVALID_SOCKET) - return; + testSocket = dfunc.Open_Socket(0); + if (testSocket == INVALID_SOCKET) + return; - testInProgress = true; - testPollCount = 20; - testDriver = net_landriverlevel; + testInProgress = true; + testPollCount = 20; + testDriver = net_landriverlevel; - for (n = 0; n < maxusers; n++) - { - SZ_Clear(&net_message); - // save space for the header, filled in later - MSG_WriteLong(&net_message, 0); - MSG_WriteByte(&net_message, CCREQ_PLAYER_INFO); - MSG_WriteByte(&net_message, n); - *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Write (testSocket, net_message.data, net_message.cursize, &sendaddr); - } - SZ_Clear(&net_message); - SchedulePollProcedure(&testPollProcedure, 0.1); + for (n = 0; n < maxusers; n++) { + SZ_Clear(&net_message); + // save space for the header, filled in later + MSG_WriteLong(&net_message, 0); + MSG_WriteByte(&net_message, CCREQ_PLAYER_INFO); + MSG_WriteByte(&net_message, n); + *((int *) net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); + dfunc.Write(testSocket, net_message.data, net_message.cursize, &sendaddr); + } + SZ_Clear(&net_message); + SchedulePollProcedure(&testPollProcedure, 0.1); } static qboolean test2InProgress = false; -static int test2Driver; -static sys_socket_t test2Socket; +static int test2Driver; +static sys_socket_t test2Socket; -static void Test2_Poll (void *); -static PollProcedure test2PollProcedure = {NULL, 0.0, Test2_Poll}; +static void Test2_Poll(void *); -static void Test2_Poll (void *unused) -{ - struct qsockaddr clientaddr; - int control; - int len; - char name[256]; - char value[256]; +static PollProcedure test2PollProcedure = {NULL, 0.0, Test2_Poll}; - net_landriverlevel = test2Driver; - name[0] = 0; +static void Test2_Poll(void *unused) { + struct qsockaddr clientaddr; + int control; + int len; + char name[256]; + char value[256]; - len = dfunc.Read (test2Socket, net_message.data, net_message.maxsize, &clientaddr); - if (len < (int) sizeof(int)) - goto Reschedule; + net_landriverlevel = test2Driver; + name[0] = 0; - net_message.cursize = len; + len = dfunc.Read(test2Socket, net_message.data, net_message.maxsize, &clientaddr); + if (len < (int) sizeof(int)) + goto Reschedule; - MSG_BeginReading (); - control = BigLong(*((int *)net_message.data)); - MSG_ReadLong(); - if (control == -1) - goto Error; - if ((control & (~NETFLAG_LENGTH_MASK)) != (int)NETFLAG_CTL) - goto Error; - if ((control & NETFLAG_LENGTH_MASK) != len) - goto Error; + net_message.cursize = len; - if (MSG_ReadByte() != CCREP_RULE_INFO) - goto Error; + MSG_BeginReading(); + control = BigLong(*((int *) net_message.data)); + MSG_ReadLong(); + if (control == -1) + goto Error; + if ((control & (~NETFLAG_LENGTH_MASK)) != (int) NETFLAG_CTL) + goto Error; + if ((control & NETFLAG_LENGTH_MASK) != len) + goto Error; - Q_strcpy(name, MSG_ReadString()); - if (name[0] == 0) - goto Done; - Q_strcpy(value, MSG_ReadString()); + if (MSG_ReadByte() != CCREP_RULE_INFO) + goto Error; - Con_Printf("%-16.16s %-16.16s\n", name, value); + Q_strcpy(name, MSG_ReadString()); + if (name[0] == 0) + goto Done; + Q_strcpy(value, MSG_ReadString()); - SZ_Clear(&net_message); - // save space for the header, filled in later - MSG_WriteLong(&net_message, 0); - MSG_WriteByte(&net_message, CCREQ_RULE_INFO); - MSG_WriteString(&net_message, name); - *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Write (test2Socket, net_message.data, net_message.cursize, &clientaddr); - SZ_Clear(&net_message); + Con_Printf("%-16.16s %-16.16s\n", name, value); + + SZ_Clear(&net_message); + // save space for the header, filled in later + MSG_WriteLong(&net_message, 0); + MSG_WriteByte(&net_message, CCREQ_RULE_INFO); + MSG_WriteString(&net_message, name); + *((int *) net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); + dfunc.Write(test2Socket, net_message.data, net_message.cursize, &clientaddr); + SZ_Clear(&net_message); Reschedule: - SchedulePollProcedure(&test2PollProcedure, 0.05); - return; + SchedulePollProcedure(&test2PollProcedure, 0.05); + return; Error: - Con_Printf("Unexpected response to Rule Info request\n"); + Con_Printf("Unexpected response to Rule Info request\n"); Done: - dfunc.Close_Socket(test2Socket); - test2InProgress = false; - return; + dfunc.Close_Socket(test2Socket); + test2InProgress = false; + return; } -static void Test2_f (void) -{ - const char *host; - int n; - struct qsockaddr sendaddr; +static void Test2_f(void) { + const char *host; + int n; + struct qsockaddr sendaddr; - if (test2InProgress) - return; + if (test2InProgress) + return; - host = Strip_Port (Cmd_Argv(1)); + host = Strip_Port(command::argv(1).value_or("").c_str()); - if (host && hostCacheCount) - { - for (n = 0; n < hostCacheCount; n++) - { - if (q_strcasecmp (host, hostcache[n].name) == 0) - { - if (hostcache[n].driver != myDriverLevel) - continue; - net_landriverlevel = hostcache[n].ldriver; - Q_memcpy(&sendaddr, &hostcache[n].addr, sizeof(struct qsockaddr)); - break; - } - } + if (host && hostCacheCount) { + for (n = 0; n < hostCacheCount; n++) { + if (q_strcasecmp(host, hostcache[n].name) == 0) { + if (hostcache[n].driver != myDriverLevel) + continue; + net_landriverlevel = hostcache[n].ldriver; + Q_memcpy(&sendaddr, &hostcache[n].addr, sizeof(struct qsockaddr)); + break; + } + } - if (n < hostCacheCount) - goto JustDoIt; - } + if (n < hostCacheCount) + goto JustDoIt; + } - for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) - { - if (!net_landrivers[net_landriverlevel].initialized) - continue; + for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) { + if (!net_landrivers[net_landriverlevel].initialized) + continue; - // see if we can resolve the host name - if (dfunc.GetAddrFromName(host, &sendaddr) != -1) - break; - } + // see if we can resolve the host name + if (dfunc.GetAddrFromName(host, &sendaddr) != -1) + break; + } - if (net_landriverlevel == net_numlandrivers) - { - Con_Printf("Could not resolve %s\n", host); - return; - } + if (net_landriverlevel == net_numlandrivers) { + Con_Printf("Could not resolve %s\n", host); + return; + } JustDoIt: - test2Socket = dfunc.Open_Socket(0); - if (test2Socket == INVALID_SOCKET) - return; + test2Socket = dfunc.Open_Socket(0); + if (test2Socket == INVALID_SOCKET) + return; - test2InProgress = true; - test2Driver = net_landriverlevel; + test2InProgress = true; + test2Driver = net_landriverlevel; - SZ_Clear(&net_message); - // save space for the header, filled in later - MSG_WriteLong(&net_message, 0); - MSG_WriteByte(&net_message, CCREQ_RULE_INFO); - MSG_WriteString(&net_message, ""); - *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Write (test2Socket, net_message.data, net_message.cursize, &sendaddr); - SZ_Clear(&net_message); - SchedulePollProcedure(&test2PollProcedure, 0.05); + SZ_Clear(&net_message); + // save space for the header, filled in later + MSG_WriteLong(&net_message, 0); + MSG_WriteByte(&net_message, CCREQ_RULE_INFO); + MSG_WriteString(&net_message, ""); + *((int *) net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); + dfunc.Write(test2Socket, net_message.data, net_message.cursize, &sendaddr); + SZ_Clear(&net_message); + SchedulePollProcedure(&test2PollProcedure, 0.05); } -int Datagram_Init (void) -{ - int i, num_inited; - sys_socket_t csock; +int Datagram_Init(void) { + int i, num_inited; + sys_socket_t csock; #ifdef BAN_TEST - banAddr.s_addr = INADDR_ANY; - banMask.s_addr = INADDR_NONE; + banAddr.s_addr = INADDR_ANY; + banMask.s_addr = INADDR_NONE; #endif - myDriverLevel = net_driverlevel; + myDriverLevel = net_driverlevel; - Cmd_AddCommand ("net_stats", NET_Stats_f); + command::add("net_stats", NET_Stats_f); - if (safemode || COM_CheckParm("-nolan")) - return -1; + if (safemode || COM_CheckParm("-nolan")) + return -1; - num_inited = 0; - for (i = 0; i < net_numlandrivers; i++) - { - csock = net_landrivers[i].Init (); - if (csock == INVALID_SOCKET) - continue; - net_landrivers[i].initialized = true; - net_landrivers[i].controlSock = csock; - num_inited++; - } + num_inited = 0; + for (i = 0; i < net_numlandrivers; i++) { + csock = net_landrivers[i].Init(); + if (csock == INVALID_SOCKET) + continue; + net_landrivers[i].initialized = true; + net_landrivers[i].controlSock = csock; + num_inited++; + } - if (num_inited == 0) - return -1; + if (num_inited == 0) + return -1; #ifdef BAN_TEST - Cmd_AddCommand ("ban", NET_Ban_f); + command::add("ban", NET_Ban_f); #endif - Cmd_AddCommand ("test", Test_f); - Cmd_AddCommand ("test2", Test2_f); + command::add("test", Test_f); + command::add("test2", Test2_f); - return 0; + return 0; } -void Datagram_Shutdown (void) -{ - int i; +void Datagram_Shutdown(void) { + int i; -// -// shutdown the lan drivers -// - for (i = 0; i < net_numlandrivers; i++) - { - if (net_landrivers[i].initialized) - { - net_landrivers[i].Shutdown (); - net_landrivers[i].initialized = false; - } - } + // + // shutdown the lan drivers + // + for (i = 0; i < net_numlandrivers; i++) { + if (net_landrivers[i].initialized) { + net_landrivers[i].Shutdown(); + net_landrivers[i].initialized = false; + } + } } -void Datagram_Close (qsocket_t *sock) -{ - sfunc.Close_Socket(sock->socket); +void Datagram_Close(qsocket_t *sock) { + sfunc.Close_Socket(sock->socket); } -void Datagram_Listen (qboolean state) -{ - int i; +void Datagram_Listen(qboolean state) { + int i; - for (i = 0; i < net_numlandrivers; i++) - { - if (net_landrivers[i].initialized) - net_landrivers[i].Listen (state); - } + for (i = 0; i < net_numlandrivers; i++) { + if (net_landrivers[i].initialized) + net_landrivers[i].Listen(state); + } } -static qsocket_t *_Datagram_CheckNewConnections (void) -{ - struct qsockaddr clientaddr; - struct qsockaddr newaddr; - sys_socket_t newsock; - sys_socket_t acceptsock; - qsocket_t *sock; - qsocket_t *s; - int len; - int command; - int control; - int ret; +static qsocket_t *_Datagram_CheckNewConnections(void) { + struct qsockaddr clientaddr; + struct qsockaddr newaddr; + sys_socket_t newsock; + sys_socket_t acceptsock; + qsocket_t *sock; + qsocket_t *s; + int len; + int command; + int control; + int ret; - acceptsock = dfunc.CheckNewConnections(); - if (acceptsock == INVALID_SOCKET) - return NULL; + acceptsock = dfunc.CheckNewConnections(); + if (acceptsock == INVALID_SOCKET) + return NULL; - SZ_Clear(&net_message); + SZ_Clear(&net_message); - len = dfunc.Read (acceptsock, net_message.data, net_message.maxsize, &clientaddr); - if (len < (int) sizeof(int)) - return NULL; - net_message.cursize = len; + len = dfunc.Read(acceptsock, net_message.data, net_message.maxsize, &clientaddr); + if (len < (int) sizeof(int)) + return NULL; + net_message.cursize = len; - MSG_BeginReading (); - control = BigLong(*((int *)net_message.data)); - MSG_ReadLong(); - if (control == -1) - return NULL; - if ((control & (~NETFLAG_LENGTH_MASK)) != (int)NETFLAG_CTL) - return NULL; - if ((control & NETFLAG_LENGTH_MASK) != len) - return NULL; + MSG_BeginReading(); + control = BigLong(*((int *) net_message.data)); + MSG_ReadLong(); + if (control == -1) + return NULL; + if ((control & (~NETFLAG_LENGTH_MASK)) != (int) NETFLAG_CTL) + return NULL; + if ((control & NETFLAG_LENGTH_MASK) != len) + return NULL; - command = MSG_ReadByte(); - if (command == CCREQ_SERVER_INFO) - { - if (Q_strcmp(MSG_ReadString(), "QUAKE") != 0) - return NULL; + command = MSG_ReadByte(); + if (command == CCREQ_SERVER_INFO) { + if (Q_strcmp(MSG_ReadString(), "QUAKE") != 0) + return NULL; - SZ_Clear(&net_message); - // save space for the header, filled in later - MSG_WriteLong(&net_message, 0); - MSG_WriteByte(&net_message, CCREP_SERVER_INFO); - dfunc.GetSocketAddr(acceptsock, &newaddr); - MSG_WriteString(&net_message, dfunc.AddrToString(&newaddr)); - MSG_WriteString(&net_message, hostname.string); - MSG_WriteString(&net_message, sv.name); - MSG_WriteByte(&net_message, net_activeconnections); - MSG_WriteByte(&net_message, svs.maxclients); - MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION); - *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr); - SZ_Clear(&net_message); - return NULL; - } + SZ_Clear(&net_message); + // save space for the header, filled in later + MSG_WriteLong(&net_message, 0); + MSG_WriteByte(&net_message, CCREP_SERVER_INFO); + dfunc.GetSocketAddr(acceptsock, &newaddr); + MSG_WriteString(&net_message, dfunc.AddrToString(&newaddr)); + MSG_WriteString(&net_message, hostname.string); + MSG_WriteString(&net_message, sv.name); + MSG_WriteByte(&net_message, net_activeconnections); + MSG_WriteByte(&net_message, svs.maxclients); + MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION); + *((int *) net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); + dfunc.Write(acceptsock, net_message.data, net_message.cursize, &clientaddr); + SZ_Clear(&net_message); + return NULL; + } - if (command == CCREQ_PLAYER_INFO) - { - int playerNumber; - int activeNumber; - int clientNumber; - client_t *client; + if (command == CCREQ_PLAYER_INFO) { + int playerNumber; + int activeNumber; + int clientNumber; + client_t *client; - playerNumber = MSG_ReadByte(); - activeNumber = -1; + playerNumber = MSG_ReadByte(); + activeNumber = -1; - for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++) - { - if (client->active) - { - activeNumber++; - if (activeNumber == playerNumber) - break; - } - } + for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++) { + if (client->active) { + activeNumber++; + if (activeNumber == playerNumber) + break; + } + } - if (clientNumber == svs.maxclients) - return NULL; + if (clientNumber == svs.maxclients) + return NULL; - SZ_Clear(&net_message); - // save space for the header, filled in later - MSG_WriteLong(&net_message, 0); - MSG_WriteByte(&net_message, CCREP_PLAYER_INFO); - MSG_WriteByte(&net_message, playerNumber); - MSG_WriteString(&net_message, client->name); - MSG_WriteLong(&net_message, client->colors); - MSG_WriteLong(&net_message, (int)client->edict->v.frags); - MSG_WriteLong(&net_message, (int)(net_time - client->netconnection->connecttime)); - MSG_WriteString(&net_message, client->netconnection->address); - *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr); - SZ_Clear(&net_message); + SZ_Clear(&net_message); + // save space for the header, filled in later + MSG_WriteLong(&net_message, 0); + MSG_WriteByte(&net_message, CCREP_PLAYER_INFO); + MSG_WriteByte(&net_message, playerNumber); + MSG_WriteString(&net_message, client->name); + MSG_WriteLong(&net_message, client->colors); + MSG_WriteLong(&net_message, (int) client->edict->v.frags); + MSG_WriteLong(&net_message, (int) (net_time - client->netconnection->connecttime)); + MSG_WriteString(&net_message, client->netconnection->address); + *((int *) net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); + dfunc.Write(acceptsock, net_message.data, net_message.cursize, &clientaddr); + SZ_Clear(&net_message); - return NULL; - } + return NULL; + } - if (command == CCREQ_RULE_INFO) - { - const char *prevCvarName; - cvar_t *var; + if (command == CCREQ_RULE_INFO) { + const char *prevCvarName; - // find the search start location - prevCvarName = MSG_ReadString(); - var = Cvar_FindVarAfter (prevCvarName, CVAR_SERVERINFO); + // find the search start location + prevCvarName = MSG_ReadString(); + auto var = convar::find_var_after(prevCvarName, std::nullopt); - // send the response - SZ_Clear(&net_message); - // save space for the header, filled in later - MSG_WriteLong(&net_message, 0); - MSG_WriteByte(&net_message, CCREP_RULE_INFO); - if (var) - { - MSG_WriteString(&net_message, var->name); - MSG_WriteString(&net_message, var->string); - } - *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr); - SZ_Clear(&net_message); + // send the response + SZ_Clear(&net_message); + // save space for the header, filled in later + MSG_WriteLong(&net_message, 0); + MSG_WriteByte(&net_message, CCREP_RULE_INFO); + if (var) { + MSG_WriteString(&net_message, var.value()->name.c_str()); + MSG_WriteString(&net_message, var.value()->string); + } + *((int *) net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); + dfunc.Write(acceptsock, net_message.data, net_message.cursize, &clientaddr); + SZ_Clear(&net_message); - return NULL; - } + return NULL; + } - if (command != CCREQ_CONNECT) - return NULL; + if (command != CCREQ_CONNECT) + return NULL; - if (Q_strcmp(MSG_ReadString(), "QUAKE") != 0) - return NULL; + if (Q_strcmp(MSG_ReadString(), "QUAKE") != 0) + return NULL; - if (MSG_ReadByte() != NET_PROTOCOL_VERSION) - { - SZ_Clear(&net_message); - // save space for the header, filled in later - MSG_WriteLong(&net_message, 0); - MSG_WriteByte(&net_message, CCREP_REJECT); - MSG_WriteString(&net_message, "Incompatible version.\n"); - *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr); - SZ_Clear(&net_message); - return NULL; - } + if (MSG_ReadByte() != NET_PROTOCOL_VERSION) { + SZ_Clear(&net_message); + // save space for the header, filled in later + MSG_WriteLong(&net_message, 0); + MSG_WriteByte(&net_message, CCREP_REJECT); + MSG_WriteString(&net_message, "Incompatible version.\n"); + *((int *) net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); + dfunc.Write(acceptsock, net_message.data, net_message.cursize, &clientaddr); + SZ_Clear(&net_message); + return NULL; + } #ifdef BAN_TEST - // check for a ban - if (clientaddr.qsa_family == AF_INET) - { - in_addr_t testAddr; - testAddr = ((struct sockaddr_in *)&clientaddr)->sin_addr.s_addr; - if ((testAddr & banMask.s_addr) == banAddr.s_addr) - { - SZ_Clear(&net_message); - // save space for the header, filled in later - MSG_WriteLong(&net_message, 0); - MSG_WriteByte(&net_message, CCREP_REJECT); - MSG_WriteString(&net_message, "You have been banned.\n"); - *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr); - SZ_Clear(&net_message); - return NULL; - } - } + // check for a ban + if (clientaddr.qsa_family == AF_INET) { + in_addr_t testAddr; + testAddr = ((struct sockaddr_in *) &clientaddr)->sin_addr.s_addr; + if ((testAddr & banMask.s_addr) == banAddr.s_addr) { + SZ_Clear(&net_message); + // save space for the header, filled in later + MSG_WriteLong(&net_message, 0); + MSG_WriteByte(&net_message, CCREP_REJECT); + MSG_WriteString(&net_message, "You have been banned.\n"); + *((int *) net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); + dfunc.Write(acceptsock, net_message.data, net_message.cursize, &clientaddr); + SZ_Clear(&net_message); + return NULL; + } + } #endif - // see if this guy is already connected - for (s = net_activeSockets; s; s = s->next) - { - if (s->driver != net_driverlevel) - continue; - ret = dfunc.AddrCompare(&clientaddr, &s->addr); - if (ret >= 0) - { - // is this a duplicate connection reqeust? - if (ret == 0 && net_time - s->connecttime < 2.0) - { - // yes, so send a duplicate reply - SZ_Clear(&net_message); - // save space for the header, filled in later - MSG_WriteLong(&net_message, 0); - MSG_WriteByte(&net_message, CCREP_ACCEPT); - dfunc.GetSocketAddr(s->socket, &newaddr); - MSG_WriteLong(&net_message, dfunc.GetSocketPort(&newaddr)); - *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr); - SZ_Clear(&net_message); - return NULL; - } - // it's somebody coming back in from a crash/disconnect - // so close the old qsocket and let their retry get them back in - NET_Close(s); - return NULL; - } - } + // see if this guy is already connected + for (s = net_activeSockets; s; s = s->next) { + if (s->driver != net_driverlevel) + continue; + ret = dfunc.AddrCompare(&clientaddr, &s->addr); + if (ret >= 0) { + // is this a duplicate connection reqeust? + if (ret == 0 && net_time - s->connecttime < 2.0) { + // yes, so send a duplicate reply + SZ_Clear(&net_message); + // save space for the header, filled in later + MSG_WriteLong(&net_message, 0); + MSG_WriteByte(&net_message, CCREP_ACCEPT); + dfunc.GetSocketAddr(s->socket, &newaddr); + MSG_WriteLong(&net_message, dfunc.GetSocketPort(&newaddr)); + *((int *) net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); + dfunc.Write(acceptsock, net_message.data, net_message.cursize, &clientaddr); + SZ_Clear(&net_message); + return NULL; + } + // it's somebody coming back in from a crash/disconnect + // so close the old qsocket and let their retry get them back in + NET_Close(s); + return NULL; + } + } - // allocate a QSocket - sock = NET_NewQSocket (); - if (sock == NULL) // no room; try to let him know - { - SZ_Clear(&net_message); - // save space for the header, filled in later - MSG_WriteLong(&net_message, 0); - MSG_WriteByte(&net_message, CCREP_REJECT); - MSG_WriteString(&net_message, "Server is full.\n"); - *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr); - SZ_Clear(&net_message); - return NULL; - } + // allocate a QSocket + sock = NET_NewQSocket(); + if (sock == NULL) // no room; try to let him know + { + SZ_Clear(&net_message); + // save space for the header, filled in later + MSG_WriteLong(&net_message, 0); + MSG_WriteByte(&net_message, CCREP_REJECT); + MSG_WriteString(&net_message, "Server is full.\n"); + *((int *) net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); + dfunc.Write(acceptsock, net_message.data, net_message.cursize, &clientaddr); + SZ_Clear(&net_message); + return NULL; + } - // allocate a network socket - newsock = dfunc.Open_Socket(0); - if (newsock == INVALID_SOCKET) - { - NET_FreeQSocket(sock); - return NULL; - } + // allocate a network socket + newsock = dfunc.Open_Socket(0); + if (newsock == INVALID_SOCKET) { + NET_FreeQSocket(sock); + return NULL; + } - // connect to the client - if (dfunc.Connect (newsock, &clientaddr) == -1) - { - dfunc.Close_Socket(newsock); - NET_FreeQSocket(sock); - return NULL; - } + // connect to the client + if (dfunc.Connect(newsock, &clientaddr) == -1) { + dfunc.Close_Socket(newsock); + NET_FreeQSocket(sock); + return NULL; + } - // everything is allocated, just fill in the details - sock->socket = newsock; - sock->landriver = net_landriverlevel; - sock->addr = clientaddr; - Q_strcpy(sock->address, dfunc.AddrToString(&clientaddr)); + // everything is allocated, just fill in the details + sock->socket = newsock; + sock->landriver = net_landriverlevel; + sock->addr = clientaddr; + Q_strcpy(sock->address, dfunc.AddrToString(&clientaddr)); - // send him back the info about the server connection he has been allocated - SZ_Clear(&net_message); - // save space for the header, filled in later - MSG_WriteLong(&net_message, 0); - MSG_WriteByte(&net_message, CCREP_ACCEPT); - dfunc.GetSocketAddr(newsock, &newaddr); - MSG_WriteLong(&net_message, dfunc.GetSocketPort(&newaddr)); -// MSG_WriteString(&net_message, dfunc.AddrToString(&newaddr)); - *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr); - SZ_Clear(&net_message); + // send him back the info about the server connection he has been allocated + SZ_Clear(&net_message); + // save space for the header, filled in later + MSG_WriteLong(&net_message, 0); + MSG_WriteByte(&net_message, CCREP_ACCEPT); + dfunc.GetSocketAddr(newsock, &newaddr); + MSG_WriteLong(&net_message, dfunc.GetSocketPort(&newaddr)); + // MSG_WriteString(&net_message, dfunc.AddrToString(&newaddr)); + *((int *) net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); + dfunc.Write(acceptsock, net_message.data, net_message.cursize, &clientaddr); + SZ_Clear(&net_message); - return sock; + return sock; } -qsocket_t *Datagram_CheckNewConnections (void) -{ - qsocket_t *ret = NULL; +qsocket_t *Datagram_CheckNewConnections(void) { + qsocket_t *ret = NULL; - for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) - { - if (net_landrivers[net_landriverlevel].initialized) - { - if ((ret = _Datagram_CheckNewConnections ()) != NULL) - break; - } - } - return ret; + for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) { + if (net_landrivers[net_landriverlevel].initialized) { + if ((ret = _Datagram_CheckNewConnections()) != NULL) + break; + } + } + return ret; } -static void _Datagram_SearchForHosts (qboolean xmit) -{ - int ret; - int n; - int i; - struct qsockaddr readaddr; - struct qsockaddr myaddr; - int control; +static void _Datagram_SearchForHosts(qboolean xmit) { + int ret; + int n; + int i; + struct qsockaddr readaddr; + struct qsockaddr myaddr; + int control; - dfunc.GetSocketAddr (dfunc.controlSock, &myaddr); - if (xmit) - { - SZ_Clear(&net_message); - // save space for the header, filled in later - MSG_WriteLong(&net_message, 0); - MSG_WriteByte(&net_message, CCREQ_SERVER_INFO); - MSG_WriteString(&net_message, "QUAKE"); - MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION); - *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Broadcast(dfunc.controlSock, net_message.data, net_message.cursize); - SZ_Clear(&net_message); - } + dfunc.GetSocketAddr(dfunc.controlSock, &myaddr); + if (xmit) { + SZ_Clear(&net_message); + // save space for the header, filled in later + MSG_WriteLong(&net_message, 0); + MSG_WriteByte(&net_message, CCREQ_SERVER_INFO); + MSG_WriteString(&net_message, "QUAKE"); + MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION); + *((int *) net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); + dfunc.Broadcast(dfunc.controlSock, net_message.data, net_message.cursize); + SZ_Clear(&net_message); + } - while ((ret = dfunc.Read (dfunc.controlSock, net_message.data, net_message.maxsize, &readaddr)) > 0) - { - if (ret < (int) sizeof(int)) - continue; - net_message.cursize = ret; + while ((ret = dfunc.Read(dfunc.controlSock, net_message.data, net_message.maxsize, &readaddr)) > 0) { + if (ret < (int) sizeof(int)) + continue; + net_message.cursize = ret; - // don't answer our own query - if (dfunc.AddrCompare(&readaddr, &myaddr) >= 0) - continue; + // don't answer our own query + if (dfunc.AddrCompare(&readaddr, &myaddr) >= 0) + continue; - // is the cache full? - if (hostCacheCount == HOSTCACHESIZE) - continue; + // is the cache full? + if (hostCacheCount == HOSTCACHESIZE) + continue; - MSG_BeginReading (); - control = BigLong(*((int *)net_message.data)); - MSG_ReadLong(); - if (control == -1) - continue; - if ((control & (~NETFLAG_LENGTH_MASK)) != (int)NETFLAG_CTL) - continue; - if ((control & NETFLAG_LENGTH_MASK) != ret) - continue; + MSG_BeginReading(); + control = BigLong(*((int *) net_message.data)); + MSG_ReadLong(); + if (control == -1) + continue; + if ((control & (~NETFLAG_LENGTH_MASK)) != (int) NETFLAG_CTL) + continue; + if ((control & NETFLAG_LENGTH_MASK) != ret) + continue; - if (MSG_ReadByte() != CCREP_SERVER_INFO) - continue; + if (MSG_ReadByte() != CCREP_SERVER_INFO) + continue; - dfunc.GetAddrFromName(MSG_ReadString(), &readaddr); - // search the cache for this server - for (n = 0; n < hostCacheCount; n++) - { - if (dfunc.AddrCompare(&readaddr, &hostcache[n].addr) == 0) - break; - } + dfunc.GetAddrFromName(MSG_ReadString(), &readaddr); + // search the cache for this server + for (n = 0; n < hostCacheCount; n++) { + if (dfunc.AddrCompare(&readaddr, &hostcache[n].addr) == 0) + break; + } - // is it already there? - if (n < hostCacheCount) - continue; + // is it already there? + if (n < hostCacheCount) + continue; - // add it - hostCacheCount++; - Q_strcpy(hostcache[n].name, MSG_ReadString()); - Q_strcpy(hostcache[n].map, MSG_ReadString()); - hostcache[n].users = MSG_ReadByte(); - hostcache[n].maxusers = MSG_ReadByte(); - if (MSG_ReadByte() != NET_PROTOCOL_VERSION) - { - Q_strcpy(hostcache[n].cname, hostcache[n].name); - hostcache[n].cname[14] = 0; - Q_strcpy(hostcache[n].name, "*"); - Q_strcat(hostcache[n].name, hostcache[n].cname); - } - Q_memcpy(&hostcache[n].addr, &readaddr, sizeof(struct qsockaddr)); - hostcache[n].driver = net_driverlevel; - hostcache[n].ldriver = net_landriverlevel; - Q_strcpy(hostcache[n].cname, dfunc.AddrToString(&readaddr)); + // add it + hostCacheCount++; + Q_strcpy(hostcache[n].name, MSG_ReadString()); + Q_strcpy(hostcache[n].map, MSG_ReadString()); + hostcache[n].users = MSG_ReadByte(); + hostcache[n].maxusers = MSG_ReadByte(); + if (MSG_ReadByte() != NET_PROTOCOL_VERSION) { + Q_strcpy(hostcache[n].cname, hostcache[n].name); + hostcache[n].cname[14] = 0; + Q_strcpy(hostcache[n].name, "*"); + Q_strcat(hostcache[n].name, hostcache[n].cname); + } + Q_memcpy(&hostcache[n].addr, &readaddr, sizeof(struct qsockaddr)); + hostcache[n].driver = net_driverlevel; + hostcache[n].ldriver = net_landriverlevel; + Q_strcpy(hostcache[n].cname, dfunc.AddrToString(&readaddr)); - // check for a name conflict - for (i = 0; i < hostCacheCount; i++) - { - if (i == n) - continue; - if (q_strcasecmp (hostcache[n].name, hostcache[i].name) == 0) - { - i = Q_strlen(hostcache[n].name); - if (i < 15 && hostcache[n].name[i-1] > '8') - { - hostcache[n].name[i] = '0'; - hostcache[n].name[i+1] = 0; - } - else - hostcache[n].name[i-1]++; + // check for a name conflict + for (i = 0; i < hostCacheCount; i++) { + if (i == n) + continue; + if (q_strcasecmp(hostcache[n].name, hostcache[i].name) == 0) { + i = Q_strlen(hostcache[n].name); + if (i < 15 && hostcache[n].name[i - 1] > '8') { + hostcache[n].name[i] = '0'; + hostcache[n].name[i + 1] = 0; + } else + hostcache[n].name[i - 1]++; - i = -1; - } - } - } + i = -1; + } + } + } } -void Datagram_SearchForHosts (qboolean xmit) -{ - for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) - { - if (hostCacheCount == HOSTCACHESIZE) - break; - if (net_landrivers[net_landriverlevel].initialized) - _Datagram_SearchForHosts (xmit); - } +void Datagram_SearchForHosts(qboolean xmit) { + for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) { + if (hostCacheCount == HOSTCACHESIZE) + break; + if (net_landrivers[net_landriverlevel].initialized) + _Datagram_SearchForHosts(xmit); + } } -static qsocket_t *_Datagram_Connect (const char *host) -{ - struct qsockaddr sendaddr; - struct qsockaddr readaddr; - qsocket_t *sock; - sys_socket_t newsock; - int ret; - int reps; - double start_time; - int control; - const char *reason; +static qsocket_t *_Datagram_Connect(const char *host) { + struct qsockaddr sendaddr; + struct qsockaddr readaddr; + qsocket_t *sock; + sys_socket_t newsock; + int ret; + int reps; + double start_time; + int control; + const char *reason; - // see if we can resolve the host name - if (dfunc.GetAddrFromName(host, &sendaddr) == -1) - { - Con_Printf("Could not resolve %s\n", host); - return NULL; - } + // see if we can resolve the host name + if (dfunc.GetAddrFromName(host, &sendaddr) == -1) { + Con_Printf("Could not resolve %s\n", host); + return NULL; + } - newsock = dfunc.Open_Socket (0); - if (newsock == INVALID_SOCKET) - return NULL; + newsock = dfunc.Open_Socket(0); + if (newsock == INVALID_SOCKET) + return NULL; - sock = NET_NewQSocket (); - if (sock == NULL) - goto ErrorReturn2; - sock->socket = newsock; - sock->landriver = net_landriverlevel; + sock = NET_NewQSocket(); + if (sock == NULL) + goto ErrorReturn2; + sock->socket = newsock; + sock->landriver = net_landriverlevel; - // connect to the host - if (dfunc.Connect (newsock, &sendaddr) == -1) - goto ErrorReturn; + // connect to the host + if (dfunc.Connect(newsock, &sendaddr) == -1) + goto ErrorReturn; - // send the connection request - Con_Printf("trying...\n"); - SCR_UpdateScreen (); - start_time = net_time; + // send the connection request + Con_Printf("trying...\n"); + SCR_UpdateScreen(); + start_time = net_time; - for (reps = 0; reps < 3; reps++) - { - SZ_Clear(&net_message); - // save space for the header, filled in later - MSG_WriteLong(&net_message, 0); - MSG_WriteByte(&net_message, CCREQ_CONNECT); - MSG_WriteString(&net_message, "QUAKE"); - MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION); - *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Write (newsock, net_message.data, net_message.cursize, &sendaddr); - SZ_Clear(&net_message); - do - { - ret = dfunc.Read (newsock, net_message.data, net_message.maxsize, &readaddr); - // if we got something, validate it - if (ret > 0) - { - // is it from the right place? - if (sfunc.AddrCompare(&readaddr, &sendaddr) != 0) - { - Con_Printf("wrong reply address\n"); - Con_Printf("Expected: %s | %s\n", dfunc.AddrToString (&sendaddr), StrAddr(&sendaddr)); - Con_Printf("Received: %s | %s\n", dfunc.AddrToString (&readaddr), StrAddr(&readaddr)); - SCR_UpdateScreen (); - ret = 0; - continue; - } + for (reps = 0; reps < 3; reps++) { + SZ_Clear(&net_message); + // save space for the header, filled in later + MSG_WriteLong(&net_message, 0); + MSG_WriteByte(&net_message, CCREQ_CONNECT); + MSG_WriteString(&net_message, "QUAKE"); + MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION); + *((int *) net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); + dfunc.Write(newsock, net_message.data, net_message.cursize, &sendaddr); + SZ_Clear(&net_message); + do { + ret = dfunc.Read(newsock, net_message.data, net_message.maxsize, &readaddr); + // if we got something, validate it + if (ret > 0) { + // is it from the right place? + if (sfunc.AddrCompare(&readaddr, &sendaddr) != 0) { + Con_Printf("wrong reply address\n"); + Con_Printf("Expected: %s | %s\n", dfunc.AddrToString(&sendaddr), StrAddr(&sendaddr)); + Con_Printf("Received: %s | %s\n", dfunc.AddrToString(&readaddr), StrAddr(&readaddr)); + SCR_UpdateScreen(); + ret = 0; + continue; + } - if (ret < (int) sizeof(int)) - { - ret = 0; - continue; - } + if (ret < (int) sizeof(int)) { + ret = 0; + continue; + } - net_message.cursize = ret; - MSG_BeginReading (); + net_message.cursize = ret; + MSG_BeginReading(); - control = BigLong(*((int *)net_message.data)); - MSG_ReadLong(); - if (control == -1) - { - ret = 0; - continue; - } - if ((control & (~NETFLAG_LENGTH_MASK)) != (int)NETFLAG_CTL) - { - ret = 0; - continue; - } - if ((control & NETFLAG_LENGTH_MASK) != ret) - { - ret = 0; - continue; - } - } - } - while (ret == 0 && (SetNetTime() - start_time) < 2.5); + control = BigLong(*((int *) net_message.data)); + MSG_ReadLong(); + if (control == -1) { + ret = 0; + continue; + } + if ((control & (~NETFLAG_LENGTH_MASK)) != (int) NETFLAG_CTL) { + ret = 0; + continue; + } + if ((control & NETFLAG_LENGTH_MASK) != ret) { + ret = 0; + continue; + } + } + } while (ret == 0 && (SetNetTime() - start_time) < 2.5); - if (ret) - break; + if (ret) + break; - Con_Printf("still trying...\n"); - SCR_UpdateScreen (); - start_time = SetNetTime(); - } + Con_Printf("still trying...\n"); + SCR_UpdateScreen(); + start_time = SetNetTime(); + } - if (ret == 0) - { - reason = "No Response"; - Con_Printf("%s\n", reason); - Q_strcpy(m_return_reason, reason); - goto ErrorReturn; - } + if (ret == 0) { + reason = "No Response"; + Con_Printf("%s\n", reason); + Q_strcpy(m_return_reason, reason); + goto ErrorReturn; + } - if (ret == -1) - { - reason = "Network Error"; - Con_Printf("%s\n", reason); - Q_strcpy(m_return_reason, reason); - goto ErrorReturn; - } + if (ret == -1) { + reason = "Network Error"; + Con_Printf("%s\n", reason); + Q_strcpy(m_return_reason, reason); + goto ErrorReturn; + } - ret = MSG_ReadByte(); - if (ret == CCREP_REJECT) - { - reason = MSG_ReadString(); - Con_Printf("%s\n", reason); - q_strlcpy(m_return_reason, reason, sizeof(m_return_reason)); - goto ErrorReturn; - } + ret = MSG_ReadByte(); + if (ret == CCREP_REJECT) { + reason = MSG_ReadString(); + Con_Printf("%s\n", reason); + q_strlcpy(m_return_reason, reason, sizeof(m_return_reason)); + goto ErrorReturn; + } - if (ret == CCREP_ACCEPT) - { - Q_memcpy(&sock->addr, &sendaddr, sizeof(struct qsockaddr)); - dfunc.SetSocketPort (&sock->addr, MSG_ReadLong()); - } - else - { - reason = "Bad Response"; - Con_Printf("%s\n", reason); - Q_strcpy(m_return_reason, reason); - goto ErrorReturn; - } + if (ret == CCREP_ACCEPT) { + Q_memcpy(&sock->addr, &sendaddr, sizeof(struct qsockaddr)); + dfunc.SetSocketPort(&sock->addr, MSG_ReadLong()); + } else { + reason = "Bad Response"; + Con_Printf("%s\n", reason); + Q_strcpy(m_return_reason, reason); + goto ErrorReturn; + } - dfunc.GetNameFromAddr (&sendaddr, sock->address); + dfunc.GetNameFromAddr(&sendaddr, sock->address); - Con_Printf ("Connection accepted\n"); - sock->lastMessageTime = SetNetTime(); + Con_Printf("Connection accepted\n"); + sock->lastMessageTime = SetNetTime(); - // switch the connection to the specified address - if (dfunc.Connect (newsock, &sock->addr) == -1) - { - reason = "Connect to Game failed"; - Con_Printf("%s\n", reason); - Q_strcpy(m_return_reason, reason); - goto ErrorReturn; - } + // switch the connection to the specified address + if (dfunc.Connect(newsock, &sock->addr) == -1) { + reason = "Connect to Game failed"; + Con_Printf("%s\n", reason); + Q_strcpy(m_return_reason, reason); + goto ErrorReturn; + } - m_return_onerror = false; - return sock; + m_return_onerror = false; + return sock; ErrorReturn: - NET_FreeQSocket(sock); + NET_FreeQSocket(sock); ErrorReturn2: - dfunc.Close_Socket(newsock); - if (m_return_onerror) - { - IN_Deactivate(modestate == MS_WINDOWED); - key_dest = key_menu; - m_state = m_return_state; - m_return_onerror = false; - } - return NULL; + dfunc.Close_Socket(newsock); + if (m_return_onerror) { + IN_Deactivate(modestate == MS_WINDOWED); + key_dest = key_menu; + m_state = m_return_state; + m_return_onerror = false; + } + return NULL; } -qsocket_t *Datagram_Connect (const char *host) -{ - qsocket_t *ret = NULL; +qsocket_t *Datagram_Connect(const char *host) { + qsocket_t *ret = NULL; - host = Strip_Port (host); - for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) - { - if (net_landrivers[net_landriverlevel].initialized) - { - if ((ret = _Datagram_Connect (host)) != NULL) - break; - } - } - return ret; + host = Strip_Port(host); + for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) { + if (net_landrivers[net_landriverlevel].initialized) { + if ((ret = _Datagram_Connect(host)) != NULL) + break; + } + } + return ret; } - diff --git a/Quake/net_main.cpp b/Quake/net_main.cpp index 1395339..96894f9 100644 --- a/Quake/net_main.cpp +++ b/Quake/net_main.cpp @@ -25,56 +25,57 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.hpp" #include "net_defs.hpp" -qsocket_t *net_activeSockets = NULL; -qsocket_t *net_freeSockets = NULL; -int net_numsockets = 0; +qsocket_t *net_activeSockets = NULL; +qsocket_t *net_freeSockets = NULL; +int net_numsockets = 0; -qboolean ipxAvailable = false; -qboolean tcpipAvailable = false; +qboolean ipxAvailable = false; +qboolean tcpipAvailable = false; -int net_hostport; -int DEFAULTnet_hostport = 26000; +int net_hostport; +int DEFAULTnet_hostport = 26000; -char my_ipx_address[NET_NAMELEN]; -char my_tcpip_address[NET_NAMELEN]; +char my_ipx_address[NET_NAMELEN]; +char my_tcpip_address[NET_NAMELEN]; -static qboolean listening = false; +static qboolean listening = false; -qboolean slistInProgress = false; -qboolean slistSilent = false; -qboolean slistLocal = true; -static double slistStartTime; -static int slistLastShown; +qboolean slistInProgress = false; +qboolean slistSilent = false; +qboolean slistLocal = true; +static double slistStartTime; +static int slistLastShown; -static void Slist_Send (void *); -static void Slist_Poll (void *); -static PollProcedure slistSendProcedure = {NULL, 0.0, Slist_Send}; -static PollProcedure slistPollProcedure = {NULL, 0.0, Slist_Poll}; +static void Slist_Send(void *); -sizebuf_t net_message; -int net_activeconnections = 0; +static void Slist_Poll(void *); -int messagesSent = 0; -int messagesReceived = 0; -int unreliableMessagesSent = 0; -int unreliableMessagesReceived = 0; +static PollProcedure slistSendProcedure = {NULL, 0.0, Slist_Send}; +static PollProcedure slistPollProcedure = {NULL, 0.0, Slist_Poll}; -static cvar_t net_messagetimeout = {"net_messagetimeout","300",CVAR_NONE}; -cvar_t hostname = {"hostname", "UNNAMED", CVAR_NONE}; +sizebuf_t net_message; +int net_activeconnections = 0; + +int messagesSent = 0; +int messagesReceived = 0; +int unreliableMessagesSent = 0; +int unreliableMessagesReceived = 0; + +static convar net_messagetimeout = {"net_messagetimeout", "300"}; +convar hostname = {"hostname", "UNNAMED"}; // these two macros are to make the code more readable #define sfunc net_drivers[sock->driver] #define dfunc net_drivers[net_driverlevel] -int net_driverlevel; +int net_driverlevel; -double net_time; +double net_time; -double SetNetTime (void) -{ - net_time = Sys_DoubleTime(); - return net_time; +double SetNetTime(void) { + net_time = Sys_DoubleTime(); + return net_time; } @@ -86,320 +87,282 @@ Called by drivers when a new communications endpoint is required The sequence and buffer fields will be filled in properly =================== */ -qsocket_t *NET_NewQSocket (void) -{ - qsocket_t *sock; +qsocket_t *NET_NewQSocket(void) { + qsocket_t *sock; - if (net_freeSockets == NULL) - return NULL; + if (net_freeSockets == NULL) + return NULL; - if (net_activeconnections >= svs.maxclients) - return NULL; + if (net_activeconnections >= svs.maxclients) + return NULL; - // get one from free list - sock = net_freeSockets; - net_freeSockets = sock->next; + // get one from free list + sock = net_freeSockets; + net_freeSockets = sock->next; - // add it to active list - sock->next = net_activeSockets; - net_activeSockets = sock; + // add it to active list + sock->next = net_activeSockets; + net_activeSockets = sock; - sock->disconnected = false; - sock->connecttime = net_time; - Q_strcpy (sock->address,"UNSET ADDRESS"); - sock->driver = net_driverlevel; - sock->socket = 0; - sock->driverdata = NULL; - sock->canSend = true; - sock->sendNext = false; - sock->lastMessageTime = net_time; - sock->ackSequence = 0; - sock->sendSequence = 0; - sock->unreliableSendSequence = 0; - sock->sendMessageLength = 0; - sock->receiveSequence = 0; - sock->unreliableReceiveSequence = 0; - sock->receiveMessageLength = 0; + sock->disconnected = false; + sock->connecttime = net_time; + Q_strcpy(sock->address, "UNSET ADDRESS"); + sock->driver = net_driverlevel; + sock->socket = 0; + sock->driverdata = NULL; + sock->canSend = true; + sock->sendNext = false; + sock->lastMessageTime = net_time; + sock->ackSequence = 0; + sock->sendSequence = 0; + sock->unreliableSendSequence = 0; + sock->sendMessageLength = 0; + sock->receiveSequence = 0; + sock->unreliableReceiveSequence = 0; + sock->receiveMessageLength = 0; - return sock; + return sock; } -void NET_FreeQSocket(qsocket_t *sock) -{ - qsocket_t *s; +void NET_FreeQSocket(qsocket_t *sock) { + qsocket_t *s; - // remove it from active list - if (sock == net_activeSockets) - net_activeSockets = net_activeSockets->next; - else - { - for (s = net_activeSockets; s; s = s->next) - { - if (s->next == sock) - { - s->next = sock->next; - break; - } - } + // remove it from active list + if (sock == net_activeSockets) + net_activeSockets = net_activeSockets->next; + else { + for (s = net_activeSockets; s; s = s->next) { + if (s->next == sock) { + s->next = sock->next; + break; + } + } - if (!s) - Sys_Error ("NET_FreeQSocket: not active"); - } + if (!s) + Sys_Error("NET_FreeQSocket: not active"); + } - // add it to free list - sock->next = net_freeSockets; - net_freeSockets = sock; - sock->disconnected = true; + // add it to free list + sock->next = net_freeSockets; + net_freeSockets = sock; + sock->disconnected = true; } -double NET_QSocketGetTime (const qsocket_t *s) -{ - return s->connecttime; +double NET_QSocketGetTime(const qsocket_t *s) { + return s->connecttime; } -const char *NET_QSocketGetAddressString (const qsocket_t *s) -{ - return s->address; +const char *NET_QSocketGetAddressString(const qsocket_t *s) { + return s->address; } -static void NET_Listen_f (void) -{ - if (Cmd_Argc () != 2) - { - Con_Printf ("\"listen\" is \"%d\"\n", listening ? 1 : 0); - return; - } +static void NET_Listen_f(void) { + if (command::argc() != 2) { + Con_Printf("\"listen\" is \"%d\"\n", listening ? 1 : 0); + return; + } - listening = Q_atoi(Cmd_Argv(1)) ? true : false; + listening = Q_atoi(command::argv(1)->c_str()) ? true : false; - for (net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) - { - if (net_drivers[net_driverlevel].initialized == false) - continue; - dfunc.Listen (listening); - } + for (net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) { + if (net_drivers[net_driverlevel].initialized == false) + continue; + dfunc.Listen(listening); + } } -static void MaxPlayers_f (void) -{ - int n; +static void MaxPlayers_f(void) { + int n; - if (Cmd_Argc () != 2) - { - Con_Printf ("\"maxplayers\" is \"%d\"\n", svs.maxclients); - return; - } + if (command::argc() != 2) { + Con_Printf("\"maxplayers\" is \"%d\"\n", svs.maxclients); + return; + } - if (sv.active) - { - Con_Printf ("maxplayers can not be changed while a server is running.\n"); - return; - } + if (sv.active) { + Con_Printf("maxplayers can not be changed while a server is running.\n"); + return; + } - n = Q_atoi(Cmd_Argv(1)); - if (n < 1) - n = 1; - if (n > svs.maxclientslimit) - { - n = svs.maxclientslimit; - Con_Printf ("\"maxplayers\" set to \"%d\"\n", n); - } + n = Q_atoi(command::argv(1)->c_str()); + if (n < 1) + n = 1; + if (n > svs.maxclientslimit) { + n = svs.maxclientslimit; + Con_Printf("\"maxplayers\" set to \"%d\"\n", n); + } - if ((n == 1) && listening) - Cbuf_AddText ("listen 0\n"); + if ((n == 1) && listening) + Cbuf_AddText("listen 0\n"); - if ((n > 1) && (!listening)) - Cbuf_AddText ("listen 1\n"); + if ((n > 1) && (!listening)) + Cbuf_AddText("listen 1\n"); - svs.maxclients = n; - if (n == 1) - Cvar_Set ("deathmatch", "0"); - else - Cvar_Set ("deathmatch", "1"); + svs.maxclients = n; + if (n == 1) + convar::set("deathmatch", "0"); + else + convar::set("deathmatch", "1"); } -static void NET_Port_f (void) -{ - int n; +static void NET_Port_f(void) { + int n; - if (Cmd_Argc () != 2) - { - Con_Printf ("\"port\" is \"%d\"\n", net_hostport); - return; - } + if (command::argc() != 2) { + Con_Printf("\"port\" is \"%d\"\n", net_hostport); + return; + } - n = Q_atoi(Cmd_Argv(1)); - if (n < 1 || n > 65534) - { - Con_Printf ("Bad value, must be between 1 and 65534\n"); - return; - } + n = Q_atoi(command::argv(1)->c_str()); + if (n < 1 || n > 65534) { + Con_Printf("Bad value, must be between 1 and 65534\n"); + return; + } - DEFAULTnet_hostport = n; - net_hostport = n; + DEFAULTnet_hostport = n; + net_hostport = n; - if (listening) - { - // force a change to the new port - Cbuf_AddText ("listen 0\n"); - Cbuf_AddText ("listen 1\n"); - } + if (listening) { + // force a change to the new port + Cbuf_AddText("listen 0\n"); + Cbuf_AddText("listen 1\n"); + } } -static void PrintSlistHeader(void) -{ - Con_Printf("Server Map Users\n"); - Con_Printf("--------------- --------------- -----\n"); - slistLastShown = 0; +static void PrintSlistHeader(void) { + Con_Printf("Server Map Users\n"); + Con_Printf("--------------- --------------- -----\n"); + slistLastShown = 0; } -static void PrintSlist(void) -{ - int n; +static void PrintSlist(void) { + int n; - for (n = slistLastShown; n < hostCacheCount; n++) - { - if (hostcache[n].maxusers) - Con_Printf("%-15.15s %-15.15s %2u/%2u\n", hostcache[n].name, hostcache[n].map, hostcache[n].users, hostcache[n].maxusers); - else - Con_Printf("%-15.15s %-15.15s\n", hostcache[n].name, hostcache[n].map); - } - slistLastShown = n; + for (n = slistLastShown; n < hostCacheCount; n++) { + if (hostcache[n].maxusers) + Con_Printf("%-15.15s %-15.15s %2u/%2u\n", hostcache[n].name, hostcache[n].map, hostcache[n].users, + hostcache[n].maxusers); + else + Con_Printf("%-15.15s %-15.15s\n", hostcache[n].name, hostcache[n].map); + } + slistLastShown = n; } -static void PrintSlistTrailer(void) -{ - if (hostCacheCount) - Con_Printf("== end list ==\n\n"); - else - Con_Printf("No Quake servers found.\n\n"); +static void PrintSlistTrailer(void) { + if (hostCacheCount) + Con_Printf("== end list ==\n\n"); + else + Con_Printf("No Quake servers found.\n\n"); } -void NET_Slist_f (void) -{ - if (slistInProgress) - return; +void NET_Slist_f(void) { + if (slistInProgress) + return; - if (! slistSilent) - { - Con_Printf("Looking for Quake servers...\n"); - PrintSlistHeader(); - } + if (!slistSilent) { + Con_Printf("Looking for Quake servers...\n"); + PrintSlistHeader(); + } - slistInProgress = true; - slistStartTime = Sys_DoubleTime(); + slistInProgress = true; + slistStartTime = Sys_DoubleTime(); - SchedulePollProcedure(&slistSendProcedure, 0.0); - SchedulePollProcedure(&slistPollProcedure, 0.1); + SchedulePollProcedure(&slistSendProcedure, 0.0); + SchedulePollProcedure(&slistPollProcedure, 0.1); - hostCacheCount = 0; + hostCacheCount = 0; } -void NET_SlistSort (void) -{ - if (hostCacheCount > 1) - { - int i, j; - hostcache_t temp; - for (i = 0; i < hostCacheCount; i++) - { - for (j = i + 1; j < hostCacheCount; j++) - { - if (strcmp(hostcache[j].name, hostcache[i].name) < 0) - { - memcpy(&temp, &hostcache[j], sizeof(hostcache_t)); - memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t)); - memcpy(&hostcache[i], &temp, sizeof(hostcache_t)); - } - } - } - } +void NET_SlistSort(void) { + if (hostCacheCount > 1) { + int i, j; + hostcache_t temp; + for (i = 0; i < hostCacheCount; i++) { + for (j = i + 1; j < hostCacheCount; j++) { + if (strcmp(hostcache[j].name, hostcache[i].name) < 0) { + memcpy(&temp, &hostcache[j], sizeof(hostcache_t)); + memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t)); + memcpy(&hostcache[i], &temp, sizeof(hostcache_t)); + } + } + } + } } -const char *NET_SlistPrintServer (int idx) -{ - static char string[64]; +const char *NET_SlistPrintServer(int idx) { + static char string[64]; - if (idx < 0 || idx >= hostCacheCount) - return ""; + if (idx < 0 || idx >= hostCacheCount) + return ""; - if (hostcache[idx].maxusers) - { - q_snprintf(string, sizeof(string), "%-15.15s %-15.15s %2u/%2u\n", - hostcache[idx].name, hostcache[idx].map, - hostcache[idx].users, hostcache[idx].maxusers); - } - else - { - q_snprintf(string, sizeof(string), "%-15.15s %-15.15s\n", - hostcache[idx].name, hostcache[idx].map); - } + if (hostcache[idx].maxusers) { + q_snprintf(string, sizeof(string), "%-15.15s %-15.15s %2u/%2u\n", + hostcache[idx].name, hostcache[idx].map, + hostcache[idx].users, hostcache[idx].maxusers); + } else { + q_snprintf(string, sizeof(string), "%-15.15s %-15.15s\n", + hostcache[idx].name, hostcache[idx].map); + } - return string; + return string; } -const char *NET_SlistPrintServerName (int idx) -{ - if (idx < 0 || idx >= hostCacheCount) - return ""; - return hostcache[idx].cname; +const char *NET_SlistPrintServerName(int idx) { + if (idx < 0 || idx >= hostCacheCount) + return ""; + return hostcache[idx].cname; } -static void Slist_Send (void *unused) -{ - for (net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) - { - if (!slistLocal && IS_LOOP_DRIVER(net_driverlevel)) - continue; - if (net_drivers[net_driverlevel].initialized == false) - continue; - dfunc.SearchForHosts (true); - } +static void Slist_Send(void *unused) { + for (net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) { + if (!slistLocal && IS_LOOP_DRIVER(net_driverlevel)) + continue; + if (net_drivers[net_driverlevel].initialized == false) + continue; + dfunc.SearchForHosts(true); + } - if ((Sys_DoubleTime() - slistStartTime) < 0.5) - SchedulePollProcedure(&slistSendProcedure, 0.75); + if ((Sys_DoubleTime() - slistStartTime) < 0.5) + SchedulePollProcedure(&slistSendProcedure, 0.75); } -static void Slist_Poll (void *unused) -{ - for (net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) - { - if (!slistLocal && IS_LOOP_DRIVER(net_driverlevel)) - continue; - if (net_drivers[net_driverlevel].initialized == false) - continue; - dfunc.SearchForHosts (false); - } +static void Slist_Poll(void *unused) { + for (net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) { + if (!slistLocal && IS_LOOP_DRIVER(net_driverlevel)) + continue; + if (net_drivers[net_driverlevel].initialized == false) + continue; + dfunc.SearchForHosts(false); + } - if (! slistSilent) - PrintSlist(); + if (!slistSilent) + PrintSlist(); - if ((Sys_DoubleTime() - slistStartTime) < 1.5) - { - SchedulePollProcedure(&slistPollProcedure, 0.1); - return; - } + if ((Sys_DoubleTime() - slistStartTime) < 1.5) { + SchedulePollProcedure(&slistPollProcedure, 0.1); + return; + } - if (! slistSilent) - PrintSlistTrailer(); - slistInProgress = false; - slistSilent = false; - slistLocal = true; + if (!slistSilent) + PrintSlistTrailer(); + slistInProgress = false; + slistSilent = false; + slistLocal = true; } @@ -412,83 +375,72 @@ NET_Connect int hostCacheCount = 0; hostcache_t hostcache[HOSTCACHESIZE]; -qsocket_t *NET_Connect (const char *host) -{ - qsocket_t *ret; - int n; - int numdrivers = net_numdrivers; +qsocket_t *NET_Connect(const char *host) { + qsocket_t *ret; + int n; + int numdrivers = net_numdrivers; - SetNetTime(); + SetNetTime(); - if (host && *host == 0) - host = NULL; + if (host && *host == 0) + host = NULL; - if (host) - { - if (q_strcasecmp (host, "local") == 0) - { - numdrivers = 1; - goto JustDoIt; - } + if (host) { + if (q_strcasecmp(host, "local") == 0) { + numdrivers = 1; + goto JustDoIt; + } - if (hostCacheCount) - { - for (n = 0; n < hostCacheCount; n++) - if (q_strcasecmp (host, hostcache[n].name) == 0) - { - host = hostcache[n].cname; - break; - } - if (n < hostCacheCount) - goto JustDoIt; - } - } + if (hostCacheCount) { + for (n = 0; n < hostCacheCount; n++) + if (q_strcasecmp(host, hostcache[n].name) == 0) { + host = hostcache[n].cname; + break; + } + if (n < hostCacheCount) + goto JustDoIt; + } + } - slistSilent = host ? true : false; - NET_Slist_f (); + slistSilent = host ? true : false; + NET_Slist_f(); - while (slistInProgress) - NET_Poll(); + while (slistInProgress) + NET_Poll(); - if (host == NULL) - { - if (hostCacheCount != 1) - return NULL; - host = hostcache[0].cname; - Con_Printf("Connecting to...\n%s @ %s\n\n", hostcache[0].name, host); - } + if (host == NULL) { + if (hostCacheCount != 1) + return NULL; + host = hostcache[0].cname; + Con_Printf("Connecting to...\n%s @ %s\n\n", hostcache[0].name, host); + } - if (hostCacheCount) - { - for (n = 0; n < hostCacheCount; n++) - { - if (q_strcasecmp (host, hostcache[n].name) == 0) - { - host = hostcache[n].cname; - break; - } - } - } + if (hostCacheCount) { + for (n = 0; n < hostCacheCount; n++) { + if (q_strcasecmp(host, hostcache[n].name) == 0) { + host = hostcache[n].cname; + break; + } + } + } JustDoIt: - for (net_driverlevel = 0; net_driverlevel < numdrivers; net_driverlevel++) - { - if (net_drivers[net_driverlevel].initialized == false) - continue; - ret = dfunc.Connect (host); - if (ret) - return ret; - } + for (net_driverlevel = 0; net_driverlevel < numdrivers; net_driverlevel++) { + if (net_drivers[net_driverlevel].initialized == false) + continue; + ret = dfunc.Connect(host); + if (ret) + return ret; + } - if (host) - { - Con_Printf("\n"); - PrintSlistHeader(); - PrintSlist(); - PrintSlistTrailer(); - } + if (host) { + Con_Printf("\n"); + PrintSlistHeader(); + PrintSlist(); + PrintSlistTrailer(); + } - return NULL; + return NULL; } @@ -497,26 +449,23 @@ JustDoIt: NET_CheckNewConnections =================== */ -qsocket_t *NET_CheckNewConnections (void) -{ - qsocket_t *ret; +qsocket_t *NET_CheckNewConnections(void) { + qsocket_t *ret; - SetNetTime(); + SetNetTime(); - for (net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) - { - if (net_drivers[net_driverlevel].initialized == false) - continue; - if (!IS_LOOP_DRIVER(net_driverlevel) && listening == false) - continue; - ret = dfunc.CheckNewConnections (); - if (ret) - { - return ret; - } - } + for (net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) { + if (net_drivers[net_driverlevel].initialized == false) + continue; + if (!IS_LOOP_DRIVER(net_driverlevel) && listening == false) + continue; + ret = dfunc.CheckNewConnections(); + if (ret) { + return ret; + } + } - return NULL; + return NULL; } /* @@ -524,20 +473,19 @@ qsocket_t *NET_CheckNewConnections (void) NET_Close =================== */ -void NET_Close (qsocket_t *sock) -{ - if (!sock) - return; +void NET_Close(qsocket_t *sock) { + if (!sock) + return; - if (sock->disconnected) - return; + if (sock->disconnected) + return; - SetNetTime(); + SetNetTime(); - // call the driver_Close function - sfunc.Close (sock); + // call the driver_Close function + sfunc.Close(sock); - NET_FreeQSocket(sock); + NET_FreeQSocket(sock); } @@ -552,46 +500,40 @@ returns 1 if a message was received returns -1 if connection is invalid ================= */ -int NET_GetMessage (qsocket_t *sock) -{ - int ret; +int NET_GetMessage(qsocket_t *sock) { + int ret; - if (!sock) - return -1; + if (!sock) + return -1; - if (sock->disconnected) - { - Con_Printf("NET_GetMessage: disconnected socket\n"); - return -1; - } + if (sock->disconnected) { + Con_Printf("NET_GetMessage: disconnected socket\n"); + return -1; + } - SetNetTime(); + SetNetTime(); - ret = sfunc.QGetMessage(sock); + ret = sfunc.QGetMessage(sock); - // see if this connection has timed out - if (ret == 0 && !IS_LOOP_DRIVER(sock->driver)) - { - if (net_time - sock->lastMessageTime > net_messagetimeout.value) - { - NET_Close(sock); - return -1; - } - } + // see if this connection has timed out + if (ret == 0 && !IS_LOOP_DRIVER(sock->driver)) { + if (net_time - sock->lastMessageTime > net_messagetimeout.value) { + NET_Close(sock); + return -1; + } + } - if (ret > 0) - { - if (!IS_LOOP_DRIVER(sock->driver)) - { - sock->lastMessageTime = net_time; - if (ret == 1) - messagesReceived++; - else if (ret == 2) - unreliableMessagesReceived++; - } - } + if (ret > 0) { + if (!IS_LOOP_DRIVER(sock->driver)) { + sock->lastMessageTime = net_time; + if (ret == 1) + messagesReceived++; + else if (ret == 2) + unreliableMessagesReceived++; + } + } - return ret; + return ret; } @@ -606,47 +548,43 @@ returns 1 if the message was sent properly returns -1 if the connection died ================== */ -int NET_SendMessage (qsocket_t *sock, sizebuf_t *data) -{ - int r; +int NET_SendMessage(qsocket_t *sock, sizebuf_t *data) { + int r; - if (!sock) - return -1; + if (!sock) + return -1; - if (sock->disconnected) - { - Con_Printf("NET_SendMessage: disconnected socket\n"); - return -1; - } + if (sock->disconnected) { + Con_Printf("NET_SendMessage: disconnected socket\n"); + return -1; + } - SetNetTime(); - r = sfunc.QSendMessage(sock, data); - if (r == 1 && !IS_LOOP_DRIVER(sock->driver)) - messagesSent++; + SetNetTime(); + r = sfunc.QSendMessage(sock, data); + if (r == 1 && !IS_LOOP_DRIVER(sock->driver)) + messagesSent++; - return r; + return r; } -int NET_SendUnreliableMessage (qsocket_t *sock, sizebuf_t *data) -{ - int r; +int NET_SendUnreliableMessage(qsocket_t *sock, sizebuf_t *data) { + int r; - if (!sock) - return -1; + if (!sock) + return -1; - if (sock->disconnected) - { - Con_Printf("NET_SendMessage: disconnected socket\n"); - return -1; - } + if (sock->disconnected) { + Con_Printf("NET_SendMessage: disconnected socket\n"); + return -1; + } - SetNetTime(); - r = sfunc.SendUnreliableMessage(sock, data); - if (r == 1 && !IS_LOOP_DRIVER(sock->driver)) - unreliableMessagesSent++; + SetNetTime(); + r = sfunc.SendUnreliableMessage(sock, data); + if (r == 1 && !IS_LOOP_DRIVER(sock->driver)) + unreliableMessagesSent++; - return r; + return r; } @@ -658,94 +596,77 @@ Returns true or false if the given qsocket can currently accept a message to be transmitted. ================== */ -qboolean NET_CanSendMessage (qsocket_t *sock) -{ - if (!sock) - return false; +qboolean NET_CanSendMessage(qsocket_t *sock) { + if (!sock) + return false; - if (sock->disconnected) - return false; + if (sock->disconnected) + return false; - SetNetTime(); + SetNetTime(); - return sfunc.CanSendMessage(sock); + return sfunc.CanSendMessage(sock); } -int NET_SendToAll (sizebuf_t *data, double blocktime) -{ - double start; - int i; - int count = 0; - qboolean msg_init[MAX_SCOREBOARD]; /* did we write the message to the client's connection */ - qboolean msg_sent[MAX_SCOREBOARD]; /* did the msg arrive its destination (canSend state). */ +int NET_SendToAll(sizebuf_t *data, double blocktime) { + double start; + int i; + int count = 0; + qboolean msg_init[MAX_SCOREBOARD]; /* did we write the message to the client's connection */ + qboolean msg_sent[MAX_SCOREBOARD]; /* did the msg arrive its destination (canSend state). */ - for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) - { - /* - if (!host_client->netconnection) - continue; - if (host_client->active) - */ - if (host_client->netconnection && host_client->active) - { - if (IS_LOOP_DRIVER(host_client->netconnection->driver)) - { - NET_SendMessage(host_client->netconnection, data); - msg_init[i] = true; - msg_sent[i] = true; - continue; - } - count++; - msg_init[i] = false; - msg_sent[i] = false; - } - else - { - msg_init[i] = true; - msg_sent[i] = true; - } - } + for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) { + /* + if (!host_client->netconnection) + continue; + if (host_client->active) + */ + if (host_client->netconnection && host_client->active) { + if (IS_LOOP_DRIVER(host_client->netconnection->driver)) { + NET_SendMessage(host_client->netconnection, data); + msg_init[i] = true; + msg_sent[i] = true; + continue; + } + count++; + msg_init[i] = false; + msg_sent[i] = false; + } else { + msg_init[i] = true; + msg_sent[i] = true; + } + } - start = Sys_DoubleTime(); - while (count) - { - count = 0; - for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) - { - if (! msg_init[i]) - { - if (NET_CanSendMessage (host_client->netconnection)) - { - msg_init[i] = true; - NET_SendMessage(host_client->netconnection, data); - } - else - { - NET_GetMessage (host_client->netconnection); - } - count++; - continue; - } + start = Sys_DoubleTime(); + while (count) { + count = 0; + for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) { + if (!msg_init[i]) { + if (NET_CanSendMessage(host_client->netconnection)) { + msg_init[i] = true; + NET_SendMessage(host_client->netconnection, data); + } else { + NET_GetMessage(host_client->netconnection); + } + count++; + continue; + } - if (! msg_sent[i]) - { - if (NET_CanSendMessage (host_client->netconnection)) - { - msg_sent[i] = true; - } - else - { - NET_GetMessage (host_client->netconnection); - } - count++; - continue; - } - } - if ((Sys_DoubleTime() - start) > blocktime) - break; - } - return count; + if (!msg_sent[i]) { + if (NET_CanSendMessage(host_client->netconnection)) { + msg_sent[i] = true; + } else { + NET_GetMessage(host_client->netconnection); + } + count++; + continue; + } + } + if ((Sys_DoubleTime() - start) > blocktime) + break; + } + return count; } @@ -757,81 +678,74 @@ NET_Init ==================== */ -void NET_Init (void) -{ - int i; - qsocket_t *s; +void NET_Init(void) { + int i; + qsocket_t *s; - i = COM_CheckParm ("-port"); - if (!i) - i = COM_CheckParm ("-udpport"); - if (!i) - i = COM_CheckParm ("-ipxport"); + i = COM_CheckParm("-port"); + if (!i) + i = COM_CheckParm("-udpport"); + if (!i) + i = COM_CheckParm("-ipxport"); - if (i) - { - if (i < com_argc-1) - DEFAULTnet_hostport = Q_atoi (com_argv[i+1]); - else - Sys_Error ("NET_Init: you must specify a number after -port"); - } - net_hostport = DEFAULTnet_hostport; + if (i) { + if (i < com_argc - 1) + DEFAULTnet_hostport = Q_atoi(com_argv[i + 1]); + else + Sys_Error("NET_Init: you must specify a number after -port"); + } + net_hostport = DEFAULTnet_hostport; - net_numsockets = svs.maxclientslimit; - if (cls.state != ca_dedicated) - net_numsockets++; - if (COM_CheckParm("-listen") || cls.state == ca_dedicated) - listening = true; + net_numsockets = svs.maxclientslimit; + if (cls.state != ca_dedicated) + net_numsockets++; + if (COM_CheckParm("-listen") || cls.state == ca_dedicated) + listening = true; - SetNetTime(); + SetNetTime(); - for (i = 0; i < net_numsockets; i++) - { - s = (qsocket_t *)Hunk_AllocName(sizeof(qsocket_t), "qsocket"); - s->next = net_freeSockets; - net_freeSockets = s; - s->disconnected = true; - } + for (i = 0; i < net_numsockets; i++) { + s = (qsocket_t *) Hunk_AllocName(sizeof(qsocket_t), "qsocket"); + s->next = net_freeSockets; + net_freeSockets = s; + s->disconnected = true; + } - // allocate space for network message buffer - SZ_Alloc (&net_message, NET_MAXMESSAGE); + // allocate space for network message buffer + SZ_Alloc(&net_message, NET_MAXMESSAGE); - Cvar_RegisterVariable (&net_messagetimeout); - Cvar_RegisterVariable (&hostname); + net_messagetimeout.inscribe(); + hostname.inscribe(); - Cmd_AddCommand ("slist", NET_Slist_f); - Cmd_AddCommand ("listen", NET_Listen_f); - Cmd_AddCommand ("maxplayers", MaxPlayers_f); - Cmd_AddCommand ("port", NET_Port_f); + command::add("slist", NET_Slist_f); + command::add("listen", NET_Listen_f); + command::add("maxplayers", MaxPlayers_f); + command::add("port", NET_Port_f); - // initialize all the drivers - for (i = net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) - { - if (net_drivers[net_driverlevel].Init() == -1) - continue; - i++; - net_drivers[net_driverlevel].initialized = true; - if (listening) - net_drivers[net_driverlevel].Listen (true); - } + // initialize all the drivers + for (i = net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) { + if (net_drivers[net_driverlevel].Init() == -1) + continue; + i++; + net_drivers[net_driverlevel].initialized = true; + if (listening) + net_drivers[net_driverlevel].Listen(true); + } - /* Loop_Init() returns -1 for dedicated server case, - * therefore the i == 0 check is correct */ - if (i == 0 - && cls.state == ca_dedicated - ) - { - Sys_Error("Network not available!"); - } + /* Loop_Init() returns -1 for dedicated server case, + * therefore the i == 0 check is correct */ + if (i == 0 + && cls.state == ca_dedicated + ) { + Sys_Error("Network not available!"); + } - if (*my_ipx_address) - { - Con_DPrintf("IPX address %s\n", my_ipx_address); - } - if (*my_tcpip_address) - { - Con_DPrintf("TCP/IP address %s\n", my_tcpip_address); - } + if (*my_ipx_address) { + Con_DPrintf("IPX address %s\n", my_ipx_address); + } + if (*my_tcpip_address) { + Con_DPrintf("TCP/IP address %s\n", my_tcpip_address); + } } /* @@ -840,67 +754,58 @@ NET_Shutdown ==================== */ -void NET_Shutdown (void) -{ - qsocket_t *sock; +void NET_Shutdown(void) { + qsocket_t *sock; - SetNetTime(); + SetNetTime(); - for (sock = net_activeSockets; sock; sock = sock->next) - NET_Close(sock); + for (sock = net_activeSockets; sock; sock = sock->next) + NET_Close(sock); -// -// shutdown the drivers -// - for (net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) - { - if (net_drivers[net_driverlevel].initialized == true) - { - net_drivers[net_driverlevel].Shutdown (); - net_drivers[net_driverlevel].initialized = false; - } - } + // + // shutdown the drivers + // + for (net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) { + if (net_drivers[net_driverlevel].initialized == true) { + net_drivers[net_driverlevel].Shutdown(); + net_drivers[net_driverlevel].initialized = false; + } + } } static PollProcedure *pollProcedureList = NULL; -void NET_Poll(void) -{ - PollProcedure *pp; +void NET_Poll(void) { + PollProcedure *pp; - SetNetTime(); + SetNetTime(); - for (pp = pollProcedureList; pp; pp = pp->next) - { - if (pp->nextTime > net_time) - break; - pollProcedureList = pp->next; - pp->procedure(pp->arg); - } + for (pp = pollProcedureList; pp; pp = pp->next) { + if (pp->nextTime > net_time) + break; + pollProcedureList = pp->next; + pp->procedure(pp->arg); + } } -void SchedulePollProcedure(PollProcedure *proc, double timeOffset) -{ - PollProcedure *pp, *prev; +void SchedulePollProcedure(PollProcedure *proc, double timeOffset) { + PollProcedure *pp, *prev; - proc->nextTime = Sys_DoubleTime() + timeOffset; - for (pp = pollProcedureList, prev = NULL; pp; pp = pp->next) - { - if (pp->nextTime >= proc->nextTime) - break; - prev = pp; - } + proc->nextTime = Sys_DoubleTime() + timeOffset; + for (pp = pollProcedureList, prev = NULL; pp; pp = pp->next) { + if (pp->nextTime >= proc->nextTime) + break; + prev = pp; + } - if (prev == NULL) - { - proc->next = pollProcedureList; - pollProcedureList = proc; - return; - } + if (prev == NULL) { + proc->next = pollProcedureList; + pollProcedureList = proc; + return; + } - proc->next = pp; - prev->next = proc; + proc->next = pp; + prev->next = proc; } - diff --git a/Quake/pl_linux.cpp b/Quake/pl_linux.cpp index 3e9f1b6..ae0c17f 100644 --- a/Quake/pl_linux.cpp +++ b/Quake/pl_linux.cpp @@ -80,7 +80,7 @@ char *PL_GetClipboardData (void) * such as an ip address, etc: do chop the size * here, otherwise we may experience Z_Malloc() * failures and all other not-oh-so-fun stuff. */ - size = q_min((size_t)(MAX_CLIPBOARDTXT), size); + size = std::min((size_t)(MAX_CLIPBOARDTXT), size); data = (char *) Z_Malloc((int)size); q_strlcpy (data, cliptext, size); } diff --git a/Quake/pl_osx.m b/Quake/pl_osx.m index 792afd1..ddc0fb5 100644 --- a/Quake/pl_osx.m +++ b/Quake/pl_osx.m @@ -67,7 +67,7 @@ char *PL_GetClipboardData (void) if (srcdata != NULL) { size_t sz = [clipboardString length] + 1; - sz = q_min((size_t)(MAX_CLIPBOARDTXT), sz); + sz = std::min((size_t)(MAX_CLIPBOARDTXT), sz); data = (char *) Z_Malloc((int)sz); q_strlcpy (data, srcdata, sz); } diff --git a/Quake/pl_win.cpp b/Quake/pl_win.cpp index 486e3fc..ea0d8eb 100644 --- a/Quake/pl_win.cpp +++ b/Quake/pl_win.cpp @@ -95,7 +95,7 @@ char *PL_GetClipboardData (void) * such as an ip address, etc: do chop the size * here, otherwise we may experience Z_Malloc() * failures and all other not-oh-so-fun stuff. */ - size = q_min((size_t)(MAX_CLIPBOARDTXT), size); + size = std::min((size_t)(MAX_CLIPBOARDTXT), size); data = (char *) Z_Malloc((int)size); q_strlcpy (data, cliptext, size); GlobalUnlock (hClipboardData); diff --git a/Quake/pr_cmds.cpp b/Quake/pr_cmds.cpp index 03d416d..d11dd80 100644 --- a/Quake/pr_cmds.cpp +++ b/Quake/pr_cmds.cpp @@ -930,7 +930,7 @@ static void PF_cvar (void) str = G_STRING(OFS_PARM0); - G_FLOAT(OFS_RETURN) = Cvar_VariableValue (str); + G_FLOAT(OFS_RETURN) = convar::variable_value(str).value_or(0.0); } /* @@ -947,7 +947,7 @@ static void PF_cvar_set (void) var = G_STRING(OFS_PARM0); val = G_STRING(OFS_PARM1); - Cvar_Set (var, val); + convar::set (var, val); } /* @@ -1378,7 +1378,7 @@ Pick a vector for the player to shoot along vector aim(entity, missilespeed) ============= */ -cvar_t sv_aim = {"sv_aim", "1", CVAR_NONE}; // ericw -- turn autoaim off by default. was 0.93 +convar sv_aim{"sv_aim", "1"}; // ericw -- turn autoaim off by default. was 0.93 static void PF_aim (void) { edict_t *ent, *check, *bestent; diff --git a/Quake/pr_edict.cpp b/Quake/pr_edict.cpp index 452d09f..ce233b8 100644 --- a/Quake/pr_edict.cpp +++ b/Quake/pr_edict.cpp @@ -21,6 +21,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // sv_edict.c -- entity dictionary +#include + #include "quakedef.hpp" dprograms_t *progs; @@ -72,17 +74,17 @@ static gefv_cache gefvCache[GEFV_CACHESIZE] = { NULL, "" } }; -cvar_t nomonsters = {"nomonsters", "0", CVAR_NONE}; -cvar_t gamecfg = {"gamecfg", "0", CVAR_NONE}; -cvar_t scratch1 = {"scratch1", "0", CVAR_NONE}; -cvar_t scratch2 = {"scratch2", "0", CVAR_NONE}; -cvar_t scratch3 = {"scratch3", "0", CVAR_NONE}; -cvar_t scratch4 = {"scratch4", "0", CVAR_NONE}; -cvar_t savedgamecfg = {"savedgamecfg", "0", CVAR_ARCHIVE}; -cvar_t saved1 = {"saved1", "0", CVAR_ARCHIVE}; -cvar_t saved2 = {"saved2", "0", CVAR_ARCHIVE}; -cvar_t saved3 = {"saved3", "0", CVAR_ARCHIVE}; -cvar_t saved4 = {"saved4", "0", CVAR_ARCHIVE}; +convar nomonsters{"nomonsters", "0"}; +convar gamecfg{"gamecfg", "0"}; +convar scratch1{"scratch1", "0"}; +convar scratch2{"scratch2", "0"}; +convar scratch3{"scratch3", "0"}; +convar scratch4{"scratch4", "0"}; +convar savedgamecfg{"savedgamecfg", "0", {.archive = true}}; +convar saved1{"saved1", "0", {.archive = true}}; +convar saved2{"saved2", "0", {.archive = true}}; +convar saved3{"saved3", "0", {.archive = true}}; +convar saved4{"saved4", "0", {.archive = true}}; /* ================= @@ -619,7 +621,7 @@ static void ED_PrintEdict_f (void) if (!sv.active) return; - i = Q_atoi (Cmd_Argv(1)); + i = Q_atoi (command::argv(1).value_or("").c_str()); if (i < 0 || i >= sv.num_edicts) { Con_Printf("Bad edict number\n"); @@ -711,41 +713,43 @@ void ED_WriteGlobals (FILE *f) ED_ParseGlobals ============= */ -const char *ED_ParseGlobals (const char *data) +void ED_ParseGlobals (std::istringstream &ss) { - char keyname[64]; ddef_t *key; - while (1) + std::string keyname; + + while (true) { // parse key - data = COM_Parse (data); - if (com_token[0] == '}') + auto token = common::parse_token(ss); + if (token.has_value() && token->front() == '}') { break; - if (!data) + } + if (ss.eof()) { Host_Error ("ED_ParseEntity: EOF without closing brace"); + } - q_strlcpy (keyname, com_token, sizeof(keyname)); + keyname = token.value(); // parse value - data = COM_Parse (data); - if (!data) + token = common::parse_token(ss); + if (ss.eof()) Host_Error ("ED_ParseEntity: EOF without closing brace"); - if (com_token[0] == '}') + if (token->front() == '}') Host_Error ("ED_ParseEntity: closing brace without data"); - key = ED_FindGlobal (keyname); + key = ED_FindGlobal (keyname.c_str()); if (!key) { - Con_Printf ("'%s' is not a global\n", keyname); + Con_Printf ("'%s' is not a global\n", keyname.c_str()); continue; } - if (!ED_ParseEpair ((void *)pr_globals, key, com_token)) + if (!ED_ParseEpair ((void *)pr_globals, key, token->c_str())) Host_Error ("ED_ParseGlobals: parse error"); } - return data; } //============================================================================ @@ -879,13 +883,14 @@ ed should be a properly initialized empty edict. Used for initial level load and for savegames. ==================== */ -const char *ED_ParseEdict (const char *data, edict_t *ent) +void ED_ParseEdict(std::istringstream &ss, edict_t *ent) { ddef_t *key; - char keyname[256]; qboolean anglehack, init; int n; + std::string keyname{}; + init = false; // clear it @@ -896,83 +901,82 @@ const char *ED_ParseEdict (const char *data, edict_t *ent) while (1) { // parse key - data = COM_Parse (data); - if (com_token[0] == '}') + auto token = common::parse_token(ss); + if (token.has_value() && token->front() == '}') { break; - if (!data) + } + if (ss.eof()) { Host_Error ("ED_ParseEntity: EOF without closing brace"); + } // anglehack is to allow QuakeEd to write single scalar angles // and allow them to be turned into vectors. (FIXME...) - if (!strcmp(com_token, "angle")) + if (token == "angle") { - strcpy (com_token, "angles"); + token = "angles"; anglehack = true; } else anglehack = false; // FIXME: change light to _light to get rid of this hack - if (!strcmp(com_token, "light")) - strcpy (com_token, "light_lev"); // hack for single light def + if (token == "light") { + token = "light_lev"; + } - q_strlcpy (keyname, com_token, sizeof(keyname)); + keyname = *token; // another hack to fix keynames with trailing spaces - n = strlen(keyname); - while (n && keyname[n-1] == ' ') - { - keyname[n-1] = 0; - n--; + while (!keyname.empty() && keyname.back() == ' ') { + keyname.pop_back(); } // parse value // HACK: we allow truncation when reading the wad field, // otherwise maps using lots of wads with absolute paths // could cause a parse error - data = COM_ParseEx (data, !strcmp (keyname, "wad") ? CPE_ALLOWTRUNC : CPE_NOTRUNC); - if (!data) + token = common::parse_token(ss); + if (ss.eof()) { Host_Error ("ED_ParseEntity: EOF without closing brace"); + } - if (com_token[0] == '}') + if (token->front() == '}') { Host_Error ("ED_ParseEntity: closing brace without data"); + } init = true; // keynames with a leading underscore are used for utility comments, // and are immediately discarded by quake - if (keyname[0] == '_') + if (keyname[0] == '_') { continue; + } //johnfitz -- hack to support .alpha even when progs.dat doesn't know about it - if (!strcmp(keyname, "alpha")) - ent->alpha = ENTALPHA_ENCODE(Q_atof(com_token)); + if (keyname == "alpha") + ent->alpha = ENTALPHA_ENCODE(Q_atof(token->c_str())); //johnfitz - key = ED_FindField (keyname); + key = ED_FindField (keyname.c_str()); if (!key) { //johnfitz -- HACK -- suppress error becuase fog/sky/alpha fields might not be mentioned in defs.qc - if (strncmp(keyname, "sky", 3) && strcmp(keyname, "fog") && strcmp(keyname, "alpha")) - Con_DPrintf ("\"%s\" is not a field\n", keyname); //johnfitz -- was Con_Printf + if (keyname != "sky" && keyname != "fog" && keyname != "alpha") + Con_DPrintf ("\"%s\" is not a field\n", keyname.c_str()); //johnfitz -- was Con_Printf continue; } if (anglehack) { - char temp[32]; - strcpy (temp, com_token); - sprintf (com_token, "0 %s 0", temp); + token = std::format("0 {} 0", *token); } - if (!ED_ParseEpair ((void *)&ent->v, key, com_token)) + if (!ED_ParseEpair ((void *)&ent->v, key, token->c_str())) Host_Error ("ED_ParseEdict: parse error"); } if (!init) ent->free = true; - - return data; } @@ -999,21 +1003,24 @@ void ED_LoadFromFile (const char *data) pr_global_struct->time = sv.time; + std::istringstream ss{data}; + + // parse ents - while (1) + while (true) { // parse the opening brace - data = COM_Parse (data); - if (!data) + auto token = common::parse_token(ss); + if (ss.eof()) break; - if (com_token[0] != '{') - Host_Error ("ED_LoadFromFile: found %s when expecting {",com_token); + if (token->front() != '{') + Host_Error ("ED_LoadFromFile: found %s when expecting {", token->c_str()); if (!ent) ent = EDICT_NUM(0); else ent = ED_Alloc (); - data = ED_ParseEdict (data, ent); + ED_ParseEdict (ss, ent); // remove things from different skill levels or deathmatch if (deathmatch.value) @@ -1270,21 +1277,21 @@ PR_Init */ void PR_Init (void) { - Cmd_AddCommand ("edict", ED_PrintEdict_f); - Cmd_AddCommand ("edicts", ED_PrintEdicts); - Cmd_AddCommand ("edictcount", ED_Count); - Cmd_AddCommand ("profile", PR_Profile_f); - Cvar_RegisterVariable (&nomonsters); - Cvar_RegisterVariable (&gamecfg); - Cvar_RegisterVariable (&scratch1); - Cvar_RegisterVariable (&scratch2); - Cvar_RegisterVariable (&scratch3); - Cvar_RegisterVariable (&scratch4); - Cvar_RegisterVariable (&savedgamecfg); - Cvar_RegisterVariable (&saved1); - Cvar_RegisterVariable (&saved2); - Cvar_RegisterVariable (&saved3); - Cvar_RegisterVariable (&saved4); + command::add("edict", ED_PrintEdict_f); + command::add("edicts", ED_PrintEdicts); + command::add("edictcount", ED_Count); + command::add("profile", PR_Profile_f); + nomonsters.inscribe(); + gamecfg.inscribe(); + scratch1.inscribe(); + scratch2.inscribe(); + scratch3.inscribe(); + scratch4.inscribe(); + savedgamecfg.inscribe(); + saved1.inscribe(); + saved2.inscribe(); + saved3.inscribe(); + saved4.inscribe(); } diff --git a/Quake/progs.hpp b/Quake/progs.hpp index 30a78c5..b8f1c30 100644 --- a/Quake/progs.hpp +++ b/Quake/progs.hpp @@ -87,10 +87,11 @@ void ED_Free (edict_t *ed); void ED_Print (edict_t *ed); void ED_Write (FILE *f, edict_t *ed); -const char *ED_ParseEdict (const char *data, edict_t *ent); + +void ED_ParseEdict(std::istringstream &ss, edict_t *ent); void ED_WriteGlobals (FILE *f); -const char *ED_ParseGlobals (const char *data); +void ED_ParseGlobals (std::istringstream &ss); void ED_LoadFromFile (const char *data); diff --git a/Quake/q_sound.hpp b/Quake/q_sound.hpp index ded7b5d..25459ba 100644 --- a/Quake/q_sound.hpp +++ b/Quake/q_sound.hpp @@ -168,16 +168,16 @@ extern vec3_t listener_forward; extern vec3_t listener_right; extern vec3_t listener_up; -extern cvar_t sndspeed; -extern cvar_t snd_mixspeed; -extern cvar_t snd_filterquality; -extern cvar_t sfxvolume; -extern cvar_t loadas8bit; +extern convar sndspeed; +extern convar snd_mixspeed; +extern convar snd_filterquality; +extern convar sfxvolume; +extern convar loadas8bit; #define MAX_RAW_SAMPLES 8192 extern portable_samplepair_t s_rawsamples[MAX_RAW_SAMPLES]; -extern cvar_t bgmvolume; +extern convar bgmvolume; void S_LocalSound (const char *name); sfxcache_t *S_LoadSound (sfx_t *s); diff --git a/Quake/q_stdinc.hpp b/Quake/q_stdinc.hpp index b0b141b..c3d4690 100644 --- a/Quake/q_stdinc.hpp +++ b/Quake/q_stdinc.hpp @@ -75,15 +75,15 @@ #endif #endif -#define Q_MAXCHAR ((char)0x7f) -#define Q_MAXSHORT ((short)0x7fff) -#define Q_MAXINT ((int)0x7fffffff) -#define Q_MAXLONG ((int)0x7fffffff) +#define q_maxCHAR ((char)0x7f) +#define q_maxSHORT ((short)0x7fff) +#define q_maxINT ((int)0x7fffffff) +#define q_maxLONG ((int)0x7fffffff) -#define Q_MINCHAR ((char)0x80) -#define Q_MINSHORT ((short)0x8000) -#define Q_MININT ((int)0x80000000) -#define Q_MINLONG ((int)0x80000000) +#define q_minCHAR ((char)0x80) +#define q_minSHORT ((short)0x8000) +#define q_minINT ((int)0x80000000) +#define q_minLONG ((int)0x80000000) #ifndef COMPILE_TIME_ASSERT #if defined(__cplusplus) diff --git a/Quake/quakedef.hpp b/Quake/quakedef.hpp index bc773c4..7c91bcf 100644 --- a/Quake/quakedef.hpp +++ b/Quake/quakedef.hpp @@ -211,7 +211,7 @@ typedef struct #include "sys.hpp" #include "zone.hpp" #include "mathlib.hpp" -#include "cvar.hpp" +#include "convar.hpp" #include "protocol.hpp" #include "net.hpp" @@ -275,11 +275,11 @@ extern qboolean noclip_anglehack; // extern quakeparms_t *host_parms; -extern cvar_t sys_ticrate; -extern cvar_t sys_throttle; -extern cvar_t sys_nostdout; -extern cvar_t developer; -extern cvar_t max_edicts; //johnfitz +extern convar sys_ticrate; +extern convar sys_throttle; +extern convar sys_nostdout; +extern convar developer; +extern convar max_edicts; //johnfitz extern qboolean host_initialized; // true if into command execution extern double host_frametime; @@ -303,7 +303,7 @@ void Host_ServerFrame (void); void Host_InitCommands (void); void Host_Init (void); void Host_Shutdown(void); -void Host_Callback_Notify (cvar_t *var); /* callback function for CVAR_NOTIFY */ +void Host_Callback_Notify (convar *var); /* callback function for CVAR_NOTIFY */ FUNC_NORETURN void Host_Error (const char *error, ...) FUNC_PRINTF(1,2); FUNC_NORETURN void Host_EndGame (const char *message, ...) FUNC_PRINTF(1,2); #ifdef __WATCOMC__ diff --git a/Quake/r_alias.cpp b/Quake/r_alias.cpp index 334884f..5e213e2 100644 --- a/Quake/r_alias.cpp +++ b/Quake/r_alias.cpp @@ -24,8 +24,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.hpp" -extern cvar_t r_drawflat, gl_overbright_models, gl_fullbrights, r_lerpmodels, r_lerpmove; //johnfitz -extern cvar_t scr_fov, cl_gun_fovscale; +extern convar r_drawflat, gl_overbright_models, gl_fullbrights, r_lerpmodels, r_lerpmove; //johnfitz +extern convar scr_fov, cl_gun_fovscale; //up to 16 color translated skins gltexture_t *playertextures[MAX_SCOREBOARD]; //johnfitz -- changed to an array of pointers diff --git a/Quake/r_brush.cpp b/Quake/r_brush.cpp index aafb4cc..1424040 100644 --- a/Quake/r_brush.cpp +++ b/Quake/r_brush.cpp @@ -24,8 +24,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.hpp" -extern cvar_t gl_fullbrights, r_drawflat, gl_overbright, r_oldwater; //johnfitz -extern cvar_t gl_zfix; // QuakeSpasm z-fighting fix +extern convar gl_fullbrights, r_drawflat, gl_overbright, r_oldwater; //johnfitz +extern convar gl_zfix; // QuakeSpasm z-fighting fix int gl_lightmap_format; int lightmap_bytes; diff --git a/Quake/r_part.cpp b/Quake/r_part.cpp index b26e626..6360f92 100644 --- a/Quake/r_part.cpp +++ b/Quake/r_part.cpp @@ -39,8 +39,8 @@ static int r_numparticles; static gltexture_t *particletexture, *particletexture1, *particletexture2, *particletexture3; //johnfitz static float texturescalefactor; //johnfitz -- compensate for apparent size of different particle textures -cvar_t r_particles = {"r_particles","1", CVAR_ARCHIVE}; //johnfitz -cvar_t r_quadparticles = {"r_quadparticles","1", CVAR_ARCHIVE}; //johnfitz +convar r_particles{"r_particles","1", {.archive = true}}; //johnfitz +convar r_quadparticles{"r_quadparticles","1", {.archive = true}}; //johnfitz /* =============== @@ -57,7 +57,7 @@ int R_ParticleTextureLookup (int x, int y, int sharpness) r = x * x + y * y; r = r > 255 ? 255 : r; a = sharpness * (255 - r); - a = q_min(a,255); + a = std::min(a,255); return a; } @@ -120,7 +120,7 @@ void R_InitParticleTextures (void) R_SetParticleTexture_f -- johnfitz =============== */ -static void R_SetParticleTexture_f (cvar_t *var) +static void R_SetParticleTexture_f (convar *var) { switch ((int)(r_particles.value)) { @@ -166,9 +166,9 @@ void R_InitParticles (void) particles = (particle_t *) Hunk_AllocName (r_numparticles * sizeof(particle_t), "particles"); - Cvar_RegisterVariable (&r_particles); //johnfitz - Cvar_SetCallback (&r_particles, R_SetParticleTexture_f); - Cvar_RegisterVariable (&r_quadparticles); //johnfitz + r_particles.inscribe(); //johnfitz + r_particles.set_callback(R_SetParticleTexture_f); + r_quadparticles.inscribe(); //johnfitz R_InitParticleTextures (); //johnfitz } @@ -722,7 +722,7 @@ void CL_RunParticles (void) particle_t *p, *kill; int i; float time1, time2, time3, dvel, frametime, grav; - extern cvar_t sv_gravity; + extern convar sv_gravity; frametime = cl.time - cl.oldtime; time3 = frametime * 15; @@ -829,7 +829,7 @@ void R_DrawParticles (void) float scale; vec3_t up, right, p_up, p_right, p_upright; //johnfitz -- p_ vectors GLubyte color[4], *c; //johnfitz -- particle transparency - extern cvar_t r_particles; //johnfitz + extern convar r_particles; //johnfitz //float alpha; //johnfitz -- particle transparency if (!r_particles.value) @@ -949,7 +949,7 @@ void R_DrawParticles_ShowTris (void) particle_t *p; float scale; vec3_t up, right, p_up, p_right, p_upright; - extern cvar_t r_particles; + extern convar r_particles; if (!r_particles.value) return; diff --git a/Quake/r_world.cpp b/Quake/r_world.cpp index 5db3bd2..997905a 100644 --- a/Quake/r_world.cpp +++ b/Quake/r_world.cpp @@ -24,7 +24,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.hpp" -extern cvar_t gl_fullbrights, r_drawflat, gl_overbright, r_oldwater, r_oldskyleaf, r_showtris; //johnfitz +extern convar gl_fullbrights, r_drawflat, gl_overbright, r_oldwater, r_oldskyleaf, r_showtris; //johnfitz byte *SV_FatPVS (vec3_t org, qmodel_t *worldmodel); diff --git a/Quake/sbar.cpp b/Quake/sbar.cpp index 56805ff..a54bff6 100644 --- a/Quake/sbar.cpp +++ b/Quake/sbar.cpp @@ -253,8 +253,8 @@ Sbar_Init -- johnfitz -- rewritten */ void Sbar_Init (void) { - Cmd_AddCommand ("+showscores", Sbar_ShowScores); - Cmd_AddCommand ("-showscores", Sbar_DontShowScores); + command::add ("+showscores", Sbar_ShowScores); + command::add ("-showscores", Sbar_DontShowScores); Sbar_LoadPics (); } @@ -388,7 +388,7 @@ void Sbar_DrawNum (int x, int y, int num, int digits, int color) char *ptr; int l, frame; - num = q_min(999,num); //johnfitz -- cap high values rather than truncating number + num = std::min(999,num); //johnfitz -- cap high values rather than truncating number l = Sbar_itoa (num, str); ptr = str; @@ -640,7 +640,7 @@ void Sbar_DrawInventory (void) for (i = 0; i < 4; i++) { val = cl.stats[STAT_SHELLS+i]; - val = (val < 0)? 0 : q_min(999,val);//johnfitz -- cap displayed value to 999 + val = (val < 0)? 0 : std::min(999,val);//johnfitz -- cap displayed value to 999 sprintf (num, "%3i", val); if (num[0] != ' ') Sbar_DrawCharacter ( (6*i+1)*8 + 2, -24, 18 + num[0] - '0'); @@ -754,7 +754,7 @@ void Sbar_DrawFrags (void) Sbar_SortFrags (); // draw the text - numscores = q_min(scoreboardlines, 4); + numscores = std::min(scoreboardlines, 4); for (i = 0, x = 184; iwidth + 24; - total = q_min (320, total); + total = std::min (320, total); Draw_Pic (160 - total / 2, 56, pic); pic = Draw_CachePic ("gfx/complete.lmp"); diff --git a/Quake/screen.hpp b/Quake/screen.hpp index 73c888c..7196909 100644 --- a/Quake/screen.hpp +++ b/Quake/screen.hpp @@ -50,9 +50,9 @@ extern int clearnotify; // set to 0 whenever notify text is drawn extern qboolean scr_disabled_for_loading; extern qboolean scr_skipupdate; -extern cvar_t scr_viewsize; +extern convar scr_viewsize; -extern cvar_t scr_sbaralpha; //johnfitz +extern convar scr_sbaralpha; //johnfitz void SCR_UpdateWholeScreen (void); @@ -70,12 +70,12 @@ typedef enum { CANVAS_TOPRIGHT, CANVAS_INVALID = -1 } canvastype; -extern cvar_t scr_menuscale; -extern cvar_t scr_sbarscale; -extern cvar_t scr_conwidth; -extern cvar_t scr_conscale; -extern cvar_t scr_scale; -extern cvar_t scr_crosshairscale; +extern convar scr_menuscale; +extern convar scr_sbarscale; +extern convar scr_conwidth; +extern convar scr_conscale; +extern convar scr_scale; +extern convar scr_crosshairscale; //johnfitz extern int scr_tileclear_updates; //johnfitz diff --git a/Quake/server.hpp b/Quake/server.hpp index 92e13b0..7c63a33 100644 --- a/Quake/server.hpp +++ b/Quake/server.hpp @@ -189,12 +189,12 @@ typedef struct client_s //============================================================================ -extern cvar_t teamplay; -extern cvar_t skill; -extern cvar_t deathmatch; -extern cvar_t coop; -extern cvar_t fraglimit; -extern cvar_t timelimit; +extern convar teamplay; +extern convar skill; +extern convar deathmatch; +extern convar coop; +extern convar fraglimit; +extern convar timelimit; extern server_static_t svs; // persistant server info extern server_t sv; // local server diff --git a/Quake/snd_dma.cpp b/Quake/snd_dma.cpp index 3c8b097..26565f4 100644 --- a/Quake/snd_dma.cpp +++ b/Quake/snd_dma.cpp @@ -28,56 +28,61 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "snd_codec.hpp" #include "bgmusic.hpp" -static void S_Play (void); -static void S_PlayVol (void); -static void S_SoundList (void); -static void S_Update_ (void); -void S_StopAllSounds (qboolean clear); -static void S_StopAllSoundsC (void); +static void S_Play(void); + +static void S_PlayVol(void); + +static void S_SoundList(void); + +static void S_Update_(void); + +void S_StopAllSounds(qboolean clear); + +static void S_StopAllSoundsC(void); // ======================================================================= // Internal sound data & structures // ======================================================================= -channel_t snd_channels[MAX_CHANNELS]; -int total_channels; +channel_t snd_channels[MAX_CHANNELS]; +int total_channels; -static int snd_blocked = 0; -static qboolean snd_initialized = false; +static int snd_blocked = 0; +static qboolean snd_initialized = false; -static dma_t sn; -volatile dma_t *shm = NULL; +static dma_t sn; +volatile dma_t *shm = NULL; -vec3_t listener_origin; -vec3_t listener_forward; -vec3_t listener_right; -vec3_t listener_up; +vec3_t listener_origin; +vec3_t listener_forward; +vec3_t listener_right; +vec3_t listener_up; #define sound_nominal_clip_dist 1000.0 -int soundtime; // sample PAIRS -int paintedtime; // sample PAIRS +int soundtime; // sample PAIRS +int paintedtime; // sample PAIRS -int s_rawend; -portable_samplepair_t s_rawsamples[MAX_RAW_SAMPLES]; +int s_rawend; +portable_samplepair_t s_rawsamples[MAX_RAW_SAMPLES]; #define MAX_SFX 1024 -static sfx_t *known_sfx = NULL; // hunk allocated [MAX_SFX] -static int num_sfx; +static sfx_t *known_sfx = NULL; // hunk allocated [MAX_SFX] +static int num_sfx; -static sfx_t *ambient_sfx[NUM_AMBIENTS]; +static sfx_t *ambient_sfx[NUM_AMBIENTS]; -static qboolean sound_started = false; +static qboolean sound_started = false; -cvar_t bgmvolume = {"bgmvolume", "1", CVAR_ARCHIVE}; -cvar_t sfxvolume = {"volume", "0.7", CVAR_ARCHIVE}; +convar bgmvolume = {"bgmvolume", "1", {.archive = true}}; +convar sfxvolume = {"volume", "0.7", {.archive = true}}; -cvar_t precache = {"precache", "1", CVAR_NONE}; -cvar_t loadas8bit = {"loadas8bit", "0", CVAR_NONE}; +convar precache = {"precache", "1"}; +convar loadas8bit = {"loadas8bit", "0"}; -cvar_t sndspeed = {"sndspeed", "11025", CVAR_NONE}; -cvar_t snd_mixspeed = {"snd_mixspeed", "44100", CVAR_NONE}; +convar sndspeed = {"sndspeed", "11025"}; +convar snd_mixspeed = {"snd_mixspeed", "44100"}; #if defined(_WIN32) #define SND_FILTERQUALITY_DEFAULT "5" @@ -85,47 +90,41 @@ cvar_t snd_mixspeed = {"snd_mixspeed", "44100", CVAR_NONE}; #define SND_FILTERQUALITY_DEFAULT "1" #endif -cvar_t snd_filterquality = {"snd_filterquality", SND_FILTERQUALITY_DEFAULT, - CVAR_NONE}; +convar snd_filterquality = {"snd_filterquality", SND_FILTERQUALITY_DEFAULT}; -static cvar_t nosound = {"nosound", "0", CVAR_NONE}; -static cvar_t ambient_level = {"ambient_level", "0.3", CVAR_NONE}; -static cvar_t ambient_fade = {"ambient_fade", "100", CVAR_NONE}; -static cvar_t snd_noextraupdate = {"snd_noextraupdate", "0", CVAR_NONE}; -static cvar_t snd_show = {"snd_show", "0", CVAR_NONE}; -static cvar_t _snd_mixahead = {"_snd_mixahead", "0.1", CVAR_ARCHIVE}; +static convar nosound = {"nosound", "0"}; +static convar ambient_level = {"ambient_level", "0.3"}; +static convar ambient_fade = {"ambient_fade", "100"}; +static convar snd_noextraupdate = {"snd_noextraupdate", "0"}; +static convar snd_show = {"snd_show", "0"}; +static convar _snd_mixahead = {"_snd_mixahead", "0.1", {.archive = true}}; -static void S_SoundInfo_f (void) -{ - if (!sound_started || !shm) - { - Con_Printf ("sound system not started\n"); - return; - } +static void S_SoundInfo_f(void) { + if (!sound_started || !shm) { + Con_Printf("sound system not started\n"); + return; + } - Con_Printf("%d bit, %s, %d Hz\n", shm->samplebits, - (shm->channels == 2) ? "stereo" : "mono", shm->speed); - Con_Printf("%5d samples\n", shm->samples); - Con_Printf("%5d samplepos\n", shm->samplepos); - Con_Printf("%5d submission_chunk\n", shm->submission_chunk); - Con_Printf("%5d total_channels\n", total_channels); - Con_Printf("%p dma buffer\n", shm->buffer); + Con_Printf("%d bit, %s, %d Hz\n", shm->samplebits, + (shm->channels == 2) ? "stereo" : "mono", shm->speed); + Con_Printf("%5d samples\n", shm->samples); + Con_Printf("%5d samplepos\n", shm->samplepos); + Con_Printf("%5d submission_chunk\n", shm->submission_chunk); + Con_Printf("%5d total_channels\n", total_channels); + Con_Printf("%p dma buffer\n", shm->buffer); } -static void SND_Callback_sfxvolume (cvar_t *var) -{ - SND_InitScaletable (); +static void SND_Callback_sfxvolume(convar *var) { + SND_InitScaletable(); } -static void SND_Callback_snd_filterquality (cvar_t *var) -{ - if (snd_filterquality.value < 1 || snd_filterquality.value > 5) - { - Con_Printf ("snd_filterquality must be between 1 and 5\n"); - Cvar_SetQuick (&snd_filterquality, SND_FILTERQUALITY_DEFAULT); - } +static void SND_Callback_snd_filterquality(convar *var) { + if (snd_filterquality.value < 1 || snd_filterquality.value > 5) { + Con_Printf("snd_filterquality must be between 1 and 5\n"); + snd_filterquality.set(SND_FILTERQUALITY_DEFAULT); + } } /* @@ -133,22 +132,18 @@ static void SND_Callback_snd_filterquality (cvar_t *var) S_Startup ================ */ -void S_Startup (void) -{ - if (!snd_initialized) - return; +void S_Startup(void) { + if (!snd_initialized) + return; - sound_started = SNDDMA_Init(&sn); + sound_started = SNDDMA_Init(&sn); - if (!sound_started) - { - Con_Printf("Failed initializing sound\n"); - } - else - { - Con_Printf("Audio: %d bit, %s, %d Hz\n", shm->samplebits, - (shm->channels == 2) ? "stereo" : "mono", shm->speed); - } + if (!sound_started) { + Con_Printf("Failed initializing sound\n"); + } else { + Con_Printf("Audio: %d bit, %s, %d Hz\n", shm->samplebits, + (shm->channels == 2) ? "stereo" : "mono", shm->speed); + } } @@ -157,101 +152,95 @@ void S_Startup (void) S_Init ================ */ -void S_Init (void) -{ - int i; +void S_Init(void) { + int i; - if (snd_initialized) - { - Con_Printf("Sound is already initialized\n"); - return; - } + if (snd_initialized) { + Con_Printf("Sound is already initialized\n"); + return; + } - Cvar_RegisterVariable(&nosound); - Cvar_RegisterVariable(&sfxvolume); - Cvar_RegisterVariable(&precache); - Cvar_RegisterVariable(&loadas8bit); - Cvar_RegisterVariable(&bgmvolume); - Cvar_RegisterVariable(&ambient_level); - Cvar_RegisterVariable(&ambient_fade); - Cvar_RegisterVariable(&snd_noextraupdate); - Cvar_RegisterVariable(&snd_show); - Cvar_RegisterVariable(&_snd_mixahead); - Cvar_RegisterVariable(&sndspeed); - Cvar_RegisterVariable(&snd_mixspeed); - Cvar_RegisterVariable(&snd_filterquality); - - if (safemode || COM_CheckParm("-nosound")) - return; + nosound.inscribe(); + sfxvolume.inscribe(); + precache.inscribe(); + loadas8bit.inscribe(); + bgmvolume.inscribe(); + ambient_level.inscribe(); + ambient_fade.inscribe(); + snd_noextraupdate.inscribe(); + snd_show.inscribe(); + _snd_mixahead.inscribe(); + sndspeed.inscribe(); + snd_mixspeed.inscribe(); + snd_filterquality.inscribe(); - Con_Printf("\nSound Initialization\n"); + if (safemode || COM_CheckParm("-nosound")) + return; - Cmd_AddCommand("play", S_Play); - Cmd_AddCommand("playvol", S_PlayVol); - Cmd_AddCommand("stopsound", S_StopAllSoundsC); - Cmd_AddCommand("soundlist", S_SoundList); - Cmd_AddCommand("soundinfo", S_SoundInfo_f); + Con_Printf("\nSound Initialization\n"); - i = COM_CheckParm("-sndspeed"); - if (i && i < com_argc-1) - { - Cvar_SetQuick (&sndspeed, com_argv[i + 1]); - } + command::add("play", S_Play); + command::add("playvol", S_PlayVol); + command::add("stopsound", S_StopAllSoundsC); + command::add("soundlist", S_SoundList); + command::add("soundinfo", S_SoundInfo_f); - i = COM_CheckParm("-mixspeed"); - if (i && i < com_argc-1) - { - Cvar_SetQuick (&snd_mixspeed, com_argv[i + 1]); - } + i = COM_CheckParm("-sndspeed"); + if (i && i < com_argc - 1) { + sndspeed.set(com_argv[i + 1]); + } - if (host_parms->memsize < 0x800000) - { - Cvar_SetQuick (&loadas8bit, "1"); - Con_Printf ("loading all sounds as 8bit\n"); - } + i = COM_CheckParm("-mixspeed"); + if (i && i < com_argc - 1) { + snd_mixspeed.set(com_argv[i + 1]); + } - Cvar_SetCallback(&sfxvolume, SND_Callback_sfxvolume); - Cvar_SetCallback(&snd_filterquality, &SND_Callback_snd_filterquality); + if (host_parms->memsize < 0x800000) { + loadas8bit.set("1"); + Con_Printf("loading all sounds as 8bit\n"); + } - SND_InitScaletable (); + sfxvolume.set_callback(SND_Callback_sfxvolume); + snd_filterquality.set_callback(&SND_Callback_snd_filterquality); - known_sfx = (sfx_t *) Hunk_AllocName (MAX_SFX*sizeof(sfx_t), "sfx_t"); - num_sfx = 0; + SND_InitScaletable(); - snd_initialized = true; + known_sfx = (sfx_t *) Hunk_AllocName(MAX_SFX * sizeof(sfx_t), "sfx_t"); + num_sfx = 0; - S_Startup (); - if (sound_started == 0) - return; + snd_initialized = true; -// provides a tick sound until washed clean -// if (shm->buffer) -// shm->buffer[4] = shm->buffer[5] = 0x7f; // force a pop for debugging + S_Startup(); + if (sound_started == 0) + return; - ambient_sfx[AMBIENT_WATER] = S_PrecacheSound ("ambience/water1.wav"); - ambient_sfx[AMBIENT_SKY] = S_PrecacheSound ("ambience/wind2.wav"); + // provides a tick sound until washed clean + // if (shm->buffer) + // shm->buffer[4] = shm->buffer[5] = 0x7f; // force a pop for debugging - S_CodecInit (); + ambient_sfx[AMBIENT_WATER] = S_PrecacheSound("ambience/water1.wav"); + ambient_sfx[AMBIENT_SKY] = S_PrecacheSound("ambience/wind2.wav"); - S_StopAllSounds (true); + S_CodecInit(); + + S_StopAllSounds(true); } // ======================================================================= // Shutdown sound engine // ======================================================================= -void S_Shutdown (void) -{ - if (!sound_started) - return; +void S_Shutdown(void) { + if (!sound_started) + return; - sound_started = 0; - snd_blocked = 0; + sound_started = 0; + snd_blocked = 0; - S_CodecShutdown(); + S_CodecShutdown(); - SNDDMA_Shutdown(); - shm = NULL; + SNDDMA_Shutdown(); + shm = NULL; } @@ -265,35 +254,32 @@ S_FindName ================== */ -static sfx_t *S_FindName (const char *name) -{ - int i; - sfx_t *sfx; +static sfx_t *S_FindName(const char *name) { + int i; + sfx_t *sfx; - if (!name) - Sys_Error ("S_FindName: NULL"); + if (!name) + Sys_Error("S_FindName: NULL"); - if (strlen(name) >= MAX_QPATH) - Sys_Error ("Sound name too long: %s", name); + if (strlen(name) >= MAX_QPATH) + Sys_Error("Sound name too long: %s", name); -// see if already loaded - for (i = 0; i < num_sfx; i++) - { - if (!strcmp(known_sfx[i].name, name)) - { - return &known_sfx[i]; - } - } + // see if already loaded + for (i = 0; i < num_sfx; i++) { + if (!strcmp(known_sfx[i].name, name)) { + return &known_sfx[i]; + } + } - if (num_sfx == MAX_SFX) - Sys_Error ("S_FindName: out of sfx_t"); + if (num_sfx == MAX_SFX) + Sys_Error("S_FindName: out of sfx_t"); - sfx = &known_sfx[i]; - q_strlcpy (sfx->name, name, sizeof(sfx->name)); + sfx = &known_sfx[i]; + q_strlcpy(sfx->name, name, sizeof(sfx->name)); - num_sfx++; + num_sfx++; - return sfx; + return sfx; } @@ -303,15 +289,14 @@ S_TouchSound ================== */ -void S_TouchSound (const char *name) -{ - sfx_t *sfx; +void S_TouchSound(const char *name) { + sfx_t *sfx; - if (!sound_started) - return; + if (!sound_started) + return; - sfx = S_FindName (name); - Cache_Check (&sfx->cache); + sfx = S_FindName(name); + Cache_Check(&sfx->cache); } /* @@ -320,20 +305,19 @@ S_PrecacheSound ================== */ -sfx_t *S_PrecacheSound (const char *name) -{ - sfx_t *sfx; +sfx_t *S_PrecacheSound(const char *name) { + sfx_t *sfx; - if (!sound_started || nosound.value) - return NULL; + if (!sound_started || nosound.value) + return NULL; - sfx = S_FindName (name); + sfx = S_FindName(name); -// cache it in - if (precache.value) - S_LoadSound (sfx); + // cache it in + if (precache.value) + S_LoadSound(sfx); - return sfx; + return sfx; } @@ -346,43 +330,40 @@ SND_PickChannel picks a channel based on priorities, empty slots, number of channels ================= */ -channel_t *SND_PickChannel (int entnum, int entchannel) -{ - int ch_idx; - int first_to_die; - int life_left; +channel_t *SND_PickChannel(int entnum, int entchannel) { + int ch_idx; + int first_to_die; + int life_left; -// Check for replacement sound, or find the best one to replace - first_to_die = -1; - life_left = 0x7fffffff; - for (ch_idx = NUM_AMBIENTS; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS; ch_idx++) - { - if (entchannel != 0 // channel 0 never overrides - && snd_channels[ch_idx].entnum == entnum - && (snd_channels[ch_idx].entchannel == entchannel || entchannel == -1) ) - { // always override sound from same entity - first_to_die = ch_idx; - break; - } + // Check for replacement sound, or find the best one to replace + first_to_die = -1; + life_left = 0x7fffffff; + for (ch_idx = NUM_AMBIENTS; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS; ch_idx++) { + if (entchannel != 0 // channel 0 never overrides + && snd_channels[ch_idx].entnum == entnum + && (snd_channels[ch_idx].entchannel == entchannel || entchannel == -1)) { + // always override sound from same entity + first_to_die = ch_idx; + break; + } - // don't let monster sounds override player sounds - if (snd_channels[ch_idx].entnum == cl.viewentity && entnum != cl.viewentity && snd_channels[ch_idx].sfx) - continue; + // don't let monster sounds override player sounds + if (snd_channels[ch_idx].entnum == cl.viewentity && entnum != cl.viewentity && snd_channels[ch_idx].sfx) + continue; - if (snd_channels[ch_idx].end - paintedtime < life_left) - { - life_left = snd_channels[ch_idx].end - paintedtime; - first_to_die = ch_idx; - } - } + if (snd_channels[ch_idx].end - paintedtime < life_left) { + life_left = snd_channels[ch_idx].end - paintedtime; + first_to_die = ch_idx; + } + } - if (first_to_die == -1) - return NULL; + if (first_to_die == -1) + return NULL; - if (snd_channels[first_to_die].sfx) - snd_channels[first_to_die].sfx = NULL; + if (snd_channels[first_to_die].sfx) + snd_channels[first_to_die].sfx = NULL; - return &snd_channels[first_to_die]; + return &snd_channels[first_to_die]; } /* @@ -392,47 +373,42 @@ SND_Spatialize spatializes a channel ================= */ -void SND_Spatialize (channel_t *ch) -{ - vec_t dot; - vec_t dist; - vec_t lscale, rscale, scale; - vec3_t source_vec; +void SND_Spatialize(channel_t *ch) { + vec_t dot; + vec_t dist; + vec_t lscale, rscale, scale; + vec3_t source_vec; -// anything coming from the view entity will always be full volume - if (ch->entnum == cl.viewentity) - { - ch->leftvol = ch->master_vol; - ch->rightvol = ch->master_vol; - return; - } + // anything coming from the view entity will always be full volume + if (ch->entnum == cl.viewentity) { + ch->leftvol = ch->master_vol; + ch->rightvol = ch->master_vol; + return; + } -// calculate stereo seperation and distance attenuation - VectorSubtract(ch->origin, listener_origin, source_vec); - dist = VectorNormalize(source_vec) * ch->dist_mult; - dot = DotProduct(listener_right, source_vec); + // calculate stereo seperation and distance attenuation + VectorSubtract(ch->origin, listener_origin, source_vec); + dist = VectorNormalize(source_vec) * ch->dist_mult; + dot = DotProduct(listener_right, source_vec); - if (shm->channels == 1) - { - rscale = 1.0; - lscale = 1.0; - } - else - { - rscale = 1.0 + dot; - lscale = 1.0 - dot; - } + if (shm->channels == 1) { + rscale = 1.0; + lscale = 1.0; + } else { + rscale = 1.0 + dot; + lscale = 1.0 - dot; + } -// add in distance effect - scale = (1.0 - dist) * rscale; - ch->rightvol = (int) (ch->master_vol * scale); - if (ch->rightvol < 0) - ch->rightvol = 0; + // add in distance effect + scale = (1.0 - dist) * rscale; + ch->rightvol = (int) (ch->master_vol * scale); + if (ch->rightvol < 0) + ch->rightvol = 0; - scale = (1.0 - dist) * lscale; - ch->leftvol = (int) (ch->master_vol * scale); - if (ch->leftvol < 0) - ch->leftvol = 0; + scale = (1.0 - dist) * lscale; + ch->leftvol = (int) (ch->master_vol * scale); + if (ch->leftvol < 0) + ch->leftvol = 0; } @@ -440,141 +416,130 @@ void SND_Spatialize (channel_t *ch) // Start a sound effect // ======================================================================= -void S_StartSound (int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation) -{ - channel_t *target_chan, *check; - sfxcache_t *sc; - int ch_idx; - int skip; +void S_StartSound(int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation) { + channel_t *target_chan, *check; + sfxcache_t *sc; + int ch_idx; + int skip; - if (!sound_started) - return; + if (!sound_started) + return; - if (!sfx) - return; + if (!sfx) + return; - if (nosound.value) - return; + if (nosound.value) + return; -// pick a channel to play on - target_chan = SND_PickChannel(entnum, entchannel); - if (!target_chan) - return; + // pick a channel to play on + target_chan = SND_PickChannel(entnum, entchannel); + if (!target_chan) + return; -// spatialize - memset (target_chan, 0, sizeof(*target_chan)); - VectorCopy(origin, target_chan->origin); - target_chan->dist_mult = attenuation / sound_nominal_clip_dist; - target_chan->master_vol = (int) (fvol * 255); - target_chan->entnum = entnum; - target_chan->entchannel = entchannel; - SND_Spatialize(target_chan); + // spatialize + memset(target_chan, 0, sizeof(*target_chan)); + VectorCopy(origin, target_chan->origin); + target_chan->dist_mult = attenuation / sound_nominal_clip_dist; + target_chan->master_vol = (int) (fvol * 255); + target_chan->entnum = entnum; + target_chan->entchannel = entchannel; + SND_Spatialize(target_chan); - if (!target_chan->leftvol && !target_chan->rightvol) - return; // not audible at all + if (!target_chan->leftvol && !target_chan->rightvol) + return; // not audible at all -// new channel - sc = S_LoadSound (sfx); - if (!sc) - { - target_chan->sfx = NULL; - return; // couldn't load the sound's data - } + // new channel + sc = S_LoadSound(sfx); + if (!sc) { + target_chan->sfx = NULL; + return; // couldn't load the sound's data + } - target_chan->sfx = sfx; - target_chan->pos = 0.0; - target_chan->end = paintedtime + sc->length; + target_chan->sfx = sfx; + target_chan->pos = 0.0; + target_chan->end = paintedtime + sc->length; -// if an identical sound has also been started this frame, offset the pos -// a bit to keep it from just making the first one louder - check = &snd_channels[NUM_AMBIENTS]; - for (ch_idx = NUM_AMBIENTS; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS; ch_idx++, check++) - { - if (check == target_chan) - continue; - if (check->sfx == sfx && !check->pos) - { - /* - skip = rand () % (int)(0.1 * shm->speed); - if (skip >= target_chan->end) - skip = target_chan->end - 1; - */ - /* LordHavoc: fixed skip calculations */ - skip = 0.1 * shm->speed; /* 0.1 * sc->speed */ - if (skip > sc->length) - skip = sc->length; - if (skip > 0) - skip = rand() % skip; - target_chan->pos += skip; - target_chan->end -= skip; - break; - } - } + // if an identical sound has also been started this frame, offset the pos + // a bit to keep it from just making the first one louder + check = &snd_channels[NUM_AMBIENTS]; + for (ch_idx = NUM_AMBIENTS; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS; ch_idx++, check++) { + if (check == target_chan) + continue; + if (check->sfx == sfx && !check->pos) { + /* + skip = rand () % (int)(0.1 * shm->speed); + if (skip >= target_chan->end) + skip = target_chan->end - 1; + */ + /* LordHavoc: fixed skip calculations */ + skip = 0.1 * shm->speed; /* 0.1 * sc->speed */ + if (skip > sc->length) + skip = sc->length; + if (skip > 0) + skip = rand() % skip; + target_chan->pos += skip; + target_chan->end -= skip; + break; + } + } } -void S_StopSound (int entnum, int entchannel) -{ - int i; +void S_StopSound(int entnum, int entchannel) { + int i; - for (i = 0; i < MAX_DYNAMIC_CHANNELS; i++) - { - if (snd_channels[i].entnum == entnum - && snd_channels[i].entchannel == entchannel) - { - snd_channels[i].end = 0; - snd_channels[i].sfx = NULL; - return; - } - } + for (i = 0; i < MAX_DYNAMIC_CHANNELS; i++) { + if (snd_channels[i].entnum == entnum + && snd_channels[i].entchannel == entchannel) { + snd_channels[i].end = 0; + snd_channels[i].sfx = NULL; + return; + } + } } -void S_StopAllSounds (qboolean clear) -{ - int i; +void S_StopAllSounds(qboolean clear) { + int i; - if (!sound_started) - return; + if (!sound_started) + return; - total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS; // no statics + total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS; // no statics - for (i = 0; i < MAX_CHANNELS; i++) - { - if (snd_channels[i].sfx) - snd_channels[i].sfx = NULL; - } + for (i = 0; i < MAX_CHANNELS; i++) { + if (snd_channels[i].sfx) + snd_channels[i].sfx = NULL; + } - memset(snd_channels, 0, MAX_CHANNELS * sizeof(channel_t)); + memset(snd_channels, 0, MAX_CHANNELS * sizeof(channel_t)); - if (clear) - S_ClearBuffer (); + if (clear) + S_ClearBuffer(); } -static void S_StopAllSoundsC (void) -{ - S_StopAllSounds (true); +static void S_StopAllSoundsC(void) { + S_StopAllSounds(true); } -void S_ClearBuffer (void) -{ - int clear; +void S_ClearBuffer(void) { + int clear; - if (!sound_started || !shm) - return; + if (!sound_started || !shm) + return; - SNDDMA_LockBuffer (); - if (! shm->buffer) - return; + SNDDMA_LockBuffer(); + if (!shm->buffer) + return; - s_rawend = 0; + s_rawend = 0; - if (shm->samplebits == 8 && !shm->signed8) - clear = 0x80; - else - clear = 0; + if (shm->samplebits == 8 && !shm->signed8) + clear = 0x80; + else + clear = 0; - memset(shm->buffer, clear, shm->samples * shm->samplebits / 8); + memset(shm->buffer, clear, shm->samples * shm->samplebits / 8); - SNDDMA_Submit (); + SNDDMA_Submit(); } @@ -583,40 +548,37 @@ void S_ClearBuffer (void) S_StaticSound ================= */ -void S_StaticSound (sfx_t *sfx, vec3_t origin, float vol, float attenuation) -{ - channel_t *ss; - sfxcache_t *sc; +void S_StaticSound(sfx_t *sfx, vec3_t origin, float vol, float attenuation) { + channel_t *ss; + sfxcache_t *sc; - if (!sfx) - return; + if (!sfx) + return; - if (total_channels == MAX_CHANNELS) - { - Con_Printf ("total_channels == MAX_CHANNELS\n"); - return; - } + if (total_channels == MAX_CHANNELS) { + Con_Printf("total_channels == MAX_CHANNELS\n"); + return; + } - ss = &snd_channels[total_channels]; - total_channels++; + ss = &snd_channels[total_channels]; + total_channels++; - sc = S_LoadSound (sfx); - if (!sc) - return; + sc = S_LoadSound(sfx); + if (!sc) + return; - if (sc->loopstart == -1) - { - Con_Printf ("Sound %s not looped\n", sfx->name); - return; - } + if (sc->loopstart == -1) { + Con_Printf("Sound %s not looped\n", sfx->name); + return; + } - ss->sfx = sfx; - VectorCopy (origin, ss->origin); - ss->master_vol = (int)vol; - ss->dist_mult = (attenuation / 64) / sound_nominal_clip_dist; - ss->end = paintedtime + sc->length; + ss->sfx = sfx; + VectorCopy(origin, ss->origin); + ss->master_vol = (int) vol; + ss->dist_mult = (attenuation / 64) / sound_nominal_clip_dist; + ss->end = paintedtime + sc->length; - SND_Spatialize (ss); + SND_Spatialize(ss); } @@ -627,52 +589,46 @@ void S_StaticSound (sfx_t *sfx, vec3_t origin, float vol, float attenuation) S_UpdateAmbientSounds =================== */ -static void S_UpdateAmbientSounds (void) -{ - mleaf_t *l; - int vol, ambient_channel; - channel_t *chan; +static void S_UpdateAmbientSounds(void) { + mleaf_t *l; + int vol, ambient_channel; + channel_t *chan; -// no ambients when disconnected - if (cls.state != ca_connected) - return; -// calc ambient sound levels - if (!cl.worldmodel) - return; + // no ambients when disconnected + if (cls.state != ca_connected) + return; + // calc ambient sound levels + if (!cl.worldmodel) + return; - l = Mod_PointInLeaf (listener_origin, cl.worldmodel); - if (!l || !ambient_level.value) - { - for (ambient_channel = 0; ambient_channel < NUM_AMBIENTS; ambient_channel++) - snd_channels[ambient_channel].sfx = NULL; - return; - } + l = Mod_PointInLeaf(listener_origin, cl.worldmodel); + if (!l || !ambient_level.value) { + for (ambient_channel = 0; ambient_channel < NUM_AMBIENTS; ambient_channel++) + snd_channels[ambient_channel].sfx = NULL; + return; + } - for (ambient_channel = 0; ambient_channel < NUM_AMBIENTS; ambient_channel++) - { - chan = &snd_channels[ambient_channel]; - chan->sfx = ambient_sfx[ambient_channel]; + for (ambient_channel = 0; ambient_channel < NUM_AMBIENTS; ambient_channel++) { + chan = &snd_channels[ambient_channel]; + chan->sfx = ambient_sfx[ambient_channel]; - vol = (int) (ambient_level.value * l->ambient_sound_level[ambient_channel]); - if (vol < 8) - vol = 0; + vol = (int) (ambient_level.value * l->ambient_sound_level[ambient_channel]); + if (vol < 8) + vol = 0; - // don't adjust volume too fast - if (chan->master_vol < vol) - { - chan->master_vol += (int) (host_frametime * ambient_fade.value); - if (chan->master_vol > vol) - chan->master_vol = vol; - } - else if (chan->master_vol > vol) - { - chan->master_vol -= (int) (host_frametime * ambient_fade.value); - if (chan->master_vol < vol) - chan->master_vol = vol; - } + // don't adjust volume too fast + if (chan->master_vol < vol) { + chan->master_vol += (int) (host_frametime * ambient_fade.value); + if (chan->master_vol > vol) + chan->master_vol = vol; + } else if (chan->master_vol > vol) { + chan->master_vol -= (int) (host_frametime * ambient_fade.value); + if (chan->master_vol < vol) + chan->master_vol = vol; + } - chan->leftvol = chan->rightvol = chan->master_vol; - } + chan->leftvol = chan->rightvol = chan->master_vol; + } } @@ -686,79 +642,67 @@ Expects data in signed 16 bit, or unsigned 8 bit format. =================== */ -void S_RawSamples (int samples, int rate, int width, int channels, byte *data, float volume) -{ - int i; - int src, dst; - float scale; - int intVolume; +void S_RawSamples(int samples, int rate, int width, int channels, byte *data, float volume) { + int i; + int src, dst; + float scale; + int intVolume; - if (s_rawend < paintedtime) - s_rawend = paintedtime; + if (s_rawend < paintedtime) + s_rawend = paintedtime; - scale = (float) rate / shm->speed; - intVolume = (int) (256 * volume); + scale = (float) rate / shm->speed; + intVolume = (int) (256 * volume); - if (channels == 2 && width == 2) - { - for (i = 0; ; i++) - { - src = i * scale; - if (src >= samples) - break; - dst = s_rawend & (MAX_RAW_SAMPLES - 1); - s_rawend++; - s_rawsamples [dst].left = ((short *) data)[src * 2] * intVolume; - s_rawsamples [dst].right = ((short *) data)[src * 2 + 1] * intVolume; - } - } - else if (channels == 1 && width == 2) - { - for (i = 0; ; i++) - { - src = i * scale; - if (src >= samples) - break; - dst = s_rawend & (MAX_RAW_SAMPLES - 1); - s_rawend++; - s_rawsamples [dst].left = ((short *) data)[src] * intVolume; - s_rawsamples [dst].right = ((short *) data)[src] * intVolume; - } - } - else if (channels == 2 && width == 1) - { - intVolume *= 256; + if (channels == 2 && width == 2) { + for (i = 0; ; i++) { + src = i * scale; + if (src >= samples) + break; + dst = s_rawend & (MAX_RAW_SAMPLES - 1); + s_rawend++; + s_rawsamples[dst].left = ((short *) data)[src * 2] * intVolume; + s_rawsamples[dst].right = ((short *) data)[src * 2 + 1] * intVolume; + } + } else if (channels == 1 && width == 2) { + for (i = 0; ; i++) { + src = i * scale; + if (src >= samples) + break; + dst = s_rawend & (MAX_RAW_SAMPLES - 1); + s_rawend++; + s_rawsamples[dst].left = ((short *) data)[src] * intVolume; + s_rawsamples[dst].right = ((short *) data)[src] * intVolume; + } + } else if (channels == 2 && width == 1) { + intVolume *= 256; - for (i = 0; ; i++) - { - src = i * scale; - if (src >= samples) - break; - dst = s_rawend & (MAX_RAW_SAMPLES - 1); - s_rawend++; - // s_rawsamples [dst].left = ((signed char *) data)[src * 2] * intVolume; - // s_rawsamples [dst].right = ((signed char *) data)[src * 2 + 1] * intVolume; - s_rawsamples [dst].left = (((byte *) data)[src * 2] - 128) * intVolume; - s_rawsamples [dst].right = (((byte *) data)[src * 2 + 1] - 128) * intVolume; - } - } - else if (channels == 1 && width == 1) - { - intVolume *= 256; + for (i = 0; ; i++) { + src = i * scale; + if (src >= samples) + break; + dst = s_rawend & (MAX_RAW_SAMPLES - 1); + s_rawend++; + // s_rawsamples [dst].left = ((signed char *) data)[src * 2] * intVolume; + // s_rawsamples [dst].right = ((signed char *) data)[src * 2 + 1] * intVolume; + s_rawsamples[dst].left = (((byte *) data)[src * 2] - 128) * intVolume; + s_rawsamples[dst].right = (((byte *) data)[src * 2 + 1] - 128) * intVolume; + } + } else if (channels == 1 && width == 1) { + intVolume *= 256; - for (i = 0; ; i++) - { - src = i * scale; - if (src >= samples) - break; - dst = s_rawend & (MAX_RAW_SAMPLES - 1); - s_rawend++; - // s_rawsamples [dst].left = ((signed char *) data)[src] * intVolume; - // s_rawsamples [dst].right = ((signed char *) data)[src] * intVolume; - s_rawsamples [dst].left = (((byte *) data)[src] - 128) * intVolume; - s_rawsamples [dst].right = (((byte *) data)[src] - 128) * intVolume; - } - } + for (i = 0; ; i++) { + src = i * scale; + if (src >= samples) + break; + dst = s_rawend & (MAX_RAW_SAMPLES - 1); + s_rawend++; + // s_rawsamples [dst].left = ((signed char *) data)[src] * intVolume; + // s_rawsamples [dst].right = ((signed char *) data)[src] * intVolume; + s_rawsamples[dst].left = (((byte *) data)[src] - 128) * intVolume; + s_rawsamples[dst].right = (((byte *) data)[src] - 128) * intVolume; + } + } } /* @@ -768,192 +712,173 @@ S_Update Called once each time through the main loop ============ */ -void S_Update (vec3_t origin, vec3_t forward, vec3_t right, vec3_t up) -{ - int i, j; - int total; - channel_t *ch; - channel_t *combine; +void S_Update(vec3_t origin, vec3_t forward, vec3_t right, vec3_t up) { + int i, j; + int total; + channel_t *ch; + channel_t *combine; - if (!sound_started || (snd_blocked > 0)) - return; + if (!sound_started || (snd_blocked > 0)) + return; - VectorCopy(origin, listener_origin); - VectorCopy(forward, listener_forward); - VectorCopy(right, listener_right); - VectorCopy(up, listener_up); + VectorCopy(origin, listener_origin); + VectorCopy(forward, listener_forward); + VectorCopy(right, listener_right); + VectorCopy(up, listener_up); -// update general area ambient sound sources - S_UpdateAmbientSounds (); + // update general area ambient sound sources + S_UpdateAmbientSounds(); - combine = NULL; + combine = NULL; -// update spatialization for static and dynamic sounds - ch = snd_channels + NUM_AMBIENTS; - for (i = NUM_AMBIENTS; i < total_channels; i++, ch++) - { - if (!ch->sfx) - continue; - SND_Spatialize(ch); // respatialize channel - if (!ch->leftvol && !ch->rightvol) - continue; + // update spatialization for static and dynamic sounds + ch = snd_channels + NUM_AMBIENTS; + for (i = NUM_AMBIENTS; i < total_channels; i++, ch++) { + if (!ch->sfx) + continue; + SND_Spatialize(ch); // respatialize channel + if (!ch->leftvol && !ch->rightvol) + continue; - // try to combine static sounds with a previous channel of the same - // sound effect so we don't mix five torches every frame + // try to combine static sounds with a previous channel of the same + // sound effect so we don't mix five torches every frame - if (i >= MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS) - { - // see if it can just use the last one - if (combine && combine->sfx == ch->sfx) - { - combine->leftvol += ch->leftvol; - combine->rightvol += ch->rightvol; - ch->leftvol = ch->rightvol = 0; - continue; - } - // search for one - combine = snd_channels + MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS; - for (j = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS; j < i; j++, combine++) - { - if (combine->sfx == ch->sfx) - break; - } + if (i >= MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS) { + // see if it can just use the last one + if (combine && combine->sfx == ch->sfx) { + combine->leftvol += ch->leftvol; + combine->rightvol += ch->rightvol; + ch->leftvol = ch->rightvol = 0; + continue; + } + // search for one + combine = snd_channels + MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS; + for (j = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS; j < i; j++, combine++) { + if (combine->sfx == ch->sfx) + break; + } - if (j == total_channels) - { - combine = NULL; - } - else - { - if (combine != ch) - { - combine->leftvol += ch->leftvol; - combine->rightvol += ch->rightvol; - ch->leftvol = ch->rightvol = 0; - } - continue; - } - } - } + if (j == total_channels) { + combine = NULL; + } else { + if (combine != ch) { + combine->leftvol += ch->leftvol; + combine->rightvol += ch->rightvol; + ch->leftvol = ch->rightvol = 0; + } + continue; + } + } + } -// -// debugging output -// - if (snd_show.value) - { - total = 0; - ch = snd_channels; - for (i = 0; i < total_channels; i++, ch++) - { - if (ch->sfx && (ch->leftvol || ch->rightvol) ) - { - // Con_Printf ("%3i %3i %s\n", ch->leftvol, ch->rightvol, ch->sfx->name); - total++; - } - } + // + // debugging output + // + if (snd_show.value) { + total = 0; + ch = snd_channels; + for (i = 0; i < total_channels; i++, ch++) { + if (ch->sfx && (ch->leftvol || ch->rightvol)) { + // Con_Printf ("%3i %3i %s\n", ch->leftvol, ch->rightvol, ch->sfx->name); + total++; + } + } - Con_Printf ("----(%i)----\n", total); - } + Con_Printf("----(%i)----\n", total); + } -// add raw data from streamed samples -// BGM_Update(); // moved to the main loop just before S_Update () + // add raw data from streamed samples + // BGM_Update(); // moved to the main loop just before S_Update () -// mix some sound - S_Update_(); + // mix some sound + S_Update_(); } -static void GetSoundtime (void) -{ - int samplepos; - static int buffers; - static int oldsamplepos; - int fullsamples; +static void GetSoundtime(void) { + int samplepos; + static int buffers; + static int oldsamplepos; + int fullsamples; - fullsamples = shm->samples / shm->channels; + fullsamples = shm->samples / shm->channels; -// it is possible to miscount buffers if it has wrapped twice between -// calls to S_Update. Oh well. - samplepos = SNDDMA_GetDMAPos(); + // it is possible to miscount buffers if it has wrapped twice between + // calls to S_Update. Oh well. + samplepos = SNDDMA_GetDMAPos(); - if (samplepos < oldsamplepos) - { - buffers++; // buffer wrapped + if (samplepos < oldsamplepos) { + buffers++; // buffer wrapped - if (paintedtime > 0x40000000) - { // time to chop things off to avoid 32 bit limits - buffers = 0; - paintedtime = fullsamples; - S_StopAllSounds (true); - } - } - oldsamplepos = samplepos; + if (paintedtime > 0x40000000) { + // time to chop things off to avoid 32 bit limits + buffers = 0; + paintedtime = fullsamples; + S_StopAllSounds(true); + } + } + oldsamplepos = samplepos; - soundtime = buffers*fullsamples + samplepos/shm->channels; + soundtime = buffers * fullsamples + samplepos / shm->channels; } -void S_ExtraUpdate (void) -{ - if (snd_noextraupdate.value) - return; // don't pollute timings - S_Update_(); +void S_ExtraUpdate(void) { + if (snd_noextraupdate.value) + return; // don't pollute timings + S_Update_(); } -static void S_Update_ (void) -{ - unsigned int endtime; - int samps; +static void S_Update_(void) { + unsigned int endtime; + int samps; - if (!sound_started || (snd_blocked > 0)) - return; + if (!sound_started || (snd_blocked > 0)) + return; - SNDDMA_LockBuffer (); - if (! shm->buffer) - return; + SNDDMA_LockBuffer(); + if (!shm->buffer) + return; -// Updates DMA time - GetSoundtime(); + // Updates DMA time + GetSoundtime(); -// check to make sure that we haven't overshot - if (paintedtime < soundtime) - { - // Con_Printf ("S_Update_ : overflow\n"); - paintedtime = soundtime; - } + // check to make sure that we haven't overshot + if (paintedtime < soundtime) { + // Con_Printf ("S_Update_ : overflow\n"); + paintedtime = soundtime; + } -// mix ahead of current position - endtime = soundtime + (unsigned int)(_snd_mixahead.value * shm->speed); - samps = shm->samples >> (shm->channels - 1); - endtime = q_min(endtime, (unsigned int)(soundtime + samps)); + // mix ahead of current position + endtime = soundtime + (unsigned int) (_snd_mixahead.value * shm->speed); + samps = shm->samples >> (shm->channels - 1); + endtime = std::min(endtime, (unsigned int)(soundtime + samps)); - S_PaintChannels (endtime); + S_PaintChannels(endtime); - SNDDMA_Submit (); + SNDDMA_Submit(); } -void S_BlockSound (void) -{ -/* FIXME: do we really need the blocking at the - * driver level? - */ - if (sound_started && snd_blocked == 0) /* ++snd_blocked == 1 */ - { - snd_blocked = 1; - S_ClearBuffer (); - if (shm) - SNDDMA_BlockSound(); - } +void S_BlockSound(void) { + /* FIXME: do we really need the blocking at the + * driver level? + */ + if (sound_started && snd_blocked == 0) /* ++snd_blocked == 1 */ + { + snd_blocked = 1; + S_ClearBuffer(); + if (shm) + SNDDMA_BlockSound(); + } } -void S_UnblockSound (void) -{ - if (!sound_started || !snd_blocked) - return; - if (snd_blocked == 1) /* --snd_blocked == 0 */ - { - snd_blocked = 0; - SNDDMA_UnblockSound(); - S_ClearBuffer (); - } +void S_UnblockSound(void) { + if (!sound_started || !snd_blocked) + return; + if (snd_blocked == 1) /* --snd_blocked == 0 */ + { + snd_blocked = 0; + SNDDMA_UnblockSound(); + S_ClearBuffer(); + } } /* @@ -964,102 +889,89 @@ console functions =============================================================================== */ -static void S_Play (void) -{ - static int hash = 345; - int i; - char name[256]; - sfx_t *sfx; +static void S_Play(void) { + static int hash = 345; + int i; + char name[256]; + sfx_t *sfx; - i = 1; - while (i < Cmd_Argc()) - { - q_strlcpy(name, Cmd_Argv(i), sizeof(name)); - if (!strrchr(Cmd_Argv(i), '.')) - { - q_strlcat(name, ".wav", sizeof(name)); - } - sfx = S_PrecacheSound(name); - S_StartSound(hash++, 0, sfx, listener_origin, 1.0, 1.0); - i++; - } + i = 1; + while (i < command::argc()) { + q_strlcpy(name, command::argv(i)->c_str(), sizeof(name)); + if (!strrchr(command::argv(i)->c_str(), '.')) { + q_strlcat(name, ".wav", sizeof(name)); + } + sfx = S_PrecacheSound(name); + S_StartSound(hash++, 0, sfx, listener_origin, 1.0, 1.0); + i++; + } } -static void S_PlayVol (void) -{ - static int hash = 543; - int i; - float vol; - char name[256]; - sfx_t *sfx; +static void S_PlayVol(void) { + static int hash = 543; + int i; + float vol; + char name[256]; + sfx_t *sfx; - i = 1; - while (i < Cmd_Argc()) - { - q_strlcpy(name, Cmd_Argv(i), sizeof(name)); - if (!strrchr(Cmd_Argv(i), '.')) - { - q_strlcat(name, ".wav", sizeof(name)); - } - sfx = S_PrecacheSound(name); - vol = atof(Cmd_Argv(i + 1)); - S_StartSound(hash++, 0, sfx, listener_origin, vol, 1.0); - i += 2; - } + i = 1; + while (i < command::argc()) { + q_strlcpy(name, command::argv(i)->c_str(), sizeof(name)); + if (!strrchr(command::argv(i)->c_str(), '.')) { + q_strlcat(name, ".wav", sizeof(name)); + } + sfx = S_PrecacheSound(name); + vol = atof(command::argv(i + 1).value_or("").c_str()); + S_StartSound(hash++, 0, sfx, listener_origin, vol, 1.0); + i += 2; + } } -static void S_SoundList (void) -{ - int i; - sfx_t *sfx; - sfxcache_t *sc; - int size, total; +static void S_SoundList(void) { + int i; + sfx_t *sfx; + sfxcache_t *sc; + int size, total; - total = 0; - for (sfx = known_sfx, i = 0; i < num_sfx; i++, sfx++) - { - sc = (sfxcache_t *) Cache_Check (&sfx->cache); - if (!sc) - continue; - size = sc->length*sc->width*(sc->stereo + 1); - total += size; - if (sc->loopstart >= 0) - Con_SafePrintf ("L"); //johnfitz -- was Con_Printf - else - Con_SafePrintf (" "); //johnfitz -- was Con_Printf - Con_SafePrintf("(%2db) %6i : %s\n", sc->width*8, size, sfx->name); //johnfitz -- was Con_Printf - } - Con_Printf ("%i sounds, %i bytes\n", num_sfx, total); //johnfitz -- added count + total = 0; + for (sfx = known_sfx, i = 0; i < num_sfx; i++, sfx++) { + sc = (sfxcache_t *) Cache_Check(&sfx->cache); + if (!sc) + continue; + size = sc->length * sc->width * (sc->stereo + 1); + total += size; + if (sc->loopstart >= 0) + Con_SafePrintf("L"); //johnfitz -- was Con_Printf + else + Con_SafePrintf(" "); //johnfitz -- was Con_Printf + Con_SafePrintf("(%2db) %6i : %s\n", sc->width * 8, size, sfx->name); //johnfitz -- was Con_Printf + } + Con_Printf("%i sounds, %i bytes\n", num_sfx, total); //johnfitz -- added count } -void S_LocalSound (const char *name) -{ - sfx_t *sfx; +void S_LocalSound(const char *name) { + sfx_t *sfx; - if (nosound.value) - return; - if (!sound_started) - return; + if (nosound.value) + return; + if (!sound_started) + return; - sfx = S_PrecacheSound (name); - if (!sfx) - { - Con_Printf ("S_LocalSound: can't cache %s\n", name); - return; - } - S_StartSound (cl.viewentity, -1, sfx, vec3_origin, 1, 1); + sfx = S_PrecacheSound(name); + if (!sfx) { + Con_Printf("S_LocalSound: can't cache %s\n", name); + return; + } + S_StartSound(cl.viewentity, -1, sfx, vec3_origin, 1, 1); } -void S_ClearPrecache (void) -{ +void S_ClearPrecache(void) { } -void S_BeginPrecaching (void) -{ +void S_BeginPrecaching(void) { } -void S_EndPrecaching (void) -{ +void S_EndPrecaching(void) { } diff --git a/Quake/snd_mp3.cpp b/Quake/snd_mp3.cpp index 21eb311..259603a 100644 --- a/Quake/snd_mp3.cpp +++ b/Quake/snd_mp3.cpp @@ -183,7 +183,7 @@ static int mp3_decode(snd_stream_t *stream, byte *buf, int len) do { x = (p->Synth.pcm.length - p->cursamp) * stream->info.channels; - donow = q_min(len, x); + donow = std::min(len, x); i = 0; while (i < donow) { diff --git a/Quake/sv_main.cpp b/Quake/sv_main.cpp index 91c2e9e..4d7b8c0 100644 --- a/Quake/sv_main.cpp +++ b/Quake/sv_main.cpp @@ -44,13 +44,13 @@ void SV_Protocol_f (void) { int i; - switch (Cmd_Argc()) + switch (command::argc()) { case 1: Con_Printf ("\"sv_protocol\" is \"%i\"\n", sv_protocol); break; - case 2: - i = atoi(Cmd_Argv(1)); + case 2: + i = atoi(command::argv(1)->c_str()); if (i != PROTOCOL_NETQUAKE && i != PROTOCOL_FITZQUAKE && i != PROTOCOL_RMQ) Con_Printf ("sv_protocol must be %i or %i or %i\n", PROTOCOL_NETQUAKE, PROTOCOL_FITZQUAKE, PROTOCOL_RMQ); else @@ -75,38 +75,38 @@ void SV_Init (void) { int i; const char *p; - extern cvar_t sv_maxvelocity; - extern cvar_t sv_gravity; - extern cvar_t sv_nostep; - extern cvar_t sv_freezenonclients; - extern cvar_t sv_friction; - extern cvar_t sv_edgefriction; - extern cvar_t sv_stopspeed; - extern cvar_t sv_maxspeed; - extern cvar_t sv_accelerate; - extern cvar_t sv_idealpitchscale; - extern cvar_t sv_aim; - extern cvar_t sv_altnoclip; //johnfitz + extern convar sv_maxvelocity; + extern convar sv_gravity; + extern convar sv_nostep; + extern convar sv_freezenonclients; + extern convar sv_friction; + extern convar sv_edgefriction; + extern convar sv_stopspeed; + extern convar sv_maxspeed; + extern convar sv_accelerate; + extern convar sv_idealpitchscale; + extern convar sv_aim; + extern convar sv_altnoclip; //johnfitz sv.edicts = NULL; // ericw -- sv.edicts switched to use malloc() - Cvar_RegisterVariable (&sv_maxvelocity); - Cvar_RegisterVariable (&sv_gravity); - Cvar_RegisterVariable (&sv_friction); - Cvar_SetCallback (&sv_gravity, Host_Callback_Notify); - Cvar_SetCallback (&sv_friction, Host_Callback_Notify); - Cvar_RegisterVariable (&sv_edgefriction); - Cvar_RegisterVariable (&sv_stopspeed); - Cvar_RegisterVariable (&sv_maxspeed); - Cvar_SetCallback (&sv_maxspeed, Host_Callback_Notify); - Cvar_RegisterVariable (&sv_accelerate); - Cvar_RegisterVariable (&sv_idealpitchscale); - Cvar_RegisterVariable (&sv_aim); - Cvar_RegisterVariable (&sv_nostep); - Cvar_RegisterVariable (&sv_freezenonclients); - Cvar_RegisterVariable (&sv_altnoclip); //johnfitz + sv_maxvelocity.inscribe(); + sv_gravity.inscribe(); + sv_friction.inscribe(); + sv_gravity.set_callback(Host_Callback_Notify); + sv_friction.set_callback(Host_Callback_Notify); + sv_edgefriction.inscribe(); + sv_stopspeed.inscribe(); + sv_maxspeed.inscribe(); + sv_maxspeed.set_callback(Host_Callback_Notify); + sv_accelerate.inscribe(); + sv_idealpitchscale.inscribe(); + sv_aim.inscribe(); + sv_nostep.inscribe(); + sv_freezenonclients.inscribe(); + sv_altnoclip.inscribe(); //johnfitz - Cmd_AddCommand ("sv_protocol", &SV_Protocol_f); //johnfitz + command::add ("sv_protocol", &SV_Protocol_f); //johnfitz for (i=0 ; icursize > 1024 && dev_peakstats.packetsize <= 1024) Con_DWarning ("%i byte packet exceeds standard limit of 1024 (max = %d).\n", msg->cursize, msg->maxsize); dev_stats.packetsize = msg->cursize; - dev_peakstats.packetsize = q_max(msg->cursize, dev_peakstats.packetsize); + dev_peakstats.packetsize = std::max(msg->cursize, dev_peakstats.packetsize); //johnfitz } @@ -1415,7 +1415,7 @@ void SV_SendReconnect (void) NET_SendToAll (&msg, 5.0); if (!isDedicated) - Cmd_ExecuteString ("reconnect\n", src_command); + command::execute_string ("reconnect\n", command::source::command); } @@ -1463,7 +1463,7 @@ void SV_SpawnServer (const char *server) // let's not have any servers with no name if (hostname.string[0] == 0) - Cvar_Set ("hostname", "UNNAMED"); + convar::set ("hostname", "UNNAMED"); scr_centertime_off = 0; Con_DPrintf ("SpawnServer: %s\n",server); @@ -1481,14 +1481,14 @@ void SV_SpawnServer (const char *server) // make cvars consistant // if (coop.value) - Cvar_Set ("deathmatch", "0"); + convar::set ("deathmatch", "0"); current_skill = (int)(skill.value + 0.5); if (current_skill < 0) current_skill = 0; if (current_skill > 3) current_skill = 3; - Cvar_SetValue ("skill", (float)current_skill); + convar::set_value ("skill", (float)current_skill); // // set up the new server diff --git a/Quake/sv_phys.cpp b/Quake/sv_phys.cpp index 3575756..f3299b3 100644 --- a/Quake/sv_phys.cpp +++ b/Quake/sv_phys.cpp @@ -41,12 +41,12 @@ solid_edge items only clip against bsp models. */ -cvar_t sv_friction = {"sv_friction","4",CVAR_NOTIFY|CVAR_SERVERINFO}; -cvar_t sv_stopspeed = {"sv_stopspeed","100",CVAR_NONE}; -cvar_t sv_gravity = {"sv_gravity","800",CVAR_NOTIFY|CVAR_SERVERINFO}; -cvar_t sv_maxvelocity = {"sv_maxvelocity","2000",CVAR_NONE}; -cvar_t sv_nostep = {"sv_nostep","0",CVAR_NONE}; -cvar_t sv_freezenonclients = {"sv_freezenonclients","0",CVAR_NONE}; +convar sv_friction{"sv_friction","4", {.notify = true,. server_info = true}}; +convar sv_stopspeed{"sv_stopspeed","100"}; +convar sv_gravity{"sv_gravity","800",{.notify = true,. server_info = true}}; +convar sv_maxvelocity{"sv_maxvelocity","2000"}; +convar sv_nostep{"sv_nostep","0"}; +convar sv_freezenonclients{"sv_freezenonclients","0"}; #define MOVE_EPSILON 0.01 diff --git a/Quake/sv_user.cpp b/Quake/sv_user.cpp index 04f7822..52e30d5 100644 --- a/Quake/sv_user.cpp +++ b/Quake/sv_user.cpp @@ -25,9 +25,9 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. edict_t *sv_player; -extern cvar_t sv_friction; -cvar_t sv_edgefriction = {"edgefriction", "2", CVAR_NONE}; -extern cvar_t sv_stopspeed; +extern convar sv_friction; +convar sv_edgefriction{"edgefriction", "2"}; +extern convar sv_stopspeed; static vec3_t forward, right, up; @@ -40,8 +40,8 @@ qboolean onground; usercmd_t cmd; -cvar_t sv_idealpitchscale = {"sv_idealpitchscale","0.8",CVAR_NONE}; -cvar_t sv_altnoclip = {"sv_altnoclip","1",CVAR_ARCHIVE}; //johnfitz +convar sv_idealpitchscale{"sv_idealpitchscale","0.8"}; +convar sv_altnoclip{"sv_altnoclip","1",{.archive = true}}; //johnfitz /* =============== @@ -163,8 +163,8 @@ void SV_UserFriction (void) SV_Accelerate ============== */ -cvar_t sv_maxspeed = {"sv_maxspeed", "320", CVAR_NOTIFY|CVAR_SERVERINFO}; -cvar_t sv_accelerate = {"sv_accelerate", "10", CVAR_NONE}; +convar sv_maxspeed{"sv_maxspeed", "320", {.notify = true,. server_info = true}}; +convar sv_accelerate{"sv_accelerate", "10"}; void SV_Accelerate (float wishspeed, const vec3_t wishdir) { int i; @@ -570,7 +570,7 @@ nextmsg: ret = 1; if (ret == 1) - Cmd_ExecuteString (s, src_client); + command::execute_string (s, command::source::client); else Con_DPrintf("%s tried to %s\n", host_client->name, s); break; diff --git a/Quake/sys_sdl_unix.cpp b/Quake/sys_sdl_unix.cpp index 500c0ef..8cc7272 100644 --- a/Quake/sys_sdl_unix.cpp +++ b/Quake/sys_sdl_unix.cpp @@ -49,7 +49,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. qboolean isDedicated; -cvar_t sys_throttle = {"sys_throttle", "0.02", CVAR_ARCHIVE}; +convar sys_throttle = {"sys_throttle", "0.02", {.archive = true}}; #define MAX_HANDLES 32 /* johnfitz -- was 10 */ static FILE *sys_handles[MAX_HANDLES]; diff --git a/Quake/view.cpp b/Quake/view.cpp index 1f84e72..7e83a8b 100644 --- a/Quake/view.cpp +++ b/Quake/view.cpp @@ -32,42 +32,43 @@ when crossing a water boudnary. */ -cvar_t scr_ofsx = {"scr_ofsx","0", CVAR_NONE}; -cvar_t scr_ofsy = {"scr_ofsy","0", CVAR_NONE}; -cvar_t scr_ofsz = {"scr_ofsz","0", CVAR_NONE}; +convar scr_ofsx{"scr_ofsx", "0"}; +convar scr_ofsy{"scr_ofsy", "0"}; +convar scr_ofsz{"scr_ofsz", "0"}; -cvar_t cl_rollspeed = {"cl_rollspeed", "200", CVAR_NONE}; -cvar_t cl_rollangle = {"cl_rollangle", "2.0", CVAR_NONE}; +convar cl_rollspeed{"cl_rollspeed", "200"}; +convar cl_rollangle{"cl_rollangle", "2.0"}; -cvar_t cl_bob = {"cl_bob","0.02", CVAR_NONE}; -cvar_t cl_bobcycle = {"cl_bobcycle","0.6", CVAR_NONE}; -cvar_t cl_bobup = {"cl_bobup","0.5", CVAR_NONE}; +convar cl_bob{"cl_bob", "0.02"}; +convar cl_bobcycle{"cl_bobcycle", "0.6"}; +convar cl_bobup{"cl_bobup", "0.5"}; -cvar_t v_kicktime = {"v_kicktime", "0.5", CVAR_NONE}; -cvar_t v_kickroll = {"v_kickroll", "0.6", CVAR_NONE}; -cvar_t v_kickpitch = {"v_kickpitch", "0.6", CVAR_NONE}; -cvar_t v_gunkick = {"v_gunkick", "1", CVAR_NONE}; //johnfitz +convar v_kicktime{"v_kicktime", "0.5"}; +convar v_kickroll{"v_kickroll", "0.6"}; +convar v_kickpitch{"v_kickpitch", "0.6"}; +convar v_gunkick{"v_gunkick", "1"}; //johnfitz -cvar_t v_iyaw_cycle = {"v_iyaw_cycle", "2", CVAR_NONE}; -cvar_t v_iroll_cycle = {"v_iroll_cycle", "0.5", CVAR_NONE}; -cvar_t v_ipitch_cycle = {"v_ipitch_cycle", "1", CVAR_NONE}; -cvar_t v_iyaw_level = {"v_iyaw_level", "0.3", CVAR_NONE}; -cvar_t v_iroll_level = {"v_iroll_level", "0.1", CVAR_NONE}; -cvar_t v_ipitch_level = {"v_ipitch_level", "0.3", CVAR_NONE}; +convar v_iyaw_cycle{"v_iyaw_cycle", "2"}; +convar v_iroll_cycle{"v_iroll_cycle", "0.5"}; +convar v_ipitch_cycle{"v_ipitch_cycle", "1"}; +convar v_iyaw_level{"v_iyaw_level", "0.3"}; +convar v_iroll_level{"v_iroll_level", "0.1"}; +convar v_ipitch_level{"v_ipitch_level", "0.3"}; -cvar_t v_idlescale = {"v_idlescale", "0", CVAR_NONE}; +convar v_idlescale{"v_idlescale", "0"}; -cvar_t crosshair = {"crosshair", "0", CVAR_ARCHIVE}; +convar crosshair = {"crosshair", "0", {.archive = true}}; -cvar_t gl_cshiftpercent = {"gl_cshiftpercent", "100", CVAR_NONE}; -cvar_t gl_cshiftpercent_contents = {"gl_cshiftpercent_contents", "100", CVAR_NONE}; // QuakeSpasm -cvar_t gl_cshiftpercent_damage = {"gl_cshiftpercent_damage", "100", CVAR_NONE}; // QuakeSpasm -cvar_t gl_cshiftpercent_bonus = {"gl_cshiftpercent_bonus", "100", CVAR_NONE}; // QuakeSpasm -cvar_t gl_cshiftpercent_powerup = {"gl_cshiftpercent_powerup", "100", CVAR_NONE}; // QuakeSpasm +convar gl_cshiftpercent{"gl_cshiftpercent", "100"}; +convar gl_cshiftpercent_contents{"gl_cshiftpercent_contents", "100"}; // QuakeSpasm +convar gl_cshiftpercent_damage{"gl_cshiftpercent_damage", "100"}; // QuakeSpasm +convar gl_cshiftpercent_bonus{"gl_cshiftpercent_bonus", "100"}; // QuakeSpasm +convar gl_cshiftpercent_powerup{"gl_cshiftpercent_powerup", "100"}; // QuakeSpasm -cvar_t r_viewmodel_quake = {"r_viewmodel_quake", "0", CVAR_ARCHIVE}; +convar r_viewmodel_quake{"r_viewmodel_quake", "0", {.archive = true}}; -vec3_t v_punchangles[2]; //johnfitz -- copied from cl.punchangle. 0 is current, 1 is previous value. never the same unless map just loaded +vec3_t v_punchangles[2]; +//johnfitz -- copied from cl.punchangle. 0 is current, 1 is previous value. never the same unless map just loaded /* =============== @@ -76,28 +77,27 @@ V_CalcRoll Used by view and sv_user =============== */ -float V_CalcRoll (vec3_t angles, vec3_t velocity) -{ - vec3_t forward, right, up; - float sign; - float side; - float value; +float V_CalcRoll(vec3_t angles, vec3_t velocity) { + vec3_t forward, right, up; + float sign; + float side; + float value; - AngleVectors (angles, forward, right, up); - side = DotProduct (velocity, right); - sign = side < 0 ? -1 : 1; - side = fabs(side); + AngleVectors(angles, forward, right, up); + side = DotProduct(velocity, right); + sign = side < 0 ? -1 : 1; + side = fabs(side); - value = cl_rollangle.value; -// if (cl.inwater) -// value *= 6; + value = cl_rollangle.value; + // if (cl.inwater) + // value *= 6; - if (side < cl_rollspeed.value) - side = side * value / cl_rollspeed.value; - else - side = value; + if (side < cl_rollspeed.value) + side = side * value / cl_rollspeed.value; + else + side = value; - return side*sign; + return side * sign; } @@ -107,63 +107,58 @@ V_CalcBob =============== */ -float V_CalcBob (void) -{ - float bob; - float cycle; +float V_CalcBob(void) { + float bob; + float cycle; - if (!cl_bobcycle.value) /* Avoid divide-by-zero, don't bob */ - return 0.0f; + if (!cl_bobcycle.value) /* Avoid divide-by-zero, don't bob */ + return 0.0f; - cycle = cl.time - (int)(cl.time/cl_bobcycle.value)*cl_bobcycle.value; - cycle /= cl_bobcycle.value; - if (cycle < cl_bobup.value) - cycle = M_PI * cycle / cl_bobup.value; - else - cycle = M_PI + M_PI*(cycle-cl_bobup.value)/(1.0 - cl_bobup.value); + cycle = cl.time - (int) (cl.time / cl_bobcycle.value) * cl_bobcycle.value; + cycle /= cl_bobcycle.value; + if (cycle < cl_bobup.value) + cycle = M_PI * cycle / cl_bobup.value; + else + cycle = M_PI + M_PI * (cycle - cl_bobup.value) / (1.0 - cl_bobup.value); -// bob is proportional to velocity in the xy plane -// (don't count Z, or jumping messes it up) + // bob is proportional to velocity in the xy plane + // (don't count Z, or jumping messes it up) - bob = sqrt(cl.velocity[0]*cl.velocity[0] + cl.velocity[1]*cl.velocity[1]) * cl_bob.value; -//Con_Printf ("speed: %5.1f\n", VectorLength(cl.velocity)); - bob = bob*0.3 + bob*0.7*sin(cycle); - if (bob > 4) - bob = 4; - else if (bob < -7) - bob = -7; - return bob; + bob = sqrt(cl.velocity[0] * cl.velocity[0] + cl.velocity[1] * cl.velocity[1]) * cl_bob.value; + //Con_Printf ("speed: %5.1f\n", VectorLength(cl.velocity)); + bob = bob * 0.3 + bob * 0.7 * sin(cycle); + if (bob > 4) + bob = 4; + else if (bob < -7) + bob = -7; + return bob; } //============================================================================= -cvar_t v_centermove = {"v_centermove", "0.15", CVAR_NONE}; -cvar_t v_centerspeed = {"v_centerspeed","500", CVAR_NONE}; +convar v_centermove{"v_centermove", "0.15"}; +convar v_centerspeed{"v_centerspeed", "500"}; -void V_StartPitchDrift (void) -{ +void V_StartPitchDrift(void) { #if 1 - if (cl.laststop == cl.time) - { - return; // something else is keeping it from drifting - } + if (cl.laststop == cl.time) { + return; // something else is keeping it from drifting + } #endif - if (cl.nodrift || !cl.pitchvel) - { - cl.pitchvel = v_centerspeed.value; - cl.nodrift = false; - cl.driftmove = 0; - } + if (cl.nodrift || !cl.pitchvel) { + cl.pitchvel = v_centerspeed.value; + cl.nodrift = false; + cl.driftmove = 0; + } } -void V_StopPitchDrift (void) -{ - cl.laststop = cl.time; - cl.nodrift = true; - cl.pitchvel = 0; +void V_StopPitchDrift(void) { + cl.laststop = cl.time; + cl.nodrift = true; + cl.pitchvel = 0; } /* @@ -179,65 +174,56 @@ Drifting is enabled when the center view key is hit, mlook is released and lookspring is non 0, or when =============== */ -void V_DriftPitch (void) -{ - float delta, move; +void V_DriftPitch(void) { + float delta, move; - if (noclip_anglehack || !cl.onground || cls.demoplayback ) - //FIXME: noclip_anglehack is set on the server, so in a nonlocal game this won't work. - { - cl.driftmove = 0; - cl.pitchvel = 0; - return; - } + if (noclip_anglehack || !cl.onground || cls.demoplayback) + //FIXME: noclip_anglehack is set on the server, so in a nonlocal game this won't work. + { + cl.driftmove = 0; + cl.pitchvel = 0; + return; + } -// don't count small mouse motion - if (cl.nodrift) - { - if ( fabs(cl.cmd.forwardmove) < cl_forwardspeed.value) - cl.driftmove = 0; - else - cl.driftmove += host_frametime; + // don't count small mouse motion + if (cl.nodrift) { + if (fabs(cl.cmd.forwardmove) < cl_forwardspeed.value) + cl.driftmove = 0; + else + cl.driftmove += host_frametime; - if ( cl.driftmove > v_centermove.value) - { - if (lookspring.value) - V_StartPitchDrift (); - } - return; - } + if (cl.driftmove > v_centermove.value) { + if (lookspring.value) + V_StartPitchDrift(); + } + return; + } - delta = cl.idealpitch - cl.viewangles[PITCH]; + delta = cl.idealpitch - cl.viewangles[PITCH]; - if (!delta) - { - cl.pitchvel = 0; - return; - } + if (!delta) { + cl.pitchvel = 0; + return; + } - move = host_frametime * cl.pitchvel; - cl.pitchvel += host_frametime * v_centerspeed.value; + move = host_frametime * cl.pitchvel; + cl.pitchvel += host_frametime * v_centerspeed.value; -//Con_Printf ("move: %f (%f)\n", move, host_frametime); + //Con_Printf ("move: %f (%f)\n", move, host_frametime); - if (delta > 0) - { - if (move > delta) - { - cl.pitchvel = 0; - move = delta; - } - cl.viewangles[PITCH] += move; - } - else if (delta < 0) - { - if (move > -delta) - { - cl.pitchvel = 0; - move = -delta; - } - cl.viewangles[PITCH] -= move; - } + if (delta > 0) { + if (move > delta) { + cl.pitchvel = 0; + move = delta; + } + cl.viewangles[PITCH] += move; + } else if (delta < 0) { + if (move > -delta) { + cl.pitchvel = 0; + move = -delta; + } + cl.viewangles[PITCH] -= move; + } } /* @@ -248,14 +234,14 @@ void V_DriftPitch (void) ============================================================================== */ -static cshift_t cshift_empty = { {130,80,50}, 0 }; -static cshift_t cshift_water = { {130,80,50}, 128 }; -static cshift_t cshift_slime = { {0,25,5}, 150 }; -static cshift_t cshift_lava = { {255,80,0}, 150 }; +static cshift_t cshift_empty = {{130, 80, 50}, 0}; +static cshift_t cshift_water = {{130, 80, 50}, 128}; +static cshift_t cshift_slime = {{0, 25, 5}, 150}; +static cshift_t cshift_lava = {{255, 80, 0}, 150}; static float v_dmg_time, v_dmg_roll, v_dmg_pitch; -float v_blend[4]; // rgba 0.0 - 1.0 +float v_blend[4]; // rgba 0.0 - 1.0 //johnfitz -- deleted BuildGammaTable(), V_CheckGamma(), gammatable[], and ramps[][] @@ -264,69 +250,63 @@ float v_blend[4]; // rgba 0.0 - 1.0 V_ParseDamage =============== */ -void V_ParseDamage (void) -{ - int armor, blood; - vec3_t from; - int i; - vec3_t forward, right, up; - entity_t *ent; - float side; - float count; +void V_ParseDamage(void) { + int armor, blood; + vec3_t from; + int i; + vec3_t forward, right, up; + entity_t *ent; + float side; + float count; - armor = MSG_ReadByte (); - blood = MSG_ReadByte (); - for (i=0 ; i<3 ; i++) - from[i] = MSG_ReadCoord (cl.protocolflags); + armor = MSG_ReadByte(); + blood = MSG_ReadByte(); + for (i = 0; i < 3; i++) + from[i] = MSG_ReadCoord(cl.protocolflags); - count = blood*0.5 + armor*0.5; - if (count < 10) - count = 10; + count = blood * 0.5 + armor * 0.5; + if (count < 10) + count = 10; - cl.faceanimtime = cl.time + 0.2; // but sbar face into pain frame + cl.faceanimtime = cl.time + 0.2; // but sbar face into pain frame - cl.cshifts[CSHIFT_DAMAGE].percent += 3*count; - if (cl.cshifts[CSHIFT_DAMAGE].percent < 0) - cl.cshifts[CSHIFT_DAMAGE].percent = 0; - if (cl.cshifts[CSHIFT_DAMAGE].percent > 150) - cl.cshifts[CSHIFT_DAMAGE].percent = 150; + cl.cshifts[CSHIFT_DAMAGE].percent += 3 * count; + if (cl.cshifts[CSHIFT_DAMAGE].percent < 0) + cl.cshifts[CSHIFT_DAMAGE].percent = 0; + if (cl.cshifts[CSHIFT_DAMAGE].percent > 150) + cl.cshifts[CSHIFT_DAMAGE].percent = 150; - if (armor > blood) - { - cl.cshifts[CSHIFT_DAMAGE].destcolor[0] = 200; - cl.cshifts[CSHIFT_DAMAGE].destcolor[1] = 100; - cl.cshifts[CSHIFT_DAMAGE].destcolor[2] = 100; - } - else if (armor) - { - cl.cshifts[CSHIFT_DAMAGE].destcolor[0] = 220; - cl.cshifts[CSHIFT_DAMAGE].destcolor[1] = 50; - cl.cshifts[CSHIFT_DAMAGE].destcolor[2] = 50; - } - else - { - cl.cshifts[CSHIFT_DAMAGE].destcolor[0] = 255; - cl.cshifts[CSHIFT_DAMAGE].destcolor[1] = 0; - cl.cshifts[CSHIFT_DAMAGE].destcolor[2] = 0; - } + if (armor > blood) { + cl.cshifts[CSHIFT_DAMAGE].destcolor[0] = 200; + cl.cshifts[CSHIFT_DAMAGE].destcolor[1] = 100; + cl.cshifts[CSHIFT_DAMAGE].destcolor[2] = 100; + } else if (armor) { + cl.cshifts[CSHIFT_DAMAGE].destcolor[0] = 220; + cl.cshifts[CSHIFT_DAMAGE].destcolor[1] = 50; + cl.cshifts[CSHIFT_DAMAGE].destcolor[2] = 50; + } else { + cl.cshifts[CSHIFT_DAMAGE].destcolor[0] = 255; + cl.cshifts[CSHIFT_DAMAGE].destcolor[1] = 0; + cl.cshifts[CSHIFT_DAMAGE].destcolor[2] = 0; + } -// -// calculate view angle kicks -// - ent = &cl_entities[cl.viewentity]; + // + // calculate view angle kicks + // + ent = &cl_entities[cl.viewentity]; - VectorSubtract (from, ent->origin, from); - VectorNormalize (from); + VectorSubtract(from, ent->origin, from); + VectorNormalize(from); - AngleVectors (ent->angles, forward, right, up); + AngleVectors(ent->angles, forward, right, up); - side = DotProduct (from, right); - v_dmg_roll = count*side*v_kickroll.value; + side = DotProduct(from, right); + v_dmg_roll = count * side * v_kickroll.value; - side = DotProduct (from, forward); - v_dmg_pitch = count*side*v_kickpitch.value; + side = DotProduct(from, forward); + v_dmg_pitch = count * side * v_kickpitch.value; - v_dmg_time = v_kicktime.value; + v_dmg_time = v_kicktime.value; } @@ -335,12 +315,11 @@ void V_ParseDamage (void) V_cshift_f ================== */ -void V_cshift_f (void) -{ - cshift_empty.destcolor[0] = atoi(Cmd_Argv(1)); - cshift_empty.destcolor[1] = atoi(Cmd_Argv(2)); - cshift_empty.destcolor[2] = atoi(Cmd_Argv(3)); - cshift_empty.percent = atoi(Cmd_Argv(4)); +void V_cshift_f(void) { + cshift_empty.destcolor[0] = atoi(command::argv(1).value_or("").c_str()); + cshift_empty.destcolor[1] = atoi(command::argv(2).value_or("").c_str()); + cshift_empty.destcolor[2] = atoi(command::argv(3).value_or("").c_str()); + cshift_empty.percent = atoi(command::argv(4).value_or("").c_str()); } @@ -351,12 +330,11 @@ V_BonusFlash_f When you run over an item, the server sends this command ================== */ -void V_BonusFlash_f (void) -{ - cl.cshifts[CSHIFT_BONUS].destcolor[0] = 215; - cl.cshifts[CSHIFT_BONUS].destcolor[1] = 186; - cl.cshifts[CSHIFT_BONUS].destcolor[2] = 69; - cl.cshifts[CSHIFT_BONUS].percent = 50; +void V_BonusFlash_f(void) { + cl.cshifts[CSHIFT_BONUS].destcolor[0] = 215; + cl.cshifts[CSHIFT_BONUS].destcolor[1] = 186; + cl.cshifts[CSHIFT_BONUS].destcolor[2] = 69; + cl.cshifts[CSHIFT_BONUS].percent = 50; } /* @@ -366,24 +344,22 @@ V_SetContentsColor Underwater, lava, etc each has a color shift ============= */ -void V_SetContentsColor (int contents) -{ - switch (contents) - { - case CONTENTS_EMPTY: - case CONTENTS_SOLID: - case CONTENTS_SKY: //johnfitz -- no blend in sky - cl.cshifts[CSHIFT_CONTENTS] = cshift_empty; - break; - case CONTENTS_LAVA: - cl.cshifts[CSHIFT_CONTENTS] = cshift_lava; - break; - case CONTENTS_SLIME: - cl.cshifts[CSHIFT_CONTENTS] = cshift_slime; - break; - default: - cl.cshifts[CSHIFT_CONTENTS] = cshift_water; - } +void V_SetContentsColor(int contents) { + switch (contents) { + case CONTENTS_EMPTY: + case CONTENTS_SOLID: + case CONTENTS_SKY: //johnfitz -- no blend in sky + cl.cshifts[CSHIFT_CONTENTS] = cshift_empty; + break; + case CONTENTS_LAVA: + cl.cshifts[CSHIFT_CONTENTS] = cshift_lava; + break; + case CONTENTS_SLIME: + cl.cshifts[CSHIFT_CONTENTS] = cshift_slime; + break; + default: + cl.cshifts[CSHIFT_CONTENTS] = cshift_water; + } } /* @@ -391,38 +367,29 @@ void V_SetContentsColor (int contents) V_CalcPowerupCshift ============= */ -void V_CalcPowerupCshift (void) -{ - if (cl.items & IT_QUAD) - { - cl.cshifts[CSHIFT_POWERUP].destcolor[0] = 0; - cl.cshifts[CSHIFT_POWERUP].destcolor[1] = 0; - cl.cshifts[CSHIFT_POWERUP].destcolor[2] = 255; - cl.cshifts[CSHIFT_POWERUP].percent = 30; - } - else if (cl.items & IT_SUIT) - { - cl.cshifts[CSHIFT_POWERUP].destcolor[0] = 0; - cl.cshifts[CSHIFT_POWERUP].destcolor[1] = 255; - cl.cshifts[CSHIFT_POWERUP].destcolor[2] = 0; - cl.cshifts[CSHIFT_POWERUP].percent = 20; - } - else if (cl.items & IT_INVISIBILITY) - { - cl.cshifts[CSHIFT_POWERUP].destcolor[0] = 100; - cl.cshifts[CSHIFT_POWERUP].destcolor[1] = 100; - cl.cshifts[CSHIFT_POWERUP].destcolor[2] = 100; - cl.cshifts[CSHIFT_POWERUP].percent = 100; - } - else if (cl.items & IT_INVULNERABILITY) - { - cl.cshifts[CSHIFT_POWERUP].destcolor[0] = 255; - cl.cshifts[CSHIFT_POWERUP].destcolor[1] = 255; - cl.cshifts[CSHIFT_POWERUP].destcolor[2] = 0; - cl.cshifts[CSHIFT_POWERUP].percent = 30; - } - else - cl.cshifts[CSHIFT_POWERUP].percent = 0; +void V_CalcPowerupCshift(void) { + if (cl.items & IT_QUAD) { + cl.cshifts[CSHIFT_POWERUP].destcolor[0] = 0; + cl.cshifts[CSHIFT_POWERUP].destcolor[1] = 0; + cl.cshifts[CSHIFT_POWERUP].destcolor[2] = 255; + cl.cshifts[CSHIFT_POWERUP].percent = 30; + } else if (cl.items & IT_SUIT) { + cl.cshifts[CSHIFT_POWERUP].destcolor[0] = 0; + cl.cshifts[CSHIFT_POWERUP].destcolor[1] = 255; + cl.cshifts[CSHIFT_POWERUP].destcolor[2] = 0; + cl.cshifts[CSHIFT_POWERUP].percent = 20; + } else if (cl.items & IT_INVISIBILITY) { + cl.cshifts[CSHIFT_POWERUP].destcolor[0] = 100; + cl.cshifts[CSHIFT_POWERUP].destcolor[1] = 100; + cl.cshifts[CSHIFT_POWERUP].destcolor[2] = 100; + cl.cshifts[CSHIFT_POWERUP].percent = 100; + } else if (cl.items & IT_INVULNERABILITY) { + cl.cshifts[CSHIFT_POWERUP].destcolor[0] = 255; + cl.cshifts[CSHIFT_POWERUP].destcolor[1] = 255; + cl.cshifts[CSHIFT_POWERUP].destcolor[2] = 0; + cl.cshifts[CSHIFT_POWERUP].percent = 30; + } else + cl.cshifts[CSHIFT_POWERUP].percent = 0; } /* @@ -430,53 +397,51 @@ void V_CalcPowerupCshift (void) V_CalcBlend ============= */ -void V_CalcBlend (void) -{ - float r, g, b, a, a2; - int j; - cvar_t *cshiftpercent_cvars[NUM_CSHIFTS] = { - &gl_cshiftpercent_contents, - &gl_cshiftpercent_damage, - &gl_cshiftpercent_bonus, - &gl_cshiftpercent_powerup - }; +void V_CalcBlend(void) { + float r, g, b, a, a2; + int j; + convar *cshiftpercent_cvars[NUM_CSHIFTS] = { + &gl_cshiftpercent_contents, + &gl_cshiftpercent_damage, + &gl_cshiftpercent_bonus, + &gl_cshiftpercent_powerup + }; - r = 0; - g = 0; - b = 0; - a = 0; + r = 0; + g = 0; + b = 0; + a = 0; - for (j=0 ; jvalue / 100.0); - // QuakeSpasm - if (!a2) - continue; - a = a + a2*(1-a); - a2 = a2/a; - r = r*(1-a2) + cl.cshifts[j].destcolor[0]*a2; - g = g*(1-a2) + cl.cshifts[j].destcolor[1]*a2; - b = b*(1-a2) + cl.cshifts[j].destcolor[2]*a2; - } + a2 = ((cl.cshifts[j].percent * gl_cshiftpercent.value) / 100.0) / 255.0; + // QuakeSpasm -- also scale by the specific gl_cshiftpercent_* cvar + a2 *= (cshiftpercent_cvars[j]->value / 100.0); + // QuakeSpasm + if (!a2) + continue; + a = a + a2 * (1 - a); + a2 = a2 / a; + r = r * (1 - a2) + cl.cshifts[j].destcolor[0] * a2; + g = g * (1 - a2) + cl.cshifts[j].destcolor[1] * a2; + b = b * (1 - a2) + cl.cshifts[j].destcolor[2] * a2; + } - v_blend[0] = r/255.0; - v_blend[1] = g/255.0; - v_blend[2] = b/255.0; - v_blend[3] = a; - if (v_blend[3] > 1) - v_blend[3] = 1; - if (v_blend[3] < 0) - v_blend[3] = 0; + v_blend[0] = r / 255.0; + v_blend[1] = g / 255.0; + v_blend[2] = b / 255.0; + v_blend[3] = a; + if (v_blend[3] > 1) + v_blend[3] = 1; + if (v_blend[3] < 0) + v_blend[3] = 0; } /* @@ -484,42 +449,38 @@ void V_CalcBlend (void) V_UpdateBlend -- johnfitz -- V_UpdatePalette cleaned up and renamed ============= */ -void V_UpdateBlend (void) -{ - int i, j; - qboolean blend_changed; +void V_UpdateBlend(void) { + int i, j; + qboolean blend_changed; - V_CalcPowerupCshift (); + V_CalcPowerupCshift(); - blend_changed = false; + blend_changed = false; - for (i=0 ; i 180) - a -= 360; - return a; +float angledelta(float a) { + a = anglemod(a); + if (a > 180) + a -= 360; + return a; } /* @@ -582,57 +541,50 @@ float angledelta (float a) CalcGunAngle ================== */ -void CalcGunAngle (void) -{ - float yaw, pitch, move; - static float oldyaw = 0; - static float oldpitch = 0; +void CalcGunAngle(void) { + float yaw, pitch, move; + static float oldyaw = 0; + static float oldpitch = 0; - yaw = r_refdef.viewangles[YAW]; - pitch = -r_refdef.viewangles[PITCH]; + yaw = r_refdef.viewangles[YAW]; + pitch = -r_refdef.viewangles[PITCH]; - yaw = angledelta(yaw - r_refdef.viewangles[YAW]) * 0.4; - if (yaw > 10) - yaw = 10; - if (yaw < -10) - yaw = -10; - pitch = angledelta(-pitch - r_refdef.viewangles[PITCH]) * 0.4; - if (pitch > 10) - pitch = 10; - if (pitch < -10) - pitch = -10; - move = host_frametime*20; - if (yaw > oldyaw) - { - if (oldyaw + move < yaw) - yaw = oldyaw + move; - } - else - { - if (oldyaw - move > yaw) - yaw = oldyaw - move; - } + yaw = angledelta(yaw - r_refdef.viewangles[YAW]) * 0.4; + if (yaw > 10) + yaw = 10; + if (yaw < -10) + yaw = -10; + pitch = angledelta(-pitch - r_refdef.viewangles[PITCH]) * 0.4; + if (pitch > 10) + pitch = 10; + if (pitch < -10) + pitch = -10; + move = host_frametime * 20; + if (yaw > oldyaw) { + if (oldyaw + move < yaw) + yaw = oldyaw + move; + } else { + if (oldyaw - move > yaw) + yaw = oldyaw - move; + } - if (pitch > oldpitch) - { - if (oldpitch + move < pitch) - pitch = oldpitch + move; - } - else - { - if (oldpitch - move > pitch) - pitch = oldpitch - move; - } + if (pitch > oldpitch) { + if (oldpitch + move < pitch) + pitch = oldpitch + move; + } else { + if (oldpitch - move > pitch) + pitch = oldpitch - move; + } - oldyaw = yaw; - oldpitch = pitch; + oldyaw = yaw; + oldpitch = pitch; - cl.viewent.angles[YAW] = r_refdef.viewangles[YAW] + yaw; - cl.viewent.angles[PITCH] = - (r_refdef.viewangles[PITCH] + pitch); + cl.viewent.angles[YAW] = r_refdef.viewangles[YAW] + yaw; + cl.viewent.angles[PITCH] = -(r_refdef.viewangles[PITCH] + pitch); - cl.viewent.angles[ROLL] -= v_idlescale.value * sin(cl.time*v_iroll_cycle.value) * v_iroll_level.value; - cl.viewent.angles[PITCH] -= v_idlescale.value * sin(cl.time*v_ipitch_cycle.value) * v_ipitch_level.value; - cl.viewent.angles[YAW] -= v_idlescale.value * sin(cl.time*v_iyaw_cycle.value) * v_iyaw_level.value; + cl.viewent.angles[ROLL] -= v_idlescale.value * sin(cl.time * v_iroll_cycle.value) * v_iroll_level.value; + cl.viewent.angles[PITCH] -= v_idlescale.value * sin(cl.time * v_ipitch_cycle.value) * v_ipitch_level.value; + cl.viewent.angles[YAW] -= v_idlescale.value * sin(cl.time * v_iyaw_cycle.value) * v_iyaw_level.value; } /* @@ -640,27 +592,26 @@ void CalcGunAngle (void) V_BoundOffsets ============== */ -void V_BoundOffsets (void) -{ - entity_t *ent; +void V_BoundOffsets(void) { + entity_t *ent; - ent = &cl_entities[cl.viewentity]; + ent = &cl_entities[cl.viewentity]; -// absolutely bound refresh reletive to entity clipping hull -// so the view can never be inside a solid wall + // absolutely bound refresh reletive to entity clipping hull + // so the view can never be inside a solid wall - if (r_refdef.vieworg[0] < ent->origin[0] - 14) - r_refdef.vieworg[0] = ent->origin[0] - 14; - else if (r_refdef.vieworg[0] > ent->origin[0] + 14) - r_refdef.vieworg[0] = ent->origin[0] + 14; - if (r_refdef.vieworg[1] < ent->origin[1] - 14) - r_refdef.vieworg[1] = ent->origin[1] - 14; - else if (r_refdef.vieworg[1] > ent->origin[1] + 14) - r_refdef.vieworg[1] = ent->origin[1] + 14; - if (r_refdef.vieworg[2] < ent->origin[2] - 22) - r_refdef.vieworg[2] = ent->origin[2] - 22; - else if (r_refdef.vieworg[2] > ent->origin[2] + 30) - r_refdef.vieworg[2] = ent->origin[2] + 30; + if (r_refdef.vieworg[0] < ent->origin[0] - 14) + r_refdef.vieworg[0] = ent->origin[0] - 14; + else if (r_refdef.vieworg[0] > ent->origin[0] + 14) + r_refdef.vieworg[0] = ent->origin[0] + 14; + if (r_refdef.vieworg[1] < ent->origin[1] - 14) + r_refdef.vieworg[1] = ent->origin[1] - 14; + else if (r_refdef.vieworg[1] > ent->origin[1] + 14) + r_refdef.vieworg[1] = ent->origin[1] + 14; + if (r_refdef.vieworg[2] < ent->origin[2] - 22) + r_refdef.vieworg[2] = ent->origin[2] - 22; + else if (r_refdef.vieworg[2] > ent->origin[2] + 30) + r_refdef.vieworg[2] = ent->origin[2] + 30; } /* @@ -670,11 +621,10 @@ V_AddIdle Idle swaying ============== */ -void V_AddIdle (void) -{ - r_refdef.viewangles[ROLL] += v_idlescale.value * sin(cl.time*v_iroll_cycle.value) * v_iroll_level.value; - r_refdef.viewangles[PITCH] += v_idlescale.value * sin(cl.time*v_ipitch_cycle.value) * v_ipitch_level.value; - r_refdef.viewangles[YAW] += v_idlescale.value * sin(cl.time*v_iyaw_cycle.value) * v_iyaw_level.value; +void V_AddIdle(void) { + r_refdef.viewangles[ROLL] += v_idlescale.value * sin(cl.time * v_iroll_cycle.value) * v_iroll_level.value; + r_refdef.viewangles[PITCH] += v_idlescale.value * sin(cl.time * v_ipitch_cycle.value) * v_ipitch_level.value; + r_refdef.viewangles[YAW] += v_idlescale.value * sin(cl.time * v_iyaw_cycle.value) * v_iyaw_level.value; } @@ -685,25 +635,22 @@ V_CalcViewRoll Roll is induced by movement and damage ============== */ -void V_CalcViewRoll (void) -{ - float side; +void V_CalcViewRoll(void) { + float side; - side = V_CalcRoll (cl_entities[cl.viewentity].angles, cl.velocity); - r_refdef.viewangles[ROLL] += side; + side = V_CalcRoll(cl_entities[cl.viewentity].angles, cl.velocity); + r_refdef.viewangles[ROLL] += side; - if (v_dmg_time > 0) - { - r_refdef.viewangles[ROLL] += v_dmg_time/v_kicktime.value*v_dmg_roll; - r_refdef.viewangles[PITCH] += v_dmg_time/v_kicktime.value*v_dmg_pitch; - v_dmg_time -= host_frametime; - } + if (v_dmg_time > 0) { + r_refdef.viewangles[ROLL] += v_dmg_time / v_kicktime.value * v_dmg_roll; + r_refdef.viewangles[PITCH] += v_dmg_time / v_kicktime.value * v_dmg_pitch; + v_dmg_time -= host_frametime; + } - if (cl.stats[STAT_HEALTH] <= 0) - { - r_refdef.viewangles[ROLL] = 80; // dead view angle - return; - } + if (cl.stats[STAT_HEALTH] <= 0) { + r_refdef.viewangles[ROLL] = 80; // dead view angle + return; + } } /* @@ -712,25 +659,24 @@ V_CalcIntermissionRefdef ================== */ -void V_CalcIntermissionRefdef (void) -{ - entity_t *ent, *view; - float old; +void V_CalcIntermissionRefdef(void) { + entity_t *ent, *view; + float old; -// ent is the player model (visible when out of body) - ent = &cl_entities[cl.viewentity]; -// view is the weapon model (only visible from inside body) - view = &cl.viewent; + // ent is the player model (visible when out of body) + ent = &cl_entities[cl.viewentity]; + // view is the weapon model (only visible from inside body) + view = &cl.viewent; - VectorCopy (ent->origin, r_refdef.vieworg); - VectorCopy (ent->angles, r_refdef.viewangles); - view->model = NULL; + VectorCopy(ent->origin, r_refdef.vieworg); + VectorCopy(ent->angles, r_refdef.viewangles); + view->model = NULL; -// allways idle in intermission - old = v_idlescale.value; - v_idlescale.value = 1; - V_AddIdle (); - v_idlescale.value = old; + // allways idle in intermission + old = v_idlescale.value; + v_idlescale.value = 1; + V_AddIdle(); + v_idlescale.value = old; } /* @@ -738,144 +684,138 @@ void V_CalcIntermissionRefdef (void) V_CalcRefdef ================== */ -void V_CalcRefdef (void) -{ - entity_t *ent, *view; - int i; - vec3_t forward, right, up; - vec3_t angles; - float bob; - static float oldz = 0; - static vec3_t punch = {0,0,0}; //johnfitz -- v_gunkick - float delta; //johnfitz -- v_gunkick +void V_CalcRefdef(void) { + entity_t *ent, *view; + int i; + vec3_t forward, right, up; + vec3_t angles; + float bob; + static float oldz = 0; + static vec3_t punch = {0, 0, 0}; //johnfitz -- v_gunkick + float delta; //johnfitz -- v_gunkick - V_DriftPitch (); + V_DriftPitch(); -// ent is the player model (visible when out of body) - ent = &cl_entities[cl.viewentity]; -// view is the weapon model (only visible from inside body) - view = &cl.viewent; + // ent is the player model (visible when out of body) + ent = &cl_entities[cl.viewentity]; + // view is the weapon model (only visible from inside body) + view = &cl.viewent; -// transform the view offset by the model's matrix to get the offset from -// model origin for the view - ent->angles[YAW] = cl.viewangles[YAW]; // the model should face the view dir - ent->angles[PITCH] = -cl.viewangles[PITCH]; // the model should face the view dir + // transform the view offset by the model's matrix to get the offset from + // model origin for the view + ent->angles[YAW] = cl.viewangles[YAW]; // the model should face the view dir + ent->angles[PITCH] = -cl.viewangles[PITCH]; // the model should face the view dir - bob = V_CalcBob (); + bob = V_CalcBob(); -// refresh position - VectorCopy (ent->origin, r_refdef.vieworg); - r_refdef.vieworg[2] += cl.viewheight + bob; + // refresh position + VectorCopy(ent->origin, r_refdef.vieworg); + r_refdef.vieworg[2] += cl.viewheight + bob; -// never let it sit exactly on a node line, because a water plane can -// dissapear when viewed with the eye exactly on it. -// the server protocol only specifies to 1/16 pixel, so add 1/32 in each axis - r_refdef.vieworg[0] += 1.0/32; - r_refdef.vieworg[1] += 1.0/32; - r_refdef.vieworg[2] += 1.0/32; + // never let it sit exactly on a node line, because a water plane can + // dissapear when viewed with the eye exactly on it. + // the server protocol only specifies to 1/16 pixel, so add 1/32 in each axis + r_refdef.vieworg[0] += 1.0 / 32; + r_refdef.vieworg[1] += 1.0 / 32; + r_refdef.vieworg[2] += 1.0 / 32; - VectorCopy (cl.viewangles, r_refdef.viewangles); - V_CalcViewRoll (); - V_AddIdle (); + VectorCopy(cl.viewangles, r_refdef.viewangles); + V_CalcViewRoll(); + V_AddIdle(); -// offsets - angles[PITCH] = -ent->angles[PITCH]; // because entity pitches are actually backward - angles[YAW] = ent->angles[YAW]; - angles[ROLL] = ent->angles[ROLL]; + // offsets + angles[PITCH] = -ent->angles[PITCH]; // because entity pitches are actually backward + angles[YAW] = ent->angles[YAW]; + angles[ROLL] = ent->angles[ROLL]; - AngleVectors (angles, forward, right, up); + AngleVectors(angles, forward, right, up); - if (cl.maxclients <= 1) //johnfitz -- moved cheat-protection here from V_RenderView - for (i=0 ; i<3 ; i++) - r_refdef.vieworg[i] += scr_ofsx.value*forward[i] + scr_ofsy.value*right[i] + scr_ofsz.value*up[i]; + if (cl.maxclients <= 1) //johnfitz -- moved cheat-protection here from V_RenderView + for (i = 0; i < 3; i++) + r_refdef.vieworg[i] += scr_ofsx.value * forward[i] + scr_ofsy.value * right[i] + scr_ofsz.value * up[i]; - V_BoundOffsets (); + V_BoundOffsets(); -// set up gun position - VectorCopy (cl.viewangles, view->angles); + // set up gun position + VectorCopy(cl.viewangles, view->angles); - CalcGunAngle (); + CalcGunAngle(); - VectorCopy (ent->origin, view->origin); - view->origin[2] += cl.viewheight; + VectorCopy(ent->origin, view->origin); + view->origin[2] += cl.viewheight; - for (i=0 ; i<3 ; i++) - view->origin[i] += forward[i]*bob*0.4; - view->origin[2] += bob; + for (i = 0; i < 3; i++) + view->origin[i] += forward[i] * bob * 0.4; + view->origin[2] += bob; - //johnfitz -- removed all gun position fudging code (was used to keep gun from getting covered by sbar) - //MarkV -- restored this with r_viewmodel_quake cvar - if (r_viewmodel_quake.value) - { - if (scr_viewsize.value == 110) - view->origin[2] += 1; - else if (scr_viewsize.value == 100) - view->origin[2] += 2; - else if (scr_viewsize.value == 90) - view->origin[2] += 1; - else if (scr_viewsize.value == 80) - view->origin[2] += 0.5; - } + //johnfitz -- removed all gun position fudging code (was used to keep gun from getting covered by sbar) + //MarkV -- restored this with r_viewmodel_quake cvar + if (r_viewmodel_quake.value) { + if (scr_viewsize.value == 110) + view->origin[2] += 1; + else if (scr_viewsize.value == 100) + view->origin[2] += 2; + else if (scr_viewsize.value == 90) + view->origin[2] += 1; + else if (scr_viewsize.value == 80) + view->origin[2] += 0.5; + } - if (ent->lerpflags & LERP_FINISH) - { - view->lerpflags |= LERP_FINISH; - view->lerpfinish = ent->lerpfinish; - } - else - view->lerpflags &= ~LERP_FINISH; + if (ent->lerpflags & LERP_FINISH) { + view->lerpflags |= LERP_FINISH; + view->lerpfinish = ent->lerpfinish; + } else + view->lerpflags &= ~LERP_FINISH; - view->model = cl.model_precache[cl.stats[STAT_WEAPON]]; - view->frame = cl.stats[STAT_WEAPONFRAME]; - view->colormap = vid.colormap; - view->scale = ENTSCALE_DEFAULT; + view->model = cl.model_precache[cl.stats[STAT_WEAPON]]; + view->frame = cl.stats[STAT_WEAPONFRAME]; + view->colormap = vid.colormap; + view->scale = ENTSCALE_DEFAULT; -//johnfitz -- v_gunkick - if (v_gunkick.value == 1) //original quake kick - VectorAdd (r_refdef.viewangles, cl.punchangle, r_refdef.viewangles); - if (v_gunkick.value == 2) //lerped kick - { - for (i=0; i<3; i++) - if (punch[i] != v_punchangles[0][i]) - { - //speed determined by how far we need to lerp in 1/10th of a second - delta = (v_punchangles[0][i]-v_punchangles[1][i]) * host_frametime * 10; + //johnfitz -- v_gunkick + if (v_gunkick.value == 1) //original quake kick + VectorAdd(r_refdef.viewangles, cl.punchangle, r_refdef.viewangles); + if (v_gunkick.value == 2) //lerped kick + { + for (i = 0; i < 3; i++) + if (punch[i] != v_punchangles[0][i]) { + //speed determined by how far we need to lerp in 1/10th of a second + delta = (v_punchangles[0][i] - v_punchangles[1][i]) * host_frametime * 10; - if (delta > 0) - punch[i] = q_min(punch[i]+delta, v_punchangles[0][i]); - else if (delta < 0) - punch[i] = q_max(punch[i]+delta, v_punchangles[0][i]); - } + if (delta > 0) + punch[i] = std::min(punch[i]+delta, v_punchangles[0][i]); + else if (delta < 0) + punch[i] = std::max(punch[i]+delta, v_punchangles[0][i]); + } - VectorAdd (r_refdef.viewangles, punch, r_refdef.viewangles); - } -//johnfitz + VectorAdd(r_refdef.viewangles, punch, r_refdef.viewangles); + } + //johnfitz -// smooth out stair step ups - if (!noclip_anglehack && cl.onground && ent->origin[2] - oldz > 0) //johnfitz -- added exception for noclip - //FIXME: noclip_anglehack is set on the server, so in a nonlocal game this won't work. - { - float steptime; + // smooth out stair step ups + if (!noclip_anglehack && cl.onground && ent->origin[2] - oldz > 0) //johnfitz -- added exception for noclip + //FIXME: noclip_anglehack is set on the server, so in a nonlocal game this won't work. + { + float steptime; - steptime = cl.time - cl.oldtime; - if (steptime < 0) - //FIXME I_Error ("steptime < 0"); - steptime = 0; + steptime = cl.time - cl.oldtime; + if (steptime < 0) + //FIXME I_Error ("steptime < 0"); + steptime = 0; - oldz += steptime * 80; - if (oldz > ent->origin[2]) - oldz = ent->origin[2]; - if (ent->origin[2] - oldz > 12) - oldz = ent->origin[2] - 12; - r_refdef.vieworg[2] += oldz - ent->origin[2]; - view->origin[2] += oldz - ent->origin[2]; - } - else - oldz = ent->origin[2]; + oldz += steptime * 80; + if (oldz > ent->origin[2]) + oldz = ent->origin[2]; + if (ent->origin[2] - oldz > 12) + oldz = ent->origin[2] - 12; + r_refdef.vieworg[2] += oldz - ent->origin[2]; + view->origin[2] += oldz - ent->origin[2]; + } else + oldz = ent->origin[2]; - if (chase_active.value) - Chase_UpdateForDrawing (); //johnfitz + if (chase_active.value) + Chase_UpdateForDrawing(); //johnfitz } /* @@ -886,10 +826,9 @@ Resets the viewentity angles to the last values received from the server (undoing the manual adjustments performed by V_CalcRefdef) ================== */ -void V_RestoreAngles (void) -{ - entity_t *ent = &cl_entities[cl.viewentity]; - VectorCopy (ent->msg_angles[0], ent->angles); +void V_RestoreAngles(void) { + entity_t *ent = &cl_entities[cl.viewentity]; + VectorCopy(ent->msg_angles[0], ent->angles); } /* @@ -900,23 +839,22 @@ The player's clipping box goes from (-16 -16 -24) to (16 16 32) from the entity origin, so any view position inside that will be valid ================== */ -extern vrect_t scr_vrect; +extern vrect_t scr_vrect; -void V_RenderView (void) -{ - if (con_forcedup) - return; +void V_RenderView(void) { + if (con_forcedup) + return; - if (cl.intermission) - V_CalcIntermissionRefdef (); - else if (!cl.paused /* && (cl.maxclients > 1 || key_dest == key_game) */) - V_CalcRefdef (); + if (cl.intermission) + V_CalcIntermissionRefdef(); + else if (!cl.paused /* && (cl.maxclients > 1 || key_dest == key_game) */) + V_CalcRefdef(); - //johnfitz -- removed lcd code + //johnfitz -- removed lcd code - R_RenderView (); + R_RenderView(); - V_PolyBlend (); //johnfitz -- moved here from R_Renderview (); + V_PolyBlend(); //johnfitz -- moved here from R_Renderview (); } /* @@ -932,44 +870,42 @@ void V_RenderView (void) V_Init ============= */ -void V_Init (void) -{ - Cmd_AddCommand ("v_cshift", V_cshift_f); - Cmd_AddCommand ("bf", V_BonusFlash_f); - Cmd_AddCommand ("centerview", V_StartPitchDrift); +void V_Init(void) { + command::add("v_cshift", V_cshift_f); + command::add("bf", V_BonusFlash_f); + command::add("centerview", V_StartPitchDrift); - Cvar_RegisterVariable (&v_centermove); - Cvar_RegisterVariable (&v_centerspeed); + v_centermove.inscribe(); + v_centerspeed.inscribe(); - Cvar_RegisterVariable (&v_iyaw_cycle); - Cvar_RegisterVariable (&v_iroll_cycle); - Cvar_RegisterVariable (&v_ipitch_cycle); - Cvar_RegisterVariable (&v_iyaw_level); - Cvar_RegisterVariable (&v_iroll_level); - Cvar_RegisterVariable (&v_ipitch_level); + v_iyaw_cycle.inscribe(); + v_iroll_cycle.inscribe(); + v_ipitch_cycle.inscribe(); + v_iyaw_level.inscribe(); + v_iroll_level.inscribe(); + v_ipitch_level.inscribe(); - Cvar_RegisterVariable (&v_idlescale); - Cvar_RegisterVariable (&crosshair); - Cvar_RegisterVariable (&gl_cshiftpercent); - Cvar_RegisterVariable (&gl_cshiftpercent_contents); // QuakeSpasm - Cvar_RegisterVariable (&gl_cshiftpercent_damage); // QuakeSpasm - Cvar_RegisterVariable (&gl_cshiftpercent_bonus); // QuakeSpasm - Cvar_RegisterVariable (&gl_cshiftpercent_powerup); // QuakeSpasm + v_idlescale.inscribe(); + crosshair.inscribe(); + gl_cshiftpercent.inscribe(); + gl_cshiftpercent_contents.inscribe(); // QuakeSpasm + gl_cshiftpercent_damage.inscribe(); // QuakeSpasm + gl_cshiftpercent_bonus.inscribe(); // QuakeSpasm + gl_cshiftpercent_powerup.inscribe(); // QuakeSpasm - Cvar_RegisterVariable (&scr_ofsx); - Cvar_RegisterVariable (&scr_ofsy); - Cvar_RegisterVariable (&scr_ofsz); - Cvar_RegisterVariable (&cl_rollspeed); - Cvar_RegisterVariable (&cl_rollangle); - Cvar_RegisterVariable (&cl_bob); - Cvar_RegisterVariable (&cl_bobcycle); - Cvar_RegisterVariable (&cl_bobup); + scr_ofsx.inscribe(); + scr_ofsy.inscribe(); + scr_ofsz.inscribe(); + cl_rollspeed.inscribe(); + cl_rollangle.inscribe(); + cl_bob.inscribe(); + cl_bobcycle.inscribe(); + cl_bobup.inscribe(); - Cvar_RegisterVariable (&v_kicktime); - Cvar_RegisterVariable (&v_kickroll); - Cvar_RegisterVariable (&v_kickpitch); - Cvar_RegisterVariable (&v_gunkick); //johnfitz + v_kicktime.inscribe(); + v_kickroll.inscribe(); + v_kickpitch.inscribe(); + v_gunkick.inscribe(); //johnfitz - Cvar_RegisterVariable (&r_viewmodel_quake); //MarkV + r_viewmodel_quake.inscribe(); //MarkV } - diff --git a/Quake/view.hpp b/Quake/view.hpp index 32d683b..05009db 100644 --- a/Quake/view.hpp +++ b/Quake/view.hpp @@ -23,8 +23,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #ifndef _QUAKE_VIEW_H #define _QUAKE_VIEW_H -extern cvar_t vid_gamma; -extern cvar_t vid_contrast; +extern convar vid_gamma; +extern convar vid_contrast; extern float v_blend[4]; diff --git a/Quake/zone.cpp b/Quake/zone.cpp index 37044ca..66d16b1 100644 --- a/Quake/zone.cpp +++ b/Quake/zone.cpp @@ -238,7 +238,7 @@ void *Z_Realloc(void *ptr, int size) Sys_Error ("Z_Realloc: failed on allocation of %i bytes", size); if (ptr != old_ptr) - memmove (ptr, old_ptr, q_min(old_size, size)); + memmove (ptr, old_ptr, std::min(old_size, size)); if (old_size < size) memset ((byte *)ptr + old_size, 0, size - old_size); @@ -838,7 +838,7 @@ void Cache_Init (void) cache_head.next = cache_head.prev = &cache_head; cache_head.lru_next = cache_head.lru_prev = &cache_head; - Cmd_AddCommand ("flush", Cache_Flush); + command::add ("flush", Cache_Flush); } /* @@ -984,6 +984,6 @@ void Memory_Init (void *buf, int size) mainzone = (memzone_t *) Hunk_AllocName (zonesize, "zone" ); Memory_InitZone (mainzone, zonesize); - Cmd_AddCommand ("hunk_print", Hunk_Print_f); //johnfitz + command::add ("hunk_print", Hunk_Print_f); //johnfitz }