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)
+297 -330
View File
@@ -26,84 +26,110 @@
#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 {
Con_Printf("music <musicfile>\n");
} }
else {
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)
bgmloop = false; bgmloop = false;
else if (q_strcasecmp(command::argv(1)->c_str(), "1") == 0 || else if (q_strcasecmp(command::argv(1)->c_str(), "1") == 0 ||
q_strcasecmp(command::argv(1)->c_str(),"on") == 0) q_strcasecmp(command::argv(1)->c_str(), "on") == 0)
bgmloop = true; bgmloop = true;
else if (q_strcasecmp(command::argv(1)->c_str(),"toggle") == 0) else if (q_strcasecmp(command::argv(1)->c_str(), "toggle") == 0)
bgmloop = !bgmloop; bgmloop = !bgmloop;
if (bgmstream) bgmstream->loop = bgmloop; if (bgmstream) bgmstream->loop = bgmloop;
@@ -113,288 +139,73 @@ static void BGM_Loop_f (void)
Con_Printf("Music will be looped\n"); Con_Printf("Music will be looped\n");
else else
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)
{
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 play_noext(const std::string &filename, const unsigned int allowed_types) {
}
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)
{
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); void update_stream() {
if (! *ext) /* try all things */ bool did_rewind = false;
{
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);
}
}
}
+17 -13
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 convar bgm_extmusic; extern bool bgmloop;
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 ();
+154 -170
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,9 +78,8 @@ 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;
@@ -118,49 +117,51 @@ void KeyUp (kbutton_t *b)
b->state |= 4; // impulse up b->state |= 4; // impulse up
} }
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_UpUp(void) {KeyUp(&in_up);}
void IN_DownDown(void) {KeyDown(&in_down);}
void IN_DownUp(void) {KeyUp(&in_down);}
void IN_LeftDown(void) {KeyDown(&in_left);}
void IN_LeftUp(void) {KeyUp(&in_left);}
void IN_RightDown(void) {KeyDown(&in_right);}
void IN_RightUp(void) {KeyUp(&in_right);}
void IN_ForwardDown(void) {KeyDown(&in_forward);}
void IN_ForwardUp(void) {KeyUp(&in_forward);}
void IN_BackDown(void) {KeyDown(&in_back);}
void IN_BackUp(void) {KeyUp(&in_back);}
void IN_LookupDown(void) {KeyDown(&in_lookup);}
void IN_LookupUp(void) {KeyUp(&in_lookup);}
void IN_LookdownDown(void) {KeyDown(&in_lookdown);}
void IN_LookdownUp(void) {KeyUp(&in_lookdown);}
void IN_MoveleftDown(void) {KeyDown(&in_moveleft);}
void IN_MoveleftUp(void) {KeyUp(&in_moveleft);}
void IN_MoverightDown(void) {KeyDown(&in_moveright);}
void IN_MoverightUp(void) {KeyUp(&in_moveright);}
void IN_SpeedDown(void) {KeyDown(&in_speed);} void IN_UpDown(void) { KeyDown(&in_up); }
void IN_SpeedUp(void) {KeyUp(&in_speed);} void IN_UpUp(void) { KeyUp(&in_up); }
void IN_StrafeDown(void) {KeyDown(&in_strafe);} void IN_DownDown(void) { KeyDown(&in_down); }
void IN_StrafeUp(void) {KeyUp(&in_strafe);} void IN_DownUp(void) { KeyUp(&in_down); }
void IN_LeftDown(void) { KeyDown(&in_left); }
void IN_LeftUp(void) { KeyUp(&in_left); }
void IN_RightDown(void) { KeyDown(&in_right); }
void IN_RightUp(void) { KeyUp(&in_right); }
void IN_ForwardDown(void) { KeyDown(&in_forward); }
void IN_ForwardUp(void) { KeyUp(&in_forward); }
void IN_BackDown(void) { KeyDown(&in_back); }
void IN_BackUp(void) { KeyUp(&in_back); }
void IN_LookupDown(void) { KeyDown(&in_lookup); }
void IN_LookupUp(void) { KeyUp(&in_lookup); }
void IN_LookdownDown(void) { KeyDown(&in_lookdown); }
void IN_LookdownUp(void) { KeyUp(&in_lookdown); }
void IN_MoveleftDown(void) { KeyDown(&in_moveleft); }
void IN_MoveleftUp(void) { KeyUp(&in_moveleft); }
void IN_MoverightDown(void) { KeyDown(&in_moveright); }
void IN_MoverightUp(void) { KeyUp(&in_moveright); }
void IN_AttackDown(void) {KeyDown(&in_attack);} void IN_SpeedDown(void) { KeyDown(&in_speed); }
void IN_AttackUp(void) {KeyUp(&in_attack);} void IN_SpeedUp(void) { KeyUp(&in_speed); }
void IN_StrafeDown(void) { KeyDown(&in_strafe); }
void IN_StrafeUp(void) { KeyUp(&in_strafe); }
void IN_UseDown (void) {KeyDown(&in_use);} void IN_AttackDown(void) { KeyDown(&in_attack); }
void IN_UseUp (void) {KeyUp(&in_use);} void IN_AttackUp(void) { KeyUp(&in_attack); }
void IN_JumpDown (void) {KeyDown(&in_jump);}
void IN_JumpUp (void) {KeyUp(&in_jump);}
void IN_Impulse (void) {in_impulse=Q_atoi(command::argv(1)->c_str());} void IN_UseDown(void) { KeyDown(&in_use); }
void IN_UseUp(void) { KeyUp(&in_use); }
void IN_JumpDown(void) { KeyDown(&in_jump); }
void IN_JumpUp(void) { KeyUp(&in_jump); }
void IN_Impulse(void) { in_impulse = 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
@@ -219,19 +215,19 @@ float CL_KeyState (kbutton_t *key)
//========================================================================== //==========================================================================
convar cl_upspeed{"cl_upspeed","200"}; convar cl_upspeed{"cl_upspeed", "200"};
convar cl_forwardspeed{"cl_forwardspeed","200", {.archive = true}}; convar cl_forwardspeed{"cl_forwardspeed", "200", {.archive = true}};
convar cl_backspeed{"cl_backspeed","200", {.archive = true}}; convar cl_backspeed{"cl_backspeed", "200", {.archive = true}};
convar cl_sidespeed{"cl_sidespeed","350"}; convar cl_sidespeed{"cl_sidespeed", "350"};
convar cl_movespeedkey{"cl_movespeedkey","2.0"}; convar cl_movespeedkey{"cl_movespeedkey", "2.0"};
convar cl_yawspeed{"cl_yawspeed","140"}; convar cl_yawspeed{"cl_yawspeed", "140"};
convar cl_pitchspeed{"cl_pitchspeed","150"}; convar cl_pitchspeed{"cl_pitchspeed", "150"};
convar cl_anglespeedkey{"cl_anglespeedkey","1.5"}; convar cl_anglespeedkey{"cl_anglespeedkey", "1.5"};
convar cl_alwaysrun{"cl_alwaysrun","0",{.archive = true}}; // QuakeSpasm -- new always run convar cl_alwaysrun{"cl_alwaysrun", "0", {.archive = true}}; // QuakeSpasm -- new always run
/* /*
================ ================
@@ -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,27 +245,25 @@ 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);
} }
up = CL_KeyState (&in_lookup); up = CL_KeyState(&in_lookup);
down = CL_KeyState(&in_lookdown); down = CL_KeyState(&in_lookdown);
cl.viewangles[PITCH] -= speed*cl_pitchspeed.value * up; cl.viewangles[PITCH] -= speed * cl_pitchspeed.value * up;
cl.viewangles[PITCH] += speed*cl_pitchspeed.value * down; cl.viewangles[PITCH] += speed * cl_pitchspeed.value * down;
if (up || down) if (up || down)
V_StopPitchDrift (); V_StopPitchDrift();
//johnfitz -- variable pitch clamping //johnfitz -- variable pitch clamping
if (cl.viewangles[PITCH] > cl_maxpitch.value) if (cl.viewangles[PITCH] > cl_maxpitch.value)
@@ -292,38 +285,34 @@ 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);
} }
cmd->sidemove += cl_sidespeed.value * CL_KeyState (&in_moveright); cmd->sidemove += cl_sidespeed.value * CL_KeyState(&in_moveright);
cmd->sidemove -= cl_sidespeed.value * CL_KeyState (&in_moveleft); cmd->sidemove -= cl_sidespeed.value * CL_KeyState(&in_moveleft);
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);
} }
// //
// 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;
@@ -349,31 +337,31 @@ void CL_SendMove (const usercmd_t *cmd)
cl.cmd = *cmd; cl.cmd = *cmd;
// //
// send the movement message // send the movement message
// //
MSG_WriteByte (&buf, clc_move); MSG_WriteByte(&buf, clc_move);
MSG_WriteFloat (&buf, cl.mtime[0]); // so server can get ping times MSG_WriteFloat(&buf, cl.mtime[0]); // so server can get ping times
for (i=0 ; i<3 ; i++) for (i = 0; i < 3; i++)
//johnfitz -- 16-bit angles for PROTOCOL_FITZQUAKE //johnfitz -- 16-bit angles for PROTOCOL_FITZQUAKE
if (cl.protocol == PROTOCOL_NETQUAKE) if (cl.protocol == PROTOCOL_NETQUAKE)
MSG_WriteAngle (&buf, cl.viewangles[i], cl.protocolflags); MSG_WriteAngle(&buf, cl.viewangles[i], cl.protocolflags);
else else
MSG_WriteAngle16 (&buf, cl.viewangles[i], cl.protocolflags); MSG_WriteAngle16(&buf, cl.viewangles[i], cl.protocolflags);
//johnfitz //johnfitz
MSG_WriteShort (&buf, cmd->forwardmove); MSG_WriteShort(&buf, cmd->forwardmove);
MSG_WriteShort (&buf, cmd->sidemove); MSG_WriteShort(&buf, cmd->sidemove);
MSG_WriteShort (&buf, cmd->upmove); MSG_WriteShort(&buf, cmd->upmove);
// //
// send button bits // send button bits
// //
bits = 0; bits = 0;
if ( in_attack.state & 3 ) if (in_attack.state & 3)
bits |= 1; bits |= 1;
in_attack.state &= ~2; in_attack.state &= ~2;
@@ -381,28 +369,27 @@ void CL_SendMove (const usercmd_t *cmd)
bits |= 2; bits |= 2;
in_jump.state &= ~2; in_jump.state &= ~2;
MSG_WriteByte (&buf, bits); MSG_WriteByte(&buf, bits);
MSG_WriteByte (&buf, in_impulse); MSG_WriteByte(&buf, in_impulse);
in_impulse = 0; in_impulse = 0;
// //
// deliver the message // deliver the message
// //
if (cls.demoplayback) if (cls.demoplayback)
return; return;
// //
// allways dump the first two message, because it may contain leftover inputs // allways dump the first two message, because it may contain leftover inputs
// from the last level // from the last level
// //
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,43 +398,40 @@ 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); command::add("-movedown", IN_DownUp);
command::add ("-movedown",IN_DownUp); command::add("+left", IN_LeftDown);
command::add ("+left",IN_LeftDown); command::add("-left", IN_LeftUp);
command::add ("-left",IN_LeftUp); command::add("+right", IN_RightDown);
command::add ("+right",IN_RightDown); command::add("-right", IN_RightUp);
command::add ("-right",IN_RightUp); command::add("+forward", IN_ForwardDown);
command::add ("+forward",IN_ForwardDown); command::add("-forward", IN_ForwardUp);
command::add ("-forward",IN_ForwardUp); command::add("+back", IN_BackDown);
command::add ("+back",IN_BackDown); command::add("-back", IN_BackUp);
command::add ("-back",IN_BackUp); command::add("+lookup", IN_LookupDown);
command::add ("+lookup", IN_LookupDown); command::add("-lookup", IN_LookupUp);
command::add ("-lookup", IN_LookupUp); command::add("+lookdown", IN_LookdownDown);
command::add ("+lookdown", IN_LookdownDown); command::add("-lookdown", IN_LookdownUp);
command::add ("-lookdown", IN_LookdownUp); command::add("+strafe", IN_StrafeDown);
command::add ("+strafe", IN_StrafeDown); command::add("-strafe", IN_StrafeUp);
command::add ("-strafe", IN_StrafeUp); command::add("+moveleft", IN_MoveleftDown);
command::add ("+moveleft", IN_MoveleftDown); command::add("-moveleft", IN_MoveleftUp);
command::add ("-moveleft", IN_MoveleftUp); command::add("+moveright", IN_MoverightDown);
command::add ("+moveright", IN_MoverightDown); command::add("-moveright", IN_MoverightUp);
command::add ("-moveright", IN_MoverightUp); command::add("+speed", IN_SpeedDown);
command::add ("+speed", IN_SpeedDown); command::add("-speed", IN_SpeedUp);
command::add ("-speed", IN_SpeedUp); command::add("+attack", IN_AttackDown);
command::add ("+attack", IN_AttackDown); command::add("-attack", IN_AttackUp);
command::add ("-attack", IN_AttackUp); command::add("+use", IN_UseDown);
command::add ("+use", IN_UseDown); command::add("-use", IN_UseUp);
command::add ("-use", IN_UseUp); command::add("+jump", IN_JumpDown);
command::add ("+jump", IN_JumpDown); command::add("-jump", IN_JumpUp);
command::add ("-jump", IN_JumpUp); command::add("impulse", IN_Impulse);
command::add ("impulse", IN_Impulse); command::add("+klook", IN_KLookDown);
command::add ("+klook", IN_KLookDown); 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);
} }
+230 -280
View File
@@ -31,19 +31,19 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
convar cl_name{"_cl_name", "player", {.archive = true}}; convar cl_name{"_cl_name", "player", {.archive = true}};
convar cl_color{"_cl_color", "0", {.archive = true}}; convar cl_color{"_cl_color", "0", {.archive = true}};
convar cl_shownet{"cl_shownet","0"}; // can be 0, 1, or 2 convar cl_shownet{"cl_shownet", "0"}; // can be 0, 1, or 2
convar cl_nolerp{"cl_nolerp","0"}; convar cl_nolerp{"cl_nolerp", "0"};
convar cfg_unbindall{"cfg_unbindall", "1", {.archive = true}}; convar cfg_unbindall{"cfg_unbindall", "1", {.archive = true}};
convar lookspring{"lookspring","0", {.archive = true}}; convar lookspring{"lookspring", "0", {.archive = true}};
convar lookstrafe{"lookstrafe","0", {.archive = true}}; convar lookstrafe{"lookstrafe", "0", {.archive = true}};
convar sensitivity{"sensitivity","3", {.archive = true}}; convar sensitivity{"sensitivity", "3", {.archive = true}};
convar m_pitch{"m_pitch","0.022", {.archive = true}}; convar m_pitch{"m_pitch", "0.022", {.archive = true}};
convar m_yaw{"m_yaw","0.022", {.archive = true}}; convar m_yaw{"m_yaw", "0.022", {.archive = true}};
convar m_forward{"m_forward","1", {.archive = true}}; convar m_forward{"m_forward", "1", {.archive = true}};
convar m_side{"m_side","0.8", {.archive = true}}; convar m_side{"m_side", "0.8", {.archive = true}};
convar cl_maxpitch{"cl_maxpitch", "90", {.archive = true}}; //johnfitz -- variable pitch clamping convar cl_maxpitch{"cl_maxpitch", "90", {.archive = true}}; //johnfitz -- variable pitch clamping
convar cl_minpitch{"cl_minpitch", "-90", {.archive = true}}; //johnfitz -- variable pitch clamping convar cl_minpitch{"cl_minpitch", "-90", {.archive = true}}; //johnfitz -- variable pitch clamping
@@ -71,25 +71,24 @@ CL_ClearState
===================== =====================
*/ */
void CL_ClearState (void) void CL_ClearState(void) {
{
if (!sv.active) if (!sv.active)
Host_ClearMemory (); Host_ClearMemory();
// wipe the entire cl structure // wipe the entire cl structure
memset (&cl, 0, sizeof(cl)); memset(&cl, 0, sizeof(cl));
SZ_Clear (&cls.message); SZ_Clear(&cls.message);
// clear other arrays // clear other arrays
memset (cl_dlights, 0, sizeof(cl_dlights)); memset(cl_dlights, 0, sizeof(cl_dlights));
memset (cl_lightstyle, 0, sizeof(cl_lightstyle)); memset(cl_lightstyle, 0, sizeof(cl_lightstyle));
memset (cl_temp_entities, 0, sizeof(cl_temp_entities)); memset(cl_temp_entities, 0, sizeof(cl_temp_entities));
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,30 +100,28 @@ 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();
Con_DPrintf ("Sending clc_disconnect\n"); Con_DPrintf("Sending clc_disconnect\n");
SZ_Clear (&cls.message); SZ_Clear(&cls.message);
MSG_WriteByte (&cls.message, clc_disconnect); MSG_WriteByte(&cls.message, clc_disconnect);
NET_SendUnreliableMessage (cls.netcon, &cls.message); NET_SendUnreliableMessage(cls.netcon, &cls.message);
SZ_Clear (&cls.message); SZ_Clear(&cls.message);
NET_Close (cls.netcon); NET_Close(cls.netcon);
cls.state = ca_disconnected; cls.state = ca_disconnected;
if (sv.active) if (sv.active)
@@ -134,14 +131,13 @@ void CL_Disconnect (void)
cls.demoplayback = cls.timedemo = false; cls.demoplayback = cls.timedemo = false;
cls.demopaused = false; cls.demopaused = false;
cl.intermission = 0; cl.intermission = 0;
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,25 +148,24 @@ 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;
if (cls.demoplayback) if (cls.demoplayback)
return; return;
CL_Disconnect (); CL_Disconnect();
cls.netcon = NET_Connect (host); cls.netcon = NET_Connect(host);
if (!cls.netcon) if (!cls.netcon)
Host_Error ("CL_Connect: connect failed"); Host_Error("CL_Connect: connect failed");
Con_DPrintf ("CL_EstablishConnection: connected to %s\n", host); Con_DPrintf("CL_EstablishConnection: connected to %s\n", host);
cls.demonum = -1; // not in the demo loop now cls.demonum = -1; // not in the demo loop now
cls.state = ca_connected; cls.state = ca_connected;
CL_ClearSignons (); // need all the signon messages before playing CL_ClearSignons(); // need all the signon messages before playing
MSG_WriteByte (&cls.message, clc_nop); // NAT Fix from ProQuake MSG_WriteByte(&cls.message, clc_nop); // NAT Fix from ProQuake
} }
/* /*
@@ -180,39 +175,38 @@ 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");
break; break;
case 2: case 2:
MSG_WriteByte (&cls.message, clc_stringcmd); MSG_WriteByte(&cls.message, clc_stringcmd);
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);
MSG_WriteString (&cls.message, str); MSG_WriteString(&cls.message, str);
break; break;
case 3: case 3:
MSG_WriteByte (&cls.message, clc_stringcmd); MSG_WriteByte(&cls.message, clc_stringcmd);
MSG_WriteString (&cls.message, "begin"); MSG_WriteString(&cls.message, "begin");
Cache_Report (); // print remaining memory Cache_Report(); // print remaining memory
break; break;
case 4: case 4:
SCR_EndLoadingPlaque (); // allow normal screen updates SCR_EndLoadingPlaque(); // allow normal screen updates
break; break;
} }
} }
@@ -224,29 +218,26 @@ 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();
return; return;
} }
} }
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,20 +271,16 @@ 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
return dl; return dl;
@@ -303,13 +288,11 @@ 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
return dl; return dl;
@@ -317,7 +300,7 @@ dlight_t *CL_AllocDlight (int key)
} }
dl = &cl_dlights[0]; dl = &cl_dlights[0];
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
return dl; return dl;
@@ -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,12 +321,11 @@ 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;
dl->radius -= time*dl->decay; dl->radius -= time * dl->decay;
if (dl->radius < 0) if (dl->radius < 0)
dl->radius = 0; dl->radius = 0;
} }
@@ -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;
@@ -415,39 +390,36 @@ void CL_RelinkEntities (void)
vec3_t oldorg; vec3_t oldorg;
dlight_t *dl; dlight_t *dl;
// determine partial update time // determine partial update time
frac = CL_LerpPoint (); frac = CL_LerpPoint();
cl_numvisedicts = 0; cl_numvisedicts = 0;
// //
// interpolate player info // interpolate player info
// //
for (i=0 ; i<3 ; i++) for (i = 0; i < 3; i++)
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;
else if (d < -180) else if (d < -180)
d += 360; d += 360;
cl.viewangles[j] = cl.mviewangles[1][j] + frac*d; cl.viewangles[j] = cl.mviewangles[1][j] + frac * d;
} }
} }
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.
@@ -456,30 +428,27 @@ void CL_RelinkEntities (void)
continue; continue;
} }
// 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,80 +460,73 @@ 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];
if (d > 180) if (d > 180)
d -= 360; d -= 360;
else if (d < -180) else if (d < -180)
d += 360; d += 360;
ent->angles[j] = ent->msg_angles[1][j] + f*d; ent->angles[j] = ent->msg_angles[1][j] + f * d;
} }
} }
// rotate binary objects locally // rotate binary objects locally
if (ent->model->flags & EF_ROTATE) if (ent->model->flags & EF_ROTATE)
ent->angles[1] = bobjrotate; ent->angles[1] = bobjrotate;
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);
VectorCopy (ent->origin, dl->origin); VectorCopy(ent->origin, dl->origin);
dl->origin[2] += 16; dl->origin[2] += 16;
AngleVectors (ent->angles, fv, rv, uv); AngleVectors(ent->angles, fv, rv, uv);
VectorMA (dl->origin, 18, fv, dl->origin); VectorMA(dl->origin, 18, fv, dl->origin);
dl->radius = 200 + (rand()&31); dl->radius = 200 + (rand() & 31);
dl->minlight = 32; dl->minlight = 32;
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
ent->lerpflags |= LERP_RESETANIM|LERP_RESETANIM2; //no lerping for two frames ent->lerpflags |= LERP_RESETANIM | LERP_RESETANIM2; //no lerping for two frames
} }
//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);
dl->die = cl.time + 0.001; dl->die = cl.time + 0.001;
dl->color[0] = 0.25f; dl->color[0] = 0.25f;
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);
dl->die = cl.time + 0.001; dl->die = cl.time + 0.001;
dl->color[0] = 1.0f; dl->color[0] = 1.0f;
dl->color[1] = 0.25f; dl->color[1] = 0.25f;
@@ -572,33 +534,30 @@ void CL_RelinkEntities (void)
} }
if (ent->model->flags & EF_GIB) if (ent->model->flags & EF_GIB)
R_RocketTrail (oldorg, ent->origin, 2); R_RocketTrail(oldorg, ent->origin, 2);
else if (ent->model->flags & EF_ZOMGIB) else if (ent->model->flags & EF_ZOMGIB)
R_RocketTrail (oldorg, ent->origin, 4); R_RocketTrail(oldorg, ent->origin, 4);
else if (ent->model->flags & EF_TRACER) else if (ent->model->flags & EF_TRACER)
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);
ent->forcelink = false; ent->forcelink = false;
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,61 +585,61 @@ 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");
if (!ret) if (!ret)
break; break;
cl.last_received_message = realtime; cl.last_received_message = realtime;
CL_ParseServerMessage (); CL_ParseServerMessage();
} while (ret && cls.state == ca_connected); } while (ret && cls.state == ca_connected);
if (cl_shownet.value) if (cl_shownet.value)
Con_Printf ("\n"); Con_Printf("\n");
CL_RelinkEntities (); CL_RelinkEntities();
CL_UpdateTEnts (); CL_UpdateTEnts();
//johnfitz -- devstats //johnfitz -- devstats
//visedicts //visedicts
if (cl_numvisedicts > 256 && dev_peakstats.visedicts <= 256) if (cl_numvisedicts > 256 && dev_peakstats.visedicts <= 256)
Con_DWarning ("%i visedicts exceeds standard limit of 256 (max = %d).\n", cl_numvisedicts, MAX_VISEDICTS); Con_DWarning("%i visedicts exceeds standard limit of 256 (max = %d).\n", cl_numvisedicts, MAX_VISEDICTS);
dev_stats.visedicts = cl_numvisedicts; dev_stats.visedicts = cl_numvisedicts;
dev_peakstats.visedicts = std::max(cl_numvisedicts, dev_peakstats.visedicts); dev_peakstats.visedicts = std::max(cl_numvisedicts, dev_peakstats.visedicts);
//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);
//beams //beams
for (i=0, b=cl_beams ; i< MAX_BEAMS ; i++, b++) for (i = 0, b = cl_beams; i < MAX_BEAMS; i++, b++)
if (b->model && b->endtime >= cl.time) if (b->model && b->endtime >= cl.time)
num_beams++; num_beams++;
if (num_beams > 24 && dev_peakstats.beams <= 24) if (num_beams > 24 && dev_peakstats.beams <= 24)
Con_DWarning ("%i beams exceeded standard limit of 24 (max = %d).\n", num_beams, MAX_BEAMS); Con_DWarning("%i beams exceeded standard limit of 24 (max = %d).\n", num_beams, MAX_BEAMS);
dev_stats.beams = num_beams; dev_stats.beams = num_beams;
dev_peakstats.beams = std::max(num_beams, dev_peakstats.beams); dev_peakstats.beams = std::max(num_beams, dev_peakstats.beams);
//dlights //dlights
for (i=0, l=cl_dlights ; i<MAX_DLIGHTS ; i++, l++) for (i = 0, l = cl_dlights; i < MAX_DLIGHTS; i++, l++)
if (l->die >= cl.time && l->radius) if (l->die >= cl.time && l->radius)
num_dlights++; num_dlights++;
if (num_dlights > 32 && dev_peakstats.dlights <= 32) if (num_dlights > 32 && dev_peakstats.dlights <= 32)
Con_DWarning ("%i dlights exceeded standard limit of 32 (max = %d).\n", num_dlights, MAX_DLIGHTS); Con_DWarning("%i dlights exceeded standard limit of 32 (max = %d).\n", num_dlights, MAX_DLIGHTS);
dev_stats.dlights = num_dlights; dev_stats.dlights = num_dlights;
dev_peakstats.dlights = std::max(num_dlights, dev_peakstats.dlights); dev_peakstats.dlights = std::max(num_dlights, dev_peakstats.dlights);
//johnfitz //johnfitz
// //
// bring the links up to date // bring the links up to date
// //
return 0; return 0;
} }
@@ -690,45 +648,41 @@ 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);
// allow mice or other external controllers to add to the move // allow mice or other external controllers to add to the move
IN_Move (&cmd); IN_Move(&cmd);
// send the unreliable message // send the unreliable message
CL_SendMove (&cmd); CL_SendMove(&cmd);
} }
if (cls.demoplayback) if (cls.demoplayback) {
{ SZ_Clear(&cls.message);
SZ_Clear (&cls.message);
return; return;
} }
// send the reliable message // send the reliable message
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;
} }
if (NET_SendMessage (cls.netcon, &cls.message) == -1) if (NET_SendMessage(cls.netcon, &cls.message) == -1)
Host_Error ("CL_SendCmd: lost server connection"); Host_Error("CL_SendCmd: lost server connection");
SZ_Clear (&cls.message); SZ_Clear(&cls.message);
} }
/* /*
@@ -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)
@@ -749,9 +702,9 @@ void CL_Tracepos_f (void)
TraceLine(r_refdef.vieworg, v, w); TraceLine(r_refdef.vieworg, v, w);
if (VectorLength(w) == 0) if (VectorLength(w) == 0)
Con_Printf ("Tracepos: trace didn't hit anything\n"); Con_Printf("Tracepos: trace didn't hit anything\n");
else else
Con_Printf ("Tracepos: (%i %i %i)\n", (int)w[0], (int)w[1], (int)w[2]); Con_Printf("Tracepos: (%i %i %i)\n", (int) w[0], (int) w[1], (int) w[2]);
} }
/* /*
@@ -761,28 +714,27 @@ 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
//camera position //camera position
Con_Printf ("Viewpos: (%i %i %i) %i %i %i\n", Con_Printf("Viewpos: (%i %i %i) %i %i %i\n",
(int)r_refdef.vieworg[0], (int) r_refdef.vieworg[0],
(int)r_refdef.vieworg[1], (int) r_refdef.vieworg[1],
(int)r_refdef.vieworg[2], (int) r_refdef.vieworg[2],
(int)r_refdef.viewangles[PITCH], (int) r_refdef.viewangles[PITCH],
(int)r_refdef.viewangles[YAW], (int) r_refdef.viewangles[YAW],
(int)r_refdef.viewangles[ROLL]); (int) r_refdef.viewangles[ROLL]);
#else #else
//player position //player position
Con_Printf ("Viewpos: (%i %i %i) %i %i %i\n", Con_Printf("Viewpos: (%i %i %i) %i %i %i\n",
(int)cl_entities[cl.viewentity].origin[0], (int) cl_entities[cl.viewentity].origin[0],
(int)cl_entities[cl.viewentity].origin[1], (int) cl_entities[cl.viewentity].origin[1],
(int)cl_entities[cl.viewentity].origin[2], (int) cl_entities[cl.viewentity].origin[2],
(int)cl.viewangles[PITCH], (int) cl.viewangles[PITCH],
(int)cl.viewangles[YAW], (int) cl.viewangles[YAW],
(int)cl.viewangles[ROLL]); (int) cl.viewangles[ROLL]);
#endif #endif
} }
@@ -791,12 +743,11 @@ 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();
CL_InitTEnts (); CL_InitTEnts();
cl_name.inscribe(); cl_name.inscribe();
cl_color.inscribe(); cl_color.inscribe();
@@ -828,14 +779,13 @@ void CL_Init (void)
cl_startdemos.inscribe(); cl_startdemos.inscribe();
command::add ("entities", CL_PrintEntities_f); command::add("entities", CL_PrintEntities_f);
command::add ("disconnect", CL_Disconnect_f); command::add("disconnect", CL_Disconnect_f);
command::add ("record", CL_Record_f); command::add("record", CL_Record_f);
command::add ("stop", CL_Stop_f); command::add("stop", CL_Stop_f);
command::add ("playdemo", CL_PlayDemo_f); command::add("playdemo", CL_PlayDemo_f);
command::add ("timedemo", CL_TimeDemo_f); command::add("timedemo", CL_TimeDemo_f);
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
+70 -212
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);
}
/*
============
Cbuf_InsertText
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);
} }
}
/* void insert_text(const std::string &text) {
============ if (_buffer.length() + text.length() >= MAX_BUFFER_SIZE) {
Cbuf_Execute Con_Printf("command::buffer::insert_text(): overflow\n");
============ return;
*/ }
void Cbuf_Execute(void) {
int i;
char *text;
char line[1024];
int quotes;
while (cmd_text.cursize) { _buffer = text + _buffer;
// find a \n or ; line break }
text = (char *) cmd_text.data;
quotes = 0; void execute() {
for (i = 0; i < cmd_text.cursize; i++) { while (!_buffer.empty()) {
if (text[i] == '"') std::string line{};
auto quotes = 0;
for (const auto c: _buffer) {
if (c == '"') {
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 */
+293 -393
View File
File diff suppressed because it is too large Load Diff
+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;
+253 -311
View File
File diff suppressed because it is too large Load Diff
+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);
+306 -364
View File
File diff suppressed because it is too large Load Diff
+607 -844
View File
File diff suppressed because it is too large Load Diff
+148 -188
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,19 +76,18 @@ 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);
COM_FOpenFile (loadfilename, &f, NULL); COM_FOpenFile(loadfilename, &f, NULL);
if (f) if (f)
return Image_LoadTGA (f, width, height); return Image_LoadTGA(f, width, height);
q_snprintf (loadfilename, sizeof(loadfilename), "%s.pcx", name); q_snprintf(loadfilename, sizeof(loadfilename), "%s.pcx", name);
COM_FOpenFile (loadfilename, &f, NULL); COM_FOpenFile(loadfilename, &f, NULL);
if (f) if (f)
return Image_LoadPCX (f, width, height); return Image_LoadPCX(f, width, height);
return NULL; return NULL;
} }
@@ -111,18 +108,16 @@ 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);
b2 = fgetc(f); b2 = fgetc(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);
@@ -130,7 +125,7 @@ int fgetLittleLong (FILE *f)
b3 = fgetc(f); b3 = fgetc(f);
b4 = fgetc(f); b4 = fgetc(f);
return b1 + (b2<<8) + (b3<<16) + (b4<<24); return b1 + (b2 << 8) + (b3 << 16) + (b4 << 24);
} }
/* /*
@@ -142,41 +137,39 @@ 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];
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);
handle = Sys_FileOpenWrite (pathname); handle = Sys_FileOpenWrite(pathname);
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;
header[14] = height&255; header[14] = height & 255;
header[15] = height>>8; header[15] = height >> 8;
header[16] = bpp; // pixel size header[16] = bpp; // pixel size
if (upsidedown) if (upsidedown)
header[17] = 0x20; //upside-down attribute header[17] = 0x20; //upside-down attribute
// 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;
} }
Sys_FileWrite (handle, header, TARGAHEADERSIZE); Sys_FileWrite(handle, header, TARGAHEADERSIZE);
Sys_FileWrite (handle, data, size); Sys_FileWrite(handle, data, size);
Sys_FileClose (handle); Sys_FileClose(handle);
return true; return true;
} }
@@ -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,18 +203,15 @@ 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)
{ Sys_Error("Image_LoadTGA: %s is not a type 2 or type 10 targa (%i)", loadfilename, targa_header.image_type);
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);
if (targa_header.colormap_type !=0 || (targa_header.pixel_size!=32 && targa_header.pixel_size!=24)) if (targa_header.colormap_type != 0 || (targa_header.pixel_size != 32 && targa_header.pixel_size != 24))
Sys_Error ("Image_LoadTGA: %s is not a 24bit or 32bit targa", loadfilename); Sys_Error("Image_LoadTGA: %s is not a 24bit or 32bit targa", loadfilename);
} }
columns = targa_header.width; columns = targa_header.width;
@@ -230,55 +219,49 @@ byte *Image_LoadTGA (FILE *fin, int *width, int *height)
numPixels = columns * rows; numPixels = columns * rows;
upside_down = !(targa_header.attributes & 0x20); //johnfitz -- fix for upside-down targas upside_down = !(targa_header.attributes & 0x20); //johnfitz -- fix for upside-down targas
targa_rgba = (byte *) Hunk_Alloc (numPixels*4); targa_rgba = (byte *) Hunk_Alloc(numPixels * 4);
if (targa_header.id_length != 0) if (targa_header.id_length != 0)
fseek(fin, targa_header.id_length, SEEK_CUR); // skip TARGA image comment fseek(fin, targa_header.id_length, SEEK_CUR); // skip TARGA image comment
buf = Buf_Alloc(fin); buf = Buf_Alloc(fin);
if (targa_header.image_type==1) // Uncompressed, paletted images if (targa_header.image_type == 1) // Uncompressed, paletted images
{ {
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);
palette[i*3+3] = 255; palette[i * 3 + 3] = 255;
} }
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];
*pixbuf++= palette[i*3+2]; *pixbuf++ = palette[i * 3 + 2];
*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;
for(row=rows-1; row>=0; row--)
{ {
unsigned char red, green, blue, alphabyte, packetHeader, packetSize, j;
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,33 +314,29 @@ 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; *pixbuf++ = alphabyte;
*pixbuf++=alphabyte;
column++; column++;
if (column==columns) // run spans across rows if (column == columns) // run spans across rows
{ {
column=0; column = 0;
if (row>0) if (row > 0)
row--; row--;
else else
goto breakOut; goto breakOut;
//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
} }
} }
} } 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);
@@ -385,16 +360,16 @@ byte *Image_LoadTGA (FILE *fin, int *width, int *height)
blue = red = green = alphabyte = 0; blue = red = green = alphabyte = 0;
} }
column++; column++;
if (column==columns) // pixel packet run spans across rows if (column == columns) // pixel packet run spans across rows
{ {
column=0; column = 0;
if (row>0) if (row > 0)
row--; row--;
else else
goto breakOut; goto breakOut;
//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
} }
} }
@@ -407,8 +382,8 @@ byte *Image_LoadTGA (FILE *fin, int *width, int *height)
Buf_Free(buf); Buf_Free(buf);
fclose(fin); fclose(fin);
*width = (int)(targa_header.width); *width = (int) (targa_header.width);
*height = (int)(targa_header.height); *height = (int) (targa_header.height);
return targa_rgba; return targa_rgba;
} }
@@ -418,14 +393,13 @@ 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;
char bits_per_pixel; char bits_per_pixel;
unsigned short xmin,ymin,xmax,ymax; unsigned short xmin, ymin, xmax, ymax;
unsigned short hdpi,vdpi; unsigned short hdpi, vdpi;
byte colortable[48]; byte colortable[48];
char reserved; char reserved;
char color_planes; char color_planes;
@@ -439,69 +413,65 @@ 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);
pcx.xmin = (unsigned short)LittleShort (pcx.xmin); pcx.xmin = (unsigned short) LittleShort(pcx.xmin);
pcx.ymin = (unsigned short)LittleShort (pcx.ymin); pcx.ymin = (unsigned short) LittleShort(pcx.ymin);
pcx.xmax = (unsigned short)LittleShort (pcx.xmax); pcx.xmax = (unsigned short) LittleShort(pcx.xmax);
pcx.ymax = (unsigned short)LittleShort (pcx.ymax); pcx.ymax = (unsigned short) LittleShort(pcx.ymax);
pcx.bytes_per_line = (unsigned short)LittleShort (pcx.bytes_per_line); pcx.bytes_per_line = (unsigned short) LittleShort(pcx.bytes_per_line);
if (pcx.signature != 0x0A) if (pcx.signature != 0x0A)
Sys_Error ("'%s' is not a valid PCX file", loadfilename); Sys_Error("'%s' is not a valid PCX file", loadfilename);
if (pcx.version != 5) if (pcx.version != 5)
Sys_Error ("'%s' is version %i, should be 5", loadfilename, pcx.version); Sys_Error("'%s' is version %i, should be 5", loadfilename, pcx.version);
if (pcx.encoding != 1 || pcx.bits_per_pixel != 8 || pcx.color_planes != 1) if (pcx.encoding != 1 || pcx.bits_per_pixel != 8 || pcx.color_planes != 1)
Sys_Error ("'%s' has wrong encoding or bit depth", loadfilename); Sys_Error("'%s' has wrong encoding or bit depth", loadfilename);
w = pcx.xmax - pcx.xmin + 1; w = pcx.xmax - pcx.xmin + 1;
h = pcx.ymax - pcx.ymin + 1; h = pcx.ymax - pcx.ymin + 1;
data = (byte *) Hunk_Alloc((w*h+1)*4); //+1 to allow reading padding byte on last line data = (byte *) Hunk_Alloc((w * h + 1) * 4); //+1 to allow reading padding byte on last line
//load palette //load palette
fseek (f, start + com_filesize - 768, SEEK_SET); fseek(f, start + com_filesize - 768, SEEK_SET);
if (!fread (palette, 768, 1, f)) if (!fread(palette, 768, 1, f))
Sys_Error ("Failed reading palette from '%s'", loadfilename); Sys_Error("Failed reading palette from '%s'", loadfilename);
//back to start of image data //back to start of image data
fseek (f, start + sizeof(pcx), SEEK_SET); fseek(f, start + sizeof(pcx), SEEK_SET);
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];
p[3] = 255; p[3] = 255;
p += 4; p += 4;
x++; x++;
@@ -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,39 +515,35 @@ 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;
int bytes_per_pixel; int bytes_per_pixel;
if (!(bpp == 32 || bpp == 24)) if (!(bpp == 32 || bpp == 24))
Sys_Error ("bpp not 24 or 32"); Sys_Error("bpp not 24 or 32");
bytes_per_pixel = bpp / 8; bytes_per_pixel = bpp / 8;
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);
if (!upsidedown) if (!upsidedown)
free (flipped); free(flipped);
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;
@@ -591,20 +555,19 @@ qboolean Image_WritePNG (const char *name, byte *data, int width, int height, in
if (!(bpp == 32 || bpp == 24)) if (!(bpp == 32 || bpp == 24))
Sys_Error("bpp not 24 or 32"); Sys_Error("bpp not 24 or 32");
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);
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);
return false; return false;
} }
// set some options for faster compression // set some options for faster compression
lodepng_state_init(&state); lodepng_state_init(&state);
state.encoder.zlibsettings.use_lz77 = 0; state.encoder.zlibsettings.use_lz77 = 0;
state.encoder.auto_convert = 0; state.encoder.auto_convert = 0;
@@ -612,28 +575,25 @@ 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;
} }
error = lodepng_encode (&png, &pngsize, flipped, width, height, &state); error = lodepng_encode(&png, &pngsize, flipped, width, height, &state);
if (error == 0) lodepng_save_file (png, pngsize, pathname); if (error == 0) lodepng_save_file(png, pngsize, pathname);
#ifdef LODEPNG_COMPILE_ERROR_TEXT #ifdef LODEPNG_COMPILE_ERROR_TEXT
else Con_Printf("WritePNG: %s\n", lodepng_error_text (error)); else Con_Printf("WritePNG: %s\n", lodepng_error_text(error));
#endif #endif
lodepng_state_cleanup (&state); lodepng_state_cleanup(&state);
lodepng_free (png); /* png was allocated by lodepng */ lodepng_free(png); /* png was allocated by lodepng */
free (filters); free(filters);
if (!upsidedown) { if (!upsidedown) {
free (flipped); free(flipped);
} }
return (error == 0); return (error == 0);
+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);
+24 -39
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;
@@ -48,7 +46,7 @@ static void Sys_InitSDL (void)
const SDL_version *sdl_version = SDL_Linked_Version(); const SDL_version *sdl_version = SDL_Linked_Version();
#endif #endif
Sys_Printf("Found SDL version %i.%i.%i\n",sdl_version->major,sdl_version->minor,sdl_version->patch); Sys_Printf("Found SDL version %i.%i.%i\n", sdl_version->major, sdl_version->minor, sdl_version->patch);
if (SDL_Init(0) < 0) { if (SDL_Init(0) < 0) {
Sys_Error("Couldn't init SDL: %s", SDL_GetError()); Sys_Error("Couldn't init SDL: %s", SDL_GetError());
@@ -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,71 +77,60 @@ 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();
Sys_Init(); Sys_Init();
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);
if (!parms.membase) if (!parms.membase)
Sys_Error ("Not enough memory free; check disk space\n"); Sys_Error("Not enough memory free; check disk space\n");
Sys_Printf("Host_Init\n"); Sys_Printf("Host_Init\n");
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;
} }
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();
time = newtime - oldtime; time = newtime - oldtime;
Host_Frame (time); Host_Frame(time);
if (time < sys_throttle.value && !cls.timedemo) if (time < sys_throttle.value && !cls.timedemo)
SDL_Delay(1); SDL_Delay(1);
+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.
+430 -522
View File
File diff suppressed because it is too large Load Diff
+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