Even more conversion, lots of superfluous macro removal

This commit is contained in:
iikorni
2026-08-29 23:14:23 -05:00
parent 70e5c02355
commit de75b014b3
102 changed files with 7060 additions and 8179 deletions
+60 -19
View File
@@ -27,20 +27,15 @@
</configurations> </configurations>
</component> </component>
<component name="ChangeListManager"> <component name="ChangeListManager">
<list default="true" id="f5455ea3-1ba8-4b1e-84ce-0eab50a09cdc" name="Changes" comment="Begin converting QS engine to CPP"> <list default="true" id="f5455ea3-1ba8-4b1e-84ce-0eab50a09cdc" name="Changes" comment="More conversion">
<change afterPath="$PROJECT_DIR$/.idea/dictionaries/project.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/Quake/convar.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/editor.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/editor.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/vcs.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/vcs.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/CMakeLists.txt" beforeDir="false" afterPath="$PROJECT_DIR$/CMakeLists.txt" afterDir="false" /> <change beforePath="$PROJECT_DIR$/CMakeLists.txt" beforeDir="false" afterPath="$PROJECT_DIR$/CMakeLists.txt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Misc/fix_externaltex.patch" beforeDir="false" afterPath="$PROJECT_DIR$/Misc/fix_externaltex.patch" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/bgmusic.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/bgmusic.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/bgmusic.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/bgmusic.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/bgmusic.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/bgmusic.hpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/bgmusic.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/bgmusic.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/cd_null.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/cd_null.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/cd_sdl.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/cd_sdl.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/cd_sdl.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/cd_sdl.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/cdaudio.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/cdaudio.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/cfgfile.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/cfgfile.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/cfgfile.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/cfgfile.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/chase.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/chase.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/cl_demo.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/cl_demo.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/cl_input.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/cl_input.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/cl_input.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/cl_input.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/cl_main.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/cl_main.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/cl_main.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/cl_main.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/cl_parse.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/cl_parse.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/cl_parse.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/cl_parse.cpp" afterDir="false" />
@@ -50,13 +45,14 @@
<change beforePath="$PROJECT_DIR$/Quake/common.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/common.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/common.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/common.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/common.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/common.hpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/common.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/common.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/console.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/console.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/console.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/console.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/cvar.cpp" beforeDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/console.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/console.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/cvar.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/convar.hpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/convar.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/convar.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/convar.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/convar.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/default_cfg.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/default_cfg.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/gl_draw.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/gl_draw.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/gl_draw.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/gl_draw.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/gl_fog.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/gl_fog.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/gl_fog.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/gl_fog.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/gl_model.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/gl_model.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/gl_model.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/gl_model.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/gl_refrag.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/gl_refrag.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/gl_model.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/gl_model.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/gl_rlight.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/gl_rlight.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/gl_rmain.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/gl_rmain.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/gl_rmain.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/gl_rmain.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/gl_rmisc.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/gl_rmisc.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/gl_rmisc.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/gl_rmisc.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/gl_screen.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/gl_screen.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/gl_screen.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/gl_screen.cpp" afterDir="false" />
@@ -67,37 +63,73 @@
<change beforePath="$PROJECT_DIR$/Quake/glquake.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/glquake.hpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/glquake.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/glquake.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/host.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/host.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/host.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/host.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/host_cmd.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/host_cmd.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/host_cmd.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/host_cmd.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/image.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/image.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/image.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/image.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/in_sdl.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/in_sdl.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/in_sdl.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/in_sdl.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/input.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/input.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/keys.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/keys.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/keys.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/keys.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/keys.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/keys.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/main_sdl.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/main_sdl.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/menu.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/menu.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/menu.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/menu.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/menu.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/menu.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/net.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/net.hpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/net.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/net.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/net_bsd.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/net_bsd.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/net_defs.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/net_defs.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/net_dgrm.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/net_dgrm.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/net_dgrm.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/net_dgrm.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/net_dgrm.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/net_dgrm.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/net_loop.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/net_loop.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/net_loop.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/net_loop.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/net_main.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/net_main.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/net_main.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/net_main.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/pl_linux.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/pl_linux.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/net_udp.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/net_udp.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/pl_osx.m" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/pl_osx.m" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/net_udp.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/net_udp.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/pl_win.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/pl_win.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/net_wins.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/net_wins.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/net_wins.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/net_wins.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/net_wipx.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/net_wipx.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/net_wipx.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/net_wipx.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/pr_cmds.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/pr_cmds.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/pr_cmds.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/pr_cmds.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/pr_edict.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/pr_edict.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/pr_edict.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/pr_edict.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/pr_exec.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/pr_exec.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/progs.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/progs.hpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/progs.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/progs.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/protocol.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/protocol.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/q_sound.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/q_sound.hpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/q_sound.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/q_sound.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/q_stdinc.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/q_stdinc.hpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/q_stdinc.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/q_stdinc.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/quakedef.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/quakedef.hpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/quakedef.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/quakedef.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/r_alias.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/r_alias.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/r_alias.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/r_alias.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/r_brush.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/r_brush.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/r_part.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/r_part.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/r_part.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/r_part.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/r_world.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/r_world.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/r_world.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/r_world.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/render.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/render.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/sbar.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/sbar.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/sbar.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/sbar.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/screen.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/screen.hpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/screen.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/screen.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/server.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/server.hpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/server.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/server.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/snd_codec.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/snd_codec.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/snd_codec.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/snd_codec.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/snd_codeci.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/snd_codeci.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/snd_dma.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/snd_dma.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/snd_dma.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/snd_dma.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/snd_flac.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/snd_flac.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/snd_mikmod.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/snd_mikmod.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/snd_mix.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/snd_mix.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/snd_modplug.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/snd_modplug.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/snd_mp3.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/snd_mp3.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/snd_mp3.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/snd_mp3.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/snd_mp3tag.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/snd_mp3tag.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/snd_mpg123.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/snd_mpg123.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/snd_opus.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/snd_opus.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/snd_sdl.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/snd_sdl.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/snd_umx.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/snd_umx.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/snd_vorbis.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/snd_vorbis.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/snd_wave.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/snd_wave.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/snd_xmp.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/snd_xmp.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/sv_main.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/sv_main.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/sv_main.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/sv_main.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/sv_move.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/sv_move.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/sv_phys.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/sv_phys.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/sv_phys.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/sv_phys.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/sv_user.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/sv_user.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/sv_user.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/sv_user.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/sys_sdl_unix.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/sys_sdl_unix.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/sys_sdl_unix.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/sys_sdl_unix.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/sys_sdl_win.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/sys_sdl_win.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/vid.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/vid.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/view.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/view.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/view.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/view.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/view.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/view.hpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/world.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/world.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/world.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/world.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/zone.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/zone.cpp" afterDir="false" /> <change beforePath="$PROJECT_DIR$/Quake/zone.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/zone.cpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Quake/zone.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/Quake/zone.hpp" afterDir="false" />
</list> </list>
<option name="SHOW_DIALOG" value="false" /> <option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_CONFLICTS" value="true" />
@@ -148,7 +180,7 @@
"cidr.known.project.marker": "true", "cidr.known.project.marker": "true",
"codeWithMe.voiceChat.enabledByDefault": "false", "codeWithMe.voiceChat.enabledByDefault": "false",
"git-widget-placeholder": "master", "git-widget-placeholder": "master",
"last_opened_file_path": "/home/iikorni/Downloads/DOOM-master/linuxdoom-1.10", "last_opened_file_path": "/home/iikorni/Downloads/quakespasm-0.96.3/cmake-build-debug/id1",
"node.js.detected.package.eslint": "true", "node.js.detected.package.eslint": "true",
"node.js.detected.package.jshint": "true", "node.js.detected.package.jshint": "true",
"node.js.detected.package.tslint": "true", "node.js.detected.package.tslint": "true",
@@ -159,11 +191,19 @@
} }
}]]></component> }]]></component>
<component name="RecentsManager"> <component name="RecentsManager">
<key name="CopyFile.RECENT_KEYS">
<recent name="$PROJECT_DIR$/cmake-build-debug/id1" />
</key>
<key name="MoveFile.RECENT_KEYS"> <key name="MoveFile.RECENT_KEYS">
<recent name="$PROJECT_DIR$/cmake-build-debug" /> <recent name="$PROJECT_DIR$/cmake-build-debug" />
</key> </key>
</component> </component>
<component name="RunManager"> <component name="RunManager">
<configuration default="true" type="CMakeRunConfiguration" factoryName="Application" REDIRECT_INPUT="false" ELEVATE="false" USE_EXTERNAL_CONSOLE="false" EMULATE_TERMINAL="false" PASS_PARENT_ENVS_2="true">
<method v="2">
<option name="com.jetbrains.cidr.execution.CidrBuildBeforeRunTaskProvider$BuildBeforeRunTask" enabled="true" />
</method>
</configuration>
<configuration name="quakespasm" type="CMakeRunConfiguration" factoryName="Application" REDIRECT_INPUT="false" ELEVATE="false" USE_EXTERNAL_CONSOLE="false" EMULATE_TERMINAL="false" PASS_PARENT_ENVS_2="true" PROJECT_NAME="quakespasm" TARGET_NAME="quakespasm" CONFIG_NAME="Debug" RUN_TARGET_PROJECT_NAME="quakespasm" RUN_TARGET_NAME="quakespasm"> <configuration name="quakespasm" type="CMakeRunConfiguration" factoryName="Application" REDIRECT_INPUT="false" ELEVATE="false" USE_EXTERNAL_CONSOLE="false" EMULATE_TERMINAL="false" PASS_PARENT_ENVS_2="true" PROJECT_NAME="quakespasm" TARGET_NAME="quakespasm" CONFIG_NAME="Debug" RUN_TARGET_PROJECT_NAME="quakespasm" RUN_TARGET_NAME="quakespasm">
<method v="2"> <method v="2">
<option name="com.jetbrains.cidr.execution.CidrBuildBeforeRunTaskProvider$BuildBeforeRunTask" enabled="true" /> <option name="com.jetbrains.cidr.execution.CidrBuildBeforeRunTaskProvider$BuildBeforeRunTask" enabled="true" />
@@ -214,6 +254,7 @@
</component> </component>
<component name="VcsManagerConfiguration"> <component name="VcsManagerConfiguration">
<MESSAGE value="Begin converting QS engine to CPP" /> <MESSAGE value="Begin converting QS engine to CPP" />
<option name="LAST_COMMIT_MESSAGE" value="Begin converting QS engine to CPP" /> <MESSAGE value="More conversion" />
<option name="LAST_COMMIT_MESSAGE" value="More conversion" />
</component> </component>
</project> </project>
+2
View File
@@ -16,3 +16,5 @@ target_link_libraries(quakespasm vorbis)
target_link_libraries(quakespasm ogg) target_link_libraries(quakespasm ogg)
target_link_libraries(quakespasm mad) target_link_libraries(quakespasm mad)
target_link_libraries(quakespasm m) target_link_libraries(quakespasm m)
add_compile_definitions(USE_CODEC_VORBIS)
+285 -318
View File
@@ -26,76 +26,102 @@
#include "snd_codec.hpp" #include "snd_codec.hpp"
#include "bgmusic.hpp" #include "bgmusic.hpp"
#include <vector>
#define MUSIC_DIRNAME "music" #define MUSIC_DIRNAME "music"
qboolean bgmloop;
convar bgm_extmusic{"bgm_extmusic", "1", {.archive = true}};
static qboolean no_extmusic= false;
static float old_volume = -1.0f;
typedef enum _bgm_player
{
BGM_NONE = -1,
BGM_MIDIDRV = 1,
BGM_STREAMER
} bgm_player_t;
typedef struct music_handler_s
{
unsigned int type; /* 1U << n (see snd_codec.h) */
bgm_player_t player; /* Enumerated bgm player type */
int is_available; /* -1 means not present */
const char *ext; /* Expected file extension */
const char *dir; /* Where to look for music file */
struct music_handler_s *next;
} music_handler_t;
static music_handler_t wanted_handlers[] =
{
{ CODECTYPE_VORBIS,BGM_STREAMER,-1, "ogg", MUSIC_DIRNAME, NULL },
{ CODECTYPE_OPUS, BGM_STREAMER, -1, "opus", MUSIC_DIRNAME, NULL },
{ CODECTYPE_MP3, BGM_STREAMER, -1, "mp3", MUSIC_DIRNAME, NULL },
{ CODECTYPE_FLAC, BGM_STREAMER, -1, "flac", MUSIC_DIRNAME, NULL },
{ CODECTYPE_WAV, BGM_STREAMER, -1, "wav", MUSIC_DIRNAME, NULL },
{ CODECTYPE_MOD, BGM_STREAMER, -1, "it", MUSIC_DIRNAME, NULL },
{ CODECTYPE_MOD, BGM_STREAMER, -1, "s3m", MUSIC_DIRNAME, NULL },
{ CODECTYPE_MOD, BGM_STREAMER, -1, "xm", MUSIC_DIRNAME, NULL },
{ CODECTYPE_MOD, BGM_STREAMER, -1, "mod", MUSIC_DIRNAME, NULL },
{ CODECTYPE_UMX, BGM_STREAMER, -1, "umx", MUSIC_DIRNAME, NULL },
{ CODECTYPE_NONE, BGM_NONE, -1, NULL, NULL, NULL }
};
static music_handler_t *music_handlers = NULL;
#define ANY_CODECTYPE 0xFFFFFFFF
#define CDRIP_TYPES (CODECTYPE_VORBIS | CODECTYPE_MP3 | CODECTYPE_FLAC | CODECTYPE_WAV | CODECTYPE_OPUS) #define CDRIP_TYPES (CODECTYPE_VORBIS | CODECTYPE_MP3 | CODECTYPE_FLAC | CODECTYPE_WAV | CODECTYPE_OPUS)
#define CDRIPTYPE(x) (((x) & CDRIP_TYPES) != 0) #define CDRIPTYPE(x) (((x) & CDRIP_TYPES) != 0)
static snd_stream_t *bgmstream = NULL; namespace music {
bool bgmloop;
convar bgm_extmusic{"bgm_extmusic", "1", {.archive = true}};
static void BGM_Play_f (void) namespace {
snd_stream_t *bgmstream = nullptr;
bool no_extmusic = false;
float old_volume = -1.0f;
constexpr unsigned int ANY_CODECTYPE = 0xFFFFFFFF;
enum class player_kind {
none = -1,
midi_drv = 1,
streamer
};
struct handler {
unsigned int type; /* 1U << n (see snd_codec.h) */
player_kind player; /* Enumerated bgm player type */
int is_available; /* -1 means not present */
const char *ext; /* Expected file extension */
const char *dir; /* Where to look for music file */
};
std::vector<handler> active_handlers{};
std::array wanted_handlers =
{ {
handler{
.type = CODECTYPE_VORBIS, .player = player_kind::streamer, .is_available = -1, .ext = "ogg",
.dir = MUSIC_DIRNAME
},
handler{
.type = CODECTYPE_OPUS, .player = player_kind::streamer, .is_available = -1, .ext = "opus",
.dir = MUSIC_DIRNAME
},
handler{
.type = CODECTYPE_MP3, .player = player_kind::streamer, .is_available = -1, .ext = "mp3",
.dir = MUSIC_DIRNAME
},
handler{
.type = CODECTYPE_FLAC, .player = player_kind::streamer, .is_available = -1, .ext = "flac",
.dir = MUSIC_DIRNAME
},
handler{
.type = CODECTYPE_WAV, .player = player_kind::streamer, .is_available = -1, .ext = "wav",
.dir = MUSIC_DIRNAME
},
handler{
.type = CODECTYPE_MOD, .player = player_kind::streamer, .is_available = -1, .ext = "it", .dir = MUSIC_DIRNAME
},
handler{
.type = CODECTYPE_MOD, .player = player_kind::streamer, .is_available = -1, .ext = "s3m",
.dir = MUSIC_DIRNAME
},
handler{
.type = CODECTYPE_MOD, .player = player_kind::streamer, .is_available = -1, .ext = "xm", .dir = MUSIC_DIRNAME
},
handler{
.type = CODECTYPE_MOD, .player = player_kind::streamer, .is_available = -1, .ext = "mod",
.dir = MUSIC_DIRNAME
},
handler{
.type = CODECTYPE_UMX, .player = player_kind::streamer, .is_available = -1, .ext = "umx",
.dir = MUSIC_DIRNAME
},
handler{.type = CODECTYPE_NONE, .player = player_kind::none, .is_available = -1, .ext = nullptr, .dir = nullptr}
};
void _play() {
if (command::argc() == 2) { if (command::argc() == 2) {
BGM_Play (command::argv(1)->c_str()); play(*command::argv(1));
} } else {
else {
Con_Printf("music <musicfile>\n"); Con_Printf("music <musicfile>\n");
} }
} }
static void BGM_Pause_f (void) void _pause() {
{ pause();
BGM_Pause ();
} }
static void BGM_Resume_f (void) void _resume() {
{ resume();
BGM_Resume ();
} }
static void BGM_Loop_f (void) void _loop() {
{
if (command::argc() == 2) { if (command::argc() == 2) {
if (q_strcasecmp(command::argv(1)->c_str(), "0") == 0 || if (q_strcasecmp(command::argv(1)->c_str(), "0") == 0 ||
q_strcasecmp(command::argv(1)->c_str(), "off") == 0) q_strcasecmp(command::argv(1)->c_str(), "off") == 0)
@@ -115,286 +141,71 @@ static void BGM_Loop_f (void)
Con_Printf("Music will not be looped\n"); Con_Printf("Music will not be looped\n");
} }
static void BGM_Stop_f (void) void _stop() {
{ stop();
BGM_Stop();
} }
static void BGM_Jump_f (void) void _jump() {
{
if (command::argc() != 2) { if (command::argc() != 2) {
Con_Printf("music_jump <ordernum>\n"); Con_Printf("music_jump <ordernum>\n");
} } else if (bgmstream) {
else if (bgmstream) { S_CodecJumpToOrder(bgmstream, static_cast<int>(std::strtol(command::argv(1)->c_str(), nullptr, 10)));
S_CodecJumpToOrder(bgmstream, atoi(command::argv(1)->c_str()));
} }
} }
qboolean BGM_Init (void) void play_noext(const std::string &filename, const unsigned int allowed_types) {
{
music_handler_t *handlers = NULL;
int i;
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;
bgmloop = true;
for (i = 0; wanted_handlers[i].type != CODECTYPE_NONE; i++)
{
switch (wanted_handlers[i].player)
{
case BGM_MIDIDRV:
/* not supported in quake */
break;
case BGM_STREAMER:
wanted_handlers[i].is_available =
S_CodecIsAvailable(wanted_handlers[i].type);
break;
case BGM_NONE:
default:
break;
}
if (wanted_handlers[i].is_available != -1)
{
if (handlers)
{
handlers->next = &wanted_handlers[i];
handlers = handlers->next;
}
else
{
music_handlers = &wanted_handlers[i];
handlers = music_handlers;
}
}
}
return true;
}
void BGM_Shutdown (void)
{
BGM_Stop();
/* sever our connections to
* midi_drv and snd_codec */
music_handlers = NULL;
}
static void BGM_Play_noext (const char *filename, unsigned int allowed_types)
{
char tmp[MAX_QPATH]; char tmp[MAX_QPATH];
music_handler_t *handler;
handler = music_handlers; for (auto &handler: active_handlers) {
while (handler) if (!(handler.type & allowed_types)) {
{
if (! (handler->type & allowed_types))
{
handler = handler->next;
continue; continue;
} }
if (!handler->is_available) if (!handler.is_available) {
{
handler = handler->next;
continue; continue;
} }
q_snprintf(tmp, sizeof(tmp), "%s/%s.%s", q_snprintf(tmp, sizeof(tmp), "%s/%s.%s",
handler->dir, filename, handler->ext); handler.dir, filename.c_str(), handler.ext);
switch (handler->player) switch (handler.player) {
{ case player_kind::midi_drv:
case BGM_MIDIDRV:
/* not supported in quake */ /* not supported in quake */
break; break;
case BGM_STREAMER: case player_kind::streamer:
bgmstream = S_CodecOpenStreamType(tmp, handler->type, bgmloop); bgmstream = S_CodecOpenStreamType(tmp, handler.type, bgmloop);
if (bgmstream) if (bgmstream)
return; /* success */ return; /* success */
break; break;
case BGM_NONE: case player_kind::none:
default: default:
break; break;
} }
handler = handler->next;
} }
Con_Printf("Couldn't handle music file %s\n", filename); Con_Printf("Couldn't handle music file %s\n", filename.c_str());
} }
void BGM_Play (const char *filename) void update_stream() {
{ bool did_rewind = false;
char tmp[MAX_QPATH];
const char *ext;
music_handler_t *handler;
BGM_Stop();
if (music_handlers == NULL)
return;
if (!filename || !*filename)
{
Con_DPrintf("null music file name\n");
return;
}
ext = COM_FileGetExtension(filename);
if (! *ext) /* try all things */
{
BGM_Play_noext(filename, ANY_CODECTYPE);
return;
}
handler = music_handlers;
while (handler)
{
if (handler->is_available &&
!q_strcasecmp(ext, handler->ext))
break;
handler = handler->next;
}
if (!handler)
{
Con_Printf("Unhandled extension for %s\n", filename);
return;
}
q_snprintf(tmp, sizeof(tmp), "%s/%s", handler->dir, filename);
switch (handler->player)
{
case BGM_MIDIDRV:
/* not supported in quake */
break;
case BGM_STREAMER:
bgmstream = S_CodecOpenStreamType(tmp, handler->type, bgmloop);
if (bgmstream)
return; /* success */
break;
case BGM_NONE:
default:
break;
}
Con_Printf("Couldn't handle music file %s\n", filename);
}
void BGM_PlayCDtrack (byte track, qboolean looping)
{
/* instead of searching by the order of music_handlers, do so by
* the order of searchpath priority: the file from the searchpath
* with the highest path_id is most likely from our own gamedir
* itself. This way, if a mod has track02 as a *.mp3 file, which
* is below *.ogg in the music_handler order, the mp3 will still
* have priority over track02.ogg from, say, id1.
*/
char tmp[MAX_QPATH];
const char *ext;
unsigned int path_id, prev_id, type;
music_handler_t *handler;
BGM_Stop();
if (CDAudio_Play(track, looping) == 0)
return; /* success */
if (music_handlers == NULL)
return;
if (no_extmusic || !bgm_extmusic.value)
return;
prev_id = 0;
type = 0;
ext = NULL;
handler = music_handlers;
while (handler)
{
if (! handler->is_available)
goto _next;
if (! CDRIPTYPE(handler->type))
goto _next;
q_snprintf(tmp, sizeof(tmp), "%s/track%02d.%s",
MUSIC_DIRNAME, (int)track, handler->ext);
if (! COM_FileExists(tmp, &path_id))
goto _next;
if (path_id > prev_id)
{
prev_id = path_id;
type = handler->type;
ext = handler->ext;
}
_next:
handler = handler->next;
}
if (ext == NULL)
Con_Printf("Couldn't find a cdrip for track %d\n", (int)track);
else
{
q_snprintf(tmp, sizeof(tmp), "%s/track%02d.%s",
MUSIC_DIRNAME, (int)track, ext);
bgmstream = S_CodecOpenStreamType(tmp, type, bgmloop);
if (! bgmstream)
Con_Printf("Couldn't handle music file %s\n", tmp);
}
}
void BGM_Stop (void)
{
if (bgmstream)
{
bgmstream->status = STREAM_NONE;
S_CodecCloseStream(bgmstream);
bgmstream = NULL;
s_rawend = 0;
}
}
void BGM_Pause (void)
{
if (bgmstream)
{
if (bgmstream->status == STREAM_PLAY)
bgmstream->status = STREAM_PAUSE;
}
}
void BGM_Resume (void)
{
if (bgmstream)
{
if (bgmstream->status == STREAM_PAUSE)
bgmstream->status = STREAM_PLAY;
}
}
static void BGM_UpdateStream (void)
{
qboolean did_rewind = false;
int res; /* Number of bytes read. */ int res; /* Number of bytes read. */
int bufferSamples; int bufferSamples;
int fileSamples; int fileSamples;
int fileBytes; int fileBytes;
byte raw[16384]; byte raw[16384];
if (bgmstream->status != STREAM_PLAY) if (bgmstream->status != STREAM_PLAY) {
return; return;
}
/* don't bother playing anything if musicvolume is 0 */ /* don't bother playing anything if musicvolume is 0 */
if (bgmvolume.value <= 0) if (bgmvolume.value <= 0) {
return; return;
}
/* see how many samples should be copied into the raw buffer */ /* see how many samples should be copied into the raw buffer */
if (s_rawend < paintedtime) if (s_rawend < paintedtime) {
s_rawend = paintedtime; s_rawend = paintedtime;
}
while (s_rawend < paintedtime + MAX_RAW_SAMPLES) while (s_rawend < paintedtime + MAX_RAW_SAMPLES) {
{
bufferSamples = MAX_RAW_SAMPLES - (s_rawend - paintedtime); bufferSamples = MAX_RAW_SAMPLES - (s_rawend - paintedtime);
/* decide how much data needs to be read from the file */ /* decide how much data needs to be read from the file */
@@ -404,8 +215,7 @@ static void BGM_UpdateStream (void)
/* our max buffer size */ /* our max buffer size */
fileBytes = fileSamples * (bgmstream->info.width * bgmstream->info.channels); fileBytes = fileSamples * (bgmstream->info.width * bgmstream->info.channels);
if (fileBytes > (int) sizeof(raw)) if (fileBytes > (int) sizeof(raw)) {
{
fileBytes = (int) sizeof(raw); fileBytes = (int) sizeof(raw);
fileSamples = fileBytes / fileSamples = fileBytes /
(bgmstream->info.width * bgmstream->info.channels); (bgmstream->info.width * bgmstream->info.channels);
@@ -413,8 +223,7 @@ static void BGM_UpdateStream (void)
/* Read */ /* Read */
res = S_CodecReadStream(bgmstream, fileBytes, raw); res = S_CodecReadStream(bgmstream, fileBytes, raw);
if (res < fileBytes) if (res < fileBytes) {
{
fileBytes = res; fileBytes = res;
fileSamples = res / (bgmstream->info.width * bgmstream->info.channels); fileSamples = res / (bgmstream->info.width * bgmstream->info.channels);
} }
@@ -426,46 +235,135 @@ static void BGM_UpdateStream (void)
bgmstream->info.channels, bgmstream->info.channels,
raw, bgmvolume.value); raw, bgmvolume.value);
did_rewind = false; did_rewind = false;
} } else if (res == 0) /* EOF */
else if (res == 0) /* EOF */
{
if (bgmloop)
{
if (did_rewind)
{ {
if (bgmloop) {
if (did_rewind) {
Con_Printf("Stream keeps returning EOF.\n"); Con_Printf("Stream keeps returning EOF.\n");
BGM_Stop(); stop();
return; return;
} }
res = S_CodecRewindStream(bgmstream); res = S_CodecRewindStream(bgmstream);
if (res != 0) if (res != 0) {
{
Con_Printf("Stream seek error (%i), stopping.\n", res); Con_Printf("Stream seek error (%i), stopping.\n", res);
BGM_Stop(); stop();
return; return;
} }
did_rewind = true; did_rewind = true;
} } else {
else stop();
{
BGM_Stop();
return; return;
} }
} } else /* res < 0: some read error */
else /* res < 0: some read error */
{ {
Con_Printf("Stream read error (%i), stopping.\n", res); Con_Printf("Stream read error (%i), stopping.\n", res);
BGM_Stop(); stop();
return; return;
} }
} }
} }
}
void BGM_Update (void) void init() {
{ bgm_extmusic.inscribe();
if (old_volume != bgmvolume.value) command::add("music", _play);
command::add("music_pause", _pause);
command::add("music_resume", _resume);
command::add("music_loop", _loop);
command::add("music_stop", _stop);
command::add("music_jump", _jump);
if (common::check_param("-noextmusic").has_value())
no_extmusic = true;
bgmloop = true;
for (auto i = 0; wanted_handlers[i].type != CODECTYPE_NONE; i++) {
switch (wanted_handlers[i].player) {
case player_kind::midi_drv:
/* not supported in quake */
break;
case player_kind::streamer:
wanted_handlers[i].is_available =
S_CodecIsAvailable(wanted_handlers[i].type);
break;
case player_kind::none:
default:
break;
}
if (wanted_handlers[i].is_available != -1) {
active_handlers.push_back(wanted_handlers[i]);
}
}
}
void shutdown() {
stop();
active_handlers.clear();
}
void play(const std::string &filename) {
char tmp[MAX_QPATH];
stop();
if (active_handlers.empty())
return;
if (filename.empty()) {
Con_DPrintf("null music file name\n");
return;
}
const char *ext = COM_FileGetExtension(filename.c_str());
if (*ext == '\0') /* try all things */
{ {
play_noext(filename, ANY_CODECTYPE);
return;
}
const handler *chosen = nullptr;
for (const auto &handler: active_handlers) {
if (handler.is_available &&
!q_strcasecmp(ext, handler.ext)) {
chosen = &handler;
break;
}
}
if (chosen == nullptr) {
Con_Printf("Unhandled extension for %s\n", filename.c_str());
return;
}
q_snprintf(tmp, sizeof(tmp), "%s/%s", chosen->dir, filename.c_str());
switch (chosen->player) {
case player_kind::midi_drv:
/* not supported in quake */
break;
case player_kind::streamer:
bgmstream = S_CodecOpenStreamType(tmp, chosen->type, bgmloop);
if (bgmstream)
return; /* success */
break;
case player_kind::none:
default:
break;
}
Con_Printf("Couldn't handle music file %s\n", filename.c_str());
}
void stop() {
if (bgmstream) {
bgmstream->status = STREAM_NONE;
S_CodecCloseStream(bgmstream);
bgmstream = nullptr;
s_rawend = 0;
}
}
void update() {
if (old_volume != bgmvolume.value) {
if (bgmvolume.value < 0) if (bgmvolume.value < 0)
bgmvolume.set("0"); bgmvolume.set("0");
else if (bgmvolume.value > 1) else if (bgmvolume.value > 1)
@@ -473,6 +371,75 @@ void BGM_Update (void)
old_volume = bgmvolume.value; old_volume = bgmvolume.value;
} }
if (bgmstream) if (bgmstream)
BGM_UpdateStream (); update_stream();
} }
void pause() {
if (bgmstream) {
if (bgmstream->status == STREAM_PLAY)
bgmstream->status = STREAM_PAUSE;
}
}
void resume() {
if (bgmstream) {
if (bgmstream->status == STREAM_PAUSE)
bgmstream->status = STREAM_PLAY;
}
}
void play_cd_track(const byte track, const bool looping) {
/* instead of searching by the order of music_handlers, do so by
* the order of searchpath priority: the file from the searchpath
* with the highest path_id is most likely from our own gamedir
* itself. This way, if a mod has track02 as a *.mp3 file, which
* is below *.ogg in the music_handler order, the mp3 will still
* have priority over track02.ogg from, say, id1.
*/
char tmp[MAX_QPATH];
unsigned int path_id;
stop();
if (CDAudio_Play(track, looping) == 0) {
return; /* success */
}
if (active_handlers.empty())
return; // We obviously can't play anything without handlers.
if (no_extmusic || bgm_extmusic.value == 0.0)
return;
unsigned int prev_id = 0;
unsigned int type = 0;
const char *ext = nullptr;
for (const auto handler: active_handlers) {
if (!handler.is_available) {
continue;
}
if (!CDRIPTYPE(handler.type)) {
continue;
}
q_snprintf(tmp, sizeof(tmp), "%s/track%02d.%s",
MUSIC_DIRNAME, static_cast<int>(track), handler.ext);
if (!COM_FileExists(tmp, &path_id)) {
continue;
}
if (path_id > prev_id) {
prev_id = path_id;
type = handler.type;
ext = handler.ext;
}
}
if (ext == nullptr)
Con_Printf("Couldn't find a cdrip for track %d\n", static_cast<int>(track));
else {
q_snprintf(tmp, sizeof(tmp), "%s/track%02d.%s",
MUSIC_DIRNAME, static_cast<int>(track), ext);
bgmstream = S_CodecOpenStreamType(tmp, type, bgmloop);
if (!bgmstream)
Con_Printf("Couldn't handle music file %s\n", tmp);
}
}
}
+16 -12
View File
@@ -4,6 +4,7 @@
* *
* Copyright (C) 1999-2005 Id Software, Inc. * Copyright (C) 1999-2005 Id Software, Inc.
* Copyright (C) 2010-2012 O.Sezer <[email protected]> * Copyright (C) 2010-2012 O.Sezer <[email protected]>
* Copyright (C) 2026 iikorni
* *
* This program is free software; you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@@ -22,22 +23,25 @@
* *
*/ */
#ifndef _BGMUSIC_H_ #pragma once
#define _BGMUSIC_H_
extern qboolean bgmloop; namespace music {
extern bool bgmloop;
extern convar bgm_extmusic; extern convar bgm_extmusic;
qboolean BGM_Init (void); void init();
void BGM_Shutdown (void);
void BGM_Play (const char *filename); void shutdown();
void BGM_Stop (void);
void BGM_Update (void);
void BGM_Pause (void);
void BGM_Resume (void);
void BGM_PlayCDtrack (byte track, qboolean looping); void play(const std::string &filename);
#endif /* _BGMUSIC_H_ */ void stop();
void update();
void pause();
void resume();
void play_cd_track(byte track, bool looping);
}
+1 -1
View File
@@ -20,7 +20,7 @@
#include "quakedef.h" #include "quakedef.h"
int CDAudio_Play(byte track, qboolean looping) int CDAudio_Play(byte track, bool looping)
{ {
return -1; return -1;
} }
+19 -21
View File
@@ -43,18 +43,18 @@
#include "quakedef.hpp" #include "quakedef.hpp"
static qboolean cdValid = false; static bool cdValid = false;
static qboolean playing = false; static bool playing = false;
static qboolean wasPlaying = false; static bool wasPlaying = false;
static qboolean enabled = true; static bool enabled = true;
static qboolean playLooping = false; static bool playLooping = false;
static byte remap[100]; static byte remap[100];
static byte playTrack; static byte playTrack;
static double endOfTrack = -1.0, pausetime = -1.0; static double endOfTrack = -1.0, pausetime = -1.0;
static SDL_CD *cd_handle; static SDL_CD *cd_handle;
static int cd_dev = -1; static int cd_dev = -1;
static float old_cdvolume; static float old_cdvolume;
static qboolean hw_vol_works = true; static bool hw_vol_works = true;
static void CDAudio_Eject(void) static void CDAudio_Eject(void)
@@ -84,7 +84,7 @@ static int CDAudio_GetAudioDiskInfo(void)
return 0; return 0;
} }
int CDAudio_Play(byte track, qboolean looping) int CDAudio_Play(byte track, bool looping)
{ {
int len_m, len_s, len_f; int len_m, len_s, len_f;
@@ -370,21 +370,21 @@ static void CD_f (void)
Con_Printf ("cd: unknown command \"%s\"\n", command); Con_Printf ("cd: unknown command \"%s\"\n", command);
} }
static qboolean CD_GetVolume (void *unused) static bool CD_GetVolume (void *unused)
{ {
/* FIXME: write proper code in here when SDL /* FIXME: write proper code in here when SDL
supports cdrom volume control some day. */ supports cdrom volume control some day. */
return false; return false;
} }
static qboolean CD_SetVolume (void *unused) static bool CD_SetVolume (void *unused)
{ {
/* FIXME: write proper code in here when SDL /* FIXME: write proper code in here when SDL
supports cdrom volume control some day. */ supports cdrom volume control some day. */
return false; return false;
} }
static qboolean CDAudio_SetVolume (float value) static bool CDAudio_SetVolume (float value)
{ {
if (!cd_handle || !enabled) if (!cd_handle || !enabled)
return false; return false;
@@ -485,11 +485,11 @@ static void export_cddev_arg (void)
/* Bad ugly hack to workaround SDL's cdrom device detection. /* Bad ugly hack to workaround SDL's cdrom device detection.
* not needed for windows due to the way SDL_cdrom works. */ * not needed for windows due to the way SDL_cdrom works. */
#if !defined(_WIN32) #if !defined(_WIN32)
int i = COM_CheckParm("-cddev"); auto i = common::check_param("-cddev");
if (i != 0 && i < com_argc - 1 && com_argv[i+1][0] != '\0') if (i.has_value() && i.value() < com_argc - 1 && com_argv[i.value()+1][0] != '\0')
{ {
static char arg[64]; static char arg[64];
q_snprintf(arg, sizeof(arg), "SDL_CDROM=%s", com_argv[i+1]); q_snprintf(arg, sizeof(arg), "SDL_CDROM=%s", com_argv[i.value()+1]);
putenv(arg); putenv(arg);
} }
#endif #endif
@@ -497,9 +497,7 @@ static void export_cddev_arg (void)
int CDAudio_Init(void) int CDAudio_Init(void)
{ {
int i, sdl_num_drives; if (safemode || common::check_param("-nocdaudio").has_value())
if (safemode || COM_CheckParm("-nocdaudio"))
return -1; return -1;
export_cddev_arg(); export_cddev_arg();
@@ -510,22 +508,22 @@ int CDAudio_Init(void)
return -1; return -1;
} }
sdl_num_drives = SDL_CDNumDrives (); const int sdl_num_drives = SDL_CDNumDrives();
Con_Printf ("SDL detected %d CD-ROM drive%c\n", sdl_num_drives, Con_Printf ("SDL detected %d CD-ROM drive%c\n", sdl_num_drives,
sdl_num_drives == 1 ? ' ' : 's'); sdl_num_drives == 1 ? ' ' : 's');
if (sdl_num_drives < 1) if (sdl_num_drives < 1)
return -1; return -1;
if ((i = COM_CheckParm("-cddev")) != 0 && i < com_argc - 1) if (const auto dev = common::check_param("-cddev"); dev.has_value() && dev.value() < com_argc - 1)
{ {
const char *userdev = get_cddev_arg(com_argv[i+1]); const char *userdev = get_cddev_arg(com_argv[dev.value()+1]);
if (!userdev) if (!userdev)
{ {
Con_Printf("Invalid argument to -cddev\n"); Con_Printf("Invalid argument to -cddev\n");
return -1; return -1;
} }
for (i = 0; i < sdl_num_drives; i++) for (auto i = 0; i < sdl_num_drives; i++)
{ {
if (!q_strcasecmp(SDL_CDName(i), userdev)) if (!q_strcasecmp(SDL_CDName(i), userdev))
{ {
@@ -551,7 +549,7 @@ int CDAudio_Init(void)
return -1; return -1;
} }
for (i = 0; i < 100; i++) for (auto i = 0; i < 100; i++)
remap[i] = i; remap[i] = i;
enabled = true; enabled = true;
old_cdvolume = bgmvolume.value; old_cdvolume = bgmvolume.value;
+1 -1
View File
@@ -23,7 +23,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#define __CDAUDIO_H #define __CDAUDIO_H
int CDAudio_Init (void); int CDAudio_Init (void);
int CDAudio_Play (byte track, qboolean looping); int CDAudio_Play (byte track, bool looping);
/* returns 0 for success, -1 for failure. */ /* returns 0 for success, -1 for failure. */
void CDAudio_Stop (void); void CDAudio_Stop (void);
void CDAudio_Pause (void); void CDAudio_Pause (void);
+2 -2
View File
@@ -131,7 +131,7 @@ void CFG_ReadCvarOverrides (const char **vars, int num_vars)
for (i = 0; i < num_vars; i++) for (i = 0; i < num_vars; i++)
{ {
q_strlcpy (&buff[1], vars[i], sizeof(buff) - 1); q_strlcpy (&buff[1], vars[i], sizeof(buff) - 1);
j = COM_CheckParm(buff); j = common::check_param(buff).has_value();
if (j != 0 && j < com_argc - 1) if (j != 0 && j < com_argc - 1)
{ {
if (com_argv[j + 1][0] != '-' && com_argv[j + 1][0] != '+') if (com_argv[j + 1][0] != '-' && com_argv[j + 1][0] != '+')
@@ -154,7 +154,7 @@ int CFG_OpenConfig (const char *cfg_name)
{ {
FILE *f; FILE *f;
long length; long length;
qboolean pak; bool pak;
CFG_CloseConfig (); CFG_CloseConfig ();
+27 -43
View File
@@ -24,6 +24,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// Quake is a trademark of Id Software, Inc., (c) 1996 Id Software, Inc. All // Quake is a trademark of Id Software, Inc., (c) 1996 Id Software, Inc. All
// rights reserved. // rights reserved.
#include <cstring>
#include "quakedef.hpp" #include "quakedef.hpp"
extern convar cl_maxpitch; //johnfitz -- variable pitch clamping extern convar cl_maxpitch; //johnfitz -- variable pitch clamping
@@ -60,8 +62,7 @@ kbutton_t in_up, in_down;
int in_impulse; int in_impulse;
void KeyDown (kbutton_t *b) void KeyDown(kbutton_t *b) {
{
int k; int k;
auto c = command::argv(1).value_or(""); auto c = command::argv(1).value_or("");
@@ -77,8 +78,7 @@ void KeyDown (kbutton_t *b)
b->down[0] = k; b->down[0] = k;
else if (!b->down[1]) else if (!b->down[1])
b->down[1] = k; b->down[1] = k;
else else {
{
Con_Printf("Three keys down for a button!\n"); Con_Printf("Three keys down for a button!\n");
return; return;
} }
@@ -88,16 +88,15 @@ void KeyDown (kbutton_t *b)
b->state |= 1 + 2; // down + impulse down b->state |= 1 + 2; // down + impulse down
} }
void KeyUp (kbutton_t *b) void KeyUp(kbutton_t *b) {
{
int k; int k;
const char *c; const char *c;
c = command::argv(1)->c_str(); c = command::argv(1)->c_str();
if (c[0]) if (c[0])
k = atoi(c); k = atoi(c);
else else {
{ // typed manually at the console, assume for unsticking, so clear all // typed manually at the console, assume for unsticking, so clear all
b->down[0] = b->down[1] = 0; b->down[0] = b->down[1] = 0;
b->state = 4; // impulse up b->state = 4; // impulse up
return; return;
@@ -121,11 +120,13 @@ void KeyUp (kbutton_t *b)
void IN_KLookDown(void) { KeyDown(&in_klook); } void IN_KLookDown(void) { KeyDown(&in_klook); }
void IN_KLookUp(void) { KeyUp(&in_klook); } void IN_KLookUp(void) { KeyUp(&in_klook); }
void IN_MLookDown(void) { KeyDown(&in_mlook); } void IN_MLookDown(void) { KeyDown(&in_mlook); }
void IN_MLookUp(void) { void IN_MLookUp(void) {
KeyUp(&in_mlook); KeyUp(&in_mlook);
if (!(in_mlook.state & 1) && lookspring.value) if (!(in_mlook.state & 1) && lookspring.value)
V_StartPitchDrift(); V_StartPitchDrift();
} }
void IN_UpDown(void) { KeyDown(&in_up); } void IN_UpDown(void) { KeyDown(&in_up); }
void IN_UpUp(void) { KeyUp(&in_up); } void IN_UpUp(void) { KeyUp(&in_up); }
void IN_DownDown(void) { KeyDown(&in_down); } void IN_DownDown(void) { KeyDown(&in_down); }
@@ -160,7 +161,7 @@ void IN_UseUp (void) {KeyUp(&in_use);}
void IN_JumpDown(void) { KeyDown(&in_jump); } void IN_JumpDown(void) { KeyDown(&in_jump); }
void IN_JumpUp(void) { KeyUp(&in_jump); } void IN_JumpUp(void) { KeyUp(&in_jump); }
void IN_Impulse (void) {in_impulse=Q_atoi(command::argv(1)->c_str());} void IN_Impulse(void) { in_impulse = std::atoi(command::argv(1)->c_str()); }
/* /*
=============== ===============
@@ -172,39 +173,34 @@ Returns 0.25 if a key was pressed and released during the frame,
1.0 if held for the entire time 1.0 if held for the entire time
=============== ===============
*/ */
float CL_KeyState (kbutton_t *key) float CL_KeyState(kbutton_t *key) {
{
float val; float val;
qboolean impulsedown, impulseup, down; bool impulsedown, impulseup, down;
impulsedown = key->state & 2; impulsedown = key->state & 2;
impulseup = key->state & 4; impulseup = key->state & 4;
down = key->state & 1; down = key->state & 1;
val = 0; val = 0;
if (impulsedown && !impulseup) if (impulsedown && !impulseup) {
{
if (down) if (down)
val = 0.5; // pressed and held this frame val = 0.5; // pressed and held this frame
else else
val = 0; // I_Error (); val = 0; // I_Error ();
} }
if (impulseup && !impulsedown) if (impulseup && !impulsedown) {
{
if (down) if (down)
val = 0; // I_Error (); val = 0; // I_Error ();
else else
val = 0; // released this frame val = 0; // released this frame
} }
if (!impulsedown && !impulseup) if (!impulsedown && !impulseup) {
{
if (down) if (down)
val = 1.0; // held the entire frame val = 1.0; // held the entire frame
else else
val = 0; // up the entire frame val = 0; // up the entire frame
} }
if (impulsedown && impulseup) if (impulsedown && impulseup) {
{
if (down) if (down)
val = 0.75; // released and re-pressed this frame val = 0.75; // released and re-pressed this frame
else else
@@ -240,8 +236,7 @@ CL_AdjustAngles
Moves the local angle positions Moves the local angle positions
================ ================
*/ */
void CL_AdjustAngles (void) void CL_AdjustAngles(void) {
{
float speed; float speed;
float up, down; float up, down;
@@ -250,14 +245,12 @@ void CL_AdjustAngles (void)
else else
speed = host_frametime; speed = host_frametime;
if (!(in_strafe.state & 1)) if (!(in_strafe.state & 1)) {
{
cl.viewangles[YAW] -= speed * cl_yawspeed.value * CL_KeyState(&in_right); cl.viewangles[YAW] -= speed * cl_yawspeed.value * CL_KeyState(&in_right);
cl.viewangles[YAW] += speed * cl_yawspeed.value * CL_KeyState(&in_left); cl.viewangles[YAW] += speed * cl_yawspeed.value * CL_KeyState(&in_left);
cl.viewangles[YAW] = anglemod(cl.viewangles[YAW]); cl.viewangles[YAW] = anglemod(cl.viewangles[YAW]);
} }
if (in_klook.state & 1) if (in_klook.state & 1) {
{
V_StopPitchDrift(); V_StopPitchDrift();
cl.viewangles[PITCH] -= speed * cl_pitchspeed.value * CL_KeyState(&in_forward); cl.viewangles[PITCH] -= speed * cl_pitchspeed.value * CL_KeyState(&in_forward);
cl.viewangles[PITCH] += speed * cl_pitchspeed.value * CL_KeyState(&in_back); cl.viewangles[PITCH] += speed * cl_pitchspeed.value * CL_KeyState(&in_back);
@@ -292,17 +285,15 @@ CL_BaseMove
Send the intended movement message to the server Send the intended movement message to the server
================ ================
*/ */
void CL_BaseMove (usercmd_t *cmd) void CL_BaseMove(usercmd_t *cmd) {
{
if (cls.signon != SIGNONS) if (cls.signon != SIGNONS)
return; return;
CL_AdjustAngles(); CL_AdjustAngles();
Q_memset (cmd, 0, sizeof(*cmd)); std::memset(cmd, 0, sizeof(*cmd));
if (in_strafe.state & 1) if (in_strafe.state & 1) {
{
cmd->sidemove += cl_sidespeed.value * CL_KeyState(&in_right); cmd->sidemove += cl_sidespeed.value * CL_KeyState(&in_right);
cmd->sidemove -= cl_sidespeed.value * CL_KeyState(&in_left); cmd->sidemove -= cl_sidespeed.value * CL_KeyState(&in_left);
} }
@@ -313,8 +304,7 @@ void CL_BaseMove (usercmd_t *cmd)
cmd->upmove += cl_upspeed.value * CL_KeyState(&in_up); cmd->upmove += cl_upspeed.value * CL_KeyState(&in_up);
cmd->upmove -= cl_upspeed.value * CL_KeyState(&in_down); cmd->upmove -= cl_upspeed.value * CL_KeyState(&in_down);
if (! (in_klook.state & 1) ) if (!(in_klook.state & 1)) {
{
cmd->forwardmove += cl_forwardspeed.value * CL_KeyState(&in_forward); cmd->forwardmove += cl_forwardspeed.value * CL_KeyState(&in_forward);
cmd->forwardmove -= cl_backspeed.value * CL_KeyState(&in_back); cmd->forwardmove -= cl_backspeed.value * CL_KeyState(&in_back);
} }
@@ -322,8 +312,7 @@ void CL_BaseMove (usercmd_t *cmd)
// //
// adjust for speed key // adjust for speed key
// //
if ((in_speed.state & 1) ^ (cl_alwaysrun.value != 0.0)) if ((in_speed.state & 1) ^ (cl_alwaysrun.value != 0.0)) {
{
cmd->forwardmove *= cl_movespeedkey.value; cmd->forwardmove *= cl_movespeedkey.value;
cmd->sidemove *= cl_movespeedkey.value; cmd->sidemove *= cl_movespeedkey.value;
cmd->upmove *= cl_movespeedkey.value; cmd->upmove *= cl_movespeedkey.value;
@@ -336,8 +325,7 @@ void CL_BaseMove (usercmd_t *cmd)
CL_SendMove CL_SendMove
============== ==============
*/ */
void CL_SendMove (const usercmd_t *cmd) void CL_SendMove(const usercmd_t *cmd) {
{
int i; int i;
int bits; int bits;
sizebuf_t buf; sizebuf_t buf;
@@ -399,8 +387,7 @@ void CL_SendMove (const usercmd_t *cmd)
if (++cl.movemessages <= 2) if (++cl.movemessages <= 2)
return; return;
if (NET_SendUnreliableMessage (cls.netcon, &buf) == -1) if (NET_SendUnreliableMessage(cls.netcon, &buf) == -1) {
{
Con_Printf("CL_SendMove: lost server connection\n"); Con_Printf("CL_SendMove: lost server connection\n");
CL_Disconnect(); CL_Disconnect();
} }
@@ -411,8 +398,7 @@ void CL_SendMove (const usercmd_t *cmd)
CL_InitInput CL_InitInput
============ ============
*/ */
void CL_InitInput (void) void CL_InitInput(void) {
{
command::add("+moveup", IN_UpDown); command::add("+moveup", IN_UpDown);
command::add("-moveup", IN_UpUp); command::add("-moveup", IN_UpUp);
command::add("+movedown", IN_DownDown); command::add("+movedown", IN_DownDown);
@@ -448,6 +434,4 @@ void CL_InitInput (void)
command::add("-klook", IN_KLookUp); command::add("-klook", IN_KLookUp);
command::add("+mlook", IN_MLookDown); command::add("+mlook", IN_MLookDown);
command::add("-mlook", IN_MLookUp); command::add("-mlook", IN_MLookUp);
} }
+68 -118
View File
@@ -71,8 +71,7 @@ CL_ClearState
===================== =====================
*/ */
void CL_ClearState (void) void CL_ClearState(void) {
{
if (!sv.active) if (!sv.active)
Host_ClearMemory(); Host_ClearMemory();
@@ -88,7 +87,7 @@ void CL_ClearState (void)
memset(cl_beams, 0, sizeof(cl_beams)); memset(cl_beams, 0, sizeof(cl_beams));
//johnfitz -- cl_entities is now dynamically allocated //johnfitz -- cl_entities is now dynamically allocated
cl_max_edicts = CLAMP (MIN_EDICTS,(int)max_edicts.value,MAX_EDICTS); cl_max_edicts = std::clamp((int) max_edicts.value,MIN_EDICTS, MAX_EDICTS);
cl_entities = (entity_t *) Hunk_AllocName(cl_max_edicts * sizeof(entity_t), "cl_entities"); cl_entities = (entity_t *) Hunk_AllocName(cl_max_edicts * sizeof(entity_t), "cl_entities");
//johnfitz //johnfitz
} }
@@ -101,21 +100,19 @@ Sends a disconnect message to the server
This is also called on Host_Error, so it shouldn't cause any errors This is also called on Host_Error, so it shouldn't cause any errors
===================== =====================
*/ */
void CL_Disconnect (void) void CL_Disconnect(void) {
{
if (key_dest == key_message) if (key_dest == key_message)
Key_EndChat(); // don't get stuck in chat mode Key_EndChat(); // don't get stuck in chat mode
// stop sounds (especially looping!) // stop sounds (especially looping!)
S_StopAllSounds(true); S_StopAllSounds(true);
BGM_Stop(); music::stop();
CDAudio_Stop(); CDAudio_Stop();
// if running a local server, shut it down // if running a local server, shut it down
if (cls.demoplayback) if (cls.demoplayback)
CL_StopPlayback(); CL_StopPlayback();
else if (cls.state == ca_connected) else if (cls.state == ca_connected) {
{
if (cls.demorecording) if (cls.demorecording)
CL_Stop_f(); CL_Stop_f();
@@ -137,8 +134,7 @@ void CL_Disconnect (void)
CL_ClearSignons(); CL_ClearSignons();
} }
void CL_Disconnect_f (void) void CL_Disconnect_f(void) {
{
CL_Disconnect(); CL_Disconnect();
if (sv.active) if (sv.active)
Host_ShutdownServer(false); Host_ShutdownServer(false);
@@ -152,8 +148,7 @@ CL_EstablishConnection
Host should be either "local" or a net address to be passed on Host should be either "local" or a net address to be passed on
===================== =====================
*/ */
void CL_EstablishConnection (const char *host) void CL_EstablishConnection(const char *host) {
{
if (cls.state == ca_dedicated) if (cls.state == ca_dedicated)
return; return;
@@ -180,14 +175,12 @@ CL_SignonReply
An svc_signonnum has been received, perform a client side setup An svc_signonnum has been received, perform a client side setup
===================== =====================
*/ */
void CL_SignonReply (void) void CL_SignonReply(void) {
{
char str[8192]; char str[8192];
Con_DPrintf("CL_SignonReply: %i\n", cls.signon); Con_DPrintf("CL_SignonReply: %i\n", cls.signon);
switch (cls.signon) switch (cls.signon) {
{
case 1: case 1:
MSG_WriteByte(&cls.message, clc_stringcmd); MSG_WriteByte(&cls.message, clc_stringcmd);
MSG_WriteString(&cls.message, "prespawn"); MSG_WriteString(&cls.message, "prespawn");
@@ -198,7 +191,8 @@ void CL_SignonReply (void)
MSG_WriteString(&cls.message, va("name \"%s\"\n", cl_name.string)); MSG_WriteString(&cls.message, va("name \"%s\"\n", cl_name.string));
MSG_WriteByte(&cls.message, clc_stringcmd); MSG_WriteByte(&cls.message, clc_stringcmd);
MSG_WriteString (&cls.message, va("color %i %i\n", ((int)cl_color.value)>>4, ((int)cl_color.value)&15)); MSG_WriteString(&cls.message,
va("color %i %i\n", ((int) cl_color.value) >> 4, ((int) cl_color.value) & 15));
MSG_WriteByte(&cls.message, clc_stringcmd); MSG_WriteByte(&cls.message, clc_stringcmd);
sprintf(str, "spawn %s", cls.spawnparms); sprintf(str, "spawn %s", cls.spawnparms);
@@ -224,18 +218,15 @@ CL_NextDemo
Called to play the next demo in the demo loop Called to play the next demo in the demo loop
===================== =====================
*/ */
void CL_NextDemo (void) void CL_NextDemo(void) {
{
char str[1024]; char str[1024];
if (cls.demonum == -1) if (cls.demonum == -1)
return; // don't play demos return; // don't play demos
if (!cls.demos[cls.demonum][0] || cls.demonum == MAX_DEMOS) if (!cls.demos[cls.demonum][0] || cls.demonum == MAX_DEMOS) {
{
cls.demonum = 0; cls.demonum = 0;
if (!cls.demos[cls.demonum][0]) if (!cls.demos[cls.demonum][0]) {
{
Con_Printf("No demos listed with startdemos\n"); Con_Printf("No demos listed with startdemos\n");
cls.demonum = -1; cls.demonum = -1;
CL_Disconnect(); CL_Disconnect();
@@ -246,7 +237,7 @@ void CL_NextDemo (void)
SCR_BeginLoadingPlaque(); SCR_BeginLoadingPlaque();
sprintf(str, "playdemo %s\n", cls.demos[cls.demonum]); sprintf(str, "playdemo %s\n", cls.demos[cls.demonum]);
Cbuf_InsertText (str); command::buffer::insert_text(str);
cls.demonum++; cls.demonum++;
} }
@@ -255,24 +246,22 @@ void CL_NextDemo (void)
CL_PrintEntities_f CL_PrintEntities_f
============== ==============
*/ */
void CL_PrintEntities_f (void) void CL_PrintEntities_f(void) {
{
entity_t *ent; entity_t *ent;
int i; int i;
if (cls.state != ca_connected) if (cls.state != ca_connected)
return; return;
for (i=0,ent=cl_entities ; i<cl.num_entities ; i++,ent++) for (i = 0, ent = cl_entities; i < cl.num_entities; i++, ent++) {
{
Con_Printf("%3i:", i); Con_Printf("%3i:", i);
if (!ent->model) if (!ent->model) {
{
Con_Printf("EMPTY\n"); Con_Printf("EMPTY\n");
continue; continue;
} }
Con_Printf("%s:%2i (%5.1f,%5.1f,%5.1f) [%5.1f %5.1f %5.1f]\n" Con_Printf("%s:%2i (%5.1f,%5.1f,%5.1f) [%5.1f %5.1f %5.1f]\n"
,ent->model->name,ent->frame, ent->origin[0], ent->origin[1], ent->origin[2], ent->angles[0], ent->angles[1], ent->angles[2]); , ent->model->name, ent->frame, ent->origin[0], ent->origin[1], ent->origin[2], ent->angles[0],
ent->angles[1], ent->angles[2]);
} }
} }
@@ -282,19 +271,15 @@ CL_AllocDlight
=============== ===============
*/ */
dlight_t *CL_AllocDlight (int key) dlight_t *CL_AllocDlight(int key) {
{
int i; int i;
dlight_t *dl; dlight_t *dl;
// first look for an exact key match // first look for an exact key match
if (key) if (key) {
{
dl = cl_dlights; dl = cl_dlights;
for (i=0 ; i<MAX_DLIGHTS ; i++, dl++) for (i = 0; i < MAX_DLIGHTS; i++, dl++) {
{ if (dl->key == key) {
if (dl->key == key)
{
memset(dl, 0, sizeof(*dl)); memset(dl, 0, sizeof(*dl));
dl->key = key; dl->key = key;
dl->color[0] = dl->color[1] = dl->color[2] = 1; //johnfitz -- lit support via lordhavoc dl->color[0] = dl->color[1] = dl->color[2] = 1; //johnfitz -- lit support via lordhavoc
@@ -305,10 +290,8 @@ dlight_t *CL_AllocDlight (int key)
// then look for anything else // then look for anything else
dl = cl_dlights; dl = cl_dlights;
for (i=0 ; i<MAX_DLIGHTS ; i++, dl++) for (i = 0; i < MAX_DLIGHTS; i++, dl++) {
{ if (dl->die < cl.time) {
if (dl->die < cl.time)
{
memset(dl, 0, sizeof(*dl)); memset(dl, 0, sizeof(*dl));
dl->key = key; dl->key = key;
dl->color[0] = dl->color[1] = dl->color[2] = 1; //johnfitz -- lit support via lordhavoc dl->color[0] = dl->color[1] = dl->color[2] = 1; //johnfitz -- lit support via lordhavoc
@@ -330,8 +313,7 @@ CL_DecayLights
=============== ===============
*/ */
void CL_DecayLights (void) void CL_DecayLights(void) {
{
int i; int i;
dlight_t *dl; dlight_t *dl;
float time; float time;
@@ -339,8 +321,7 @@ void CL_DecayLights (void)
time = cl.time - cl.oldtime; time = cl.time - cl.oldtime;
dl = cl_dlights; dl = cl_dlights;
for (i=0 ; i<MAX_DLIGHTS ; i++, dl++) for (i = 0; i < MAX_DLIGHTS; i++, dl++) {
{
if (dl->die < cl.time || !dl->radius) if (dl->die < cl.time || !dl->radius)
continue; continue;
@@ -359,14 +340,12 @@ Determines the fraction between the last two messages that the objects
should be put at. should be put at.
=============== ===============
*/ */
float CL_LerpPoint (void) float CL_LerpPoint(void) {
{
float f, frac; float f, frac;
f = cl.mtime[0] - cl.mtime[1]; f = cl.mtime[0] - cl.mtime[1];
if (!f || cls.timedemo || sv.active) if (!f || cls.timedemo || sv.active) {
{
cl.time = cl.mtime[0]; cl.time = cl.mtime[0];
return 1; return 1;
} }
@@ -379,14 +358,11 @@ float CL_LerpPoint (void)
frac = (cl.time - cl.mtime[1]) / f; frac = (cl.time - cl.mtime[1]) / f;
if (frac < 0) if (frac < 0) {
{
if (frac < -0.01) if (frac < -0.01)
cl.time = cl.mtime[1]; cl.time = cl.mtime[1];
frac = 0; frac = 0;
} } else if (frac > 1) {
else if (frac > 1)
{
if (frac > 1.01) if (frac > 1.01)
cl.time = cl.mtime[0]; cl.time = cl.mtime[0];
frac = 1; frac = 1;
@@ -405,8 +381,7 @@ float CL_LerpPoint (void)
CL_RelinkEntities CL_RelinkEntities
=============== ===============
*/ */
void CL_RelinkEntities (void) void CL_RelinkEntities(void) {
{
entity_t *ent; entity_t *ent;
int i, j; int i, j;
float frac, f, d; float frac, f, d;
@@ -427,11 +402,9 @@ void CL_RelinkEntities (void)
cl.velocity[i] = cl.mvelocity[1][i] + cl.velocity[i] = cl.mvelocity[1][i] +
frac * (cl.mvelocity[0][i] - cl.mvelocity[1][i]); frac * (cl.mvelocity[0][i] - cl.mvelocity[1][i]);
if (cls.demoplayback) if (cls.demoplayback) {
{
// interpolate the angles // interpolate the angles
for (j=0 ; j<3 ; j++) for (j = 0; j < 3; j++) {
{
d = cl.mviewangles[0][j] - cl.mviewangles[1][j]; d = cl.mviewangles[0][j] - cl.mviewangles[1][j];
if (d > 180) if (d > 180)
d -= 360; d -= 360;
@@ -444,10 +417,9 @@ void CL_RelinkEntities (void)
bobjrotate = anglemod(100 * cl.time); bobjrotate = anglemod(100 * cl.time);
// start on the entity after the world // start on the entity after the world
for (i=1,ent=cl_entities+1 ; i<cl.num_entities ; i++,ent++) for (i = 1, ent = cl_entities + 1; i < cl.num_entities; i++, ent++) {
{ if (!ent->model) {
if (!ent->model) // empty slot
{ // empty slot
// ericw -- efrags are only used for static entities in GLQuake // ericw -- efrags are only used for static entities in GLQuake
// ent can't be static, so this is a no-op. // ent can't be static, so this is a no-op.
@@ -457,29 +429,26 @@ void CL_RelinkEntities (void)
} }
// if the object wasn't included in the last packet, remove it // if the object wasn't included in the last packet, remove it
if (ent->msgtime != cl.mtime[0]) if (ent->msgtime != cl.mtime[0]) {
{
ent->model = NULL; ent->model = NULL;
ent->lerpflags |= LERP_RESETMOVE|LERP_RESETANIM; //johnfitz -- next time this entity slot is reused, the lerp will need to be reset ent->lerpflags |= LERP_RESETMOVE | LERP_RESETANIM;
//johnfitz -- next time this entity slot is reused, the lerp will need to be reset
continue; continue;
} }
VectorCopy(ent->origin, oldorg); VectorCopy(ent->origin, oldorg);
if (ent->forcelink) if (ent->forcelink) {
{ // the entity was not updated in the last message // the entity was not updated in the last message
// so move to the final spot // so move to the final spot
VectorCopy(ent->msg_origins[0], ent->origin); VectorCopy(ent->msg_origins[0], ent->origin);
VectorCopy(ent->msg_angles[0], ent->angles); VectorCopy(ent->msg_angles[0], ent->angles);
} } else {
else // if the delta is large, assume a teleport and don't lerp
{ // if the delta is large, assume a teleport and don't lerp
f = frac; f = frac;
for (j=0 ; j<3 ; j++) for (j = 0; j < 3; j++) {
{
delta[j] = ent->msg_origins[0][j] - ent->msg_origins[1][j]; delta[j] = ent->msg_origins[0][j] - ent->msg_origins[1][j];
if (delta[j] > 100 || delta[j] < -100) if (delta[j] > 100 || delta[j] < -100) {
{
f = 1; // assume a teleportation, not a motion f = 1; // assume a teleportation, not a motion
ent->lerpflags |= LERP_RESETMOVE; //johnfitz -- don't lerp teleports ent->lerpflags |= LERP_RESETMOVE; //johnfitz -- don't lerp teleports
} }
@@ -491,8 +460,7 @@ void CL_RelinkEntities (void)
//johnfitz //johnfitz
// interpolate the origin and angles // interpolate the origin and angles
for (j=0 ; j<3 ; j++) for (j = 0; j < 3; j++) {
{
ent->origin[j] = ent->msg_origins[1][j] + f * delta[j]; ent->origin[j] = ent->msg_origins[1][j] + f * delta[j];
d = ent->msg_angles[0][j] - ent->msg_angles[1][j]; d = ent->msg_angles[0][j] - ent->msg_angles[1][j];
@@ -511,8 +479,7 @@ void CL_RelinkEntities (void)
if (ent->effects & EF_BRIGHTFIELD) if (ent->effects & EF_BRIGHTFIELD)
R_EntityParticles(ent); R_EntityParticles(ent);
if (ent->effects & EF_MUZZLEFLASH) if (ent->effects & EF_MUZZLEFLASH) {
{
vec3_t fv, rv, uv; vec3_t fv, rv, uv;
dl = CL_AllocDlight(i); dl = CL_AllocDlight(i);
@@ -526,8 +493,7 @@ void CL_RelinkEntities (void)
dl->die = cl.time + 0.1; dl->die = cl.time + 0.1;
//johnfitz -- assume muzzle flash accompanied by muzzle flare, which looks bad when lerped //johnfitz -- assume muzzle flash accompanied by muzzle flare, which looks bad when lerped
if (r_lerpmodels.value != 2) if (r_lerpmodels.value != 2) {
{
if (ent == &cl_entities[cl.viewentity]) if (ent == &cl_entities[cl.viewentity])
cl.viewent.lerpflags |= LERP_RESETANIM | LERP_RESETANIM2; //no lerping for two frames cl.viewent.lerpflags |= LERP_RESETANIM | LERP_RESETANIM2; //no lerping for two frames
else else
@@ -535,23 +501,20 @@ void CL_RelinkEntities (void)
} }
//johnfitz //johnfitz
} }
if (ent->effects & EF_BRIGHTLIGHT) if (ent->effects & EF_BRIGHTLIGHT) {
{
dl = CL_AllocDlight(i); dl = CL_AllocDlight(i);
VectorCopy(ent->origin, dl->origin); VectorCopy(ent->origin, dl->origin);
dl->origin[2] += 16; dl->origin[2] += 16;
dl->radius = 400 + (rand() & 31); dl->radius = 400 + (rand() & 31);
dl->die = cl.time + 0.001; dl->die = cl.time + 0.001;
} }
if (ent->effects & EF_DIMLIGHT) if (ent->effects & EF_DIMLIGHT) {
{
dl = CL_AllocDlight(i); dl = CL_AllocDlight(i);
VectorCopy(ent->origin, dl->origin); VectorCopy(ent->origin, dl->origin);
dl->radius = 200 + (rand() & 31); dl->radius = 200 + (rand() & 31);
dl->die = cl.time + 0.001; dl->die = cl.time + 0.001;
} }
if (ent->effects & EF_QEX_QUADLIGHT) if (ent->effects & EF_QEX_QUADLIGHT) {
{
dl = CL_AllocDlight(i); dl = CL_AllocDlight(i);
VectorCopy(ent->origin, dl->origin); VectorCopy(ent->origin, dl->origin);
dl->radius = 200 + (rand() & 31); dl->radius = 200 + (rand() & 31);
@@ -560,8 +523,7 @@ void CL_RelinkEntities (void)
dl->color[1] = 0.25f; dl->color[1] = 0.25f;
dl->color[2] = 1.0f; dl->color[2] = 1.0f;
} }
if (ent->effects & EF_QEX_PENTALIGHT) if (ent->effects & EF_QEX_PENTALIGHT) {
{
dl = CL_AllocDlight(i); dl = CL_AllocDlight(i);
VectorCopy(ent->origin, dl->origin); VectorCopy(ent->origin, dl->origin);
dl->radius = 200 + (rand() & 31); dl->radius = 200 + (rand() & 31);
@@ -579,15 +541,13 @@ void CL_RelinkEntities (void)
R_RocketTrail(oldorg, ent->origin, 3); R_RocketTrail(oldorg, ent->origin, 3);
else if (ent->model->flags & EF_TRACER2) else if (ent->model->flags & EF_TRACER2)
R_RocketTrail(oldorg, ent->origin, 5); R_RocketTrail(oldorg, ent->origin, 5);
else if (ent->model->flags & EF_ROCKET) else if (ent->model->flags & EF_ROCKET) {
{
R_RocketTrail(oldorg, ent->origin, 0); R_RocketTrail(oldorg, ent->origin, 0);
dl = CL_AllocDlight(i); dl = CL_AllocDlight(i);
VectorCopy(ent->origin, dl->origin); VectorCopy(ent->origin, dl->origin);
dl->radius = 200; dl->radius = 200;
dl->die = cl.time + 0.01; dl->die = cl.time + 0.01;
} } else if (ent->model->flags & EF_GRENADE)
else if (ent->model->flags & EF_GRENADE)
R_RocketTrail(oldorg, ent->origin, 1); R_RocketTrail(oldorg, ent->origin, 1);
else if (ent->model->flags & EF_TRACER3) else if (ent->model->flags & EF_TRACER3)
R_RocketTrail(oldorg, ent->origin, 6); R_RocketTrail(oldorg, ent->origin, 6);
@@ -597,8 +557,7 @@ void CL_RelinkEntities (void)
if (i == cl.viewentity && !chase_active.value) if (i == cl.viewentity && !chase_active.value)
continue; continue;
if (cl_numvisedicts < MAX_VISEDICTS) if (cl_numvisedicts < MAX_VISEDICTS) {
{
cl_visedicts[cl_numvisedicts] = ent; cl_visedicts[cl_numvisedicts] = ent;
cl_numvisedicts++; cl_numvisedicts++;
} }
@@ -613,8 +572,7 @@ CL_ReadFromServer
Read all incoming data from the server Read all incoming data from the server
=============== ===============
*/ */
int CL_ReadFromServer (void) int CL_ReadFromServer(void) {
{
int ret; int ret;
extern int num_temp_entities; //johnfitz extern int num_temp_entities; //johnfitz
int num_beams = 0; //johnfitz int num_beams = 0; //johnfitz
@@ -627,8 +585,7 @@ int CL_ReadFromServer (void)
cl.oldtime = cl.time; cl.oldtime = cl.time;
cl.time += host_frametime; cl.time += host_frametime;
do do {
{
ret = CL_GetMessage(); ret = CL_GetMessage();
if (ret == -1) if (ret == -1)
Host_Error("CL_ReadFromServer: lost server connection"); Host_Error("CL_ReadFromServer: lost server connection");
@@ -655,7 +612,8 @@ int CL_ReadFromServer (void)
//temp entities //temp entities
if (num_temp_entities > 64 && dev_peakstats.tempents <= 64) 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); 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_stats.tempents = num_temp_entities;
dev_peakstats.tempents = std::max(num_temp_entities, dev_peakstats.tempents); dev_peakstats.tempents = std::max(num_temp_entities, dev_peakstats.tempents);
@@ -690,15 +648,13 @@ int CL_ReadFromServer (void)
CL_SendCmd CL_SendCmd
================= =================
*/ */
void CL_SendCmd (void) void CL_SendCmd(void) {
{
usercmd_t cmd; usercmd_t cmd;
if (cls.state != ca_connected) if (cls.state != ca_connected)
return; return;
if (cls.signon == SIGNONS) if (cls.signon == SIGNONS) {
{
// get basic movement from keyboard // get basic movement from keyboard
CL_BaseMove(&cmd); CL_BaseMove(&cmd);
@@ -709,8 +665,7 @@ void CL_SendCmd (void)
CL_SendMove(&cmd); CL_SendMove(&cmd);
} }
if (cls.demoplayback) if (cls.demoplayback) {
{
SZ_Clear(&cls.message); SZ_Clear(&cls.message);
return; return;
} }
@@ -719,8 +674,7 @@ void CL_SendCmd (void)
if (!cls.message.cursize) if (!cls.message.cursize)
return; // no message at all return; // no message at all
if (!NET_CanSendMessage (cls.netcon)) if (!NET_CanSendMessage(cls.netcon)) {
{
Con_DPrintf("CL_SendCmd: can't send\n"); Con_DPrintf("CL_SendCmd: can't send\n");
return; return;
} }
@@ -738,8 +692,7 @@ CL_Tracepos_f -- johnfitz
display impact point of trace along VPN display impact point of trace along VPN
============= =============
*/ */
void CL_Tracepos_f (void) void CL_Tracepos_f(void) {
{
vec3_t v, w; vec3_t v, w;
if (cls.state != ca_connected) if (cls.state != ca_connected)
@@ -761,8 +714,7 @@ CL_Viewpos_f -- johnfitz
display client's position and angles display client's position and angles
============= =============
*/ */
void CL_Viewpos_f (void) void CL_Viewpos_f(void) {
{
if (cls.state != ca_connected) if (cls.state != ca_connected)
return; return;
#if 0 #if 0
@@ -791,8 +743,7 @@ void CL_Viewpos_f (void)
CL_Init CL_Init
================= =================
*/ */
void CL_Init (void) void CL_Init(void) {
{
SZ_Alloc(&cls.message, 1024); SZ_Alloc(&cls.message, 1024);
CL_InitInput(); CL_InitInput();
@@ -838,4 +789,3 @@ void CL_Init (void)
command::add("tracepos", CL_Tracepos_f); //johnfitz command::add("tracepos", CL_Tracepos_f); //johnfitz
command::add("viewpos", CL_Viewpos_f); //johnfitz command::add("viewpos", CL_Viewpos_f); //johnfitz
} }
+9 -9
View File
@@ -98,9 +98,9 @@ const char *svc_strings[] =
"svc_backtolobby", // 55 "svc_backtolobby", // 55
"svc_localsound" // 56 "svc_localsound" // 56
}; };
#define NUM_SVC_STRINGS Q_COUNTOF(svc_strings) #define NUM_SVC_STRINGS std::size(svc_strings)
qboolean warn_about_nehahra_protocol; //johnfitz bool warn_about_nehahra_protocol; //johnfitz
extern vec3_t v_punchangles[2]; //johnfitz extern vec3_t v_punchangles[2]; //johnfitz
@@ -432,7 +432,7 @@ void CL_ParseUpdate(int bits) {
int i; int i;
qmodel_t *model; qmodel_t *model;
int modnum; int modnum;
qboolean forcelink; bool forcelink;
entity_t *ent; entity_t *ent;
int num; int num;
int skin; int skin;
@@ -1034,7 +1034,7 @@ void CL_ParseServerMessage(void) {
break; break;
case svc_stufftext: case svc_stufftext:
Cbuf_AddText(MSG_ReadString()); command::buffer::add_text(MSG_ReadString());
break; break;
case svc_damage: case svc_damage:
@@ -1060,7 +1060,7 @@ void CL_ParseServerMessage(void) {
if (i >= MAX_LIGHTSTYLES) if (i >= MAX_LIGHTSTYLES)
Sys_Error("svc_lightstyle > MAX_LIGHTSTYLES"); Sys_Error("svc_lightstyle > MAX_LIGHTSTYLES");
q_strlcpy(cl_lightstyle[i].map, MSG_ReadString(), MAX_STYLESTRING); q_strlcpy(cl_lightstyle[i].map, MSG_ReadString(), MAX_STYLESTRING);
cl_lightstyle[i].length = Q_strlen(cl_lightstyle[i].map); cl_lightstyle[i].length = std::strlen(cl_lightstyle[i].map);
//johnfitz -- save extra info //johnfitz -- save extra info
if (cl_lightstyle[i].length) { if (cl_lightstyle[i].length) {
total = 0; total = 0;
@@ -1131,10 +1131,10 @@ void CL_ParseServerMessage(void) {
cl.paused = MSG_ReadByte(); cl.paused = MSG_ReadByte();
if (cl.paused) { if (cl.paused) {
CDAudio_Pause(); CDAudio_Pause();
BGM_Pause(); music::pause();
} else { } else {
CDAudio_Resume(); CDAudio_Resume();
BGM_Resume(); music::resume();
} }
break; break;
@@ -1177,9 +1177,9 @@ void CL_ParseServerMessage(void) {
cl.cdtrack = MSG_ReadByte(); cl.cdtrack = MSG_ReadByte();
cl.looptrack = MSG_ReadByte(); cl.looptrack = MSG_ReadByte();
if ((cls.demoplayback || cls.demorecording) && (cls.forcetrack != -1)) if ((cls.demoplayback || cls.demorecording) && (cls.forcetrack != -1))
BGM_PlayCDtrack((byte) cls.forcetrack, true); music::play_cd_track((byte) cls.forcetrack, true);
else else
BGM_PlayCDtrack((byte) cl.cdtrack, true); music::play_cd_track((byte) cl.cdtrack, true);
break; break;
case svc_intermission: case svc_intermission:
+8 -8
View File
@@ -112,14 +112,14 @@ typedef struct
// demo recording info must be here, because record is started before // demo recording info must be here, because record is started before
// entering a map (and clearing client_state_t) // entering a map (and clearing client_state_t)
qboolean demorecording; bool demorecording;
qboolean demoplayback; bool demoplayback;
// did the user pause demo playback? (separate from cl.paused because we don't // did the user pause demo playback? (separate from cl.paused because we don't
// want a svc_setpause inside the demo to actually pause demo playback). // want a svc_setpause inside the demo to actually pause demo playback).
qboolean demopaused; bool demopaused;
qboolean timedemo; bool timedemo;
int forcetrack; // -1 = use normal cd track int forcetrack; // -1 = use normal cd track
FILE *demofile; FILE *demofile;
int td_lastframe; // to meter out one message a frame int td_lastframe; // to meter out one message a frame
@@ -173,16 +173,16 @@ typedef struct
// pitch drifting vars // pitch drifting vars
float idealpitch; float idealpitch;
float pitchvel; float pitchvel;
qboolean nodrift; bool nodrift;
float driftmove; float driftmove;
double laststop; double laststop;
float viewheight; float viewheight;
float crouch; // local amount for smoothing stepups float crouch; // local amount for smoothing stepups
qboolean paused; // send over by server bool paused; // send over by server
qboolean onground; bool onground;
qboolean inwater; bool inwater;
int intermission; // don't change view angle, full screen, etc int intermission; // don't change view angle, full screen, etc
int completed_time; // latched at intermission start int completed_time; // latched at intermission start
+67 -209
View File
@@ -29,8 +29,6 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#include "quakedef.hpp" #include "quakedef.hpp"
void Cmd_ForwardToServer(void);
constexpr int CMDLINE_LENGTH = 256; constexpr int CMDLINE_LENGTH = 256;
constexpr int MAX_ARGS = 80; constexpr int MAX_ARGS = 80;
@@ -57,7 +55,7 @@ namespace command {
* bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2" * bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2"
* ``` * ```
*/ */
void set_wait() { void _set_wait() {
waiting = true; waiting = true;
} }
@@ -111,13 +109,11 @@ namespace command {
} }
void _alias() { void _alias() {
char cmd[1024];
switch (argc()) { switch (argc()) {
case 1: { case 1: {
//list all aliases //list all aliases
auto count = 0; auto count = 0;
for (auto &[name, alias]: command::ALIASES) { for (auto &[name, alias]: ALIASES) {
Con_SafePrintf(" %s: %s", name.c_str(), alias.value.c_str()); Con_SafePrintf(" %s: %s", name.c_str(), alias.value.c_str());
count++; count++;
} }
@@ -130,7 +126,7 @@ namespace command {
case 2: { case 2: {
//output current alias string //output current alias string
const auto lookup = argv(1).value(); const auto lookup = argv(1).value();
for (auto &[name, alias]: command::ALIASES) for (auto &[name, alias]: ALIASES)
if (name.starts_with(lookup)) if (name.starts_with(lookup))
Con_Printf(" %s: %s", name.c_str(), alias.value.c_str()); Con_Printf(" %s: %s", name.c_str(), alias.value.c_str());
break; break;
@@ -138,14 +134,14 @@ namespace command {
default: { default: {
//set alias string //set alias string
const auto new_name = argv(1).value(); const auto new_name = argv(1).value();
if (new_name.length() >= command::MAX_ALIAS_LENGTH) { if (new_name.length() >= MAX_ALIAS_LENGTH) {
Con_Printf("Alias name is too long\n"); Con_Printf("Alias name is too long\n");
return; return;
} }
std::optional<command::alias> new_alias = std::nullopt; std::optional<alias> new_alias = std::nullopt;
// if the alias already exists, reuse it // if the alias already exists, reuse it
for (auto &[name, alias]: command::ALIASES) { for (auto &[name, alias]: ALIASES) {
if (name == new_name) { if (name == new_name) {
new_alias = alias; new_alias = alias;
alias.value.clear(); alias.value.clear();
@@ -154,26 +150,21 @@ namespace command {
} }
if (!new_alias.has_value()) { if (!new_alias.has_value()) {
new_alias = command::alias{}; new_alias = alias{};
} }
new_alias->name = new_name; new_alias->name = new_name;
// copy the rest of the command line // copy the rest of the command line
cmd[0] = 0; // start out with a null string auto cmd = std::string{};
auto c = argc(); const auto count = argc();
// TODO: ew for (auto i = 2; i < count; i++) {
for (auto i = 2; i < c; i++) { cmd += argv(i).value();
q_strlcat(cmd, argv(i).value().c_str(), sizeof(cmd)); if (i != count - 1) {
if (i != c - 1) cmd += ' ';
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;
} }
cmd += '\n';
new_alias->value = Z_Strdup(cmd); new_alias->value = cmd;
break; break;
} }
} }
@@ -195,9 +186,9 @@ namespace command {
*/ */
void _stuffcmds() { void _stuffcmds() {
char cmds[CMDLINE_LENGTH]; char cmds[CMDLINE_LENGTH];
int i, j, plus; int i, j;
plus = false; // On Unix, argv[0] is command name auto plus = false; // On Unix, argv[0] is command name
for (i = 0, j = 0; cmdline.string[i]; i++) { for (i = 0, j = 0; cmdline.string[i]; i++) {
if (cmdline.string[i] == '+') { if (cmdline.string[i] == '+') {
@@ -214,33 +205,32 @@ namespace command {
} }
cmds[j] = 0; cmds[j] = 0;
Cbuf_InsertText(cmds); buffer::insert_text(cmds);
} }
#include "default_cfg.hpp" #include "default_cfg.hpp"
void _exec() { void _exec() {
const char *f;
int mark;
if (argc() != 2) { if (argc() != 2) {
Con_Printf("exec <filename> : execute a script file\n"); Con_Printf("exec <filename> : execute a script file\n");
return; return;
} }
mark = Hunk_LowMark(); const auto mark = Hunk_LowMark();
auto filename = argv(1); const auto filename = argv(1);
f = (const char *) COM_LoadHunkFile(filename->c_str(), NULL);
if (!f && !strcmp(argv(1)->c_str(), "default.cfg")) { auto f = reinterpret_cast<const char *>(COM_LoadHunkFile(filename->c_str(), nullptr));
if (f == nullptr && argv(1) == "default.cfg") {
f = default_cfg; /* see above.. */ f = default_cfg; /* see above.. */
} }
if (!f) { if (f == nullptr) {
Con_Printf("couldn't exec %s\n", argv(1)->c_str()); Con_Printf("couldn't exec %s\n", argv(1)->c_str());
return; return;
} }
Con_Printf("execing %s\n", argv(1)->c_str()); Con_Printf("execing %s\n", argv(1)->c_str());
Cbuf_InsertText(f); buffer::insert_text(f);
if (f != default_cfg) { if (f != default_cfg) {
Hunk_FreeToLowMark(mark); Hunk_FreeToLowMark(mark);
} }
@@ -252,7 +242,7 @@ namespace command {
Con_Printf("\n"); Con_Printf("\n");
} }
char *tint_substring(const char *in, const char *substr, char *out, size_t outsize) { char *tint_substring(const char *in, const char *substr, char *out, const size_t outsize) {
int l; int l;
char *m; char *m;
q_strlcpy(out, in, outsize); q_strlcpy(out, in, outsize);
@@ -311,8 +301,8 @@ namespace command {
add("exec", _exec); add("exec", _exec);
add("echo", _echo); add("echo", _echo);
add("alias", _alias); add("alias", _alias);
add("cmd", Cmd_ForwardToServer); add("cmd", forward_to_server);
add("wait", set_wait); add("wait", _set_wait);
add("apropos", _apropos); add("apropos", _apropos);
add("find", _apropos); add("find", _apropos);
@@ -424,7 +414,7 @@ namespace command {
if (argc() == 0) if (argc() == 0)
return; // no tokens return; // no tokens
auto needle = argv(0).value(); const auto needle = argv(0).value();
// check functions // check functions
for (const auto &[name, ref]: REFS) { for (const auto &[name, ref]: REFS) {
if (!q_strcasecmp(needle.c_str(), name.c_str())) { if (!q_strcasecmp(needle.c_str(), name.c_str())) {
@@ -436,7 +426,7 @@ namespace command {
// check alias // check alias
for (const auto &[name, alias]: ALIASES) { for (const auto &[name, alias]: ALIASES) {
if (!q_strcasecmp(argv(0).value().c_str(), name.c_str())) { if (!q_strcasecmp(argv(0).value().c_str(), name.c_str())) {
Cbuf_InsertText(alias.value.c_str()); buffer::insert_text(alias.value);
return; return;
} }
} }
@@ -473,9 +463,6 @@ namespace command {
alias_view get_aliases() { alias_view get_aliases() {
return std::ranges::views::values(ALIASES); return std::ranges::views::values(ALIASES);
} }
void print(std::string text) {
}
} }
@@ -490,201 +477,72 @@ namespace command {
============================================================================= =============================================================================
*/ */
sizebuf_t cmd_text;
/* namespace command::buffer {
============ namespace {
Cbuf_Init constexpr std::size_t MAX_BUFFER_SIZE = 1 << 18;
============ std::string _buffer;
*/
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 init() {
_buffer = std::string{};
_buffer.reserve(MAX_BUFFER_SIZE);
}
/* void add_text(const std::string &text) {
============ if (_buffer.length() + text.length() >= MAX_BUFFER_SIZE) {
Cbuf_AddText Con_Printf("command::buffer::add_text(): overflow\n");
Adds command text at the end of the buffer
============
*/
void Cbuf_AddText(const char *text) {
int l;
l = Q_strlen(text);
if (cmd_text.cursize + l >= cmd_text.maxsize) {
Con_Printf("Cbuf_AddText: overflow\n");
return; return;
} }
SZ_Write(&cmd_text, text, Q_strlen(text)); _buffer.append(text);
} }
void insert_text(const std::string &text) {
/* if (_buffer.length() + text.length() >= MAX_BUFFER_SIZE) {
============ Con_Printf("command::buffer::insert_text(): overflow\n");
Cbuf_InsertText return;
Adds command text immediately after the current command
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;
// 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);
}
} }
/* _buffer = text + _buffer;
============ }
Cbuf_Execute
============
*/
void Cbuf_Execute(void) {
int i;
char *text;
char line[1024];
int quotes;
while (cmd_text.cursize) { void execute() {
// find a \n or ; line break while (!_buffer.empty()) {
text = (char *) cmd_text.data; std::string line{};
auto quotes = 0;
quotes = 0; for (const auto c: _buffer) {
for (i = 0; i < cmd_text.cursize; i++) { if (c == '"') {
if (text[i] == '"')
quotes++; quotes++;
if (!(quotes & 1) && text[i] == ';') }
if (!(quotes & 1) && c == ';') {
break; // don't break if inside a quoted string break; // don't break if inside a quoted string
if (text[i] == '\n') }
if (c == '\n') {
break; break;
} }
line += c;
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 // delete the text from the command buffer and move remaining commands down
// this is necessary because commands (exec, alias) can insert data at the // this is necessary because commands (exec, alias) can insert data at the
// beginning of the text buffer // beginning of the text buffer
if (i == cmd_text.cursize) if (line.length() + 1 == _buffer.length()) {
cmd_text.cursize = 0; _buffer.clear();
else { } else {
i++; _buffer = _buffer.substr(line.length() + 1);
cmd_text.cursize -= i;
memmove(text, text + i, cmd_text.cursize);
} }
// execute the command line // execute the command line
command::execute_string(line, command::source::command); execute_string(line, source::command);
if (command::is_waiting()) { if (is_waiting()) {
// skip out while text still remains in buffer, leaving it // skip out while text still remains in buffer, leaving it
// for next frame // for next frame
command::stop_waiting(); stop_waiting();
break; break;
} }
} }
} }
/*
==============================================================================
SCRIPT COMMANDS
==============================================================================
*/
/* id1/pak0.pak from 2021 re-release doesn't have a default.cfg
* embedding Quakespasm's customized default.cfg for that... */
/*
=============================================================================
COMMAND EXECUTION
=============================================================================
*/
/*
============
Cmd_AddCommand
============
*/
/*
============
Cmd_Exists
============
*/
/*
============
Cmd_CompleteCommand
============
*/
/*
============
Cmd_ExecuteString
A complete command line has been parsed, so try to execute it
FIXME: lookupnoadd the token to speed search?
============
*/
/*
===================
Cmd_ForwardToServer
Sends the entire command line over to the server
===================
*/
void Cmd_ForwardToServer(void) {
}
/*
================
Cmd_CheckParm
Returns the position (1 to argc-1) in the command's argument list
where the given parameter apears, or 0 if not present
================
*/
int Cmd_CheckParm(const char *parm) {
} }
+20 -70
View File
@@ -2,6 +2,7 @@
Copyright (C) 1996-2001 Id Software, Inc. Copyright (C) 1996-2001 Id Software, Inc.
Copyright (C) 2002-2009 John Fitzgibbons and others Copyright (C) 2002-2009 John Fitzgibbons and others
Copyright (C) 2010-2014 QuakeSpasm developers Copyright (C) 2010-2014 QuakeSpasm developers
Copyright (C) 2026 iikorni
This program is free software; you can redistribute it and/or This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License modify it under the terms of the GNU General Public License
@@ -26,54 +27,20 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//=========================================================================== //===========================================================================
/*
Any number of commands can be added in a frame, from several different sources.
Most commands come from either keybindings or console line input, but remote
servers can also send across commands and entire text files can be execed.
The + command line options are also added to the command buffer.
The game starts with a Cbuf_AddText ("exec quake.rc\n"); Cbuf_Execute ();
*/
void Cbuf_Init (void);
// allocates an initial text buffer that will grow as needed
void Cbuf_AddText (const char *text);
// as new commands are generated from the console or keybindings,
// the text is added to the end of the command buffer.
void Cbuf_InsertText (const char *text);
// when a command wants to issue other commands immediately, the text is
// inserted at the beginning of the buffer, before any remaining unexecuted
// commands.
void Cbuf_Execute (void);
// Pulls off \n terminated lines of text from the command buffer and sends
// them through Cmd_ExecuteString. Stops when the buffer is empty.
// Normally called once per frame, but may be explicitly invoked.
// Do not call inside a command function!
//===========================================================================
/*
Command execution takes a null terminated string, breaks it into tokens,
then searches for a command or variable that matches the first token.
Commands can come from three sources, but the handler functions may choose
to dissallow the action or forward it to a remote server if the source is
not apropriate.
*/
typedef void (*xcommand_t) (void);
typedef void (*xcommand_t)();
namespace command { namespace command {
namespace buffer {
void init();
void add_text(const std::string &text);
void insert_text(const std::string &text);
void execute();
}
enum class source { enum class source {
client, client,
command command
@@ -96,18 +63,24 @@ namespace command {
} }
}; };
using definition_view = std::ranges::elements_view<std::ranges::ref_view<std::map<std::string, definition, std::less<>>>, 1>; using definition_view = std::ranges::elements_view<std::ranges::ref_view<std::map<std::string, definition, std::less
using alias_view = std::ranges::elements_view<std::ranges::ref_view<std::map<std::string, alias, std::less<>>>, 1>; <> > >, 1>;
using alias_view = std::ranges::elements_view<std::ranges::ref_view<std::map<std::string, alias, std::less<> > >, 1>
;
void init(); void init();
void add(const std::string &name, xcommand_t cmd); void add(const std::string &name, xcommand_t cmd);
std::optional<std::string> complete(const std::string &partial); std::optional<std::string> complete(const std::string &partial);
bool exists(std::string_view lookup); bool exists(std::string_view lookup);
int argc(); int argc();
std::optional<std::string> argv(int arg); std::optional<std::string> argv(int arg);
std::string args(); std::string args();
int check_parm(const std::string &parm); int check_parm(const std::string &parm);
@@ -122,26 +95,3 @@ namespace command {
alias_view get_aliases(); alias_view get_aliases();
} }
// 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
// used by the cvar code to check for cvar / command name overlap
// attempts to match a partial command for automatic command line completion
// returns NULL if nothing fits
// Returns the position (1 to argc-1) in the command's argument list
// where the given parameter apears, or 0 if not present
// 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.
// 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.
// used by command functions to send output to either the graphics console or
// passed as a print message to the client
+116 -338
View File
@@ -22,6 +22,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// common.c -- misc functions used in client and server // common.c -- misc functions used in client and server
#include <cstring>
#include "quakedef.hpp" #include "quakedef.hpp"
#include "q_ctype.hpp" #include "q_ctype.hpp"
#include <errno.h> #include <errno.h>
@@ -37,9 +39,9 @@ int safemode;
convar registered = {"registered", "1", {.rom = true}}; /* set to correct value in COM_CheckRegistered() */ 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 */ 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 bool com_modified; // set true if using non-id files
qboolean fitzmode; bool fitzmode;
static void COM_Path_f(void); static void COM_Path_f(void);
@@ -58,7 +60,7 @@ char **com_argv;
#define CMDLINE_LENGTH 256 /* johnfitz -- mirrored in cmd.c */ #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; bool standard_quake = true, rogue, hipnotic;
// this graphic needs to be in the pak file to use registered features // this graphic needs to be in the pak file to use registered features
static unsigned short pop[] = static unsigned short pop[] =
@@ -309,232 +311,6 @@ int q_snprintf(char *str, size_t size, const char *format, ...) {
return ret; return ret;
} }
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;
}
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];
}
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_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;
count = 0;
while (str[count])
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;
}
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++;
}
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++;
}
return -1;
}
int Q_atoi(const char *str) {
int val;
int sign;
int c;
while (q_isspace(*str))
++str;
if (*str == '-') {
sign = -1;
str++;
} else
sign = 1;
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 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';
}
return 0;
}
float Q_atof(const char *str) {
double val;
int sign;
int c;
int decimal, total;
while (q_isspace(*str))
++str;
if (*str == '-') {
sign = -1;
str++;
} else
sign = 1;
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 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++;
}
if (decimal == -1)
return val * sign;
while (total > decimal) {
val /= 10;
total--;
}
return val * sign;
}
/* /*
============================================================================ ============================================================================
@@ -543,7 +319,7 @@ float Q_atof(const char *str) {
============================================================================ ============================================================================
*/ */
qboolean host_bigendian; bool host_bigendian;
short (*BigShort)(short l); short (*BigShort)(short l);
@@ -680,7 +456,7 @@ void MSG_WriteString(sizebuf_t *sb, const char *s) {
if (!s) if (!s)
SZ_Write(sb, "", 1); SZ_Write(sb, "", 1);
else else
SZ_Write(sb, s, Q_strlen(s) + 1); SZ_Write(sb, s, std::strlen(s) + 1);
} }
//johnfitz -- original behavior, 13.3 fixed point coords, max range +-4096 //johnfitz -- original behavior, 13.3 fixed point coords, max range +-4096
@@ -730,7 +506,7 @@ void MSG_WriteAngle16(sizebuf_t *sb, float f, unsigned int flags) {
// reading functions // reading functions
// //
int msg_readcount; int msg_readcount;
qboolean msg_badread; bool msg_badread;
void MSG_BeginReading(void) { void MSG_BeginReading(void) {
msg_readcount = 0; msg_readcount = 0;
@@ -924,18 +700,18 @@ void *SZ_GetSpace(sizebuf_t *buf, int length) {
} }
void SZ_Write(sizebuf_t *buf, const void *data, int length) { void SZ_Write(sizebuf_t *buf, const void *data, int length) {
Q_memcpy(SZ_GetSpace(buf, length), data, length); std::memcpy(SZ_GetSpace(buf, length), data, length);
} }
void SZ_Print(sizebuf_t *buf, const char *data) { void SZ_Print(sizebuf_t *buf, const char *data) {
int len = Q_strlen(data) + 1; int len = std::strlen(data) + 1;
if (buf->data[buf->cursize - 1]) { if (buf->data[buf->cursize - 1]) {
/* no trailing 0 */ /* no trailing 0 */
Q_memcpy((byte *) SZ_GetSpace(buf, len), data, len); std::memcpy(SZ_GetSpace(buf, len), data, len);
} else { } else {
/* write over trailing 0 */ /* write over trailing 0 */
Q_memcpy((byte *) SZ_GetSpace(buf, len - 1) - 1, data, len); std::memcpy(static_cast<byte *>(SZ_GetSpace(buf, len - 1)) - 1, data, len);
} }
} }
@@ -1090,6 +866,66 @@ void COM_AddExtension(char *path, const char *extension, size_t len) {
namespace common { namespace common {
void init() {
int i = 0x12345678;
/* U N I X */
/*
BE_ORDER: 12 34 56 78
U N I X
LE_ORDER: 78 56 34 12
X I N U
PDP_ORDER: 34 12 78 56
N U X I
*/
if (*reinterpret_cast<char *>(&i) == 0x12) {
host_bigendian = true;
}
else if (*reinterpret_cast<char *>(&i) == 0x78) {
host_bigendian = false;
}
else {
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 (check_param("-fitz").has_value()) {
fitzmode = true;
}
}
std::optional<size_t> check_param(std::string_view parm) {
for (auto i = 1; i < com_argc; i++) {
if (!com_argv[i]) {
continue; // NEXTSTEP sometimes clears appkit vars.
}
if (parm == com_argv[i]) {
return i;
}
}
return std::nullopt;
}
/** /**
* Parses a single token from a string-stream. * Parses a single token from a string-stream.
* *
@@ -1214,27 +1050,6 @@ namespace common {
} }
/*
================
COM_CheckParm
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;
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;
}
/* /*
================ ================
COM_CheckRegistered COM_CheckRegistered
@@ -1318,73 +1133,25 @@ void COM_InitArgv(int argc, char **argv) {
for (com_argc = 0; (com_argc < MAX_NUM_ARGVS) && (com_argc < argc); com_argc++) { for (com_argc = 0; (com_argc < MAX_NUM_ARGVS) && (com_argc < argc); com_argc++) {
largv[com_argc] = argv[com_argc]; largv[com_argc] = argv[com_argc];
if (!Q_strcmp("-safe", argv[com_argc])) if (!std::strcmp("-safe", argv[com_argc]))
safemode = 1; safemode = 1;
} }
largv[com_argc] = argvdummy; largv[com_argc] = argvdummy;
com_argv = largv; com_argv = largv;
if (COM_CheckParm("-rogue")) { if (common::check_param("-rogue").has_value()) {
rogue = true; rogue = true;
standard_quake = false; standard_quake = false;
} }
if (COM_CheckParm("-hipnotic") || COM_CheckParm("-quoth")) //johnfitz -- "-quoth" support if (common::check_param("-hipnotic").has_value() || common::check_param("-quoth").has_value()) //johnfitz -- "-quoth" support
{ {
hipnotic = true; hipnotic = true;
standard_quake = false; standard_quake = false;
} }
} }
/*
================
COM_Init
================
*/
void COM_Init(void) {
int i = 0x12345678;
/* U N I X */
/*
BE_ORDER: 12 34 56 78
U N I X
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.");
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;
}
/* /*
============ ============
va va
@@ -1632,7 +1399,7 @@ COM_FileExists
Returns whether the file is found in the quake filesystem. Returns whether the file is found in the quake filesystem.
=========== ===========
*/ */
qboolean COM_FileExists(const char *filename, unsigned int *path_id) { bool COM_FileExists(const char *filename, unsigned int *path_id) {
int ret = COM_FindFile(filename, NULL, NULL, path_id); int ret = COM_FindFile(filename, NULL, NULL, path_id);
return (ret == -1) ? false : true; return (ret == -1) ? false : true;
} }
@@ -1927,7 +1694,7 @@ static void COM_AddGameDirectory(const char *base, const char *dir) {
searchpath_t *search; searchpath_t *search;
pack_t *pak, *qspak; pack_t *pak, *qspak;
char pakfile[MAX_OSPATH]; char pakfile[MAX_OSPATH];
qboolean been_here = false; bool 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));
@@ -1951,7 +1718,7 @@ _add_path:
if (i != 0 || path_id != 1 || fitzmode) if (i != 0 || path_id != 1 || fitzmode)
qspak = NULL; qspak = NULL;
else { else {
qboolean old = com_modified; bool old = com_modified;
if (been_here) base = host_parms->userdir; if (been_here) base = host_parms->userdir;
q_snprintf(pakfile, sizeof(pakfile), "%s/quakespasm.pak", base); q_snprintf(pakfile, sizeof(pakfile), "%s/quakespasm.pak", base);
qspak = COM_LoadPackFile(pakfile); qspak = COM_LoadPackFile(pakfile);
@@ -2110,8 +1877,8 @@ static void COM_Game_f(void) {
Con_Printf("\"game\" changed to \"%s\"\n", COM_SkipPath(com_gamedir)); Con_Printf("\"game\" changed to \"%s\"\n", COM_SkipPath(com_gamedir));
VID_Lock(); VID_Lock();
Cbuf_AddText("exec quake.rc\n"); command::buffer::add_text("exec quake.rc\n");
Cbuf_AddText("vid_unlock\n"); command::buffer::add_text("vid_unlock\n");
} else //Diplay the current gamedir } else //Diplay the current gamedir
Con_Printf("\"game\" is \"%s\"\n", COM_SkipPath(com_gamedir)); Con_Printf("\"game\" is \"%s\"\n", COM_SkipPath(com_gamedir));
} }
@@ -2123,23 +1890,24 @@ 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;
registered.inscribe(); registered.inscribe();
cmdline.inscribe(); cmdline.inscribe();
command::add("path", COM_Path_f); command::add("path", COM_Path_f);
command::add("game", COM_Game_f); //johnfitz command::add("game", COM_Game_f); //johnfitz
i = COM_CheckParm("-basedir"); auto i = common::check_param("-basedir");
if (i && i < com_argc - 1) if (i.has_value() && i.value() < com_argc - 1) {
q_strlcpy(com_basedir, com_argv[i + 1], sizeof(com_basedir)); q_strlcpy(com_basedir, com_argv[i.value() + 1], sizeof(com_basedir));
else }
else {
q_strlcpy(com_basedir, host_parms->basedir, sizeof(com_basedir)); q_strlcpy(com_basedir, host_parms->basedir, sizeof(com_basedir));
}
j = strlen(com_basedir); const auto j = strlen(com_basedir);
if (j < 1) Sys_Error("Bad argument to -basedir"); if (j < 1) Sys_Error("Bad argument to -basedir");
if ((com_basedir[j - 1] == '\\') || (com_basedir[j - 1] == '/')) if ((com_basedir[j - 1] == '\\') || (com_basedir[j - 1] == '/')) {
com_basedir[j - 1] = 0; com_basedir[j - 1] = 0;
}
// start up with GAMENAME by default (id1) // start up with GAMENAME by default (id1)
COM_AddGameDirectory(com_basedir, GAMENAME); COM_AddGameDirectory(com_basedir, GAMENAME);
@@ -2151,24 +1919,34 @@ void COM_InitFilesystem(void) //johnfitz -- modified based on topaz's tutorial
com_base_searchpaths = com_searchpaths; com_base_searchpaths = com_searchpaths;
// add mission pack requests (only one should be specified) // add mission pack requests (only one should be specified)
if (COM_CheckParm("-rogue")) if (common::check_param("-rogue").has_value()) {
COM_AddGameDirectory(com_basedir, "rogue"); COM_AddGameDirectory(com_basedir, "rogue");
if (COM_CheckParm("-hipnotic")) }
if (common::check_param("-hipnotic").has_value()) {
COM_AddGameDirectory(com_basedir, "hipnotic"); COM_AddGameDirectory(com_basedir, "hipnotic");
if (COM_CheckParm("-quoth")) }
if (common::check_param("-quoth").has_value()) {
COM_AddGameDirectory(com_basedir, "quoth"); COM_AddGameDirectory(com_basedir, "quoth");
}
i = COM_CheckParm("-game"); i = common::check_param("-game");
if (i && i < com_argc - 1) { if (i.has_value() && i.value() < com_argc - 1) {
const char *p = com_argv[i + 1]; const char *p = com_argv[i.value() + 1];
if (!*p || !strcmp(p, ".") || strstr(p, "..") || strstr(p, "/") || strstr(p, "\\") || strstr(p, ":")) 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"); Sys_Error("gamedir should be a single directory name, not a path\n");
}
com_modified = true; com_modified = true;
// don't load mission packs twice // don't load mission packs twice
if (COM_CheckParm("-rogue") && !q_strcasecmp(p, "rogue")) p = NULL; if (common::check_param("-rogue").has_value() && !q_strcasecmp(p, "rogue")) {
if (p && COM_CheckParm("-hipnotic") && !q_strcasecmp(p, "hipnotic")) p = NULL; p = nullptr;
if (p && COM_CheckParm("-quoth") && !q_strcasecmp(p, "quoth")) p = NULL; }
if (p != NULL) { if (p && common::check_param("-hipnotic").has_value() && !q_strcasecmp(p, "hipnotic")) {
p = nullptr;
}
if (p && common::check_param("-quoth").has_value() && !q_strcasecmp(p, "quoth")) {
p = nullptr;
}
if (p != nullptr) {
COM_AddGameDirectory(com_basedir, p); COM_AddGameDirectory(com_basedir, p);
// QuakeSpasm extension: treat '-game missionpack' as '-missionpack' // QuakeSpasm extension: treat '-game missionpack' as '-missionpack'
if (!q_strcasecmp(p, "rogue")) { if (!q_strcasecmp(p, "rogue")) {
@@ -2509,8 +2287,8 @@ void LOC_LoadFile(const char *file) {
Con_DPrintf("LOC_LoadFile: malformed comment on line %d\n", lineno); Con_DPrintf("LOC_LoadFile: malformed comment on line %d\n", lineno);
} else if (equals) { } else if (equals) {
char *key_end = equals; char *key_end = equals;
qboolean leading_quote; bool leading_quote;
qboolean trailing_quote; bool trailing_quote;
locentry_t *entry; locentry_t *entry;
char *value_src; char *value_src;
char *value_dst; char *value_dst;
@@ -2675,7 +2453,7 @@ const char *LOC_GetRawString(const char *key) {
return NULL; return NULL;
entry = &localization.entries[idx - 1]; entry = &localization.entries[idx - 1];
if (!Q_strcmp(entry->key, key)) if (!std::strcmp(entry->key, key))
return entry->value; return entry->value;
++pos; ++pos;
@@ -2733,7 +2511,7 @@ static int LOC_ParseArg(const char **pstr) {
LOC_HasPlaceholders LOC_HasPlaceholders
================ ================
*/ */
qboolean LOC_HasPlaceholders(const char *str) { bool LOC_HasPlaceholders(const char *str) {
if (!localization.numindices) if (!localization.numindices)
return false; return false;
while (*str) { while (*str) {
@@ -2778,14 +2556,14 @@ size_t LOC_Format(const char *format, const char * (*getarg_fn)(int idx, void *u
insert = getarg_fn(argindex, userdata); insert = getarg_fn(argindex, userdata);
space_left = len - written; space_left = len - written;
insert_len = Q_strlen(insert); insert_len = std::strlen(insert);
if (insert_len > space_left) { if (insert_len > space_left) {
Con_DPrintf("LOC_Format: overflow at argument #%d\n", numargs); Con_DPrintf("LOC_Format: overflow at argument #%d\n", numargs);
insert_len = space_left; insert_len = space_left;
} }
Q_memcpy(out + written, insert, insert_len); std::memcpy(out + written, insert, insert_len);
written += insert_len; written += insert_len;
} }
+15 -43
View File
@@ -79,30 +79,13 @@ GENERIC_TYPES (IMPL_GENERIC_FUNCS, NO_COMMA)
#define SELECT_CLAMP(type, suffix) type: clamp_##suffix #define SELECT_CLAMP(type, suffix) type: clamp_##suffix
#define CLAMP(minval, val, maxval) _Generic((minval) + (val) + (maxval), \ #define CLAMP(minval, val, maxval) _Generic((minval) + (val) + (maxval), \
GENERIC_TYPES (SELECT_CLAMP, COMMA))(minval, val, maxval) GENERIC_TYPES (SELECT_CLAMP, COMMA))(minval, val, maxval)
#elif defined(__GNUC__)
#define CLAMP(_minval, x, _maxval) ({ \
const __typeof(x) x_ = (x); \
const __typeof(_minval) valmin_ = (_minval);\
const __typeof(_maxval) valmax_ = (_maxval);\
(void)(&x_ == &valmin_); \
(void)(&x_ == &valmax_); \
(x_ < valmin_) ? valmin_ : \
(x_ > valmax_) ? valmax_ : x_; \
})
#else
#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))
#endif #endif
// TODO: Maybe some special casing on an std::vector?
typedef struct sizebuf_s typedef struct sizebuf_s
{ {
qboolean allowoverflow; // if false, do a Sys_Error bool allowoverflow; // if false, do a Sys_Error
qboolean overflowed; // set to true if the buffer size failed bool overflowed; // set to true if the buffer size failed
byte *data; byte *data;
int maxsize; int maxsize;
int cursize; int cursize;
@@ -154,7 +137,7 @@ void Vec_Free (void **pvec);
//============================================================================ //============================================================================
extern qboolean host_bigendian; extern bool host_bigendian;
extern short (*BigShort) (short l); extern short (*BigShort) (short l);
extern short (*LittleShort) (short l); extern short (*LittleShort) (short l);
@@ -176,7 +159,7 @@ void MSG_WriteAngle (sizebuf_t *sb, float f, unsigned int flags);
void MSG_WriteAngle16 (sizebuf_t *sb, float f, unsigned int flags); //johnfitz void MSG_WriteAngle16 (sizebuf_t *sb, float f, unsigned int flags); //johnfitz
extern int msg_readcount; extern int msg_readcount;
extern qboolean msg_badread; // set if a read goes beyond end of message extern bool msg_badread; // set if a read goes beyond end of message
void MSG_BeginReading (void); void MSG_BeginReading (void);
int MSG_ReadChar (void); int MSG_ReadChar (void);
@@ -192,18 +175,6 @@ float MSG_ReadAngle16 (unsigned int flags); //johnfitz
//============================================================================ //============================================================================
void Q_memset (void *dest, int fill, size_t count);
void Q_memcpy (void *dest, const void *src, size_t count);
int Q_memcmp (const void *m1, const void *m2, size_t count);
void Q_strcpy (char *dest, const char *src);
void Q_strncpy (char *dest, const char *src, int count);
int Q_strlen (const char *str);
char *Q_strrchr (const char *s, char c);
void Q_strcat (char *dest, const char *src);
int Q_strcmp (const char *s1, const char *s2);
int Q_strncmp (const char *s1, const char *s2, int count);
int Q_atoi (const char *str);
float Q_atof (const char *str);
#include "strl_fn.hpp" #include "strl_fn.hpp"
@@ -225,10 +196,14 @@ extern int q_vsnprintf(char *str, size_t size, const char *format, va_list args)
//============================================================================ //============================================================================
extern qboolean com_eof; extern bool com_eof;
namespace common { namespace common {
void init();
std::optional<size_t> check_param(std::string_view parm);
std::optional<std::string> parse_token(std::istringstream &ss); std::optional<std::string> parse_token(std::istringstream &ss);
std::string parse_string_newline(std::istringstream &ss); std::string parse_string_newline(std::istringstream &ss);
@@ -247,9 +222,6 @@ extern int safemode;
-nomouse, -nojoy, -nolan -nomouse, -nojoy, -nolan
*/ */
int COM_CheckParm (const char *parm);
void COM_Init (void);
void COM_InitArgv (int argc, char **argv); void COM_InitArgv (int argc, char **argv);
void COM_InitFilesystem (void); void COM_InitFilesystem (void);
@@ -274,7 +246,7 @@ void LOC_Init (void);
void LOC_Shutdown (void); void LOC_Shutdown (void);
const char* LOC_GetRawString (const char *key); const char* LOC_GetRawString (const char *key);
const char* LOC_GetString (const char *key); const char* LOC_GetString (const char *key);
qboolean LOC_HasPlaceholders (const char *str); bool LOC_HasPlaceholders (const char *str);
size_t LOC_Format (const char *format, const char* (*getarg_fn)(int idx, void* userdata), void* userdata, char* out, size_t len); size_t LOC_Format (const char *format, const char* (*getarg_fn)(int idx, void* userdata), void* userdata, char* out, size_t len);
//============================================================================ //============================================================================
@@ -317,7 +289,7 @@ extern int file_from_pak; // global indicating that file came from a pak
void COM_WriteFile (const char *filename, const void *data, int len); void COM_WriteFile (const char *filename, const void *data, int len);
int COM_OpenFile (const char *filename, int *handle, unsigned int *path_id); int COM_OpenFile (const char *filename, int *handle, unsigned int *path_id);
int COM_FOpenFile (const char *filename, FILE **file, unsigned int *path_id); int COM_FOpenFile (const char *filename, FILE **file, unsigned int *path_id);
qboolean COM_FileExists (const char *filename, unsigned int *path_id); bool COM_FileExists (const char *filename, unsigned int *path_id);
void COM_CloseFile (int h); void COM_CloseFile (int h);
// these procedures open a file using COM_FindFile and loads it into a proper // these procedures open a file using COM_FindFile and loads it into a proper
@@ -359,7 +331,7 @@ byte *COM_LoadMallocFile_TextMode_OSPath (const char *path, long *len_out);
typedef struct _fshandle_t typedef struct _fshandle_t
{ {
FILE *file; FILE *file;
qboolean pak; /* is the file read from a pak */ bool pak; /* is the file read from a pak */
long start; /* file or data start position */ long start; /* file or data start position */
long length; /* file or data size */ long length; /* file or data size */
long pos; /* current position relative to start */ long pos; /* current position relative to start */
@@ -378,8 +350,8 @@ long FS_filelength (fshandle_t *fh);
extern convar registered; extern convar registered;
extern qboolean standard_quake, rogue, hipnotic; extern bool standard_quake, rogue, hipnotic;
extern qboolean fitzmode; extern bool fitzmode;
/* if true, run in fitzquake mode disabling custom quakespasm hacks */ /* if true, run in fitzquake mode disabling custom quakespasm hacks */
#endif /* _Q_COMMON_H */ #endif /* _Q_COMMON_H */
+123 -223
View File
@@ -21,6 +21,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/ */
// console.c // console.c
#include <cstring>
#include <sys/types.h> #include <sys/types.h>
#include <time.h> #include <time.h>
#include <sys/stat.h> #include <sys/stat.h>
@@ -42,7 +43,7 @@ float con_cursorspeed = 4;
int con_buffersize; //johnfitz -- user can now override default int con_buffersize; //johnfitz -- user can now override default
qboolean con_forcedup; // because no entities to refresh bool con_forcedup; // because no entities to refresh
int con_totallines; // total lines in console scrollback int con_totallines; // total lines in console scrollback
int con_backscroll; // lines up from bottom to display int con_backscroll; // lines up from bottom to display
@@ -61,9 +62,9 @@ float con_times[NUM_CON_TIMES]; // realtime time the line was generated
int con_vislines; int con_vislines;
qboolean con_debuglog = false; bool con_debuglog = false;
qboolean con_initialized; bool con_initialized;
/* /*
@@ -73,8 +74,7 @@ Con_Quakebar -- johnfitz -- returns a bar of the desired length, but never wider
includes a newline, unless len >= con_linewidth. includes a newline, unless len >= con_linewidth.
================ ================
*/ */
const char *Con_Quakebar (int len) const char *Con_Quakebar(int len) {
{
static char bar[42]; static char bar[42];
int i; int i;
@@ -86,12 +86,10 @@ const char *Con_Quakebar (int len)
bar[i] = '\36'; bar[i] = '\36';
bar[len - 1] = '\37'; bar[len - 1] = '\37';
if (len < con_linewidth) if (len < con_linewidth) {
{
bar[len] = '\n'; bar[len] = '\n';
bar[len + 1] = 0; bar[len + 1] = 0;
} } else
else
bar[len] = 0; bar[len] = 0;
return bar; return bar;
@@ -104,27 +102,20 @@ Con_ToggleConsole_f
*/ */
extern int history_line; //johnfitz extern int history_line; //johnfitz
void Con_ToggleConsole_f (void) void Con_ToggleConsole_f(void) {
{ if (key_dest == key_console/* || (key_dest == key_game && con_forcedup)*/) {
if (key_dest == key_console/* || (key_dest == key_game && con_forcedup)*/)
{
key_lines[edit_line][1] = 0; // clear any typing key_lines[edit_line][1] = 0; // clear any typing
key_linepos = 1; key_linepos = 1;
con_backscroll = 0; //johnfitz -- toggleconsole should return you to the bottom of the scrollback con_backscroll = 0; //johnfitz -- toggleconsole should return you to the bottom of the scrollback
history_line = edit_line; //johnfitz -- it should also return you to the bottom of the command history history_line = edit_line; //johnfitz -- it should also return you to the bottom of the command history
if (cls.state == ca_connected) if (cls.state == ca_connected) {
{
IN_Activate(); IN_Activate();
key_dest = key_game; key_dest = key_game;
} } else {
else
{
M_Menu_Main_f(); M_Menu_Main_f();
} }
} } else {
else
{
IN_Deactivate(modestate == MS_WINDOWED); IN_Deactivate(modestate == MS_WINDOWED);
key_dest = key_console; key_dest = key_console;
} }
@@ -138,10 +129,9 @@ void Con_ToggleConsole_f (void)
Con_Clear_f Con_Clear_f
================ ================
*/ */
static void Con_Clear_f (void) static void Con_Clear_f(void) {
{
if (con_text) if (con_text)
Q_memset (con_text, ' ', con_buffersize); //johnfitz -- con_buffersize replaces CON_TEXTSIZE std::memset(con_text, ' ', con_buffersize); //johnfitz -- con_buffersize replaces CON_TEXTSIZE
con_backscroll = 0; //johnfitz -- if console is empty, being scrolled up is confusing con_backscroll = 0; //johnfitz -- if console is empty, being scrolled up is confusing
} }
@@ -150,8 +140,7 @@ static void Con_Clear_f (void)
Con_Dump_f -- johnfitz -- adapted from quake2 source Con_Dump_f -- johnfitz -- adapted from quake2 source
================ ================
*/ */
static void Con_Dump_f (void) static void Con_Dump_f(void) {
{
int l, x; int l, x;
const char *line; const char *line;
FILE *f; FILE *f;
@@ -161,15 +150,13 @@ static void Con_Dump_f (void)
q_snprintf(name, sizeof(name), "%s/condump.txt", com_gamedir); q_snprintf(name, sizeof(name), "%s/condump.txt", com_gamedir);
COM_CreatePath(name); COM_CreatePath(name);
f = fopen(name, "w"); f = fopen(name, "w");
if (!f) if (!f) {
{
Con_Printf("ERROR: couldn't open file %s.\n", name); Con_Printf("ERROR: couldn't open file %s.\n", name);
return; return;
} }
// skip initial empty lines // skip initial empty lines
for (l = con_current - con_totallines + 1; l <= con_current; l++) for (l = con_current - con_totallines + 1; l <= con_current; l++) {
{
line = con_text + (l % con_totallines) * con_linewidth; line = con_text + (l % con_totallines) * con_linewidth;
for (x = 0; x < con_linewidth; x++) for (x = 0; x < con_linewidth; x++)
if (line[x] != ' ') if (line[x] != ' ')
@@ -180,12 +167,10 @@ static void Con_Dump_f (void)
// write the remaining lines // write the remaining lines
buffer[con_linewidth] = 0; buffer[con_linewidth] = 0;
for ( ; l <= con_current; l++) for (; l <= con_current; l++) {
{
line = con_text + (l % con_totallines) * con_linewidth; line = con_text + (l % con_totallines) * con_linewidth;
strncpy(buffer, line, con_linewidth); strncpy(buffer, line, con_linewidth);
for (x = con_linewidth - 1; x >= 0; x--) for (x = con_linewidth - 1; x >= 0; x--) {
{
if (buffer[x] == ' ') if (buffer[x] == ' ')
buffer[x] = 0; buffer[x] = 0;
else else
@@ -206,8 +191,7 @@ static void Con_Dump_f (void)
Con_ClearNotify Con_ClearNotify
================ ================
*/ */
void Con_ClearNotify (void) void Con_ClearNotify(void) {
{
int i; int i;
for (i = 0; i < NUM_CON_TIMES; i++) for (i = 0; i < NUM_CON_TIMES; i++)
@@ -220,8 +204,7 @@ void Con_ClearNotify (void)
Con_MessageMode_f Con_MessageMode_f
================ ================
*/ */
static void Con_MessageMode_f (void) static void Con_MessageMode_f(void) {
{
if (cls.state != ca_connected || cls.demoplayback) if (cls.state != ca_connected || cls.demoplayback)
return; return;
chat_team = false; chat_team = false;
@@ -233,8 +216,7 @@ static void Con_MessageMode_f (void)
Con_MessageMode2_f Con_MessageMode2_f
================ ================
*/ */
static void Con_MessageMode2_f (void) static void Con_MessageMode2_f(void) {
{
if (cls.state != ca_connected || cls.demoplayback) if (cls.state != ca_connected || cls.demoplayback)
return; return;
chat_team = true; chat_team = true;
@@ -249,8 +231,7 @@ Con_CheckResize
If the line width has changed, reformat the buffer. If the line width has changed, reformat the buffer.
================ ================
*/ */
void Con_CheckResize (void) void Con_CheckResize(void) {
{
int i, j, width, oldwidth, oldtotallines, numlines, numchars; int i, j, width, oldwidth, oldtotallines, numlines, numchars;
char *tbuf; //johnfitz -- tbuf no longer a static array char *tbuf; //johnfitz -- tbuf no longer a static array
int mark; //johnfitz int mark; //johnfitz
@@ -277,13 +258,11 @@ void Con_CheckResize (void)
mark = Hunk_LowMark(); //johnfitz mark = Hunk_LowMark(); //johnfitz
tbuf = (char *) Hunk_Alloc(con_buffersize); //johnfitz tbuf = (char *) Hunk_Alloc(con_buffersize); //johnfitz
Q_memcpy (tbuf, con_text, con_buffersize);//johnfitz -- con_buffersize replaces CON_TEXTSIZE std::memcpy(tbuf, con_text, con_buffersize); //johnfitz -- con_buffersize replaces CON_TEXTSIZE
Q_memset (con_text, ' ', con_buffersize);//johnfitz -- con_buffersize replaces CON_TEXTSIZE std::memset(con_text, ' ', con_buffersize); //johnfitz -- con_buffersize replaces CON_TEXTSIZE
for (i = 0; i < numlines; i++) for (i = 0; i < numlines; i++) {
{ for (j = 0; j < numchars; j++) {
for (j = 0; j < numchars; j++)
{
con_text[(con_totallines - 1 - i) * con_linewidth + j] = con_text[(con_totallines - 1 - i) * con_linewidth + j] =
tbuf[((con_current - i + oldtotallines) % oldtotallines) * oldwidth + j]; tbuf[((con_current - i + oldtotallines) % oldtotallines) * oldwidth + j];
} }
@@ -303,23 +282,19 @@ void Con_CheckResize (void)
Con_Init Con_Init
================ ================
*/ */
void Con_Init (void) void Con_Init(void) {
{
int i;
//johnfitz -- user settable console buffer size //johnfitz -- user settable console buffer size
i = COM_CheckParm("-consize"); auto i = common::check_param("-consize");
if (i && i < com_argc-1) { if (i.has_value() && i.value() < com_argc - 1) {
con_buffersize = Q_atoi(com_argv[i+1])*1024; con_buffersize = std::atoi(com_argv[i.value() + 1]) * 1024;
if (con_buffersize < CON_MINSIZE) if (con_buffersize < CON_MINSIZE)
con_buffersize = CON_MINSIZE; con_buffersize = CON_MINSIZE;
} } else
else
con_buffersize = CON_TEXTSIZE; con_buffersize = CON_TEXTSIZE;
//johnfitz //johnfitz
con_text = (char *) Hunk_AllocName(con_buffersize, "context"); //johnfitz -- con_buffersize replaces CON_TEXTSIZE con_text = (char *) Hunk_AllocName(con_buffersize, "context"); //johnfitz -- con_buffersize replaces CON_TEXTSIZE
Q_memset (con_text, ' ', con_buffersize);//johnfitz -- con_buffersize replaces CON_TEXTSIZE std::memset(con_text, ' ', con_buffersize); //johnfitz -- con_buffersize replaces CON_TEXTSIZE
con_linewidth = -1; con_linewidth = -1;
//johnfitz -- no need to run Con_CheckResize here //johnfitz -- no need to run Con_CheckResize here
@@ -348,8 +323,7 @@ void Con_Init (void)
Con_Linefeed Con_Linefeed
=============== ===============
*/ */
static void Con_Linefeed (void) static void Con_Linefeed(void) {
{
//johnfitz -- improved scrolling //johnfitz -- improved scrolling
if (con_backscroll) if (con_backscroll)
con_backscroll++; con_backscroll++;
@@ -359,7 +333,7 @@ static void Con_Linefeed (void)
con_x = 0; con_x = 0;
con_current++; con_current++;
Q_memset (&con_text[(con_current%con_totallines)*con_linewidth], ' ', con_linewidth); std::memset(&con_text[(con_current % con_totallines) * con_linewidth], ' ', con_linewidth);
} }
/* /*
@@ -371,40 +345,31 @@ All console printing must go through this in order to be logged to disk
If no console is visible, the notify window will pop up. If no console is visible, the notify window will pop up.
================ ================
*/ */
static void Con_Print (const char *txt) static void Con_Print(const char *txt) {
{
int y; int y;
int c, l; int c, l;
static int cr; static int cr;
int mask; int mask;
qboolean boundary; bool boundary;
//con_backscroll = 0; //johnfitz -- better console scrolling //con_backscroll = 0; //johnfitz -- better console scrolling
if (txt[0] == 1) if (txt[0] == 1) {
{
mask = 128; // go to colored text mask = 128; // go to colored text
S_LocalSound("misc/talk.wav"); // play talk wav S_LocalSound("misc/talk.wav"); // play talk wav
txt++; txt++;
} } else if (txt[0] == 2) {
else if (txt[0] == 2)
{
mask = 128; // go to colored text mask = 128; // go to colored text
txt++; txt++;
} } else
else
mask = 0; mask = 0;
boundary = true; boundary = true;
while ( (c = *txt) ) while ((c = *txt)) {
{ if (c <= ' ') {
if (c <= ' ')
{
boundary = true; boundary = true;
} } else if (boundary) {
else if (boundary)
{
// count word length // count word length
for (l = 0; l < con_linewidth; l++) for (l = 0; l < con_linewidth; l++)
if (txt[l] <= ' ') if (txt[l] <= ' ')
@@ -419,22 +384,19 @@ static void Con_Print (const char *txt)
txt++; txt++;
if (cr) if (cr) {
{
con_current--; con_current--;
cr = false; cr = false;
} }
if (!con_x) if (!con_x) {
{
Con_Linefeed(); Con_Linefeed();
// mark time for transparent overlay // mark time for transparent overlay
if (con_current >= 0) if (con_current >= 0)
con_times[con_current % NUM_CON_TIMES] = realtime; con_times[con_current % NUM_CON_TIMES] = realtime;
} }
switch (c) switch (c) {
{
case '\n': case '\n':
con_x = 0; con_x = 0;
break; break;
@@ -466,13 +428,11 @@ static int log_fd = -1; // log file descriptor
Con_DebugLog Con_DebugLog
================ ================
*/ */
void Con_DebugLog(const char *msg) void Con_DebugLog(const char *msg) {
{
if (log_fd == -1) if (log_fd == -1)
return; return;
if (write(log_fd, msg, strlen(msg)) < 0) if (write(log_fd, msg, strlen(msg)) < 0) {
{
close(log_fd); close(log_fd);
log_fd = -1; log_fd = -1;
con_debuglog = false; con_debuglog = false;
@@ -489,11 +449,11 @@ Handles cursor positioning, line wrapping, etc
================ ================
*/ */
#define MAXPRINTMSG 4096 #define MAXPRINTMSG 4096
void Con_Printf (const char *fmt, ...)
{ void Con_Printf(const char *fmt, ...) {
va_list argptr; va_list argptr;
char msg[MAXPRINTMSG]; char msg[MAXPRINTMSG];
static qboolean inupdate; static bool inupdate;
va_start(argptr, fmt); va_start(argptr, fmt);
q_vsnprintf(msg, sizeof(msg), fmt, argptr); q_vsnprintf(msg, sizeof(msg), fmt, argptr);
@@ -516,12 +476,10 @@ void Con_Printf (const char *fmt, ...)
Con_Print(msg); Con_Print(msg);
// update the screen if the console is displayed // update the screen if the console is displayed
if (cls.signon != SIGNONS && !scr_disabled_for_loading ) if (cls.signon != SIGNONS && !scr_disabled_for_loading) {
{
// protect against infinite loop if something in SCR_UpdateScreen calls // protect against infinite loop if something in SCR_UpdateScreen calls
// Con_Printd // Con_Printd
if (!inupdate) if (!inupdate) {
{
inupdate = true; inupdate = true;
SCR_UpdateScreen(); SCR_UpdateScreen();
inupdate = false; inupdate = false;
@@ -538,8 +496,7 @@ use for "exceeds standard limit of" messages, which are only relevant for develo
targetting vanilla engines targetting vanilla engines
================ ================
*/ */
void Con_DWarning (const char *fmt, ...) void Con_DWarning(const char *fmt, ...) {
{
va_list argptr; va_list argptr;
char msg[MAXPRINTMSG]; char msg[MAXPRINTMSG];
@@ -559,13 +516,12 @@ void Con_DWarning (const char *fmt, ...)
Con_Warning -- johnfitz -- prints a warning to the console Con_Warning -- johnfitz -- prints a warning to the console
================ ================
*/ */
void Con_Warning (const char *fmt, ...) void Con_Warning(const char *fmt, ...) {
{
va_list argptr; va_list argptr;
char msg[MAXPRINTMSG]; char msg[MAXPRINTMSG];
va_start(argptr, fmt); va_start(argptr, fmt);
q_vsnprintf (msg, sizeof(msg), fmt, argptr); std::vsnprintf(msg, sizeof(msg), fmt, argptr);
va_end(argptr); va_end(argptr);
Con_SafePrintf("\x02Warning: "); Con_SafePrintf("\x02Warning: ");
@@ -579,8 +535,7 @@ Con_DPrintf
A Con_Printf that only shows up if the "developer" cvar is set A Con_Printf that only shows up if the "developer" cvar is set
================ ================
*/ */
void Con_DPrintf (const char *fmt, ...) void Con_DPrintf(const char *fmt, ...) {
{
va_list argptr; va_list argptr;
char msg[MAXPRINTMSG]; char msg[MAXPRINTMSG];
@@ -601,13 +556,11 @@ Con_DPrintf2 -- johnfitz -- only prints if "developer" >= 2
currently not used currently not used
================ ================
*/ */
void Con_DPrintf2 (const char *fmt, ...) void Con_DPrintf2(const char *fmt, ...) {
{
va_list argptr; va_list argptr;
char msg[MAXPRINTMSG]; char msg[MAXPRINTMSG];
if (developer.value >= 2) if (developer.value >= 2) {
{
va_start(argptr, fmt); va_start(argptr, fmt);
q_vsnprintf(msg, sizeof(msg), fmt, argptr); q_vsnprintf(msg, sizeof(msg), fmt, argptr);
va_end(argptr); va_end(argptr);
@@ -623,8 +576,7 @@ Con_SafePrintf
Okay to call even when the screen can't be updated Okay to call even when the screen can't be updated
================== ==================
*/ */
void Con_SafePrintf (const char *fmt, ...) void Con_SafePrintf(const char *fmt, ...) {
{
va_list argptr; va_list argptr;
char msg[MAXPRINTMSG]; char msg[MAXPRINTMSG];
int temp; int temp;
@@ -645,8 +597,8 @@ Con_CenterPrintf -- johnfitz -- pad each line with spaces to make it appear cent
================ ================
*/ */
void Con_CenterPrintf(int linewidth, const char *fmt, ...) FUNC_PRINTF(2, 3); void Con_CenterPrintf(int linewidth, const char *fmt, ...) FUNC_PRINTF(2, 3);
void Con_CenterPrintf (int linewidth, const char *fmt, ...)
{ void Con_CenterPrintf(int linewidth, const char *fmt, ...) {
va_list argptr; va_list argptr;
char msg[MAXPRINTMSG]; //the original message char msg[MAXPRINTMSG]; //the original message
char line[MAXPRINTMSG]; //one line from the message char line[MAXPRINTMSG]; //one line from the message
@@ -659,8 +611,7 @@ void Con_CenterPrintf (int linewidth, const char *fmt, ...)
va_end(argptr); va_end(argptr);
linewidth = std::min(linewidth, con_linewidth); linewidth = std::min(linewidth, con_linewidth);
for (src = msg; *src; ) for (src = msg; *src;) {
{
dst = line; dst = line;
while (*src && *src != '\n') while (*src && *src != '\n')
*dst++ = *src++; *dst++ = *src++;
@@ -669,14 +620,12 @@ void Con_CenterPrintf (int linewidth, const char *fmt, ...)
src++; src++;
len = strlen(line); len = strlen(line);
if (len < linewidth) if (len < linewidth) {
{
s = (linewidth - len) / 2; s = (linewidth - len) / 2;
memset(spaces, ' ', s); memset(spaces, ' ', s);
spaces[s] = 0; spaces[s] = 0;
Con_Printf("%s%s\n", spaces, line); Con_Printf("%s%s\n", spaces, line);
} } else
else
Con_Printf("%s\n", line); Con_Printf("%s\n", line);
} }
} }
@@ -686,8 +635,7 @@ void Con_CenterPrintf (int linewidth, const char *fmt, ...)
Con_LogCenterPrint -- johnfitz -- echo centerprint message to the console Con_LogCenterPrint -- johnfitz -- echo centerprint message to the console
================== ==================
*/ */
void Con_LogCenterPrint (const char *str) void Con_LogCenterPrint(const char *str) {
{
if (!strcmp(str, con_lastcenterstring)) if (!strcmp(str, con_lastcenterstring))
return; //ignore duplicates return; //ignore duplicates
@@ -696,8 +644,7 @@ void Con_LogCenterPrint (const char *str)
strcpy(con_lastcenterstring, str); strcpy(con_lastcenterstring, str);
if (con_logcenterprint.value) if (con_logcenterprint.value) {
{
Con_Printf("%s", Con_Quakebar(40)); Con_Printf("%s", Con_Quakebar(40));
Con_CenterPrintf(40, "%s\n", str); Con_CenterPrintf(40, "%s\n", str);
Con_Printf("%s", Con_Quakebar(40)); Con_Printf("%s", Con_Quakebar(40));
@@ -716,17 +663,18 @@ void Con_LogCenterPrint (const char *str)
//johnfitz -- tab completion stuff //johnfitz -- tab completion stuff
//unique defs //unique defs
char key_tabpartial[MAXCMDLINE]; char key_tabpartial[MAXCMDLINE];
typedef struct tab_s
{ typedef struct tab_s {
const char *name; const char *name;
const char *type; const char *type;
struct tab_s *next; struct tab_s *next;
struct tab_s *prev; struct tab_s *prev;
} tab_t; } tab_t;
tab_t *tablist; tab_t *tablist;
//defs from elsewhere //defs from elsewhere
extern qboolean keydown[256]; extern bool keydown[256];
#define MAX_ALIAS_NAME 32 #define MAX_ALIAS_NAME 32
/* /*
@@ -740,27 +688,22 @@ tablist is a doubly-linked loop, alphabetized by name
// bash_partial is the string that can be expanded, // bash_partial is the string that can be expanded,
// aka Linux Bash shell. -- S.A. // aka Linux Bash shell. -- S.A.
static char bash_partial[80]; static char bash_partial[80];
static qboolean bash_singlematch; static bool bash_singlematch;
void AddToTabList (const char *name, const char *type) void AddToTabList(const char *name, const char *type) {
{
tab_t *t, *insert; tab_t *t, *insert;
char *i_bash; char *i_bash;
const char *i_name; const char *i_name;
if (!*bash_partial) if (!*bash_partial) {
{
strncpy(bash_partial, name, 79); strncpy(bash_partial, name, 79);
bash_partial[79] = '\0'; bash_partial[79] = '\0';
} } else {
else
{
bash_singlematch = 0; bash_singlematch = 0;
// find max common between bash_partial and name // find max common between bash_partial and name
i_bash = bash_partial; i_bash = bash_partial;
i_name = name; i_name = name;
while (*i_bash && (*i_bash == *i_name)) while (*i_bash && (*i_bash == *i_name)) {
{
i_bash++; i_bash++;
i_name++; i_name++;
} }
@@ -776,20 +719,17 @@ void AddToTabList (const char *name, const char *type)
tablist = t; tablist = t;
t->next = t; t->next = t;
t->prev = t; t->prev = t;
} } else if (strcmp(name, tablist->name) < 0) //insert at front
else if (strcmp(name, tablist->name) < 0) //insert at front
{ {
t->next = tablist; t->next = tablist;
t->prev = tablist->prev; t->prev = tablist->prev;
t->next->prev = t; t->next->prev = t;
t->prev->next = t; t->prev->next = t;
tablist = t; tablist = t;
} } else //insert later
else //insert later
{ {
insert = tablist; insert = tablist;
do do {
{
if (strcmp(name, insert->name) < 0) if (strcmp(name, insert->name) < 0)
break; break;
insert = insert->next; insert = insert->next;
@@ -802,8 +742,7 @@ void AddToTabList (const char *name, const char *type)
} }
} }
typedef struct arg_completion_type_s typedef struct arg_completion_type_s {
{
const char *command; const char *command;
filelist_item_t **filelist; filelist_item_t **filelist;
} arg_completion_type_t; } arg_completion_type_t;
@@ -818,15 +757,14 @@ static const arg_completion_type_t arg_completion_types[] =
{"timedemo ", &demolist} {"timedemo ", &demolist}
}; };
static const int num_arg_completion_types = Q_COUNTOF(arg_completion_types); static constexpr int num_arg_completion_types = std::size(arg_completion_types);
/* /*
============ ============
FindCompletion -- stevenaaus FindCompletion -- stevenaaus
============ ============
*/ */
const char *FindCompletion (const char *partial, filelist_item_t *filelist, int *nummatches_out) const char *FindCompletion(const char *partial, filelist_item_t *filelist, int *nummatches_out) {
{
static char matched[40]; static char matched[40];
char *i_matched, *i_name; char *i_matched, *i_name;
filelist_item_t *file; filelist_item_t *file;
@@ -836,22 +774,17 @@ const char *FindCompletion (const char *partial, filelist_item_t *filelist, int
plen = strlen(partial); plen = strlen(partial);
match = 0; match = 0;
for (file = filelist, init = 0; file; file = file->next) for (file = filelist, init = 0; file; file = file->next) {
{ if (!strncmp(file->name, partial, plen)) {
if (!strncmp(file->name, partial, plen)) if (init == 0) {
{
if (init == 0)
{
init = 1; init = 1;
strncpy(matched, file->name, sizeof(matched) - 1); strncpy(matched, file->name, sizeof(matched) - 1);
matched[sizeof(matched) - 1] = '\0'; matched[sizeof(matched) - 1] = '\0';
} } else {
else // find max common
{ // find max common
i_matched = matched; i_matched = matched;
i_name = file->name; i_name = file->name;
while (*i_matched && (*i_matched == *i_name)) while (*i_matched && (*i_matched == *i_name)) {
{
i_matched++; i_matched++;
i_name++; i_name++;
} }
@@ -863,10 +796,8 @@ const char *FindCompletion (const char *partial, filelist_item_t *filelist, int
*nummatches_out = match; *nummatches_out = match;
if (match > 1) if (match > 1) {
{ for (file = filelist; file; file = file->next) {
for (file = filelist; file; file = file->next)
{
if (!strncmp(file->name, partial, plen)) if (!strncmp(file->name, partial, plen))
Con_SafePrintf(" %s\n", file->name); Con_SafePrintf(" %s\n", file->name);
} }
@@ -881,8 +812,7 @@ const char *FindCompletion (const char *partial, filelist_item_t *filelist, int
BuildTabList -- johnfitz BuildTabList -- johnfitz
============ ============
*/ */
void BuildTabList (const char *partial) void BuildTabList(const char *partial) {
{
int len; int len;
tablist = NULL; tablist = NULL;
@@ -892,15 +822,15 @@ void BuildTabList (const char *partial)
bash_singlematch = 1; bash_singlematch = 1;
for (const auto cvar: convar::get_variables()) for (const auto cvar: convar::get_variables())
if (!Q_strncmp (partial, cvar->name.c_str(), len)) if (!std::strncmp(partial, cvar->name.c_str(), len))
AddToTabList(cvar->name.c_str(), "cvar"); AddToTabList(cvar->name.c_str(), "cvar");
for (const auto &ccmd: command::get_commands()) for (const auto &ccmd: command::get_commands())
if (!Q_strncmp (partial,ccmd.name.c_str(), len)) if (!std::strncmp(partial, ccmd.name.c_str(), len))
AddToTabList(ccmd.name.c_str(), "command"); AddToTabList(ccmd.name.c_str(), "command");
for (const auto &alias: command::get_aliases()) for (const auto &alias: command::get_aliases())
if (!Q_strncmp (partial, alias.name.c_str(), len)) if (!std::strncmp(partial, alias.name.c_str(), len))
AddToTabList(alias.name.c_str(), "alias"); AddToTabList(alias.name.c_str(), "alias");
} }
@@ -909,8 +839,7 @@ void BuildTabList (const char *partial)
Con_TabComplete -- johnfitz Con_TabComplete -- johnfitz
============ ============
*/ */
void Con_TabComplete (void) void Con_TabComplete(void) {
{
char partial[MAXCMDLINE]; char partial[MAXCMDLINE];
const char *match; const char *match;
static char *c; static char *c;
@@ -936,15 +865,13 @@ void Con_TabComplete (void)
// Map autocomplete function -- S.A // Map autocomplete function -- S.A
// Since we don't have argument completion, this hack will do for now... // Since we don't have argument completion, this hack will do for now...
for (j=0; j<num_arg_completion_types; j++) for (j = 0; j < num_arg_completion_types; j++) {
{
// arg_completion contains a command we can complete the arguments // arg_completion contains a command we can complete the arguments
// for (like "map ") and a list of all the maps. // for (like "map ") and a list of all the maps.
arg_completion_type_t arg_completion = arg_completion_types[j]; arg_completion_type_t arg_completion = arg_completion_types[j];
const char *command_name = arg_completion.command; const char *command_name = arg_completion.command;
if (!strncmp (key_lines[edit_line] + 1, command_name, strlen(command_name))) if (!strncmp(key_lines[edit_line] + 1, command_name, strlen(command_name))) {
{
int nummatches = 0; int nummatches = 0;
const char *matched_map = FindCompletion(partial, *arg_completion.filelist, &nummatches); const char *matched_map = FindCompletion(partial, *arg_completion.filelist, &nummatches);
if (!*matched_map) if (!*matched_map)
@@ -952,13 +879,12 @@ void Con_TabComplete (void)
q_strlcpy(partial, matched_map, MAXCMDLINE); q_strlcpy(partial, matched_map, MAXCMDLINE);
*c = '\0'; *c = '\0';
q_strlcat(key_lines[edit_line], partial, MAXCMDLINE); q_strlcat(key_lines[edit_line], partial, MAXCMDLINE);
key_linepos = c - key_lines[edit_line] + Q_strlen(matched_map); //set new cursor position key_linepos = c - key_lines[edit_line] + std::strlen(matched_map); //set new cursor position
if (key_linepos >= MAXCMDLINE) if (key_linepos >= MAXCMDLINE)
key_linepos = MAXCMDLINE - 1; key_linepos = MAXCMDLINE - 1;
// if only one match, append a space // if only one match, append a space
if (key_linepos < MAXCMDLINE - 1 && if (key_linepos < MAXCMDLINE - 1 &&
key_lines[edit_line][key_linepos] == 0 && (nummatches == 1)) key_lines[edit_line][key_linepos] == 0 && (nummatches == 1)) {
{
key_lines[edit_line][key_linepos] = ' '; key_lines[edit_line][key_linepos] = ' ';
key_linepos++; key_linepos++;
key_lines[edit_line][key_linepos] = 0; key_lines[edit_line][key_linepos] = 0;
@@ -987,12 +913,10 @@ void Con_TabComplete (void)
return; return;
// print list if length > 1 // print list if length > 1
if (tablist->next != tablist) if (tablist->next != tablist) {
{
t = tablist; t = tablist;
Con_SafePrintf("\n"); Con_SafePrintf("\n");
do do {
{
Con_SafePrintf(" %s (%s)\n", t->name, t->type); Con_SafePrintf(" %s (%s)\n", t->name, t->type);
t = t->next; t = t->next;
} while (t != tablist); } while (t != tablist);
@@ -1002,9 +926,7 @@ void Con_TabComplete (void)
// match = tablist->name; // match = tablist->name;
// First time, just show maximum matching chars -- S.A. // First time, just show maximum matching chars -- S.A.
match = bash_partial; match = bash_partial;
} } else {
else
{
BuildTabList(key_tabpartial); BuildTabList(key_tabpartial);
if (!tablist) if (!tablist)
@@ -1013,10 +935,8 @@ void Con_TabComplete (void)
//find current match -- can't save a pointer because the list will be rebuilt each time //find current match -- can't save a pointer because the list will be rebuilt each time
t = tablist; t = tablist;
match = keydown[K_SHIFT] ? t->prev->name : t->name; match = keydown[K_SHIFT] ? t->prev->name : t->name;
do do {
{ if (!std::strcmp(t->name, partial)) {
if (!Q_strcmp(t->name, partial))
{
match = keydown[K_SHIFT] ? t->prev->name : t->next->name; match = keydown[K_SHIFT] ? t->prev->name : t->next->name;
break; break;
} }
@@ -1030,14 +950,13 @@ void Con_TabComplete (void)
q_strlcat(partial, key_lines[edit_line] + key_linepos, MAXCMDLINE); //then add chars after cursor q_strlcat(partial, key_lines[edit_line] + key_linepos, MAXCMDLINE); //then add chars after cursor
*c = '\0'; //now copy all of this into edit line *c = '\0'; //now copy all of this into edit line
q_strlcat(key_lines[edit_line], partial, MAXCMDLINE); q_strlcat(key_lines[edit_line], partial, MAXCMDLINE);
key_linepos = c - key_lines[edit_line] + Q_strlen(match); //set new cursor position key_linepos = c - key_lines[edit_line] + std::strlen(match); //set new cursor position
if (key_linepos >= MAXCMDLINE) if (key_linepos >= MAXCMDLINE)
key_linepos = MAXCMDLINE - 1; key_linepos = MAXCMDLINE - 1;
// if cursor is at end of string, let's append a space to make life easier // if cursor is at end of string, let's append a space to make life easier
if (key_linepos < MAXCMDLINE - 1 && if (key_linepos < MAXCMDLINE - 1 &&
key_lines[edit_line][key_linepos] == 0 && bash_singlematch) key_lines[edit_line][key_linepos] == 0 && bash_singlematch) {
{
key_lines[edit_line][key_linepos] = ' '; key_lines[edit_line][key_linepos] = ' ';
key_linepos++; key_linepos++;
key_lines[edit_line][key_linepos] = 0; key_lines[edit_line][key_linepos] = 0;
@@ -1064,8 +983,7 @@ Con_DrawNotify
Draws the last few lines of output transparently over the game top Draws the last few lines of output transparently over the game top
================ ================
*/ */
void Con_DrawNotify (void) void Con_DrawNotify(void) {
{
int i, x, v; int i, x, v;
const char *text; const char *text;
float time; float time;
@@ -1073,8 +991,7 @@ void Con_DrawNotify (void)
GL_SetCanvas(CANVAS_CONSOLE); //johnfitz GL_SetCanvas(CANVAS_CONSOLE); //johnfitz
v = vid.conheight; //johnfitz v = vid.conheight; //johnfitz
for (i = con_current-NUM_CON_TIMES+1; i <= con_current; i++) for (i = con_current - NUM_CON_TIMES + 1; i <= con_current; i++) {
{
if (i < 0) if (i < 0)
continue; continue;
time = con_times[i % NUM_CON_TIMES]; time = con_times[i % NUM_CON_TIMES];
@@ -1095,17 +1012,13 @@ void Con_DrawNotify (void)
scr_tileclear_updates = 0; //johnfitz scr_tileclear_updates = 0; //johnfitz
} }
if (key_dest == key_message) if (key_dest == key_message) {
{
clearnotify = 0; clearnotify = 0;
if (chat_team) if (chat_team) {
{
Draw_String(8, v, "say_team:"); Draw_String(8, v, "say_team:");
x = 11; x = 11;
} } else {
else
{
Draw_String(8, v, "say:"); Draw_String(8, v, "say:");
x = 6; x = 6;
} }
@@ -1115,8 +1028,7 @@ void Con_DrawNotify (void)
if (i > con_linewidth - x - 1) if (i > con_linewidth - x - 1)
text += i - con_linewidth + x + 1; text += i - con_linewidth + x + 1;
while (*text) while (*text) {
{
Draw_Character(x << 3, v, *text); Draw_Character(x << 3, v, *text);
x++; x++;
text++; text++;
@@ -1138,8 +1050,7 @@ The input line scrolls horizontally if typing goes beyond the right edge
*/ */
extern qpic_t *pic_ovr, *pic_ins; //johnfitz -- new cursor handling extern qpic_t *pic_ovr, *pic_ins; //johnfitz -- new cursor handling
void Con_DrawInput (void) void Con_DrawInput(void) {
{
int i, ofs; int i, ofs;
if (key_dest != key_console && !con_forcedup) if (key_dest != key_console && !con_forcedup)
@@ -1156,8 +1067,7 @@ void Con_DrawInput (void)
Draw_Character((i + 1) << 3, vid.conheight - 16, key_lines[edit_line][i + ofs]); Draw_Character((i + 1) << 3, vid.conheight - 16, key_lines[edit_line][i + ofs]);
// johnfitz -- new cursor handling // johnfitz -- new cursor handling
if (!((int)((realtime-key_blinktime)*con_cursorspeed) & 1)) if (!((int) ((realtime - key_blinktime) * con_cursorspeed) & 1)) {
{
i = key_linepos - ofs; i = key_linepos - ofs;
Draw_Pic((i + 1) << 3, vid.conheight - 16, key_insert ? pic_ins : pic_ovr); Draw_Pic((i + 1) << 3, vid.conheight - 16, key_insert ? pic_ins : pic_ovr);
} }
@@ -1171,8 +1081,7 @@ Draws the console with the solid background
The typing input line at the bottom should only be drawn if typing is allowed The typing input line at the bottom should only be drawn if typing is allowed
================ ================
*/ */
void Con_DrawConsole (int lines, qboolean drawinput) void Con_DrawConsole(int lines, bool drawinput) {
{
int i, x, y, j, sb, rows; int i, x, y, j, sb, rows;
const char *text; const char *text;
char ver[32]; char ver[32];
@@ -1192,8 +1101,7 @@ void Con_DrawConsole (int lines, qboolean drawinput)
rows -= 2; //for input and version lines rows -= 2; //for input and version lines
sb = (con_backscroll) ? 2 : 0; sb = (con_backscroll) ? 2 : 0;
for (i = con_current - rows + 1; i <= con_current - sb; i++, y += 8) for (i = con_current - rows + 1; i <= con_current - sb; i++, y += 8) {
{
j = i - con_backscroll; j = i - con_backscroll;
if (j < 0) if (j < 0)
j = 0; j = 0;
@@ -1204,8 +1112,7 @@ void Con_DrawConsole (int lines, qboolean drawinput)
} }
// draw scrollback arrows // draw scrollback arrows
if (con_backscroll) if (con_backscroll) {
{
y += 8; // blank line y += 8; // blank line
for (x = 0; x < con_linewidth; x += 4) for (x = 0; x < con_linewidth; x += 4)
Draw_Character((x + 1) << 3, y, '^'); Draw_Character((x + 1) << 3, y, '^');
@@ -1229,8 +1136,7 @@ void Con_DrawConsole (int lines, qboolean drawinput)
Con_NotifyBox Con_NotifyBox
================== ==================
*/ */
void Con_NotifyBox (const char *text) void Con_NotifyBox(const char *text) {
{
double t1, t2; double t1, t2;
int lastkey, lastchar; int lastkey, lastchar;
@@ -1244,8 +1150,7 @@ void Con_NotifyBox (const char *text)
key_dest = key_console; key_dest = key_console;
Key_BeginInputGrab(); Key_BeginInputGrab();
do do {
{
t1 = Sys_DoubleTime(); t1 = Sys_DoubleTime();
SCR_UpdateScreen(); SCR_UpdateScreen();
Sys_SendKeyEvents(); Sys_SendKeyEvents();
@@ -1263,12 +1168,11 @@ void Con_NotifyBox (const char *text)
} }
void LOG_Init (quakeparms_t *parms) void LOG_Init(quakeparms_t *parms) {
{
time_t inittime; time_t inittime;
char session[24]; char session[24];
if (!COM_CheckParm("-condebug")) if (!common::check_param("-condebug").has_value())
return; return;
inittime = time(NULL); inittime = time(NULL);
@@ -1278,22 +1182,18 @@ void LOG_Init (quakeparms_t *parms)
// unlink (logfilename); // unlink (logfilename);
log_fd = open(logfilename, O_WRONLY | O_CREAT | O_TRUNC, 0666); log_fd = open(logfilename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (log_fd == -1) if (log_fd == -1) {
{
fprintf(stderr, "Error: Unable to create log file %s\n", logfilename); fprintf(stderr, "Error: Unable to create log file %s\n", logfilename);
return; return;
} }
con_debuglog = true; con_debuglog = true;
Con_DebugLog(va("LOG started on: %s \n", session)); Con_DebugLog(va("LOG started on: %s \n", session));
} }
void LOG_Close (void) void LOG_Close(void) {
{
if (log_fd == -1) if (log_fd == -1)
return; return;
close(log_fd); close(log_fd);
log_fd = -1; log_fd = -1;
} }
+3 -3
View File
@@ -28,8 +28,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// //
extern int con_totallines; extern int con_totallines;
extern int con_backscroll; extern int con_backscroll;
extern qboolean con_forcedup; // because no entities to refresh extern bool con_forcedup; // because no entities to refresh
extern qboolean con_initialized; extern bool con_initialized;
extern byte *con_chars; extern byte *con_chars;
extern char con_lastcenterstring[]; //johnfitz extern char con_lastcenterstring[]; //johnfitz
@@ -38,7 +38,7 @@ void Con_DrawCharacter (int cx, int line, int num);
void Con_CheckResize (void); void Con_CheckResize (void);
void Con_Init (void); void Con_Init (void);
void Con_DrawConsole (int lines, qboolean drawinput); void Con_DrawConsole (int lines, bool drawinput);
void Con_Printf (const char *fmt, ...) FUNC_PRINTF(1,2); void Con_Printf (const char *fmt, ...) FUNC_PRINTF(1,2);
void Con_DWarning (const char *fmt, ...) FUNC_PRINTF(1,2); //ericw void Con_DWarning (const char *fmt, ...) FUNC_PRINTF(1,2); //ericw
void Con_Warning (const char *fmt, ...) FUNC_PRINTF(1,2); //johnfitz void Con_Warning (const char *fmt, ...) FUNC_PRINTF(1,2); //johnfitz
+8 -8
View File
@@ -50,7 +50,7 @@ void Cvar_List_f() {
if (command::argc() > 1) { if (command::argc() > 1) {
partial = command::argv(1)->c_str(); partial = command::argv(1)->c_str();
len = Q_strlen(partial); len = std::strlen(partial);
} else { } else {
partial = NULL; partial = NULL;
len = 0; len = 0;
@@ -58,7 +58,7 @@ void Cvar_List_f() {
count = 0; count = 0;
for (const auto &[name, var]: CLIENT_VARIABLES) { for (const auto &[name, var]: CLIENT_VARIABLES) {
if (partial && Q_strncmp(partial, name.c_str(), len)) { if (partial && std::strncmp(partial, name.c_str(), len) != 0) {
continue; continue;
} }
Con_SafePrintf("%s%s %s \"%s\"\n", Con_SafePrintf("%s%s %s \"%s\"\n",
@@ -91,7 +91,7 @@ void Cvar_Inc_f(void) {
convar::set_value(*command::argv(1), convar::variable_value(*command::argv(1)).value_or(0.0) + 1); convar::set_value(*command::argv(1), convar::variable_value(*command::argv(1)).value_or(0.0) + 1);
break; break;
case 3: 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())); convar::set_value(*command::argv(1), convar::variable_value(*command::argv(1)).value_or(0.0) + std::atof(command::argv(2)->c_str()));
break; break;
} }
} }
@@ -136,11 +136,11 @@ void Cvar_Cycle_f() {
//zero is assumed to be a string, even though it could actually be zero. The worst case //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, //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. //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 (std::atof(command::argv(i)->c_str()) == 0) {
if (!strcmp(command::argv(i)->c_str(), convar::variable_string(*command::argv(1)).value_or("").c_str())) if (!strcmp(command::argv(i)->c_str(), convar::variable_string(*command::argv(1)).value_or("").c_str()))
break; break;
} else { } else {
if (Q_atof(command::argv(i)->c_str()) == convar::variable_value(*command::argv(1)).value_or(0.0)) if (std::atof(command::argv(i)->c_str()) == convar::variable_value(*command::argv(1)).value_or(0.0))
break; break;
} }
} }
@@ -341,14 +341,14 @@ void convar::set(const std::string &new_value) {
const std::size_t len = new_value.length(); const std::size_t len = new_value.length();
if (len != Q_strlen(this->string)) { if (len != std::strlen(this->string)) {
Z_Free((void *) this->string); Z_Free((void *) this->string);
this->string = (char *) Z_Malloc(len + 1); this->string = (char *) Z_Malloc(len + 1);
} }
memcpy((char *) this->string, new_value.c_str(), len + 1); memcpy((char *) this->string, new_value.c_str(), len + 1);
} }
this->value = Q_atof(this->string); this->value = std::atof(this->string);
//johnfitz -- save initial value for "reset" command //johnfitz -- save initial value for "reset" command
if (!this->default_string) if (!this->default_string)
@@ -507,7 +507,7 @@ Cvar_Command
Handles variable inspection and changing from the console Handles variable inspection and changing from the console
============ ============
*/ */
qboolean Cvar_Command() { bool Cvar_Command() {
// check variables // check variables
auto var = convar::find_var(command::argv(0).value_or("")); auto var = convar::find_var(command::argv(0).value_or(""));
if (!var.has_value()) if (!var.has_value())
+1 -1
View File
@@ -149,6 +149,6 @@ struct convar {
static convar_view get_variables(); static convar_view get_variables();
}; };
qboolean Cvar_Command(void); bool Cvar_Command(void);
void Cvar_WriteVariables(FILE *f); void Cvar_WriteVariables(FILE *f);
+2 -1
View File
@@ -1,6 +1,7 @@
// keep in sync with Misc/qs_pak/default.cfg // keep in sync with Misc/qs_pak/default.cfg
#pragma once
static const char default_cfg[] = constexpr char default_cfg[] =
"unbindall\n" "unbindall\n"
"bind ALT +strafe\n" "bind ALT +strafe\n"
+4 -4
View File
@@ -136,7 +136,7 @@ byte menuplyr_pixels[4096];
int scrap_allocated[MAX_SCRAPS][BLOCK_WIDTH]; int scrap_allocated[MAX_SCRAPS][BLOCK_WIDTH];
byte scrap_texels[MAX_SCRAPS][BLOCK_WIDTH*BLOCK_HEIGHT]; //johnfitz -- removed *4 after BLOCK_HEIGHT byte scrap_texels[MAX_SCRAPS][BLOCK_WIDTH*BLOCK_HEIGHT]; //johnfitz -- removed *4 after BLOCK_HEIGHT
qboolean scrap_dirty; bool scrap_dirty;
gltexture_t *scrap_textures[MAX_SCRAPS]; //johnfitz gltexture_t *scrap_textures[MAX_SCRAPS]; //johnfitz
@@ -704,13 +704,13 @@ void GL_SetCanvas (canvastype newcanvas)
break; break;
case CANVAS_MENU: case CANVAS_MENU:
s = std::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); s = std::clamp(scr_menuscale.value, 1.0f, s);
// ericw -- doubled width to 640 to accommodate long keybindings // ericw -- doubled width to 640 to accommodate long keybindings
glOrtho (0, 640, 200, 0, -99999, 99999); glOrtho (0, 640, 200, 0, -99999, 99999);
glViewport (glx + (glwidth - 320*s) / 2, gly + (glheight - 200*s) / 2, 640*s, 200*s); glViewport (glx + (glwidth - 320*s) / 2, gly + (glheight - 200*s) / 2, 640*s, 200*s);
break; break;
case CANVAS_SBAR: case CANVAS_SBAR:
s = CLAMP (1.0f, scr_sbarscale.value, (float)glwidth / 320.0f); s = std::clamp(scr_sbarscale.value, 1.0f, (float)glwidth / 320.0f);
if (cl.gametype == GAME_DEATHMATCH) if (cl.gametype == GAME_DEATHMATCH)
{ {
glOrtho (0, glwidth / s, 48, 0, -99999, 99999); glOrtho (0, glwidth / s, 48, 0, -99999, 99999);
@@ -727,7 +727,7 @@ void GL_SetCanvas (canvastype newcanvas)
glViewport (glx, gly+glheight-gl_warpimagesize, gl_warpimagesize, gl_warpimagesize); glViewport (glx, gly+glheight-gl_warpimagesize, gl_warpimagesize, gl_warpimagesize);
break; break;
case CANVAS_CROSSHAIR: //0,0 is center of viewport case CANVAS_CROSSHAIR: //0,0 is center of viewport
s = CLAMP (1.0f, scr_crosshairscale.value, 10.0f); s = std::clamp(scr_crosshairscale.value, 1.0f, 10.0f);
glOrtho (scr_vrect.width/-2/s, scr_vrect.width/2/s, scr_vrect.height/2/s, scr_vrect.height/-2/s, -99999, 99999); glOrtho (scr_vrect.width/-2/s, scr_vrect.width/2/s, scr_vrect.height/2/s, scr_vrect.height/-2/s, -99999, 99999);
glViewport (scr_vrect.x, glheight - scr_vrect.y - scr_vrect.height, scr_vrect.width & ~1, scr_vrect.height & ~1); glViewport (scr_vrect.x, glheight - scr_vrect.y - scr_vrect.height, scr_vrect.width & ~1, scr_vrect.height & ~1);
break; break;
+16 -16
View File
@@ -126,15 +126,15 @@ void Fog_FogCommand_f(void) {
Con_Printf(" \"blue\" is \"%f\"\n", fog_blue); Con_Printf(" \"blue\" is \"%f\"\n", fog_blue);
return; return;
case 2: case 2:
d = Q_atof(command::argv(1)->c_str()); d = std::atof(command::argv(1)->c_str());
t = 0.0f; t = 0.0f;
r = fog_red; r = fog_red;
g = fog_green; g = fog_green;
b = fog_blue; b = fog_blue;
break; break;
case 3: //TEST case 3: //TEST
d = Q_atof(command::argv(1)->c_str()); d = std::atof(command::argv(1)->c_str());
t = Q_atof(command::argv(2)->c_str()); t = std::atof(command::argv(2)->c_str());
r = fog_red; r = fog_red;
g = fog_green; g = fog_green;
b = fog_blue; b = fog_blue;
@@ -142,23 +142,23 @@ void Fog_FogCommand_f(void) {
case 4: case 4:
d = fog_density; d = fog_density;
t = 0.0f; t = 0.0f;
r = Q_atof(command::argv(1)->c_str()); r = std::atof(command::argv(1)->c_str());
g = Q_atof(command::argv(2)->c_str()); g = std::atof(command::argv(2)->c_str());
b = Q_atof(command::argv(3)->c_str()); b = std::atof(command::argv(3)->c_str());
break; break;
case 5: case 5:
d = Q_atof(command::argv(1)->c_str()); d = std::atof(command::argv(1)->c_str());
r = Q_atof(command::argv(2)->c_str()); r = std::atof(command::argv(2)->c_str());
g = Q_atof(command::argv(3)->c_str()); g = std::atof(command::argv(3)->c_str());
b = Q_atof(command::argv(4)->c_str()); b = std::atof(command::argv(4)->c_str());
t = 0.0f; t = 0.0f;
break; break;
case 6: //TEST case 6: //TEST
d = Q_atof(command::argv(1)->c_str()); d = std::atof(command::argv(1)->c_str());
r = Q_atof(command::argv(2)->c_str()); r = std::atof(command::argv(2)->c_str());
g = Q_atof(command::argv(3)->c_str()); g = std::atof(command::argv(3)->c_str());
b = Q_atof(command::argv(4)->c_str()); b = std::atof(command::argv(4)->c_str());
t = Q_atof(command::argv(5)->c_str()); t = std::atof(command::argv(5)->c_str());
break; break;
} }
@@ -262,7 +262,7 @@ float *Fog_GetColor(void) {
} }
for (i = 0; i < 3; i++) { for (i = 0; i < 3; i++) {
c[i] = CLAMP(0.f, c[i], 1.f); c[i] = std::clamp(c[i], 0.f, 1.f);
} }
//find closest 24-bit RGB value, so solid-colored sky can match the fog perfectly //find closest 24-bit RGB value, so solid-colored sky can match the fog perfectly
+8 -8
View File
@@ -32,7 +32,7 @@ static char loadname[32]; // for hunk tags
static void Mod_LoadSpriteModel (qmodel_t *mod, void *buffer); static void Mod_LoadSpriteModel (qmodel_t *mod, void *buffer);
static void Mod_LoadBrushModel (qmodel_t *mod, void *buffer); static void Mod_LoadBrushModel (qmodel_t *mod, void *buffer);
static void Mod_LoadAliasModel (qmodel_t *mod, void *buffer); static void Mod_LoadAliasModel (qmodel_t *mod, void *buffer);
static qmodel_t *Mod_LoadModel (qmodel_t *mod, qboolean crash); static qmodel_t *Mod_LoadModel (qmodel_t *mod, bool crash);
static void Mod_Print (void); static void Mod_Print (void);
@@ -312,7 +312,7 @@ Mod_LoadModel
Loads a model into the cache Loads a model into the cache
================== ==================
*/ */
static qmodel_t *Mod_LoadModel (qmodel_t *mod, qboolean crash) static qmodel_t *Mod_LoadModel (qmodel_t *mod, bool crash)
{ {
byte *buf; byte *buf;
byte stackbuf[1024]; // avoid dirtying the cache heap byte stackbuf[1024]; // avoid dirtying the cache heap
@@ -388,7 +388,7 @@ Mod_ForName
Loads in a model for the given name Loads in a model for the given name
================== ==================
*/ */
qmodel_t *Mod_ForName (const char *name, qboolean crash) qmodel_t *Mod_ForName (const char *name, bool crash)
{ {
qmodel_t *mod; qmodel_t *mod;
@@ -413,7 +413,7 @@ static byte *mod_base;
Mod_CheckFullbrights -- johnfitz Mod_CheckFullbrights -- johnfitz
================= =================
*/ */
static qboolean Mod_CheckFullbrights (byte *pixels, int count) static bool Mod_CheckFullbrights (byte *pixels, int count)
{ {
int i; int i;
for (i = 0; i < count; i++) for (i = 0; i < count; i++)
@@ -432,7 +432,7 @@ Quake64 bsp
Check if we have any missing textures in the array Check if we have any missing textures in the array
================= =================
*/ */
static qboolean Mod_CheckAnimTextureArrayQ64(texture_t *anims[], int numTex) static bool Mod_CheckAnimTextureArrayQ64(texture_t *anims[], int numTex)
{ {
int i; int i;
@@ -1220,7 +1220,7 @@ static void Mod_CalcSurfaceBounds (msurface_t *s)
Mod_LoadFaces Mod_LoadFaces
================= =================
*/ */
static void Mod_LoadFaces (lump_t *l, qboolean bsp2) static void Mod_LoadFaces (lump_t *l, bool bsp2)
{ {
dsface_t *ins; dsface_t *ins;
dlface_t *inl; dlface_t *inl;
@@ -1705,7 +1705,7 @@ static void Mod_LoadLeafs (lump_t *l, int bsp2)
Mod_LoadClipnodes Mod_LoadClipnodes
================= =================
*/ */
static void Mod_LoadClipnodes (lump_t *l, qboolean bsp2) static void Mod_LoadClipnodes (lump_t *l, bool bsp2)
{ {
dsclipnode_t *ins; dsclipnode_t *ins;
dlclipnode_t *inl; dlclipnode_t *inl;
@@ -2672,7 +2672,7 @@ static void Mod_CalcAliasBounds (aliashdr_t *a)
loadmodel->ymaxs[2] = loadmodel->maxs[2]; loadmodel->ymaxs[2] = loadmodel->maxs[2];
} }
static qboolean static bool
nameInList(const char *list, const char *name) nameInList(const char *list, const char *name)
{ {
const char *s; const char *s;
+7 -7
View File
@@ -93,7 +93,7 @@ typedef struct texture_s
struct gltexture_s *gltexture; //johnfitz -- pointer to gltexture struct gltexture_s *gltexture; //johnfitz -- pointer to gltexture
struct gltexture_s *fullbright; //johnfitz -- fullbright mask texture struct gltexture_s *fullbright; //johnfitz -- fullbright mask texture
struct gltexture_s *warpimage; //johnfitz -- for water animation struct gltexture_s *warpimage; //johnfitz -- for water animation
qboolean update_warp; //johnfitz -- update warp this frame bool update_warp; //johnfitz -- update warp this frame
struct msurface_s *texturechains[2]; // for texture chains struct msurface_s *texturechains[2]; // for texture chains
int anim_total; // total tenths in sequence ( 0 = no) int anim_total; // total tenths in sequence ( 0 = no)
int anim_min, anim_max; // time for this frame min <=time< max int anim_min, anim_max; // time for this frame min <=time< max
@@ -172,7 +172,7 @@ typedef struct msurface_s
int lightmaptexturenum; int lightmaptexturenum;
byte styles[MAXLIGHTMAPS]; byte styles[MAXLIGHTMAPS];
int cached_light[MAXLIGHTMAPS]; // values currently used in lightmap int cached_light[MAXLIGHTMAPS]; // values currently used in lightmap
qboolean cached_dlight; // true if dynamic light in cache bool cached_dlight; // true if dynamic light in cache
byte *samples; // [numstyles*surfsize] byte *samples; // [numstyles*surfsize]
} msurface_t; } msurface_t;
@@ -412,7 +412,7 @@ typedef struct qmodel_s
char name[MAX_QPATH]; char name[MAX_QPATH];
unsigned int path_id; // path id of the game directory unsigned int path_id; // path id of the game directory
// that this model came from // that this model came from
qboolean needload; // bmodels and sprites don't cache normally bool needload; // bmodels and sprites don't cache normally
modtype_t type; modtype_t type;
int numframes; int numframes;
@@ -431,7 +431,7 @@ typedef struct qmodel_s
// //
// solid volume for clipping // solid volume for clipping
// //
qboolean clipbox; bool clipbox;
vec3_t clipmins, clipmaxs; vec3_t clipmins, clipmaxs;
// //
@@ -481,10 +481,10 @@ typedef struct qmodel_s
byte *lightdata; byte *lightdata;
char *entities; char *entities;
qboolean viswarn; // for Mod_DecompressVis() bool viswarn; // for Mod_DecompressVis()
int bspversion; int bspversion;
qboolean haslitwater; bool haslitwater;
// //
// alias model // alias model
// //
@@ -507,7 +507,7 @@ typedef struct qmodel_s
void Mod_Init (void); void Mod_Init (void);
void Mod_ClearAll (void); void Mod_ClearAll (void);
void Mod_ResetAll (void); // for gamedir changes (Host_Game_f) void Mod_ResetAll (void); // for gamedir changes (Host_Game_f)
qmodel_t *Mod_ForName (const char *name, qboolean crash); qmodel_t *Mod_ForName (const char *name, bool crash);
void *Mod_Extradata (qmodel_t *mod); // handles caching void *Mod_Extradata (qmodel_t *mod); // handles caching
void Mod_TouchModel (const char *name); void Mod_TouchModel (const char *name);
+8 -8
View File
@@ -114,7 +114,7 @@ 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 bool r_drawflat_cheatsafe, r_fullbright_cheatsafe, r_lightmap_cheatsafe, r_drawworld_cheatsafe; //johnfitz
convar r_scale{"r_scale", "1", {.archive = true}}; convar r_scale{"r_scale", "1", {.archive = true}};
@@ -266,7 +266,7 @@ R_CullBox -- johnfitz -- replaced with new function from lordhavoc
Returns true if the box is completely outside the frustum Returns true if the box is completely outside the frustum
================= =================
*/ */
qboolean R_CullBox(vec3_t emins, vec3_t emaxs) { bool R_CullBox(vec3_t emins, vec3_t emaxs) {
int i; int i;
mplane_t *p; mplane_t *p;
byte signbits; byte signbits;
@@ -289,7 +289,7 @@ qboolean R_CullBox(vec3_t emins, vec3_t emaxs) {
R_CullModelForEntity -- johnfitz -- uses correct bounds based on rotation R_CullModelForEntity -- johnfitz -- uses correct bounds based on rotation
=============== ===============
*/ */
qboolean R_CullModelForEntity(entity_t *e) { bool R_CullModelForEntity(entity_t *e) {
vec3_t mins, maxs; vec3_t mins, maxs;
vec_t scalefactor, *minbounds, *maxbounds; vec_t scalefactor, *minbounds, *maxbounds;
@@ -444,7 +444,7 @@ void R_SetupGL(void) {
//johnfitz -- rewrote this section //johnfitz -- rewrote this section
glMatrixMode(GL_PROJECTION); glMatrixMode(GL_PROJECTION);
glLoadIdentity(); glLoadIdentity();
scale = CLAMP(1, (int)r_scale.value, 4); // ericw -- see R_ScaleView scale = std::clamp((int)r_scale.value, 1, 4); // ericw -- see R_ScaleView
glViewport(glx + r_refdef.vrect.x, glViewport(glx + r_refdef.vrect.x,
gly + glheight - r_refdef.vrect.y - r_refdef.vrect.height, gly + glheight - r_refdef.vrect.y - r_refdef.vrect.height,
r_refdef.vrect.width / scale, r_refdef.vrect.width / scale,
@@ -573,7 +573,7 @@ void R_SetupView(void) {
R_DrawEntitiesOnList R_DrawEntitiesOnList
============= =============
*/ */
void R_DrawEntitiesOnList(qboolean alphapass) //johnfitz -- added parameter void R_DrawEntitiesOnList(bool alphapass) //johnfitz -- added parameter
{ {
int i; int i;
@@ -905,7 +905,7 @@ void R_ScaleView(void) {
int srcx, srcy, srcw, srch; int srcx, srcy, srcw, srch;
// copied from R_SetupGL() // copied from R_SetupGL()
scale = CLAMP(1, (int)r_scale.value, 4); scale = std::clamp((int)r_scale.value, 1, 4);
srcx = glx + r_refdef.vrect.x; srcx = glx + r_refdef.vrect.x;
srcy = gly + glheight - r_refdef.vrect.y - r_refdef.vrect.height; srcy = gly + glheight - r_refdef.vrect.y - r_refdef.vrect.height;
srcw = r_refdef.vrect.width / scale; srcw = r_refdef.vrect.width / scale;
@@ -1008,8 +1008,8 @@ void R_RenderView(void) {
//johnfitz -- stereo rendering -- full of hacky goodness //johnfitz -- stereo rendering -- full of hacky goodness
if (r_stereo.value) { if (r_stereo.value) {
float eyesep = CLAMP(-8.0f, r_stereo.value, 8.0f); float eyesep = std::clamp(r_stereo.value, -8.0f, 8.0f);
float fdepth = CLAMP(32.0f, r_stereodepth.value, 1024.0f); float fdepth = std::clamp(r_stereodepth.value, 32.0f, 1024.0f);
AngleVectors(r_refdef.viewangles, vpn, vright, vup); AngleVectors(r_refdef.viewangles, vpn, vright, vup);
+3 -3
View File
@@ -438,7 +438,7 @@ void D_FlushCaches(void) {
static GLuint gl_programs[16]; static GLuint gl_programs[16];
static int gl_num_programs; static int gl_num_programs;
static qboolean GL_CheckShader(GLuint shader) { static bool GL_CheckShader(GLuint shader) {
GLint status; GLint status;
GL_GetShaderivFunc(shader, GL_COMPILE_STATUS, &status); GL_GetShaderivFunc(shader, GL_COMPILE_STATUS, &status);
@@ -455,7 +455,7 @@ static qboolean GL_CheckShader(GLuint shader) {
return true; return true;
} }
static qboolean GL_CheckProgram(GLuint program) { static bool GL_CheckProgram(GLuint program) {
GLint status; GLint status;
GL_GetProgramivFunc(program, GL_LINK_STATUS, &status); GL_GetProgramivFunc(program, GL_LINK_STATUS, &status);
@@ -539,7 +539,7 @@ GLuint GL_CreateProgram(const GLchar *vertSource, const GLchar *fragSource, int
GL_DeleteProgramFunc(program); GL_DeleteProgramFunc(program);
return 0; return 0;
} else { } else {
if (gl_num_programs == Q_COUNTOF(gl_programs)) if (gl_num_programs == std::size(gl_programs))
Host_Error("gl_programs overflow"); Host_Error("gl_programs overflow");
gl_programs[gl_num_programs] = program; gl_programs[gl_num_programs] = program;
+76 -134
View File
@@ -23,6 +23,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// screen.c -- master for refresh, status bar, console, chat, notify, etc // screen.c -- master for refresh, status bar, console, chat, notify, etc
#include <cstring>
#include "quakedef.hpp" #include "quakedef.hpp"
/* /*
@@ -103,7 +105,7 @@ convar cl_gun_fovscale = {"cl_gun_fovscale","1",{.archive = true}}; // Qrack
extern convar crosshair; extern convar crosshair;
qboolean scr_initialized; // ready to draw bool scr_initialized; // ready to draw
qpic_t *scr_net; qpic_t *scr_net;
qpic_t *scr_turtle; qpic_t *scr_turtle;
@@ -113,8 +115,8 @@ int clearnotify;
vrect_t scr_vrect; vrect_t scr_vrect;
qboolean scr_disabled_for_loading; bool scr_disabled_for_loading;
qboolean scr_drawloading; bool scr_drawloading;
float scr_disabled_time; float scr_disabled_time;
int scr_tileclear_updates = 0; //johnfitz int scr_tileclear_updates = 0; //johnfitz
@@ -153,8 +155,7 @@ void SCR_CenterPrint (const char *str) //update centerprint data
// count the number of lines for centering // count the number of lines for centering
scr_center_lines = 1; scr_center_lines = 1;
str = scr_centerstring; str = scr_centerstring;
while (*str) while (*str) {
{
if (*str == '\n') if (*str == '\n')
scr_center_lines++; scr_center_lines++;
str++; str++;
@@ -187,15 +188,13 @@ void SCR_DrawCenterString (void) //actually do the drawing
if (crosshair.value) if (crosshair.value)
y -= 8; y -= 8;
do do {
{
// scan the width of the line // scan the width of the line
for (l = 0; l < 40; l++) for (l = 0; l < 40; l++)
if (start[l] == '\n' || !start[l]) if (start[l] == '\n' || !start[l])
break; break;
x = (320 - l * 8) / 2; //johnfitz -- 320x200 coordinate system x = (320 - l * 8) / 2; //johnfitz -- 320x200 coordinate system
for (j=0 ; j<l ; j++, x+=8) for (j = 0; j < l; j++, x += 8) {
{
Draw_Character(x, y, start[j]); //johnfitz -- stretch overlays Draw_Character(x, y, start[j]); //johnfitz -- stretch overlays
if (!remaining--) if (!remaining--)
return; return;
@@ -212,8 +211,7 @@ void SCR_DrawCenterString (void) //actually do the drawing
} while (1); } while (1);
} }
void SCR_CheckDrawCenterString (void) void SCR_CheckDrawCenterString(void) {
{
if (scr_center_lines > scr_erase_lines) if (scr_center_lines > scr_erase_lines)
scr_erase_lines = scr_center_lines; scr_erase_lines = scr_center_lines;
@@ -238,8 +236,7 @@ Adapt a 4:3 horizontal FOV to the current screen size using the "Hor+" scaling:
2.0 * atan(width / height * 3.0 / 4.0 * tan(fov_x / 2.0)) 2.0 * atan(width / height * 3.0 / 4.0 * tan(fov_x / 2.0))
==================== ====================
*/ */
float AdaptFovx (float fov_x, float width, float height) float AdaptFovx(float fov_x, float width, float height) {
{
float a, x; float a, x;
if (fov_x < 1 || fov_x > 179) if (fov_x < 1 || fov_x > 179)
@@ -259,8 +256,7 @@ float AdaptFovx (float fov_x, float width, float height)
CalcFovy CalcFovy
==================== ====================
*/ */
float CalcFovy (float fov_x, float width, float height) float CalcFovy(float fov_x, float width, float height) {
{
float a, x; float a, x;
if (fov_x < 1 || fov_x > 179) if (fov_x < 1 || fov_x > 179)
@@ -280,8 +276,7 @@ Must be called whenever vid changes
Internal use only Internal use only
================= =================
*/ */
static void SCR_CalcRefdef (void) static void SCR_CalcRefdef(void) {
{
float size, scale; //johnfitz -- scale float size, scale; //johnfitz -- scale
// force the status bar to redraw // force the status bar to redraw
@@ -305,7 +300,7 @@ static void SCR_CalcRefdef (void)
//johnfitz -- rewrote this section //johnfitz -- rewrote this section
size = scr_viewsize.value; size = scr_viewsize.value;
scale = CLAMP (1.0f, scr_sbarscale.value, (float)glwidth / 320.0f); scale = std::clamp(scr_sbarscale.value, 1.0f, (float) glwidth / 320.0f);
if (size >= 120 || cl.intermission || scr_sbaralpha.value < 1) //johnfitz -- scr_sbaralpha.value if (size >= 120 || cl.intermission || scr_sbaralpha.value < 1) //johnfitz -- scr_sbaralpha.value
sb_lines = 0; sb_lines = 0;
@@ -338,8 +333,7 @@ SCR_SizeUp_f
Keybinding command Keybinding command
================= =================
*/ */
void SCR_SizeUp_f (void) void SCR_SizeUp_f(void) {
{
scr_viewsize.set_value(scr_viewsize.value + 10); scr_viewsize.set_value(scr_viewsize.value + 10);
} }
@@ -351,13 +345,11 @@ SCR_SizeDown_f
Keybinding command Keybinding command
================= =================
*/ */
void SCR_SizeDown_f (void) void SCR_SizeDown_f(void) {
{
scr_viewsize.set_value(scr_viewsize.value - 10); scr_viewsize.set_value(scr_viewsize.value - 10);
} }
static void SCR_Callback_refdef (convar *var) static void SCR_Callback_refdef(convar *var) {
{
vid.recalc_refdef = 1; vid.recalc_refdef = 1;
} }
@@ -366,11 +358,14 @@ static void SCR_Callback_refdef (convar *var)
SCR_Conwidth_f -- johnfitz -- called when scr_conwidth or scr_conscale changes SCR_Conwidth_f -- johnfitz -- called when scr_conwidth or scr_conscale changes
================== ==================
*/ */
void SCR_Conwidth_f (convar *var) void SCR_Conwidth_f(convar *var) {
{
vid.recalc_refdef = 1; 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; vid.conwidth = (scr_conwidth.value > 0)
vid.conwidth = CLAMP (320, vid.conwidth, vid.width); ? (int) scr_conwidth.value
: (scr_conscale.value > 0)
? (int) (vid.width / scr_conscale.value)
: vid.width;
vid.conwidth = std::clamp(vid.conwidth, 320, vid.width);
vid.conwidth &= 0xFFFFFFF8; vid.conwidth &= 0xFFFFFFF8;
vid.conheight = vid.conwidth * vid.height / vid.width; vid.conheight = vid.conwidth * vid.height / vid.width;
} }
@@ -382,8 +377,7 @@ void SCR_Conwidth_f (convar *var)
SCR_LoadPics -- johnfitz SCR_LoadPics -- johnfitz
================== ==================
*/ */
void SCR_LoadPics (void) void SCR_LoadPics(void) {
{
scr_net = Draw_PicFromWad("net"); scr_net = Draw_PicFromWad("net");
scr_turtle = Draw_PicFromWad("turtle"); scr_turtle = Draw_PicFromWad("turtle");
} }
@@ -393,8 +387,7 @@ void SCR_LoadPics (void)
SCR_Init SCR_Init
================== ==================
*/ */
void SCR_Init (void) void SCR_Init(void) {
{
//johnfitz -- new cvars //johnfitz -- new cvars
scr_menuscale.inscribe(); scr_menuscale.inscribe();
scr_sbarscale.inscribe(); scr_sbarscale.inscribe();
@@ -439,8 +432,7 @@ void SCR_Init (void)
SCR_DrawFPS -- johnfitz SCR_DrawFPS -- johnfitz
============== ==============
*/ */
void SCR_DrawFPS (void) void SCR_DrawFPS(void) {
{
static double oldtime = 0; static double oldtime = 0;
static double lastfps = 0; static double lastfps = 0;
static int oldframecount = 0; static int oldframecount = 0;
@@ -450,22 +442,19 @@ void SCR_DrawFPS (void)
elapsed_time = realtime - oldtime; elapsed_time = realtime - oldtime;
frames = r_framecount - oldframecount; frames = r_framecount - oldframecount;
if (elapsed_time < 0 || frames < 0) if (elapsed_time < 0 || frames < 0) {
{
oldtime = realtime; oldtime = realtime;
oldframecount = r_framecount; oldframecount = r_framecount;
return; return;
} }
// update value every 3/4 second // update value every 3/4 second
if (elapsed_time > 0.75) if (elapsed_time > 0.75) {
{
lastfps = frames / elapsed_time; lastfps = frames / elapsed_time;
oldtime = realtime; oldtime = realtime;
oldframecount = r_framecount; oldframecount = r_framecount;
} }
if (scr_showfps.value) if (scr_showfps.value) {
{
char st[16]; char st[16];
int x, y; int x, y;
sprintf(st, "%4.0f fps", lastfps); sprintf(st, "%4.0f fps", lastfps);
@@ -483,20 +472,17 @@ void SCR_DrawFPS (void)
SCR_DrawClock -- johnfitz SCR_DrawClock -- johnfitz
============== ==============
*/ */
void SCR_DrawClock (void) void SCR_DrawClock(void) {
{
char str[12]; char str[12];
if (scr_clock.value == 1) if (scr_clock.value == 1) {
{
int minutes, seconds; int minutes, seconds;
minutes = cl.time / 60; minutes = cl.time / 60;
seconds = ((int) cl.time) % 60; seconds = ((int) cl.time) % 60;
sprintf(str, "%i:%i%i", minutes, seconds / 10, seconds % 10); sprintf(str, "%i:%i%i", minutes, seconds / 10, seconds % 10);
} } else
else
return; return;
//draw it //draw it
@@ -511,8 +497,7 @@ void SCR_DrawClock (void)
SCR_DrawDevStats SCR_DrawDevStats
============== ==============
*/ */
void SCR_DrawDevStats (void) void SCR_DrawDevStats(void) {
{
char str[40]; char str[40];
int y = 25 - 9; //9=number of lines to print int y = 25 - 9; //9=number of lines to print
int x = 0; //margin int x = 0; //margin
@@ -557,15 +542,13 @@ void SCR_DrawDevStats (void)
SCR_DrawTurtle SCR_DrawTurtle
============== ==============
*/ */
void SCR_DrawTurtle (void) void SCR_DrawTurtle(void) {
{
static int count; static int count;
if (!scr_showturtle.value) if (!scr_showturtle.value)
return; return;
if (host_frametime < 0.1) if (host_frametime < 0.1) {
{
count = 0; count = 0;
return; return;
} }
@@ -584,8 +567,7 @@ void SCR_DrawTurtle (void)
SCR_DrawNet SCR_DrawNet
============== ==============
*/ */
void SCR_DrawNet (void) void SCR_DrawNet(void) {
{
if (realtime - cl.last_received_message < 0.3) if (realtime - cl.last_received_message < 0.3)
return; return;
if (cls.demoplayback) if (cls.demoplayback)
@@ -601,8 +583,7 @@ void SCR_DrawNet (void)
DrawPause DrawPause
============== ==============
*/ */
void SCR_DrawPause (void) void SCR_DrawPause(void) {
{
qpic_t *pic; qpic_t *pic;
if (!cl.paused) if (!cl.paused)
@@ -624,8 +605,7 @@ void SCR_DrawPause (void)
SCR_DrawLoading SCR_DrawLoading
============== ==============
*/ */
void SCR_DrawLoading (void) void SCR_DrawLoading(void) {
{
qpic_t *pic; qpic_t *pic;
if (!scr_drawloading) if (!scr_drawloading)
@@ -644,8 +624,7 @@ void SCR_DrawLoading (void)
SCR_DrawCrosshair -- johnfitz SCR_DrawCrosshair -- johnfitz
============== ==============
*/ */
void SCR_DrawCrosshair (void) void SCR_DrawCrosshair(void) {
{
if (!crosshair.value) if (!crosshair.value)
return; return;
@@ -654,7 +633,6 @@ void SCR_DrawCrosshair (void)
} }
//============================================================================= //=============================================================================
@@ -663,8 +641,7 @@ void SCR_DrawCrosshair (void)
SCR_SetUpToDrawConsole SCR_SetUpToDrawConsole
================== ==================
*/ */
void SCR_SetUpToDrawConsole (void) void SCR_SetUpToDrawConsole(void) {
{
//johnfitz -- let's hack away the problem of slow console when host_timescale is <0 //johnfitz -- let's hack away the problem of slow console when host_timescale is <0
extern convar host_timescale; extern convar host_timescale;
float timescale, conspeed; float timescale, conspeed;
@@ -678,12 +655,10 @@ void SCR_SetUpToDrawConsole (void)
// decide on the height of the console // decide on the height of the console
con_forcedup = !cl.worldmodel || cls.signon != SIGNONS; con_forcedup = !cl.worldmodel || cls.signon != SIGNONS;
if (con_forcedup) if (con_forcedup) {
{
scr_conlines = glheight; //full screen //johnfitz -- glheight instead of vid.height scr_conlines = glheight; //full screen //johnfitz -- glheight instead of vid.height
scr_con_current = scr_conlines; scr_con_current = scr_conlines;
} } else if (key_dest == key_console)
else if (key_dest == key_console)
scr_conlines = glheight / 2; //half screen //johnfitz -- glheight instead of vid.height scr_conlines = glheight / 2; //half screen //johnfitz -- glheight instead of vid.height
else else
scr_conlines = 0; //none visible scr_conlines = 0; //none visible
@@ -691,15 +666,12 @@ void SCR_SetUpToDrawConsole (void)
timescale = (host_timescale.value > 0) ? host_timescale.value : 1; //johnfitz -- timescale timescale = (host_timescale.value > 0) ? host_timescale.value : 1; //johnfitz -- timescale
conspeed = (scr_conspeed.value > 0) ? scr_conspeed.value : 1e6f; conspeed = (scr_conspeed.value > 0) ? scr_conspeed.value : 1e6f;
if (scr_conlines < scr_con_current) if (scr_conlines < scr_con_current) {
{
// ericw -- (glheight/600.0) factor makes conspeed resolution independent, using 800x600 as a baseline // ericw -- (glheight/600.0) factor makes conspeed resolution independent, using 800x600 as a baseline
scr_con_current -= conspeed * (glheight / 600.0) * host_frametime / timescale; //johnfitz -- timescale scr_con_current -= conspeed * (glheight / 600.0) * host_frametime / timescale; //johnfitz -- timescale
if (scr_conlines > scr_con_current) if (scr_conlines > scr_con_current)
scr_con_current = scr_conlines; scr_con_current = scr_conlines;
} } else if (scr_conlines > scr_con_current) {
else if (scr_conlines > scr_con_current)
{
// ericw -- (glheight/600.0) // ericw -- (glheight/600.0)
scr_con_current += conspeed * (glheight / 600.0) * host_frametime / timescale; //johnfitz -- timescale scr_con_current += conspeed * (glheight / 600.0) * host_frametime / timescale; //johnfitz -- timescale
if (scr_conlines < scr_con_current) if (scr_conlines < scr_con_current)
@@ -718,15 +690,11 @@ void SCR_SetUpToDrawConsole (void)
SCR_DrawConsole SCR_DrawConsole
================== ==================
*/ */
void SCR_DrawConsole (void) void SCR_DrawConsole(void) {
{ if (scr_con_current) {
if (scr_con_current)
{
Con_DrawConsole(scr_con_current, true); Con_DrawConsole(scr_con_current, true);
clearconsole = 0; clearconsole = 0;
} } else {
else
{
if (key_dest == key_game || key_dest == key_message) if (key_dest == key_game || key_dest == key_message)
Con_DrawNotify(); // only draw notify in game Con_DrawNotify(); // only draw notify in game
} }
@@ -741,8 +709,7 @@ SCREEN SHOTS
============================================================================== ==============================================================================
*/ */
static void SCR_ScreenShot_Usage (void) static void SCR_ScreenShot_Usage(void) {
{
Con_Printf("usage: screenshot <format> <quality>\n"); Con_Printf("usage: screenshot <format> <quality>\n");
Con_Printf(" format must be \"png\" or \"tga\" or \"jpg\"\n"); Con_Printf(" format must be \"png\" or \"tga\" or \"jpg\"\n");
Con_Printf(" quality must be 1-100\n"); Con_Printf(" quality must be 1-100\n");
@@ -754,27 +721,24 @@ static void SCR_ScreenShot_Usage (void)
SCR_ScreenShot_f -- johnfitz -- rewritten to use Image_WriteTGA SCR_ScreenShot_f -- johnfitz -- rewritten to use Image_WriteTGA
================== ==================
*/ */
void SCR_ScreenShot_f (void) void SCR_ScreenShot_f(void) {
{
byte *buffer; byte *buffer;
char ext[4]; char ext[4];
char imagename[16]; //johnfitz -- was [80] char imagename[16]; //johnfitz -- was [80]
char checkname[MAX_OSPATH]; char checkname[MAX_OSPATH];
int i, quality; int i, quality;
qboolean ok; bool ok;
Q_strncpy (ext, "png", sizeof(ext)); std::strncpy(ext, "png", sizeof(ext));
if (command::argc () >= 2) if (command::argc() >= 2) {
{
const char *requested_ext = command::argv(1)->c_str(); const char *requested_ext = command::argv(1)->c_str();
if (!q_strcasecmp("png", requested_ext) if (!q_strcasecmp("png", requested_ext)
|| !q_strcasecmp("tga", requested_ext) || !q_strcasecmp("tga", requested_ext)
|| !q_strcasecmp("jpg", requested_ext)) || !q_strcasecmp("jpg", requested_ext))
Q_strncpy (ext, requested_ext, sizeof(ext)); std::strncpy(ext, requested_ext, sizeof(ext));
else else {
{
SCR_ScreenShot_Usage(); SCR_ScreenShot_Usage();
return; return;
} }
@@ -783,30 +747,26 @@ void SCR_ScreenShot_f (void)
// read quality as the 3rd param (only used for JPG) // read quality as the 3rd param (only used for JPG)
quality = 90; quality = 90;
if (command::argc() >= 3) if (command::argc() >= 3)
quality = Q_atoi (command::argv(2)->c_str()); quality = std::atoi(command::argv(2)->c_str());
if (quality < 1 || quality > 100) if (quality < 1 || quality > 100) {
{
SCR_ScreenShot_Usage(); SCR_ScreenShot_Usage();
return; return;
} }
// find a file name to save it to // find a file name to save it to
for (i=0; i<10000; i++) for (i = 0; i < 10000; i++) {
{
q_snprintf(imagename, sizeof(imagename), "spasm%04i.%s", i, ext); // "fitz%04i.tga" q_snprintf(imagename, sizeof(imagename), "spasm%04i.%s", i, ext); // "fitz%04i.tga"
q_snprintf(checkname, sizeof(checkname), "%s/%s", com_gamedir, imagename); q_snprintf(checkname, sizeof(checkname), "%s/%s", com_gamedir, imagename);
if (Sys_FileType(checkname) == FS_ENT_NONE) if (Sys_FileType(checkname) == FS_ENT_NONE)
break; // file doesn't exist break; // file doesn't exist
} }
if (i == 10000) if (i == 10000) {
{
Con_Printf("SCR_ScreenShot_f: Couldn't find an unused filename\n"); Con_Printf("SCR_ScreenShot_f: Couldn't find an unused filename\n");
return; return;
} }
//get data //get data
if (!(buffer = (byte *) malloc(glwidth*glheight*3))) if (!(buffer = (byte *) malloc(glwidth * glheight * 3))) {
{
Con_Printf("SCR_ScreenShot_f: Couldn't allocate memory\n"); Con_Printf("SCR_ScreenShot_f: Couldn't allocate memory\n");
return; return;
} }
@@ -842,8 +802,7 @@ SCR_BeginLoadingPlaque
================ ================
*/ */
void SCR_BeginLoadingPlaque (void) void SCR_BeginLoadingPlaque(void) {
{
S_StopAllSounds(true); S_StopAllSounds(true);
if (cls.state != ca_connected) if (cls.state != ca_connected)
@@ -871,8 +830,7 @@ SCR_EndLoadingPlaque
================ ================
*/ */
void SCR_EndLoadingPlaque (void) void SCR_EndLoadingPlaque(void) {
{
scr_disabled_for_loading = false; scr_disabled_for_loading = false;
Con_ClearNotify(); Con_ClearNotify();
} }
@@ -880,10 +838,9 @@ void SCR_EndLoadingPlaque (void)
//============================================================================= //=============================================================================
const char *scr_notifystring; const char *scr_notifystring;
qboolean scr_drawdialog; bool scr_drawdialog;
void SCR_DrawNotifyString (void) void SCR_DrawNotifyString(void) {
{
const char *start; const char *start;
int l; int l;
int j; int j;
@@ -895,8 +852,7 @@ void SCR_DrawNotifyString (void)
y = 200 * 0.35; //johnfitz -- stretched overlays y = 200 * 0.35; //johnfitz -- stretched overlays
do do {
{
// scan the width of the line // scan the width of the line
for (l = 0; l < 40; l++) for (l = 0; l < 40; l++)
if (start[l] == '\n' || !start[l]) if (start[l] == '\n' || !start[l])
@@ -945,8 +901,7 @@ int SCR_ModalMessage (const char *text, float timeout) //johnfitz -- timeout
time2 = 0.0f; //johnfitz -- timeout time2 = 0.0f; //johnfitz -- timeout
Key_BeginInputGrab(); Key_BeginInputGrab();
do do {
{
Sys_SendKeyEvents(); Sys_SendKeyEvents();
Key_GetGrabbedInput(&lastkey, &lastchar); Key_GetGrabbedInput(&lastkey, &lastchar);
Sys_Sleep(16); Sys_Sleep(16);
@@ -983,15 +938,13 @@ johnfitz -- modified to use glwidth/glheight instead of vid.width/vid.height
also added scr_tileclear_updates also added scr_tileclear_updates
================== ==================
*/ */
void SCR_TileClear (void) void SCR_TileClear(void) {
{
//ericw -- added check for glsl gamma. TODO: remove this ugly optimization? //ericw -- added check for glsl gamma. TODO: remove this ugly optimization?
if (scr_tileclear_updates >= vid.numpages && !gl_clear.value && !(gl_glsl_gamma_able && vid_gamma.value != 1)) if (scr_tileclear_updates >= vid.numpages && !gl_clear.value && !(gl_glsl_gamma_able && vid_gamma.value != 1))
return; return;
scr_tileclear_updates++; scr_tileclear_updates++;
if (r_refdef.vrect.x > 0) if (r_refdef.vrect.x > 0) {
{
// left // left
Draw_TileClear(0, Draw_TileClear(0,
0, 0,
@@ -1004,8 +957,7 @@ void SCR_TileClear (void)
glheight - sb_lines); glheight - sb_lines);
} }
if (r_refdef.vrect.y > 0) if (r_refdef.vrect.y > 0) {
{
// top // top
Draw_TileClear(r_refdef.vrect.x, Draw_TileClear(r_refdef.vrect.x,
0, 0,
@@ -1030,18 +982,14 @@ WARNING: be very careful calling this from elsewhere, because the refresh
needs almost the entire 256k of stack space! needs almost the entire 256k of stack space!
================== ==================
*/ */
void SCR_UpdateScreen (void) void SCR_UpdateScreen(void) {
{
vid.numpages = (gl_triplebuffer.value) ? 3 : 2; vid.numpages = (gl_triplebuffer.value) ? 3 : 2;
if (scr_disabled_for_loading) if (scr_disabled_for_loading) {
{ if (realtime - scr_disabled_time > 60) {
if (realtime - scr_disabled_time > 60)
{
scr_disabled_for_loading = false; scr_disabled_for_loading = false;
Con_Printf("load failed.\n"); Con_Printf("load failed.\n");
} } else
else
return; return;
} }
@@ -1077,23 +1025,18 @@ void SCR_UpdateScreen (void)
Sbar_Draw(); Sbar_Draw();
Draw_FadeScreen(); Draw_FadeScreen();
SCR_DrawNotifyString(); SCR_DrawNotifyString();
} } else if (scr_drawloading) //loading
else if (scr_drawloading) //loading
{ {
SCR_DrawLoading(); SCR_DrawLoading();
Sbar_Draw(); Sbar_Draw();
} } else if (cl.intermission == 1 && key_dest == key_game) //end of level
else if (cl.intermission == 1 && key_dest == key_game) //end of level
{ {
Sbar_IntermissionOverlay(); Sbar_IntermissionOverlay();
} } else if (cl.intermission == 2 && key_dest == key_game) //end of episode
else if (cl.intermission == 2 && key_dest == key_game) //end of episode
{ {
Sbar_FinaleOverlay(); Sbar_FinaleOverlay();
SCR_CheckDrawCenterString(); SCR_CheckDrawCenterString();
} } else {
else
{
SCR_DrawCrosshair(); //johnfitz SCR_DrawCrosshair(); //johnfitz
SCR_DrawNet(); SCR_DrawNet();
SCR_DrawTurtle(); SCR_DrawTurtle();
@@ -1113,4 +1056,3 @@ void SCR_UpdateScreen (void)
GL_EndRendering(); GL_EndRendering();
} }
+6 -5
View File
@@ -221,7 +221,7 @@ void Sky_LoadSkyBox (const char *name)
int i, mark, width, height; int i, mark, width, height;
char filename[MAX_OSPATH]; char filename[MAX_OSPATH];
byte *data; byte *data;
qboolean nonefound = true; bool nonefound = true;
if (strcmp(skybox_name, name) == 0) if (strcmp(skybox_name, name) == 0)
return; //no change return; //no change
@@ -502,7 +502,7 @@ static void Sky_ClipPoly (int nump, vec3_t vecs, int stage)
{ {
const float *norm; const float *norm;
float *v; float *v;
qboolean front, back; bool front, back;
float d, e; float d, e;
int newc[2]; int newc[2];
int i, j; int i, j;
@@ -680,7 +680,7 @@ void Sky_ProcessEntities (void)
glpoly_t *p; glpoly_t *p;
int i,j,k,mark; int i,j,k,mark;
float dot; float dot;
qboolean rotated; bool rotated;
vec3_t temp, forward, right, up; vec3_t temp, forward, right, up;
if (!r_drawentities.value) if (!r_drawentities.value)
@@ -838,7 +838,7 @@ void Sky_DrawSkyBox (void)
c = Fog_GetColor(); c = Fog_GetColor();
glEnable (GL_BLEND); glEnable (GL_BLEND);
glDisable (GL_TEXTURE_2D); glDisable (GL_TEXTURE_2D);
glColor4f (c[0],c[1],c[2], CLAMP(0.0f,skyfog,1.0f)); glColor4f (c[0],c[1],c[2], std::clamp(skyfog,0.0f, 1.0f));
glBegin (GL_QUADS); glBegin (GL_QUADS);
Sky_EmitSkyBoxVertex (skymins[0][i], skymins[1][i], i); Sky_EmitSkyBoxVertex (skymins[0][i], skymins[1][i], i);
@@ -989,13 +989,14 @@ void Sky_DrawFaceQuad (glpoly_t *p)
c = Fog_GetColor(); c = Fog_GetColor();
glEnable (GL_BLEND); glEnable (GL_BLEND);
glDisable (GL_TEXTURE_2D); glDisable (GL_TEXTURE_2D);
glColor4f (c[0],c[1],c[2], CLAMP(0.0f,skyfog,1.0f)); glColor4f (c[0],c[1],c[2], std::clamp(skyfog,0.0f, 1.0f));
glBegin (GL_QUADS); glBegin (GL_QUADS);
for (i=0, v=p->verts[0] ; i<4 ; i++, v+=VERTEXSIZE) for (i=0, v=p->verts[0] ; i<4 ; i++, v+=VERTEXSIZE)
glVertex3fv (v); glVertex3fv (v);
glEnd (); glEnd ();
glColor3f (1, 1, 1); glColor3f (1, 1, 1);
glEnable (GL_TEXTURE_2D); glEnable (GL_TEXTURE_2D);
glDisable (GL_BLEND); glDisable (GL_BLEND);
+9 -7
View File
@@ -22,6 +22,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//gl_texmgr.c -- fitzquake's texture manager. manages opengl texture images //gl_texmgr.c -- fitzquake's texture manager. manages opengl texture images
#include <cstring>
#include "quakedef.hpp" #include "quakedef.hpp"
static const int gl_solid_format = 3; static const int gl_solid_format = 3;
@@ -68,7 +70,7 @@ static glmode_t glmodes[] = {
{GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, "GL_LINEAR_MIPMAP_NEAREST"}, {GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, "GL_LINEAR_MIPMAP_NEAREST"},
{GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, "GL_LINEAR_MIPMAP_LINEAR"}, {GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, "GL_LINEAR_MIPMAP_LINEAR"},
}; };
#define NUM_GLMODES (int)Q_COUNTOF(glmodes) #define NUM_GLMODES (int)std::size(glmodes)
static int glmode_idx = NUM_GLMODES - 1; /* trilinear */ static int glmode_idx = NUM_GLMODES - 1; /* trilinear */
/* /*
@@ -117,7 +119,7 @@ static void TexMgr_TextureMode_f(convar *var) {
int i; int i;
for (i = 0; i < NUM_GLMODES; i++) { for (i = 0; i < NUM_GLMODES; i++) {
if (!Q_strcmp(glmodes[i].name, gl_texturemode.string)) { if (!std::strcmp(glmodes[i].name, gl_texturemode.string)) {
if (glmode_idx != i) { if (glmode_idx != i) {
glmode_idx = i; glmode_idx = i;
for (glt = active_gltextures; glt; glt = glt->next) for (glt = active_gltextures; glt; glt = glt->next)
@@ -306,7 +308,7 @@ gltexture_t *TexMgr_NewTexture(void) {
static void GL_DeleteTexture(gltexture_t *texture); static void GL_DeleteTexture(gltexture_t *texture);
//ericw -- workaround for preventing TexMgr_FreeTexture during TexMgr_ReloadImages //ericw -- workaround for preventing TexMgr_FreeTexture during TexMgr_ReloadImages
static qboolean in_reload_images; static bool in_reload_images;
/* /*
================ ================
@@ -688,7 +690,7 @@ static unsigned *TexMgr_MipMapH(unsigned *data, int width, int height) {
TexMgr_ResampleTexture -- bilinear resample TexMgr_ResampleTexture -- bilinear resample
================ ================
*/ */
static unsigned *TexMgr_ResampleTexture(unsigned *in, int inwidth, int inheight, qboolean alpha) { static unsigned *TexMgr_ResampleTexture(unsigned *in, int inwidth, int inheight, bool alpha) {
byte *nwpx, *nepx, *swpx, *sepx, *dest; byte *nwpx, *nepx, *swpx, *sepx, *dest;
unsigned xfrac, yfrac, x, y, modx, mody, imodx, imody, injump, outjump; unsigned xfrac, yfrac, x, y, modx, mody, imodx, imody, injump, outjump;
unsigned *out; unsigned *out;
@@ -1047,7 +1049,7 @@ TexMgr_LoadImage8 -- handles 8bit source data, then passes it to LoadImage32
*/ */
static void TexMgr_LoadImage8(gltexture_t *glt, byte *data) { static void TexMgr_LoadImage8(gltexture_t *glt, byte *data) {
extern convar gl_fullbrights; extern convar gl_fullbrights;
qboolean padw = false, padh = false; bool padw = false, padh = false;
byte padbyte; byte padbyte;
unsigned int *usepal; unsigned int *usepal;
int i; int i;
@@ -1129,7 +1131,7 @@ TexMgr_LoadLightmap -- handles lightmap data
================ ================
*/ */
static void TexMgr_LoadLightmap(gltexture_t *glt, byte *data) { static void TexMgr_LoadLightmap(gltexture_t *glt, byte *data) {
const qboolean wide10bits = !!r_lightmapwide.value; const bool wide10bits = !!r_lightmapwide.value;
const GLenum type = wide10bits ? GL_UNSIGNED_INT_10_10_10_2 : GL_UNSIGNED_BYTE; const GLenum type = wide10bits ? GL_UNSIGNED_INT_10_10_10_2 : GL_UNSIGNED_BYTE;
const GLint internalfmt = wide10bits ? GL_RGB10_A2 : lightmap_bytes; const GLint internalfmt = wide10bits ? GL_RGB10_A2 : lightmap_bytes;
@@ -1381,7 +1383,7 @@ void TexMgr_ReloadNobrightImages(void) {
static GLuint currenttexture[3] = {GL_UNUSED_TEXTURE, GL_UNUSED_TEXTURE, GL_UNUSED_TEXTURE}; static GLuint currenttexture[3] = {GL_UNUSED_TEXTURE, GL_UNUSED_TEXTURE, GL_UNUSED_TEXTURE};
// to avoid unnecessary texture sets // to avoid unnecessary texture sets
static GLenum currenttarget = GL_TEXTURE0_ARB; static GLenum currenttarget = GL_TEXTURE0_ARB;
qboolean mtexenabled = false; bool mtexenabled = false;
/* /*
================ ================
+74 -74
View File
@@ -71,7 +71,7 @@ static char *gl_extensions_nice;
static vmode_t modelist[MAX_MODE_LIST]; static vmode_t modelist[MAX_MODE_LIST];
static int nummodes; static int nummodes;
static qboolean vid_initialized = false; static bool vid_initialized = false;
#if defined(USE_SDL2) #if defined(USE_SDL2)
static SDL_Window *draw_context; static SDL_Window *draw_context;
@@ -80,8 +80,8 @@ static SDL_GLContext gl_context;
static SDL_Surface *draw_context; static SDL_Surface *draw_context;
#endif #endif
static qboolean vid_locked = false; //johnfitz static bool vid_locked = false; //johnfitz
static qboolean vid_changed = false; static bool vid_changed = false;
static void VID_Menu_Init(void); //johnfitz static void VID_Menu_Init(void); //johnfitz
static void VID_Menu_f(void); //johnfitz static void VID_Menu_f(void); //johnfitz
@@ -97,21 +97,21 @@ static void GL_SetupState(void); //johnfitz
viddef_t vid; // global video state viddef_t vid; // global video state
modestate_t modestate = MS_UNINIT; modestate_t modestate = MS_UNINIT;
qboolean scr_skipupdate; bool scr_skipupdate;
qboolean gl_mtexable = false; bool gl_mtexable = false;
qboolean gl_packed_pixels = false; bool gl_packed_pixels = false;
qboolean gl_texture_env_combine = false; //johnfitz bool gl_texture_env_combine = false; //johnfitz
qboolean gl_texture_env_add = false; //johnfitz bool gl_texture_env_add = false; //johnfitz
qboolean gl_swap_control = false; //johnfitz bool gl_swap_control = false; //johnfitz
qboolean gl_anisotropy_able = false; //johnfitz bool gl_anisotropy_able = false; //johnfitz
float gl_max_anisotropy; //johnfitz float gl_max_anisotropy; //johnfitz
qboolean gl_texture_NPOT = false; //ericw bool gl_texture_NPOT = false; //ericw
qboolean gl_vbo_able = false; //ericw bool gl_vbo_able = false; //ericw
qboolean gl_glsl_able = false; //ericw bool gl_glsl_able = false; //ericw
GLint gl_max_texture_units = 0; //ericw GLint gl_max_texture_units = 0; //ericw
qboolean gl_glsl_gamma_able = false; //ericw bool gl_glsl_gamma_able = false; //ericw
qboolean gl_glsl_alias_able = false; //ericw bool gl_glsl_alias_able = false; //ericw
int gl_stencilbits; int gl_stencilbits;
PFNGLMULTITEXCOORD2FARBPROC GL_MTexCoord2fFunc = NULL; //johnfitz PFNGLMULTITEXCOORD2FARBPROC GL_MTexCoord2fFunc = NULL; //johnfitz
@@ -184,7 +184,7 @@ static unsigned short vid_sysgamma_green[256];
static unsigned short vid_sysgamma_blue[256]; static unsigned short vid_sysgamma_blue[256];
#endif #endif
static qboolean gammaworks = false; // whether hw-gamma works static bool gammaworks = false; // whether hw-gamma works
static int fsaa; static int fsaa;
/* /*
@@ -396,7 +396,7 @@ VID_GetFullscreen
returns true if we are in regular fullscreen or "desktop fullscren" returns true if we are in regular fullscreen or "desktop fullscren"
==================== ====================
*/ */
static qboolean VID_GetFullscreen(void) { static bool VID_GetFullscreen(void) {
#if defined(USE_SDL2) #if defined(USE_SDL2)
return (SDL_GetWindowFlags(draw_context) & SDL_WINDOW_FULLSCREEN) != 0; return (SDL_GetWindowFlags(draw_context) & SDL_WINDOW_FULLSCREEN) != 0;
#else #else
@@ -411,7 +411,7 @@ VID_GetDesktopFullscreen
returns true if we are specifically in "desktop fullscreen" mode returns true if we are specifically in "desktop fullscreen" mode
==================== ====================
*/ */
static qboolean VID_GetDesktopFullscreen(void) { static bool VID_GetDesktopFullscreen(void) {
#if defined(USE_SDL2) #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 #else
@@ -424,7 +424,7 @@ static qboolean VID_GetDesktopFullscreen(void) {
VID_GetVSync VID_GetVSync
==================== ====================
*/ */
static qboolean VID_GetVSync(void) { static bool VID_GetVSync(void) {
#if defined(USE_SDL2) #if defined(USE_SDL2)
return SDL_GL_GetSwapInterval() == 1; return SDL_GL_GetSwapInterval() == 1;
#else #else
@@ -455,7 +455,7 @@ void *VID_GetWindow(void) {
VID_HasMouseOrInputFocus VID_HasMouseOrInputFocus
==================== ====================
*/ */
qboolean VID_HasMouseOrInputFocus(void) { bool VID_HasMouseOrInputFocus(void) {
#if defined(USE_SDL2) #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 #else
@@ -468,7 +468,7 @@ qboolean VID_HasMouseOrInputFocus(void) {
VID_IsMinimized VID_IsMinimized
==================== ====================
*/ */
qboolean VID_IsMinimized(void) { bool VID_IsMinimized(void) {
#if defined(USE_SDL2) #if defined(USE_SDL2)
return !(SDL_GetWindowFlags(draw_context) & SDL_WINDOW_SHOWN); return !(SDL_GetWindowFlags(draw_context) & SDL_WINDOW_SHOWN);
#else #else
@@ -514,7 +514,7 @@ static SDL_DisplayMode *VID_SDL2_GetDisplayMode(int width, int height, int refre
VID_ValidMode VID_ValidMode
================ ================
*/ */
static qboolean VID_ValidMode(int width, int height, int refreshrate, int bpp, qboolean fullscreen) { static bool VID_ValidMode(int width, int height, int refreshrate, int bpp, bool fullscreen) {
// ignore width / height / bpp if vid_desktopfullscreen is enabled // ignore width / height / bpp if vid_desktopfullscreen is enabled
if (fullscreen && vid_desktopfullscreen.value) if (fullscreen && vid_desktopfullscreen.value)
return true; return true;
@@ -555,7 +555,7 @@ static qboolean VID_ValidMode(int width, int height, int refreshrate, int bpp, q
VID_SetMode VID_SetMode
================ ================
*/ */
static qboolean VID_SetMode(int width, int height, int refreshrate, int bpp, qboolean fullscreen) { static bool VID_SetMode(int width, int height, int refreshrate, int bpp, bool fullscreen) {
int temp; int temp;
Uint32 flags; Uint32 flags;
char caption[50]; char caption[50];
@@ -570,7 +570,7 @@ static qboolean VID_SetMode(int width, int height, int refreshrate, int bpp, qbo
scr_disabled_for_loading = true; scr_disabled_for_loading = true;
CDAudio_Pause(); CDAudio_Pause();
BGM_Pause(); music::pause();
/* z-buffer depth */ /* z-buffer depth */
if (bpp == 16) { if (bpp == 16) {
@@ -722,7 +722,7 @@ static qboolean VID_SetMode(int width, int height, int refreshrate, int bpp, qbo
modestate = VID_GetFullscreen() ? MS_FULLSCREEN : MS_WINDOWED; modestate = VID_GetFullscreen() ? MS_FULLSCREEN : MS_WINDOWED;
CDAudio_Resume(); CDAudio_Resume();
BGM_Resume(); music::resume();
scr_disabled_for_loading = temp; scr_disabled_for_loading = temp;
// fix the leftover Alt from any Alt-Tab or the like that switched us away // fix the leftover Alt from any Alt-Tab or the like that switched us away
@@ -760,7 +760,7 @@ VID_Restart -- johnfitz -- change video modes on the fly
*/ */
static void VID_Restart(void) { static void VID_Restart(void) {
int width, height, refreshrate, bpp; int width, height, refreshrate, bpp;
qboolean fullscreen; bool fullscreen;
if (vid_locked || !vid_changed) if (vid_locked || !vid_changed)
return; return;
@@ -815,7 +815,7 @@ static void VID_Restart(void) {
: (scr_conscale.value > 0) : (scr_conscale.value > 0)
? (int) (vid.width / scr_conscale.value) ? (int) (vid.width / scr_conscale.value)
: vid.width; : vid.width;
vid.conwidth = CLAMP(320, vid.conwidth, vid.width); vid.conwidth = std::clamp(vid.conwidth, 320, vid.width);
vid.conwidth &= 0xFFFFFFF8; vid.conwidth &= 0xFFFFFFF8;
vid.conheight = vid.conwidth * vid.height / vid.width; vid.conheight = vid.conwidth * vid.height / vid.width;
// //
@@ -944,7 +944,7 @@ static void GL_Info_f(void) {
GL_CheckExtensions GL_CheckExtensions
=============== ===============
*/ */
static qboolean GL_ParseExtensionList(const char *list, const char *name) { static bool GL_ParseExtensionList(const char *list, const char *name) {
const char *start; const char *start;
const char *where, *terminator; const char *where, *terminator;
@@ -972,7 +972,7 @@ static void GL_CheckExtensions(void) {
// ARB_vertex_buffer_object // ARB_vertex_buffer_object
// //
if (COM_CheckParm("-novbo")) if (common::check_param("-novbo").has_value())
Con_Warning("Vertex buffer objects disabled at command line\n"); Con_Warning("Vertex buffer objects disabled at command line\n");
else if (gl_version_major < 1 || (gl_version_major == 1 && gl_version_minor < 5)) 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"); Con_Warning("OpenGL version < 1.5, skipping ARB_vertex_buffer_object check\n");
@@ -993,7 +993,7 @@ static void GL_CheckExtensions(void) {
// multitexture // multitexture
// //
if (COM_CheckParm("-nomtex")) if (common::check_param("-nomtex").has_value())
Con_Warning("Mutitexture disabled at command line\n"); Con_Warning("Mutitexture disabled at command line\n");
else if (GL_ParseExtensionList(gl_extensions, "GL_ARB_multitexture")) { else if (GL_ParseExtensionList(gl_extensions, "GL_ARB_multitexture")) {
GL_MTexCoord2fFunc = (PFNGLMULTITEXCOORD2FARBPROC) SDL_GL_GetProcAddress("glMultiTexCoord2fARB"); GL_MTexCoord2fFunc = (PFNGLMULTITEXCOORD2FARBPROC) SDL_GL_GetProcAddress("glMultiTexCoord2fARB");
@@ -1015,7 +1015,7 @@ static void GL_CheckExtensions(void) {
// texture_env_combine // texture_env_combine
// //
if (COM_CheckParm("-nocombine")) if (common::check_param("-nocombine").has_value())
Con_Warning("texture_env_combine disabled at command line\n"); Con_Warning("texture_env_combine disabled at command line\n");
else if (GL_ParseExtensionList(gl_extensions, "GL_ARB_texture_env_combine")) { else if (GL_ParseExtensionList(gl_extensions, "GL_ARB_texture_env_combine")) {
Con_Printf("FOUND: ARB_texture_env_combine\n"); Con_Printf("FOUND: ARB_texture_env_combine\n");
@@ -1029,7 +1029,7 @@ static void GL_CheckExtensions(void) {
// texture_env_add // texture_env_add
// //
if (COM_CheckParm("-noadd")) if (common::check_param("-noadd").has_value())
Con_Warning("texture_env_add disabled at command line\n"); Con_Warning("texture_env_add disabled at command line\n");
else if (GL_ParseExtensionList(gl_extensions, "GL_ARB_texture_env_add")) { else if (GL_ParseExtensionList(gl_extensions, "GL_ARB_texture_env_add")) {
Con_Printf("FOUND: ARB_texture_env_add\n"); Con_Printf("FOUND: ARB_texture_env_add\n");
@@ -1110,7 +1110,7 @@ static void GL_CheckExtensions(void) {
// texture_non_power_of_two // texture_non_power_of_two
// //
if (COM_CheckParm("-notexturenpot")) if (common::check_param("-notexturenpot").has_value())
Con_Warning("texture_non_power_of_two disabled at command line\n"); 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")) { else if (GL_ParseExtensionList(gl_extensions, "GL_ARB_texture_non_power_of_two")) {
Con_Printf("FOUND: ARB_texture_non_power_of_two\n"); Con_Printf("FOUND: ARB_texture_non_power_of_two\n");
@@ -1121,7 +1121,7 @@ static void GL_CheckExtensions(void) {
// GLSL // GLSL
// //
if (COM_CheckParm("-noglsl")) if (common::check_param("-noglsl").has_value())
Con_Warning("GLSL disabled at command line\n"); Con_Warning("GLSL disabled at command line\n");
else if (gl_version_major >= 2) { else if (gl_version_major >= 2) {
GL_CreateShaderFunc = (QS_PFNGLCREATESHADERPROC) SDL_GL_GetProcAddress("glCreateShader"); GL_CreateShaderFunc = (QS_PFNGLCREATESHADERPROC) SDL_GL_GetProcAddress("glCreateShader");
@@ -1183,7 +1183,7 @@ static void GL_CheckExtensions(void) {
} }
// GLSL gamma // GLSL gamma
// //
if (COM_CheckParm("-noglslgamma")) if (common::check_param("-noglslgamma").has_value())
Con_Warning("GLSL gamma disabled at command line\n"); Con_Warning("GLSL gamma disabled at command line\n");
else if (gl_glsl_able) { else if (gl_glsl_able) {
gl_glsl_gamma_able = true; gl_glsl_gamma_able = true;
@@ -1193,7 +1193,7 @@ static void GL_CheckExtensions(void) {
} }
// GLSL alias model rendering // GLSL alias model rendering
// //
if (COM_CheckParm("-noglslalias")) if (common::check_param("-noglslalias").has_value())
Con_Warning("GLSL alias model rendering disabled at command line\n"); Con_Warning("GLSL alias model rendering disabled at command line\n");
else if (gl_glsl_able && gl_vbo_able && gl_max_texture_units >= 3) { else if (gl_glsl_able && gl_vbo_able && gl_max_texture_units >= 3) {
gl_glsl_alias_able = true; gl_glsl_alias_able = true;
@@ -1204,7 +1204,7 @@ static void GL_CheckExtensions(void) {
// packed_pixels // packed_pixels
// //
if (COM_CheckParm("-nopackedpixels")) if (common::check_param("-nopackedpixels").has_value())
Con_Warning("EXT_packed_pixels disabled at command line\n"); Con_Warning("EXT_packed_pixels disabled at command line\n");
else if (gl_glsl_alias_able) { else if (gl_glsl_alias_able) {
gl_packed_pixels = true; gl_packed_pixels = true;
@@ -1223,7 +1223,7 @@ static void GL_CheckExtensions(void) {
#endif #endif
// glGenerateMipmap for warp textures // glGenerateMipmap for warp textures
if (COM_CheckParm("-nowarpmipmaps")) if (common::check_param("-nowarpmipmaps").has_value())
Con_Warning("glGenerateMipmap disabled at command line\n"); Con_Warning("glGenerateMipmap disabled at command line\n");
else { else {
if (gl_version_major >= 3 || GL_ParseExtensionList(gl_extensions, "GL_ARB_framebuffer_object")) { if (gl_version_major >= 3 || GL_ParseExtensionList(gl_extensions, "GL_ARB_framebuffer_object")) {
@@ -1305,7 +1305,7 @@ static void GL_Init(void) {
//johnfitz -- intel video workarounds from Baker //johnfitz -- intel video workarounds from Baker
if (!strcmp(gl_vendor, "Intel")) { if (!strcmp(gl_vendor, "Intel")) {
Con_Printf("Intel Display Adapter detected, enabling gl_clear\n"); Con_Printf("Intel Display Adapter detected, enabling gl_clear\n");
Cbuf_AddText("gl_clear 1"); command::buffer::add_text("gl_clear 1");
} }
//johnfitz //johnfitz
@@ -1474,7 +1474,7 @@ static void VID_InitModelist(void) {
// enumerate fullscreen modes // enumerate fullscreen modes
flags = DEFAULT_SDL_FLAGS | SDL_FULLSCREEN; flags = DEFAULT_SDL_FLAGS | SDL_FULLSCREEN;
for (i = 0; i < (int) Q_COUNTOF(bpps); i++) { for (i = 0; i < (int) std::size(bpps); i++) {
if (nummodes >= MAX_MODE_LIST) if (nummodes >= MAX_MODE_LIST)
break; break;
@@ -1520,9 +1520,9 @@ VID_Init
*/ */
void VID_Init(void) { void VID_Init(void) {
static char vid_center[] = "SDL_VIDEO_CENTERED=center"; static char vid_center[] = "SDL_VIDEO_CENTERED=center";
int p, width, height, refreshrate, bpp; int width, height, refreshrate, bpp;
int display_width, display_height, display_refreshrate, display_bpp; int display_width, display_height, display_refreshrate, display_bpp;
qboolean fullscreen; bool fullscreen;
const char *read_vars[] = { const char *read_vars[] = {
"vid_fullscreen", "vid_fullscreen",
"vid_width", "vid_width",
@@ -1534,7 +1534,7 @@ void VID_Init(void) {
"vid_desktopfullscreen", "vid_desktopfullscreen",
"vid_borderless" "vid_borderless"
}; };
#define num_readvars Q_COUNTOF(read_vars) #define num_readvars std::size(read_vars)
vid_fullscreen.inscribe(); //johnfitz vid_fullscreen.inscribe(); //johnfitz
vid_width.inscribe(); //johnfitz vid_width.inscribe(); //johnfitz
@@ -1604,46 +1604,46 @@ void VID_Init(void) {
fullscreen = (int) vid_fullscreen.value; fullscreen = (int) vid_fullscreen.value;
fsaa = (int) vid_fsaa.value; fsaa = (int) vid_fsaa.value;
if (COM_CheckParm("-current")) { if (common::check_param("-current").has_value()) {
width = display_width; width = display_width;
height = display_height; height = display_height;
refreshrate = display_refreshrate; refreshrate = display_refreshrate;
bpp = display_bpp; bpp = display_bpp;
fullscreen = true; fullscreen = true;
} else { } else {
p = COM_CheckParm("-width"); auto p = common::check_param("-width");
if (p && p < com_argc - 1) { if (p.has_value() && p.value() < com_argc - 1) {
width = Q_atoi(com_argv[p + 1]); width = std::atoi(com_argv[p.value() + 1]);
if (!COM_CheckParm("-height")) if (!common::check_param("-height").has_value())
height = width * 3 / 4; height = width * 3 / 4;
} }
p = COM_CheckParm("-height"); p = common::check_param("-height");
if (p && p < com_argc - 1) { if (p.has_value() && p.value() < com_argc - 1) {
height = Q_atoi(com_argv[p + 1]); height = std::atoi(com_argv[p.value() + 1]);
if (!COM_CheckParm("-width")) if (!common::check_param("-width").has_value())
width = height * 4 / 3; width = height * 4 / 3;
} }
p = COM_CheckParm("-refreshrate"); p = common::check_param("-refreshrate");
if (p && p < com_argc - 1) if (p.has_value() && p.value() < com_argc - 1)
refreshrate = Q_atoi(com_argv[p + 1]); refreshrate = std::atoi(com_argv[p.value() + 1]);
p = COM_CheckParm("-bpp"); p = common::check_param("-bpp");
if (p && p < com_argc - 1) if (p.has_value() && p.value() < com_argc - 1)
bpp = Q_atoi(com_argv[p + 1]); bpp = std::atoi(com_argv[p.value() + 1]);
if (COM_CheckParm("-window") || COM_CheckParm("-w")) if (common::check_param("-window").has_value() || common::check_param("-w").has_value())
fullscreen = false; fullscreen = false;
else if (COM_CheckParm("-fullscreen") || COM_CheckParm("-f")) else if (common::check_param("-fullscreen").has_value() || common::check_param("-f").has_value())
fullscreen = true; fullscreen = true;
} }
p = COM_CheckParm("-fsaa"); auto p = common::check_param("-fsaa");
if (p && p < com_argc - 1) if (p.has_value() && p.value() < com_argc - 1)
fsaa = atoi(com_argv[p + 1]); fsaa = atoi(com_argv[p.value() + 1]);
if (!VID_ValidMode(width, height, refreshrate, bpp, fullscreen)) { if (!VID_ValidMode(width, height, refreshrate, bpp, fullscreen)) {
width = (int) vid_width.value; width = (int) vid_width.value;
@@ -1706,8 +1706,8 @@ void VID_Toggle(void) {
// TODO: Clear out the dead code, reinstate the fast path using SDL_SetWindowFullscreen // 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 // inside VID_SetMode, check window size to fix WinXP issue. This will
// keep all the mode changing code in one place. // keep all the mode changing code in one place.
static qboolean vid_toggle_works = false; static bool vid_toggle_works = false;
qboolean toggleWorked; bool toggleWorked;
#if defined(USE_SDL2) #if defined(USE_SDL2)
Uint32 flags = 0; Uint32 flags = 0;
#endif #endif
@@ -1756,7 +1756,7 @@ void VID_Toggle(void) {
Con_DPrintf("SDL_WM_ToggleFullScreen failed, attempting VID_Restart\n"); Con_DPrintf("SDL_WM_ToggleFullScreen failed, attempting VID_Restart\n");
vrestart: vrestart:
vid_fullscreen.set(VID_GetFullscreen() ? "0" : "1"); vid_fullscreen.set(VID_GetFullscreen() ? "0" : "1");
Cbuf_AddText("vid_restart\n"); command::buffer::add_text("vid_restart\n");
} }
} }
@@ -2074,10 +2074,10 @@ static void VID_MenuKey(int key) {
VID_Menu_ChooseNextRate(1); VID_Menu_ChooseNextRate(1);
break; break;
case VID_OPT_FULLSCREEN: case VID_OPT_FULLSCREEN:
Cbuf_AddText("toggle vid_fullscreen\n"); command::buffer::add_text("toggle vid_fullscreen\n");
break; break;
case VID_OPT_VSYNC: case VID_OPT_VSYNC:
Cbuf_AddText("toggle vid_vsync\n"); // kristian command::buffer::add_text("toggle vid_vsync\n"); // kristian
break; break;
default: default:
break; break;
@@ -2097,10 +2097,10 @@ static void VID_MenuKey(int key) {
VID_Menu_ChooseNextRate(-1); VID_Menu_ChooseNextRate(-1);
break; break;
case VID_OPT_FULLSCREEN: case VID_OPT_FULLSCREEN:
Cbuf_AddText("toggle vid_fullscreen\n"); command::buffer::add_text("toggle vid_fullscreen\n");
break; break;
case VID_OPT_VSYNC: case VID_OPT_VSYNC:
Cbuf_AddText("toggle vid_vsync\n"); command::buffer::add_text("toggle vid_vsync\n");
break; break;
default: default:
break; break;
@@ -2122,16 +2122,16 @@ static void VID_MenuKey(int key) {
VID_Menu_ChooseNextRate(1); VID_Menu_ChooseNextRate(1);
break; break;
case VID_OPT_FULLSCREEN: case VID_OPT_FULLSCREEN:
Cbuf_AddText("toggle vid_fullscreen\n"); command::buffer::add_text("toggle vid_fullscreen\n");
break; break;
case VID_OPT_VSYNC: case VID_OPT_VSYNC:
Cbuf_AddText("toggle vid_vsync\n"); command::buffer::add_text("toggle vid_vsync\n");
break; break;
case VID_OPT_TEST: case VID_OPT_TEST:
Cbuf_AddText("vid_test\n"); command::buffer::add_text("vid_test\n");
break; break;
case VID_OPT_APPLY: case VID_OPT_APPLY:
Cbuf_AddText("vid_restart\n"); command::buffer::add_text("vid_restart\n");
key_dest = key_game; key_dest = key_game;
m_state = m_none; m_state = m_none;
IN_Activate(); IN_Activate();
+1 -1
View File
@@ -229,7 +229,7 @@ void R_UpdateWarpTextures (void)
if (r_oldwater.value || cl.paused || r_drawflat_cheatsafe || r_lightmap_cheatsafe) if (r_oldwater.value || cl.paused || r_drawflat_cheatsafe || r_lightmap_cheatsafe)
return; return;
warptess = 128.0f/CLAMP (3.0f, floorf(r_waterquality.value), 64.0f); warptess = 128.0f/std::clamp(floorf(r_waterquality.value), 3.0f, 64.0f);
for (i=0; i<cl.worldmodel->numtextures; i++) for (i=0; i<cl.worldmodel->numtextures; i++)
{ {
+15 -15
View File
@@ -162,8 +162,8 @@ extern float load_subdivide_size; //johnfitz -- remember what subdivide_size val
extern int gl_stencilbits; extern int gl_stencilbits;
// Multitexture // Multitexture
extern qboolean mtexenabled; extern bool mtexenabled;
extern qboolean gl_mtexable; extern bool gl_mtexable;
extern PFNGLMULTITEXCOORD2FARBPROC GL_MTexCoord2fFunc; extern PFNGLMULTITEXCOORD2FARBPROC GL_MTexCoord2fFunc;
extern PFNGLACTIVETEXTUREARBPROC GL_SelectTextureFunc; extern PFNGLACTIVETEXTUREARBPROC GL_SelectTextureFunc;
extern PFNGLCLIENTACTIVETEXTUREARBPROC GL_ClientActiveTextureFunc; extern PFNGLCLIENTACTIVETEXTUREARBPROC GL_ClientActiveTextureFunc;
@@ -173,7 +173,7 @@ extern GLint gl_max_texture_units; //ericw
#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE #define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE
#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF #define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
extern float gl_max_anisotropy; extern float gl_max_anisotropy;
extern qboolean gl_anisotropy_able; extern bool gl_anisotropy_able;
//ericw -- VBO //ericw -- VBO
extern PFNGLBINDBUFFERARBPROC GL_BindBufferFunc; extern PFNGLBINDBUFFERARBPROC GL_BindBufferFunc;
@@ -181,7 +181,7 @@ extern PFNGLBUFFERDATAARBPROC GL_BufferDataFunc;
extern PFNGLBUFFERSUBDATAARBPROC GL_BufferSubDataFunc; extern PFNGLBUFFERSUBDATAARBPROC GL_BufferSubDataFunc;
extern PFNGLDELETEBUFFERSARBPROC GL_DeleteBuffersFunc; extern PFNGLDELETEBUFFERSARBPROC GL_DeleteBuffersFunc;
extern PFNGLGENBUFFERSARBPROC GL_GenBuffersFunc; extern PFNGLGENBUFFERSARBPROC GL_GenBuffersFunc;
extern qboolean gl_vbo_able; extern bool gl_vbo_able;
//ericw //ericw
//ericw -- GLSL //ericw -- GLSL
@@ -235,16 +235,16 @@ extern QS_PFNGLUNIFORM1IPROC GL_Uniform1iFunc;
extern QS_PFNGLUNIFORM1FPROC GL_Uniform1fFunc; extern QS_PFNGLUNIFORM1FPROC GL_Uniform1fFunc;
extern QS_PFNGLUNIFORM3FPROC GL_Uniform3fFunc; extern QS_PFNGLUNIFORM3FPROC GL_Uniform3fFunc;
extern QS_PFNGLUNIFORM4FPROC GL_Uniform4fFunc; extern QS_PFNGLUNIFORM4FPROC GL_Uniform4fFunc;
extern qboolean gl_glsl_able; extern bool gl_glsl_able;
extern qboolean gl_glsl_gamma_able; extern bool gl_glsl_gamma_able;
extern qboolean gl_glsl_alias_able; extern bool gl_glsl_alias_able;
// ericw -- // ericw --
//mipmapped warp textures //mipmapped warp textures
extern QS_PFNGENERATEMIPMAP GL_GenerateMipmap; extern QS_PFNGENERATEMIPMAP GL_GenerateMipmap;
//ericw -- NPOT texture support //ericw -- NPOT texture support
extern qboolean gl_texture_NPOT; extern bool gl_texture_NPOT;
//johnfitz -- polygon offset //johnfitz -- polygon offset
#define OFFSET_BMODEL 1 #define OFFSET_BMODEL 1
@@ -258,7 +258,7 @@ void GL_PolygonOffset (int);
#ifndef GL_UNSIGNED_INT_10_10_10_2 #ifndef GL_UNSIGNED_INT_10_10_10_2
#define GL_UNSIGNED_INT_10_10_10_2 0x8036 #define GL_UNSIGNED_INT_10_10_10_2 0x8036
#endif #endif
extern qboolean gl_packed_pixels; extern bool gl_packed_pixels;
//johnfitz -- GL_EXT_texture_env_combine //johnfitz -- GL_EXT_texture_env_combine
//the values for GL_ARB_ are identical //the values for GL_ARB_ are identical
@@ -273,8 +273,8 @@ extern qboolean gl_packed_pixels;
#define GL_SOURCE1_RGB_EXT 0x8581 #define GL_SOURCE1_RGB_EXT 0x8581
#define GL_SOURCE0_ALPHA_EXT 0x8588 #define GL_SOURCE0_ALPHA_EXT 0x8588
#define GL_SOURCE1_ALPHA_EXT 0x8589 #define GL_SOURCE1_ALPHA_EXT 0x8589
extern qboolean gl_texture_env_combine; extern bool gl_texture_env_combine;
extern qboolean gl_texture_env_add; // for GL_EXT_texture_env_add extern bool gl_texture_env_add; // for GL_EXT_texture_env_add
//johnfitz -- rendering statistics //johnfitz -- rendering statistics
extern int rs_brushpolys, rs_aliaspolys, rs_skypolys; extern int rs_brushpolys, rs_aliaspolys, rs_skypolys;
@@ -316,7 +316,7 @@ struct lightmap_s
{ {
gltexture_t *texture; gltexture_t *texture;
glpoly_t *polys; glpoly_t *polys;
qboolean modified; bool modified;
glRect_t rectchange; glRect_t rectchange;
// the lightmap texture data needs to be kept in // the lightmap texture data needs to be kept in
@@ -328,7 +328,7 @@ extern int lightmap_count; //allocated lightmaps
extern int gl_warpimagesize; //johnfitz -- for water warp extern int gl_warpimagesize; //johnfitz -- for water warp
extern qboolean r_drawflat_cheatsafe, r_fullbright_cheatsafe, r_lightmap_cheatsafe, r_drawworld_cheatsafe; //johnfitz extern bool r_drawflat_cheatsafe, r_fullbright_cheatsafe, r_lightmap_cheatsafe, r_drawworld_cheatsafe; //johnfitz
typedef struct glsl_attrib_binding_s { typedef struct glsl_attrib_binding_s {
const char *name; const char *name;
@@ -357,9 +357,9 @@ void R_NewGame (void);
void R_AnimateLight (void); void R_AnimateLight (void);
void R_MarkSurfaces (void); void R_MarkSurfaces (void);
qboolean R_CullBox (vec3_t emins, vec3_t emaxs); bool R_CullBox (vec3_t emins, vec3_t emaxs);
void R_StoreEfrags (efrag_t **ppefrag); void R_StoreEfrags (efrag_t **ppefrag);
qboolean R_CullModelForEntity (entity_t *e); bool R_CullModelForEntity (entity_t *e);
void R_RotateForEntity (vec3_t origin, vec3_t angles, unsigned char scale); void R_RotateForEntity (vec3_t origin, vec3_t angles, unsigned char scale);
void R_MarkLights (dlight_t *light, int num, mnode_t *node); void R_MarkLights (dlight_t *light, int num, mnode_t *node);
+80 -138
View File
@@ -39,7 +39,7 @@ Memory is cleared / released when a server or client begins, not when they end.
quakeparms_t *host_parms; quakeparms_t *host_parms;
qboolean host_initialized; // true if into command execution bool host_initialized; // true if into command execution
double host_frametime; double host_frametime;
double realtime; // without any filtering or bounding double realtime; // without any filtering or bounding
@@ -88,15 +88,15 @@ convar horde = {"horde","0"}; // for the 2021 rerelease
convar sv_cheats = {"sv_cheats", "0"}; // for the 2021 rerelease convar sv_cheats = {"sv_cheats", "0"}; // for the 2021 rerelease
devstats_t dev_stats, dev_peakstats; 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 overflowtimes_t dev_overflows;
//this stores the last time overflow messages were displayed, not the last time overflows occured
/* /*
================ ================
Max_Edicts_f -- johnfitz Max_Edicts_f -- johnfitz
================ ================
*/ */
static void Max_Edicts_f (convar *var) static void Max_Edicts_f(convar *var) {
{
//TODO: clamp it here? //TODO: clamp it here?
if (cls.state == ca_connected || sv.active) if (cls.state == ca_connected || sv.active)
Con_Printf("Changes to max_edicts will not take effect until the next time a map is loaded.\n"); Con_Printf("Changes to max_edicts will not take effect until the next time a map is loaded.\n");
@@ -107,8 +107,7 @@ static void Max_Edicts_f (convar *var)
Max_Fps_f -- ericw Max_Fps_f -- ericw
================ ================
*/ */
static void Max_Fps_f (convar *var) static void Max_Fps_f(convar *var) {
{
if (var->value > 72) if (var->value > 72)
Con_Warning("host_maxfps above 72 breaks physics.\n"); Con_Warning("host_maxfps above 72 breaks physics.\n");
} }
@@ -118,8 +117,7 @@ static void Max_Fps_f (convar *var)
Host_EndGame Host_EndGame
================ ================
*/ */
void Host_EndGame (const char *message, ...) void Host_EndGame(const char *message, ...) {
{
va_list argptr; va_list argptr;
char string[1024]; char string[1024];
@@ -149,11 +147,10 @@ Host_Error
This shuts down both the client and server This shuts down both the client and server
================ ================
*/ */
void Host_Error (const char *error, ...) void Host_Error(const char *error, ...) {
{
va_list argptr; va_list argptr;
char string[1024]; char string[1024];
static qboolean inerror = false; static bool inerror = false;
if (inerror) if (inerror)
Sys_Error("Host_Error: recursively entered"); Sys_Error("Host_Error: recursively entered");
@@ -186,33 +183,25 @@ void Host_Error (const char *error, ...)
Host_FindMaxClients Host_FindMaxClients
================ ================
*/ */
void Host_FindMaxClients (void) void Host_FindMaxClients(void) {
{
int i;
svs.maxclients = 1; svs.maxclients = 1;
i = COM_CheckParm ("-dedicated"); auto i = common::check_param("-dedicated");
if (i) if (i.has_value()) {
{
cls.state = ca_dedicated; cls.state = ca_dedicated;
if (i != (com_argc - 1)) if (i != (com_argc - 1)) {
{ svs.maxclients = std::atoi(com_argv[i.value() + 1]);
svs.maxclients = Q_atoi (com_argv[i+1]); } else
}
else
svs.maxclients = 8; svs.maxclients = 8;
} } else
else
cls.state = ca_disconnected; cls.state = ca_disconnected;
i = COM_CheckParm ("-listen"); i = common::check_param("-listen");
if (i) if (i.has_value()) {
{
if (cls.state == ca_dedicated) if (cls.state == ca_dedicated)
Sys_Error("Only one of -dedicated or -listen can be specified"); Sys_Error("Only one of -dedicated or -listen can be specified");
if (i != (com_argc - 1)) if (i != (com_argc - 1))
svs.maxclients = Q_atoi (com_argv[i+1]); svs.maxclients = std::atoi(com_argv[i.value() + 1]);
else else
svs.maxclients = 8; svs.maxclients = 8;
} }
@@ -232,16 +221,14 @@ void Host_FindMaxClients (void)
deathmatch.set("0"); deathmatch.set("0");
} }
void Host_Version_f (void) void Host_Version_f(void) {
{
Con_Printf("Quake Version %1.2f\n", VERSION); Con_Printf("Quake Version %1.2f\n", VERSION);
Con_Printf("QuakeSpasm Version " QUAKESPASM_VER_STRING "\n"); Con_Printf("QuakeSpasm Version " QUAKESPASM_VER_STRING "\n");
Con_Printf("Exe: " __TIME__ " " __DATE__ "\n"); Con_Printf("Exe: " __TIME__ " " __DATE__ "\n");
} }
/* cvar callback functions : */ /* cvar callback functions : */
void Host_Callback_Notify (convar *var) void Host_Callback_Notify(convar *var) {
{
if (sv.active) if (sv.active)
SV_BroadcastPrintf("\"%s\" changed to \"%s\"\n", var->name.c_str(), var->string); SV_BroadcastPrintf("\"%s\" changed to \"%s\"\n", var->name.c_str(), var->string);
} }
@@ -251,8 +238,7 @@ void Host_Callback_Notify (convar *var)
Host_InitLocal Host_InitLocal
====================== ======================
*/ */
void Host_InitLocal (void) void Host_InitLocal(void) {
{
command::add("version", Host_Version_f); command::add("version", Host_Version_f);
Host_InitCommands(); Host_InitCommands();
@@ -304,17 +290,14 @@ Host_WriteConfiguration
Writes key bindings and archived cvars to config.cfg Writes key bindings and archived cvars to config.cfg
=============== ===============
*/ */
void Host_WriteConfiguration (void) void Host_WriteConfiguration(void) {
{
FILE *f; FILE *f;
// dedicated servers initialize the host but don't parse and set the // dedicated servers initialize the host but don't parse and set the
// config.cfg cvars // config.cfg cvars
if (host_initialized && !isDedicated && !host_parms->errstate) if (host_initialized && !isDedicated && !host_parms->errstate) {
{
f = fopen(va("%s/config.cfg", com_gamedir), "w"); f = fopen(va("%s/config.cfg", com_gamedir), "w");
if (!f) if (!f) {
{
Con_Printf("Couldn't write config.cfg.\n"); Con_Printf("Couldn't write config.cfg.\n");
return; return;
} }
@@ -342,8 +325,7 @@ Sends text across to be displayed
FIXME: make this just a stuffed echo? FIXME: make this just a stuffed echo?
================= =================
*/ */
void SV_ClientPrintf (const char *fmt, ...) void SV_ClientPrintf(const char *fmt, ...) {
{
va_list argptr; va_list argptr;
char string[1024]; char string[1024];
@@ -362,8 +344,7 @@ SV_BroadcastPrintf
Sends text to all active clients Sends text to all active clients
================= =================
*/ */
void SV_BroadcastPrintf (const char *fmt, ...) void SV_BroadcastPrintf(const char *fmt, ...) {
{
va_list argptr; va_list argptr;
char string[1024]; char string[1024];
int i; int i;
@@ -372,10 +353,8 @@ void SV_BroadcastPrintf (const char *fmt, ...)
q_vsnprintf(string, sizeof(string), fmt, argptr); q_vsnprintf(string, sizeof(string), fmt, argptr);
va_end(argptr); va_end(argptr);
for (i = 0; i < svs.maxclients; i++) for (i = 0; i < svs.maxclients; i++) {
{ if (svs.clients[i].active && svs.clients[i].spawned) {
if (svs.clients[i].active && svs.clients[i].spawned)
{
MSG_WriteByte(&svs.clients[i].message, svc_print); MSG_WriteByte(&svs.clients[i].message, svc_print);
MSG_WriteString(&svs.clients[i].message, string); MSG_WriteString(&svs.clients[i].message, string);
} }
@@ -389,8 +368,7 @@ Host_ClientCommands
Send text over to the client to be executed Send text over to the client to be executed
================= =================
*/ */
void Host_ClientCommands (const char *fmt, ...) void Host_ClientCommands(const char *fmt, ...) {
{
va_list argptr; va_list argptr;
char string[1024]; char string[1024];
@@ -410,23 +388,19 @@ Called when the player is getting totally kicked off the host
if (crash = true), don't bother sending signofs if (crash = true), don't bother sending signofs
===================== =====================
*/ */
void SV_DropClient (qboolean crash) void SV_DropClient(bool crash) {
{
int saveSelf; int saveSelf;
int i; int i;
client_t *client; client_t *client;
if (!crash) if (!crash) {
{
// send any final messages (don't check for errors) // send any final messages (don't check for errors)
if (NET_CanSendMessage (host_client->netconnection)) if (NET_CanSendMessage(host_client->netconnection)) {
{
MSG_WriteByte(&host_client->message, svc_disconnect); MSG_WriteByte(&host_client->message, svc_disconnect);
NET_SendMessage(host_client->netconnection, &host_client->message); NET_SendMessage(host_client->netconnection, &host_client->message);
} }
if (host_client->edict && host_client->spawned) if (host_client->edict && host_client->spawned) {
{
// call the prog function for removing a client // call the prog function for removing a client
// this will set the body to a dead frame, among other things // this will set the body to a dead frame, among other things
saveSelf = pr_global_struct->self; saveSelf = pr_global_struct->self;
@@ -449,8 +423,7 @@ void SV_DropClient (qboolean crash)
net_activeconnections--; net_activeconnections--;
// send notification to all clients // send notification to all clients
for (i = 0, client = svs.clients; i < svs.maxclients; i++, client++) for (i = 0, client = svs.clients; i < svs.maxclients; i++, client++) {
{
if (!client->active) if (!client->active)
continue; continue;
MSG_WriteByte(&client->message, svc_updatename); MSG_WriteByte(&client->message, svc_updatename);
@@ -472,8 +445,7 @@ Host_ShutdownServer
This only happens at the end of a game, not between levels This only happens at the end of a game, not between levels
================== ==================
*/ */
void Host_ShutdownServer(qboolean crash) void Host_ShutdownServer(bool crash) {
{
int i; int i;
int count; int count;
sizebuf_t buf; sizebuf_t buf;
@@ -491,20 +463,14 @@ void Host_ShutdownServer(qboolean crash)
// flush any pending messages - like the score!!! // flush any pending messages - like the score!!!
start = Sys_DoubleTime(); start = Sys_DoubleTime();
do do {
{
count = 0; count = 0;
for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++) for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) {
{ if (host_client->active && host_client->message.cursize) {
if (host_client->active && host_client->message.cursize) if (NET_CanSendMessage(host_client->netconnection)) {
{
if (NET_CanSendMessage (host_client->netconnection))
{
NET_SendMessage(host_client->netconnection, &host_client->message); NET_SendMessage(host_client->netconnection, &host_client->message);
SZ_Clear(&host_client->message); SZ_Clear(&host_client->message);
} } else {
else
{
NET_GetMessage(host_client->netconnection); NET_GetMessage(host_client->netconnection);
count++; count++;
} }
@@ -512,8 +478,7 @@ void Host_ShutdownServer(qboolean crash)
} }
if ((Sys_DoubleTime() - start) > 3.0) if ((Sys_DoubleTime() - start) > 3.0)
break; break;
} } while (count);
while (count);
// make sure all the clients know we're disconnecting // make sure all the clients know we're disconnecting
buf.data = message; buf.data = message;
@@ -544,8 +509,7 @@ This clears all the memory used by both the client and server, but does
not reinitialize anything. not reinitialize anything.
================ ================
*/ */
void Host_ClearMemory (void) void Host_ClearMemory(void) {
{
Con_DPrintf("Clearing memory\n"); Con_DPrintf("Clearing memory\n");
D_FlushCaches(); D_FlushCaches();
Mod_ClearAll(); Mod_ClearAll();
@@ -572,14 +536,13 @@ Host_FilterTime
Returns false if the time is too short to run a frame Returns false if the time is too short to run a frame
=================== ===================
*/ */
qboolean Host_FilterTime (float time) bool Host_FilterTime(float time) {
{
float maxfps; //johnfitz float maxfps; //johnfitz
realtime += time; realtime += time;
//johnfitz -- max fps cvar //johnfitz -- max fps cvar
maxfps = CLAMP (10.f, host_maxfps.value, 1000.f); maxfps = std::clamp(host_maxfps.value, 10.f, 1000.f);
if (!cls.timedemo && realtime - oldrealtime < 1.0 / maxfps) if (!cls.timedemo && realtime - oldrealtime < 1.0 / maxfps)
return false; // framerate is too high return false; // framerate is too high
//johnfitz //johnfitz
@@ -594,7 +557,7 @@ qboolean Host_FilterTime (float time)
else if (host_framerate.value > 0) else if (host_framerate.value > 0)
host_frametime = host_framerate.value; host_frametime = host_framerate.value;
else // don't allow really long or short frames else // don't allow really long or short frames
host_frametime = CLAMP (0.001, host_frametime, 0.1); //johnfitz -- use CLAMP host_frametime = std::clamp(host_frametime, 0.001, 0.1); //johnfitz -- use CLAMP
return true; return true;
} }
@@ -606,19 +569,17 @@ Host_GetConsoleCommands
Add them exactly as if they had been typed at the console Add them exactly as if they had been typed at the console
=================== ===================
*/ */
void Host_GetConsoleCommands (void) void Host_GetConsoleCommands(void) {
{
const char *cmd; const char *cmd;
if (!isDedicated) if (!isDedicated)
return; // no stdin necessary in graphical mode return; // no stdin necessary in graphical mode
while (1) while (1) {
{
cmd = Sys_ConsoleInput(); cmd = Sys_ConsoleInput();
if (!cmd) if (!cmd)
break; break;
Cbuf_AddText (cmd); command::buffer::add_text(cmd);
} }
} }
@@ -627,8 +588,7 @@ void Host_GetConsoleCommands (void)
Host_ServerFrame Host_ServerFrame
================== ==================
*/ */
void Host_ServerFrame (void) void Host_ServerFrame(void) {
{
int i, active; //johnfitz int i, active; //johnfitz
edict_t *ent; //johnfitz edict_t *ent; //johnfitz
@@ -650,10 +610,8 @@ void Host_ServerFrame (void)
SV_Physics(); SV_Physics();
//johnfitz -- devstats //johnfitz -- devstats
if (cls.signon == SIGNONS) if (cls.signon == SIGNONS) {
{ for (i = 0, active = 0; i < sv.num_edicts; i++) {
for (i=0, active=0; i<sv.num_edicts; i++)
{
ent = EDICT_NUM(i); ent = EDICT_NUM(i);
if (!ent->free) if (!ent->free)
active++; active++;
@@ -676,8 +634,7 @@ Host_Frame
Runs all active servers Runs all active servers
================== ==================
*/ */
void _Host_Frame (float time) void _Host_Frame(float time) {
{
static double time1 = 0; static double time1 = 0;
static double time2 = 0; static double time2 = 0;
static double time3 = 0; static double time3 = 0;
@@ -702,7 +659,7 @@ void _Host_Frame (float time)
IN_Commands(); IN_Commands();
// process console commands // process console commands
Cbuf_Execute (); command::buffer::execute();
NET_Poll(); NET_Poll();
@@ -749,19 +706,16 @@ void _Host_Frame (float time)
time2 = Sys_DoubleTime(); time2 = Sys_DoubleTime();
// update audio // update audio
BGM_Update(); // adds music raw samples and/or advances midi driver music::update(); // adds music raw samples and/or advances midi driver
if (cls.signon == SIGNONS) if (cls.signon == SIGNONS) {
{
S_Update(r_origin, vpn, vright, vup); S_Update(r_origin, vpn, vright, vup);
CL_DecayLights(); CL_DecayLights();
} } else
else
S_Update(vec3_origin, vec3_origin, vec3_origin, vec3_origin); S_Update(vec3_origin, vec3_origin, vec3_origin, vec3_origin);
CDAudio_Update(); CDAudio_Update();
if (host_speeds.value) if (host_speeds.value) {
{
pass1 = (time1 - time3) * 1000; pass1 = (time1 - time3) * 1000;
time3 = Sys_DoubleTime(); time3 = Sys_DoubleTime();
pass2 = (time2 - time1) * 1000; pass2 = (time2 - time1) * 1000;
@@ -771,18 +725,15 @@ void _Host_Frame (float time)
} }
host_framecount++; host_framecount++;
} }
void Host_Frame (float time) void Host_Frame(float time) {
{
double time1, time2; double time1, time2;
static double timetotal; static double timetotal;
static int timecount; static int timecount;
int i, c, m; int i, c, m;
if (!serverprofile.value) if (!serverprofile.value) {
{
_Host_Frame(time); _Host_Frame(time);
return; return;
} }
@@ -801,8 +752,7 @@ void Host_Frame (float time)
timecount = 0; timecount = 0;
timetotal = 0; timetotal = 0;
c = 0; c = 0;
for (i = 0; i < svs.maxclients; i++) for (i = 0; i < svs.maxclients; i++) {
{
if (svs.clients[i].active) if (svs.clients[i].active)
c++; c++;
} }
@@ -815,13 +765,12 @@ void Host_Frame (float time)
Host_Init Host_Init
==================== ====================
*/ */
void Host_Init (void) void Host_Init(void) {
{
if (standard_quake) if (standard_quake)
minimum_memory = MINIMUM_MEMORY; minimum_memory = MINIMUM_MEMORY;
else minimum_memory = MINIMUM_MEMORY_LEVELPAK; else minimum_memory = MINIMUM_MEMORY_LEVELPAK;
if (COM_CheckParm ("-minmemory")) if (common::check_param("-minmemory").has_value())
host_parms->memsize = minimum_memory; host_parms->memsize = minimum_memory;
if (host_parms->memsize < minimum_memory) if (host_parms->memsize < minimum_memory)
@@ -831,16 +780,15 @@ void Host_Init (void)
com_argv = host_parms->argv; com_argv = host_parms->argv;
Memory_Init(host_parms->membase, host_parms->memsize); Memory_Init(host_parms->membase, host_parms->memsize);
Cbuf_Init (); command::buffer::init();
command::init(); command::init();
LOG_Init(host_parms); LOG_Init(host_parms);
Cvar_Init(); //johnfitz Cvar_Init(); //johnfitz
COM_Init (); common::init();
COM_InitFilesystem(); COM_InitFilesystem();
Host_InitLocal(); Host_InitLocal();
W_LoadWadFile(); //johnfitz -- filename is now hard-coded for honesty W_LoadWadFile(); //johnfitz -- filename is now hard-coded for honesty
if (cls.state != ca_dedicated) if (cls.state != ca_dedicated) {
{
Key_Init(); Key_Init();
Con_Init(); Con_Init();
} }
@@ -852,8 +800,7 @@ void Host_Init (void)
Con_Printf("Exe: " __TIME__ " " __DATE__ "\n"); Con_Printf("Exe: " __TIME__ " " __DATE__ "\n");
Con_Printf("%4.1f megabyte heap\n", host_parms->memsize / (1024 * 1024.0)); Con_Printf("%4.1f megabyte heap\n", host_parms->memsize / (1024 * 1024.0));
if (cls.state != ca_dedicated) if (cls.state != ca_dedicated) {
{
host_colormap = (byte *) COM_LoadHunkFile("gfx/colormap.lmp", NULL); host_colormap = (byte *) COM_LoadHunkFile("gfx/colormap.lmp", NULL);
if (!host_colormap) if (!host_colormap)
Sys_Error("Couldn't load gfx/colormap.lmp"); Sys_Error("Couldn't load gfx/colormap.lmp");
@@ -872,7 +819,7 @@ void Host_Init (void)
R_Init(); R_Init();
S_Init(); S_Init();
CDAudio_Init(); CDAudio_Init();
BGM_Init(); music::init();
Sbar_Init(); Sbar_Init();
CL_Init(); CL_Init();
} }
@@ -885,21 +832,19 @@ void Host_Init (void)
host_initialized = true; host_initialized = true;
Con_Printf("\n========= Quake Initialized =========\n\n"); Con_Printf("\n========= Quake Initialized =========\n\n");
if (cls.state != ca_dedicated) if (cls.state != ca_dedicated) {
{ command::buffer::insert_text("exec quake.rc\n");
Cbuf_InsertText ("exec quake.rc\n");
// johnfitz -- in case the vid mode was locked during vid_init, we can unlock it now. // johnfitz -- in case the vid mode was locked during vid_init, we can unlock it now.
// note: two leading newlines because the command buffer swallows one of them. // note: two leading newlines because the command buffer swallows one of them.
Cbuf_AddText ("\n\nvid_unlock\n"); command::buffer::add_text("\n\nvid_unlock\n");
} }
if (cls.state == ca_dedicated) if (cls.state == ca_dedicated) {
{ command::buffer::add_text("exec autoexec.cfg\n");
Cbuf_AddText ("exec autoexec.cfg\n"); command::buffer::add_text("stuffcmds");
Cbuf_AddText ("stuffcmds"); command::buffer::execute();
Cbuf_Execute ();
if (!sv.active) if (!sv.active)
Cbuf_AddText ("map start\n"); command::buffer::add_text("map start\n");
} }
} }
@@ -912,12 +857,10 @@ FIXME: this is a callback from Sys_Quit and Sys_Error. It would be better
to run quit through here before the final handoff to the sys code. to run quit through here before the final handoff to the sys code.
=============== ===============
*/ */
void Host_Shutdown(void) void Host_Shutdown(void) {
{ static bool isdown = false;
static qboolean isdown = false;
if (isdown) if (isdown) {
{
printf("recursive shutdown\n"); printf("recursive shutdown\n");
return; return;
} }
@@ -930,11 +873,10 @@ void Host_Shutdown(void)
NET_Shutdown(); NET_Shutdown();
if (cls.state != ca_dedicated) if (cls.state != ca_dedicated) {
{
if (con_initialized) if (con_initialized)
History_Shutdown(); History_Shutdown();
BGM_Shutdown(); music::shutdown();
CDAudio_Shutdown(); CDAudio_Shutdown();
S_Shutdown(); S_Shutdown();
IN_Shutdown(); IN_Shutdown();
+246 -483
View File
File diff suppressed because it is too large Load Diff
+49 -89
View File
@@ -31,6 +31,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#define LODEPNG_NO_COMPILE_CPP #define LODEPNG_NO_COMPILE_CPP
#define LODEPNG_NO_COMPILE_ANCILLARY_CHUNKS #define LODEPNG_NO_COMPILE_ANCILLARY_CHUNKS
#define LODEPNG_NO_COMPILE_ERROR_TEXT #define LODEPNG_NO_COMPILE_ERROR_TEXT
#include <cstring>
#include "lodepng.hpp" #include "lodepng.hpp"
#include "lodepng.cpp" #include "lodepng.cpp"
@@ -43,22 +45,18 @@ typedef struct stdio_buffer_s {
int pos; int pos;
} stdio_buffer_t; } stdio_buffer_t;
static stdio_buffer_t *Buf_Alloc(FILE *f) static stdio_buffer_t *Buf_Alloc(FILE *f) {
{
stdio_buffer_t *buf = (stdio_buffer_t *) calloc(1, sizeof(stdio_buffer_t)); stdio_buffer_t *buf = (stdio_buffer_t *) calloc(1, sizeof(stdio_buffer_t));
buf->f = f; buf->f = f;
return buf; return buf;
} }
static void Buf_Free(stdio_buffer_t *buf) static void Buf_Free(stdio_buffer_t *buf) {
{
free(buf); free(buf);
} }
static inline int Buf_GetC(stdio_buffer_t *buf) static inline int Buf_GetC(stdio_buffer_t *buf) {
{ if (buf->pos >= buf->size) {
if (buf->pos >= buf->size)
{
buf->size = fread(buf->buffer, 1, sizeof(buf->buffer), buf->f); buf->size = fread(buf->buffer, 1, sizeof(buf->buffer), buf->f);
buf->pos = 0; buf->pos = 0;
@@ -78,8 +76,7 @@ returns a pointer to hunk allocated RGBA data
TODO: search order: tga png jpg pcx lmp TODO: search order: tga png jpg pcx lmp
============ ============
*/ */
byte *Image_LoadImage (const char *name, int *width, int *height) byte *Image_LoadImage(const char *name, int *width, int *height) {
{
FILE *f; FILE *f;
q_snprintf(loadfilename, sizeof(loadfilename), "%s.tga", name); q_snprintf(loadfilename, sizeof(loadfilename), "%s.tga", name);
@@ -111,8 +108,7 @@ typedef struct targaheader_s {
#define TARGAHEADERSIZE 18 /* size on disk */ #define TARGAHEADERSIZE 18 /* size on disk */
int fgetLittleShort (FILE *f) int fgetLittleShort(FILE *f) {
{
byte b1, b2; byte b1, b2;
b1 = fgetc(f); b1 = fgetc(f);
@@ -121,8 +117,7 @@ int fgetLittleShort (FILE *f)
return (short) (b1 + b2 * 256); return (short) (b1 + b2 * 256);
} }
int fgetLittleLong (FILE *f) int fgetLittleLong(FILE *f) {
{
byte b1, b2, b3, b4; byte b1, b2, b3, b4;
b1 = fgetc(f); b1 = fgetc(f);
@@ -142,8 +137,7 @@ returns true if successful
TODO: support BGRA and BGR formats (since opengl can return them, and we don't have to swap) TODO: support BGRA and BGR formats (since opengl can return them, and we don't have to swap)
============ ============
*/ */
qboolean Image_WriteTGA (const char *name, byte *data, int width, int height, int bpp, qboolean upsidedown) bool Image_WriteTGA(const char *name, byte *data, int width, int height, int bpp, bool upsidedown) {
{
int handle, i, size, temp, bytes; int handle, i, size, temp, bytes;
char pathname[MAX_OSPATH]; char pathname[MAX_OSPATH];
byte header[TARGAHEADERSIZE]; byte header[TARGAHEADERSIZE];
@@ -154,7 +148,7 @@ qboolean Image_WriteTGA (const char *name, byte *data, int width, int height, in
if (handle == -1) if (handle == -1)
return false; return false;
Q_memset (header, 0, TARGAHEADERSIZE); std::memset(header, 0, TARGAHEADERSIZE);
header[2] = 2; // uncompressed type header[2] = 2; // uncompressed type
header[12] = width & 255; header[12] = width & 255;
header[13] = width >> 8; header[13] = width >> 8;
@@ -167,8 +161,7 @@ qboolean Image_WriteTGA (const char *name, byte *data, int width, int height, in
// swap red and blue bytes // swap red and blue bytes
bytes = bpp / 8; bytes = bpp / 8;
size = width * height * bytes; size = width * height * bytes;
for (i=0; i<size; i+=bytes) for (i = 0; i < size; i += bytes) {
{
temp = data[i]; temp = data[i];
data[i] = data[i + 2]; data[i] = data[i + 2];
data[i + 2] = temp; data[i + 2] = temp;
@@ -186,14 +179,13 @@ qboolean Image_WriteTGA (const char *name, byte *data, int width, int height, in
Image_LoadTGA Image_LoadTGA
============= =============
*/ */
byte *Image_LoadTGA (FILE *fin, int *width, int *height) byte *Image_LoadTGA(FILE *fin, int *width, int *height) {
{
int columns, rows, numPixels; int columns, rows, numPixels;
byte *pixbuf; byte *pixbuf;
int row, column; int row, column;
byte *targa_rgba; byte *targa_rgba;
int realrow; //johnfitz -- fix for upside-down targas int realrow; //johnfitz -- fix for upside-down targas
qboolean upside_down; //johnfitz -- fix for upside-down targas bool upside_down; //johnfitz -- fix for upside-down targas
stdio_buffer_t *buf; stdio_buffer_t *buf;
targaheader_t targa_header; targaheader_t targa_header;
@@ -211,13 +203,10 @@ byte *Image_LoadTGA (FILE *fin, int *width, int *height)
targa_header.pixel_size = fgetc(fin); targa_header.pixel_size = fgetc(fin);
targa_header.attributes = fgetc(fin); targa_header.attributes = fgetc(fin);
if (targa_header.image_type==1) if (targa_header.image_type == 1) {
{
if (targa_header.pixel_size != 8 || targa_header.colormap_size != 24 || targa_header.colormap_length > 256) if (targa_header.pixel_size != 8 || targa_header.colormap_size != 24 || targa_header.colormap_length > 256)
Sys_Error("Image_LoadTGA: %s has an %ibit palette", loadfilename, targa_header.colormap_type); Sys_Error("Image_LoadTGA: %s has an %ibit palette", loadfilename, targa_header.colormap_type);
} } else {
else
{
if (targa_header.image_type != 2 && targa_header.image_type != 10) if (targa_header.image_type != 2 && targa_header.image_type != 10)
Sys_Error("Image_LoadTGA: %s is not a type 2 or type 10 targa (%i)", loadfilename, targa_header.image_type); Sys_Error("Image_LoadTGA: %s is not a type 2 or type 10 targa (%i)", loadfilename, targa_header.image_type);
@@ -242,8 +231,8 @@ byte *Image_LoadTGA (FILE *fin, int *width, int *height)
byte palette[256 * 4]; byte palette[256 * 4];
int i; int i;
//palette data comes first //palette data comes first
for (i = 0; i < targa_header.colormap_length; i++) for (i = 0; i < targa_header.colormap_length; i++) {
{ //this palette data is bgr. //this palette data is bgr.
palette[i * 3 + 2] = Buf_GetC(buf); palette[i * 3 + 2] = Buf_GetC(buf);
palette[i * 3 + 1] = Buf_GetC(buf); palette[i * 3 + 1] = Buf_GetC(buf);
palette[i * 3 + 0] = Buf_GetC(buf); palette[i * 3 + 0] = Buf_GetC(buf);
@@ -251,13 +240,11 @@ byte *Image_LoadTGA (FILE *fin, int *width, int *height)
} }
for (i = targa_header.colormap_length * 4; i < sizeof(palette); i++) for (i = targa_header.colormap_length * 4; i < sizeof(palette); i++)
palette[i] = 0; palette[i] = 0;
for(row=rows-1; row>=0; row--) for (row = rows - 1; row >= 0; row--) {
{
realrow = upside_down ? row : rows - 1 - row; realrow = upside_down ? row : rows - 1 - row;
pixbuf = targa_rgba + realrow * columns * 4; pixbuf = targa_rgba + realrow * columns * 4;
for(column=0; column<columns; column++) for (column = 0; column < columns; column++) {
{
i = Buf_GetC(buf); i = Buf_GetC(buf);
*pixbuf++ = palette[i * 3 + 0]; *pixbuf++ = palette[i * 3 + 0];
*pixbuf++ = palette[i * 3 + 1]; *pixbuf++ = palette[i * 3 + 1];
@@ -265,20 +252,16 @@ byte *Image_LoadTGA (FILE *fin, int *width, int *height)
*pixbuf++ = palette[i * 3 + 3]; *pixbuf++ = palette[i * 3 + 3];
} }
} }
} } else if (targa_header.image_type == 2) // Uncompressed, RGB images
else if (targa_header.image_type==2) // Uncompressed, RGB images
{
for(row=rows-1; row>=0; row--)
{ {
for (row = rows - 1; row >= 0; row--) {
//johnfitz -- fix for upside-down targas //johnfitz -- fix for upside-down targas
realrow = upside_down ? row : rows - 1 - row; realrow = upside_down ? row : rows - 1 - row;
pixbuf = targa_rgba + realrow * columns * 4; pixbuf = targa_rgba + realrow * columns * 4;
//johnfitz //johnfitz
for(column=0; column<columns; column++) for (column = 0; column < columns; column++) {
{
unsigned char red, green, blue, alphabyte; unsigned char red, green, blue, alphabyte;
switch (targa_header.pixel_size) switch (targa_header.pixel_size) {
{
case 24: case 24:
blue = Buf_GetC(buf); blue = Buf_GetC(buf);
green = Buf_GetC(buf); green = Buf_GetC(buf);
@@ -301,24 +284,20 @@ byte *Image_LoadTGA (FILE *fin, int *width, int *height)
} }
} }
} }
} } else if (targa_header.image_type == 10) // Runlength encoded RGB images
else if (targa_header.image_type==10) // Runlength encoded RGB images
{ {
unsigned char red, green, blue, alphabyte, packetHeader, packetSize, j; unsigned char red, green, blue, alphabyte, packetHeader, packetSize, j;
for(row=rows-1; row>=0; row--) for (row = rows - 1; row >= 0; row--) {
{
//johnfitz -- fix for upside-down targas //johnfitz -- fix for upside-down targas
realrow = upside_down ? row : rows - 1 - row; realrow = upside_down ? row : rows - 1 - row;
pixbuf = targa_rgba + realrow * columns * 4; pixbuf = targa_rgba + realrow * columns * 4;
//johnfitz //johnfitz
for(column=0; column<columns; ) for (column = 0; column < columns;) {
{
packetHeader = Buf_GetC(buf); packetHeader = Buf_GetC(buf);
packetSize = 1 + (packetHeader & 0x7f); packetSize = 1 + (packetHeader & 0x7f);
if (packetHeader & 0x80) // run-length packet if (packetHeader & 0x80) // run-length packet
{ {
switch (targa_header.pixel_size) switch (targa_header.pixel_size) {
{
case 24: case 24:
blue = Buf_GetC(buf); blue = Buf_GetC(buf);
green = Buf_GetC(buf); green = Buf_GetC(buf);
@@ -335,8 +314,7 @@ byte *Image_LoadTGA (FILE *fin, int *width, int *height)
blue = red = green = alphabyte = 0; blue = red = green = alphabyte = 0;
} }
for(j=0;j<packetSize;j++) for (j = 0; j < packetSize; j++) {
{
*pixbuf++ = red; *pixbuf++ = red;
*pixbuf++ = green; *pixbuf++ = green;
*pixbuf++ = blue; *pixbuf++ = blue;
@@ -355,13 +333,10 @@ byte *Image_LoadTGA (FILE *fin, int *width, int *height)
//johnfitz //johnfitz
} }
} }
} } else // non run-length packet
else // non run-length packet
{
for(j=0;j<packetSize;j++)
{
switch (targa_header.pixel_size)
{ {
for (j = 0; j < packetSize; j++) {
switch (targa_header.pixel_size) {
case 24: case 24:
blue = Buf_GetC(buf); blue = Buf_GetC(buf);
green = Buf_GetC(buf); green = Buf_GetC(buf);
@@ -418,8 +393,7 @@ byte *Image_LoadTGA (FILE *fin, int *width, int *height)
// //
//============================================================================== //==============================================================================
typedef struct typedef struct {
{
char signature; char signature;
char version; char version;
char encoding; char encoding;
@@ -439,15 +413,15 @@ typedef struct
Image_LoadPCX Image_LoadPCX
============ ============
*/ */
byte *Image_LoadPCX (FILE *f, int *width, int *height) byte *Image_LoadPCX(FILE *f, int *width, int *height) {
{
pcxheader_t pcx; pcxheader_t pcx;
int x, y, w, h, readbyte, runlength, start; int x, y, w, h, readbyte, runlength, start;
byte *p, *data; byte *p, *data;
byte palette[768]; byte palette[768];
stdio_buffer_t *buf; stdio_buffer_t *buf;
start = ftell (f); //save start of file (since we might be inside a pak file, SEEK_SET might not be the start of the pcx) start = ftell(f);
//save start of file (since we might be inside a pak file, SEEK_SET might not be the start of the pcx)
if (!fread(&pcx, sizeof(pcx), 1, f)) if (!fread(&pcx, sizeof(pcx), 1, f))
Sys_Error("Failed reading header from '%s'", loadfilename); Sys_Error("Failed reading header from '%s'", loadfilename);
@@ -481,24 +455,20 @@ byte *Image_LoadPCX (FILE *f, int *width, int *height)
buf = Buf_Alloc(f); buf = Buf_Alloc(f);
for (y=0; y<h; y++) for (y = 0; y < h; y++) {
{
p = data + y * w * 4; p = data + y * w * 4;
for (x = 0; x < (pcx.bytes_per_line);) //read the extra padding byte if necessary for (x = 0; x < (pcx.bytes_per_line);) //read the extra padding byte if necessary
{ {
readbyte = Buf_GetC(buf); readbyte = Buf_GetC(buf);
if(readbyte >= 0xC0) if (readbyte >= 0xC0) {
{
runlength = readbyte & 0x3F; runlength = readbyte & 0x3F;
readbyte = Buf_GetC(buf); readbyte = Buf_GetC(buf);
} } else
else
runlength = 1; runlength = 1;
while(runlength--) while (runlength--) {
{
p[0] = palette[readbyte * 3]; p[0] = palette[readbyte * 3];
p[1] = palette[readbyte * 3 + 1]; p[1] = palette[readbyte * 3 + 1];
p[2] = palette[readbyte * 3 + 2]; p[2] = palette[readbyte * 3 + 2];
@@ -523,8 +493,7 @@ byte *Image_LoadPCX (FILE *f, int *width, int *height)
// //
//============================================================================== //==============================================================================
static byte *CopyFlipped(const byte *data, int width, int height, int bpp) static byte *CopyFlipped(const byte *data, int width, int height, int bpp) {
{
int y, rowsize; int y, rowsize;
byte *flipped; byte *flipped;
@@ -533,8 +502,7 @@ static byte *CopyFlipped(const byte *data, int width, int height, int bpp)
if (!flipped) if (!flipped)
return NULL; return NULL;
for (y=0; y<height; y++) for (y = 0; y < height; y++) {
{
memcpy(&flipped[y * rowsize], &data[(height - 1 - y) * rowsize], rowsize); memcpy(&flipped[y * rowsize], &data[(height - 1 - y) * rowsize], rowsize);
} }
return flipped; return flipped;
@@ -547,8 +515,7 @@ Image_WriteJPG -- writes using stb_image_write
returns true if successful returns true if successful
============ ============
*/ */
qboolean Image_WriteJPG (const char *name, byte *data, int width, int height, int bpp, int quality, qboolean upsidedown) bool Image_WriteJPG(const char *name, byte *data, int width, int height, int bpp, int quality, bool upsidedown) {
{
unsigned error; unsigned error;
char pathname[MAX_OSPATH]; char pathname[MAX_OSPATH];
byte *flipped; byte *flipped;
@@ -562,13 +529,11 @@ qboolean Image_WriteJPG (const char *name, byte *data, int width, int height, in
Sys_mkdir(com_gamedir); //if we've switched to a nonexistant gamedir, create it now so we don't crash Sys_mkdir(com_gamedir); //if we've switched to a nonexistant gamedir, create it now so we don't crash
q_snprintf(pathname, sizeof(pathname), "%s/%s", com_gamedir, name); q_snprintf(pathname, sizeof(pathname), "%s/%s", com_gamedir, name);
if (!upsidedown) if (!upsidedown) {
{
flipped = CopyFlipped(data, width, height, bpp); flipped = CopyFlipped(data, width, height, bpp);
if (!flipped) if (!flipped)
return false; return false;
} } else
else
flipped = data; flipped = data;
error = stbi_write_jpg(pathname, width, height, bytes_per_pixel, flipped, quality); error = stbi_write_jpg(pathname, width, height, bytes_per_pixel, flipped, quality);
@@ -578,8 +543,7 @@ qboolean Image_WriteJPG (const char *name, byte *data, int width, int height, in
return (error != 0); return (error != 0);
} }
qboolean Image_WritePNG (const char *name, byte *data, int width, int height, int bpp, qboolean upsidedown) bool Image_WritePNG(const char *name, byte *data, int width, int height, int bpp, bool upsidedown) {
{
unsigned error; unsigned error;
char pathname[MAX_OSPATH]; char pathname[MAX_OSPATH];
byte *flipped; byte *flipped;
@@ -596,8 +560,7 @@ qboolean Image_WritePNG (const char *name, byte *data, int width, int height, in
flipped = (!upsidedown) ? CopyFlipped(data, width, height, bpp) : data; flipped = (!upsidedown) ? CopyFlipped(data, width, height, bpp) : data;
filters = (unsigned char *) malloc(height); filters = (unsigned char *) malloc(height);
if (!filters || !flipped) if (!filters || !flipped) {
{
if (!upsidedown) if (!upsidedown)
free(flipped); free(flipped);
free(filters); free(filters);
@@ -612,13 +575,10 @@ qboolean Image_WritePNG (const char *name, byte *data, int width, int height, in
memset(filters, 1, height); //use filter 1; see https://www.w3.org/TR/PNG-Filters.html memset(filters, 1, height); //use filter 1; see https://www.w3.org/TR/PNG-Filters.html
state.encoder.predefined_filters = filters; state.encoder.predefined_filters = filters;
if (bpp == 24) if (bpp == 24) {
{
state.info_raw.colortype = LCT_RGB; state.info_raw.colortype = LCT_RGB;
state.info_png.color.colortype = LCT_RGB; state.info_png.color.colortype = LCT_RGB;
} } else {
else
{
state.info_raw.colortype = LCT_RGBA; state.info_raw.colortype = LCT_RGBA;
state.info_png.color.colortype = LCT_RGBA; state.info_png.color.colortype = LCT_RGBA;
} }
+3 -3
View File
@@ -30,9 +30,9 @@ byte *Image_LoadTGA (FILE *f, int *width, int *height);
byte *Image_LoadPCX (FILE *f, int *width, int *height); byte *Image_LoadPCX (FILE *f, int *width, int *height);
byte *Image_LoadImage (const char *name, int *width, int *height); byte *Image_LoadImage (const char *name, int *width, int *height);
qboolean Image_WriteTGA (const char *name, byte *data, int width, int height, int bpp, qboolean upsidedown); bool Image_WriteTGA (const char *name, byte *data, int width, int height, int bpp, bool upsidedown);
qboolean Image_WritePNG (const char *name, byte *data, int width, int height, int bpp, qboolean upsidedown); bool Image_WritePNG (const char *name, byte *data, int width, int height, int bpp, bool upsidedown);
qboolean Image_WriteJPG (const char *name, byte *data, int width, int height, int bpp, int quality, qboolean upsidedown); bool Image_WriteJPG (const char *name, byte *data, int width, int height, int bpp, int quality, bool upsidedown);
#endif /* GL_IMAGE_H */ #endif /* GL_IMAGE_H */
+12 -12
View File
@@ -32,8 +32,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#include "SDL.h" #include "SDL.h"
#endif #endif
static qboolean windowhasfocus = true; //just in case sdl fails to tell us... static bool windowhasfocus = true; //just in case sdl fails to tell us...
static qboolean textmode; static bool textmode;
static convar in_debugkeys{"in_debugkeys", "0"}; static convar in_debugkeys{"in_debugkeys", "0"};
@@ -68,7 +68,7 @@ static SDL_JoystickID joy_active_instaceid = -1;
static SDL_GameController *joy_active_controller = NULL; static SDL_GameController *joy_active_controller = NULL;
#endif #endif
static qboolean no_mouse = false; static bool no_mouse = false;
static int buttonremap[] = static int buttonremap[] =
{ {
@@ -231,7 +231,7 @@ void IN_Activate(void) {
total_dy = 0; total_dy = 0;
} }
void IN_Deactivate(qboolean free_cursor) { void IN_Deactivate(bool free_cursor) {
if (no_mouse) if (no_mouse)
return; return;
@@ -331,7 +331,7 @@ void IN_Init(void) {
else else
SDL_StopTextInput(); SDL_StopTextInput();
#endif #endif
if (safemode || COM_CheckParm("-nomouse")) { if (safemode || common::check_param("-nomouse").has_value()) {
no_mouse = true; no_mouse = true;
/* discard all mouse events when input is deactivated */ /* discard all mouse events when input is deactivated */
IN_BeginIgnoringMouseEvents(); IN_BeginIgnoringMouseEvents();
@@ -381,7 +381,7 @@ typedef struct joyaxis_s {
} joyaxis_t; } joyaxis_t;
typedef struct joy_buttonstate_s { typedef struct joy_buttonstate_s {
qboolean buttondown[SDL_CONTROLLER_BUTTON_MAX]; bool buttondown[SDL_CONTROLLER_BUTTON_MAX];
} joybuttonstate_t; } joybuttonstate_t;
typedef struct axisstate_s { typedef struct axisstate_s {
@@ -499,7 +499,7 @@ and generates key repeats if the button is held down.
Adapted from DarkPlaces by lordhavoc Adapted from DarkPlaces by lordhavoc
================ ================
*/ */
static void IN_JoyKeyEvent(qboolean wasdown, qboolean isdown, int key, double *timer) { static void IN_JoyKeyEvent(bool wasdown, bool isdown, int key, double *timer) {
// we can't use `realtime` for key repeats because it is not monotomic // we can't use `realtime` for key repeats because it is not monotomic
const double currenttime = Sys_DoubleTime(); const double currenttime = Sys_DoubleTime();
@@ -544,8 +544,8 @@ void IN_Commands(void) {
// emit key events for controller buttons // emit key events for controller buttons
for (i = 0; i < SDL_CONTROLLER_BUTTON_MAX; i++) { for (i = 0; i < SDL_CONTROLLER_BUTTON_MAX; i++) {
qboolean newstate = SDL_GameControllerGetButton(joy_active_controller, (SDL_GameControllerButton) i); bool newstate = SDL_GameControllerGetButton(joy_active_controller, (SDL_GameControllerButton) i);
qboolean oldstate = joy_buttonstate.buttondown[i]; bool oldstate = joy_buttonstate.buttondown[i];
joy_buttonstate.buttondown[i] = newstate; joy_buttonstate.buttondown[i] = newstate;
@@ -700,7 +700,7 @@ void IN_ClearStates(void) {
} }
void IN_UpdateInputMode(void) { void IN_UpdateInputMode(void) {
qboolean want_textmode = Key_TextEntry(); bool want_textmode = Key_TextEntry();
if (textmode != want_textmode) { if (textmode != want_textmode) {
textmode = want_textmode; textmode = want_textmode;
#if !defined(USE_SDL2) #if !defined(USE_SDL2)
@@ -942,7 +942,7 @@ static void IN_DebugKeyEvent(SDL_Event *event) {
void IN_SendKeyEvents(void) { void IN_SendKeyEvents(void) {
SDL_Event event; SDL_Event event;
int key; int key;
qboolean down; bool down;
while (SDL_PollEvent(&event)) { while (SDL_PollEvent(&event)) {
switch (event.type) { switch (event.type) {
@@ -1012,7 +1012,7 @@ void IN_SendKeyEvents(void) {
case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP: case SDL_MOUSEBUTTONUP:
if (event.button.button < 1 || if (event.button.button < 1 ||
event.button.button > Q_COUNTOF(buttonremap)) { event.button.button > std::size(buttonremap)) {
Con_Printf("Ignored event for mouse button %d\n", Con_Printf("Ignored event for mouse button %d\n",
event.button.button); event.button.button);
break; break;
+1 -1
View File
@@ -51,6 +51,6 @@ void IN_ClearStates (void);
void IN_Activate (void); void IN_Activate (void);
// called when the app becomes inactive // called when the app becomes inactive
void IN_Deactivate (qboolean free_cursor); void IN_Deactivate (bool free_cursor);
#endif #endif
+24 -22
View File
@@ -21,6 +21,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/ */
#include <cstring>
#include "quakedef.hpp" #include "quakedef.hpp"
#include "arch_def.hpp" #include "arch_def.hpp"
@@ -40,9 +42,9 @@ int history_line = 0;
keydest_t key_dest; keydest_t key_dest;
char *keybindings[MAX_KEYS]; char *keybindings[MAX_KEYS];
qboolean consolekeys[MAX_KEYS]; // if true, can't be rebound while in console bool consolekeys[MAX_KEYS]; // if true, can't be rebound while in console
qboolean menubound[MAX_KEYS]; // if true, can't be rebound while in menu bool menubound[MAX_KEYS]; // if true, can't be rebound while in menu
qboolean keydown[MAX_KEYS]; bool keydown[MAX_KEYS];
typedef struct typedef struct
{ {
@@ -250,8 +252,8 @@ void Key_Console (int key)
case K_ENTER: case K_ENTER:
case K_KP_ENTER: case K_KP_ENTER:
key_tabpartial[0] = 0; key_tabpartial[0] = 0;
Cbuf_AddText (workline + 1); // skip the prompt command::buffer::add_text (workline + 1); // skip the prompt
Cbuf_AddText ("\n"); command::buffer::add_text ("\n");
Con_Printf ("%s\n", workline); Con_Printf ("%s\n", workline);
// If the last two lines are identical, skip storing this line in history // If the last two lines are identical, skip storing this line in history
@@ -318,7 +320,7 @@ void Key_Console (int key)
if (x != con_linewidth) if (x != con_linewidth)
break; break;
} }
con_backscroll = CLAMP(0, con_current-i%con_totallines-2, con_totallines-(glheight>>3)-1); con_backscroll = std::clamp(con_current-i%con_totallines-2, 0, con_totallines-(glheight>>3)-1);
} }
else key_linepos = 1; else key_linepos = 1;
return; return;
@@ -372,7 +374,7 @@ void Key_Console (int key)
case K_UPARROW: case K_UPARROW:
if (history_line == edit_line) if (history_line == edit_line)
Q_strcpy(current, workline); std::strcpy(current, workline);
history_line_last = history_line; history_line_last = history_line;
do do
@@ -457,7 +459,7 @@ void Char_Console (int key)
if (key_linepos < MAXCMDLINE-1) if (key_linepos < MAXCMDLINE-1)
{ {
qboolean endpos = !workline[key_linepos]; bool endpos = !workline[key_linepos];
key_tabpartial[0] = 0; //johnfitz key_tabpartial[0] = 0; //johnfitz
// if inserting, move the text to the right // if inserting, move the text to the right
@@ -489,7 +491,7 @@ void Char_Console (int key)
//============================================================================ //============================================================================
qboolean chat_team = false; bool chat_team = false;
static char chat_buffer[MAXCMDLINE]; static char chat_buffer[MAXCMDLINE];
static int chat_bufferlen = 0; static int chat_bufferlen = 0;
@@ -517,11 +519,11 @@ void Key_Message (int key)
case K_ENTER: case K_ENTER:
case K_KP_ENTER: case K_KP_ENTER:
if (chat_team) if (chat_team)
Cbuf_AddText ("say_team \""); command::buffer::add_text ("say_team \"");
else else
Cbuf_AddText ("say \""); command::buffer::add_text ("say \"");
Cbuf_AddText(chat_buffer); command::buffer::add_text(chat_buffer);
Cbuf_AddText("\"\n"); command::buffer::add_text("\"\n");
Key_EndChat (); Key_EndChat ();
return; return;
@@ -898,7 +900,7 @@ void Key_Init (void)
} }
static struct { static struct {
qboolean active; bool active;
int lastkey; int lastkey;
int lastchar; int lastchar;
} key_inputgrab = { false, -1, -1 }; } key_inputgrab = { false, -1, -1 };
@@ -954,7 +956,7 @@ Called by the system between frames for both key up and key down events
Should NOT be called during an interrupt! Should NOT be called during an interrupt!
=================== ===================
*/ */
void Key_Event (int key, qboolean down) void Key_Event (int key, bool down)
{ {
Key_EventWithKeycode (key, down, 0); Key_EventWithKeycode (key, down, 0);
} }
@@ -969,7 +971,7 @@ keycode parameter should have the key's actual keycode using the current keyboar
not necessarily the US-keyboard-based scancode. Pass 0 if not applicable. not necessarily the US-keyboard-based scancode. Pass 0 if not applicable.
=================== ===================
*/ */
void Key_EventWithKeycode (int key, qboolean down, int keycode) void Key_EventWithKeycode (int key, bool down, int keycode)
{ {
char *kb; char *kb;
char cmd[1024]; char cmd[1024];
@@ -1053,7 +1055,7 @@ void Key_EventWithKeycode (int key, qboolean down, int keycode)
if (kb && kb[0] == '+') if (kb && kb[0] == '+')
{ {
sprintf (cmd, "-%s %i\n", kb+1, key); sprintf (cmd, "-%s %i\n", kb+1, key);
Cbuf_AddText (cmd); command::buffer::add_text (cmd);
} }
return; return;
} }
@@ -1076,12 +1078,12 @@ void Key_EventWithKeycode (int key, qboolean down, int keycode)
if (kb[0] == '+') if (kb[0] == '+')
{ // button commands add keynum as a parm { // button commands add keynum as a parm
sprintf (cmd, "%s %i\n", kb, key); sprintf (cmd, "%s %i\n", kb, key);
Cbuf_AddText (cmd); command::buffer::add_text (cmd);
} }
else else
{ {
Cbuf_AddText (kb); command::buffer::add_text (kb);
Cbuf_AddText ("\n"); command::buffer::add_text ("\n");
} }
} }
return; return;
@@ -1158,7 +1160,7 @@ void Char_Event (int key)
Key_TextEntry Key_TextEntry
=================== ===================
*/ */
qboolean Key_TextEntry (void) bool Key_TextEntry (void)
{ {
if (key_inputgrab.active) if (key_inputgrab.active)
{ {
@@ -1208,7 +1210,7 @@ Key_UpdateForDest
*/ */
void Key_UpdateForDest (void) void Key_UpdateForDest (void)
{ {
static qboolean forced = false; static bool forced = false;
if (cls.state == ca_dedicated) if (cls.state == ca_dedicated)
return; return;
+4 -4
View File
@@ -171,7 +171,7 @@ extern int key_linepos;
extern int key_insert; extern int key_insert;
extern double key_blinktime; extern double key_blinktime;
extern qboolean chat_team; extern bool chat_team;
void Key_Init (void); void Key_Init (void);
void Key_ClearStates (void); void Key_ClearStates (void);
@@ -181,10 +181,10 @@ void Key_BeginInputGrab (void);
void Key_EndInputGrab (void); void Key_EndInputGrab (void);
void Key_GetGrabbedInput (int *lastkey, int *lastchar); void Key_GetGrabbedInput (int *lastkey, int *lastchar);
void Key_Event (int key, qboolean down); void Key_Event (int key, bool down);
void Key_EventWithKeycode (int key, qboolean down, int keycode); void Key_EventWithKeycode (int key, bool down, int keycode);
void Char_Event (int key); void Char_Event (int key);
qboolean Key_TextEntry (void); bool Key_TextEntry (void);
void Key_SetBinding (int keynum, const char *binding); void Key_SetBinding (int keynum, const char *binding);
const char *Key_KeynumToString (int keynum); const char *Key_KeynumToString (int keynum);
+15 -30
View File
@@ -33,13 +33,11 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#endif #endif
#include <stdio.h> #include <stdio.h>
static void Sys_AtExit (void) static void Sys_AtExit(void) {
{
SDL_Quit(); SDL_Quit();
} }
static void Sys_InitSDL (void) static void Sys_InitSDL(void) {
{
#if defined(USE_SDL2) #if defined(USE_SDL2)
SDL_version v; SDL_version v;
SDL_version *sdl_version = &v; SDL_version *sdl_version = &v;
@@ -66,9 +64,7 @@ static quakeparms_t parms;
#define main SDL_main #define main SDL_main
#endif #endif
int main(int argc, char *argv[]) int main(int argc, char *argv[]) {
{
int t;
double time, oldtime, newtime; double time, oldtime, newtime;
host_parms = &parms; host_parms = &parms;
@@ -81,7 +77,7 @@ int main(int argc, char *argv[])
COM_InitArgv(parms.argc, parms.argv); COM_InitArgv(parms.argc, parms.argv);
isDedicated = (COM_CheckParm("-dedicated") != 0); isDedicated = (common::check_param("-dedicated").has_value());
Sys_InitSDL(); Sys_InitSDL();
@@ -90,11 +86,9 @@ int main(int argc, char *argv[])
Sys_Printf("Initializing QuakeSpasm v%s\n", QUAKESPASM_VER_STRING); Sys_Printf("Initializing QuakeSpasm v%s\n", QUAKESPASM_VER_STRING);
parms.memsize = DEFAULT_MEMORY; parms.memsize = DEFAULT_MEMORY;
if (COM_CheckParm("-heapsize")) if (common::check_param("-heapsize").has_value()) {
{ if (const auto t = common::check_param("-heapsize").value() + 1; t < com_argc)
t = COM_CheckParm("-heapsize") + 1; parms.memsize = std::atoi(com_argv[t]) * 1024;
if (t < com_argc)
parms.memsize = Q_atoi(com_argv[t]) * 1024;
} }
parms.membase = malloc(parms.memsize); parms.membase = malloc(parms.memsize);
@@ -106,15 +100,12 @@ int main(int argc, char *argv[])
Host_Init(); Host_Init();
oldtime = Sys_DoubleTime(); oldtime = Sys_DoubleTime();
if (isDedicated) if (isDedicated) {
{ while (1) {
while (1)
{
newtime = Sys_DoubleTime(); newtime = Sys_DoubleTime();
time = newtime - oldtime; time = newtime - oldtime;
while (time < sys_ticrate.value ) while (time < sys_ticrate.value) {
{
SDL_Delay(1); SDL_Delay(1);
newtime = Sys_DoubleTime(); newtime = Sys_DoubleTime();
time = newtime - oldtime; time = newtime - oldtime;
@@ -123,23 +114,17 @@ int main(int argc, char *argv[])
Host_Frame(time); Host_Frame(time);
oldtime = newtime; oldtime = newtime;
} }
} } else
else while (1) {
while (1)
{
/* If we have no input focus at all, sleep a bit */ /* If we have no input focus at all, sleep a bit */
if (!VID_HasMouseOrInputFocus() || cl.paused) if (!VID_HasMouseOrInputFocus() || cl.paused) {
{
SDL_Delay(16); SDL_Delay(16);
} }
/* If we're minimised, sleep a bit more */ /* If we're minimised, sleep a bit more */
if (VID_IsMinimized()) if (VID_IsMinimized()) {
{
scr_skipupdate = 1; scr_skipupdate = 1;
SDL_Delay(32); SDL_Delay(32);
} } else {
else
{
scr_skipupdate = 0; scr_skipupdate = 0;
} }
newtime = Sys_DoubleTime(); newtime = Sys_DoubleTime();
+45 -43
View File
@@ -20,6 +20,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/ */
#include <cstring>
#include "quakedef.hpp" #include "quakedef.hpp"
#include "bgmusic.hpp" #include "bgmusic.hpp"
@@ -126,12 +128,12 @@ void M_Help_Key(int key);
void M_Quit_Key(int key); void M_Quit_Key(int key);
qboolean m_entersound; // play after drawing a frame, so caching bool m_entersound; // play after drawing a frame, so caching
// won't disrupt the sound // won't disrupt the sound
qboolean m_recursiveDraw; bool m_recursiveDraw;
enum m_state_e m_return_state; enum m_state_e m_return_state;
qboolean m_return_onerror; bool m_return_onerror;
char m_return_reason[32]; char m_return_reason[32];
#define StartingGame (m_multiplayer_cursor == 1) #define StartingGame (m_multiplayer_cursor == 1)
@@ -413,11 +415,11 @@ void M_SinglePlayer_Key(int key) {
IN_Activate(); IN_Activate();
key_dest = key_game; key_dest = key_game;
if (sv.active) if (sv.active)
Cbuf_AddText("disconnect\n"); command::buffer::add_text("disconnect\n");
Cbuf_AddText("maxplayers 1\n"); command::buffer::add_text("maxplayers 1\n");
Cbuf_AddText("deathmatch 0\n"); //johnfitz command::buffer::add_text("deathmatch 0\n"); //johnfitz
Cbuf_AddText("coop 0\n"); //johnfitz command::buffer::add_text("coop 0\n"); //johnfitz
Cbuf_AddText("map start\n"); command::buffer::add_text("map start\n");
break; break;
case 1: case 1:
@@ -548,7 +550,7 @@ void M_Load_Key(int k) {
SCR_BeginLoadingPlaque(); SCR_BeginLoadingPlaque();
// issue the load command // issue the load command
Cbuf_AddText(va("load s%i\n", load_cursor)); command::buffer::add_text(va("load s%i\n", load_cursor));
return; return;
case K_UPARROW: case K_UPARROW:
@@ -583,7 +585,7 @@ void M_Save_Key(int k) {
m_state = m_none; m_state = m_none;
IN_Activate(); IN_Activate();
key_dest = key_game; key_dest = key_game;
Cbuf_AddText(va("save s%i\n", load_cursor)); command::buffer::add_text(va("save s%i\n", load_cursor));
return; return;
case K_UPARROW: case K_UPARROW:
@@ -699,8 +701,8 @@ void M_Menu_Setup_f(void) {
key_dest = key_menu; key_dest = key_menu;
m_state = m_setup; m_state = m_setup;
m_entersound = true; m_entersound = true;
Q_strcpy(setup_myname, cl_name.string); std::strcpy(setup_myname, cl_name.string);
Q_strcpy(setup_hostname, hostname.string); std::strcpy(setup_hostname, hostname.string);
setup_top = setup_oldtop = ((int) cl_color.value) >> 4; setup_top = setup_oldtop = ((int) cl_color.value) >> 4;
setup_bottom = setup_oldbottom = ((int) cl_color.value) & 15; setup_bottom = setup_oldbottom = ((int) cl_color.value) & 15;
} }
@@ -795,12 +797,12 @@ void M_Setup_Key(int k) {
goto forward; goto forward;
// setup_cursor == 4 (OK) // setup_cursor == 4 (OK)
if (Q_strcmp(cl_name.string, setup_myname) != 0) if (std::strcmp(cl_name.string, setup_myname) != 0)
Cbuf_AddText(va("name \"%s\"\n", setup_myname)); command::buffer::add_text(va("name \"%s\"\n", setup_myname));
if (Q_strcmp(hostname.string, setup_hostname) != 0) if (std::strcmp(hostname.string, setup_hostname) != 0)
convar::set("hostname", setup_hostname); convar::set("hostname", setup_hostname);
if (setup_top != setup_oldtop || setup_bottom != setup_oldbottom) if (setup_top != setup_oldtop || setup_bottom != setup_oldbottom)
Cbuf_AddText(va("color %i %i\n", setup_top, setup_bottom)); command::buffer::add_text(va("color %i %i\n", setup_top, setup_bottom));
m_entersound = true; m_entersound = true;
M_Menu_MultiPlayer_f(); M_Menu_MultiPlayer_f();
break; break;
@@ -851,7 +853,7 @@ void M_Setup_Char(int k) {
} }
qboolean M_Setup_TextEntry(void) { bool M_Setup_TextEntry(void) {
return (setup_cursor == 0 || setup_cursor == 1); return (setup_cursor == 0 || setup_cursor == 1);
} }
@@ -1059,7 +1061,7 @@ void M_AdjustSliders(int dir) {
convar::set_value("bgmvolume", f); convar::set_value("bgmvolume", f);
break; break;
case OPT_MUSICEXT: // enable external music vs cdaudio case OPT_MUSICEXT: // enable external music vs cdaudio
convar::set("bgm_extmusic", bgm_extmusic.value ? "0" : "1"); convar::set("bgm_extmusic", music::bgm_extmusic.value ? "0" : "1");
break; break;
case OPT_SNDVOL: // sfx volume case OPT_SNDVOL: // sfx volume
f = sfxvolume.value + dir * 0.1; f = sfxvolume.value + dir * 0.1;
@@ -1100,9 +1102,9 @@ void M_AdjustSliders(int dir) {
case OPT_ALWAYSMLOOK: case OPT_ALWAYSMLOOK:
if (in_mlook.state & 1) if (in_mlook.state & 1)
Cbuf_AddText("-mlook"); command::buffer::add_text("-mlook");
else else
Cbuf_AddText("+mlook"); command::buffer::add_text("+mlook");
break; break;
case OPT_LOOKSPRING: // lookspring case OPT_LOOKSPRING: // lookspring
@@ -1205,7 +1207,7 @@ void M_Options_Draw(void) {
// OPT_MUSICEXT: // OPT_MUSICEXT:
M_Print(16, 32 + 8 * OPT_MUSICEXT, " External Music"); M_Print(16, 32 + 8 * OPT_MUSICEXT, " External Music");
M_DrawCheckbox(220, 32 + 8 * OPT_MUSICEXT, bgm_extmusic.value); M_DrawCheckbox(220, 32 + 8 * OPT_MUSICEXT, music::bgm_extmusic.value);
// OPT_ALWAYRUN: // OPT_ALWAYRUN:
M_Print(16, 32 + 8 * OPT_ALWAYRUN, " Always Run"); M_Print(16, 32 + 8 * OPT_ALWAYRUN, " Always Run");
@@ -1263,8 +1265,8 @@ void M_Options_Key(int k) {
case OPT_DEFAULTS: case OPT_DEFAULTS:
if (SCR_ModalMessage("This will reset all controls\n" if (SCR_ModalMessage("This will reset all controls\n"
"and stored cvars. Continue? (y/n)\n", 15.0f)) { "and stored cvars. Continue? (y/n)\n", 15.0f)) {
Cbuf_AddText("resetcfg\n"); command::buffer::add_text("resetcfg\n");
Cbuf_AddText("exec default.cfg\n"); command::buffer::add_text("exec default.cfg\n");
} }
break; break;
case OPT_VIDEO: case OPT_VIDEO:
@@ -1333,10 +1335,10 @@ const char *bindnames[][2] =
{"+movedown", "swim down"} {"+movedown", "swim down"}
}; };
#define NUMCOMMANDS Q_COUNTOF(bindnames) #define NUMCOMMANDS std::size(bindnames)
static int keys_cursor; static int keys_cursor;
static qboolean bind_grab; static bool bind_grab;
void M_Menu_Keys_f(void) { void M_Menu_Keys_f(void) {
IN_Deactivate(modestate == MS_WINDOWED); IN_Deactivate(modestate == MS_WINDOWED);
@@ -1444,7 +1446,7 @@ void M_Keys_Key(int k) {
S_LocalSound("misc/menu1.wav"); S_LocalSound("misc/menu1.wav");
if ((k != K_ESCAPE) && (k != '`')) { if ((k != K_ESCAPE) && (k != '`')) {
sprintf(cmd, "bind \"%s\" \"%s\"\n", Key_KeynumToString(k), bindnames[keys_cursor][0]); sprintf(cmd, "bind \"%s\" \"%s\"\n", Key_KeynumToString(k), bindnames[keys_cursor][0]);
Cbuf_InsertText(cmd); command::buffer::insert_text(cmd);
} }
bind_grab = false; bind_grab = false;
@@ -1559,7 +1561,7 @@ void M_Help_Key(int key) {
int msgNumber; int msgNumber;
enum m_state_e m_quit_prevstate; enum m_state_e m_quit_prevstate;
qboolean wasInMenus; bool wasInMenus;
void M_Menu_Quit_f(void) { void M_Menu_Quit_f(void) {
if (m_state == m_quit) if (m_state == m_quit)
@@ -1615,7 +1617,7 @@ void M_Quit_Char(int key) {
} }
qboolean M_Quit_TextEntry(void) { bool M_Quit_TextEntry(void) {
return true; return true;
} }
@@ -1785,7 +1787,7 @@ void M_LanConfig_Key(int key) {
IN_Activate(); IN_Activate();
key_dest = key_game; key_dest = key_game;
m_state = m_none; m_state = m_none;
Cbuf_AddText(va("connect \"%s\"\n", lanConfig_joinname)); command::buffer::add_text(va("connect \"%s\"\n", lanConfig_joinname));
break; break;
} }
@@ -1811,7 +1813,7 @@ void M_LanConfig_Key(int key) {
lanConfig_cursor = 0; lanConfig_cursor = 0;
} }
l = Q_atoi(lanConfig_portname); l = std::atoi(lanConfig_portname);
if (l > 65535) if (l > 65535)
l = lanConfig_port; l = lanConfig_port;
else else
@@ -1844,7 +1846,7 @@ void M_LanConfig_Char(int key) {
} }
qboolean M_LanConfig_TextEntry(void) { bool M_LanConfig_TextEntry(void) {
return (lanConfig_cursor == 0 || lanConfig_cursor == 2); return (lanConfig_cursor == 0 || lanConfig_cursor == 2);
} }
@@ -1996,7 +1998,7 @@ episode_t rogueepisodes[] =
int startepisode; int startepisode;
int startlevel; int startlevel;
int maxplayers; int maxplayers;
qboolean m_serverInfoMessage = false; bool m_serverInfoMessage = false;
double m_serverInfoMessageTime; double m_serverInfoMessageTime;
void M_Menu_GameOptions_f(void) { void M_Menu_GameOptions_f(void) {
@@ -2269,18 +2271,18 @@ void M_GameOptions_Key(int key) {
S_LocalSound("misc/menu2.wav"); S_LocalSound("misc/menu2.wav");
if (gameoptions_cursor == 0) { if (gameoptions_cursor == 0) {
if (sv.active) if (sv.active)
Cbuf_AddText("disconnect\n"); command::buffer::add_text("disconnect\n");
Cbuf_AddText("listen 0\n"); // so host_netport will be re-examined command::buffer::add_text("listen 0\n"); // so host_netport will be re-examined
Cbuf_AddText(va("maxplayers %u\n", maxplayers)); command::buffer::add_text(va("maxplayers %u\n", maxplayers));
SCR_BeginLoadingPlaque(); SCR_BeginLoadingPlaque();
if (hipnotic) if (hipnotic)
Cbuf_AddText(va( command::buffer::add_text(va(
"map %s\n", hipnoticlevels[hipnoticepisodes[startepisode].firstLevel + startlevel].name)); "map %s\n", hipnoticlevels[hipnoticepisodes[startepisode].firstLevel + startlevel].name));
else if (rogue) else if (rogue)
Cbuf_AddText(va("map %s\n", roguelevels[rogueepisodes[startepisode].firstLevel + startlevel].name)); command::buffer::add_text(va("map %s\n", roguelevels[rogueepisodes[startepisode].firstLevel + startlevel].name));
else else
Cbuf_AddText(va("map %s\n", levels[episodes[startepisode].firstLevel + startlevel].name)); command::buffer::add_text(va("map %s\n", levels[episodes[startepisode].firstLevel + startlevel].name));
return; return;
} }
@@ -2293,7 +2295,7 @@ void M_GameOptions_Key(int key) {
//============================================================================= //=============================================================================
/* SEARCH MENU */ /* SEARCH MENU */
qboolean searchComplete = false; bool searchComplete = false;
double searchCompleteTime; double searchCompleteTime;
void M_Menu_Search_f(void) { void M_Menu_Search_f(void) {
@@ -2348,7 +2350,7 @@ void M_Search_Key(int key) {
/* SLIST MENU */ /* SLIST MENU */
int slist_cursor; int slist_cursor;
qboolean slist_sorted; bool slist_sorted;
void M_Menu_ServerList_f(void) { void M_Menu_ServerList_f(void) {
IN_Deactivate(modestate == MS_WINDOWED); IN_Deactivate(modestate == MS_WINDOWED);
@@ -2419,7 +2421,7 @@ void M_ServerList_Key(int k) {
IN_Activate(); IN_Activate();
key_dest = key_game; key_dest = key_game;
m_state = m_none; m_state = m_none;
Cbuf_AddText(va("connect \"%s\"\n", NET_SlistPrintServerName(slist_cursor))); command::buffer::add_text(va("connect \"%s\"\n", NET_SlistPrintServerName(slist_cursor)));
break; break;
default: default:
@@ -2643,7 +2645,7 @@ void M_Charinput(int key) {
} }
qboolean M_TextEntry(void) { bool M_TextEntry(void) {
switch (m_state) { switch (m_state) {
case m_setup: case m_setup:
return M_Setup_TextEntry(); return M_Setup_TextEntry();
@@ -2659,7 +2661,7 @@ qboolean M_TextEntry(void) {
void M_ConfigureNetSubsystem(void) { void M_ConfigureNetSubsystem(void) {
// enable/disable net systems to match desired config // enable/disable net systems to match desired config
Cbuf_AddText("stopdemo\n"); command::buffer::add_text("stopdemo\n");
if (IPXConfig || TCPIPConfig) if (IPXConfig || TCPIPConfig)
net_hostport = lanConfig_port; net_hostport = lanConfig_port;
+2 -2
View File
@@ -46,7 +46,7 @@ enum m_state_e {
extern enum m_state_e m_state; extern enum m_state_e m_state;
extern enum m_state_e m_return_state; extern enum m_state_e m_return_state;
extern qboolean m_entersound; extern bool m_entersound;
// //
// menus // menus
@@ -54,7 +54,7 @@ extern qboolean m_entersound;
void M_Init (void); void M_Init (void);
void M_Keydown (int key); void M_Keydown (int key);
void M_Charinput (int key); void M_Charinput (int key);
qboolean M_TextEntry (void); bool M_TextEntry (void);
void M_ToggleMenu_f (void); void M_ToggleMenu_f (void);
void M_Menu_Main_f (void); void M_Menu_Main_f (void);
+6 -6
View File
@@ -58,7 +58,7 @@ struct qsocket_s *NET_Connect (const char *host);
double NET_QSocketGetTime (const struct qsocket_s *sock); double NET_QSocketGetTime (const struct qsocket_s *sock);
const char *NET_QSocketGetAddressString (const struct qsocket_s *sock); const char *NET_QSocketGetAddressString (const struct qsocket_s *sock);
qboolean NET_CanSendMessage (struct qsocket_s *sock); bool NET_CanSendMessage (struct qsocket_s *sock);
// Returns true or false if the given qsocket can currently accept a // Returns true or false if the given qsocket can currently accept a
// message to be transmitted. // message to be transmitted.
@@ -92,9 +92,9 @@ void NET_Poll (void);
// Server list related globals: // Server list related globals:
extern qboolean slistInProgress; extern bool slistInProgress;
extern qboolean slistSilent; extern bool slistSilent;
extern qboolean slistLocal; extern bool slistLocal;
extern int hostCacheCount; extern int hostCacheCount;
@@ -106,8 +106,8 @@ const char *NET_SlistPrintServerName (int n);
/* FIXME: driver related, but public: /* FIXME: driver related, but public:
*/ */
extern qboolean ipxAvailable; extern bool ipxAvailable;
extern qboolean tcpipAvailable; extern bool tcpipAvailable;
extern char my_ipx_address[NET_NAMELEN]; extern char my_ipx_address[NET_NAMELEN];
extern char my_tcpip_address[NET_NAMELEN]; extern char my_tcpip_address[NET_NAMELEN];
+2 -2
View File
@@ -63,7 +63,7 @@ net_driver_t net_drivers[] =
} }
}; };
const int net_numdrivers = Q_COUNTOF(net_drivers); const int net_numdrivers = std::size(net_drivers);
#include "net_udp.hpp" #include "net_udp.hpp"
@@ -93,4 +93,4 @@ net_landriver_t net_landrivers[] =
} }
}; };
const int net_numlandrivers = Q_COUNTOF(net_landrivers); const int net_numlandrivers = std::size(net_landrivers);
+10 -10
View File
@@ -134,9 +134,9 @@ typedef struct qsocket_s
double lastMessageTime; double lastMessageTime;
double lastSendTime; double lastSendTime;
qboolean disconnected; bool disconnected;
qboolean canSend; bool canSend;
qboolean sendNext; bool sendNext;
int driver; int driver;
int landriver; int landriver;
@@ -166,11 +166,11 @@ extern int net_numsockets;
typedef struct typedef struct
{ {
const char *name; const char *name;
qboolean initialized; bool initialized;
sys_socket_t controlSock; sys_socket_t controlSock;
sys_socket_t (*Init) (void); sys_socket_t (*Init) (void);
void (*Shutdown) (void); void (*Shutdown) (void);
void (*Listen) (qboolean state); void (*Listen) (bool state);
sys_socket_t (*Open_Socket) (int port); sys_socket_t (*Open_Socket) (int port);
int (*Close_Socket) (sys_socket_t socketid); int (*Close_Socket) (sys_socket_t socketid);
int (*Connect) (sys_socket_t socketid, struct qsockaddr *addr); int (*Connect) (sys_socket_t socketid, struct qsockaddr *addr);
@@ -195,17 +195,17 @@ extern const int net_numlandrivers;
typedef struct typedef struct
{ {
const char *name; const char *name;
qboolean initialized; bool initialized;
int (*Init) (void); int (*Init) (void);
void (*Listen) (qboolean state); void (*Listen) (bool state);
void (*SearchForHosts) (qboolean xmit); void (*SearchForHosts) (bool xmit);
qsocket_t *(*Connect) (const char *host); qsocket_t *(*Connect) (const char *host);
qsocket_t *(*CheckNewConnections) (void); qsocket_t *(*CheckNewConnections) (void);
int (*QGetMessage) (qsocket_t *sock); int (*QGetMessage) (qsocket_t *sock);
int (*QSendMessage) (qsocket_t *sock, sizebuf_t *data); int (*QSendMessage) (qsocket_t *sock, sizebuf_t *data);
int (*SendUnreliableMessage) (qsocket_t *sock, sizebuf_t *data); int (*SendUnreliableMessage) (qsocket_t *sock, sizebuf_t *data);
qboolean (*CanSendMessage) (qsocket_t *sock); bool (*CanSendMessage) (qsocket_t *sock);
qboolean (*CanSendUnreliableMessage) (qsocket_t *sock); bool (*CanSendUnreliableMessage) (qsocket_t *sock);
void (*Close) (qsocket_t *sock); void (*Close) (qsocket_t *sock);
void (*Shutdown) (void); void (*Shutdown) (void);
} net_driver_t; } net_driver_t;
+44 -42
View File
@@ -29,6 +29,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#include "net_defs.hpp" #include "net_defs.hpp"
#include "net_dgrm.hpp" #include "net_dgrm.hpp"
#include <cstring>
// these two macros are to make the code more readable // these two macros are to make the code more readable
#define sfunc net_landrivers[sock->landriver] #define sfunc net_landrivers[sock->landriver]
#define dfunc net_landrivers[net_landriverlevel] #define dfunc net_landrivers[net_landriverlevel]
@@ -51,7 +53,7 @@ static struct {
static int myDriverLevel; static int myDriverLevel;
extern qboolean m_return_onerror; extern bool m_return_onerror;
extern char m_return_reason[32]; extern char m_return_reason[32];
@@ -91,8 +93,8 @@ static void NET_Ban_f(void) {
switch (command::argc()) { switch (command::argc()) {
case 1: case 1:
if (banAddr.s_addr != INADDR_ANY) { if (banAddr.s_addr != INADDR_ANY) {
Q_strcpy(addrStr, inet_ntoa(banAddr)); std::strcpy(addrStr, inet_ntoa(banAddr));
Q_strcpy(maskStr, inet_ntoa(banMask)); std::strcpy(maskStr, inet_ntoa(banMask));
print_fn("Banning %s [%s]\n", addrStr, maskStr); print_fn("Banning %s [%s]\n", addrStr, maskStr);
} else } else
print_fn("Banning not active\n"); print_fn("Banning not active\n");
@@ -135,7 +137,7 @@ int Datagram_SendMessage(qsocket_t *sock, sizebuf_t *data) {
Sys_Error("SendMessage: called with canSend == false"); Sys_Error("SendMessage: called with canSend == false");
#endif #endif
Q_memcpy(sock->sendMessage, data->data, data->cursize); std::memcpy(sock->sendMessage, data->data, data->cursize);
sock->sendMessageLength = data->cursize; sock->sendMessageLength = data->cursize;
if (data->cursize <= MAX_DATAGRAM) { if (data->cursize <= MAX_DATAGRAM) {
@@ -149,7 +151,7 @@ int Datagram_SendMessage(qsocket_t *sock, sizebuf_t *data) {
packetBuffer.length = BigLong(packetLen | (NETFLAG_DATA | eom)); packetBuffer.length = BigLong(packetLen | (NETFLAG_DATA | eom));
packetBuffer.sequence = BigLong(sock->sendSequence++); packetBuffer.sequence = BigLong(sock->sendSequence++);
Q_memcpy(packetBuffer.data, sock->sendMessage, dataLen); std::memcpy(packetBuffer.data, sock->sendMessage, dataLen);
sock->canSend = false; sock->canSend = false;
@@ -178,7 +180,7 @@ static int SendMessageNext(qsocket_t *sock) {
packetBuffer.length = BigLong(packetLen | (NETFLAG_DATA | eom)); packetBuffer.length = BigLong(packetLen | (NETFLAG_DATA | eom));
packetBuffer.sequence = BigLong(sock->sendSequence++); packetBuffer.sequence = BigLong(sock->sendSequence++);
Q_memcpy(packetBuffer.data, sock->sendMessage, dataLen); std::memcpy(packetBuffer.data, sock->sendMessage, dataLen);
sock->sendNext = false; sock->sendNext = false;
@@ -207,7 +209,7 @@ static int ReSendMessage(qsocket_t *sock) {
packetBuffer.length = BigLong(packetLen | (NETFLAG_DATA | eom)); packetBuffer.length = BigLong(packetLen | (NETFLAG_DATA | eom));
packetBuffer.sequence = BigLong(sock->sendSequence - 1); packetBuffer.sequence = BigLong(sock->sendSequence - 1);
Q_memcpy(packetBuffer.data, sock->sendMessage, dataLen); std::memcpy(packetBuffer.data, sock->sendMessage, dataLen);
sock->sendNext = false; sock->sendNext = false;
@@ -220,7 +222,7 @@ static int ReSendMessage(qsocket_t *sock) {
} }
qboolean Datagram_CanSendMessage(qsocket_t *sock) { bool Datagram_CanSendMessage(qsocket_t *sock) {
if (sock->sendNext) if (sock->sendNext)
SendMessageNext(sock); SendMessageNext(sock);
@@ -228,7 +230,7 @@ qboolean Datagram_CanSendMessage(qsocket_t *sock) {
} }
qboolean Datagram_CanSendUnreliableMessage(qsocket_t *sock) { bool Datagram_CanSendUnreliableMessage(qsocket_t *sock) {
return true; return true;
} }
@@ -248,7 +250,7 @@ int Datagram_SendUnreliableMessage(qsocket_t *sock, sizebuf_t *data) {
packetBuffer.length = BigLong(packetLen | NETFLAG_UNRELIABLE); packetBuffer.length = BigLong(packetLen | NETFLAG_UNRELIABLE);
packetBuffer.sequence = BigLong(sock->unreliableSendSequence++); packetBuffer.sequence = BigLong(sock->unreliableSendSequence++);
Q_memcpy(packetBuffer.data, data->data, data->cursize); std::memcpy(packetBuffer.data, data->data, data->cursize);
if (sfunc.Write(sock->socket, (byte *) &packetBuffer, packetLen, &sock->addr) == -1) if (sfunc.Write(sock->socket, (byte *) &packetBuffer, packetLen, &sock->addr) == -1)
return -1; return -1;
@@ -376,7 +378,7 @@ int Datagram_GetMessage(qsocket_t *sock) {
break; break;
} }
Q_memcpy(sock->receiveMessage + sock->receiveMessageLength, packetBuffer.data, length); std::memcpy(sock->receiveMessage + sock->receiveMessageLength, packetBuffer.data, length);
sock->receiveMessageLength += length; sock->receiveMessageLength += length;
continue; continue;
} }
@@ -410,7 +412,7 @@ static void NET_Stats_f(void) {
Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount); Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
Con_Printf("shortPacketCount = %i\n", shortPacketCount); Con_Printf("shortPacketCount = %i\n", shortPacketCount);
Con_Printf("droppedDatagrams = %i\n", droppedDatagrams); Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
} else if (Q_strcmp(command::argv(1)->c_str(), "*") == 0) { } else if (std::strcmp(command::argv(1)->c_str(), "*") == 0) {
for (s = net_activeSockets; s; s = s->next) for (s = net_activeSockets; s; s = s->next)
PrintStats(s); PrintStats(s);
for (s = net_freeSockets; s; s = s->next) for (s = net_freeSockets; s; s = s->next)
@@ -446,10 +448,10 @@ static const char *Strip_Port(const char *host) {
if (!host || !*host) if (!host || !*host)
return host; return host;
q_strlcpy(noport, host, sizeof(noport)); q_strlcpy(noport, host, sizeof(noport));
if ((p = Q_strrchr(noport, ':')) == NULL) if ((p = std::strrchr(noport, ':')) == NULL)
return host; return host;
*p++ = '\0'; *p++ = '\0';
port = Q_atoi(p); port = std::atoi(p);
if (port > 0 && port < 65536 && port != net_hostport) { if (port > 0 && port < 65536 && port != net_hostport) {
net_hostport = port; net_hostport = port;
Con_Printf("Port set to %d\n", net_hostport); Con_Printf("Port set to %d\n", net_hostport);
@@ -458,7 +460,7 @@ static const char *Strip_Port(const char *host) {
} }
static qboolean testInProgress = false; static bool testInProgress = false;
static int testPollCount; static int testPollCount;
static int testDriver; static int testDriver;
static sys_socket_t testSocket; static sys_socket_t testSocket;
@@ -500,11 +502,11 @@ static void Test_Poll(void *unused) {
Sys_Error("Unexpected response to Player Info request\n"); Sys_Error("Unexpected response to Player Info request\n");
MSG_ReadByte(); /* playerNumber */ MSG_ReadByte(); /* playerNumber */
Q_strcpy(name, MSG_ReadString()); std::strcpy(name, MSG_ReadString());
colors = MSG_ReadLong(); colors = MSG_ReadLong();
frags = MSG_ReadLong(); frags = MSG_ReadLong();
connectTime = MSG_ReadLong(); connectTime = MSG_ReadLong();
Q_strcpy(address, MSG_ReadString()); std::strcpy(address, MSG_ReadString());
Con_Printf("%s\n frags:%3i colors:%d %d time:%d\n %s\n", name, frags, colors >> 4, colors & 0x0f, Con_Printf("%s\n frags:%3i colors:%d %d time:%d\n %s\n", name, frags, colors >> 4, colors & 0x0f,
connectTime / 60, address); connectTime / 60, address);
@@ -537,7 +539,7 @@ static void Test_f(void) {
continue; continue;
net_landriverlevel = hostcache[n].ldriver; net_landriverlevel = hostcache[n].ldriver;
maxusers = hostcache[n].maxusers; maxusers = hostcache[n].maxusers;
Q_memcpy(&sendaddr, &hostcache[n].addr, sizeof(struct qsockaddr)); std::memcpy(&sendaddr, &hostcache[n].addr, sizeof(struct qsockaddr));
break; break;
} }
} }
@@ -583,7 +585,7 @@ JustDoIt:
} }
static qboolean test2InProgress = false; static bool test2InProgress = false;
static int test2Driver; static int test2Driver;
static sys_socket_t test2Socket; static sys_socket_t test2Socket;
@@ -620,10 +622,10 @@ static void Test2_Poll(void *unused) {
if (MSG_ReadByte() != CCREP_RULE_INFO) if (MSG_ReadByte() != CCREP_RULE_INFO)
goto Error; goto Error;
Q_strcpy(name, MSG_ReadString()); std::strcpy(name, MSG_ReadString());
if (name[0] == 0) if (name[0] == 0)
goto Done; goto Done;
Q_strcpy(value, MSG_ReadString()); std::strcpy(value, MSG_ReadString());
Con_Printf("%-16.16s %-16.16s\n", name, value); Con_Printf("%-16.16s %-16.16s\n", name, value);
@@ -664,7 +666,7 @@ static void Test2_f(void) {
if (hostcache[n].driver != myDriverLevel) if (hostcache[n].driver != myDriverLevel)
continue; continue;
net_landriverlevel = hostcache[n].ldriver; net_landriverlevel = hostcache[n].ldriver;
Q_memcpy(&sendaddr, &hostcache[n].addr, sizeof(struct qsockaddr)); std::memcpy(&sendaddr, &hostcache[n].addr, sizeof(struct qsockaddr));
break; break;
} }
} }
@@ -719,7 +721,7 @@ int Datagram_Init(void) {
command::add("net_stats", NET_Stats_f); command::add("net_stats", NET_Stats_f);
if (safemode || COM_CheckParm("-nolan")) if (safemode || common::check_param("-nolan").has_value())
return -1; return -1;
num_inited = 0; num_inited = 0;
@@ -765,7 +767,7 @@ void Datagram_Close(qsocket_t *sock) {
} }
void Datagram_Listen(qboolean state) { void Datagram_Listen(bool state) {
int i; int i;
for (i = 0; i < net_numlandrivers; i++) { for (i = 0; i < net_numlandrivers; i++) {
@@ -810,7 +812,7 @@ static qsocket_t *_Datagram_CheckNewConnections(void) {
command = MSG_ReadByte(); command = MSG_ReadByte();
if (command == CCREQ_SERVER_INFO) { if (command == CCREQ_SERVER_INFO) {
if (Q_strcmp(MSG_ReadString(), "QUAKE") != 0) if (std::strcmp(MSG_ReadString(), "QUAKE") != 0)
return NULL; return NULL;
SZ_Clear(&net_message); SZ_Clear(&net_message);
@@ -893,7 +895,7 @@ static qsocket_t *_Datagram_CheckNewConnections(void) {
if (command != CCREQ_CONNECT) if (command != CCREQ_CONNECT)
return NULL; return NULL;
if (Q_strcmp(MSG_ReadString(), "QUAKE") != 0) if (std::strcmp(MSG_ReadString(), "QUAKE") != 0)
return NULL; return NULL;
if (MSG_ReadByte() != NET_PROTOCOL_VERSION) { if (MSG_ReadByte() != NET_PROTOCOL_VERSION) {
@@ -987,7 +989,7 @@ static qsocket_t *_Datagram_CheckNewConnections(void) {
sock->socket = newsock; sock->socket = newsock;
sock->landriver = net_landriverlevel; sock->landriver = net_landriverlevel;
sock->addr = clientaddr; sock->addr = clientaddr;
Q_strcpy(sock->address, dfunc.AddrToString(&clientaddr)); std::strcpy(sock->address, dfunc.AddrToString(&clientaddr));
// send him back the info about the server connection he has been allocated // send him back the info about the server connection he has been allocated
SZ_Clear(&net_message); SZ_Clear(&net_message);
@@ -1017,7 +1019,7 @@ qsocket_t *Datagram_CheckNewConnections(void) {
} }
static void _Datagram_SearchForHosts(qboolean xmit) { static void _Datagram_SearchForHosts(bool xmit) {
int ret; int ret;
int n; int n;
int i; int i;
@@ -1077,27 +1079,27 @@ static void _Datagram_SearchForHosts(qboolean xmit) {
// add it // add it
hostCacheCount++; hostCacheCount++;
Q_strcpy(hostcache[n].name, MSG_ReadString()); std::strcpy(hostcache[n].name, MSG_ReadString());
Q_strcpy(hostcache[n].map, MSG_ReadString()); std::strcpy(hostcache[n].map, MSG_ReadString());
hostcache[n].users = MSG_ReadByte(); hostcache[n].users = MSG_ReadByte();
hostcache[n].maxusers = MSG_ReadByte(); hostcache[n].maxusers = MSG_ReadByte();
if (MSG_ReadByte() != NET_PROTOCOL_VERSION) { if (MSG_ReadByte() != NET_PROTOCOL_VERSION) {
Q_strcpy(hostcache[n].cname, hostcache[n].name); std::strcpy(hostcache[n].cname, hostcache[n].name);
hostcache[n].cname[14] = 0; hostcache[n].cname[14] = 0;
Q_strcpy(hostcache[n].name, "*"); std::strcpy(hostcache[n].name, "*");
Q_strcat(hostcache[n].name, hostcache[n].cname); std::strcat(hostcache[n].name, hostcache[n].cname);
} }
Q_memcpy(&hostcache[n].addr, &readaddr, sizeof(struct qsockaddr)); std::memcpy(&hostcache[n].addr, &readaddr, sizeof(struct qsockaddr));
hostcache[n].driver = net_driverlevel; hostcache[n].driver = net_driverlevel;
hostcache[n].ldriver = net_landriverlevel; hostcache[n].ldriver = net_landriverlevel;
Q_strcpy(hostcache[n].cname, dfunc.AddrToString(&readaddr)); std::strcpy(hostcache[n].cname, dfunc.AddrToString(&readaddr));
// check for a name conflict // check for a name conflict
for (i = 0; i < hostCacheCount; i++) { for (i = 0; i < hostCacheCount; i++) {
if (i == n) if (i == n)
continue; continue;
if (q_strcasecmp(hostcache[n].name, hostcache[i].name) == 0) { if (q_strcasecmp(hostcache[n].name, hostcache[i].name) == 0) {
i = Q_strlen(hostcache[n].name); i = std::strlen(hostcache[n].name);
if (i < 15 && hostcache[n].name[i - 1] > '8') { if (i < 15 && hostcache[n].name[i - 1] > '8') {
hostcache[n].name[i] = '0'; hostcache[n].name[i] = '0';
hostcache[n].name[i + 1] = 0; hostcache[n].name[i + 1] = 0;
@@ -1110,7 +1112,7 @@ static void _Datagram_SearchForHosts(qboolean xmit) {
} }
} }
void Datagram_SearchForHosts(qboolean xmit) { void Datagram_SearchForHosts(bool xmit) {
for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) { for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) {
if (hostCacheCount == HOSTCACHESIZE) if (hostCacheCount == HOSTCACHESIZE)
break; break;
@@ -1216,14 +1218,14 @@ static qsocket_t *_Datagram_Connect(const char *host) {
if (ret == 0) { if (ret == 0) {
reason = "No Response"; reason = "No Response";
Con_Printf("%s\n", reason); Con_Printf("%s\n", reason);
Q_strcpy(m_return_reason, reason); std::strcpy(m_return_reason, reason);
goto ErrorReturn; goto ErrorReturn;
} }
if (ret == -1) { if (ret == -1) {
reason = "Network Error"; reason = "Network Error";
Con_Printf("%s\n", reason); Con_Printf("%s\n", reason);
Q_strcpy(m_return_reason, reason); std::strcpy(m_return_reason, reason);
goto ErrorReturn; goto ErrorReturn;
} }
@@ -1236,12 +1238,12 @@ static qsocket_t *_Datagram_Connect(const char *host) {
} }
if (ret == CCREP_ACCEPT) { if (ret == CCREP_ACCEPT) {
Q_memcpy(&sock->addr, &sendaddr, sizeof(struct qsockaddr)); std::memcpy(&sock->addr, &sendaddr, sizeof(struct qsockaddr));
dfunc.SetSocketPort(&sock->addr, MSG_ReadLong()); dfunc.SetSocketPort(&sock->addr, MSG_ReadLong());
} else { } else {
reason = "Bad Response"; reason = "Bad Response";
Con_Printf("%s\n", reason); Con_Printf("%s\n", reason);
Q_strcpy(m_return_reason, reason); std::strcpy(m_return_reason, reason);
goto ErrorReturn; goto ErrorReturn;
} }
@@ -1254,7 +1256,7 @@ static qsocket_t *_Datagram_Connect(const char *host) {
if (dfunc.Connect(newsock, &sock->addr) == -1) { if (dfunc.Connect(newsock, &sock->addr) == -1) {
reason = "Connect to Game failed"; reason = "Connect to Game failed";
Con_Printf("%s\n", reason); Con_Printf("%s\n", reason);
Q_strcpy(m_return_reason, reason); std::strcpy(m_return_reason, reason);
goto ErrorReturn; goto ErrorReturn;
} }
+4 -4
View File
@@ -23,15 +23,15 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#define __NET_DATAGRAM_H #define __NET_DATAGRAM_H
int Datagram_Init (void); int Datagram_Init (void);
void Datagram_Listen (qboolean state); void Datagram_Listen (bool state);
void Datagram_SearchForHosts (qboolean xmit); void Datagram_SearchForHosts (bool xmit);
qsocket_t *Datagram_Connect (const char *host); qsocket_t *Datagram_Connect (const char *host);
qsocket_t *Datagram_CheckNewConnections (void); qsocket_t *Datagram_CheckNewConnections (void);
int Datagram_GetMessage (qsocket_t *sock); int Datagram_GetMessage (qsocket_t *sock);
int Datagram_SendMessage (qsocket_t *sock, sizebuf_t *data); int Datagram_SendMessage (qsocket_t *sock, sizebuf_t *data);
int Datagram_SendUnreliableMessage (qsocket_t *sock, sizebuf_t *data); int Datagram_SendUnreliableMessage (qsocket_t *sock, sizebuf_t *data);
qboolean Datagram_CanSendMessage (qsocket_t *sock); bool Datagram_CanSendMessage (qsocket_t *sock);
qboolean Datagram_CanSendUnreliableMessage (qsocket_t *sock); bool Datagram_CanSendUnreliableMessage (qsocket_t *sock);
void Datagram_Close (qsocket_t *sock); void Datagram_Close (qsocket_t *sock);
void Datagram_Shutdown (void); void Datagram_Shutdown (void);
+17 -15
View File
@@ -26,7 +26,9 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#include "net_defs.hpp" #include "net_defs.hpp"
#include "net_loop.hpp" #include "net_loop.hpp"
static qboolean localconnectpending = false; #include <cstring>
static bool localconnectpending = false;
static qsocket_t *loop_client = NULL; static qsocket_t *loop_client = NULL;
static qsocket_t *loop_server = NULL; static qsocket_t *loop_server = NULL;
@@ -43,32 +45,32 @@ void Loop_Shutdown (void)
} }
void Loop_Listen (qboolean state) void Loop_Listen (bool state)
{ {
} }
void Loop_SearchForHosts (qboolean xmit) void Loop_SearchForHosts (bool xmit)
{ {
if (!sv.active) if (!sv.active)
return; return;
hostCacheCount = 1; hostCacheCount = 1;
if (Q_strcmp(hostname.string, "UNNAMED") == 0) if (std::strcmp(hostname.string, "UNNAMED") == 0)
Q_strcpy(hostcache[0].name, "local"); std::strcpy(hostcache[0].name, "local");
else else
Q_strcpy(hostcache[0].name, hostname.string); std::strcpy(hostcache[0].name, hostname.string);
Q_strcpy(hostcache[0].map, sv.name); std::strcpy(hostcache[0].map, sv.name);
hostcache[0].users = net_activeconnections; hostcache[0].users = net_activeconnections;
hostcache[0].maxusers = svs.maxclients; hostcache[0].maxusers = svs.maxclients;
hostcache[0].driver = net_driverlevel; hostcache[0].driver = net_driverlevel;
Q_strcpy(hostcache[0].cname, "local"); std::strcpy(hostcache[0].cname, "local");
} }
qsocket_t *Loop_Connect (const char *host) qsocket_t *Loop_Connect (const char *host)
{ {
if (Q_strcmp(host,"local") != 0) if (std::strcmp(host,"local") != 0)
return NULL; return NULL;
localconnectpending = true; localconnectpending = true;
@@ -80,7 +82,7 @@ qsocket_t *Loop_Connect (const char *host)
Con_Printf("Loop_Connect: no qsocket available\n"); Con_Printf("Loop_Connect: no qsocket available\n");
return NULL; return NULL;
} }
Q_strcpy (loop_client->address, "localhost"); std::strcpy (loop_client->address, "localhost");
} }
loop_client->receiveMessageLength = 0; loop_client->receiveMessageLength = 0;
loop_client->sendMessageLength = 0; loop_client->sendMessageLength = 0;
@@ -93,7 +95,7 @@ qsocket_t *Loop_Connect (const char *host)
Con_Printf("Loop_Connect: no qsocket available\n"); Con_Printf("Loop_Connect: no qsocket available\n");
return NULL; return NULL;
} }
Q_strcpy (loop_server->address, "LOCAL"); std::strcpy (loop_server->address, "LOCAL");
} }
loop_server->receiveMessageLength = 0; loop_server->receiveMessageLength = 0;
loop_server->sendMessageLength = 0; loop_server->sendMessageLength = 0;
@@ -181,7 +183,7 @@ int Loop_SendMessage (qsocket_t *sock, sizebuf_t *data)
buffer++; buffer++;
// message // message
Q_memcpy(buffer, data->data, data->cursize); std::memcpy(buffer, data->data, data->cursize);
*bufferLength = IntAlign(*bufferLength + data->cursize + 4); *bufferLength = IntAlign(*bufferLength + data->cursize + 4);
sock->canSend = false; sock->canSend = false;
@@ -215,13 +217,13 @@ int Loop_SendUnreliableMessage (qsocket_t *sock, sizebuf_t *data)
buffer++; buffer++;
// message // message
Q_memcpy(buffer, data->data, data->cursize); std::memcpy(buffer, data->data, data->cursize);
*bufferLength = IntAlign(*bufferLength + data->cursize + 4); *bufferLength = IntAlign(*bufferLength + data->cursize + 4);
return 1; return 1;
} }
qboolean Loop_CanSendMessage (qsocket_t *sock) bool Loop_CanSendMessage (qsocket_t *sock)
{ {
if (!sock->driverdata) if (!sock->driverdata)
return false; return false;
@@ -229,7 +231,7 @@ qboolean Loop_CanSendMessage (qsocket_t *sock)
} }
qboolean Loop_CanSendUnreliableMessage (qsocket_t *sock) bool Loop_CanSendUnreliableMessage (qsocket_t *sock)
{ {
return true; return true;
} }
+4 -4
View File
@@ -24,15 +24,15 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// net_loop.h // net_loop.h
int Loop_Init (void); int Loop_Init (void);
void Loop_Listen (qboolean state); void Loop_Listen (bool state);
void Loop_SearchForHosts (qboolean xmit); void Loop_SearchForHosts (bool xmit);
qsocket_t *Loop_Connect (const char *host); qsocket_t *Loop_Connect (const char *host);
qsocket_t *Loop_CheckNewConnections (void); qsocket_t *Loop_CheckNewConnections (void);
int Loop_GetMessage (qsocket_t *sock); int Loop_GetMessage (qsocket_t *sock);
int Loop_SendMessage (qsocket_t *sock, sizebuf_t *data); int Loop_SendMessage (qsocket_t *sock, sizebuf_t *data);
int Loop_SendUnreliableMessage (qsocket_t *sock, sizebuf_t *data); int Loop_SendUnreliableMessage (qsocket_t *sock, sizebuf_t *data);
qboolean Loop_CanSendMessage (qsocket_t *sock); bool Loop_CanSendMessage (qsocket_t *sock);
qboolean Loop_CanSendUnreliableMessage (qsocket_t *sock); bool Loop_CanSendUnreliableMessage (qsocket_t *sock);
void Loop_Close (qsocket_t *sock); void Loop_Close (qsocket_t *sock);
void Loop_Shutdown (void); void Loop_Shutdown (void);
+33 -31
View File
@@ -19,6 +19,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/ */
#include <cstring>
#include "q_stdinc.hpp" #include "q_stdinc.hpp"
#include "arch_def.hpp" #include "arch_def.hpp"
#include "net_sys.hpp" #include "net_sys.hpp"
@@ -29,8 +31,8 @@ qsocket_t *net_activeSockets = NULL;
qsocket_t *net_freeSockets = NULL; qsocket_t *net_freeSockets = NULL;
int net_numsockets = 0; int net_numsockets = 0;
qboolean ipxAvailable = false; bool ipxAvailable = false;
qboolean tcpipAvailable = false; bool tcpipAvailable = false;
int net_hostport; int net_hostport;
int DEFAULTnet_hostport = 26000; int DEFAULTnet_hostport = 26000;
@@ -38,11 +40,11 @@ int DEFAULTnet_hostport = 26000;
char my_ipx_address[NET_NAMELEN]; char my_ipx_address[NET_NAMELEN];
char my_tcpip_address[NET_NAMELEN]; char my_tcpip_address[NET_NAMELEN];
static qboolean listening = false; static bool listening = false;
qboolean slistInProgress = false; bool slistInProgress = false;
qboolean slistSilent = false; bool slistSilent = false;
qboolean slistLocal = true; bool slistLocal = true;
static double slistStartTime; static double slistStartTime;
static int slistLastShown; static int slistLastShown;
@@ -106,7 +108,7 @@ qsocket_t *NET_NewQSocket(void) {
sock->disconnected = false; sock->disconnected = false;
sock->connecttime = net_time; sock->connecttime = net_time;
Q_strcpy(sock->address, "UNSET ADDRESS"); std::strcpy(sock->address, "UNSET ADDRESS");
sock->driver = net_driverlevel; sock->driver = net_driverlevel;
sock->socket = 0; sock->socket = 0;
sock->driverdata = NULL; sock->driverdata = NULL;
@@ -166,7 +168,7 @@ static void NET_Listen_f(void) {
return; return;
} }
listening = Q_atoi(command::argv(1)->c_str()) ? true : false; listening = std::atoi(command::argv(1)->c_str()) ? true : false;
for (net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) { for (net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) {
if (net_drivers[net_driverlevel].initialized == false) if (net_drivers[net_driverlevel].initialized == false)
@@ -189,7 +191,7 @@ static void MaxPlayers_f(void) {
return; return;
} }
n = Q_atoi(command::argv(1)->c_str()); n = std::atoi(command::argv(1)->c_str());
if (n < 1) if (n < 1)
n = 1; n = 1;
if (n > svs.maxclientslimit) { if (n > svs.maxclientslimit) {
@@ -198,10 +200,10 @@ static void MaxPlayers_f(void) {
} }
if ((n == 1) && listening) if ((n == 1) && listening)
Cbuf_AddText("listen 0\n"); command::buffer::add_text("listen 0\n");
if ((n > 1) && (!listening)) if ((n > 1) && (!listening))
Cbuf_AddText("listen 1\n"); command::buffer::add_text("listen 1\n");
svs.maxclients = n; svs.maxclients = n;
if (n == 1) if (n == 1)
@@ -219,7 +221,7 @@ static void NET_Port_f(void) {
return; return;
} }
n = Q_atoi(command::argv(1)->c_str()); n = std::atoi(command::argv(1)->c_str());
if (n < 1 || n > 65534) { if (n < 1 || n > 65534) {
Con_Printf("Bad value, must be between 1 and 65534\n"); Con_Printf("Bad value, must be between 1 and 65534\n");
return; return;
@@ -230,8 +232,8 @@ static void NET_Port_f(void) {
if (listening) { if (listening) {
// force a change to the new port // force a change to the new port
Cbuf_AddText("listen 0\n"); command::buffer::add_text("listen 0\n");
Cbuf_AddText("listen 1\n"); command::buffer::add_text("listen 1\n");
} }
} }
@@ -596,7 +598,7 @@ Returns true or false if the given qsocket can currently accept a
message to be transmitted. message to be transmitted.
================== ==================
*/ */
qboolean NET_CanSendMessage(qsocket_t *sock) { bool NET_CanSendMessage(qsocket_t *sock) {
if (!sock) if (!sock)
return false; return false;
@@ -613,8 +615,8 @@ int NET_SendToAll(sizebuf_t *data, double blocktime) {
double start; double start;
int i; int i;
int count = 0; int count = 0;
qboolean msg_init[MAX_SCOREBOARD]; /* did we write the message to the client's connection */ bool 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). */ bool 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++) { for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) {
/* /*
@@ -679,18 +681,17 @@ NET_Init
*/ */
void NET_Init(void) { void NET_Init(void) {
int i;
qsocket_t *s; qsocket_t *s;
i = COM_CheckParm("-port"); auto port = common::check_param("-port");
if (!i) if (!port.has_value())
i = COM_CheckParm("-udpport"); port = common::check_param("-udpport");
if (!i) if (!port.has_value())
i = COM_CheckParm("-ipxport"); port = common::check_param("-ipxport");
if (i) { if (port.has_value()) {
if (i < com_argc - 1) if (port < com_argc - 1)
DEFAULTnet_hostport = Q_atoi(com_argv[i + 1]); DEFAULTnet_hostport = std::atoi(com_argv[port.value() + 1]);
else else
Sys_Error("NET_Init: you must specify a number after -port"); Sys_Error("NET_Init: you must specify a number after -port");
} }
@@ -699,12 +700,12 @@ void NET_Init(void) {
net_numsockets = svs.maxclientslimit; net_numsockets = svs.maxclientslimit;
if (cls.state != ca_dedicated) if (cls.state != ca_dedicated)
net_numsockets++; net_numsockets++;
if (COM_CheckParm("-listen") || cls.state == ca_dedicated) if (common::check_param("-listen").has_value() || cls.state == ca_dedicated)
listening = true; listening = true;
SetNetTime(); SetNetTime();
for (i = 0; i < net_numsockets; i++) { for (auto i = 0; i < net_numsockets; i++) {
s = (qsocket_t *) Hunk_AllocName(sizeof(qsocket_t), "qsocket"); s = (qsocket_t *) Hunk_AllocName(sizeof(qsocket_t), "qsocket");
s->next = net_freeSockets; s->next = net_freeSockets;
net_freeSockets = s; net_freeSockets = s;
@@ -722,11 +723,12 @@ void NET_Init(void) {
command::add("maxplayers", MaxPlayers_f); command::add("maxplayers", MaxPlayers_f);
command::add("port", NET_Port_f); command::add("port", NET_Port_f);
int lvl;
// initialize all the drivers // initialize all the drivers
for (i = net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) { for (lvl = net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) {
if (net_drivers[net_driverlevel].Init() == -1) if (net_drivers[net_driverlevel].Init() == -1)
continue; continue;
i++; lvl++;
net_drivers[net_driverlevel].initialized = true; net_drivers[net_driverlevel].initialized = true;
if (listening) if (listening)
net_drivers[net_driverlevel].Listen(true); net_drivers[net_driverlevel].Listen(true);
@@ -734,7 +736,7 @@ void NET_Init(void) {
/* Loop_Init() returns -1 for dedicated server case, /* Loop_Init() returns -1 for dedicated server case,
* therefore the i == 0 check is correct */ * therefore the i == 0 check is correct */
if (i == 0 if (lvl == 0
&& cls.state == ca_dedicated && cls.state == ca_dedicated
) { ) {
Sys_Error("Network not available!"); Sys_Error("Network not available!");
+9 -9
View File
@@ -39,13 +39,13 @@ static in_addr_t myAddr;
sys_socket_t UDP_Init (void) sys_socket_t UDP_Init (void)
{ {
int err, i; int err;
char *tst; char *tst;
char buff[MAXHOSTNAMELEN]; char buff[MAXHOSTNAMELEN];
struct hostent *local; struct hostent *local;
struct qsockaddr addr; struct qsockaddr addr;
if (COM_CheckParm ("-noudp")) if (common::check_param ("-noudp").has_value())
return INVALID_SOCKET; return INVALID_SOCKET;
// determine my name & address // determine my name & address
@@ -81,15 +81,15 @@ sys_socket_t UDP_Init (void)
} }
else else
{ {
i = COM_CheckParm ("-ip"); auto i = common::check_param ("-ip");
if (i) if (i.has_value())
{ {
if (i < com_argc-1) if (i.value() < com_argc-1)
{ {
myAddr = inet_addr(com_argv[i + 1]); myAddr = inet_addr(com_argv[i.value() + 1]);
if (myAddr == INADDR_NONE) if (myAddr == INADDR_NONE)
Sys_Error ("%s is not a valid IP address", com_argv[i + 1]); Sys_Error ("%s is not a valid IP address", com_argv[i.value() + 1]);
strcpy(my_tcpip_address, com_argv[i + 1]); strcpy(my_tcpip_address, com_argv[i.value() + 1]);
} }
else else
{ {
@@ -134,7 +134,7 @@ void UDP_Shutdown (void)
//============================================================================= //=============================================================================
void UDP_Listen (qboolean state) void UDP_Listen (bool state)
{ {
// enable listening // enable listening
if (state) if (state)
+1 -1
View File
@@ -24,7 +24,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
sys_socket_t UDP_Init (void); sys_socket_t UDP_Init (void);
void UDP_Shutdown (void); void UDP_Shutdown (void);
void UDP_Listen (qboolean state); void UDP_Listen (bool state);
sys_socket_t UDP_OpenSocket (int port); sys_socket_t UDP_OpenSocket (int port);
int UDP_CloseSocket (sys_socket_t socketid); int UDP_CloseSocket (sys_socket_t socketid);
int UDP_Connect (sys_socket_t socketid, struct qsockaddr *addr); int UDP_Connect (sys_socket_t socketid, struct qsockaddr *addr);
+2 -2
View File
@@ -194,7 +194,7 @@ void WINS_Shutdown (void)
//============================================================================= //=============================================================================
void WINS_Listen (qboolean state) void WINS_Listen (bool state)
{ {
// enable listening // enable listening
if (state) if (state)
@@ -310,7 +310,7 @@ static int PartialIPAddress (const char *in, struct qsockaddr *hostaddr)
} }
if (*b++ == ':') if (*b++ == ':')
port = Q_atoi(b); port = std::atoi(b);
else else
port = net_hostport; port = net_hostport;
+1 -1
View File
@@ -24,7 +24,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
sys_socket_t WINS_Init (void); sys_socket_t WINS_Init (void);
void WINS_Shutdown (void); void WINS_Shutdown (void);
void WINS_Listen (qboolean state); void WINS_Listen (bool state);
sys_socket_t WINS_OpenSocket (int port); sys_socket_t WINS_OpenSocket (int port);
int WINS_CloseSocket (sys_socket_t socketid); int WINS_CloseSocket (sys_socket_t socketid);
int WINS_Connect (sys_socket_t socketid, struct qsockaddr *addr); int WINS_Connect (sys_socket_t socketid, struct qsockaddr *addr);
+1 -1
View File
@@ -120,7 +120,7 @@ void WIPX_Shutdown (void)
//============================================================================= //=============================================================================
void WIPX_Listen (qboolean state) void WIPX_Listen (bool state)
{ {
// enable listening // enable listening
if (state) if (state)
+1 -1
View File
@@ -24,7 +24,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
sys_socket_t WIPX_Init (void); sys_socket_t WIPX_Init (void);
void WIPX_Shutdown (void); void WIPX_Shutdown (void);
void WIPX_Listen (qboolean state); void WIPX_Listen (bool state);
sys_socket_t WIPX_OpenSocket (int port); sys_socket_t WIPX_OpenSocket (int port);
int WIPX_CloseSocket (sys_socket_t socketid); int WIPX_CloseSocket (sys_socket_t socketid);
int WIPX_Connect (sys_socket_t socketid, struct qsockaddr *addr); int WIPX_Connect (sys_socket_t socketid, struct qsockaddr *addr);
+4 -4
View File
@@ -190,7 +190,7 @@ static void PF_setorigin (void)
} }
static void SetMinMaxSize (edict_t *e, float *minvec, float *maxvec, qboolean rotate) static void SetMinMaxSize (edict_t *e, float *minvec, float *maxvec, bool rotate)
{ {
float *angles; float *angles;
vec3_t rmin, rmax; vec3_t rmin, rmax;
@@ -914,7 +914,7 @@ static void PF_localcmd (void)
const char *str; const char *str;
str = G_STRING(OFS_PARM0); str = G_STRING(OFS_PARM0);
Cbuf_AddText (str); command::buffer::add_text (str);
} }
/* /*
@@ -1705,7 +1705,7 @@ static void PF_changelevel (void)
svs.changelevel_issued = true; svs.changelevel_issued = true;
s = G_STRING(OFS_PARM0); s = G_STRING(OFS_PARM0);
Cbuf_AddText (va("changelevel %s\n",s)); command::buffer::add_text (va("changelevel %s\n",s));
} }
/* /*
@@ -1855,4 +1855,4 @@ static builtin_t pr_builtin[] =
}; };
const builtin_t *pr_builtins = pr_builtin; const builtin_t *pr_builtins = pr_builtin;
const int pr_numbuiltins = Q_COUNTOF(pr_builtin); const int pr_numbuiltins = std::size(pr_builtin);
+10 -10
View File
@@ -36,7 +36,7 @@ static int pr_numknownstrings;
static ddef_t *pr_fielddefs; static ddef_t *pr_fielddefs;
static ddef_t *pr_globaldefs; static ddef_t *pr_globaldefs;
qboolean pr_alpha_supported; //johnfitz bool pr_alpha_supported; //johnfitz
int pr_effects_mask; // only enable 2021 rerelease quad/penta dlights when applicable int pr_effects_mask; // only enable 2021 rerelease quad/penta dlights when applicable
dstatement_t *pr_statements; dstatement_t *pr_statements;
@@ -58,7 +58,7 @@ const int type_size[NUM_TYPE_SIZES] = {
}; };
static ddef_t *ED_FieldAtOfs (int ofs); static ddef_t *ED_FieldAtOfs (int ofs);
static qboolean ED_ParseEpair (void *base, ddef_t *key, const char *s); static bool ED_ParseEpair (void *base, ddef_t *key, const char *s);
#define MAX_FIELD_LEN 64 #define MAX_FIELD_LEN 64
#define GEFV_CACHESIZE 2 #define GEFV_CACHESIZE 2
@@ -416,7 +416,7 @@ padded to 20 field width
const char *PR_GlobalString (int ofs) const char *PR_GlobalString (int ofs)
{ {
static char line[512]; static char line[512];
static const int lastchari = Q_COUNTOF(line) - 2; static const int lastchari = std::size(line) - 2;
const char *s; const char *s;
int i; int i;
ddef_t *def; ddef_t *def;
@@ -447,7 +447,7 @@ const char *PR_GlobalString (int ofs)
const char *PR_GlobalStringNoContents (int ofs) const char *PR_GlobalStringNoContents (int ofs)
{ {
static char line[512]; static char line[512];
static const int lastchari = Q_COUNTOF(line) - 2; static const int lastchari = std::size(line) - 2;
int i; int i;
ddef_t *def; ddef_t *def;
@@ -621,7 +621,7 @@ static void ED_PrintEdict_f (void)
if (!sv.active) if (!sv.active)
return; return;
i = Q_atoi (command::argv(1).value_or("").c_str()); i = std::atoi (command::argv(1).value_or("").c_str());
if (i < 0 || i >= sv.num_edicts) if (i < 0 || i >= sv.num_edicts)
{ {
Con_Printf("Bad edict number\n"); Con_Printf("Bad edict number\n");
@@ -795,7 +795,7 @@ Can parse either fields or globals
returns false if error returns false if error
============= =============
*/ */
static qboolean ED_ParseEpair (void *base, ddef_t *key, const char *s) static bool ED_ParseEpair (void *base, ddef_t *key, const char *s)
{ {
int i; int i;
char string[128]; char string[128];
@@ -886,7 +886,7 @@ Used for initial level load and for savegames.
void ED_ParseEdict(std::istringstream &ss, edict_t *ent) void ED_ParseEdict(std::istringstream &ss, edict_t *ent)
{ {
ddef_t *key; ddef_t *key;
qboolean anglehack, init; bool anglehack, init;
int n; int n;
std::string keyname{}; std::string keyname{};
@@ -954,7 +954,7 @@ void ED_ParseEdict(std::istringstream &ss, edict_t *ent)
//johnfitz -- hack to support .alpha even when progs.dat doesn't know about it //johnfitz -- hack to support .alpha even when progs.dat doesn't know about it
if (keyname == "alpha") if (keyname == "alpha")
ent->alpha = ENTALPHA_ENCODE(Q_atof(token->c_str())); ent->alpha = ENTALPHA_ENCODE(std::atof(token->c_str()));
//johnfitz //johnfitz
key = ED_FindField (keyname.c_str()); key = ED_FindField (keyname.c_str());
@@ -1078,7 +1078,7 @@ void ED_LoadFromFile (const char *data)
PR_HasGlobal PR_HasGlobal
=============== ===============
*/ */
static qboolean PR_HasGlobal (const char *name, float value) static bool PR_HasGlobal (const char *name, float value)
{ {
ddef_t *g = ED_FindGlobal (name); ddef_t *g = ED_FindGlobal (name);
return g && (g->type & ~DEF_SAVEGLOBAL) == ev_float && G_FLOAT (g->ofs) == value; return g && (g->type & ~DEF_SAVEGLOBAL) == ev_float && G_FLOAT (g->ofs) == value;
@@ -1096,7 +1096,7 @@ to avoid conflicts (e.g. Arcane Dimensions uses bit 32 for its explosions)
*/ */
static int PR_FindSupportedEffects (void) static int PR_FindSupportedEffects (void)
{ {
qboolean isqex = bool isqex =
PR_HasGlobal ("EF_QUADLIGHT", EF_QEX_QUADLIGHT) && PR_HasGlobal ("EF_QUADLIGHT", EF_QEX_QUADLIGHT) &&
(PR_HasGlobal ("EF_PENTLIGHT", EF_QEX_PENTALIGHT) || PR_HasGlobal ("EF_PENTALIGHT", EF_QEX_PENTALIGHT)) (PR_HasGlobal ("EF_PENTLIGHT", EF_QEX_PENTALIGHT) || PR_HasGlobal ("EF_PENTALIGHT", EF_QEX_PENTALIGHT))
; ;
+2 -2
View File
@@ -35,7 +35,7 @@ static int pr_depth;
static int localstack[LOCALSTACK_SIZE]; static int localstack[LOCALSTACK_SIZE];
static int localstack_used; static int localstack_used;
qboolean pr_trace; bool pr_trace;
dfunction_t *pr_xfunction; dfunction_t *pr_xfunction;
int pr_xstatement; int pr_xstatement;
int pr_argc; int pr_argc;
@@ -144,7 +144,7 @@ static void PR_PrintStatement (dstatement_t *s)
{ {
int i; int i;
if ((unsigned int)s->op < Q_COUNTOF(pr_opnames)) if ((unsigned int)s->op < std::size(pr_opnames))
{ {
Con_Printf("%s ", pr_opnames[s->op]); Con_Printf("%s ", pr_opnames[s->op]);
i = strlen(pr_opnames[s->op]); i = strlen(pr_opnames[s->op]);
+3 -3
View File
@@ -39,7 +39,7 @@ typedef union eval_s
#define MAX_ENT_LEAFS 32 #define MAX_ENT_LEAFS 32
typedef struct edict_s typedef struct edict_s
{ {
qboolean free; bool free;
link_t area; /* linked to a division node or leaf */ link_t area; /* linked to a division node or leaf */
int num_leafs; int num_leafs;
@@ -48,7 +48,7 @@ typedef struct edict_s
entity_state_t baseline; entity_state_t baseline;
unsigned char alpha; /* johnfitz -- hack to support alpha since it's not part of entvars_t */ unsigned char alpha; /* johnfitz -- hack to support alpha since it's not part of entvars_t */
unsigned char scale; /* Quakespasm: added for model scale support. */ unsigned char scale; /* Quakespasm: added for model scale support. */
qboolean sendinterval; /* johnfitz -- send time until nextthink to client for better lerp timing */ bool sendinterval; /* johnfitz -- send time until nextthink to client for better lerp timing */
float oldframe; float oldframe;
float oldthinktime; float oldthinktime;
@@ -136,7 +136,7 @@ typedef struct {
extern int pr_argc; extern int pr_argc;
extern qboolean pr_trace; extern bool pr_trace;
extern dfunction_t *pr_xfunction; extern dfunction_t *pr_xfunction;
extern int pr_xstatement; extern int pr_xstatement;
+3 -1
View File
@@ -128,11 +128,13 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#define B_SCALE (1<<3) #define B_SCALE (1<<3)
//johnfitz //johnfitz
#include <algorithm>
//johnfitz -- PROTOCOL_FITZQUAKE -- alpha encoding //johnfitz -- PROTOCOL_FITZQUAKE -- alpha encoding
#define ENTALPHA_DEFAULT 0 //entity's alpha is "default" (i.e. water obeys r_wateralpha) -- must be zero so zeroed out memory works #define ENTALPHA_DEFAULT 0 //entity's alpha is "default" (i.e. water obeys r_wateralpha) -- must be zero so zeroed out memory works
#define ENTALPHA_ZERO 1 //entity is invisible (lowest possible alpha) #define ENTALPHA_ZERO 1 //entity is invisible (lowest possible alpha)
#define ENTALPHA_ONE 255 //entity is fully opaque (highest possible alpha) #define ENTALPHA_ONE 255 //entity is fully opaque (highest possible alpha)
#define ENTALPHA_ENCODE(a) (((a)==0)?ENTALPHA_DEFAULT:Q_rint(CLAMP(1.0f,(a)*254.0f+1,255.0f))) //server convert to byte to send to client #define ENTALPHA_ENCODE(a) (((a)==0)?ENTALPHA_DEFAULT:Q_rint(std::clamp((float)((a)*254.0f+1), 1.0f, 255.0f))) //server convert to byte to send to client
#define ENTALPHA_DECODE(a) (((a)==ENTALPHA_DEFAULT)?1.0f:((float)(a)-1)/(254)) //client convert to float for rendering #define ENTALPHA_DECODE(a) (((a)==ENTALPHA_DEFAULT)?1.0f:((float)(a)-1)/(254)) //client convert to float for rendering
#define ENTALPHA_TOSAVE(a) (((a)==ENTALPHA_DEFAULT)?0.0f:(((a)==ENTALPHA_ZERO)?-1.0f:((float)(a)-1)/(254))) //server convert to float for savegame #define ENTALPHA_TOSAVE(a) (((a)==ENTALPHA_DEFAULT)?0.0f:(((a)==ENTALPHA_ZERO)?-1.0f:((float)(a)-1)/(254))) //server convert to float for savegame
//johnfitz //johnfitz
+2 -2
View File
@@ -95,7 +95,7 @@ void S_Shutdown (void);
void S_StartSound (int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation); void S_StartSound (int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation);
void S_StaticSound (sfx_t *sfx, vec3_t origin, float vol, float attenuation); void S_StaticSound (sfx_t *sfx, vec3_t origin, float vol, float attenuation);
void S_StopSound (int entnum, int entchannel); void S_StopSound (int entnum, int entchannel);
void S_StopAllSounds(qboolean clear); void S_StopAllSounds(bool clear);
void S_ClearBuffer (void); void S_ClearBuffer (void);
void S_Update (vec3_t origin, vec3_t forward, vec3_t right, vec3_t up); void S_Update (vec3_t origin, vec3_t forward, vec3_t right, vec3_t up);
void S_ExtraUpdate (void); void S_ExtraUpdate (void);
@@ -122,7 +122,7 @@ void S_RawSamples(int samples, int rate, int width, int channels, byte * data, f
/* Expects data in signed 16 bit, or unsigned 8 bit format. */ /* Expects data in signed 16 bit, or unsigned 8 bit format. */
/* initializes cycling through a DMA buffer and returns information on it */ /* initializes cycling through a DMA buffer and returns information on it */
qboolean SNDDMA_Init(dma_t *dma); bool SNDDMA_Init(dma_t *dma);
/* gets the current DMA position */ /* gets the current DMA position */
int SNDDMA_GetDMAPos(void); int SNDDMA_GetDMAPos(void);
+6 -42
View File
@@ -75,16 +75,6 @@
#endif #endif
#endif #endif
#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)
#ifndef COMPILE_TIME_ASSERT #ifndef COMPILE_TIME_ASSERT
#if defined(__cplusplus) #if defined(__cplusplus)
/* Keep C++ case alone: Some versions of gcc will define __STDC_VERSION__ even when compiling in C++ mode. */ /* Keep C++ case alone: Some versions of gcc will define __STDC_VERSION__ even when compiling in C++ mode. */
@@ -97,28 +87,21 @@
#define COMPILE_TIME_ASSERT(name, x) _Static_assert(x, #x) #define COMPILE_TIME_ASSERT(name, x) _Static_assert(x, #x)
#endif #endif
#endif /**/ #endif /**/
#ifndef COMPILE_TIME_ASSERT
/* universal, but may trigger -Wunused-local-typedefs */
#define COMPILE_TIME_ASSERT(name, x) \
typedef int dummy_ ## name[(x) * 2 - 1]
#endif
COMPILE_TIME_ASSERT(char, sizeof(char) == 1); static_assert(sizeof(char) == 1);
COMPILE_TIME_ASSERT(float, sizeof(float) == 4); static_assert(sizeof(float) == 4);
COMPILE_TIME_ASSERT(long, sizeof(long) >= 4); static_assert(sizeof(long) >= 4);
COMPILE_TIME_ASSERT(int, sizeof(int) == 4); static_assert(sizeof(int) == 4);
COMPILE_TIME_ASSERT(short, sizeof(short) == 2); static_assert(sizeof(short) == 2);
/* make sure enums are the size of ints for structure packing */ /* make sure enums are the size of ints for structure packing */
typedef enum { typedef enum {
THE_DUMMY_VALUE THE_DUMMY_VALUE
} THE_DUMMY_ENUM; } THE_DUMMY_ENUM;
COMPILE_TIME_ASSERT(enum, sizeof(THE_DUMMY_ENUM) == sizeof(int)); static_assert(sizeof(THE_DUMMY_ENUM) == sizeof(int));
/* for array size: */ /* for array size: */
#define Q_COUNTOF(x) (sizeof(x) / sizeof((x)[0]))
/* Provide a substitute for offsetof() if we don't have one. /* Provide a substitute for offsetof() if we don't have one.
* This variant works on most (but not *all*) systems... * This variant works on most (but not *all*) systems...
*/ */
@@ -131,25 +114,6 @@ COMPILE_TIME_ASSERT(enum, sizeof(THE_DUMMY_ENUM) == sizeof(int));
typedef unsigned char byte; typedef unsigned char byte;
/* some structures have qboolean members and the x86 asm code expect
* those members to be 4 bytes long. i.e.: qboolean must be 32 bits. */
typedef int qboolean;
#undef true
#undef false
#if !defined(__cplusplus)
#if defined __STDC_VERSION__ && (__STDC_VERSION__ >= 199901L)
#include <stdbool.h>
#else
enum {
false = 0,
true = 1
};
#endif
#endif /* */
COMPILE_TIME_ASSERT(falsehood, ((1 != 1) == false));
COMPILE_TIME_ASSERT(truth, ((1 == 1) == true));
COMPILE_TIME_ASSERT(qboolean, sizeof(qboolean) == 4);
/*==========================================================================*/ /*==========================================================================*/
/* math */ /* math */
+4 -4
View File
@@ -268,7 +268,7 @@ typedef struct
// command line parms passed to the program, and the amount of memory // command line parms passed to the program, and the amount of memory
// available for the program to use // available for the program to use
extern qboolean noclip_anglehack; extern bool noclip_anglehack;
// //
// host // host
@@ -281,7 +281,7 @@ extern convar sys_nostdout;
extern convar developer; extern convar developer;
extern convar max_edicts; //johnfitz extern convar max_edicts; //johnfitz
extern qboolean host_initialized; // true if into command execution extern bool host_initialized; // true if into command execution
extern double host_frametime; extern double host_frametime;
extern byte *host_colormap; extern byte *host_colormap;
extern int host_framecount; // incremented every frame, never reset extern int host_framecount; // incremented every frame, never reset
@@ -313,7 +313,7 @@ FUNC_NORETURN void Host_EndGame (const char *message, ...) FUNC_PRINTF(1,2);
void Host_Frame (float time); void Host_Frame (float time);
void Host_Quit_f (void); void Host_Quit_f (void);
void Host_ClientCommands (const char *fmt, ...) FUNC_PRINTF(1,2); void Host_ClientCommands (const char *fmt, ...) FUNC_PRINTF(1,2);
void Host_ShutdownServer (qboolean crash); void Host_ShutdownServer (bool crash);
void Host_WriteConfiguration (void); void Host_WriteConfiguration (void);
void Host_Resetdemos (void); void Host_Resetdemos (void);
@@ -328,7 +328,7 @@ extern int current_skill; // skill level for currently loaded level (in case
// the user changes the cvar while the level is // the user changes the cvar while the level is
// running, this reflects the level actually in use) // running, this reflects the level actually in use)
extern qboolean isDedicated; extern bool isDedicated;
extern int minimum_memory; extern int minimum_memory;
+9 -9
View File
@@ -49,9 +49,9 @@ static vec3_t shadevector;
static float entalpha; //johnfitz static float entalpha; //johnfitz
static qboolean overbright; //johnfitz static bool overbright; //johnfitz
static qboolean shading = true; //johnfitz -- if false, disable vertex shading for various reasons (fullbright, r_lightmap, showtris, etc) static bool shading = true; //johnfitz -- if false, disable vertex shading for various reasons (fullbright, r_lightmap, showtris, etc)
//johnfitz -- struct for passing lerp information to drawing functions //johnfitz -- struct for passing lerp information to drawing functions
typedef struct { typedef struct {
@@ -192,7 +192,7 @@ void GLAlias_CreateShaders (void)
if (!gl_glsl_alias_able) if (!gl_glsl_alias_able)
return; return;
r_alias_program = GL_CreateProgram (vertSource, fragSource, Q_COUNTOF(bindings), bindings); r_alias_program = GL_CreateProgram (vertSource, fragSource, std::size(bindings), bindings);
if (r_alias_program != 0) if (r_alias_program != 0)
{ {
@@ -302,7 +302,7 @@ void GL_DrawAliasFrame (aliashdr_t *paliashdr, lerpdata_t lerpdata)
int count; int count;
float u,v; float u,v;
float blend, iblend; float blend, iblend;
qboolean lerping; bool lerping;
if (lerpdata.pose1 != lerpdata.pose2) if (lerpdata.pose1 != lerpdata.pose2)
{ {
@@ -455,9 +455,9 @@ void R_SetupAliasFrame (aliashdr_t *paliashdr, int frame, lerpdata_t *lerpdata)
if (r_lerpmodels.value && !(e->model->flags & MOD_NOLERP && r_lerpmodels.value != 2)) if (r_lerpmodels.value && !(e->model->flags & MOD_NOLERP && r_lerpmodels.value != 2))
{ {
if (e->lerpflags & LERP_FINISH && numposes == 1) if (e->lerpflags & LERP_FINISH && numposes == 1)
lerpdata->blend = CLAMP (0.0f, (float)(cl.time - e->lerpstart) / (e->lerpfinish - e->lerpstart), 1.0f); lerpdata->blend = std::clamp((float)(cl.time - e->lerpstart) / (e->lerpfinish - e->lerpstart), 0.0f, 1.0f);
else else
lerpdata->blend = CLAMP (0.0f, (float)(cl.time - e->lerpstart) / e->lerptime, 1.0f); lerpdata->blend = std::clamp((float)(cl.time - e->lerpstart) / e->lerptime, 0.0f, 1.0f);
if (lerpdata->blend == 1.0f) if (lerpdata->blend == 1.0f)
e->previouspose = e->currentpose; e->previouspose = e->currentpose;
lerpdata->pose1 = e->previouspose; lerpdata->pose1 = e->previouspose;
@@ -505,9 +505,9 @@ void R_SetupEntityTransform (entity_t *e, lerpdata_t *lerpdata)
if (r_lerpmove.value && e != &cl.viewent && e->lerpflags & LERP_MOVESTEP) if (r_lerpmove.value && e != &cl.viewent && e->lerpflags & LERP_MOVESTEP)
{ {
if (e->lerpflags & LERP_FINISH) if (e->lerpflags & LERP_FINISH)
blend = CLAMP (0.0f, (float)(cl.time - e->movelerpstart) / (e->lerpfinish - e->movelerpstart), 1.0f); blend = std::clamp((float)(cl.time - e->movelerpstart) / (e->lerpfinish - e->movelerpstart), 0.0f, 1.0f);
else else
blend = CLAMP (0.0f, (float)(cl.time - e->movelerpstart) / 0.1f, 1.0f); blend = std::clamp((float)(cl.time - e->movelerpstart) / 0.1f, 0.0f, 1.0f);
//translation //translation
VectorSubtract (e->currentorigin, e->previousorigin, d); VectorSubtract (e->currentorigin, e->previousorigin, d);
@@ -636,7 +636,7 @@ void R_DrawAliasModel (entity_t *e)
int anim, skinnum; int anim, skinnum;
gltexture_t *tx, *fb; gltexture_t *tx, *fb;
lerpdata_t lerpdata; lerpdata_t lerpdata;
qboolean alphatest = !!(e->model->flags & MF_HOLEY); bool alphatest = !!(e->model->flags & MF_HOLEY);
float fovscale = 1.0f; float fovscale = 1.0f;
// //
+5 -7
View File
@@ -146,13 +146,11 @@ R_InitParticles
*/ */
void R_InitParticles (void) void R_InitParticles (void)
{ {
int i; auto i = common::check_param ("-particles");
i = COM_CheckParm ("-particles"); if (i.has_value() && i.value() < com_argc - 1)
if (i && i < com_argc - 1)
{ {
r_numparticles = atoi(com_argv[i + 1]); r_numparticles = atoi(com_argv[i.value() + 1]);
if (r_numparticles < ABSOLUTE_MIN_PARTICLES) if (r_numparticles < ABSOLUTE_MIN_PARTICLES)
r_numparticles = ABSOLUTE_MIN_PARTICLES; r_numparticles = ABSOLUTE_MIN_PARTICLES;
else if (r_numparticles > ABSOLUTE_MAX_PARTICLES) else if (r_numparticles > ABSOLUTE_MAX_PARTICLES)
@@ -870,7 +868,7 @@ void R_DrawParticles (void)
color[0] = c[0]; color[0] = c[0];
color[1] = c[1]; color[1] = c[1];
color[2] = c[2]; color[2] = c[2];
//alpha = CLAMP(0, p->die + 0.5 - cl.time, 1); //alpha = std::clamp(p->die + 0.5 - cl.time, 0, 1);
color[3] = 255; //(int)(alpha * 255); color[3] = 255; //(int)(alpha * 255);
glColor4ubv(color); glColor4ubv(color);
//johnfitz //johnfitz
@@ -913,7 +911,7 @@ void R_DrawParticles (void)
color[0] = c[0]; color[0] = c[0];
color[1] = c[1]; color[1] = c[1];
color[2] = c[2]; color[2] = c[2];
//alpha = CLAMP(0, p->die + 0.5 - cl.time, 1); //alpha = std::clamp(p->die + 0.5 - cl.time, 0, 1);
color[3] = 255; //(int)(alpha * 255); color[3] = 255; //(int)(alpha * 255);
glColor4ubv(color); glColor4ubv(color);
//johnfitz //johnfitz
+11 -11
View File
@@ -72,7 +72,7 @@ void R_ChainSurface (msurface_t *surf, texchain_t chain)
R_BackFaceCull -- johnfitz -- returns true if the surface is facing away from vieworg R_BackFaceCull -- johnfitz -- returns true if the surface is facing away from vieworg
================ ================
*/ */
qboolean R_BackFaceCull (msurface_t *surf) bool R_BackFaceCull (msurface_t *surf)
{ {
double dot; double dot;
@@ -98,7 +98,7 @@ void R_MarkSurfaces (void)
mleaf_t *leaf; mleaf_t *leaf;
msurface_t *surf, **mark; msurface_t *surf, **mark;
int i, j; int i, j;
qboolean nearwaterportal; bool nearwaterportal;
// clear lightmap chains // clear lightmap chains
for (i=0 ; i<lightmap_count ; i++) for (i=0 ; i<lightmap_count ; i++)
@@ -289,7 +289,7 @@ void R_DrawTextureChains_Glow (qmodel_t *model, entity_t *ent, texchain_t chain)
msurface_t *s; msurface_t *s;
texture_t *t; texture_t *t;
gltexture_t *glt; gltexture_t *glt;
qboolean bound; bool bound;
for (i=0 ; i<model->numtextures ; i++) for (i=0 ; i<model->numtextures ; i++)
{ {
@@ -410,7 +410,7 @@ void R_DrawTextureChains_Multitexture (qmodel_t *model, entity_t *ent, texchain_
msurface_t *s; msurface_t *s;
texture_t *t; texture_t *t;
float *v; float *v;
qboolean bound; bool bound;
for (i=0 ; i<model->numtextures ; i++) for (i=0 ; i<model->numtextures ; i++)
{ {
@@ -463,7 +463,7 @@ void R_DrawTextureChains_NoTexture (qmodel_t *model, texchain_t chain)
int i; int i;
msurface_t *s; msurface_t *s;
texture_t *t; texture_t *t;
qboolean bound; bool bound;
for (i=0 ; i<model->numtextures ; i++) for (i=0 ; i<model->numtextures ; i++)
{ {
@@ -497,7 +497,7 @@ void R_DrawTextureChains_TextureOnly (qmodel_t *model, entity_t *ent, texchain_t
int i; int i;
msurface_t *s; msurface_t *s;
texture_t *t; texture_t *t;
qboolean bound; bool bound;
for (i=0 ; i<model->numtextures ; i++) for (i=0 ; i<model->numtextures ; i++)
{ {
@@ -576,11 +576,11 @@ void R_DrawTextureChains_Water (qmodel_t *model, entity_t *ent, texchain_t chain
msurface_t *s; msurface_t *s;
texture_t *t; texture_t *t;
glpoly_t *p; glpoly_t *p;
qboolean bound; bool bound;
float entalpha; float entalpha;
int lastlightmap; int lastlightmap;
qboolean has_lit_water; bool has_lit_water;
qboolean has_unlit_water; bool has_unlit_water;
if (r_drawflat_cheatsafe || r_lightmap_cheatsafe) // ericw -- !r_drawworld_cheatsafe check moved to R_DrawWorld_Water () if (r_drawflat_cheatsafe || r_lightmap_cheatsafe) // ericw -- !r_drawworld_cheatsafe check moved to R_DrawWorld_Water ()
return; return;
@@ -885,7 +885,7 @@ void GLWorld_CreateShaders (void)
if (!gl_glsl_alias_able) if (!gl_glsl_alias_able)
return; return;
r_world_program = GL_CreateProgram (vertSource, fragSource, Q_COUNTOF(bindings), bindings); r_world_program = GL_CreateProgram (vertSource, fragSource, std::size(bindings), bindings);
if (r_world_program != 0) if (r_world_program != 0)
{ {
@@ -920,7 +920,7 @@ void R_DrawTextureChains_GLSL (qmodel_t *model, entity_t *ent, texchain_t chain)
int i; int i;
msurface_t *s; msurface_t *s;
texture_t *t; texture_t *t;
qboolean bound; bool bound;
int lastlightmap; int lastlightmap;
gltexture_t *fullbright = NULL; gltexture_t *fullbright = NULL;
+1 -1
View File
@@ -48,7 +48,7 @@ typedef struct efrag_s
typedef struct entity_s typedef struct entity_s
{ {
qboolean forcelink; // model changed bool forcelink; // model changed
int update_type; int update_type;
+4 -4
View File
@@ -46,7 +46,7 @@ static qpic_t *sb_face_quad;
static qpic_t *sb_face_invuln; static qpic_t *sb_face_invuln;
static qpic_t *sb_face_invis_invuln; static qpic_t *sb_face_invis_invuln;
static qboolean sb_showscores; static bool sb_showscores;
int sb_lines; // scan lines to draw int sb_lines; // scan lines to draw
@@ -322,7 +322,7 @@ void Sbar_DrawScrollString (int x, int y, int width, const char *str)
float scale; float scale;
int len, ofs, left; int len, ofs, left;
scale = CLAMP (1.0f, scr_sbarscale.value, (float)glwidth / 320.0f); scale = std::clamp(scr_sbarscale.value, 1.0f, (float)glwidth / 320.0f);
left = x * scale; left = x * scale;
if (cl.gametype != GAME_DEATHMATCH) if (cl.gametype != GAME_DEATHMATCH)
left += (((float)glwidth - 320.0 * scale) / 2); left += (((float)glwidth - 320.0 * scale) / 2);
@@ -911,7 +911,7 @@ void Sbar_Draw (void)
GL_SetCanvas (CANVAS_DEFAULT); //johnfitz GL_SetCanvas (CANVAS_DEFAULT); //johnfitz
//johnfitz -- don't waste fillrate by clearing the area behind the sbar //johnfitz -- don't waste fillrate by clearing the area behind the sbar
w = CLAMP (320.0f, scr_sbarscale.value * 320.0f, (float)glwidth); w = std::clamp(scr_sbarscale.value * 320.0f, 320.0f, (float)glwidth);
if (sb_lines && glwidth > w) if (sb_lines && glwidth > w)
{ {
if (scr_sbaralpha.value < 1) if (scr_sbaralpha.value < 1)
@@ -1210,7 +1210,7 @@ void Sbar_MiniDeathmatchOverlay (void)
float scale; //johnfitz float scale; //johnfitz
scoreboard_t *s; scoreboard_t *s;
scale = CLAMP (1.0f, scr_sbarscale.value, (float)glwidth / 320.0f); //johnfitz scale = std::clamp(scr_sbarscale.value, 1.0f, (float)glwidth / 320.0f); //johnfitz
//MAX_SCOREBOARDNAME = 32, so total width for this overlay plus sbar is 632, but we can cut off some i guess //MAX_SCOREBOARDNAME = 32, so total width for this overlay plus sbar is 632, but we can cut off some i guess
if (glwidth/scale < 512 || scr_viewsize.value >= 120) //johnfitz -- test should consider scr_sbarscale if (glwidth/scale < 512 || scr_viewsize.value >= 120) //johnfitz -- test should consider scr_sbarscale
+2 -2
View File
@@ -47,8 +47,8 @@ extern float scr_conlines; // lines of console to display
extern int sb_lines; extern int sb_lines;
extern int clearnotify; // set to 0 whenever notify text is drawn extern int clearnotify; // set to 0 whenever notify text is drawn
extern qboolean scr_disabled_for_loading; extern bool scr_disabled_for_loading;
extern qboolean scr_skipupdate; extern bool scr_skipupdate;
extern convar scr_viewsize; extern convar scr_viewsize;
+10 -10
View File
@@ -31,7 +31,7 @@ typedef struct
int maxclientslimit; int maxclientslimit;
struct client_s *clients; // [maxclients] struct client_s *clients; // [maxclients]
int serverflags; // episode completion information int serverflags; // episode completion information
qboolean changelevel_issued; // cleared when at SV_SpawnServer bool changelevel_issued; // cleared when at SV_SpawnServer
} server_static_t; } server_static_t;
//============================================================================= //=============================================================================
@@ -42,10 +42,10 @@ typedef enum {ss_loading, ss_active} server_state_t;
typedef struct typedef struct
{ {
qboolean active; // false if only a net client bool active; // false if only a net client
qboolean paused; bool paused;
qboolean loadgame; // handle connections specially bool loadgame; // handle connections specially
double time; double time;
@@ -94,9 +94,9 @@ enum sendsignon_e
typedef struct client_s typedef struct client_s
{ {
qboolean active; // false = client is free bool active; // false = client is free
qboolean spawned; // false = don't send datagrams bool spawned; // false = don't send datagrams
qboolean dropasap; // has been told to go to another level bool dropasap; // has been told to go to another level
enum sendsignon_e sendsignon; // only valid before spawned enum sendsignon_e sendsignon; // only valid before spawned
int signonidx; int signonidx;
@@ -212,7 +212,7 @@ void SV_StartSound (edict_t *entity, int channel, const char *sample, int volume
float attenuation); float attenuation);
void SV_LocalSound (client_t *client, const char *sample); // for 2021 rerelease void SV_LocalSound (client_t *client, const char *sample); // for 2021 rerelease
void SV_DropClient (qboolean crash); void SV_DropClient (bool crash);
void SV_SendClientMessages (void); void SV_SendClientMessages (void);
void SV_ClearDatagram (void); void SV_ClearDatagram (void);
@@ -232,8 +232,8 @@ void SV_BroadcastPrintf (const char *fmt, ...) FUNC_PRINTF(1,2);
void SV_Physics (void); void SV_Physics (void);
qboolean SV_CheckBottom (edict_t *ent); bool SV_CheckBottom (edict_t *ent);
qboolean SV_movestep (edict_t *ent, vec3_t move, qboolean relink); bool SV_movestep (edict_t *ent, vec3_t move, bool relink);
void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg); void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg);
+6 -6
View File
@@ -121,7 +121,7 @@ void S_CodecShutdown (void)
S_CodecOpenStream S_CodecOpenStream
================= =================
*/ */
snd_stream_t *S_CodecOpenStreamType (const char *filename, unsigned int type, qboolean loop) snd_stream_t *S_CodecOpenStreamType (const char *filename, unsigned int type, bool loop)
{ {
snd_codec_t *codec; snd_codec_t *codec;
snd_stream_t *stream; snd_stream_t *stream;
@@ -153,7 +153,7 @@ snd_stream_t *S_CodecOpenStreamType (const char *filename, unsigned int type, qb
return stream; return stream;
} }
snd_stream_t *S_CodecOpenStreamExt (const char *filename, qboolean loop) snd_stream_t *S_CodecOpenStreamExt (const char *filename, bool loop)
{ {
snd_codec_t *codec; snd_codec_t *codec;
snd_stream_t *stream; snd_stream_t *stream;
@@ -187,7 +187,7 @@ snd_stream_t *S_CodecOpenStreamExt (const char *filename, qboolean loop)
return stream; return stream;
} }
snd_stream_t *S_CodecOpenStreamAny (const char *filename, qboolean loop) snd_stream_t *S_CodecOpenStreamAny (const char *filename, bool loop)
{ {
snd_codec_t *codec; snd_codec_t *codec;
snd_stream_t *stream; snd_stream_t *stream;
@@ -239,7 +239,7 @@ snd_stream_t *S_CodecOpenStreamAny (const char *filename, qboolean loop)
} }
} }
qboolean S_CodecForwardStream (snd_stream_t *stream, unsigned int type) bool S_CodecForwardStream (snd_stream_t *stream, unsigned int type)
{ {
snd_codec_t *codec = codecs; snd_codec_t *codec = codecs;
@@ -280,11 +280,11 @@ int S_CodecReadStream (snd_stream_t *stream, int bytes, void *buffer)
/* Util functions (used by codecs) */ /* Util functions (used by codecs) */
snd_stream_t *S_CodecUtilOpen(const char *filename, snd_codec_t *codec, qboolean loop) snd_stream_t *S_CodecUtilOpen(const char *filename, snd_codec_t *codec, bool loop)
{ {
snd_stream_t *stream; snd_stream_t *stream;
FILE *handle; FILE *handle;
qboolean pak; bool pak;
long length; long length;
/* Try to open the file */ /* Try to open the file */
+6 -6
View File
@@ -49,12 +49,12 @@ typedef struct snd_codec_s snd_codec_t;
typedef struct snd_stream_s typedef struct snd_stream_s
{ {
fshandle_t fh; fshandle_t fh;
qboolean pak; bool pak;
char name[MAX_QPATH]; /* name of the source file */ char name[MAX_QPATH]; /* name of the source file */
snd_info_t info; snd_info_t info;
stream_status_t status; stream_status_t status;
snd_codec_t *codec; /* codec handling this stream */ snd_codec_t *codec; /* codec handling this stream */
qboolean loop; bool loop;
void *priv; /* data private to the codec. */ void *priv; /* data private to the codec. */
} snd_stream_t; } snd_stream_t;
@@ -66,14 +66,14 @@ void S_CodecShutdown (void);
* are reponsible for attaching any path to the filename */ * are reponsible for attaching any path to the filename */
snd_stream_t *S_CodecOpenStreamType (const char *filename, unsigned int type, snd_stream_t *S_CodecOpenStreamType (const char *filename, unsigned int type,
qboolean loop); bool loop);
/* Decides according to the required type. */ /* Decides according to the required type. */
snd_stream_t *S_CodecOpenStreamAny (const char *filename, qboolean loop); snd_stream_t *S_CodecOpenStreamAny (const char *filename, bool loop);
/* Decides according to file extension. if the /* Decides according to file extension. if the
* name has no extension, try all available. */ * name has no extension, try all available. */
snd_stream_t *S_CodecOpenStreamExt (const char *filename, qboolean loop); snd_stream_t *S_CodecOpenStreamExt (const char *filename, bool loop);
/* Decides according to file extension. the name /* Decides according to file extension. the name
* MUST have an extension. */ * MUST have an extension. */
@@ -82,7 +82,7 @@ int S_CodecReadStream (snd_stream_t *stream, int bytes, void *buffer);
int S_CodecRewindStream (snd_stream_t *stream); int S_CodecRewindStream (snd_stream_t *stream);
int S_CodecJumpToOrder (snd_stream_t *stream, int to); int S_CodecJumpToOrder (snd_stream_t *stream, int to);
snd_stream_t *S_CodecUtilOpen(const char *filename, snd_codec_t *codec, qboolean loop); snd_stream_t *S_CodecUtilOpen(const char *filename, snd_codec_t *codec, bool loop);
void S_CodecUtilClose(snd_stream_t **stream); void S_CodecUtilClose(snd_stream_t **stream);
+4 -4
View File
@@ -27,9 +27,9 @@
#define _SND_CODECI_H_ #define _SND_CODECI_H_
/* Codec internals */ /* Codec internals */
typedef qboolean (*CODEC_INIT)(void); typedef bool (*CODEC_INIT)(void);
typedef void (*CODEC_SHUTDOWN)(void); typedef void (*CODEC_SHUTDOWN)(void);
typedef qboolean (*CODEC_OPEN)(snd_stream_t *stream); typedef bool (*CODEC_OPEN)(snd_stream_t *stream);
typedef int (*CODEC_READ)(snd_stream_t *stream, int bytes, void *buffer); typedef int (*CODEC_READ)(snd_stream_t *stream, int bytes, void *buffer);
typedef int (*CODEC_REWIND)(snd_stream_t *stream); typedef int (*CODEC_REWIND)(snd_stream_t *stream);
typedef int (*CODEC_JUMP)(snd_stream_t *stream, int order); typedef int (*CODEC_JUMP)(snd_stream_t *stream, int order);
@@ -38,7 +38,7 @@ typedef void (*CODEC_CLOSE)(snd_stream_t *stream);
struct snd_codec_s struct snd_codec_s
{ {
unsigned int type; /* handled data type. (1U << n) */ unsigned int type; /* handled data type. (1U << n) */
qboolean initialized; /* init succeedded */ bool initialized; /* init succeedded */
const char *ext; /* expected extension */ const char *ext; /* expected extension */
CODEC_INIT initialize; CODEC_INIT initialize;
CODEC_SHUTDOWN shutdown; CODEC_SHUTDOWN shutdown;
@@ -50,7 +50,7 @@ struct snd_codec_s
snd_codec_t *next; snd_codec_t *next;
}; };
qboolean S_CodecForwardStream (snd_stream_t *stream, unsigned int type); bool S_CodecForwardStream (snd_stream_t *stream, unsigned int type);
/* Forward a stream to another codec of 'type' type. */ /* Forward a stream to another codec of 'type' type. */
#endif /* _SND_CODECI_H_ */ #endif /* _SND_CODECI_H_ */
+11 -13
View File
@@ -36,7 +36,7 @@ static void S_SoundList(void);
static void S_Update_(void); static void S_Update_(void);
void S_StopAllSounds(qboolean clear); void S_StopAllSounds(bool clear);
static void S_StopAllSoundsC(void); static void S_StopAllSoundsC(void);
@@ -48,7 +48,7 @@ channel_t snd_channels[MAX_CHANNELS];
int total_channels; int total_channels;
static int snd_blocked = 0; static int snd_blocked = 0;
static qboolean snd_initialized = false; static bool snd_initialized = false;
static dma_t sn; static dma_t sn;
volatile dma_t *shm = NULL; volatile dma_t *shm = NULL;
@@ -73,7 +73,7 @@ static int num_sfx;
static sfx_t *ambient_sfx[NUM_AMBIENTS]; static sfx_t *ambient_sfx[NUM_AMBIENTS];
static qboolean sound_started = false; static bool sound_started = false;
convar bgmvolume = {"bgmvolume", "1", {.archive = true}}; convar bgmvolume = {"bgmvolume", "1", {.archive = true}};
convar sfxvolume = {"volume", "0.7", {.archive = true}}; convar sfxvolume = {"volume", "0.7", {.archive = true}};
@@ -153,8 +153,6 @@ S_Init
================ ================
*/ */
void S_Init(void) { void S_Init(void) {
int i;
if (snd_initialized) { if (snd_initialized) {
Con_Printf("Sound is already initialized\n"); Con_Printf("Sound is already initialized\n");
return; return;
@@ -174,7 +172,7 @@ void S_Init(void) {
snd_mixspeed.inscribe(); snd_mixspeed.inscribe();
snd_filterquality.inscribe(); snd_filterquality.inscribe();
if (safemode || COM_CheckParm("-nosound")) if (safemode || common::check_param("-nosound").has_value())
return; return;
Con_Printf("\nSound Initialization\n"); Con_Printf("\nSound Initialization\n");
@@ -185,14 +183,14 @@ void S_Init(void) {
command::add("soundlist", S_SoundList); command::add("soundlist", S_SoundList);
command::add("soundinfo", S_SoundInfo_f); command::add("soundinfo", S_SoundInfo_f);
i = COM_CheckParm("-sndspeed"); auto i = common::check_param("-sndspeed");
if (i && i < com_argc - 1) { if (i.has_value() && i.value() < com_argc - 1) {
sndspeed.set(com_argv[i + 1]); sndspeed.set(com_argv[i.value() + 1]);
} }
i = COM_CheckParm("-mixspeed"); i = common::check_param("-mixspeed");
if (i && i < com_argc - 1) { if (i.has_value() && i.value() < com_argc - 1) {
snd_mixspeed.set(com_argv[i + 1]); snd_mixspeed.set(com_argv[i.value() + 1]);
} }
if (host_parms->memsize < 0x800000) { if (host_parms->memsize < 0x800000) {
@@ -497,7 +495,7 @@ void S_StopSound(int entnum, int entchannel) {
} }
} }
void S_StopAllSounds(qboolean clear) { void S_StopAllSounds(bool clear) {
int i; int i;
if (!sound_started) if (!sound_started)
+2 -2
View File
@@ -224,7 +224,7 @@ flac_meta_func (const FLAC__StreamDecoder *decoder,
} }
static qboolean S_FLAC_CodecInitialize (void) static bool S_FLAC_CodecInitialize (void)
{ {
return true; return true;
} }
@@ -233,7 +233,7 @@ static void S_FLAC_CodecShutdown (void)
{ {
} }
static qboolean S_FLAC_CodecOpenStream (snd_stream_t *stream) static bool S_FLAC_CodecOpenStream (snd_stream_t *stream)
{ {
flacfile_t *ff; flacfile_t *ff;
int rc; int rc;
+2 -2
View File
@@ -81,7 +81,7 @@ static BOOL MIK_Eof (MREADER *r)
return FS_feof(((mik_priv_t *)r)->fh); return FS_feof(((mik_priv_t *)r)->fh);
} }
static qboolean S_MIKMOD_CodecInitialize (void) static bool S_MIKMOD_CodecInitialize (void)
{ {
if (mikmod_codec.initialized) if (mikmod_codec.initialized)
return true; return true;
@@ -129,7 +129,7 @@ static void S_MIKMOD_CodecShutdown (void)
} }
} }
static qboolean S_MIKMOD_CodecOpenStream (snd_stream_t *stream) static bool S_MIKMOD_CodecOpenStream (snd_stream_t *stream)
{ {
mik_priv_t *priv; mik_priv_t *priv;
+2 -2
View File
@@ -407,8 +407,8 @@ void S_PaintChannels (int endtime)
// clipping // clipping
for (i=0; i<end-paintedtime; i++) for (i=0; i<end-paintedtime; i++)
{ {
paintbuffer[i].left = CLAMP(-32768 * 256, paintbuffer[i].left, 32767 * 256) / 2; paintbuffer[i].left = std::clamp(paintbuffer[i].left, -32768 * 256, 32767 * 256) / 2;
paintbuffer[i].right = CLAMP(-32768 * 256, paintbuffer[i].right, 32767 * 256) / 2; paintbuffer[i].right = std::clamp(paintbuffer[i].right, -32768 * 256, 32767 * 256) / 2;
} }
// apply a lowpass filter // apply a lowpass filter
+2 -2
View File
@@ -48,7 +48,7 @@ static void S_MODPLUG_SetSettings (snd_stream_t *stream)
} }
} }
static qboolean S_MODPLUG_CodecInitialize (void) static bool S_MODPLUG_CodecInitialize (void)
{ {
return true; return true;
} }
@@ -57,7 +57,7 @@ static void S_MODPLUG_CodecShutdown (void)
{ {
} }
static qboolean S_MODPLUG_CodecOpenStream (snd_stream_t *stream) static bool S_MODPLUG_CodecOpenStream (snd_stream_t *stream)
{ {
/* need to load the whole file into memory and pass it to libmodplug */ /* need to load the whole file into memory and pass it to libmodplug */
byte *moddata; byte *moddata;
+3 -3
View File
@@ -275,7 +275,7 @@ static int mp3_madseek(snd_stream_t *stream, unsigned long offset)
size_t initial_bitrate = p->Frame.header.bitrate; size_t initial_bitrate = p->Frame.header.bitrate;
size_t consumed = 0; size_t consumed = 0;
int vbr = 0; /* Variable Bit Rate, bool */ int vbr = 0; /* Variable Bit Rate, bool */
qboolean depadded = false; bool depadded = false;
unsigned long to_skip_samples = 0; unsigned long to_skip_samples = 0;
/* Reset all */ /* Reset all */
@@ -376,7 +376,7 @@ static int mp3_madseek(snd_stream_t *stream, unsigned long offset)
return -1; return -1;
} }
static qboolean S_MP3_CodecInitialize (void) static bool S_MP3_CodecInitialize (void)
{ {
return true; return true;
} }
@@ -385,7 +385,7 @@ static void S_MP3_CodecShutdown (void)
{ {
} }
static qboolean S_MP3_CodecOpenStream (snd_stream_t *stream) static bool S_MP3_CodecOpenStream (snd_stream_t *stream)
{ {
int err; int err;
+5 -5
View File
@@ -23,14 +23,14 @@
#include "snd_codec.h" #include "snd_codec.h"
#include "q_ctype.h" #include "q_ctype.h"
static inline qboolean is_id3v1(const unsigned char *data, long length) { static inline bool is_id3v1(const unsigned char *data, long length) {
/* http://id3.org/ID3v1 : 3 bytes "TAG" identifier and 125 bytes tag data */ /* http://id3.org/ID3v1 : 3 bytes "TAG" identifier and 125 bytes tag data */
if (length < 128 || memcmp(data,"TAG",3) != 0) { if (length < 128 || memcmp(data,"TAG",3) != 0) {
return false; return false;
} }
return true; return true;
} }
static qboolean is_id3v2(const unsigned char *data, size_t length) { static bool is_id3v2(const unsigned char *data, size_t length) {
/* ID3v2 header is 10 bytes: http://id3.org/id3v2.4.0-structure */ /* ID3v2 header is 10 bytes: http://id3.org/id3v2.4.0-structure */
/* bytes 0-2: "ID3" identifier */ /* bytes 0-2: "ID3" identifier */
if (length < 10 || memcmp(data,"ID3",3) != 0) { if (length < 10 || memcmp(data,"ID3",3) != 0) {
@@ -64,7 +64,7 @@ static long get_id3v2_len(const unsigned char *data, long length) {
} }
return size; return size;
} }
static qboolean is_apetag(const unsigned char *data, size_t length) { static bool is_apetag(const unsigned char *data, size_t length) {
/* http://wiki.hydrogenaud.io/index.php?title=APEv2_specification /* http://wiki.hydrogenaud.io/index.php?title=APEv2_specification
* Header/footer is 32 bytes: bytes 0-7 ident, bytes 8-11 version, * Header/footer is 32 bytes: bytes 0-7 ident, bytes 8-11 version,
* bytes 12-17 size. bytes 24-31 are reserved: must be all zeroes. */ * bytes 12-17 size. bytes 24-31 are reserved: must be all zeroes. */
@@ -121,13 +121,13 @@ static inline long get_lyrics3v2_len(const unsigned char *data, long length) {
if (length != 6) return 0; if (length != 6) return 0;
return strtol((const char *)data, NULL, 10) + 15; return strtol((const char *)data, NULL, 10) + 15;
} }
static inline qboolean verify_lyrics3v2(const unsigned char *data, long length) { static inline bool verify_lyrics3v2(const unsigned char *data, long length) {
if (length < 11) return false; if (length < 11) return false;
if (memcmp(data,"LYRICSBEGIN",11) == 0) return true; if (memcmp(data,"LYRICSBEGIN",11) == 0) return true;
return false; return false;
} }
#define MMTAG_PARANOID #define MMTAG_PARANOID
static qboolean is_musicmatch(const unsigned char *data, long length) { static bool is_musicmatch(const unsigned char *data, long length) {
/* From docs/musicmatch.txt in id3lib: https://sourceforge.net/projects/id3lib/ /* From docs/musicmatch.txt in id3lib: https://sourceforge.net/projects/id3lib/
Overall tag structure: Overall tag structure:
+2 -2
View File
@@ -55,7 +55,7 @@ static off_t mp3_seek (void *f, off_t offset, int whence)
return (off_t) FS_ftell((fshandle_t *)f); return (off_t) FS_ftell((fshandle_t *)f);
} }
static qboolean S_MP3_CodecInitialize (void) static bool S_MP3_CodecInitialize (void)
{ {
if (!mp3_codec.initialized) if (!mp3_codec.initialized)
{ {
@@ -78,7 +78,7 @@ static void S_MP3_CodecShutdown (void)
} }
} }
static qboolean S_MP3_CodecOpenStream (snd_stream_t *stream) static bool S_MP3_CodecOpenStream (snd_stream_t *stream)
{ {
long rate = 0; long rate = 0;
int encoding = 0, channels = 0; int encoding = 0, channels = 0;
+5 -5
View File
@@ -24,9 +24,9 @@
#include "quakedef.hpp" #include "quakedef.hpp"
#if defined(USE_CODEC_OPUS) #if defined(USE_CODEC_OPUS)
#include "snd_codec.h" #include "snd_codec.hpp"
#include "snd_codeci.h" #include "snd_codeci.hpp"
#include "snd_opus.h" #include "snd_opus.hpp"
#include <errno.h> #include <errno.h>
#include <opusfile.h> #include <opusfile.h>
@@ -74,7 +74,7 @@ static const OpusFileCallbacks opc_qfs =
(int (*)(void *)) opc_fclose (int (*)(void *)) opc_fclose
}; };
static qboolean S_OPUS_CodecInitialize (void) static bool S_OPUS_CodecInitialize (void)
{ {
return true; return true;
} }
@@ -83,7 +83,7 @@ static void S_OPUS_CodecShutdown (void)
{ {
} }
static qboolean S_OPUS_CodecOpenStream (snd_stream_t *stream) static bool S_OPUS_CodecOpenStream (snd_stream_t *stream)
{ {
OggOpusFile *opFile; OggOpusFile *opFile;
const OpusHead *op_info; const OpusHead *op_info;
+1 -1
View File
@@ -78,7 +78,7 @@ static void SDLCALL paint_audio (void *unused, Uint8 *stream, int len)
shm->samplepos = 0; shm->samplepos = 0;
} }
qboolean SNDDMA_Init (dma_t *dma) bool SNDDMA_Init (dma_t *dma)
{ {
SDL_AudioSpec desired; SDL_AudioSpec desired;
int tmp, val; int tmp, val;
+2 -2
View File
@@ -340,7 +340,7 @@ static int process_upkg (fshandle_t *f, int32_t *ofs, int32_t *objsize)
return probe_umx(f, &header, ofs, objsize); return probe_umx(f, &header, ofs, objsize);
} }
static qboolean S_UMX_CodecInitialize (void) static bool S_UMX_CodecInitialize (void)
{ {
return true; return true;
} }
@@ -349,7 +349,7 @@ static void S_UMX_CodecShutdown (void)
{ {
} }
static qboolean S_UMX_CodecOpenStream (snd_stream_t *stream) static bool S_UMX_CodecOpenStream (snd_stream_t *stream)
{ {
int type; int type;
int32_t ofs = 0, size = 0; int32_t ofs = 0, size = 0;
+5 -5
View File
@@ -24,9 +24,9 @@
#include "quakedef.hpp" #include "quakedef.hpp"
#if defined(USE_CODEC_VORBIS) #if defined(USE_CODEC_VORBIS)
#include "snd_codec.h" #include "snd_codec.hpp"
#include "snd_codeci.h" #include "snd_codeci.hpp"
#include "snd_vorbis.h" #include "snd_vorbis.hpp"
#define OV_EXCLUDE_STATIC_CALLBACKS #define OV_EXCLUDE_STATIC_CALLBACKS
#if defined(VORBIS_USE_TREMOR) #if defined(VORBIS_USE_TREMOR)
@@ -64,7 +64,7 @@ static ov_callbacks ovc_qfs =
(long (*)(void *)) FS_ftell (long (*)(void *)) FS_ftell
}; };
static qboolean S_VORBIS_CodecInitialize (void) static bool S_VORBIS_CodecInitialize (void)
{ {
return true; return true;
} }
@@ -73,7 +73,7 @@ static void S_VORBIS_CodecShutdown (void)
{ {
} }
static qboolean S_VORBIS_CodecOpenStream (snd_stream_t *stream) static bool S_VORBIS_CodecOpenStream (snd_stream_t *stream)
{ {
OggVorbis_File *ovFile; OggVorbis_File *ovFile;
vorbis_info *ovf_info; vorbis_info *ovf_info;
+3 -3
View File
@@ -110,7 +110,7 @@ static int WAV_FindRIFFChunk(FILE *f, const char *chunk)
WAV_ReadRIFFHeader WAV_ReadRIFFHeader
================= =================
*/ */
static qboolean WAV_ReadRIFFHeader(const char *name, FILE *file, snd_info_t *info) static bool WAV_ReadRIFFHeader(const char *name, FILE *file, snd_info_t *info)
{ {
char dump[16]; char dump[16];
int wav_format; int wav_format;
@@ -189,7 +189,7 @@ static qboolean WAV_ReadRIFFHeader(const char *name, FILE *file, snd_info_t *inf
S_WAV_CodecOpenStream S_WAV_CodecOpenStream
================= =================
*/ */
static qboolean S_WAV_CodecOpenStream(snd_stream_t *stream) static bool S_WAV_CodecOpenStream(snd_stream_t *stream)
{ {
long start = stream->fh.start; long start = stream->fh.start;
@@ -247,7 +247,7 @@ static int S_WAV_CodecRewindStream (snd_stream_t *stream)
return 0; return 0;
} }
static qboolean S_WAV_CodecInitialize (void) static bool S_WAV_CodecInitialize (void)
{ {
return true; return true;
} }
+2 -2
View File
@@ -34,7 +34,7 @@
#error libxmp version 4.2 or newer is required #error libxmp version 4.2 or newer is required
#endif #endif
static qboolean S_XMP_CodecInitialize (void) static bool S_XMP_CodecInitialize (void)
{ {
return true; return true;
} }
@@ -58,7 +58,7 @@ static long xmp_ftell(void *f)
} }
#endif #endif
static qboolean S_XMP_CodecOpenStream (snd_stream_t *stream) static bool S_XMP_CodecOpenStream (snd_stream_t *stream)
{ {
/* need to load the whole file into memory and pass it to libxmp /* need to load the whole file into memory and pass it to libxmp
* using xmp_load_module_from_memory() which requires libxmp >= 4.2. * using xmp_load_module_from_memory() which requires libxmp >= 4.2.
+113 -205
View File
@@ -21,6 +21,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/ */
// sv_main.c -- server main program // sv_main.c -- server main program
#include <cstring>
#include "quakedef.hpp" #include "quakedef.hpp"
server_t sv; server_t sv;
@@ -30,7 +32,7 @@ static char localmodels[MAX_MODELS][8]; // inline model names for precache
int sv_protocol = PROTOCOL_FITZQUAKE; //johnfitz int sv_protocol = PROTOCOL_FITZQUAKE; //johnfitz
extern qboolean pr_alpha_supported; //johnfitz extern bool pr_alpha_supported; //johnfitz
extern int pr_effects_mask; extern int pr_effects_mask;
//============================================================================ //============================================================================
@@ -40,12 +42,10 @@ extern int pr_effects_mask;
SV_Protocol_f SV_Protocol_f
=============== ===============
*/ */
void SV_Protocol_f (void) void SV_Protocol_f(void) {
{
int i; int i;
switch (command::argc()) switch (command::argc()) {
{
case 1: case 1:
Con_Printf("\"sv_protocol\" is \"%i\"\n", sv_protocol); Con_Printf("\"sv_protocol\" is \"%i\"\n", sv_protocol);
break; break;
@@ -53,8 +53,7 @@ void SV_Protocol_f (void)
i = atoi(command::argv(1)->c_str()); i = atoi(command::argv(1)->c_str());
if (i != PROTOCOL_NETQUAKE && i != PROTOCOL_FITZQUAKE && i != PROTOCOL_RMQ) 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); Con_Printf("sv_protocol must be %i or %i or %i\n", PROTOCOL_NETQUAKE, PROTOCOL_FITZQUAKE, PROTOCOL_RMQ);
else else {
{
sv_protocol = i; sv_protocol = i;
if (sv.active) if (sv.active)
Con_Printf("changes will not take effect until the next level load.\n"); Con_Printf("changes will not take effect until the next level load.\n");
@@ -71,9 +70,7 @@ void SV_Protocol_f (void)
SV_Init SV_Init
=============== ===============
*/ */
void SV_Init (void) void SV_Init(void) {
{
int i;
const char *p; const char *p;
extern convar sv_maxvelocity; extern convar sv_maxvelocity;
extern convar sv_gravity; extern convar sv_gravity;
@@ -108,14 +105,12 @@ void SV_Init (void)
command::add("sv_protocol", &SV_Protocol_f); //johnfitz command::add("sv_protocol", &SV_Protocol_f); //johnfitz
for (i=0 ; i<MAX_MODELS ; i++) for (auto i = 0; i < MAX_MODELS; i++)
sprintf(localmodels[i], "*%i", i); sprintf(localmodels[i], "*%i", i);
i = COM_CheckParm ("-protocol"); if (const auto i = common::check_param("-protocol"); i && i < com_argc - 1)
if (i && i < com_argc - 1) sv_protocol = atoi(com_argv[i.value() + 1]);
sv_protocol = atoi (com_argv[i + 1]); switch (sv_protocol) {
switch (sv_protocol)
{
case PROTOCOL_NETQUAKE: case PROTOCOL_NETQUAKE:
p = "NetQuake"; p = "NetQuake";
break; break;
@@ -148,8 +143,7 @@ SV_StartParticle
Make sure the event gets sent to all clients Make sure the event gets sent to all clients
================== ==================
*/ */
void SV_StartParticle (vec3_t org, vec3_t dir, int color, int count) void SV_StartParticle(vec3_t org, vec3_t dir, int color, int count) {
{
int i, v; int i, v;
if (sv.datagram.cursize > MAX_DATAGRAM - 18) if (sv.datagram.cursize > MAX_DATAGRAM - 18)
@@ -158,8 +152,7 @@ void SV_StartParticle (vec3_t org, vec3_t dir, int color, int count)
MSG_WriteCoord(&sv.datagram, org[0], sv.protocolflags); MSG_WriteCoord(&sv.datagram, org[0], sv.protocolflags);
MSG_WriteCoord(&sv.datagram, org[1], sv.protocolflags); MSG_WriteCoord(&sv.datagram, org[1], sv.protocolflags);
MSG_WriteCoord(&sv.datagram, org[2], sv.protocolflags); MSG_WriteCoord(&sv.datagram, org[2], sv.protocolflags);
for (i=0 ; i<3 ; i++) for (i = 0; i < 3; i++) {
{
v = dir[i] * 16; v = dir[i] * 16;
if (v > 127) if (v > 127)
v = 127; v = 127;
@@ -186,8 +179,7 @@ Larger attenuations will drop off. (max 4 attenuation)
================== ==================
*/ */
void SV_StartSound (edict_t *entity, int channel, const char *sample, int volume, float attenuation) void SV_StartSound(edict_t *entity, int channel, const char *sample, int volume, float attenuation) {
{
int sound_num, ent; int sound_num, ent;
int i, field_mask; int i, field_mask;
@@ -204,14 +196,12 @@ void SV_StartSound (edict_t *entity, int channel, const char *sample, int volume
return; return;
// find precache number for sound // find precache number for sound
for (sound_num = 1; sound_num < MAX_SOUNDS && sv.sound_precache[sound_num]; sound_num++) for (sound_num = 1; sound_num < MAX_SOUNDS && sv.sound_precache[sound_num]; sound_num++) {
{
if (!strcmp(sample, sv.sound_precache[sound_num])) if (!strcmp(sample, sv.sound_precache[sound_num]))
break; break;
} }
if (sound_num == MAX_SOUNDS || !sv.sound_precache[sound_num]) if (sound_num == MAX_SOUNDS || !sv.sound_precache[sound_num]) {
{
Con_Printf("SV_StartSound: %s not precached\n", sample); Con_Printf("SV_StartSound: %s not precached\n", sample);
return; return;
} }
@@ -225,14 +215,12 @@ void SV_StartSound (edict_t *entity, int channel, const char *sample, int volume
field_mask |= SND_ATTENUATION; field_mask |= SND_ATTENUATION;
//johnfitz -- PROTOCOL_FITZQUAKE //johnfitz -- PROTOCOL_FITZQUAKE
if (ent >= 8192) if (ent >= 8192) {
{
if (sv.protocol == PROTOCOL_NETQUAKE) if (sv.protocol == PROTOCOL_NETQUAKE)
return; //don't send any info protocol can't support return; //don't send any info protocol can't support
field_mask |= SND_LARGEENTITY; field_mask |= SND_LARGEENTITY;
} }
if (sound_num >= 256 || channel >= 8) if (sound_num >= 256 || channel >= 8) {
{
if (sv.protocol == PROTOCOL_NETQUAKE) if (sv.protocol == PROTOCOL_NETQUAKE)
return; //don't send any info protocol can't support return; //don't send any info protocol can't support
field_mask |= SND_LARGESOUND; field_mask |= SND_LARGESOUND;
@@ -251,12 +239,10 @@ void SV_StartSound (edict_t *entity, int channel, const char *sample, int volume
MSG_WriteByte(&sv.datagram, attenuation * 64); MSG_WriteByte(&sv.datagram, attenuation * 64);
//johnfitz -- PROTOCOL_FITZQUAKE //johnfitz -- PROTOCOL_FITZQUAKE
if (field_mask & SND_LARGEENTITY) if (field_mask & SND_LARGEENTITY) {
{
MSG_WriteShort(&sv.datagram, ent); MSG_WriteShort(&sv.datagram, ent);
MSG_WriteByte(&sv.datagram, channel); MSG_WriteByte(&sv.datagram, channel);
} } else
else
MSG_WriteShort(&sv.datagram, (ent << 3) | channel); MSG_WriteShort(&sv.datagram, (ent << 3) | channel);
if (field_mask & SND_LARGESOUND) if (field_mask & SND_LARGESOUND)
MSG_WriteShort(&sv.datagram, sound_num); MSG_WriteShort(&sv.datagram, sound_num);
@@ -265,7 +251,8 @@ void SV_StartSound (edict_t *entity, int channel, const char *sample, int volume
//johnfitz //johnfitz
for (i = 0; i < 3; i++) for (i = 0; i < 3; i++)
MSG_WriteCoord (&sv.datagram, entity->v.origin[i]+0.5*(entity->v.mins[i]+entity->v.maxs[i]), sv.protocolflags); MSG_WriteCoord(&sv.datagram, entity->v.origin[i] + 0.5 * (entity->v.mins[i] + entity->v.maxs[i]),
sv.protocolflags);
} }
/* /*
@@ -273,24 +260,20 @@ void SV_StartSound (edict_t *entity, int channel, const char *sample, int volume
SV_LocalSound - for 2021 rerelease SV_LocalSound - for 2021 rerelease
================== ==================
*/ */
void SV_LocalSound (client_t *client, const char *sample) void SV_LocalSound(client_t *client, const char *sample) {
{
int sound_num, field_mask; int sound_num, field_mask;
for (sound_num = 1; sound_num < MAX_SOUNDS && sv.sound_precache[sound_num]; sound_num++) for (sound_num = 1; sound_num < MAX_SOUNDS && sv.sound_precache[sound_num]; sound_num++) {
{
if (!strcmp(sample, sv.sound_precache[sound_num])) if (!strcmp(sample, sv.sound_precache[sound_num]))
break; break;
} }
if (sound_num == MAX_SOUNDS || !sv.sound_precache[sound_num]) if (sound_num == MAX_SOUNDS || !sv.sound_precache[sound_num]) {
{
Con_Printf("SV_LocalSound: %s not precached\n", sample); Con_Printf("SV_LocalSound: %s not precached\n", sample);
return; return;
} }
field_mask = 0; field_mask = 0;
if (sound_num >= 256) if (sound_num >= 256) {
{
if (sv.protocol == PROTOCOL_NETQUAKE) if (sv.protocol == PROTOCOL_NETQUAKE)
return; return;
field_mask = SND_LARGESOUND; field_mask = SND_LARGESOUND;
@@ -315,9 +298,8 @@ CLIENT SPAWNING
============================================================================== ==============================================================================
*/ */
static qboolean SV_IsLocalClient (client_t *client) static bool SV_IsLocalClient(client_t *client) {
{ return std::strcmp(NET_QSocketGetAddressString(client->netconnection), "LOCAL") == 0;
return Q_strcmp (NET_QSocketGetAddressString (client->netconnection), "LOCAL") == 0;
} }
/* /*
@@ -328,21 +310,20 @@ Sends the first message from the server to a connected client.
This will be sent on the initial connection and upon each server load. This will be sent on the initial connection and upon each server load.
================ ================
*/ */
void SV_SendServerinfo (client_t *client) void SV_SendServerinfo(client_t *client) {
{
const char **s; const char **s;
char message[2048]; char message[2048];
int i; //johnfitz int i; //johnfitz
MSG_WriteByte(&client->message, svc_print); MSG_WriteByte(&client->message, svc_print);
sprintf (message, "%c\nFITZQUAKE %1.2f SERVER (%i CRC)\n", 2, FITZQUAKE_VERSION, pr_crc); //johnfitz -- include fitzquake version sprintf(message, "%c\nFITZQUAKE %1.2f SERVER (%i CRC)\n", 2, FITZQUAKE_VERSION, pr_crc);
//johnfitz -- include fitzquake version
MSG_WriteString(&client->message, message); MSG_WriteString(&client->message, message);
MSG_WriteByte(&client->message, svc_serverinfo); MSG_WriteByte(&client->message, svc_serverinfo);
MSG_WriteLong(&client->message, sv.protocol); //johnfitz -- sv.protocol instead of PROTOCOL_VERSION MSG_WriteLong(&client->message, sv.protocol); //johnfitz -- sv.protocol instead of PROTOCOL_VERSION
if (sv.protocol == PROTOCOL_RMQ) if (sv.protocol == PROTOCOL_RMQ) {
{
// mh - now send protocol flags so that the client knows the protocol features to expect // mh - now send protocol flags so that the client knows the protocol features to expect
MSG_WriteLong(&client->message, sv.protocolflags); MSG_WriteLong(&client->message, sv.protocolflags);
} }
@@ -392,8 +373,7 @@ Initializes a client_t for a new net connection. This will only be called
once for a player each game, not once for each level change. once for a player each game, not once for each level change.
================ ================
*/ */
void SV_ConnectClient (int clientnum) void SV_ConnectClient(int clientnum) {
{
edict_t *ent; edict_t *ent;
client_t *client; client_t *client;
int edictnum; int edictnum;
@@ -427,8 +407,7 @@ void SV_ConnectClient (int clientnum)
if (sv.loadgame) if (sv.loadgame)
memcpy(client->spawn_parms, spawn_parms, sizeof(spawn_parms)); memcpy(client->spawn_parms, spawn_parms, sizeof(spawn_parms));
else else {
{
// call the progs to get default spawn parms for the new client // call the progs to get default spawn parms for the new client
PR_ExecuteProgram(pr_global_struct->SetNewParms); PR_ExecuteProgram(pr_global_struct->SetNewParms);
for (i = 0; i < NUM_SPAWN_PARMS; i++) for (i = 0; i < NUM_SPAWN_PARMS; i++)
@@ -445,16 +424,14 @@ SV_CheckForNewClients
=================== ===================
*/ */
void SV_CheckForNewClients (void) void SV_CheckForNewClients(void) {
{
struct qsocket_s *ret; struct qsocket_s *ret;
int i; int i;
// //
// check for new connections // check for new connections
// //
while (1) while (1) {
{
ret = NET_CheckNewConnections(); ret = NET_CheckNewConnections();
if (!ret) if (!ret)
break; break;
@@ -490,8 +467,7 @@ SV_ClearDatagram
================== ==================
*/ */
void SV_ClearDatagram (void) void SV_ClearDatagram(void) {
{
SZ_Clear(&sv.datagram); SZ_Clear(&sv.datagram);
} }
@@ -517,13 +493,10 @@ void SV_AddToFatPVS (vec3_t org, mnode_t *node, qmodel_t *worldmodel) //johnfitz
mplane_t *plane; mplane_t *plane;
float d; float d;
while (1) while (1) {
{
// if this is a leaf, accumulate the pvs bits // if this is a leaf, accumulate the pvs bits
if (node->contents < 0) if (node->contents < 0) {
{ if (node->contents != CONTENTS_SOLID) {
if (node->contents != CONTENTS_SOLID)
{
pvs = Mod_LeafPVS((mleaf_t *) node, worldmodel); //johnfitz -- worldmodel as a parameter pvs = Mod_LeafPVS((mleaf_t *) node, worldmodel); //johnfitz -- worldmodel as a parameter
for (i = 0; i < fatbytes; i++) for (i = 0; i < fatbytes; i++)
fatpvs[i] |= pvs[i]; fatpvs[i] |= pvs[i];
@@ -537,8 +510,8 @@ void SV_AddToFatPVS (vec3_t org, mnode_t *node, qmodel_t *worldmodel) //johnfitz
node = node->children[0]; node = node->children[0];
else if (d < -8) else if (d < -8)
node = node->children[1]; node = node->children[1];
else else {
{ // go down both // go down both
SV_AddToFatPVS(org, node->children[0], worldmodel); //johnfitz -- worldmodel as a parameter SV_AddToFatPVS(org, node->children[0], worldmodel); //johnfitz -- worldmodel as a parameter
node = node->children[1]; node = node->children[1];
} }
@@ -556,15 +529,14 @@ given point.
byte *SV_FatPVS(vec3_t org, qmodel_t *worldmodel) //johnfitz -- added worldmodel as a parameter byte *SV_FatPVS(vec3_t org, qmodel_t *worldmodel) //johnfitz -- added worldmodel as a parameter
{ {
fatbytes = (worldmodel->numleafs + 7) >> 3; // ericw -- was +31, assumed to be a bug/typo fatbytes = (worldmodel->numleafs + 7) >> 3; // ericw -- was +31, assumed to be a bug/typo
if (fatpvs == NULL || fatbytes > fatpvs_capacity) if (fatpvs == NULL || fatbytes > fatpvs_capacity) {
{
fatpvs_capacity = fatbytes; fatpvs_capacity = fatbytes;
fatpvs = (byte *) realloc(fatpvs, fatpvs_capacity); fatpvs = (byte *) realloc(fatpvs, fatpvs_capacity);
if (!fatpvs) if (!fatpvs)
Sys_Error("SV_FatPVS: realloc() failed on %d bytes", fatpvs_capacity); Sys_Error("SV_FatPVS: realloc() failed on %d bytes", fatpvs_capacity);
} }
Q_memset (fatpvs, 0, fatbytes); std::memset(fatpvs, 0, fatbytes);
SV_AddToFatPVS(org, worldmodel->nodes, worldmodel); //johnfitz -- worldmodel as a parameter SV_AddToFatPVS(org, worldmodel->nodes, worldmodel); //johnfitz -- worldmodel as a parameter
return fatpvs; return fatpvs;
} }
@@ -576,8 +548,7 @@ SV_VisibleToClient -- johnfitz
PVS test encapsulated in a nice function PVS test encapsulated in a nice function
============= =============
*/ */
qboolean SV_VisibleToClient (edict_t *client, edict_t *test, qmodel_t *worldmodel) bool SV_VisibleToClient(edict_t *client, edict_t *test, qmodel_t *worldmodel) {
{
byte *pvs; byte *pvs;
vec3_t org; vec3_t org;
int i; int i;
@@ -600,8 +571,7 @@ SV_WriteEntitiesToClient
============= =============
*/ */
void SV_WriteEntitiesToClient (edict_t *clent, sizebuf_t *msg) void SV_WriteEntitiesToClient(edict_t *clent, sizebuf_t *msg) {
{
int e, i; int e, i;
int bits; int bits;
byte *pvs; byte *pvs;
@@ -616,9 +586,7 @@ void SV_WriteEntitiesToClient (edict_t *clent, sizebuf_t *msg)
// send over all entities (excpet the client) that touch the pvs // send over all entities (excpet the client) that touch the pvs
ent = NEXT_EDICT(sv.edicts); ent = NEXT_EDICT(sv.edicts);
for (e=1 ; e<sv.num_edicts ; e++, ent = NEXT_EDICT(ent)) for (e = 1; e < sv.num_edicts; e++, ent = NEXT_EDICT(ent)) {
{
if (ent != clent) // clent is ALLWAYS sent if (ent != clent) // clent is ALLWAYS sent
{ {
// ignore ents without visible models // ignore ents without visible models
@@ -648,11 +616,9 @@ void SV_WriteEntitiesToClient (edict_t *clent, sizebuf_t *msg)
// assumed here. And, for protocol 85 the max size is actually 24 bytes. // assumed here. And, for protocol 85 the max size is actually 24 bytes.
// For float coords and angles the limit is 40. // For float coords and angles the limit is 40.
// FIXME: Use tighter limit according to protocol flags and send bits. // FIXME: Use tighter limit according to protocol flags and send bits.
if (msg->cursize + 40 > msg->maxsize) if (msg->cursize + 40 > msg->maxsize) {
{
//johnfitz -- less spammy overflow message //johnfitz -- less spammy overflow message
if (!dev_overflows.packetsize || dev_overflows.packetsize + CONSOLE_RESPAM_TIME < realtime ) if (!dev_overflows.packetsize || dev_overflows.packetsize + CONSOLE_RESPAM_TIME < realtime) {
{
Con_Printf("Packet overflow!\n"); Con_Printf("Packet overflow!\n");
dev_overflows.packetsize = realtime; dev_overflows.packetsize = realtime;
} }
@@ -663,8 +629,7 @@ void SV_WriteEntitiesToClient (edict_t *clent, sizebuf_t *msg)
// send an update // send an update
bits = 0; bits = 0;
for (i=0 ; i<3 ; i++) for (i = 0; i < 3; i++) {
{
miss = ent->v.origin[i] - ent->baseline.origin[i]; miss = ent->v.origin[i] - ent->baseline.origin[i];
if (miss < -0.1 || miss > 0.1) if (miss < -0.1 || miss > 0.1)
bits |= U_ORIGIN1 << i; bits |= U_ORIGIN1 << i;
@@ -698,8 +663,7 @@ void SV_WriteEntitiesToClient (edict_t *clent, sizebuf_t *msg)
bits |= U_MODEL; bits |= U_MODEL;
//johnfitz -- alpha //johnfitz -- alpha
if (pr_alpha_supported) if (pr_alpha_supported) {
{
// TODO: find a cleaner place to put this code // TODO: find a cleaner place to put this code
val = GetEdictFieldValue(ent, "alpha"); val = GetEdictFieldValue(ent, "alpha");
if (val) if (val)
@@ -718,9 +682,7 @@ void SV_WriteEntitiesToClient (edict_t *clent, sizebuf_t *msg)
ent->scale = ENTSCALE_DEFAULT; ent->scale = ENTSCALE_DEFAULT;
//johnfitz -- PROTOCOL_FITZQUAKE //johnfitz -- PROTOCOL_FITZQUAKE
if (sv.protocol != PROTOCOL_NETQUAKE) if (sv.protocol != PROTOCOL_NETQUAKE) {
{
if (ent->baseline.alpha != ent->alpha) bits |= U_ALPHA; if (ent->baseline.alpha != ent->alpha) bits |= U_ALPHA;
if (ent->baseline.scale != ent->scale) bits |= U_SCALE; if (ent->baseline.scale != ent->scale) bits |= U_SCALE;
if (bits & U_FRAME && (int) ent->v.frame & 0xFF00) bits |= U_FRAME2; if (bits & U_FRAME && (int) ent->v.frame & 0xFF00) bits |= U_FRAME2;
@@ -809,14 +771,12 @@ SV_CleanupEnts
============= =============
*/ */
void SV_CleanupEnts (void) void SV_CleanupEnts(void) {
{
int e; int e;
edict_t *ent; edict_t *ent;
ent = NEXT_EDICT(sv.edicts); ent = NEXT_EDICT(sv.edicts);
for (e=1 ; e<sv.num_edicts ; e++, ent = NEXT_EDICT(ent)) for (e = 1; e < sv.num_edicts; e++, ent = NEXT_EDICT(ent)) {
{
ent->v.effects = (int) ent->v.effects & ~EF_MUZZLEFLASH; ent->v.effects = (int) ent->v.effects & ~EF_MUZZLEFLASH;
} }
} }
@@ -827,8 +787,7 @@ SV_WriteClientdataToMessage
================== ==================
*/ */
void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg) void SV_WriteClientdataToMessage(edict_t *ent, sizebuf_t *msg) {
{
int bits; int bits;
int i; int i;
edict_t *other; edict_t *other;
@@ -838,8 +797,7 @@ void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg)
// //
// send a damage message // send a damage message
// //
if (ent->v.dmg_take || ent->v.dmg_save) if (ent->v.dmg_take || ent->v.dmg_save) {
{
other = PROG_TO_EDICT(ent->v.dmg_inflictor); other = PROG_TO_EDICT(ent->v.dmg_inflictor);
MSG_WriteByte(msg, svc_damage); MSG_WriteByte(msg, svc_damage);
MSG_WriteByte(msg, ent->v.dmg_save); MSG_WriteByte(msg, ent->v.dmg_save);
@@ -857,8 +815,7 @@ void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg)
SV_SetIdealPitch(); // how much to look up / down ideally SV_SetIdealPitch(); // how much to look up / down ideally
// a fixangle might get lost in a dropped packet. Oh well. // a fixangle might get lost in a dropped packet. Oh well.
if ( ent->v.fixangle ) if (ent->v.fixangle) {
{
MSG_WriteByte(msg, svc_setangle); MSG_WriteByte(msg, svc_setangle);
for (i = 0; i < 3; i++) for (i = 0; i < 3; i++)
MSG_WriteAngle(msg, ent->v.angles[i], sv.protocolflags); MSG_WriteAngle(msg, ent->v.angles[i], sv.protocolflags);
@@ -890,8 +847,7 @@ void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg)
if (ent->v.waterlevel >= 2) if (ent->v.waterlevel >= 2)
bits |= SU_INWATER; bits |= SU_INWATER;
for (i=0 ; i<3 ; i++) for (i = 0; i < 3; i++) {
{
if (ent->v.punchangle[i]) if (ent->v.punchangle[i])
bits |= (SU_PUNCH1 << i); bits |= (SU_PUNCH1 << i);
if (ent->v.velocity[i]) if (ent->v.velocity[i])
@@ -908,8 +864,7 @@ void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg)
bits |= SU_WEAPON; bits |= SU_WEAPON;
//johnfitz -- PROTOCOL_FITZQUAKE //johnfitz -- PROTOCOL_FITZQUAKE
if (sv.protocol != PROTOCOL_NETQUAKE) if (sv.protocol != PROTOCOL_NETQUAKE) {
{
if (bits & SU_WEAPON && SV_ModelIndex(PR_GetString(ent->v.weaponmodel)) & 0xFF00) bits |= SU_WEAPON2; if (bits & SU_WEAPON && SV_ModelIndex(PR_GetString(ent->v.weaponmodel)) & 0xFF00) bits |= SU_WEAPON2;
if ((int) ent->v.armorvalue & 0xFF00) bits |= SU_ARMOR2; if ((int) ent->v.armorvalue & 0xFF00) bits |= SU_ARMOR2;
if ((int) ent->v.currentammo & 0xFF00) bits |= SU_AMMO2; if ((int) ent->v.currentammo & 0xFF00) bits |= SU_AMMO2;
@@ -918,7 +873,8 @@ void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg)
if ((int) ent->v.ammo_rockets & 0xFF00) bits |= SU_ROCKETS2; if ((int) ent->v.ammo_rockets & 0xFF00) bits |= SU_ROCKETS2;
if ((int) ent->v.ammo_cells & 0xFF00) bits |= SU_CELLS2; if ((int) ent->v.ammo_cells & 0xFF00) bits |= SU_CELLS2;
if (bits & SU_WEAPONFRAME && (int) ent->v.weaponframe & 0xFF00) bits |= SU_WEAPONFRAME2; if (bits & SU_WEAPONFRAME && (int) ent->v.weaponframe & 0xFF00) bits |= SU_WEAPONFRAME2;
if (bits & SU_WEAPON && ent->alpha != ENTALPHA_DEFAULT) bits |= SU_WEAPONALPHA; //for now, weaponalpha = client entity alpha if (bits & SU_WEAPON && ent->alpha != ENTALPHA_DEFAULT) bits |= SU_WEAPONALPHA;
//for now, weaponalpha = client entity alpha
if (bits >= 65536) bits |= SU_EXTEND1; if (bits >= 65536) bits |= SU_EXTEND1;
if (bits >= 16777216) bits |= SU_EXTEND2; if (bits >= 16777216) bits |= SU_EXTEND2;
} }
@@ -940,8 +896,7 @@ void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg)
if (bits & SU_IDEALPITCH) if (bits & SU_IDEALPITCH)
MSG_WriteChar(msg, ent->v.idealpitch); MSG_WriteChar(msg, ent->v.idealpitch);
for (i=0 ; i<3 ; i++) for (i = 0; i < 3; i++) {
{
if (bits & (SU_PUNCH1 << i)) if (bits & (SU_PUNCH1 << i))
MSG_WriteChar(msg, ent->v.punchangle[i]); MSG_WriteChar(msg, ent->v.punchangle[i]);
if (bits & (SU_VELOCITY1 << i)) if (bits & (SU_VELOCITY1 << i))
@@ -965,16 +920,11 @@ void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg)
MSG_WriteByte(msg, ent->v.ammo_rockets); MSG_WriteByte(msg, ent->v.ammo_rockets);
MSG_WriteByte(msg, ent->v.ammo_cells); MSG_WriteByte(msg, ent->v.ammo_cells);
if (standard_quake) if (standard_quake) {
{
MSG_WriteByte(msg, ent->v.weapon); MSG_WriteByte(msg, ent->v.weapon);
} } else {
else for (i = 0; i < 32; i++) {
{ if (((int) ent->v.weapon) & (1 << i)) {
for(i=0;i<32;i++)
{
if ( ((int)ent->v.weapon) & (1<<i) )
{
MSG_WriteByte(msg, i); MSG_WriteByte(msg, i);
break; break;
} }
@@ -1008,8 +958,7 @@ void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg)
SV_SendClientDatagram SV_SendClientDatagram
======================= =======================
*/ */
qboolean SV_SendClientDatagram (client_t *client) bool SV_SendClientDatagram(client_t *client) {
{
byte buf[MAX_DATAGRAM]; byte buf[MAX_DATAGRAM];
sizebuf_t msg; sizebuf_t msg;
@@ -1018,7 +967,7 @@ qboolean SV_SendClientDatagram (client_t *client)
msg.cursize = 0; msg.cursize = 0;
//johnfitz -- if client is nonlocal, use smaller max size so packets aren't fragmented //johnfitz -- if client is nonlocal, use smaller max size so packets aren't fragmented
if (Q_strcmp(NET_QSocketGetAddressString(client->netconnection), "LOCAL") != 0) if (std::strcmp(NET_QSocketGetAddressString(client->netconnection), "LOCAL") != 0)
msg.maxsize = DATAGRAM_MTU; msg.maxsize = DATAGRAM_MTU;
//johnfitz //johnfitz
@@ -1035,8 +984,7 @@ qboolean SV_SendClientDatagram (client_t *client)
SZ_Write(&msg, sv.datagram.data, sv.datagram.cursize); SZ_Write(&msg, sv.datagram.data, sv.datagram.cursize);
// send the datagram // send the datagram
if (NET_SendUnreliableMessage (client->netconnection, &msg) == -1) if (NET_SendUnreliableMessage(client->netconnection, &msg) == -1) {
{
SV_DropClient(true); // if the message couldn't send, kick off SV_DropClient(true); // if the message couldn't send, kick off
return false; return false;
} }
@@ -1049,18 +997,14 @@ qboolean SV_SendClientDatagram (client_t *client)
SV_UpdateToReliableMessages SV_UpdateToReliableMessages
======================= =======================
*/ */
void SV_UpdateToReliableMessages (void) void SV_UpdateToReliableMessages(void) {
{
int i, j; int i, j;
client_t *client; client_t *client;
// check for changes to be sent over the reliable streams // check for changes to be sent over the reliable streams
for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++) for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) {
{ if (host_client->old_frags != host_client->edict->v.frags) {
if (host_client->old_frags != host_client->edict->v.frags) for (j = 0, client = svs.clients; j < svs.maxclients; j++, client++) {
{
for (j=0, client = svs.clients ; j<svs.maxclients ; j++, client++)
{
if (!client->active) if (!client->active)
continue; continue;
MSG_WriteByte(&client->message, svc_updatefrags); MSG_WriteByte(&client->message, svc_updatefrags);
@@ -1072,8 +1016,7 @@ void SV_UpdateToReliableMessages (void)
} }
} }
for (j=0, client = svs.clients ; j<svs.maxclients ; j++, client++) for (j = 0, client = svs.clients; j < svs.maxclients; j++, client++) {
{
if (!client->active) if (!client->active)
continue; continue;
SZ_Write(&client->message, sv.reliable_datagram.data, sv.reliable_datagram.cursize); SZ_Write(&client->message, sv.reliable_datagram.data, sv.reliable_datagram.cursize);
@@ -1091,8 +1034,7 @@ Send a nop message without trashing or sending the accumulated client
message buffer message buffer
======================= =======================
*/ */
void SV_SendNop (client_t *client) void SV_SendNop(client_t *client) {
{
sizebuf_t msg; sizebuf_t msg;
byte buf[4]; byte buf[4];
@@ -1112,42 +1054,34 @@ void SV_SendNop (client_t *client)
SV_SendClientMessages SV_SendClientMessages
======================= =======================
*/ */
void SV_SendClientMessages (void) void SV_SendClientMessages(void) {
{
int i; int i;
// update frags, names, etc // update frags, names, etc
SV_UpdateToReliableMessages(); SV_UpdateToReliableMessages();
// build individual updates // build individual updates
for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++) for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) {
{
if (!host_client->active) if (!host_client->active)
continue; continue;
if (host_client->spawned) if (host_client->spawned) {
{
if (!SV_SendClientDatagram(host_client)) if (!SV_SendClientDatagram(host_client))
continue; continue;
} } else {
else
{
// the player isn't totally in the game yet // the player isn't totally in the game yet
// send small keepalive messages if too much time has passed // send small keepalive messages if too much time has passed
// send a full message when the next signon stage has been requested // send a full message when the next signon stage has been requested
// some other message data (name changes, etc) may accumulate // some other message data (name changes, etc) may accumulate
// between signon stages // between signon stages
if (!host_client->sendsignon) if (!host_client->sendsignon) {
{
if (realtime - host_client->last_message > 5) if (realtime - host_client->last_message > 5)
SV_SendNop(host_client); SV_SendNop(host_client);
continue; // don't send out non-signon messages continue; // don't send out non-signon messages
} }
if (host_client->sendsignon == PRESPAWN_SIGNONBUFS) if (host_client->sendsignon == PRESPAWN_SIGNONBUFS) {
{ bool local = SV_IsLocalClient(host_client);
qboolean local = SV_IsLocalClient (host_client); while (host_client->signonidx < sv.num_signon_buffers) {
while (host_client->signonidx < sv.num_signon_buffers)
{
sizebuf_t *signon = sv.signon_buffers[host_client->signonidx]; sizebuf_t *signon = sv.signon_buffers[host_client->signonidx];
if (host_client->message.cursize + signon->cursize > host_client->message.maxsize) if (host_client->message.cursize + signon->cursize > host_client->message.maxsize)
break; break;
@@ -1162,10 +1096,8 @@ void SV_SendClientMessages (void)
if (host_client->signonidx == sv.num_signon_buffers) if (host_client->signonidx == sv.num_signon_buffers)
host_client->sendsignon = PRESPAWN_SIGNONMSG; host_client->sendsignon = PRESPAWN_SIGNONMSG;
} }
if (host_client->sendsignon == PRESPAWN_SIGNONMSG) if (host_client->sendsignon == PRESPAWN_SIGNONMSG) {
{ if (host_client->message.cursize + 2 < host_client->message.maxsize) {
if (host_client->message.cursize + 2 < host_client->message.maxsize)
{
MSG_WriteByte(&host_client->message, svc_signonnum); MSG_WriteByte(&host_client->message, svc_signonnum);
MSG_WriteByte(&host_client->message, 2); MSG_WriteByte(&host_client->message, 2);
host_client->sendsignon = PRESPAWN_FLUSH; host_client->sendsignon = PRESPAWN_FLUSH;
@@ -1176,25 +1108,21 @@ void SV_SendClientMessages (void)
// check for an overflowed message. Should only happen // check for an overflowed message. Should only happen
// on a very fucked up connection that backs up a lot, then // on a very fucked up connection that backs up a lot, then
// changes level // changes level
if (host_client->message.overflowed) if (host_client->message.overflowed) {
{
SV_DropClient(true); SV_DropClient(true);
host_client->message.overflowed = false; host_client->message.overflowed = false;
continue; continue;
} }
if (host_client->message.cursize || host_client->dropasap) if (host_client->message.cursize || host_client->dropasap) {
{ if (!NET_CanSendMessage(host_client->netconnection)) {
if (!NET_CanSendMessage (host_client->netconnection))
{
// I_Printf ("can't write\n"); // I_Printf ("can't write\n");
continue; continue;
} }
if (host_client->dropasap) if (host_client->dropasap)
SV_DropClient(false); // went to another level SV_DropClient(false); // went to another level
else else {
{
if (NET_SendMessage(host_client->netconnection if (NET_SendMessage(host_client->netconnection
, &host_client->message) == -1) , &host_client->message) == -1)
SV_DropClient(true); // if the message couldn't send, kick off SV_DropClient(true); // if the message couldn't send, kick off
@@ -1227,8 +1155,7 @@ SERVER SPAWNING
SV_AddSignonBuffer SV_AddSignonBuffer
================ ================
*/ */
static void SV_AddSignonBuffer (void) static void SV_AddSignonBuffer(void) {
{
sizebuf_t *sb; sizebuf_t *sb;
if (sv.num_signon_buffers >= MAX_SIGNON_BUFFERS) if (sv.num_signon_buffers >= MAX_SIGNON_BUFFERS)
Host_Error("SV_AddSignonBuffer overflow\n"); Host_Error("SV_AddSignonBuffer overflow\n");
@@ -1245,8 +1172,7 @@ static void SV_AddSignonBuffer (void)
SV_ReserveSignonSpace SV_ReserveSignonSpace
================ ================
*/ */
void SV_ReserveSignonSpace (int numbytes) void SV_ReserveSignonSpace(int numbytes) {
{
if (sv.signon->cursize + numbytes > sv.signon->maxsize) if (sv.signon->cursize + numbytes > sv.signon->maxsize)
SV_AddSignonBuffer(); SV_AddSignonBuffer();
} }
@@ -1257,8 +1183,7 @@ SV_ModelIndex
================ ================
*/ */
int SV_ModelIndex (const char *name) int SV_ModelIndex(const char *name) {
{
int i; int i;
if (!name || !name[0]) if (!name || !name[0])
@@ -1277,15 +1202,13 @@ int SV_ModelIndex (const char *name)
SV_CreateBaseline SV_CreateBaseline
================ ================
*/ */
void SV_CreateBaseline (void) void SV_CreateBaseline(void) {
{
int i; int i;
edict_t *svent; edict_t *svent;
int entnum; int entnum;
int bits; //johnfitz -- PROTOCOL_FITZQUAKE int bits; //johnfitz -- PROTOCOL_FITZQUAKE
for (entnum = 0; entnum < sv.num_edicts ; entnum++) for (entnum = 0; entnum < sv.num_edicts; entnum++) {
{
// get the current server version // get the current server version
svent = EDICT_NUM(entnum); svent = EDICT_NUM(entnum);
if (svent->free) if (svent->free)
@@ -1300,21 +1223,17 @@ void SV_CreateBaseline (void)
VectorCopy(svent->v.angles, svent->baseline.angles); VectorCopy(svent->v.angles, svent->baseline.angles);
svent->baseline.frame = svent->v.frame; svent->baseline.frame = svent->v.frame;
svent->baseline.skin = svent->v.skin; svent->baseline.skin = svent->v.skin;
if (entnum > 0 && entnum <= svs.maxclients) if (entnum > 0 && entnum <= svs.maxclients) {
{
svent->baseline.colormap = entnum; svent->baseline.colormap = entnum;
svent->baseline.modelindex = SV_ModelIndex("progs/player.mdl"); svent->baseline.modelindex = SV_ModelIndex("progs/player.mdl");
svent->baseline.alpha = ENTALPHA_DEFAULT; //johnfitz -- alpha support svent->baseline.alpha = ENTALPHA_DEFAULT; //johnfitz -- alpha support
svent->baseline.scale = ENTSCALE_DEFAULT; svent->baseline.scale = ENTSCALE_DEFAULT;
} } else {
else
{
svent->baseline.colormap = 0; svent->baseline.colormap = 0;
svent->baseline.modelindex = SV_ModelIndex(PR_GetString(svent->v.model)); svent->baseline.modelindex = SV_ModelIndex(PR_GetString(svent->v.model));
svent->baseline.alpha = svent->alpha; //johnfitz -- alpha support svent->baseline.alpha = svent->alpha; //johnfitz -- alpha support
svent->baseline.scale = ENTSCALE_DEFAULT; svent->baseline.scale = ENTSCALE_DEFAULT;
if (sv.protocol == PROTOCOL_RMQ) if (sv.protocol == PROTOCOL_RMQ) {
{
eval_t *val; eval_t *val;
val = GetEdictFieldValue(svent, "scale"); val = GetEdictFieldValue(svent, "scale");
if (val) if (val)
@@ -1332,8 +1251,7 @@ void SV_CreateBaseline (void)
svent->baseline.frame = 0; svent->baseline.frame = 0;
svent->baseline.alpha = ENTALPHA_DEFAULT; svent->baseline.alpha = ENTALPHA_DEFAULT;
svent->baseline.scale = ENTSCALE_DEFAULT; svent->baseline.scale = ENTSCALE_DEFAULT;
} } else //decide which extra data needs to be sent
else //decide which extra data needs to be sent
{ {
if (svent->baseline.modelindex & 0xFF00) if (svent->baseline.modelindex & 0xFF00)
bits |= B_LARGEMODEL; bits |= B_LARGEMODEL;
@@ -1377,8 +1295,7 @@ void SV_CreateBaseline (void)
MSG_WriteByte(sv.signon, svent->baseline.colormap); MSG_WriteByte(sv.signon, svent->baseline.colormap);
MSG_WriteByte(sv.signon, svent->baseline.skin); MSG_WriteByte(sv.signon, svent->baseline.skin);
for (i=0 ; i<3 ; i++) for (i = 0; i < 3; i++) {
{
MSG_WriteCoord(sv.signon, svent->baseline.origin[i], sv.protocolflags); MSG_WriteCoord(sv.signon, svent->baseline.origin[i], sv.protocolflags);
MSG_WriteAngle(sv.signon, svent->baseline.angles[i], sv.protocolflags); MSG_WriteAngle(sv.signon, svent->baseline.angles[i], sv.protocolflags);
} }
@@ -1401,8 +1318,7 @@ SV_SendReconnect
Tell all the clients that the server is changing levels Tell all the clients that the server is changing levels
================ ================
*/ */
void SV_SendReconnect (void) void SV_SendReconnect(void) {
{
byte data[128]; byte data[128];
sizebuf_t msg; sizebuf_t msg;
@@ -1427,14 +1343,12 @@ Grabs the current state of each client for saving across the
transition to another level transition to another level
================ ================
*/ */
void SV_SaveSpawnparms (void) void SV_SaveSpawnparms(void) {
{
int i, j; int i, j;
svs.serverflags = pr_global_struct->serverflags; svs.serverflags = pr_global_struct->serverflags;
for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++) for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) {
{
if (!host_client->active) if (!host_client->active)
continue; continue;
@@ -1455,8 +1369,8 @@ This is called at the start of each level
================ ================
*/ */
extern float scr_centertime_off; extern float scr_centertime_off;
void SV_SpawnServer (const char *server)
{ void SV_SpawnServer(const char *server) {
static char dummy[8] = {0, 0, 0, 0, 0, 0, 0, 0}; static char dummy[8] = {0, 0, 0, 0, 0, 0, 0, 0};
edict_t *ent; edict_t *ent;
int i, signonsize; int i, signonsize;
@@ -1472,8 +1386,7 @@ void SV_SpawnServer (const char *server)
// //
// tell all connected clients that we are going to a new level // tell all connected clients that we are going to a new level
// //
if (sv.active) if (sv.active) {
{
SV_SendReconnect(); SV_SendReconnect();
} }
@@ -1500,20 +1413,18 @@ void SV_SpawnServer (const char *server)
sv.protocol = sv_protocol; // johnfitz sv.protocol = sv_protocol; // johnfitz
if (sv.protocol == PROTOCOL_RMQ) if (sv.protocol == PROTOCOL_RMQ) {
{
// set up the protocol flags used by this server // set up the protocol flags used by this server
// (note - these could be cvar-ised so that server admins could choose the protocol features used by their servers) // (note - these could be cvar-ised so that server admins could choose the protocol features used by their servers)
sv.protocolflags = PRFL_INT32COORD | PRFL_SHORTANGLE; sv.protocolflags = PRFL_INT32COORD | PRFL_SHORTANGLE;
} } else sv.protocolflags = 0;
else sv.protocolflags = 0;
// load progs to get entity field count // load progs to get entity field count
PR_LoadProgs(); PR_LoadProgs();
// allocate server memory // allocate server memory
/* Host_ClearMemory() called above already cleared the whole sv structure */ /* Host_ClearMemory() called above already cleared the whole sv structure */
sv.max_edicts = CLAMP (MIN_EDICTS,(int)max_edicts.value,MAX_EDICTS); //johnfitz -- max_edicts cvar sv.max_edicts = std::clamp((int) max_edicts.value,MIN_EDICTS, MAX_EDICTS); //johnfitz -- max_edicts cvar
sv.edicts = (edict_t *) malloc(sv.max_edicts * pr_edict_size); // ericw -- sv.edicts switched to use malloc() sv.edicts = (edict_t *) malloc(sv.max_edicts * pr_edict_size); // ericw -- sv.edicts switched to use malloc()
sv.datagram.maxsize = sizeof(sv.datagram_buf); sv.datagram.maxsize = sizeof(sv.datagram_buf);
@@ -1529,8 +1440,7 @@ void SV_SpawnServer (const char *server)
// leave slots at start for clients only // leave slots at start for clients only
sv.num_edicts = svs.maxclients + 1; sv.num_edicts = svs.maxclients + 1;
memset(sv.edicts, 0, sv.num_edicts * pr_edict_size); // ericw -- sv.edicts switched to use malloc() memset(sv.edicts, 0, sv.num_edicts * pr_edict_size); // ericw -- sv.edicts switched to use malloc()
for (i=0 ; i<svs.maxclients ; i++) for (i = 0; i < svs.maxclients; i++) {
{
ent = EDICT_NUM(i + 1); ent = EDICT_NUM(i + 1);
svs.clients[i].edict = ent; svs.clients[i].edict = ent;
} }
@@ -1543,8 +1453,7 @@ void SV_SpawnServer (const char *server)
q_strlcpy(sv.name, server, sizeof(sv.name)); q_strlcpy(sv.name, server, sizeof(sv.name));
q_snprintf(sv.modelname, sizeof(sv.modelname), "maps/%s.bsp", server); q_snprintf(sv.modelname, sizeof(sv.modelname), "maps/%s.bsp", server);
sv.worldmodel = Mod_ForName(sv.modelname, false); sv.worldmodel = Mod_ForName(sv.modelname, false);
if (!sv.worldmodel) if (!sv.worldmodel) {
{
Con_Printf("Couldn't spawn server %s\n", sv.modelname); Con_Printf("Couldn't spawn server %s\n", sv.modelname);
sv.active = false; sv.active = false;
return; return;
@@ -1559,8 +1468,7 @@ void SV_SpawnServer (const char *server)
sv.sound_precache[0] = dummy; sv.sound_precache[0] = dummy;
sv.model_precache[0] = dummy; sv.model_precache[0] = dummy;
sv.model_precache[1] = sv.modelname; sv.model_precache[1] = sv.modelname;
for (i=1 ; i<sv.worldmodel->numsubmodels ; i++) for (i = 1; i < sv.worldmodel->numsubmodels; i++) {
{
sv.model_precache[1 + i] = localmodels[i]; sv.model_precache[1 + i] = localmodels[i];
sv.models[i + 1] = Mod_ForName(localmodels[i], false); sv.models[i + 1] = Mod_ForName(localmodels[i], false);
} }
@@ -1606,7 +1514,8 @@ void SV_SpawnServer (const char *server)
signonsize += sv.signon_buffers[i]->cursize; signonsize += sv.signon_buffers[i]->cursize;
if (signonsize > 64000 - 2) if (signonsize > 64000 - 2)
Con_DWarning("%i byte signon buffer exceeds QS limit of 63998.\n", signonsize); Con_DWarning("%i byte signon buffer exceeds QS limit of 63998.\n", signonsize);
else if (signonsize > 8000-2) //max size that will fit into 8000-sized client->message buffer with 2 extra bytes on the end else if (signonsize > 8000 - 2)
//max size that will fit into 8000-sized client->message buffer with 2 extra bytes on the end
Con_DWarning("%i byte signon buffer exceeds standard limit of 7998.\n", signonsize); Con_DWarning("%i byte signon buffer exceeds standard limit of 7998.\n", signonsize);
//johnfitz //johnfitz
@@ -1617,4 +1526,3 @@ void SV_SpawnServer (const char *server)
Con_DPrintf("Server spawned.\n"); Con_DPrintf("Server spawned.\n");
} }
+4 -4
View File
@@ -36,7 +36,7 @@ is not a staircase.
*/ */
int c_yes, c_no; int c_yes, c_no;
qboolean SV_CheckBottom (edict_t *ent) bool SV_CheckBottom (edict_t *ent)
{ {
vec3_t mins, maxs, start, stop; vec3_t mins, maxs, start, stop;
trace_t trace; trace_t trace;
@@ -109,7 +109,7 @@ possible, no move is done, false is returned, and
pr_global_struct->trace_normal is set to the normal of the blocking wall pr_global_struct->trace_normal is set to the normal of the blocking wall
============= =============
*/ */
qboolean SV_movestep (edict_t *ent, vec3_t move, qboolean relink) bool SV_movestep (edict_t *ent, vec3_t move, bool relink)
{ {
float dz; float dz;
vec3_t oldorg, neworg, end; vec3_t oldorg, neworg, end;
@@ -232,7 +232,7 @@ facing it.
====================== ======================
*/ */
void PF_changeyaw (void); void PF_changeyaw (void);
qboolean SV_StepDirection (edict_t *ent, float yaw, float dist) bool SV_StepDirection (edict_t *ent, float yaw, float dist)
{ {
vec3_t move, oldorigin; vec3_t move, oldorigin;
float delta; float delta;
@@ -370,7 +370,7 @@ SV_CloseEnough
====================== ======================
*/ */
qboolean SV_CloseEnough (edict_t *ent, edict_t *goal, float dist) bool SV_CloseEnough (edict_t *ent, edict_t *goal, float dist)
{ {
int i; int i;
+3 -3
View File
@@ -120,7 +120,7 @@ in a frame. Not used for pushmove objects, because they must be exact.
Returns false if the entity removed itself. Returns false if the entity removed itself.
============= =============
*/ */
qboolean SV_RunThink (edict_t *ent) bool SV_RunThink (edict_t *ent)
{ {
float thinktime; float thinktime;
@@ -660,7 +660,7 @@ void SV_CheckStuck (edict_t *ent)
SV_CheckWater SV_CheckWater
============= =============
*/ */
qboolean SV_CheckWater (edict_t *ent) bool SV_CheckWater (edict_t *ent)
{ {
vec3_t point; vec3_t point;
int cont; int cont;
@@ -1121,7 +1121,7 @@ will fall if the floor is pulled out from under them.
*/ */
void SV_Physics_Step (edict_t *ent) void SV_Physics_Step (edict_t *ent)
{ {
qboolean hitsound; bool hitsound;
// freefall if not onground // freefall if not onground
if ( ! ((int)ent->v.flags & (FL_ONGROUND | FL_FLY | FL_SWIM) ) ) if ( ! ((int)ent->v.flags & (FL_ONGROUND | FL_FLY | FL_SWIM) ) )
+2 -2
View File
@@ -36,7 +36,7 @@ float *angles;
float *origin; float *origin;
float *velocity; float *velocity;
qboolean onground; bool onground;
usercmd_t cmd; usercmd_t cmd;
@@ -479,7 +479,7 @@ SV_ReadClientMessage
Returns false if the client should be killed Returns false if the client should be killed
=================== ===================
*/ */
qboolean SV_ReadClientMessage (void) bool SV_ReadClientMessage (void)
{ {
int ret; int ret;
int ccmd; int ccmd;
+3 -3
View File
@@ -48,12 +48,12 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#endif #endif
qboolean isDedicated; bool isDedicated;
convar sys_throttle = {"sys_throttle", "0.02", {.archive = true}}; convar sys_throttle = {"sys_throttle", "0.02", {.archive = true}};
#define MAX_HANDLES 32 /* johnfitz -- was 10 */ #define MAX_HANDLES 32 /* johnfitz -- was 10 */
static FILE *sys_handles[MAX_HANDLES]; static FILE *sys_handles[MAX_HANDLES];
static qboolean stdinIsATTY; /* from ioquake3 source */ static bool stdinIsATTY; /* from ioquake3 source */
static int findhandle (void) static int findhandle (void)
@@ -460,7 +460,7 @@ double Sys_DoubleTime (void)
const char *Sys_ConsoleInput (void) const char *Sys_ConsoleInput (void)
{ {
static qboolean con_eof = false; static bool con_eof = false;
static char con_text[256]; static char con_text[256];
static int textlen; static int textlen;
char c; char c;
+2 -2
View File
@@ -45,8 +45,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#endif #endif
qboolean isDedicated; bool isDedicated;
qboolean Win95, Win95old, WinNT, WinVista; bool Win95, Win95old, WinNT, WinVista;
cvar_t sys_throttle = {"sys_throttle", "0.02", CVAR_ARCHIVE}; cvar_t sys_throttle = {"sys_throttle", "0.02", CVAR_ARCHIVE};
static HANDLE hinput, houtput; static HANDLE hinput, houtput;
+2 -2
View File
@@ -85,8 +85,8 @@ void VID_SyncCvars (void);
void VID_Toggle (void); void VID_Toggle (void);
void *VID_GetWindow (void); void *VID_GetWindow (void);
qboolean VID_HasMouseOrInputFocus (void); bool VID_HasMouseOrInputFocus (void);
qboolean VID_IsMinimized (void); bool VID_IsMinimized (void);
void VID_Lock (void); void VID_Lock (void);
#endif /* __VID_DEFS_H */ #endif /* __VID_DEFS_H */
+1 -1
View File
@@ -451,7 +451,7 @@ V_UpdateBlend -- johnfitz -- V_UpdatePalette cleaned up and renamed
*/ */
void V_UpdateBlend(void) { void V_UpdateBlend(void) {
int i, j; int i, j;
qboolean blend_changed; bool blend_changed;
V_CalcPowerupCshift(); V_CalcPowerupCshift();
+2 -2
View File
@@ -429,7 +429,7 @@ SV_LinkEdict
=============== ===============
*/ */
void SV_LinkEdict (edict_t *ent, qboolean touch_triggers) void SV_LinkEdict (edict_t *ent, bool touch_triggers)
{ {
areanode_t *node; areanode_t *node;
@@ -603,7 +603,7 @@ SV_RecursiveHullCheck
================== ==================
*/ */
qboolean SV_RecursiveHullCheck (hull_t *hull, int num, float p1f, float p2f, vec3_t p1, vec3_t p2, trace_t *trace) bool SV_RecursiveHullCheck (hull_t *hull, int num, float p1f, float p2f, vec3_t p1, vec3_t p2, trace_t *trace)
{ {
mclipnode_t *node; //johnfitz -- was dclipnode_t mclipnode_t *node; //johnfitz -- was dclipnode_t
mplane_t *plane; mplane_t *plane;
+5 -5
View File
@@ -31,9 +31,9 @@ typedef struct
typedef struct typedef struct
{ {
qboolean allsolid; // if true, plane is not valid bool allsolid; // if true, plane is not valid
qboolean startsolid; // if true, the initial point was in a solid area bool startsolid; // if true, the initial point was in a solid area
qboolean inopen, inwater; bool inopen, inwater;
float fraction; // time completed, 1.0 = didn't hit anything float fraction; // time completed, 1.0 = didn't hit anything
vec3_t endpos; // final position vec3_t endpos; // final position
plane_t plane; // surface normal at impact plane_t plane; // surface normal at impact
@@ -54,7 +54,7 @@ void SV_UnlinkEdict (edict_t *ent);
// so it doesn't clip against itself // so it doesn't clip against itself
// flags ent->v.modified // flags ent->v.modified
void SV_LinkEdict (edict_t *ent, qboolean touch_triggers); void SV_LinkEdict (edict_t *ent, bool touch_triggers);
// Needs to be called any time an entity changes origin, mins, maxs, or solid // Needs to be called any time an entity changes origin, mins, maxs, or solid
// flags ent->v.modified // flags ent->v.modified
// sets ent->v.absmin and ent->v.absmax // sets ent->v.absmin and ent->v.absmax
@@ -81,7 +81,7 @@ trace_t SV_Move (vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int type, e
// passedict is explicitly excluded from clipping checks (normally NULL) // passedict is explicitly excluded from clipping checks (normally NULL)
qboolean SV_RecursiveHullCheck (hull_t *hull, int num, float p1f, float p2f, vec3_t p1, vec3_t p2, trace_t *trace); bool SV_RecursiveHullCheck (hull_t *hull, int num, float p1f, float p2f, vec3_t p1, vec3_t p2, trace_t *trace);
#endif /* _QUAKE_WORLD_H */ #endif /* _QUAKE_WORLD_H */

Some files were not shown because too many files have changed in this diff Show More