diff --git a/Game.Client/C_Soundscape.cs b/Game.Client/C_Soundscape.cs index c7fc9a0e..91661d8c 100644 --- a/Game.Client/C_Soundscape.cs +++ b/Game.Client/C_Soundscape.cs @@ -25,6 +25,16 @@ public static class SoundscapeGlobals public static void Soundscape_OnStopAllSounds() => g_SoundscapeSystem.OnStopAllSounds(); public static void Soundscape_Update(ref AudioParams audio) => g_SoundscapeSystem.UpdateAudioParams(ref audio); public static ConVar soundscape_fadetime = new("soundscape_fadetime", "3.0", FCvar.Cheat, "Time to crossfade sound effects between soundscapes"); + + [ConCommand(helpText: "Flushes the client side soundscapes", flags: FCvar.ServerCanExecute | FCvar.Cheat)] + static void cl_soundscape_flush() { + g_SoundscapeSystem.GetAudioParams(out AudioParams tmp); + + g_SoundscapeSystem.Shutdown(); + g_SoundscapeSystem.Init(); + + Soundscape_Update(ref tmp); + } } public struct LoopingSound @@ -206,7 +216,7 @@ public void UpdateAudioParams(ref AudioParams audio) { } } - public void GetAudioParams(out AudioParams outParams) => throw new NotImplementedException(); + public void GetAudioParams(out AudioParams outParams) => outParams = Params; public int GetCurrentSoundscape() => throw new NotImplementedException(); diff --git a/Game.Client/GarrysMod/C_GMOD_Player.cs b/Game.Client/GarrysMod/C_GMOD_Player.cs index 5c27ec45..afdcd10b 100644 --- a/Game.Client/GarrysMod/C_GMOD_Player.cs +++ b/Game.Client/GarrysMod/C_GMOD_Player.cs @@ -21,8 +21,6 @@ namespace Game.Client.GarrysMod; [NetworkName("CGMOD_Player")] public partial class C_GMOD_Player() : C_HL2MP_Player() { - static ConVar cl_playercolor = new("1.0 0.0 0.0", FCvar.UserInfo | FCvar.Archive | FCvar.ServerCanExecute, "Default Player Model"); - [NetworkTable] public static readonly new NetworkProp[] Props = [ nameof(GModPlayerFlags), diff --git a/Game.Client/HLTVCamera.cs b/Game.Client/HLTVCamera.cs new file mode 100644 index 00000000..4942e3ad --- /dev/null +++ b/Game.Client/HLTVCamera.cs @@ -0,0 +1,10 @@ +using Source.Common.Commands; + +namespace Game.Client; + +public static class HLTVCameraGlobals +{ + public static readonly ConVar spec_autodirector = new("spec_autodirector", "1", FCvar.ClientDLL | FCvar.ClientCmdCanExecute, "Auto-director chooses best view modes while spectating"); + + // todo: C_HLTVCamera +} diff --git a/Game.Client/InJoystick.cs b/Game.Client/InJoystick.cs new file mode 100644 index 00000000..1ab45907 --- /dev/null +++ b/Game.Client/InJoystick.cs @@ -0,0 +1,127 @@ +using Source.Common.Commands; + +namespace Game.Client; + +public enum GameAxis +{ + None = 0, + Forward, + Pitch, + Side, + Yaw, + Max +} + +public enum JoystickAxis +{ + X = 0, + Y, + Z, + R, + U, + V, + Max +} + +public struct JoyAxis +{ + public uint AxisMap; + public uint ControlMap; +} + +public partial class Input +{ + const uint JOY_ABSOLUTE_AXIS = 0x00000000; + const uint JOY_RELATIVE_AXIS = 0x00000010; + + static readonly ConVar joy_name = new("joy_name", "joystick", FCvar.Archive); + static readonly ConVar joy_advanced = new("joy_advanced", "1", FCvar.Archive); + static readonly ConVar joy_advaxisx = new("joy_advaxisx", "4", FCvar.Archive); + static readonly ConVar joy_advaxisy = new("joy_advaxisy", "2", FCvar.Archive); + static readonly ConVar joy_advaxisz = new("joy_advaxisz", "0", FCvar.Archive); + static readonly ConVar joy_advaxisr = new("joy_advaxisr", "1", FCvar.Archive); + static readonly ConVar joy_advaxisu = new("joy_advaxisu", "3", FCvar.Archive); + static readonly ConVar joy_advaxisv = new("joy_advaxisv", "0", FCvar.Archive); + static readonly ConVar joy_movement_stick = new("joy_movement_stick", "0", FCvar.Archive | FCvar.ArchiveXbox, "Which stick controls movement (0 is left stick)", callback: joy_movement_stick_Callback); + static readonly ConVar joy_xcontroller_cfg_loaded = new("joy_xcontroller_cfg_loaded", "0", FCvar.Archive, "If 0, the 360controller.cfg file will be executed on startup & option changes."); + + // todo: the rest of in_joystick.cpp (Init_Joystick, JoyStickMove and their ConVars) + + readonly JoyAxis[] Axes = new JoyAxis[(int)JoystickAxis.Max]; + static ConVarRef? joy_xcontroller_found; + + static void joy_movement_stick_Callback(IConVar var, in ConVarChangeContext ctx) { + engine.ClientCmd("joyadvancedupdate"); + } + + static ReadOnlySpan DescribeAxis(uint index) { + switch ((GameAxis)index) { + case GameAxis.Forward: + return "Forward"; + case GameAxis.Pitch: + return "Look"; + case GameAxis.Side: + return "Side"; + case GameAxis.Yaw: + return "Turn"; + case GameAxis.None: + default: + return "Unknown"; + } + } + + static void DescribeJoystickAxis(string axis, in JoyAxis mapping) { + if (mapping.AxisMap == 0) + Msg("%s: unmapped\n", axis); + else + Msg("%s: mapped to %s (%s)\n", axis, DescribeAxis(mapping.AxisMap).ToString(), mapping.ControlMap != 0 ? "relative" : "absolute"); + } + + void SetJoystickAxis(JoystickAxis axis, string name, int value) { + uint temp = unchecked((uint)value); + Axes[(int)axis].AxisMap = temp & 0x0000000f; + Axes[(int)axis].ControlMap = temp & JOY_RELATIVE_AXIS; + + DescribeJoystickAxis(name, in Axes[(int)axis]); + } + + public void Joystick_Advanced() { + for (int i = 0; i < (int)JoystickAxis.Max; i++) { + Axes[i].AxisMap = (uint)GameAxis.None; + Axes[i].ControlMap = JOY_ABSOLUTE_AXIS; + } + + if (!joy_advanced.GetBool()) { + Axes[(int)JoystickAxis.X].AxisMap = (uint)GameAxis.Yaw; + Axes[(int)JoystickAxis.Y].AxisMap = (uint)GameAxis.Forward; + } + else { + if (stricmp(joy_name.GetString(), "joystick") != 0) + Msg("Using joystick '%s' configuration\n", joy_name.GetString()); + + SetJoystickAxis(JoystickAxis.X, "JOY_AXIS_X", joy_movement_stick.GetBool() ? joy_advaxisu.GetInt() : joy_advaxisx.GetInt()); + SetJoystickAxis(JoystickAxis.Y, "JOY_AXIS_Y", joy_movement_stick.GetBool() ? joy_advaxisr.GetInt() : joy_advaxisy.GetInt()); + SetJoystickAxis(JoystickAxis.Z, "JOY_AXIS_Z", joy_advaxisz.GetInt()); + SetJoystickAxis(JoystickAxis.R, "JOY_AXIS_R", joy_movement_stick.GetBool() ? joy_advaxisy.GetInt() : joy_advaxisr.GetInt()); + SetJoystickAxis(JoystickAxis.U, "JOY_AXIS_U", joy_movement_stick.GetBool() ? joy_advaxisx.GetInt() : joy_advaxisu.GetInt()); + SetJoystickAxis(JoystickAxis.V, "JOY_AXIS_V", joy_advaxisv.GetInt()); + + Msg("Advanced Joystick settings initialized\n"); + } + + ConVarRef found = joy_xcontroller_found ??= new("joy_xcontroller_found"); + if (found.IsValid() && found.GetBool() && in_joystick.GetBool()) { + if (joy_xcontroller_cfg_loaded.GetInt() < 2) { + engine.ClientCmd_Unrestricted("exec 360controller.cfg"); +#if LINUX + engine.ClientCmd_Unrestricted("exec 360controller-linux.cfg"); +#endif + joy_xcontroller_cfg_loaded.SetValue(2); + } + } + else if (joy_xcontroller_cfg_loaded.GetInt() > 0) { + engine.ClientCmd_Unrestricted("exec undo360controller.cfg"); + joy_xcontroller_cfg_loaded.SetValue(0); + } + } +} diff --git a/Game.Client/InMain.cs b/Game.Client/InMain.cs index ff91d356..46825fd6 100644 --- a/Game.Client/InMain.cs +++ b/Game.Client/InMain.cs @@ -51,7 +51,7 @@ public partial class Input(ISurface Surface, IViewRender view, ThirdPersonManage readonly ConVar cl_backspeed = new("450", FCvar.Replicated | FCvar.Cheat); readonly ConVar lookspring = new("0", FCvar.Archive); readonly ConVar lookstrafe = new("0", FCvar.Archive); - readonly ConVar in_joystick = new("0", FCvar.Archive); + readonly ConVar in_joystick = new("joystick", "0", FCvar.Archive); readonly ConVar thirdperson_platformer = new("0", 0, "Player will aim in the direction they are moving."); readonly ConVar thirdperson_screenspace = new("0", 0, "Movement will be relative to the camera, eg: left means screen-left"); readonly ConVar sv_noclipduringpause = new("0", FCvar.Replicated | FCvar.Cheat, "If cheats are enabled, then you can noclip with the game paused (for doing screenshots, etc.)."); @@ -86,6 +86,8 @@ public partial class Input(ISurface Surface, IViewRender view, ThirdPersonManage KeyButtonState in_score; KeyButtonState in_break; KeyButtonState in_zoom; + KeyButtonState in_grenade1; + KeyButtonState in_grenade2; KeyButtonState in_attack3; Handle SelectedWeapon = new(); @@ -161,36 +163,41 @@ public float KeyState(ref KeyButtonState key) { return val; } #if GMOD_DLL - [ConCommand] + const FCvar IN_COMMAND_FLAGS = FCvar.ServerCanExecute; +#else + const FCvar IN_COMMAND_FLAGS = FCvar.None; +#endif +#if GMOD_DLL + [ConCommand(flags: FCvar.ServerCanExecute)] void noclip() { in_impulse = 154; } #endif - [ConCommand] void impulse(in TokenizedCommand args) => in_impulse = int.TryParse(args[1], out in_impulse) ? in_impulse : 0; - [ConCommand(name: "+moveup")] void IN_UpDown(in TokenizedCommand args) => KeyDown(ref in_up, args[1]); - [ConCommand(name: "+movedown")] void IN_DownDown(in TokenizedCommand args) => KeyDown(ref in_down, args[1]); - [ConCommand(name: "+left")] void IN_LeftDown(in TokenizedCommand args) => KeyDown(ref in_left, args[1]); - [ConCommand(name: "+right")] void IN_RightDown(in TokenizedCommand args) => KeyDown(ref in_right, args[1]); - [ConCommand(name: "+forward")] void IN_ForwardDown(in TokenizedCommand args) => KeyDown(ref in_forward, args[1]); - [ConCommand(name: "+back")] void IN_BackDown(in TokenizedCommand args) => KeyDown(ref in_back, args[1]); - [ConCommand(name: "+lookup")] void IN_LookupDown(in TokenizedCommand args) => KeyDown(ref in_lookup, args[1]); - [ConCommand(name: "+lookdown")] void IN_LookdownDown(in TokenizedCommand args) => KeyDown(ref in_lookdown, args[1]); - [ConCommand(name: "+strafe")] void IN_StrafeDown(in TokenizedCommand args) => KeyDown(ref in_strafe, args[1]); - [ConCommand(name: "+moveleft")] void IN_MoveleftDown(in TokenizedCommand args) => KeyDown(ref in_moveleft, args[1]); - [ConCommand(name: "+moveright")] void IN_MoverightDown(in TokenizedCommand args) => KeyDown(ref in_moveright, args[1]); - [ConCommand(name: "+speed")] void IN_SpeedDown(in TokenizedCommand args) => KeyDown(ref in_speed, args[1]); - [ConCommand(name: "+walk")] void IN_WalkDown(in TokenizedCommand args) => KeyDown(ref in_walk, args[1]); - [ConCommand(name: "+attack")] void IN_AttackDown(in TokenizedCommand args) => KeyDown(ref in_attack, args[1]); - [ConCommand(name: "+attack2")] void IN_Attack2Down(in TokenizedCommand args) => KeyDown(ref in_attack2, args[1]); - [ConCommand(name: "+use")] void IN_UseDown(in TokenizedCommand args) => KeyDown(ref in_use, args[1]); - [ConCommand(name: "+jump")] void IN_JumpDown(in TokenizedCommand args) => KeyDown(ref in_jump, args[1]); - [ConCommand(name: "+klook")] void IN_KLookDown(in TokenizedCommand args) => KeyDown(ref in_klook, args[1]); - [ConCommand(name: "+jlook")] void IN_JLookDown(in TokenizedCommand args) => KeyDown(ref in_jlook, args[1]); - [ConCommand(name: "+duck")] void IN_DuckDown(in TokenizedCommand args) => KeyDown(ref in_duck, args[1]); - [ConCommand(name: "+reload")] void IN_ReloadDown(in TokenizedCommand args) => KeyDown(ref in_reload, args[1]); - [ConCommand(name: "+alt1")] void IN_Alt1Down(in TokenizedCommand args) => KeyDown(ref in_alt1, args[1]); - [ConCommand(name: "+alt2")] void IN_Alt2Down(in TokenizedCommand args) => KeyDown(ref in_alt2, args[1]); - [ConCommand(name: "+score")] + [ConCommand(flags: IN_COMMAND_FLAGS)] void impulse(in TokenizedCommand args) => in_impulse = int.TryParse(args[1], out in_impulse) ? in_impulse : 0; + [ConCommand(name: "+moveup", flags: IN_COMMAND_FLAGS)] void IN_UpDown(in TokenizedCommand args) => KeyDown(ref in_up, args[1]); + [ConCommand(name: "+movedown", flags: IN_COMMAND_FLAGS)] void IN_DownDown(in TokenizedCommand args) => KeyDown(ref in_down, args[1]); + [ConCommand(name: "+left", flags: IN_COMMAND_FLAGS)] void IN_LeftDown(in TokenizedCommand args) => KeyDown(ref in_left, args[1]); + [ConCommand(name: "+right", flags: IN_COMMAND_FLAGS)] void IN_RightDown(in TokenizedCommand args) => KeyDown(ref in_right, args[1]); + [ConCommand(name: "+forward", flags: IN_COMMAND_FLAGS)] void IN_ForwardDown(in TokenizedCommand args) => KeyDown(ref in_forward, args[1]); + [ConCommand(name: "+back", flags: IN_COMMAND_FLAGS)] void IN_BackDown(in TokenizedCommand args) => KeyDown(ref in_back, args[1]); + [ConCommand(name: "+lookup", flags: IN_COMMAND_FLAGS)] void IN_LookupDown(in TokenizedCommand args) => KeyDown(ref in_lookup, args[1]); + [ConCommand(name: "+lookdown", flags: IN_COMMAND_FLAGS)] void IN_LookdownDown(in TokenizedCommand args) => KeyDown(ref in_lookdown, args[1]); + [ConCommand(name: "+strafe", flags: IN_COMMAND_FLAGS)] void IN_StrafeDown(in TokenizedCommand args) => KeyDown(ref in_strafe, args[1]); + [ConCommand(name: "+moveleft", flags: IN_COMMAND_FLAGS)] void IN_MoveleftDown(in TokenizedCommand args) => KeyDown(ref in_moveleft, args[1]); + [ConCommand(name: "+moveright", flags: IN_COMMAND_FLAGS)] void IN_MoverightDown(in TokenizedCommand args) => KeyDown(ref in_moveright, args[1]); + [ConCommand(name: "+speed", flags: IN_COMMAND_FLAGS)] void IN_SpeedDown(in TokenizedCommand args) => KeyDown(ref in_speed, args[1]); + [ConCommand(name: "+walk", flags: IN_COMMAND_FLAGS)] void IN_WalkDown(in TokenizedCommand args) => KeyDown(ref in_walk, args[1]); + [ConCommand(name: "+attack", flags: IN_COMMAND_FLAGS)] void IN_AttackDown(in TokenizedCommand args) => KeyDown(ref in_attack, args[1]); + [ConCommand(name: "+attack2", flags: IN_COMMAND_FLAGS)] void IN_Attack2Down(in TokenizedCommand args) => KeyDown(ref in_attack2, args[1]); + [ConCommand(name: "+use", flags: IN_COMMAND_FLAGS)] void IN_UseDown(in TokenizedCommand args) => KeyDown(ref in_use, args[1]); + [ConCommand(name: "+jump", flags: IN_COMMAND_FLAGS)] void IN_JumpDown(in TokenizedCommand args) => KeyDown(ref in_jump, args[1]); + [ConCommand(name: "+klook", flags: IN_COMMAND_FLAGS)] void IN_KLookDown(in TokenizedCommand args) => KeyDown(ref in_klook, args[1]); + [ConCommand(name: "+jlook", flags: IN_COMMAND_FLAGS)] void IN_JLookDown(in TokenizedCommand args) => KeyDown(ref in_jlook, args[1]); + [ConCommand(name: "+duck", flags: IN_COMMAND_FLAGS)] void IN_DuckDown(in TokenizedCommand args) => KeyDown(ref in_duck, args[1]); + [ConCommand(name: "+reload", flags: IN_COMMAND_FLAGS)] void IN_ReloadDown(in TokenizedCommand args) => KeyDown(ref in_reload, args[1]); + [ConCommand(name: "+alt1", flags: IN_COMMAND_FLAGS)] void IN_Alt1Down(in TokenizedCommand args) => KeyDown(ref in_alt1, args[1]); + [ConCommand(name: "+alt2", flags: IN_COMMAND_FLAGS)] void IN_Alt2Down(in TokenizedCommand args) => KeyDown(ref in_alt2, args[1]); + [ConCommand(name: "+score", flags: IN_COMMAND_FLAGS)] void IN_ScoreDown(in TokenizedCommand args) { KeyDown(ref in_score, args[1]); #if GMOD_DLL @@ -198,39 +205,41 @@ void IN_ScoreDown(in TokenizedCommand args) { #endif } #if GMOD_DLL - [ConCommand(name: "+showscores")] void IN_ShowScoresDown(in TokenizedCommand args) => IN_ScoreDown(in args); + [ConCommand(name: "+showscores", flags: IN_COMMAND_FLAGS)] void IN_ShowScoresDown(in TokenizedCommand args) => IN_ScoreDown(in args); #endif - [ConCommand(name: "+graph")] void IN_GraphDown(in TokenizedCommand args) => KeyDown(ref in_graph, args[1]); - [ConCommand(name: "+break")] void IN_BreakDown(in TokenizedCommand args) => KeyDown(ref in_break, args[1]); - [ConCommand(name: "+zoom")] void IN_ZoomDown(in TokenizedCommand args) => KeyDown(ref in_zoom, args[1]); + [ConCommand(name: "+graph", flags: IN_COMMAND_FLAGS)] void IN_GraphDown(in TokenizedCommand args) => KeyDown(ref in_graph, args[1]); + [ConCommand(name: "+break", flags: IN_COMMAND_FLAGS)] void IN_BreakDown(in TokenizedCommand args) => KeyDown(ref in_break, args[1]); + [ConCommand(name: "+zoom", flags: IN_COMMAND_FLAGS)] void IN_ZoomDown(in TokenizedCommand args) => KeyDown(ref in_zoom, args[1]); + [ConCommand(name: "+grenade1", flags: IN_COMMAND_FLAGS)] void IN_Grenade1Down(in TokenizedCommand args) => KeyDown(ref in_grenade1, args[1]); + [ConCommand(name: "+grenade2", flags: IN_COMMAND_FLAGS)] void IN_Grenade2Down(in TokenizedCommand args) => KeyDown(ref in_grenade2, args[1]); [ConCommand(name: "+attack3")] void IN_Attack3Down(in TokenizedCommand args) => KeyDown(ref in_attack3, args[1]); - [ConCommand(name: "-moveup")] void IN_UpUp(in TokenizedCommand args) => KeyUp(ref in_up, args[1]); - [ConCommand(name: "-movedown")] void IN_DownUp(in TokenizedCommand args) => KeyUp(ref in_down, args[1]); - [ConCommand(name: "-left")] void IN_LeftUp(in TokenizedCommand args) => KeyUp(ref in_left, args[1]); - [ConCommand(name: "-right")] void IN_RightUp(in TokenizedCommand args) => KeyUp(ref in_right, args[1]); - [ConCommand(name: "-forward")] void IN_ForwardUp(in TokenizedCommand args) => KeyUp(ref in_forward, args[1]); - [ConCommand(name: "-back")] void IN_BackUp(in TokenizedCommand args) => KeyUp(ref in_back, args[1]); - [ConCommand(name: "-lookup")] void IN_LookupUp(in TokenizedCommand args) => KeyUp(ref in_lookup, args[1]); - [ConCommand(name: "-lookdown")] void IN_LookdownUp(in TokenizedCommand args) => KeyUp(ref in_lookdown, args[1]); - [ConCommand(name: "-strafe")] void IN_StrafeUp(in TokenizedCommand args) => KeyUp(ref in_strafe, args[1]); - [ConCommand(name: "-moveleft")] void IN_MoveleftUp(in TokenizedCommand args) => KeyUp(ref in_moveleft, args[1]); - [ConCommand(name: "-moveright")] void IN_MoverightUp(in TokenizedCommand args) => KeyUp(ref in_moveright, args[1]); - [ConCommand(name: "-speed")] void IN_SpeedUp(in TokenizedCommand args) => KeyUp(ref in_speed, args[1]); - [ConCommand(name: "-walk")] void IN_WalkUp(in TokenizedCommand args) => KeyUp(ref in_walk, args[1]); - [ConCommand(name: "-attack")] void IN_AttackUp(in TokenizedCommand args) => KeyUp(ref in_attack, args[1]); - [ConCommand(name: "-attack2")] void IN_Attack2Up(in TokenizedCommand args) => KeyUp(ref in_attack2, args[1]); - [ConCommand(name: "-use")] void IN_UseUp(in TokenizedCommand args) => KeyUp(ref in_use, args[1]); - [ConCommand(name: "-jump")] void IN_JumpUp(in TokenizedCommand args) => KeyUp(ref in_jump, args[1]); - [ConCommand(name: "-klook")] void IN_KLookUp(in TokenizedCommand args) => KeyUp(ref in_klook, args[1]); - [ConCommand(name: "-jlook")] void IN_JLookUp(in TokenizedCommand args) => KeyUp(ref in_jlook, args[1]); - [ConCommand(name: "-duck")] void IN_DuckUp(in TokenizedCommand args) => KeyUp(ref in_duck, args[1]); - [ConCommand(name: "-reload")] void IN_ReloadUp(in TokenizedCommand args) => KeyUp(ref in_reload, args[1]); - [ConCommand(name: "-alt1")] void IN_Alt1Up(in TokenizedCommand args) => KeyUp(ref in_alt1, args[1]); - [ConCommand(name: "-alt2")] void IN_Alt2Up(in TokenizedCommand args) => KeyUp(ref in_alt2, args[1]); - [ConCommand(name: "-score")] + [ConCommand(name: "-moveup", flags: IN_COMMAND_FLAGS)] void IN_UpUp(in TokenizedCommand args) => KeyUp(ref in_up, args[1]); + [ConCommand(name: "-movedown", flags: IN_COMMAND_FLAGS)] void IN_DownUp(in TokenizedCommand args) => KeyUp(ref in_down, args[1]); + [ConCommand(name: "-left", flags: IN_COMMAND_FLAGS)] void IN_LeftUp(in TokenizedCommand args) => KeyUp(ref in_left, args[1]); + [ConCommand(name: "-right", flags: IN_COMMAND_FLAGS)] void IN_RightUp(in TokenizedCommand args) => KeyUp(ref in_right, args[1]); + [ConCommand(name: "-forward", flags: IN_COMMAND_FLAGS)] void IN_ForwardUp(in TokenizedCommand args) => KeyUp(ref in_forward, args[1]); + [ConCommand(name: "-back", flags: IN_COMMAND_FLAGS)] void IN_BackUp(in TokenizedCommand args) => KeyUp(ref in_back, args[1]); + [ConCommand(name: "-lookup", flags: IN_COMMAND_FLAGS)] void IN_LookupUp(in TokenizedCommand args) => KeyUp(ref in_lookup, args[1]); + [ConCommand(name: "-lookdown", flags: IN_COMMAND_FLAGS)] void IN_LookdownUp(in TokenizedCommand args) => KeyUp(ref in_lookdown, args[1]); + [ConCommand(name: "-strafe", flags: IN_COMMAND_FLAGS)] void IN_StrafeUp(in TokenizedCommand args) => KeyUp(ref in_strafe, args[1]); + [ConCommand(name: "-moveleft", flags: IN_COMMAND_FLAGS)] void IN_MoveleftUp(in TokenizedCommand args) => KeyUp(ref in_moveleft, args[1]); + [ConCommand(name: "-moveright", flags: IN_COMMAND_FLAGS)] void IN_MoverightUp(in TokenizedCommand args) => KeyUp(ref in_moveright, args[1]); + [ConCommand(name: "-speed", flags: IN_COMMAND_FLAGS)] void IN_SpeedUp(in TokenizedCommand args) => KeyUp(ref in_speed, args[1]); + [ConCommand(name: "-walk", flags: IN_COMMAND_FLAGS)] void IN_WalkUp(in TokenizedCommand args) => KeyUp(ref in_walk, args[1]); + [ConCommand(name: "-attack", flags: IN_COMMAND_FLAGS)] void IN_AttackUp(in TokenizedCommand args) => KeyUp(ref in_attack, args[1]); + [ConCommand(name: "-attack2", flags: IN_COMMAND_FLAGS)] void IN_Attack2Up(in TokenizedCommand args) => KeyUp(ref in_attack2, args[1]); + [ConCommand(name: "-use", flags: IN_COMMAND_FLAGS)] void IN_UseUp(in TokenizedCommand args) => KeyUp(ref in_use, args[1]); + [ConCommand(name: "-jump", flags: IN_COMMAND_FLAGS)] void IN_JumpUp(in TokenizedCommand args) => KeyUp(ref in_jump, args[1]); + [ConCommand(name: "-klook", flags: IN_COMMAND_FLAGS)] void IN_KLookUp(in TokenizedCommand args) => KeyUp(ref in_klook, args[1]); + [ConCommand(name: "-jlook", flags: IN_COMMAND_FLAGS)] void IN_JLookUp(in TokenizedCommand args) => KeyUp(ref in_jlook, args[1]); + [ConCommand(name: "-duck", flags: IN_COMMAND_FLAGS)] void IN_DuckUp(in TokenizedCommand args) => KeyUp(ref in_duck, args[1]); + [ConCommand(name: "-reload", flags: IN_COMMAND_FLAGS)] void IN_ReloadUp(in TokenizedCommand args) => KeyUp(ref in_reload, args[1]); + [ConCommand(name: "-alt1", flags: IN_COMMAND_FLAGS)] void IN_Alt1Up(in TokenizedCommand args) => KeyUp(ref in_alt1, args[1]); + [ConCommand(name: "-alt2", flags: IN_COMMAND_FLAGS)] void IN_Alt2Up(in TokenizedCommand args) => KeyUp(ref in_alt2, args[1]); + [ConCommand(name: "-score", flags: IN_COMMAND_FLAGS)] void IN_ScoreUp(in TokenizedCommand args) { KeyUp(ref in_score, args[1]); #if GMOD_DLL @@ -238,13 +247,25 @@ void IN_ScoreUp(in TokenizedCommand args) { #endif } #if GMOD_DLL - [ConCommand(name: "-showscores")] void IN_ShowScoresUp(in TokenizedCommand args) => IN_ScoreUp(in args); + [ConCommand(name: "-showscores", flags: IN_COMMAND_FLAGS)] void IN_ShowScoresUp(in TokenizedCommand args) => IN_ScoreUp(in args); #endif - [ConCommand(name: "-graph")] void IN_GraphUp(in TokenizedCommand args) => KeyUp(ref in_graph, args[1]); - [ConCommand(name: "-break")] void IN_BreakUp(in TokenizedCommand args) => KeyUp(ref in_break, args[1]); - [ConCommand(name: "-zoom")] void IN_ZoomUp(in TokenizedCommand args) => KeyUp(ref in_zoom, args[1]); + [ConCommand(name: "-graph", flags: IN_COMMAND_FLAGS)] void IN_GraphUp(in TokenizedCommand args) => KeyUp(ref in_graph, args[1]); + [ConCommand(name: "-break", flags: IN_COMMAND_FLAGS)] void IN_BreakUp(in TokenizedCommand args) => KeyUp(ref in_break, args[1]); + [ConCommand(name: "-zoom", flags: IN_COMMAND_FLAGS)] void IN_ZoomUp(in TokenizedCommand args) => KeyUp(ref in_zoom, args[1]); + [ConCommand(name: "-grenade1", flags: IN_COMMAND_FLAGS)] void IN_Grenade1Up(in TokenizedCommand args) => KeyUp(ref in_grenade1, args[1]); + [ConCommand(name: "-grenade2", flags: IN_COMMAND_FLAGS)] void IN_Grenade2Up(in TokenizedCommand args) => KeyUp(ref in_grenade2, args[1]); [ConCommand(name: "-attack3")] void IN_Attack3Up(in TokenizedCommand args) => KeyUp(ref in_attack3, args[1]); + [ConCommand(flags: IN_COMMAND_FLAGS)] + void force_centerview() { + engine.GetViewAngles(out QAngle viewangles); + viewangles[PITCH] = 0; + engine.SetViewAngles(in viewangles); + } + + [ConCommand(flags: FCvar.ClientCmdCanExecute)] + void joyadvancedupdate() => Joystick_Advanced(); + Hud Hud = null!; UserCmd[] Commands = new UserCmd[MULTIPLAYER_BACKUP]; @@ -778,6 +799,8 @@ public InButtons GetButtonBits(int resetState) { CalcButtonBits(ref bits, InButtons.Alt2, ClearInputState, ref in_alt2, resetState); CalcButtonBits(ref bits, InButtons.Score, ClearInputState, ref in_score, resetState); CalcButtonBits(ref bits, InButtons.Zoom, ClearInputState, ref in_zoom, resetState); + CalcButtonBits(ref bits, InButtons.Grenade1, ClearInputState, ref in_grenade1, resetState); + CalcButtonBits(ref bits, InButtons.Grenade2, ClearInputState, ref in_grenade2, resetState); CalcButtonBits(ref bits, InButtons.Attack3, ClearInputState, ref in_attack3, resetState); // TODO: duck toggle diff --git a/Game.Client/View.cs b/Game.Client/View.cs index b07e5fdb..d3161ce7 100644 --- a/Game.Client/View.cs +++ b/Game.Client/View.cs @@ -150,9 +150,10 @@ public void GetScreenFadeDistances(out float min, out float max) { min = max = 0; } - public IMaterial? GetScreenOverlayMaterial() { - throw new NotImplementedException(); - } + // todo: PerformScreenOverlay draws it + readonly MaterialReference ScreenOverlayMaterial = new(); + + public IMaterial? GetScreenOverlayMaterial() => ScreenOverlayMaterial.Get(); public ref ViewSetup GetViewSetup() { return ref CurrentView; @@ -980,9 +981,7 @@ public void SetCheapWaterStartDistance(float cheapWaterStartDistance) { CheapWaterStartDistance = cheapWaterStartDistance; } - public void SetScreenOverlayMaterial(IMaterial? pMaterial) { - throw new NotImplementedException(); - } + public void SetScreenOverlayMaterial(IMaterial? pMaterial) => ScreenOverlayMaterial.Init(pMaterial!); public bool ShouldDrawBrushModels() { throw new NotImplementedException(); diff --git a/Game.Client/ViewDebug.cs b/Game.Client/ViewDebug.cs index e787c3cf..6d8ba646 100644 --- a/Game.Client/ViewDebug.cs +++ b/Game.Client/ViewDebug.cs @@ -1,5 +1,7 @@ -using Source.Common; +using Source; +using Source.Common; using Source.Common.Commands; +using Source.Common.MaterialSystem; using System; using System.Collections.Generic; @@ -12,6 +14,25 @@ public static class DebugViewRender public static readonly ConVar cl_drawshadowtexture = new("cl_drawshadowtexture", "0", FCvar.Cheat); public static readonly ConVar cl_shadowtextureoverlaysize = new("cl_shadowtextureoverlaysize", "256", FCvar.Cheat); + [ConCommand(helpText: "Draw specified material as an overlay", flags: FCvar.Cheat | FCvar.ServerCanExecute)] + static void r_screenoverlay(in TokenizedCommand args) { + if (args.ArgC() == 2) { + if (stricmp("off", args[1]) == 0 || stricmp("0", args[1]) == 0) + view.SetScreenOverlayMaterial(null); + else { + IMaterial? material = materials.FindMaterial(args[1], MaterialDefines.TEXTURE_GROUP_OTHER, false); + if (!material.IsErrorMaterial()) + view.SetScreenOverlayMaterial(material); + else + view.SetScreenOverlayMaterial(null); + } + } + else { + IMaterial? material = view.GetScreenOverlayMaterial(); + Warning("r_screenoverlay: %s\n", material != null ? material.GetName().ToString() : "off"); + } + } + public static void Draw3DDebuggingInfo(in ViewSetup view) { render.Draw3DDebugOverlays(); } diff --git a/Game.Client/VoiceStatus.cs b/Game.Client/VoiceStatus.cs index 9e00a1b4..652618d3 100644 --- a/Game.Client/VoiceStatus.cs +++ b/Game.Client/VoiceStatus.cs @@ -37,7 +37,9 @@ public static class VoiceStatusGlobals public const double VOICE_MODEL_INTERVAL = 0.3; public const float SQUELCHOSCILLATE_PER_SECOND = 2.0f; +#if !GMOD_DLL public static readonly ConVar voice_modenable = new("voice_modenable", "1", FCvar.Archive | FCvar.ClientCmdCanExecute, "Enable/disable voice in this mod."); +#endif public static readonly ConVar voice_clientdebug = new("voice_clientdebug", "0"); // ---------------------------------------------------------------------- // @@ -287,10 +289,12 @@ public void UpdateSpeakerStatus(int entindex, bool talking) { // Is it the local player talking? if (entindex == -1) { Talking = talking; +#if !GMOD_DLL if (talking) { // Enable voice for them automatically if they try to talk. engine.ClientCmd("voice_modenable 1"); } +#endif } else if (entindex == -2) ServerAcked = talking; @@ -317,7 +321,12 @@ void UpdateServerState(bool force) { return; } +#if GMOD_DLL + ConVarRef voice_enable = new("voice_enable"); + int cvarModEnable = voice_enable.GetInt() != 0 ? 1 : 0; +#else int cvarModEnable = voice_modenable.GetInt() != 0 ? 1 : 0; +#endif if (force || ServerModEnable != cvarModEnable) { ServerModEnable = cvarModEnable; diff --git a/Game.Server/GarrysMod/GMOD_Player.cs b/Game.Server/GarrysMod/GMOD_Player.cs index d08e1cc3..5d03307e 100644 --- a/Game.Server/GarrysMod/GMOD_Player.cs +++ b/Game.Server/GarrysMod/GMOD_Player.cs @@ -141,10 +141,10 @@ static void CallShowHook(LUA_POOLEDSTRING hook) { gGM.CallFinish(1); } - [ConCommand("gm_showhelp")] static void CC_ShowHelp() => CallShowHook(LUA_POOLEDSTRING.ShowHelp); - [ConCommand("gm_showteam")] static void CC_ShowTeam() => CallShowHook(LUA_POOLEDSTRING.ShowTeam); - [ConCommand("gm_showspare1")] static void CC_ShowSpare1() => CallShowHook(LUA_POOLEDSTRING.ShowSpare1); - [ConCommand("gm_showspare2")] static void CC_ShowSpare2() => CallShowHook(LUA_POOLEDSTRING.ShowSpare2); + [ConCommand("gm_showhelp", flags: FCvar.ServerCanExecute)] static void CC_ShowHelp() => CallShowHook(LUA_POOLEDSTRING.ShowHelp); + [ConCommand("gm_showteam", flags: FCvar.ServerCanExecute)] static void CC_ShowTeam() => CallShowHook(LUA_POOLEDSTRING.ShowTeam); + [ConCommand("gm_showspare1", flags: FCvar.ServerCanExecute)] static void CC_ShowSpare1() => CallShowHook(LUA_POOLEDSTRING.ShowSpare1); + [ConCommand("gm_showspare2", flags: FCvar.ServerCanExecute)] static void CC_ShowSpare2() => CallShowHook(LUA_POOLEDSTRING.ShowSpare2); #endif public static GMOD_Player? CreatePlayer(ReadOnlySpan classname, Edict ed) { diff --git a/Game.Shared/GarrysMod/GarrysMod.cs b/Game.Shared/GarrysMod/GarrysMod.cs index de73e821..1522af42 100644 --- a/Game.Shared/GarrysMod/GarrysMod.cs +++ b/Game.Shared/GarrysMod/GarrysMod.cs @@ -119,6 +119,9 @@ public void InitializeMod(IServiceProvider services) { engine.ServerCommand("sv_allow_voice_from_file 0\n"); engine.ServerCommand("sv_client_predict 1\n"); #endif +#if CLIENT_DLL + engine.SetRestrictServerCommands(true); +#endif #if !SWDS get.IntroScreen()?.Update("Adding Custom Fonts", true); #if CLIENT_DLL diff --git a/Game.Shared/SoundEmitterSystem.cs b/Game.Shared/SoundEmitterSystem.cs index 2d47fbcf..4c32e546 100644 --- a/Game.Shared/SoundEmitterSystem.cs +++ b/Game.Shared/SoundEmitterSystem.cs @@ -11,6 +11,7 @@ using Source.Common; using Source.Common.Audio; +using Source.Common.Commands; using Source.Common.SoundEmitterSystem; using System; @@ -347,6 +348,50 @@ public void EmitAmbientSound(int entindex, in Vector3 origin, ReadOnlySpan public static class SoundEmitterSystemGlobals { public static readonly SoundEmitterSystem g_SoundEmitterSystem = new(); + +#if CLIENT_DLL + [ConCommand("playgamesound", "Play a sound from the game sounds txt file", FCvar.ClientCmdCanExecute | FCvar.ServerCanExecute, autoCompleteMethod: nameof(GamesoundCompletion))] + static void Playgamesound_f(in TokenizedCommand args) { + C_BasePlayer? player = C_BasePlayer.GetLocalPlayer(); + if (player != null) { + if (args.ArgC() > 2) { + Vector3 position = player.EyePosition(); + player.GetVectors(out Vector3 forward, out _, out _); + position += (float)atof(args[2]) * forward; + PASAttenuationFilter filter = new(player); + scoped EmitSound_t parms = new(); + parms.SoundName = args[1]; + parms.Origin = ref position; + parms.Volume = 0.0f; + parms.Pitch = 0; + g_SoundEmitterSystem.EmitSound(filter, 0, ref parms); + } + else + player.EmitSound(args[1]); + } + else + Msg("Can't play until a game is started.\n"); + } + + static IEnumerable GamesoundCompletion(string partial) { + const string cmdname = "playgamesound"; + const int COMMAND_COMPLETION_MAXITEMS = 64; + string? substring = null; + if (partial.Contains(cmdname, StringComparison.Ordinal) && partial.Length > cmdname.Length + 1) + substring = partial[(cmdname.Length + 1)..]; + + int current = 0; + for (int i = soundemitterbase.GetSoundCount() - 1; i >= 0 && current < COMMAND_COMPLETION_MAXITEMS; i--) { + if (soundemitterbase.GetSoundName(i).IsEmpty) + continue; + + if (substring == null || soundemitterbase.GetSoundName(i).StartsWith(substring, StringComparison.OrdinalIgnoreCase)) { + yield return $"{cmdname} {soundemitterbase.GetSoundName(i)}"; + current++; + } + } + } +#endif } public partial class diff --git a/Source.Bitmap/TGAWriter.cs b/Source.Bitmap/TGAWriter.cs new file mode 100644 index 00000000..1350c375 --- /dev/null +++ b/Source.Bitmap/TGAWriter.cs @@ -0,0 +1,60 @@ +using Source.Common.Bitmap; +using Source.Common.Utilities; + +namespace Source.Bitmap; + +public static class TGAWriter +{ + public static bool WriteToBuffer(Span imageData, UtlBuffer buffer, int width, int height, ImageFormat srcFormat, ImageFormat dstFormat) { + switch (dstFormat) { + case ImageFormat.RGB888: + dstFormat = ImageFormat.BGR888; + break; + case ImageFormat.RGBA8888: + dstFormat = ImageFormat.BGRA8888; + break; + } + + byte imageType; + byte pixelSize; + switch (dstFormat) { + case ImageFormat.BGR888: + imageType = 2; + pixelSize = 24; + break; + case ImageFormat.BGRA8888: + imageType = 2; + pixelSize = 32; + break; + case ImageFormat.I8: + imageType = 1; + pixelSize = 8; + break; + default: + return false; + } + + buffer.PutType(0); + buffer.PutType(0); + buffer.PutType(imageType); + buffer.PutUnsignedShort(0); + buffer.PutUnsignedShort(0); + buffer.PutType(0); + buffer.PutUnsignedShort(0); + buffer.PutUnsignedShort(0); + buffer.PutUnsignedShort((ushort)width); + buffer.PutUnsignedShort((ushort)height); + buffer.PutType(pixelSize); + buffer.PutType(0x20); + + int sizeInBytes = width * height * dstFormat.SizeInBytes(); + buffer.EnsureCapacity(buffer.TellPut() + sizeInBytes); + Span dst = buffer.Base().AsSpan(buffer.TellPut(), sizeInBytes); + + if (!ImageLoader.ConvertImageFormat(imageData, srcFormat, dst, dstFormat, width, height)) + return false; + + buffer.SeekPut(SeekOrigin.Current, sizeInBytes); + return true; + } +} diff --git a/Source.Common/Engine/IModelRender.cs b/Source.Common/Engine/IModelRender.cs index 22aa000f..376dfebb 100644 --- a/Source.Common/Engine/IModelRender.cs +++ b/Source.Common/Engine/IModelRender.cs @@ -65,6 +65,8 @@ public interface IModelRender { ModelInstanceHandle_t CreateInstance(IClientRenderable renderable, LightCacheHandle_t? cache = null); void DestroyInstance(ModelInstanceHandle_t modelInstance); + void RemoveAllDecals(ModelInstanceHandle_t handle); + void RemoveAllDecalsFromAllModels(); int DrawModel(StudioFlags flags, IClientRenderable? renderable, ModelInstanceHandle_t instance, int entityIndex, Model? model, in Vector3 origin, in QAngle angles, int skin, int body, int hitboxset, Matrix3x4? modelToWorld = null, Matrix3x4? lightingOffset = null); int DrawModelEx(ref ModelRenderInfo info); int DrawStaticPropArrayFast(Span props, int count, bool shadowDepth); diff --git a/Source.Common/Engine/IVideoMode.cs b/Source.Common/Engine/IVideoMode.cs index cb476ad9..1949461b 100644 --- a/Source.Common/Engine/IVideoMode.cs +++ b/Source.Common/Engine/IVideoMode.cs @@ -70,4 +70,5 @@ public interface IVideoMode ViewRects GetClientViewRect(); bool IsWindowedMode(); bool IsBorderlessMode(); + void TakeSnapshotTGA(ReadOnlySpan filename); } diff --git a/Source.Common/Steam/Steamworks.cs b/Source.Common/Steam/Steamworks.cs index d036ac1d..6ecd722b 100644 --- a/Source.Common/Steam/Steamworks.cs +++ b/Source.Common/Steam/Steamworks.cs @@ -122,7 +122,12 @@ public interface ISteamRemoteStorage public int GetFileSize(ReadOnlySpan pchFile) => SteamRemoteStorage.GetFileSize(new(pchFile)); public bool GetQuota(out ulong pnTotalBytes, out ulong puAvailableBytes) => SteamRemoteStorage.GetQuota(out pnTotalBytes, out puAvailableBytes); } -public interface ISteamScreenshots; +public interface ISteamScreenshots +{ + public ScreenshotHandle AddScreenshotToLibrary(ReadOnlySpan pchFilename, ReadOnlySpan pchThumbnailFilename, int nWidth, int nHeight) => SteamScreenshots.AddScreenshotToLibrary(new(pchFilename), pchThumbnailFilename.IsEmpty ? null : new(pchThumbnailFilename), nWidth, nHeight); + public bool TagUser(ScreenshotHandle hScreenshot, CSteamID steamID) => SteamScreenshots.TagUser(hScreenshot, steamID); + public bool SetLocation(ScreenshotHandle hScreenshot, ReadOnlySpan pchLocation) => SteamScreenshots.SetLocation(hScreenshot, new(pchLocation)); +} public interface ISteamHTTP; public interface ISteamController; public interface ISteamUGC; diff --git a/Source.Engine/CL.cs b/Source.Engine/CL.cs index 5dda926a..10bea7de 100644 --- a/Source.Engine/CL.cs +++ b/Source.Engine/CL.cs @@ -14,6 +14,8 @@ using Source.Engine.Client; using Source.Engine.Server; +using Steamworks; + using System.Buffers; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -307,7 +309,7 @@ public void connect(in TokenizedCommand cmd) { } } - [ConCommand(helpText: "Retry connection to last server.")] + [ConCommand(helpText: "Retry connection to last server.", flags: FCvar.DontRecord | FCvar.ServerCanExecute | FCvar.ClientCmdCanExecute)] void retry() { Retry(); } @@ -335,8 +337,181 @@ internal void ProcessVoiceData() { SendVoicePacket(false); } +#if !SWDS + static readonly ConVar cl_screenshotname = new("cl_screenshotname", "", 0, "Custom Screenshot name"); + + bool cl_takesnapshot; + bool cl_takejpeg; + int cl_snapshotnum; + readonly char[] cl_snapshotname = new char[MAX_OSPATH]; + readonly char[] cl_snapshot_subdirname = new char[MAX_OSPATH]; + + public void TakeScreenshot(ReadOnlySpan name) { + cl_takesnapshot = true; + cl_takejpeg = false; + + if (!name.IsEmpty +#if GMOD_DLL + && !name.Contains("..", StringComparison.Ordinal) +#endif + ) + strcpy(cl_snapshotname, name); + else { + cl_snapshotname[0] = '\0'; + + if (cl_screenshotname.GetString().Length > 0 +#if GMOD_DLL + && !cl_screenshotname.GetString().Contains("..", StringComparison.Ordinal) +#endif + ) + strcpy(cl_snapshotname, cl_screenshotname.GetString()); + } + + cl_snapshot_subdirname[0] = '\0'; + } + + [ConCommand(helpText: "Take a screenshot.", flags: FCvar.ClientCmdCanExecute)] + void screenshot(in TokenizedCommand args) { + // todo: test script checkpoint, cl_playback_screenshots while a demo plays + + if (args.ArgC() == 2) + TakeScreenshot(args[1]); + else + TakeScreenshot(null); + } +#endif + internal void TakeSnapshotAndSwap() { - Shader.SwapBuffers(); + bool readPixelsFromFrontBuffer = HardwareConfig.ReadPixelsFromFrontBuffer(); + if (readPixelsFromFrontBuffer) + Shader.SwapBuffers(); + +#if !SWDS + if (cl_takesnapshot) { + // todo: materials.AllowThreading + Span baseName = stackalloc char[MAX_OSPATH]; + Span filenameBuffer = stackalloc char[MAX_OSPATH]; + scoped ReadOnlySpan filename; + IClientEntity? world = entitylist.GetClientEntity(0); + + g_pFileSystem.CreateDirHierarchy("screenshots", "DEFAULT_WRITE_PATH"); + + if (world != null && world.GetModel() != null) + modelloader.GetName(world.GetModel()!).FileBase(baseName); + else + strcpy(baseName, "Snapshot"); + + ReadOnlySpan extension = cl_takejpeg ? ".jpg" : ".tga"; + ReadOnlySpan subdir = ((ReadOnlySpan)cl_snapshot_subdirname).SliceNullTerminatedString(); + + if (!subdir.IsEmpty) { + Span directory = stackalloc char[MAX_OSPATH]; + g_pFileSystem.CreateDirHierarchy(sprintf(directory, "screenshots/%s/%s").S(baseName).S(subdir).ToSpan(), "DEFAULT_WRITE_PATH"); + } + + if (cl_snapshotname[0] != '\0') { + strcpy(baseName, cl_snapshotname); + filename = sprintf(filenameBuffer, "screenshots/%s%s").S(baseName).S(extension).ToSpan(); + + int number = 0; + Span renamedBuffer = stackalloc char[MAX_OSPATH]; + scoped ReadOnlySpan renamedfile; + do + renamedfile = sprintf(renamedBuffer, "screenshots/%s_%04d%s").S(baseName).D(number++).S(extension).ToSpan(); + while (g_pFileSystem.FileExists(renamedfile)); + + if (g_pFileSystem.FileExists(filename)) + g_pFileSystem.RenameFile(filename, renamedfile); + + cl_screenshotname.SetValue(""); + } + else { + do { + if (!subdir.IsEmpty) + filename = sprintf(filenameBuffer, "screenshots/%s/%s/%s%04d%s").S(baseName).S(subdir).S(baseName).D(cl_snapshotnum++).S(extension).ToSpan(); + else + filename = sprintf(filenameBuffer, "screenshots/%s%04d%s").S(baseName).D(cl_snapshotnum++).S(extension).ToSpan(); + } + while (g_pFileSystem.FileExists(filename)); + } + + // todo: TakeSnapshotJPEG and its upload when cl_takejpeg is set + if (!cl_takejpeg) + videoMode.TakeSnapshotTGA(filename); + + cl_takesnapshot = false; + } +#endif + + // todo: movie frames + if (!readPixelsFromFrontBuffer) + Shader.SwapBuffers(); + + // todo: save game screenshots, engine tool screenshot + } + + [ConCommand(helpText: "Adds a new user info value", flags: FCvar.ClientCmdCanExecute)] + void setinfo(in TokenizedCommand args) { + if (args.ArgC() != 3) { + Msg("Syntax: setinfo \n"); + return; + } + + string name = new(args[1]); + string value = new(args[2]); + + if (stricmp(name, "name") == 0) + return; + + foreach (char c in name) { + if (!char.IsAsciiLetterOrDigit(c) && c != '_') { + Msg("Ignoring convar change request for variable '%s', which contains invalid character(s)\n", name); + return; + } + } + + ConCommandBase? command = cvar.FindCommandBase(name); + ConVarRef sv_cheats = new("sv_cheats"); + + if (command != null) { + if (command.IsCommand()) { + Msg("Name %s is already registered as console command\n", name); + return; + } + + if (!command.IsFlagSet(FCvar.UserInfo)) { + Msg("Convar %s is already registered but not as user info value\n", name); + return; + } + + EUniverse universe = Host.GetSteamUniverse(); + if (universe != EUniverse.k_EUniverseBeta && universe != EUniverse.k_EUniverseDev && command.IsFlagSet(FCvar.DevelopmentOnly)) + return; + + if (command.IsFlagSet(FCvar.Cheat) && !sv_cheats.GetBool()) { + Msg("Convar %s is marked as cheat and cheats are off\n", name); + return; + } + } + else { + command = new ConVar(name, "", FCvar.UserInfo, "Custom user info value"); + cvar.SetAssemblyIdentifier(typeof(CL).Assembly); + cvar.RegisterConCommand(command); + } + + ConVar var = (ConVar)command; + if (cl.IsConnected() && var.IsFlagSet(FCvar.NotConnected)) { + Msg("Convar %s cannot be changed while you are connected to a server.\n", name); + return; + } + + var.SetValue(value); + + if (cl.IsConnected()) { + NET_SetConVar convar = new(); + convar.AddCVar(name, value); + cl.NetChannel!.SendNetMsg(convar); + } } public void DumpStringTables() => cl.StringTableContainer?.Dump(); diff --git a/Source.Engine/Cmd.cs b/Source.Engine/Cmd.cs index 92c55148..805b8084 100644 --- a/Source.Engine/Cmd.cs +++ b/Source.Engine/Cmd.cs @@ -207,7 +207,7 @@ void alias(in TokenizedCommand args) { aliases[new string(s)] = new string(restOfCommandLine); } - [ConCommand(helpText: "Echos text to console.")] + [ConCommand(helpText: "Echo text to console.", flags: FCvar.ServerCanExecute)] void echo(in TokenizedCommand args) { for (int i = 1, argc = args.ArgC(); i < argc; i++) ConMsg($"{args[i]} "); diff --git a/Source.Engine/Host.cs b/Source.Engine/Host.cs index bee23c95..4100d626 100644 --- a/Source.Engine/Host.cs +++ b/Source.Engine/Host.cs @@ -337,6 +337,29 @@ private void _RunFrame_Sound() { public void SetAudioState(in AudioState state) => audioState = state; +#if !SWDS + [ConCommand(helpText: "Fade client volume.", flags: FCvar.ServerCanExecute)] + void soundfade(in TokenizedCommand args) { + if (args.ArgC() != 3 && args.ArgC() != 5) { + Msg("soundfade [ ]\n"); + return; + } + + float percent = Math.Clamp((float)atof(args[1]), 0.0f, 100.0f); + float holdTime = Math.Max(0.0f, (float)atof(args[2])); + + float inTime = 0.0f; + float outTime = 0.0f; + if (args.ArgC() == 5) { + outTime = Math.Max(0.0f, (float)atof(args[3])); + inTime = Math.Max(0.0f, (float)atof(args[4])); + } + + // note: GMod passes the out time where the in time is expected + Sound.SoundFade(percent, holdTime, outTime, inTime); + } +#endif + [ConCommand("snd_restart", "Restart sound system.")] public void Snd_Restart_f() { #if !SWDS diff --git a/Source.Engine/ImplStudio.cs b/Source.Engine/ImplStudio.cs index 0678299b..613abb3f 100644 --- a/Source.Engine/ImplStudio.cs +++ b/Source.Engine/ImplStudio.cs @@ -281,6 +281,24 @@ public void DestroyInstance(ModelInstanceHandle_t modelInstance) { ModelInstances.Remove(modelInstance); } + public void RemoveAllDecals(ModelInstanceHandle_t handle) { + if (!ModelInstances.TryGetValue(handle, out ModelInstance? instance)) + return; + + if (instance.Model == null) + return; + + if (instance.DecalHandle != STUDIORENDER_DECAL_INVALID) { + // todo: studiorender.DestroyDecalList(instance.DecalHandle) + instance.DecalHandle = STUDIORENDER_DECAL_INVALID; + } + } + + public void RemoveAllDecalsFromAllModels() { + foreach (ModelInstanceHandle_t handle in ModelInstances.Keys) + RemoveAllDecals(handle); + } + public ref Matrix4x4 SetupModelState(IClientRenderable renderable) { throw new NotImplementedException(); // todo } diff --git a/Source.Engine/Key.cs b/Source.Engine/Key.cs index 6aba1c45..1ab80a9f 100644 --- a/Source.Engine/Key.cs +++ b/Source.Engine/Key.cs @@ -308,6 +308,11 @@ void unbindall(in TokenizedCommand args) { } } +#if !SWDS + [ConCommand(helpText: "Escape key pressed.", flags: FCvar.ClientCmdCanExecute)] + void escape() => EngineVGui().HideGameUI(); +#endif + [ConCommand(helpText: "List bound keys with bindings.")] void key_listboundkeys(in TokenizedCommand args) { for (int i = 0; i < (int)ButtonCode.Last; i++) { diff --git a/Source.Engine/R_Decal.cs b/Source.Engine/R_Decal.cs index 7c9505fd..bff3ad51 100644 --- a/Source.Engine/R_Decal.cs +++ b/Source.Engine/R_Decal.cs @@ -560,7 +560,25 @@ public static void DecalInit() { } public static void DecalTerm(WorldBrushData? brushData, bool termPermanentDecals) { - throw new NotImplementedException(); + if (brushData == null) + return; + + for (int i = 0; i < brushData.NumSurfaces; i++) { + Decal? next; + for (Decal? decal = MSurf_DecalPointer(i); decal != null; decal = next) { + next = decal.Next; + if (termPermanentDecals || ((decal.Flags & FDecal.Permanent) == 0 && (decal.Flags & FDecal.PlayerSpray) == 0)) + DecalUnlink(decal, brushData); + else if ((decal.Flags & FDecal.PlayerSpray) != 0) { + decal.FadeStartTime += 1.0f; + if (decal.FadeStartTime >= r_spray_lifetime.GetFloat()) + DecalUnlink(decal, brushData); + } + } + + if (termPermanentDecals) + Assert(MSurf_DecalPointer(i) == null); + } } public static void DecalTermAll() { diff --git a/Source.Engine/Render.cs b/Source.Engine/Render.cs index 1d7af64a..323b47ce 100644 --- a/Source.Engine/Render.cs +++ b/Source.Engine/Render.cs @@ -310,6 +310,23 @@ private void ClearView(ViewSetup topView, ClearFlags flags, ITexture? renderTarg } } +#if !SWDS + [ConCommand(helpText: "Usage r_cleardecals .", flags: FCvar.ClientCmdCanExecute | FCvar.ServerCanExecute)] + void r_cleardecals(in TokenizedCommand args) { + if (host_state.WorldModel != null) { + bool permanent = false; + if (args.ArgC() == 2) { + if (stricmp(args[1], "permanent") == 0) + permanent = true; + } + + DecalTerm(host_state.WorldModel.Brush.Shared, permanent); + } + + modelrender.RemoveAllDecalsFromAllModels(); + } +#endif + public void LevelInit() { ConDMsg("Initializing renderer...\n"); diff --git a/Source.Engine/SysModes.cs b/Source.Engine/SysModes.cs index 4441937a..5a283338 100644 --- a/Source.Engine/SysModes.cs +++ b/Source.Engine/SysModes.cs @@ -1,12 +1,17 @@ using Microsoft.Extensions.DependencyInjection; +using Source.Bitmap; using Source.Common; +using Source.Common.Bitmap; using Source.Common.Commands; using Source.Common.Engine; using Source.Common.Filesystem; using Source.Common.Formats.Keyvalues; using Source.Common.Launcher; using Source.Common.MaterialSystem; +using Source.Common.Utilities; + +using Steamworks; using System.Drawing; @@ -15,6 +20,10 @@ namespace Source.Engine; public class VideoMode_Common(Sys Sys, IServiceProvider services, IFileSystem fileSystem, IMaterialSystem materials, RenderUtils renderUtils, ICommandLine CommandLine) : IVideoMode { + static readonly ConVar cl_savescreenshotstosteam = new("cl_savescreenshotstosteam", "0", FCvar.Hidden, "Saves screenshots to the Steam's screenshot library"); + static readonly ConVar cl_screenshotusertag = new("cl_screenshotusertag", "", FCvar.Hidden, "User to tag in the screenshot"); + static readonly ConVar cl_screenshotlocation = new("cl_screenshotlocation", "", FCvar.Hidden, "Location to tag the screenshot with"); + public const int MAX_MODE_LIST = 512; const int VIDEO_MODE_DEFAULT = -1; const int VIDEO_MODE_REQUESTED_WINDOW_SIZE = -2; @@ -282,6 +291,60 @@ public void SetGameWindow(nint window) { public void SetInitialized(bool initialized) => Initialized = initialized; public bool GetInitialized() => Initialized; + + void AddScreenshotToSteam(ReadOnlySpan filename, int width, int height) { +#if !SWDS + if (cl_savescreenshotstosteam.GetBool()) { + if (Steam3Client().SteamScreenshots() != null) { + ScreenshotHandle screenshot = Steam3Client().SteamScreenshots().AddScreenshotToLibrary(filename, null, width, height); + ApplySteamScreenshotTags(screenshot); + } + } + + cl_screenshotusertag.SetValue(0); + cl_screenshotlocation.SetValue(""); +#endif + } + +#if !SWDS + void ApplySteamScreenshotTags(ScreenshotHandle screenshot) { + if (screenshot != ScreenshotHandle.Invalid) { + if (cl_screenshotusertag.GetBool()) { + if (Steam3Client().SteamUtils() != null) { + CSteamID steamID = new(new AccountID_t((uint)cl_screenshotusertag.GetInt()), Steam3Client().SteamUtils().GetConnectedUniverse(), EAccountType.k_EAccountTypeIndividual); + Steam3Client().SteamScreenshots().TagUser(screenshot, steamID); + } + } + + ReadOnlySpan location = cl_screenshotlocation.GetString(); + if (!location.IsEmpty) + Steam3Client().SteamScreenshots().SetLocation(screenshot, location); + } + } +#endif + + public virtual void ReadScreenPixels(int x, int y, int w, int h, Span buffer, ImageFormat format) { + int bytes = ImageLoader.GetMemRequired(w, h, 1, format, false); + buffer[..bytes].Clear(); + } + + public void TakeSnapshotTGA(ReadOnlySpan filename) { + byte[] image = new byte[GetModeStereoWidth() * 3 * GetModeStereoHeight()]; + + ReadScreenPixels(0, 0, GetModeStereoWidth(), GetModeStereoHeight(), image, ImageFormat.RGB888); + + UtlBuffer outBuf = new(); + if (TGAWriter.WriteToBuffer(image, outBuf, GetModeStereoWidth(), GetModeStereoHeight(), ImageFormat.RGB888, ImageFormat.RGB888)) { + if (!fileSystem.WriteFile(filename, "GAME", outBuf.Base().AsSpan(0, outBuf.TellPut()))) + Warning("Couldn't write bitmap data snapshot to file %s.\n", filename.ToString()); + else { + Span path = stackalloc char[MAX_PATH]; + ReadOnlySpan localPath = fileSystem.RelativePathToFullPath(filename, null, path); + if (!localPath.IsEmpty) + AddScreenshotToSteam(localPath, GetModeStereoWidth(), GetModeStereoHeight()); + } + } + } } public class VideoMode_MaterialSystem(Sys Sys, IMaterialSystem materials, IGame game, IServiceProvider services, IFileSystem fileSystem, RenderUtils renderUtils, ICommandLine commandLine, MatSysInterface matSys) : VideoMode_Common(Sys, services, fileSystem, materials, renderUtils, commandLine) @@ -387,7 +450,18 @@ void ChangeDisplaySettingsToFullscreen() { } - void ReadScreenPixels() { + public override void ReadScreenPixels(int x, int y, int w, int h, Span buffer, ImageFormat format) { + // todo: g_LostVideoMemory + bool readPixelsFromFrontBuffer = HardwareConfig.ReadPixelsFromFrontBuffer(); + if (readPixelsFromFrontBuffer) + Singleton().SwapBuffers(); + + using MatRenderContextPtr renderContext = new(materials); + + Rectangle rect = new(x, y, w, h); + renderContext.ReadPixelsAndStretch(ref rect, ref rect, buffer, format, w * format.SizeInBytes()); + if (readPixelsFromFrontBuffer) + Singleton().SwapBuffers(); } } diff --git a/Source.MaterialSystem/MatRenderContext.cs b/Source.MaterialSystem/MatRenderContext.cs index ed54b074..ef49153f 100644 --- a/Source.MaterialSystem/MatRenderContext.cs +++ b/Source.MaterialSystem/MatRenderContext.cs @@ -789,9 +789,7 @@ public void PushSelectionName(int name) { public void ReadPixels(int x, int y, int width, int height, Span data, ImageFormat dstFormat) => shaderAPI.ReadPixels(x, y, width, height, data, dstFormat); - public void ReadPixelsAndStretch(ref System.Drawing.Rectangle srcRect, ref System.Drawing.Rectangle pDstRect, Span buffer, ImageFormat dstFormat, int dstStride) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void ReadPixelsAndStretch(ref System.Drawing.Rectangle srcRect, ref System.Drawing.Rectangle pDstRect, Span buffer, ImageFormat dstFormat, int dstStride) => shaderAPI.ReadPixels(ref srcRect, ref pDstRect, buffer, dstFormat, dstStride); public void RefreshFrontBufferNonInteractive() { throw new NotImplementedException("Incomplete port of IMatRenderContext"); diff --git a/Source.ShaderAPI.Gl46/HardwareConfig.cs b/Source.ShaderAPI.Gl46/HardwareConfig.cs index fb812e24..0444c228 100644 --- a/Source.ShaderAPI.Gl46/HardwareConfig.cs +++ b/Source.ShaderAPI.Gl46/HardwareConfig.cs @@ -204,7 +204,7 @@ public bool PreferReducedFillrate() { } public bool ReadPixelsFromFrontBuffer() { - throw new NotImplementedException(); + return false; } public void SetHDREnabled(bool bEnable) { diff --git a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs index f1eb550d..08578fd7 100644 --- a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs +++ b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs @@ -3729,7 +3729,20 @@ public unsafe void ReadPixels(int x, int y, int width, int height, Span da } public void ReadPixels(ref System.Drawing.Rectangle srcRect, ref System.Drawing.Rectangle dstRect, Span data, ImageFormat dstFormat, int dstStride) { - throw new NotImplementedException("Incomplete port of IShaderAPI"); + // todo: stretch when the two rectangles differ in size + if (srcRect.Width != dstRect.Width || srcRect.Height != dstRect.Height) + throw new NotImplementedException("Incomplete port of IShaderAPI"); + + int rowBytes = dstRect.Width * dstFormat.SizeInBytes(); + if (dstStride == rowBytes) { + ReadPixels(srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, data, dstFormat); + return; + } + + byte[] packed = new byte[rowBytes * dstRect.Height]; + ReadPixels(srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, packed, dstFormat); + for (int row = 0; row < dstRect.Height; row++) + packed.AsSpan(row * rowBytes, rowBytes).CopyTo(data[(row * dstStride)..]); } public void ReleaseThreadOwnership() {