diff --git a/managed/src/Entrypoint.cs b/managed/src/Entrypoint.cs index d79dad04..1ca9b8bd 100644 --- a/managed/src/Entrypoint.cs +++ b/managed/src/Entrypoint.cs @@ -9,13 +9,15 @@ internal class Entrypoint { [UnmanagedCallersOnly] [SecurityCritical] - public unsafe static void Start(IntPtr nativeTable, int nativeTableSize, IntPtr basePath) - { - try { + public unsafe static void Start( IntPtr nativeTable, int nativeTableSize, IntPtr basePath ) + { + try + { Bootstrap.Start(nativeTable, nativeTableSize, Marshal.PtrToStringUTF8(basePath)!); - } catch (Exception e) { + } + catch (Exception e) + { AnsiConsole.WriteException(e); } } - -} +} \ No newline at end of file diff --git a/managed/src/SwiftlyS2.Core/Modules/Menus/Menu.cs b/managed/src/SwiftlyS2.Core/Modules/Menus/Menu.cs index 7795fb81..b29a385e 100644 --- a/managed/src/SwiftlyS2.Core/Modules/Menus/Menu.cs +++ b/managed/src/SwiftlyS2.Core/Modules/Menus/Menu.cs @@ -390,16 +390,21 @@ public void UseSlideOption( IPlayer player, bool isRight ) Rerender(player, false); } + [Obsolete("Use GetCurrentOption instead")] public bool IsOptionSlider( IPlayer player ) { - var option = Options[SelectedIndex[player]]; - return option is SliderMenuButton || option is ChoiceMenuOption; + return Options[SelectedIndex[player]] is SliderMenuButton || Options[SelectedIndex[player]] is ChoiceMenuOption; } + [Obsolete("Use GetCurrentOption instead")] public bool IsCurrentOptionSelectable( IPlayer player ) { - var option = Options[SelectedIndex[player]]; - return IsOptionSelectable(option); + return IsOptionSelectable(Options[SelectedIndex[player]]); + } + + public IOption? GetCurrentOption( IPlayer player ) + { + return !SelectedIndex.TryGetValue(player, out var index) || index < 0 || index >= Options.Count ? null : Options[index]; } public bool IsOptionSelectable( IOption option ) diff --git a/managed/src/SwiftlyS2.Core/Modules/Menus/MenuManager.cs b/managed/src/SwiftlyS2.Core/Modules/Menus/MenuManager.cs index dea2ac72..2832a4eb 100644 --- a/managed/src/SwiftlyS2.Core/Modules/Menus/MenuManager.cs +++ b/managed/src/SwiftlyS2.Core/Modules/Menus/MenuManager.cs @@ -1,5 +1,6 @@ using System.Collections.Concurrent; using System.Globalization; +using SwiftlyS2.Core.Menu.Options; using SwiftlyS2.Core.Natives; using SwiftlyS2.Shared; using SwiftlyS2.Shared.Events; @@ -151,10 +152,17 @@ void KeyStateChange( IOnClientKeyStateChangedEvent @event ) } else if (@event.Key == useKey) { - if (menu.IsOptionSlider(player)) menu.UseSlideOption(player, true); - else menu.UseSelection(player); + var option = menu.GetCurrentOption(player); + if (option is SliderMenuButton || option is ChoiceMenuOption) + { + menu.UseSlideOption(player, true); + } + else + { + menu.UseSelection(player); + } - if (menu.HasSound) + if (menu.HasSound && (option?.HasSound() ?? false)) { _useSound.Recipients.AddRecipient(@event.PlayerId); _useSound.Emit(); @@ -198,10 +206,17 @@ void KeyStateChange( IOnClientKeyStateChangedEvent @event ) } else if (@event.Key == KeyKind.D) { - if (menu.IsOptionSlider(player)) menu.UseSlideOption(player, true); - else menu.UseSelection(player); + var option = menu.GetCurrentOption(player); + if (option is SliderMenuButton || option is ChoiceMenuOption) + { + menu.UseSlideOption(player, true); + } + else + { + menu.UseSelection(player); + } - if (menu.HasSound) + if (menu.HasSound && (option?.HasSound() ?? false)) { _useSound.Recipients.AddRecipient(@event.PlayerId); _useSound.Emit(); diff --git a/managed/src/SwiftlyS2.Core/Modules/Menus/Options/AsyncButtonMenuOption.cs b/managed/src/SwiftlyS2.Core/Modules/Menus/Options/AsyncButtonMenuOption.cs index eaa5acc5..043350a6 100644 --- a/managed/src/SwiftlyS2.Core/Modules/Menus/Options/AsyncButtonMenuOption.cs +++ b/managed/src/SwiftlyS2.Core/Modules/Menus/Options/AsyncButtonMenuOption.cs @@ -24,7 +24,7 @@ internal class AsyncButtonMenuOption : IOption private string? _loadingText; - public AsyncButtonMenuOption(string text, Func? onClickAsync = null, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null) + public AsyncButtonMenuOption( string text, Func? onClickAsync = null, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null ) { Text = text; OnClickAsync = onClickAsync; @@ -32,7 +32,7 @@ public AsyncButtonMenuOption(string text, Func? onClickAsync = nu OverflowStyle = overflowStyle; } - public AsyncButtonMenuOption(string text, Func? onClickAsync, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null) + public AsyncButtonMenuOption( string text, Func? onClickAsync, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null ) { Text = text; OnClickAsyncWithOption = onClickAsync; @@ -40,17 +40,13 @@ public AsyncButtonMenuOption(string text, Func? onClickA OverflowStyle = overflowStyle; } - public bool ShouldShow(IPlayer player) - { - return VisibilityCheck?.Invoke(player) ?? true; - } + public bool ShouldShow( IPlayer player ) => VisibilityCheck?.Invoke(player) ?? true; - public bool CanInteract(IPlayer player) - { - return !IsLoading && (EnabledCheck?.Invoke(player) ?? true); - } + public bool CanInteract( IPlayer player ) => !IsLoading && (EnabledCheck?.Invoke(player) ?? true); + + public bool HasSound() => true; - public string GetDisplayText(IPlayer player, bool updateHorizontalStyle = false) + public string GetDisplayText( IPlayer player, bool updateHorizontalStyle = false ) { var sizeClass = MenuSizeHelper.GetSizeClass(Size); @@ -73,7 +69,7 @@ public IMenuTextSize GetTextSize() return Size; } - public async Task ExecuteAsync(IPlayer player, string? loadingText = null) + public async Task ExecuteAsync( IPlayer player, string? loadingText = null ) { if (OnClickAsync == null && OnClickAsyncWithOption == null) return; @@ -92,7 +88,7 @@ public async Task ExecuteAsync(IPlayer player, string? loadingText = null) } } - public void SetLoadingText(string? text) + public void SetLoadingText( string? text ) { _loadingText = text; } diff --git a/managed/src/SwiftlyS2.Core/Modules/Menus/Options/ButtonMenuOption.cs b/managed/src/SwiftlyS2.Core/Modules/Menus/Options/ButtonMenuOption.cs index d8206467..9d0e9d5f 100644 --- a/managed/src/SwiftlyS2.Core/Modules/Menus/Options/ButtonMenuOption.cs +++ b/managed/src/SwiftlyS2.Core/Modules/Menus/Options/ButtonMenuOption.cs @@ -21,7 +21,7 @@ internal class ButtonMenuOption : IOption public bool Visible => true; public bool Enabled => true; - public ButtonMenuOption(string text, Action? onClick = null, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null) + public ButtonMenuOption( string text, Action? onClick = null, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null ) { Text = text; OnClick = onClick; @@ -29,7 +29,7 @@ public ButtonMenuOption(string text, Action? onClick = null, IMenuTextS OverflowStyle = overflowStyle; } - public ButtonMenuOption(string text, Action? onClick, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null) + public ButtonMenuOption( string text, Action? onClick, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null ) { Text = text; OnClickWithOption = onClick; @@ -37,17 +37,13 @@ public ButtonMenuOption(string text, Action? onClick, IMenuTex OverflowStyle = overflowStyle; } - public bool ShouldShow(IPlayer player) - { - return VisibilityCheck?.Invoke(player) ?? true; - } + public bool ShouldShow( IPlayer player ) => VisibilityCheck?.Invoke(player) ?? true; - public bool CanInteract(IPlayer player) - { - return EnabledCheck?.Invoke(player) ?? true; - } + public bool CanInteract( IPlayer player ) => EnabledCheck?.Invoke(player) ?? true; + + public bool HasSound() => true; - public string GetDisplayText(IPlayer player, bool updateHorizontalStyle = false) + public string GetDisplayText( IPlayer player, bool updateHorizontalStyle = false ) { var sizeClass = MenuSizeHelper.GetSizeClass(Size); diff --git a/managed/src/SwiftlyS2.Core/Modules/Menus/Options/ChoiceMenuButton.cs b/managed/src/SwiftlyS2.Core/Modules/Menus/Options/ChoiceMenuButton.cs index ef7857c0..6b1c4f24 100644 --- a/managed/src/SwiftlyS2.Core/Modules/Menus/Options/ChoiceMenuButton.cs +++ b/managed/src/SwiftlyS2.Core/Modules/Menus/Options/ChoiceMenuButton.cs @@ -23,7 +23,7 @@ internal class ChoiceMenuOption : IOption public string SelectedChoice => Choices.Count > 0 ? Choices[SelectedIndex] : ""; - public ChoiceMenuOption(string text, IEnumerable choices, string? defaultChoice = null, Action? onChange = null, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null) + public ChoiceMenuOption( string text, IEnumerable choices, string? defaultChoice = null, Action? onChange = null, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null ) { Text = text; Choices = [.. choices]; @@ -40,7 +40,7 @@ public ChoiceMenuOption(string text, IEnumerable choices, string? defaul OverflowStyle = overflowStyle; } - public ChoiceMenuOption(string text, IEnumerable choices, string? defaultChoice, Action? onChange, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null) + public ChoiceMenuOption( string text, IEnumerable choices, string? defaultChoice, Action? onChange, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null ) { Text = text; Choices = [.. choices]; @@ -57,17 +57,13 @@ public ChoiceMenuOption(string text, IEnumerable choices, string? defaul OverflowStyle = overflowStyle; } - public bool ShouldShow(IPlayer player) - { - return VisibilityCheck?.Invoke(player) ?? true; - } + public bool ShouldShow( IPlayer player ) => VisibilityCheck?.Invoke(player) ?? true; - public bool CanInteract(IPlayer player) - { - return EnabledCheck?.Invoke(player) ?? true; - } + public bool CanInteract( IPlayer player ) => EnabledCheck?.Invoke(player) ?? true; + + public bool HasSound() => true; - public string GetDisplayText(IPlayer player, bool updateHorizontalStyle = false) + public string GetDisplayText( IPlayer player, bool updateHorizontalStyle = false ) { var sizeClass = MenuSizeHelper.GetSizeClass(Size); @@ -86,16 +82,22 @@ public IMenuTextSize GetTextSize() return Size; } - public void Next(IPlayer player) + public void Next( IPlayer player ) { - if (!CanInteract(player) || Choices.Count == 0) return; + if (!CanInteract(player) || Choices.Count == 0) + { + return; + } SelectedIndex = (SelectedIndex + 1) % Choices.Count; OnChange?.Invoke(player, SelectedChoice); OnChangeWithOption?.Invoke(player, this, SelectedChoice); } - public void Previous(IPlayer player) + public void Previous( IPlayer player ) { - if (!CanInteract(player) || Choices.Count == 0) return; + if (!CanInteract(player) || Choices.Count == 0) + { + return; + } SelectedIndex = (SelectedIndex - 1 + Choices.Count) % Choices.Count; OnChange?.Invoke(player, SelectedChoice); OnChangeWithOption?.Invoke(player, this, SelectedChoice); diff --git a/managed/src/SwiftlyS2.Core/Modules/Menus/Options/DynamicMenuOption.cs b/managed/src/SwiftlyS2.Core/Modules/Menus/Options/DynamicMenuOption.cs index ef61f4a0..2a646e1c 100644 --- a/managed/src/SwiftlyS2.Core/Modules/Menus/Options/DynamicMenuOption.cs +++ b/managed/src/SwiftlyS2.Core/Modules/Menus/Options/DynamicMenuOption.cs @@ -21,8 +21,7 @@ internal class DynamicMenuOption : IOption public IMenu? Menu { get; set; } public MenuHorizontalStyle? OverflowStyle { get; init; } - public string Text - { + public string Text { get => _cachedText; set => _cachedText = value; } @@ -30,7 +29,7 @@ public string Text public bool Visible => true; public bool Enabled => true; - public DynamicMenuOption(Func textProvider, TimeSpan updateInterval, Action? onClick = null, IMenuTextSize size = IMenuTextSize.Medium) + public DynamicMenuOption( Func textProvider, TimeSpan updateInterval, Action? onClick = null, IMenuTextSize size = IMenuTextSize.Medium ) { _textProvider = textProvider; _updateInterval = updateInterval; @@ -38,7 +37,7 @@ public DynamicMenuOption(Func textProvider, TimeSpan updateInte _size = size; } - public DynamicMenuOption(Func textProvider, TimeSpan updateInterval, Action? onClick = null, IMenuTextSize size = IMenuTextSize.Medium) + public DynamicMenuOption( Func textProvider, TimeSpan updateInterval, Action? onClick = null, IMenuTextSize size = IMenuTextSize.Medium ) { _textProvider = _ => textProvider(); _updateInterval = updateInterval; @@ -46,17 +45,13 @@ public DynamicMenuOption(Func textProvider, TimeSpan updateInterval, Act _size = size; } - public bool ShouldShow(IPlayer player) - { - return _visibilityCheck?.Invoke(player) ?? true; - } + public bool ShouldShow( IPlayer player ) => _visibilityCheck?.Invoke(player) ?? true; - public bool CanInteract(IPlayer player) - { - return _onClick != null && (_enabledCheck?.Invoke(player) ?? true); - } + public bool CanInteract( IPlayer player ) => _onClick != null && (_enabledCheck?.Invoke(player) ?? true); + + public bool HasSound() => false; - public string GetDisplayText(IPlayer player, bool updateHorizontalStyle = false) + public string GetDisplayText( IPlayer player, bool updateHorizontalStyle = false ) { var sizeClass = MenuSizeHelper.GetSizeClass(_size); @@ -86,7 +81,7 @@ public IMenuTextSize GetTextSize() return _size; } - public void Click(IPlayer player) + public void Click( IPlayer player ) { if (CanInteract(player)) { @@ -99,26 +94,26 @@ public void Click(IPlayer player) } } - public DynamicMenuOption WithVisibilityCheck(Func check) + public DynamicMenuOption WithVisibilityCheck( Func check ) { _visibilityCheck = check; return this; } - public DynamicMenuOption WithEnabledCheck(Func check) + public DynamicMenuOption WithEnabledCheck( Func check ) { _enabledCheck = check; return this; } - public DynamicMenuOption WithValidation(Func check, Action? onFailed = null) + public DynamicMenuOption WithValidation( Func check, Action? onFailed = null ) { _validationCheck = check; _onValidationFailed = onFailed; return this; } - public DynamicMenuOption WithCloseOnSelect(bool close = true) + public DynamicMenuOption WithCloseOnSelect( bool close = true ) { _closeOnSelect = close; return this; diff --git a/managed/src/SwiftlyS2.Core/Modules/Menus/Options/ProgressBarMenuButton.cs b/managed/src/SwiftlyS2.Core/Modules/Menus/Options/ProgressBarMenuButton.cs index c54c0631..1c2de798 100644 --- a/managed/src/SwiftlyS2.Core/Modules/Menus/Options/ProgressBarMenuButton.cs +++ b/managed/src/SwiftlyS2.Core/Modules/Menus/Options/ProgressBarMenuButton.cs @@ -4,7 +4,7 @@ namespace SwiftlyS2.Core.Menu.Options; -internal class ProgressBarMenuOption(string text, Func progressProvider, int barWidth = 20, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null) : IOption +internal class ProgressBarMenuOption( string text, Func progressProvider, int barWidth = 20, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null ) : IOption { public string Text { get; set; } = text; public Func ProgressProvider { get; set; } = progressProvider; @@ -19,10 +19,11 @@ internal class ProgressBarMenuOption(string text, Func progressProvider, public bool Visible => true; public bool Enabled => false; - public bool ShouldShow(IPlayer player) => true; - public bool CanInteract(IPlayer player) => false; + public bool ShouldShow( IPlayer player ) => true; + public bool CanInteract( IPlayer player ) => false; + public bool HasSound() => false; - public string GetDisplayText(IPlayer player, bool updateHorizontalStyle = false) + public string GetDisplayText( IPlayer player, bool updateHorizontalStyle = false ) { var sizeClass = MenuSizeHelper.GetSizeClass(Size); diff --git a/managed/src/SwiftlyS2.Core/Modules/Menus/Options/SeparatorMenuButton.cs b/managed/src/SwiftlyS2.Core/Modules/Menus/Options/SeparatorMenuButton.cs index 0377eb30..dc36e073 100644 --- a/managed/src/SwiftlyS2.Core/Modules/Menus/Options/SeparatorMenuButton.cs +++ b/managed/src/SwiftlyS2.Core/Modules/Menus/Options/SeparatorMenuButton.cs @@ -17,10 +17,11 @@ public SeparatorMenuOption() Text = "─────────────────────"; } - public bool ShouldShow(IPlayer player) => true; - public bool CanInteract(IPlayer player) => false; + public bool ShouldShow( IPlayer player ) => true; + public bool CanInteract( IPlayer player ) => false; + public bool HasSound() => false; - public string GetDisplayText(IPlayer player, bool updateHorizontalStyle = false) + public string GetDisplayText( IPlayer player, bool updateHorizontalStyle = false ) { return $"{Text}"; } diff --git a/managed/src/SwiftlyS2.Core/Modules/Menus/Options/SliderMenuButton.cs b/managed/src/SwiftlyS2.Core/Modules/Menus/Options/SliderMenuButton.cs index c45ffa78..03ed5f3d 100644 --- a/managed/src/SwiftlyS2.Core/Modules/Menus/Options/SliderMenuButton.cs +++ b/managed/src/SwiftlyS2.Core/Modules/Menus/Options/SliderMenuButton.cs @@ -23,7 +23,7 @@ internal class SliderMenuButton : IOption public bool Visible => true; public bool Enabled => true; - public SliderMenuButton(string text, float min = 0, float max = 10, float defaultValue = 5, float step = 1, Action? onChange = null, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null) + public SliderMenuButton( string text, float min = 0, float max = 10, float defaultValue = 5, float step = 1, Action? onChange = null, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null ) { Text = text; Min = min; @@ -35,7 +35,7 @@ public SliderMenuButton(string text, float min = 0, float max = 10, float defaul OverflowStyle = overflowStyle; } - public SliderMenuButton(string text, float min, float max, float defaultValue, float step, Action? onChange, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null) + public SliderMenuButton( string text, float min, float max, float defaultValue, float step, Action? onChange, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null ) { Text = text; Min = min; @@ -47,17 +47,13 @@ public SliderMenuButton(string text, float min, float max, float defaultValue, f OverflowStyle = overflowStyle; } - public bool ShouldShow(IPlayer player) - { - return VisibilityCheck?.Invoke(player) ?? true; - } + public bool ShouldShow( IPlayer player ) => VisibilityCheck?.Invoke(player) ?? true; - public bool CanInteract(IPlayer player) - { - return EnabledCheck?.Invoke(player) ?? true; - } + public bool CanInteract( IPlayer player ) => EnabledCheck?.Invoke(player) ?? true; + + public bool HasSound() => true; - public string GetDisplayText(IPlayer player, bool updateHorizontalStyle = false) + public string GetDisplayText( IPlayer player, bool updateHorizontalStyle = false ) { var sizeClass = MenuSizeHelper.GetSizeClass(Size); @@ -89,15 +85,18 @@ public IMenuTextSize GetTextSize() return Size; } - private static float Wrap(float value, float min, float max) + private static float Wrap( float value, float min, float max ) { float range = max - min; return ((value - min) % range + range) % range + min; } - public void Increase(IPlayer player) + public void Increase( IPlayer player ) { - if (!CanInteract(player)) return; + if (!CanInteract(player)) + { + return; + } var newValue = Wrap(Value + Step, Min, Max); @@ -108,9 +107,12 @@ public void Increase(IPlayer player) OnChangeWithOption?.Invoke(player, this, Value); } } - public void Decrease(IPlayer player) + public void Decrease( IPlayer player ) { - if (!CanInteract(player)) return; + if (!CanInteract(player)) + { + return; + } var newValue = Wrap(Value - Step, Min, Max); diff --git a/managed/src/SwiftlyS2.Core/Modules/Menus/Options/SubmenuMenuOption.cs b/managed/src/SwiftlyS2.Core/Modules/Menus/Options/SubmenuMenuOption.cs index 27092f85..df39a78c 100644 --- a/managed/src/SwiftlyS2.Core/Modules/Menus/Options/SubmenuMenuOption.cs +++ b/managed/src/SwiftlyS2.Core/Modules/Menus/Options/SubmenuMenuOption.cs @@ -39,15 +39,11 @@ public SubmenuMenuOption( string text, Func> asyncSubmenuBuilder, IM Size = size; } - public bool ShouldShow( IPlayer player ) - { - return VisibilityCheck?.Invoke(player) ?? true; - } + public bool ShouldShow( IPlayer player ) => VisibilityCheck?.Invoke(player) ?? true; - public bool CanInteract( IPlayer player ) - { - return EnabledCheck?.Invoke(player) ?? true; - } + public bool CanInteract( IPlayer player ) => EnabledCheck?.Invoke(player) ?? true; + + public bool HasSound() => true; public string GetDisplayText( IPlayer player, bool updateHorizontalStyle = false ) { diff --git a/managed/src/SwiftlyS2.Core/Modules/Menus/Options/TextMenuOption.cs b/managed/src/SwiftlyS2.Core/Modules/Menus/Options/TextMenuOption.cs index 4fca0796..48bd19eb 100644 --- a/managed/src/SwiftlyS2.Core/Modules/Menus/Options/TextMenuOption.cs +++ b/managed/src/SwiftlyS2.Core/Modules/Menus/Options/TextMenuOption.cs @@ -17,7 +17,7 @@ internal class TextMenuOption : IOption public bool Visible => true; public bool Enabled => false; - public TextMenuOption(string text, ITextAlign alignment = ITextAlign.Left, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null) + public TextMenuOption( string text, ITextAlign alignment = ITextAlign.Left, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null ) { Text = text; Alignment = alignment; @@ -25,7 +25,7 @@ public TextMenuOption(string text, ITextAlign alignment = ITextAlign.Left, IMenu OverflowStyle = overflowStyle; } - public TextMenuOption(Func dynamicText, ITextAlign alignment = ITextAlign.Left, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null) + public TextMenuOption( Func dynamicText, ITextAlign alignment = ITextAlign.Left, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null ) { Text = string.Empty; DynamicText = dynamicText; @@ -34,17 +34,13 @@ public TextMenuOption(Func dynamicText, ITextAlign alignment = ITextAlig OverflowStyle = overflowStyle; } - public bool ShouldShow(IPlayer player) - { - return VisibilityCheck?.Invoke(player) ?? true; - } + public bool ShouldShow( IPlayer player ) => VisibilityCheck?.Invoke(player) ?? true; - public bool CanInteract(IPlayer player) - { - return true; - } + public bool CanInteract( IPlayer player ) => true; + + public bool HasSound() => false; - public string GetDisplayText(IPlayer player, bool updateHorizontalStyle) + public string GetDisplayText( IPlayer player, bool updateHorizontalStyle ) { var text = DynamicText?.Invoke() ?? Text; @@ -55,8 +51,7 @@ public string GetDisplayText(IPlayer player, bool updateHorizontalStyle) text = $"{text}"; - return Alignment switch - { + return Alignment switch { ITextAlign.Center => $"
{text}
", ITextAlign.Right => $"
{text}
", _ => text diff --git a/managed/src/SwiftlyS2.Core/Modules/Menus/Options/ToggleMenuOption.cs b/managed/src/SwiftlyS2.Core/Modules/Menus/Options/ToggleMenuOption.cs index cfd4f313..f70f642c 100644 --- a/managed/src/SwiftlyS2.Core/Modules/Menus/Options/ToggleMenuOption.cs +++ b/managed/src/SwiftlyS2.Core/Modules/Menus/Options/ToggleMenuOption.cs @@ -22,7 +22,7 @@ internal class ToggleMenuOption : IOption public bool Visible => true; public bool Enabled => true; - public ToggleMenuOption(string text, bool defaultValue = false, Action? onToggle = null, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null) + public ToggleMenuOption( string text, bool defaultValue = false, Action? onToggle = null, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null ) { Text = text; Value = defaultValue; @@ -31,7 +31,7 @@ public ToggleMenuOption(string text, bool defaultValue = false, Action? onToggle, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null) + public ToggleMenuOption( string text, bool defaultValue, Action? onToggle, IMenuTextSize size = IMenuTextSize.Medium, MenuHorizontalStyle? overflowStyle = null ) { Text = text; Value = defaultValue; @@ -40,17 +40,13 @@ public ToggleMenuOption(string text, bool defaultValue, Action VisibilityCheck?.Invoke(player) ?? true; - public bool CanInteract(IPlayer player) - { - return EnabledCheck?.Invoke(player) ?? true; - } + public bool CanInteract( IPlayer player ) => EnabledCheck?.Invoke(player) ?? true; + + public bool HasSound() => true; - public string GetDisplayText(IPlayer player, bool updateHorizontalStyle = false) + public string GetDisplayText( IPlayer player, bool updateHorizontalStyle = false ) { var sizeClass = MenuSizeHelper.GetSizeClass(Size); @@ -70,7 +66,7 @@ public IMenuTextSize GetTextSize() return Size; } - public void Toggle(IPlayer player) + public void Toggle( IPlayer player ) { if (!CanInteract(player)) return; diff --git a/managed/src/SwiftlyS2.Shared/Modules/Menus/IMenu.cs b/managed/src/SwiftlyS2.Shared/Modules/Menus/IMenu.cs index ff7b515a..21561214 100644 --- a/managed/src/SwiftlyS2.Shared/Modules/Menus/IMenu.cs +++ b/managed/src/SwiftlyS2.Shared/Modules/Menus/IMenu.cs @@ -138,14 +138,14 @@ public interface IMenu /// Displays the menu interface and begins player interaction. /// /// The player to show the menu to. - public void Show(IPlayer player); + public void Show( IPlayer player ); /// /// Closes the menu for the specified player. /// Hides the menu interface and ends player interaction. /// /// The player to close the menu for. - public void Close(IPlayer player); + public void Close( IPlayer player ); /// /// Moves the player's selection by the specified offset. @@ -153,14 +153,14 @@ public interface IMenu /// /// The player whose selection to move. /// The number of positions to move the selection. - public void MoveSelection(IPlayer player, int offset); + public void MoveSelection( IPlayer player, int offset ); /// /// Activates the currently selected option for the specified player. /// Triggers the selected option's action or behavior. /// /// The player whose current selection to use. - public void UseSelection(IPlayer player); + public void UseSelection( IPlayer player ); /// /// Handles slide option interaction for the specified player. @@ -168,7 +168,7 @@ public interface IMenu /// /// The player interacting with the slide option. /// True if sliding right, false if sliding left. - public void UseSlideOption(IPlayer player, bool isRight); + public void UseSlideOption( IPlayer player, bool isRight ); /// /// Forces a re-render of the menu for the specified player. @@ -176,21 +176,20 @@ public interface IMenu /// /// The player to re-render the menu for. /// True to update horizontal style, false to render without updating horizontal style. - public void Rerender(IPlayer player, bool updateHorizontalStyle = false); + public void Rerender( IPlayer player, bool updateHorizontalStyle = false ); - /// - /// Determines whether the currently selected option is selectable for the specified player. - /// Returns true if the option can be activated, false if it's disabled or non-interactive. - /// - /// The player to check the current selection for. - /// True if the current option is selectable, false otherwise. - public bool IsCurrentOptionSelectable(IPlayer player); + [Obsolete("Use GetCurrentOption instead")] + public bool IsCurrentOptionSelectable( IPlayer player ); + + [Obsolete("Use GetCurrentOption instead")] + public bool IsOptionSlider( IPlayer player ); /// - /// Determines whether the currently selected option is a slider for the specified player. - /// Returns true if the option is a slider type, false otherwise. + /// Gets the currently selected option for the specified player. /// - public bool IsOptionSlider(IPlayer player); + /// The player to get the current option for. + /// The currently selected option, or null if no option is selected. + public IOption? GetCurrentOption( IPlayer player ); /// /// Sets the freeze state for the specified player while the menu is active. @@ -198,7 +197,7 @@ public interface IMenu /// /// The player to set the freeze state for. /// True to freeze the player, false to unfreeze. - public void SetFreezeState(IPlayer player, bool freeze); + public void SetFreezeState( IPlayer player, bool freeze ); /// /// Gets or sets the vertical scroll style for the menu navigation. @@ -289,11 +288,9 @@ public readonly record struct MenuHorizontalStyle /// /// The maximum display width for menu option text in relative units. /// - public required float MaxWidth - { + public required float MaxWidth { get => maxWidth; - init - { + init { if (value < 1f) { Spectre.Console.AnsiConsole.WriteException(new ArgumentOutOfRangeException(nameof(MaxWidth), $"MaxWidth: value {value:F3} is out of range.")); @@ -337,13 +334,13 @@ public MenuHorizontalStyle() /// /// Creates a horizontal style with truncate end behavior. /// - public static MenuHorizontalStyle TruncateEnd(float maxWidth) => + public static MenuHorizontalStyle TruncateEnd( float maxWidth ) => new() { MaxWidth = maxWidth, OverflowStyle = MenuHorizontalOverflowStyle.TruncateEnd }; /// /// Creates a horizontal style with truncate both ends behavior. /// - public static MenuHorizontalStyle TruncateBothEnds(float maxWidth) => + public static MenuHorizontalStyle TruncateBothEnds( float maxWidth ) => new() { MaxWidth = maxWidth, OverflowStyle = MenuHorizontalOverflowStyle.TruncateBothEnds }; /// @@ -352,7 +349,7 @@ public static MenuHorizontalStyle TruncateBothEnds(float maxWidth) => /// Maximum display width for text. /// Number of ticks before scrolling by one character. /// Number of ticks to pause after completing one scroll loop. - public static MenuHorizontalStyle ScrollLeftFade(float maxWidth, int ticksPerScroll = 16, int pauseTicks = 0) => + public static MenuHorizontalStyle ScrollLeftFade( float maxWidth, int ticksPerScroll = 16, int pauseTicks = 0 ) => new() { MaxWidth = maxWidth, OverflowStyle = MenuHorizontalOverflowStyle.ScrollLeftFade, TicksPerScroll = ticksPerScroll, PauseTicks = pauseTicks }; /// @@ -361,7 +358,7 @@ public static MenuHorizontalStyle ScrollLeftFade(float maxWidth, int ticksPerScr /// Maximum display width for text. /// Number of ticks before scrolling by one character. /// Number of ticks to pause after completing one scroll loop. - public static MenuHorizontalStyle ScrollRightFade(float maxWidth, int ticksPerScroll = 16, int pauseTicks = 0) => + public static MenuHorizontalStyle ScrollRightFade( float maxWidth, int ticksPerScroll = 16, int pauseTicks = 0 ) => new() { MaxWidth = maxWidth, OverflowStyle = MenuHorizontalOverflowStyle.ScrollRightFade, TicksPerScroll = ticksPerScroll, PauseTicks = pauseTicks }; /// @@ -370,7 +367,7 @@ public static MenuHorizontalStyle ScrollRightFade(float maxWidth, int ticksPerSc /// Maximum display width for text. /// Number of ticks before scrolling by one character. /// Number of ticks to pause after completing one scroll loop. - public static MenuHorizontalStyle ScrollLeftLoop(float maxWidth, int ticksPerScroll = 16, int pauseTicks = 0) => + public static MenuHorizontalStyle ScrollLeftLoop( float maxWidth, int ticksPerScroll = 16, int pauseTicks = 0 ) => new() { MaxWidth = maxWidth, OverflowStyle = MenuHorizontalOverflowStyle.ScrollLeftLoop, TicksPerScroll = ticksPerScroll, PauseTicks = pauseTicks }; /// @@ -379,6 +376,6 @@ public static MenuHorizontalStyle ScrollLeftLoop(float maxWidth, int ticksPerScr /// Maximum display width for text. /// Number of ticks before scrolling by one character. /// Number of ticks to pause after completing one scroll loop. - public static MenuHorizontalStyle ScrollRightLoop(float maxWidth, int ticksPerScroll = 16, int pauseTicks = 0) => + public static MenuHorizontalStyle ScrollRightLoop( float maxWidth, int ticksPerScroll = 16, int pauseTicks = 0 ) => new() { MaxWidth = maxWidth, OverflowStyle = MenuHorizontalOverflowStyle.ScrollRightLoop, TicksPerScroll = ticksPerScroll, PauseTicks = pauseTicks }; } \ No newline at end of file diff --git a/managed/src/SwiftlyS2.Shared/Modules/Menus/IOption.cs b/managed/src/SwiftlyS2.Shared/Modules/Menus/IOption.cs index d8765642..cfc86b56 100644 --- a/managed/src/SwiftlyS2.Shared/Modules/Menus/IOption.cs +++ b/managed/src/SwiftlyS2.Shared/Modules/Menus/IOption.cs @@ -37,14 +37,14 @@ public interface IOption /// /// The player to check visibility for. /// True if the option should be shown to the player; otherwise, false. - public bool ShouldShow(IPlayer player); + public bool ShouldShow( IPlayer player ); /// /// Determines whether the specified player can interact with this option. /// /// The player to check interaction capability for. /// True if the player can interact with the option; otherwise, false. - public bool CanInteract(IPlayer player); + public bool CanInteract( IPlayer player ); /// /// Gets the display text for this option as it should appear to the specified player. @@ -52,13 +52,19 @@ public interface IOption /// The player requesting the display text. /// Indicates whether to update the horizontal style of the text. /// The formatted display text for the option. - public string GetDisplayText(IPlayer player, bool updateHorizontalStyle); + public string GetDisplayText( IPlayer player, bool updateHorizontalStyle ); /// /// Gets the text size configuration for this option. /// /// The text size setting for the option. public IMenuTextSize GetTextSize(); + + /// + /// Determines whether this option should play a sound when selected. + /// + /// True if the option should play a sound; otherwise, false. + public bool HasSound(); } /// diff --git a/managed/src/TestPlugin/BenchContext.cs b/managed/src/TestPlugin/BenchContext.cs index e019e4aa..b4cd0756 100644 --- a/managed/src/TestPlugin/BenchContext.cs +++ b/managed/src/TestPlugin/BenchContext.cs @@ -2,6 +2,7 @@ namespace TestPlugin; -public static class BenchContext { - public static CCSPlayerController? Controller { get; set; } +public static class BenchContext +{ + public static CCSPlayerController? Controller { get; set; } } \ No newline at end of file diff --git a/managed/src/TestPlugin/PlayerBenchmarks.cs b/managed/src/TestPlugin/PlayerBenchmarks.cs index 005e5ee7..2ddc79ef 100644 --- a/managed/src/TestPlugin/PlayerBenchmarks.cs +++ b/managed/src/TestPlugin/PlayerBenchmarks.cs @@ -3,27 +3,27 @@ namespace TestPlugin; -public class PlayerBenchmarks { +public class PlayerBenchmarks +{ + private CCSPlayerController _controller; - private CCSPlayerController _controller; - - [GlobalSetup] - public void Setup() - { - _controller = BenchContext.Controller; - - if (_controller is null) + [GlobalSetup] + public void Setup() { - throw new InvalidOperationException("Controller is not set"); + _controller = BenchContext.Controller; + + if (_controller is null) + { + throw new InvalidOperationException("Controller is not set"); + } } - } - [Benchmark] - public void Test() - { - for (int i = 0; i < 10000; i++) + [Benchmark] + public void Test() { - var a = _controller.Pawn.Value.WeaponServices.ActiveWeapon; + for (int i = 0; i < 10000; i++) + { + var a = _controller.Pawn.Value.WeaponServices.ActiveWeapon; + } } - } } \ No newline at end of file diff --git a/managed/src/TestPlugin/TestPlugin.cs b/managed/src/TestPlugin/TestPlugin.cs index 21ee8487..4a99d82a 100644 --- a/managed/src/TestPlugin/TestPlugin.cs +++ b/managed/src/TestPlugin/TestPlugin.cs @@ -35,729 +35,721 @@ namespace TestPlugin; public class TestConfig { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } + public int Age { get; set; } } - public class InProcessConfig : ManualConfig { - public InProcessConfig() - { - AddLogger(ConsoleLogger.Default); - AddJob(Job.Default - .WithToolchain(new InProcessNoEmitToolchain(true)) - .WithId("InProcess")); - } + public InProcessConfig() + { + AddLogger(ConsoleLogger.Default); + AddJob(Job.Default + .WithToolchain(new InProcessNoEmitToolchain(true)) + .WithId("InProcess")); + } } - [PluginMetadata(Id = "testplugin", Version = "1.0.0")] public class TestPlugin : BasePlugin { - - public TestPlugin( ISwiftlyCore core ) : base(core) - { - Console.WriteLine("[TestPlugin] TestPlugin constructed successfully!"); - // Console.WriteLine($"sizeof(bool): {sizeof(bool)}"); - // Console.WriteLine($"Marshal.SizeOf: {Marshal.SizeOf()}"); - Core.Event.OnWeaponServicesCanUseHook += ( @event ) => + public TestPlugin( ISwiftlyCore core ) : base(core) { - // Console.WriteLine($"WeaponServicesCanUse: {@event.Weapon.WeaponBaseVData.AttackMovespeedFactor} {@event.OriginalResult}"); - - }; - } - - + Console.WriteLine("[TestPlugin] TestPlugin constructed successfully!"); + // Console.WriteLine($"sizeof(bool): {sizeof(bool)}"); + // Console.WriteLine($"Marshal.SizeOf: {Marshal.SizeOf()}"); + Core.Event.OnWeaponServicesCanUseHook += ( @event ) => + { + // Console.WriteLine($"WeaponServicesCanUse: {@event.Weapon.WeaponBaseVData.AttackMovespeedFactor} {@event.OriginalResult}"); - [Command("be")] - public void Test2Command( ICommandContext context ) - { - BenchContext.Controller = context.Sender!.RequiredController; - BenchmarkRunner.Run(new InProcessConfig()); - } + }; + } - [GameEventHandler(HookMode.Pre)] - public HookResult OnPlayerSpawn( EventPlayerSpawn @event ) - { - if (!@event.UserIdPlayer.IsValid) + [Command("be")] + public void Test2Command( ICommandContext context ) { - return HookResult.Continue; + BenchContext.Controller = context.Sender!.RequiredController; + BenchmarkRunner.Run(new InProcessConfig()); } - var player = @event.UserIdPlayer.RequiredController; - if (player.InGameMoneyServices?.IsValid == true) + + [GameEventHandler(HookMode.Pre)] + public HookResult OnPlayerSpawn( EventPlayerSpawn @event ) { - player.InGameMoneyServices.Account = Core.ConVar.Find("mp_maxmoney")?.Value ?? 16000; - player.InGameMoneyServices.AccountUpdated(); + if (!@event.UserIdPlayer.IsValid) + { + return HookResult.Continue; + } + var player = @event.UserIdPlayer.RequiredController; + if (player.InGameMoneyServices?.IsValid == true) + { + player.InGameMoneyServices.Account = Core.ConVar.Find("mp_maxmoney")?.Value ?? 16000; + player.InGameMoneyServices.AccountUpdated(); + } + return HookResult.Continue; } - return HookResult.Continue; - } - - public override void Load( bool hotReload ) - { - // Core.Command.HookClientCommand((playerId, commandLine) => - // { - // Console.WriteLine("TestPlugin HookClientCommand " + playerId + " " + commandLine); - // return HookResult.Continue; - // }); - - // Core.Event.OnConsoleOutput += (@event) => - // { - // Console.WriteLine($"[TestPlugin] ConsoleOutput: {@event.Message}"); - // }; - - // Core.Event.OnCommandExecuteHook += (@event) => - // { - // if (@event.HookMode == HookMode.Pre) return; - // Core.Logger.LogInformation("CommandExecute: {name} with {args}", @event.Command[0], @event.Command.ArgS); - // }; - - // Core.Event.OnEntityStartTouch += (@event) => - // { - // Console.WriteLine($"[New] EntityStartTouch: {@event.Entity.Entity?.DesignerName} -> {@event.OtherEntity.Entity?.DesignerName}"); - // }; - - // Core.Event.OnEntityTouchHook += (@event) => - // { - // switch (@event.TouchType) - // { - // case EntityTouchType.StartTouch: - // Console.WriteLine($"EntityStartTouch: {@event.Entity.Entity?.DesignerName} -> {@event.OtherEntity.Entity?.DesignerName}"); - // break; - // case EntityTouchType.Touch: - // break; - // case EntityTouchType.EndTouch: - // if (@event.Entity.Entity?.DesignerName != "player" || @event.OtherEntity.Entity?.DesignerName != "player") - // { - // return; - // } - // var player = @event.Entity.As(); - // var otherPlayer = @event.OtherEntity.As(); - // Console.WriteLine($"EntityEndTouch: {(player.Controller.Value?.PlayerName ?? string.Empty)} -> {(otherPlayer.Controller.Value?.PlayerName ?? string.Empty)}"); - // break; - // } - // }; - - Core.Engine.ExecuteCommandWithBuffer("@ping", ( buffer ) => - { - Console.WriteLine($"pong: {buffer}"); - }); - Core.GameEvent.HookPre(@event => + public override void Load( bool hotReload ) { - @event.LocToken = "test"; - return HookResult.Continue; - }); - - Core.Configuration - .InitializeJsonWithModel("test.jsonc", "Main") - .Configure(( builder ) => - { - builder.AddJsonFile("test.jsonc", optional: false, reloadOnChange: true); - }); + // Core.Command.HookClientCommand((playerId, commandLine) => + // { + // Console.WriteLine("TestPlugin HookClientCommand " + playerId + " " + commandLine); + // return HookResult.Continue; + // }); + + // Core.Event.OnConsoleOutput += (@event) => + // { + // Console.WriteLine($"[TestPlugin] ConsoleOutput: {@event.Message}"); + // }; + + // Core.Event.OnCommandExecuteHook += (@event) => + // { + // if (@event.HookMode == HookMode.Pre) return; + // Core.Logger.LogInformation("CommandExecute: {name} with {args}", @event.Command[0], @event.Command.ArgS); + // }; + + // Core.Event.OnEntityStartTouch += (@event) => + // { + // Console.WriteLine($"[New] EntityStartTouch: {@event.Entity.Entity?.DesignerName} -> {@event.OtherEntity.Entity?.DesignerName}"); + // }; + + // Core.Event.OnEntityTouchHook += (@event) => + // { + // switch (@event.TouchType) + // { + // case EntityTouchType.StartTouch: + // Console.WriteLine($"EntityStartTouch: {@event.Entity.Entity?.DesignerName} -> {@event.OtherEntity.Entity?.DesignerName}"); + // break; + // case EntityTouchType.Touch: + // break; + // case EntityTouchType.EndTouch: + // if (@event.Entity.Entity?.DesignerName != "player" || @event.OtherEntity.Entity?.DesignerName != "player") + // { + // return; + // } + // var player = @event.Entity.As(); + // var otherPlayer = @event.OtherEntity.As(); + // Console.WriteLine($"EntityEndTouch: {(player.Controller.Value?.PlayerName ?? string.Empty)} -> {(otherPlayer.Controller.Value?.PlayerName ?? string.Empty)}"); + // break; + // } + // }; + + Core.Engine.ExecuteCommandWithBuffer("@ping", ( buffer ) => + { + Console.WriteLine($"pong: {buffer}"); + }); - ServiceCollection services = new(); + Core.GameEvent.HookPre(@event => + { + @event.LocToken = "test"; + return HookResult.Continue; + }); - services - .AddSwiftly(Core); + Core.Configuration + .InitializeJsonWithModel("test.jsonc", "Main") + .Configure(( builder ) => + { + builder.AddJsonFile("test.jsonc", optional: false, reloadOnChange: true); + }); - Core.Event.OnPrecacheResource += ( @event ) => - { - @event.AddItem("soundevents/mvp_anthem.vsndevts"); - }; + ServiceCollection services = new(); - Core.Event.OnConVarValueChanged += ( @event ) => - { - Console.WriteLine($"ConVar {@event.ConVarName} changed from {@event.OldValue} to {@event.NewValue} by player {@event.PlayerId}"); - }; + services + .AddSwiftly(Core); + Core.Event.OnPrecacheResource += ( @event ) => + { + @event.AddItem("soundevents/mvp_anthem.vsndevts"); + }; - // var provider = services.BuildServiceProvider(); + Core.Event.OnConVarValueChanged += ( @event ) => + { + Console.WriteLine($"ConVar {@event.ConVarName} changed from {@event.OldValue} to {@event.NewValue} by player {@event.PlayerId}"); + }; - // provider.GetRequiredService(); + // var provider = services.BuildServiceProvider(); - // Host.CreateDefaultBuilder() - // .ConfigureLogging((context, logging) => { - // logging.AddConsole(); - // }) - // .ConfigureAppConfiguration((context, config) => { - // config.SetBasePath(Core.Configuration.GetBasePath()); - // config.AddJsonFile("test.jsonc", optional: false, reloadOnChange: true); - // }) - // .ConfigureServices((context, services) => { - // services.AddOptionsWithValidateOnStart>() - // .Bind(context.Configuration.GetSection("Main")); - // }) - // .Build(); + // provider.GetRequiredService(); - // This can be used everywhere and the value will be updated when the config is changed - // Console.WriteLine(config.CurrentValue.Age); + // Host.CreateDefaultBuilder() + // .ConfigureLogging((context, logging) => { + // logging.AddConsole(); + // }) + // .ConfigureAppConfiguration((context, config) => { + // config.SetBasePath(Core.Configuration.GetBasePath()); + // config.AddJsonFile("test.jsonc", optional: false, reloadOnChange: true); + // }) + // .ConfigureServices((context, services) => { + // services.AddOptionsWithValidateOnStart>() + // .Bind(context.Configuration.GetSection("Main")); + // }) + // .Build(); - // var config = new TestConfig(); + // This can be used everywhere and the value will be updated when the config is changed + // Console.WriteLine(config.CurrentValue.Age); - // throw new Exception("TestPlugin loaded"); - // Core. + // var config = new TestConfig(); - int i = 0; + // throw new Exception("TestPlugin loaded"); - // var token2 = Core.Scheduler.Repeat(10, () => { - // Console.WriteLine(Core.Engine.TickCount); - // Console.WriteLine("TestPlugin Timer"); - // }); - Core.Logger.LogInformation("TestPlugin loaded"); + // Core. - using var se = new SoundEvent(); + int i = 0; - // var func = Core.Memory.GetUnmanagedFunctionByAddress(Core.Memory.GetAddressBySignature(Library.Server, "AAAAA")!.Value); + // var token2 = Core.Scheduler.Repeat(10, () => { + // Console.WriteLine(Core.Engine.TickCount); + // Console.WriteLine("TestPlugin Timer"); + // }); + Core.Logger.LogInformation("TestPlugin loaded"); - // func.CallOriginal(1, 2); + using var se = new SoundEvent(); - // func.Call(1, 2); + // var func = Core.Memory.GetUnmanagedFunctionByAddress(Core.Memory.GetAddressBySignature(Library.Server, "AAAAA")!.Value); - // func.AddHook((next) => { - // return (a, b) => { - // Console.WriteLine("TestPlugin Hook " + a + " " + b); - // next()(a, b); - // }; - // }); + // func.CallOriginal(1, 2); + // func.Call(1, 2); - // Entrypoint + // func.AddHook((next) => { + // return (a, b) => { + // Console.WriteLine("TestPlugin Hook " + a + " " + b); + // next()(a, b); + // }; + // }); - // Core.Event.OnTick += () => { - // Console.WriteLine("TestPlugin OnTick "); - // }; - // Core.Event.OnClientConnected += (@event) => { - // Console.WriteLine("TestPlugin OnClientConnected " + @event.PlayerId); - // }; + // Entrypoint - // Core.Event.OnClientPutInServer += (@event) => { - // Console.WriteLine("TestPlugin OnClientPutInServer " + @event.PlayerId); - // }; + // Core.Event.OnTick += () => { + // Console.WriteLine("TestPlugin OnTick "); + // }; - Core.Event.OnClientDisconnected += ( @event ) => - { - Console.WriteLine("TestPlugin OnClientDisconnected " + @event.PlayerId); - }; - Core.Event.OnTick += () => - { - int i = 0; - }; + // Core.Event.OnClientConnected += (@event) => { + // Console.WriteLine("TestPlugin OnClientConnected " + @event.PlayerId); + // }; + // Core.Event.OnClientPutInServer += (@event) => { + // Console.WriteLine("TestPlugin OnClientPutInServer " + @event.PlayerId); + // }; - // Core.Event.OnClientProcessUsercmds += (@event) => { - // foreach(var usercmd in @event.Usercmds) { - // usercmd.Base.ButtonsPb.Buttonstate1 &= 1UL << (int)GameButtons.Ctrl; - // usercmd.Base.ButtonsPb.Buttonstate2 &= 1UL << (int)GameButtons.Ctrl; - // usercmd.Base.ButtonsPb.Buttonstate3 &= 1UL << (int)GameButtons.Ctrl; - // } - // }; + Core.Event.OnClientDisconnected += ( @event ) => + { + Console.WriteLine("TestPlugin OnClientDisconnected " + @event.PlayerId); + }; + Core.Event.OnTick += () => + { + int i = 0; + }; - // Core.NetMessage.HookClientMessage((msg, id) => { - // Console.WriteLine("TestPlugin OnClientMove "); - // Console.WriteLine(BitConverter.ToString(msg.Data)); - // return HookResult.Continue; - // }); + // Core.Event.OnClientProcessUsercmds += (@event) => { + // foreach(var usercmd in @event.Usercmds) { + // usercmd.Base.ButtonsPb.Buttonstate1 &= 1UL << (int)GameButtons.Ctrl; + // usercmd.Base.ButtonsPb.Buttonstate2 &= 1UL << (int)GameButtons.Ctrl; + // usercmd.Base.ButtonsPb.Buttonstate3 &= 1UL << (int)GameButtons.Ctrl; + // } + // }; - // Core.Event.OnEntityTakeDamage += (@event) => { - // Console.WriteLine("TestPlugin OnEntityTakeDamage " + @event.Entity.Entity?.DesignerName + " " + @event.Info.HitGroupId); - // }; + // Core.NetMessage.HookClientMessage((msg, id) => { + // Console.WriteLine("TestPlugin OnClientMove "); + // Console.WriteLine(BitConverter.ToString(msg.Data)); + // return HookResult.Continue; + // }); - // Core.Event.OnTick += () => { + // Core.Event.OnEntityTakeDamage += (@event) => { + // Console.WriteLine("TestPlugin OnEntityTakeDamage " + @event.Entity.Entity?.DesignerName + " " + @event.Info.HitGroupId); + // }; - // Console.WriteLine("TestPlugin OnTick"); - // }; + // Core.Event.OnTick += () => { - // Core.Event.OnEntityCreated += (ev) => { - // var entity = ev.Entity; - // entity.Entity.DesignerName = "a"; - // Console.WriteLine("TestPlugin OnEntityCreated " + ev.Entity.Entity?.DesignerName); - // }; + // Console.WriteLine("TestPlugin OnTick"); + // }; + // Core.Event.OnEntityCreated += (ev) => { + // var entity = ev.Entity; + // entity.Entity.DesignerName = "a"; + // Console.WriteLine("TestPlugin OnEntityCreated " + ev.Entity.Entity?.DesignerName); + // }; - using CEntityKeyValues kv = new(); + using CEntityKeyValues kv = new(); - kv.SetBool("test", true); + kv.SetBool("test", true); - Console.WriteLine(kv.Get("test2")); + Console.WriteLine(kv.Get("test2")); + CUtlStringToken token = new("hello"); + Console.WriteLine($"2"); + } - CUtlStringToken token = new("hello"); - Console.WriteLine($"2"); - } + CEntityKeyValues kv { get; set; } + CEntityInstance entity { get; set; } - CEntityKeyValues kv { get; set; } - CEntityInstance entity { get; set; } + [Command("tt")] + public void TestCommand( ICommandContext context ) + { + // token2?.Cancel(); + // kv = new(); + // kv.SetString("test", "SAFE"); + // _Core.Logger.LogInformation("!@#"); - [Command("tt")] - public void TestCommand( ICommandContext context ) - { - // token2?.Cancel(); - // kv = new(); - // kv.SetString("test", "SAFE"); + // _Core.Logger.LogInformation(_Core.GameData.GetSignature("CEntityInstance::AcceptInput").ToString()); + // entity = _Core.EntitySystem.CreateEntityByDesignerName("point_worldtext"); + // entity.DispatchSpawn(kv); + // Console.WriteLine("Spawned entity with keyvalues"); + int j = 0; - // _Core.Logger.LogInformation("!@#"); + var cvar = Core.ConVar.Find("sv_cheats")!; + Console.WriteLine(cvar); + Console.WriteLine(cvar.Value); + var cvar2 = Core.ConVar.Find("sv_autobunnyhopping")!; + Console.WriteLine(cvar2); + Console.WriteLine(cvar2.Value); - // _Core.Logger.LogInformation(_Core.GameData.GetSignature("CEntityInstance::AcceptInput").ToString()); + var cvar3 = Core.ConVar.Create("sw_test_cvar", "Test cvar", "ABCDEFG"); + Console.WriteLine(cvar3); + Console.WriteLine(cvar3.Value); - // entity = _Core.EntitySystem.CreateEntityByDesignerName("point_worldtext"); - // entity.DispatchSpawn(kv); - // Console.WriteLine("Spawned entity with keyvalues"); + var cvar4 = Core.ConVar.Find("r_drawworld")!; - int j = 0; + cvar2.ReplicateToClient(0, true); - var cvar = Core.ConVar.Find("sv_cheats")!; - Console.WriteLine(cvar); - Console.WriteLine(cvar.Value); - var cvar2 = Core.ConVar.Find("sv_autobunnyhopping")!; - Console.WriteLine(cvar2); - Console.WriteLine(cvar2.Value); + cvar4.QueryClient(0, ( value ) => + { + Console.WriteLine("QueryCallback " + value); + }); + } - var cvar3 = Core.ConVar.Create("sw_test_cvar", "Test cvar", "ABCDEFG"); - Console.WriteLine(cvar3); - Console.WriteLine(cvar3.Value); + [Command("w")] + public void TestCommand1( ICommandContext context ) + { + var attacker = context.Sender!; + var weapons = attacker.Pawn!.WeaponServices!.MyWeapons; + foreach (var weaponHandle in weapons) + { + var weapon = weaponHandle.Value?.As(); + if (weapon == null) + { + continue; + } + + Console.WriteLine($"Weapon: {weapon.DesignerName}"); + } + } - var cvar4 = Core.ConVar.Find("r_drawworld")!; + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + delegate nint DispatchSpawnDelegate( nint pEntity, nint pKV ); + int order = 0; - cvar2.ReplicateToClient(0, true); + IUnmanagedFunction? _dispatchspawn; - cvar4.QueryClient(0, ( value ) => - { - Console.WriteLine("QueryCallback " + value); - }); - } - - [Command("w")] - public void TestCommand1( ICommandContext context ) - { - var attacker = context.Sender!; - var weapons = attacker.Pawn!.WeaponServices!.MyWeapons; - foreach (var weaponHandle in weapons) + [Command("h1")] + public void TestCommand2( ICommandContext context ) { - var weapon = weaponHandle.Value?.As(); - if (weapon == null) - return; + // var token = Core.Scheduler.DelayAndRepeat(500, 1000, () => + // { - Console.WriteLine($"Weapon: {weapon.DesignerName}"); - } + // }); + + var addres = Core.GameData.GetSignature("CBaseEntity::DispatchSpawn"); + var func = Core.Memory.GetUnmanagedFunctionByAddress(addres); + + var guid = func.AddHook(( next ) => + { + return ( pEntity, pKV ) => + { + Console.WriteLine("TestPlugin DispatchSpawn " + order++); + return next()(pEntity, pKV); + }; + }); + + _dispatchspawn.AddHook(( next ) => + { + return ( pEntity, pKV ) => + { + Console.WriteLine("TestPlugin DispatchSpawn2 " + order++); + return next()(pEntity, pKV); + }; + }); - } + } - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - delegate nint DispatchSpawnDelegate( nint pEntity, nint pKV ); - int order = 0; + [EventListener] + public void OnEntityCreated( IOnEntityCreatedEvent @event ) + { + // @event.Entity.Entity.DesignerName = "abc"; + Console.WriteLine("TestPlugin OnEntityCreated222 " + @event.Entity.Entity?.DesignerName); + } - IUnmanagedFunction? _dispatchspawn; + Guid _hookId = Guid.Empty; - [Command("h1")] - public void TestCommand2( ICommandContext context ) - { - var token = Core.Scheduler.DelayAndRepeat(500, 1000, () => + [Command("bad")] + public void TestCommandBad( ICommandContext context ) { + try + { + var isValveDS = Core.EntitySystem.GetGameRules()!.IsValveDS; + } + catch (Exception e) + { + Core.Logger.LogWarning("{Exception}", e.Message); + } - }); + try + { + Core.EntitySystem.GetGameRules()!.IsValveDS = true; + } + catch (Exception e) + { + Core.Logger.LogWarning("{Exception}", e.Message); + } - var addres = Core.GameData.GetSignature("CBaseEntity::DispatchSpawn"); - var func = Core.Memory.GetUnmanagedFunctionByAddress(addres); + try + { + Core.EntitySystem.GetGameRules()!.IsValveDSUpdated(); + } + catch (Exception e) + { + Core.Logger.LogWarning("{Exception}", e.Message); + } + } - var guid = func.AddHook(( next ) => + [Command("h2")] + public void TestCommand3( ICommandContext context ) { - return ( pEntity, pKV ) => - { - Console.WriteLine("TestPlugin DispatchSpawn " + order++); - return next()(pEntity, pKV); - }; - }); - - _dispatchspawn.AddHook(( next ) => + var ent = Core.EntitySystem.CreateEntity(); + ent.DispatchSpawn(); + ent.Collision.MaxsUpdated(); + ent.Collision.CollisionAttribute.OwnerIdUpdated(); + } + + [Command("tt3")] + public void TestCommand33( ICommandContext context ) + { + var ent = Core.EntitySystem.CreateEntity(); + using CEntityKeyValues kv = new(); + kv.Set("m_spawnflags", 256); + ent.DispatchSpawn(kv); + ent.SetModel("weapons/models/grenade/incendiary/weapon_incendiarygrenade.vmdl"); + ent.Teleport(new Vector(context.Sender!.PlayerPawn!.AbsOrigin!.Value.X + 50, context.Sender!.PlayerPawn!.AbsOrigin!.Value.Y + 50, context.Sender!.PlayerPawn!.AbsOrigin!.Value.Z + 30), QAngle.Zero, Vector.Zero); + } + + [Command("tt4")] + public void TestCommand4( ICommandContext context ) + { + Console.WriteLine(Core.Permission.PlayerHasPermission(7656, context.Args[0])); + } + + [Command("tt5")] + public void TestCommand5( ICommandContext context ) { - return ( pEntity, pKV ) => - { - Console.WriteLine("TestPlugin DispatchSpawn2 " + order++); - return next()(pEntity, pKV); - }; - }); - - } - - [EventListener] - public void OnEntityCreated( IOnEntityCreatedEvent @event ) - { - // @event.Entity.Entity.DesignerName = "abc"; - Console.WriteLine("TestPlugin OnEntityCreated222 " + @event.Entity.Entity?.DesignerName); - } - - Guid _hookId = Guid.Empty; - - [Command("bad")] - public void TestCommandBad( ICommandContext context ) - { - try + Console.WriteLine("TestPlugin TestCommand5"); + } + + [Command("tt6", permission: "tt6")] + public void TestCommand6( ICommandContext context ) { - var isValveDS = Core.EntitySystem.GetGameRules()!.IsValveDS; + Console.WriteLine("TestPlugin TestCommand6"); } - catch (Exception e) + + [Command("tt7")] + public void TestCommand7( ICommandContext context ) { - Core.Logger.LogWarning("{Exception}", e.Message); + Core.Engine.ExecuteCommandWithBuffer("@ping", ( buffer ) => + { + Console.WriteLine($"pong: {buffer}"); + }); } - try + [Command("tt8")] + public unsafe void TestCommand8( ICommandContext context ) { - Core.EntitySystem.GetGameRules()!.IsValveDS = true; + Core.EntitySystem.GetAllEntitiesByDesignerName("func_buyzone").ToList().ForEach(zone => + { + if ((zone?.IsValid ?? false)) + { + zone.Despawn(); + } + }); + + var sender = context.Sender!; + var target = Core.PlayerManager.GetAllPlayers().FirstOrDefault(p => p.PlayerID != sender.PlayerID)!; + + var origin = sender.RequiredPlayerPawn.AbsOrigin ?? Vector.Zero; + var targetOrigin = target.RequiredPlayerPawn.AbsOrigin ?? Vector.Zero; + + Console.WriteLine("\n"); + Console.WriteLine($"Origin: {origin}"); + Console.WriteLine($"Target Origin: {targetOrigin}"); + + // Ray_t* ray = stackalloc Ray_t[1]; + // ray->Init(Vector.Zero, Vector.Zero); + Ray_t ray = new(); + ray.Init(Vector.Zero, Vector.Zero); + + var filter = new CTraceFilter { + // unk01 = 1, + IterateEntities = true, + QueryShapeAttributes = new RnQueryShapeAttr_t { + InteractsWith = MaskTrace.Player | MaskTrace.Solid | MaskTrace.Hitbox | MaskTrace.Npc, + InteractsExclude = MaskTrace.Empty, + InteractsAs = MaskTrace.Player, + CollisionGroup = CollisionGroup.PlayerMovement, + ObjectSetMask = RnQueryObjectSet.AllGameEntities, + HitSolid = true, + // HitTrigger = false, + // HitSolidRequiresGenerateContacts = false, + // ShouldIgnoreDisabledPairs = true, + // IgnoreIfBothInteractWithHitboxes = true, + // ForceHitEverything = true + } + }; + + // filter.QueryShapeAttributes.EntityIdsToIgnore[0] = unchecked((uint)-1); + // filter.QueryShapeAttributes.EntityIdsToIgnore[1] = unchecked((uint)-1); + // filter.QueryShapeAttributes.OwnerIdsToIgnore[0] = unchecked((uint)-1); + // filter.QueryShapeAttributes.OwnerIdsToIgnore[1] = unchecked((uint)-1); + // filter.QueryShapeAttributes.HierarchyIds[0] = 0; + // filter.QueryShapeAttributes.HierarchyIds[1] = 0; + + var trace = new CGameTrace(); + Core.Trace.TraceShape(origin, targetOrigin, ray, filter, ref trace); + + Console.WriteLine(trace.pEntity != null ? $"! Hit Entity: {trace.Entity.DesignerName}" : "! No entity hit"); + Console.WriteLine($"! SurfaceProperties: {(nint)trace.SurfaceProperties}, pEntity: {(nint)trace.pEntity}, HitBox: {(nint)trace.HitBox}({trace.HitBox->m_name.Value}), Body: {(nint)trace.Body}, Shape: {(nint)trace.Shape}, Contents: {trace.Contents}"); + Console.WriteLine($"! StartPos: {trace.StartPos}, EndPos: {trace.EndPos}, HitNormal: {trace.HitNormal}, HitPoint: {trace.HitPoint}"); + Console.WriteLine($"! HitOffset: {trace.HitOffset}, Fraction: {trace.Fraction}, Triangle: {trace.Triangle}, HitboxBoneIndex: {trace.HitboxBoneIndex}"); + Console.WriteLine($"! RayType: {trace.RayType}, StartInSolid: {trace.StartInSolid}, ExactHitPoint: {trace.ExactHitPoint}"); + Console.WriteLine("\n"); } - catch (Exception e) + + [GameEventHandler(HookMode.Pre)] + public HookResult TestGameEventHandler( EventPlayerJump @e ) { - Core.Logger.LogWarning("{Exception}", e.Message); + Console.WriteLine(@e.UserIdController.PlayerName); + return HookResult.Continue; } - try + [ServerNetMessageHandler] + public HookResult TestServerNetMessageHandler( CCSUsrMsg_SendPlayerItemDrops msg ) { - Core.EntitySystem.GetGameRules()!.IsValveDSUpdated(); + Console.WriteLine("FIRED"); + // foreach(var item in msg.Accessor) { + // Console.WriteLine($"TestPlugin ServerNetMessageHandler: {item.EconItem.Defindex}"); + // } + return HookResult.Continue; } - catch (Exception e) + + private Callback _authTicketResponse; + + [EventListener] + public void OnSteamAPIActivated() { - Core.Logger.LogWarning("{Exception}", e.Message); + Console.WriteLine("TestPlugin OnSteamAPIActivated"); + _authTicketResponse = Callback.Create(AuthResponse); } - } - - [Command("h2")] - public void TestCommand3( ICommandContext context ) - { - var ent = Core.EntitySystem.CreateEntity(); - ent.DispatchSpawn(); - ent.Collision.MaxsUpdated(); - ent.Collision.CollisionAttribute.OwnerIdUpdated(); - - } - - [Command("tt3")] - public void TestCommand33( ICommandContext context ) - { - var ent = Core.EntitySystem.CreateEntity(); - using CEntityKeyValues kv = new(); - kv.Set("m_spawnflags", 256); - ent.DispatchSpawn(kv); - ent.SetModel("weapons/models/grenade/incendiary/weapon_incendiarygrenade.vmdl"); - ent.Teleport(new Vector(context.Sender!.PlayerPawn!.AbsOrigin!.Value.X + 50, context.Sender!.PlayerPawn!.AbsOrigin!.Value.Y + 50, context.Sender!.PlayerPawn!.AbsOrigin!.Value.Z + 30), QAngle.Zero, Vector.Zero); - } - - [Command("tt4")] - public void TestCommand4( ICommandContext context ) - { - Console.WriteLine(Core.Permission.PlayerHasPermission(7656, context.Args[0])); - } - - [Command("tt5")] - public void TestCommand5( ICommandContext context ) - { - Console.WriteLine("TestPlugin TestCommand5"); - } - - [Command("tt6", permission: "tt6")] - public void TestCommand6( ICommandContext context ) - { - Console.WriteLine("TestPlugin TestCommand6"); - } - - [Command("tt7")] - public void TestCommand7( ICommandContext context ) - { - Core.Engine.ExecuteCommandWithBuffer("@ping", ( buffer ) => + + public void AuthResponse( ValidateAuthTicketResponse_t param ) { - Console.WriteLine($"pong: {buffer}"); - }); - } - - [Command("tt8")] - public unsafe void TestCommand8( ICommandContext context ) - { - Core.EntitySystem.GetAllEntitiesByDesignerName("func_buyzone").ToList().ForEach(zone => + Console.WriteLine($"AuthResponse: {param.m_eAuthSessionResponse} -> {param.m_SteamID.m_SteamID}"); + } + + [Command("getip")] + public void GetIpCommand( ICommandContext context ) { - if (!(zone?.IsValid ?? false)) return; - zone.Despawn(); - }); - - var sender = context.Sender!; - var target = Core.PlayerManager.GetAllPlayers().FirstOrDefault(p => p.PlayerID != sender.PlayerID)!; - - var origin = sender.RequiredPlayerPawn.AbsOrigin ?? Vector.Zero; - var targetOrigin = target.RequiredPlayerPawn.AbsOrigin ?? Vector.Zero; - - Console.WriteLine("\n"); - Console.WriteLine($"Origin: {origin}"); - Console.WriteLine($"Target Origin: {targetOrigin}"); - - // Ray_t* ray = stackalloc Ray_t[1]; - // ray->Init(Vector.Zero, Vector.Zero); - Ray_t ray = new(); - ray.Init(Vector.Zero, Vector.Zero); - - var filter = new CTraceFilter { - // unk01 = 1, - IterateEntities = true, - QueryShapeAttributes = new RnQueryShapeAttr_t { - InteractsWith = MaskTrace.Player | MaskTrace.Solid | MaskTrace.Hitbox | MaskTrace.Npc, - InteractsExclude = MaskTrace.Empty, - InteractsAs = MaskTrace.Player, - CollisionGroup = CollisionGroup.PlayerMovement, - ObjectSetMask = RnQueryObjectSet.AllGameEntities, - HitSolid = true, - // HitTrigger = false, - // HitSolidRequiresGenerateContacts = false, - // ShouldIgnoreDisabledPairs = true, - // IgnoreIfBothInteractWithHitboxes = true, - // ForceHitEverything = true - } - }; - - // filter.QueryShapeAttributes.EntityIdsToIgnore[0] = unchecked((uint)-1); - // filter.QueryShapeAttributes.EntityIdsToIgnore[1] = unchecked((uint)-1); - // filter.QueryShapeAttributes.OwnerIdsToIgnore[0] = unchecked((uint)-1); - // filter.QueryShapeAttributes.OwnerIdsToIgnore[1] = unchecked((uint)-1); - // filter.QueryShapeAttributes.HierarchyIds[0] = 0; - // filter.QueryShapeAttributes.HierarchyIds[1] = 0; - - var trace = new CGameTrace(); - Core.Trace.TraceShape(origin, targetOrigin, ray, filter, ref trace); - - Console.WriteLine(trace.pEntity != null ? $"! Hit Entity: {trace.Entity.DesignerName}" : "! No entity hit"); - Console.WriteLine($"! SurfaceProperties: {(nint)trace.SurfaceProperties}, pEntity: {(nint)trace.pEntity}, HitBox: {(nint)trace.HitBox}({trace.HitBox->m_name.Value}), Body: {(nint)trace.Body}, Shape: {(nint)trace.Shape}, Contents: {trace.Contents}"); - Console.WriteLine($"! StartPos: {trace.StartPos}, EndPos: {trace.EndPos}, HitNormal: {trace.HitNormal}, HitPoint: {trace.HitPoint}"); - Console.WriteLine($"! HitOffset: {trace.HitOffset}, Fraction: {trace.Fraction}, Triangle: {trace.Triangle}, HitboxBoneIndex: {trace.HitboxBoneIndex}"); - Console.WriteLine($"! RayType: {trace.RayType}, StartInSolid: {trace.StartInSolid}, ExactHitPoint: {trace.ExactHitPoint}"); - Console.WriteLine("\n"); - } - - [GameEventHandler(HookMode.Pre)] - public HookResult TestGameEventHandler( EventPlayerJump @e ) - { - Console.WriteLine(@e.UserIdController.PlayerName); - return HookResult.Continue; - } - - [ServerNetMessageHandler] - public HookResult TestServerNetMessageHandler( CCSUsrMsg_SendPlayerItemDrops msg ) - { - - Console.WriteLine("FIRED"); - // foreach(var item in msg.Accessor) { - // Console.WriteLine($"TestPlugin ServerNetMessageHandler: {item.EconItem.Defindex}"); - // } - return HookResult.Continue; - } - - private Callback _authTicketResponse; - - [EventListener] - public void OnSteamAPIActivated() - { - Console.WriteLine("TestPlugin OnSteamAPIActivated"); - _authTicketResponse = Callback.Create(AuthResponse); - } - - public void AuthResponse( ValidateAuthTicketResponse_t param ) - { - Console.WriteLine($"AuthResponse: {param.m_eAuthSessionResponse} -> {param.m_SteamID.m_SteamID}"); - } - - [Command("getip")] - public void GetIpCommand( ICommandContext context ) - { - context.Reply(SteamGameServer.GetPublicIP().ToString()); + context.Reply(SteamGameServer.GetPublicIP().ToString()); + } + [Command("i76")] public void TestIssue76Command( ICommandContext context ) { - var player = context.Sender!; - IMenu settingsMenu = Core.Menus.CreateMenu("Settings"); - // Add the following code to render text properly - //settingsMenu.Builder.AddText("123", overflowStyle: MenuHorizontalStyle.ScrollLeftLoop(25f)); - settingsMenu.Builder.AddText("123"); - settingsMenu.Builder.AddText("1234"); - settingsMenu.Builder.AddText("12345"); - - Core.Menus.OpenMenu(player, settingsMenu); + var player = context.Sender!; + IMenu settingsMenu = Core.Menus.CreateMenu("Settings"); + // Add the following code to render text properly + //settingsMenu.Builder.AddText("123", overflowStyle: MenuHorizontalStyle.ScrollLeftLoop(25f)); + settingsMenu.Builder.AddText("123"); + settingsMenu.Builder.AddText("1234"); + settingsMenu.Builder.AddText("12345"); + + Core.Menus.OpenMenu(player, settingsMenu); } [Command("i77")] public void TestIssue77Command( ICommandContext context ) { - var player = context.Sender!; - IMenu settingsMenu = Core.Menus.CreateMenu("Settings"); - - settingsMenu.Builder.AddText("123"); - settingsMenu.Builder.AddSubmenu("Submenu", () => - { - var menu = Core.Menus.CreateMenu("Submenu"); - menu.Builder.AddText("1234"); - return menu; - }); - - settingsMenu.Builder.AddSubmenu("Async Submenu", async () => - { - await Task.Delay(5000); - var menu = Core.Menus.CreateMenu("Async Submenu"); - menu.Builder.AddText("12345"); - return menu; - }); - - Core.Menus.OpenMenu(player, settingsMenu); + var player = context.Sender!; + IMenu settingsMenu = Core.Menus.CreateMenu("Settings"); + + settingsMenu.Builder.AddText("123"); + settingsMenu.Builder.AddSubmenu("Submenu", () => + { + var menu = Core.Menus.CreateMenu("Submenu"); + menu.Builder.AddText("1234"); + return menu; + }); + + settingsMenu.Builder.AddSubmenu("Async Submenu", async () => + { + await Task.Delay(5000); + var menu = Core.Menus.CreateMenu("Async Submenu"); + menu.Builder.AddText("12345"); + return menu; + }); + + Core.Menus.OpenMenu(player, settingsMenu); } [Command("i78")] public void TestIssue78Command( ICommandContext context ) { - var player = context.Sender!; - IMenu settingsMenu = Core.Menus.CreateMenu("Settings"); - settingsMenu.Builder.AddButton("123", ( p ) => - { - player.SendMessage(MessageType.Chat, "Button"); - }); + var player = context.Sender!; + IMenu settingsMenu = Core.Menus.CreateMenu("Settings"); + settingsMenu.Builder.AddButton("123", ( p ) => + { + player.SendMessage(MessageType.Chat, "Button"); + }); - settingsMenu.Builder.Design.OverrideExitButton("shift"); - settingsMenu.Builder.Design.OverrideSelectButton("e"); + settingsMenu.Builder.Design.OverrideExitButton("shift"); + settingsMenu.Builder.Design.OverrideSelectButton("e"); - Core.Menus.OpenMenu(player, settingsMenu); + Core.Menus.OpenMenu(player, settingsMenu); } [Command("mt")] public void MenuTestCommand( ICommandContext context ) { - var player = context.Sender!; - - IMenu settingsMenu = Core.Menus.CreateMenu("MenuTest"); - - settingsMenu.Builder.Design.MaxVisibleItems(5); - - // settingsMenu.Builder.Design.MaxVisibleItems(Random.Shared.Next(-2, 8)); - if (context.Args.Length < 1 || !int.TryParse(context.Args[0], out int vtype)) vtype = 0; - settingsMenu.Builder.Design.SetVerticalScrollStyle(vtype switch { - 1 => MenuVerticalScrollStyle.LinearScroll, - 2 => MenuVerticalScrollStyle.WaitingCenter, - _ => MenuVerticalScrollStyle.CenterFixed - }); - - if (context.Args.Length < 2 || !int.TryParse(context.Args[1], out int htype)) htype = 0; - settingsMenu.Builder.Design.SetGlobalHorizontalStyle(htype switch { - 0 => MenuHorizontalStyle.Default, - 1 => MenuHorizontalStyle.TruncateBothEnds(26f), - 2 => MenuHorizontalStyle.ScrollLeftFade(26f, 8, 128), - 3 => MenuHorizontalStyle.ScrollLeftLoop(26f, 8, 128), - 1337 => MenuHorizontalStyle.TruncateEnd(0f), - _ => MenuHorizontalStyle.TruncateEnd(26f) - }); - - settingsMenu.Builder.AddButton("1. AButton", ( p ) => - { - player.SendMessage(MessageType.Chat, "Button"); - }); - - settingsMenu.Builder.AddToggle("2. Toggle", defaultValue: true, ( p, value ) => - { - player.SendMessage(MessageType.Chat, $"AddToggle {value}"); - }); - - settingsMenu.Builder.AddSlider("3. Slider", min: 0, max: 100, defaultValue: 10, step: 10, ( p, value ) => - { - player.SendMessage(MessageType.Chat, $"AddSlider {value}"); - }); - - settingsMenu.Builder.AddAsyncButton("4. AsyncButton", async ( p ) => - { - await Task.Delay(2000); - }); - - settingsMenu.Builder.AddText("5. Text"); - settingsMenu.Builder.AddText("6. Text"); - settingsMenu.Builder.AddText("7. Text"); - settingsMenu.Builder.AddText("8. Text"); - settingsMenu.Builder.AddText("9. Text"); - settingsMenu.Builder.AddSeparator(); - settingsMenu.Builder.AddText($"{HtmlGradient.GenerateGradientText("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", "#FFE4E1", "#FFC0CB", "#FF69B4")}", overflowStyle: MenuHorizontalStyle.TruncateEnd(26f)); - settingsMenu.Builder.AddText($"{HtmlGradient.GenerateGradientText("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", "#FFE5CC", "#FFAB91", "#FF7043")}", overflowStyle: MenuHorizontalStyle.TruncateBothEnds(26f)); - settingsMenu.Builder.AddText($"{HtmlGradient.GenerateGradientText("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", "#E6E6FA", "#00FFFF", "#FF1493")}", overflowStyle: MenuHorizontalStyle.ScrollRightFade(26f, 8)); - settingsMenu.Builder.AddText($"{HtmlGradient.GenerateGradientText("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", "#AFEEEE", "#7FFFD4", "#40E0D0")}", overflowStyle: MenuHorizontalStyle.ScrollLeftLoop(26f, 8)); - settingsMenu.Builder.AddText("12345678901234567890split12345678901234567890", overflowStyle: MenuHorizontalStyle.ScrollLeftFade(26f, 8, 128)); - settingsMenu.Builder.AddText("一二三四五六七八九十分割一二三四五六七八九十", overflowStyle: MenuHorizontalStyle.ScrollRightLoop(26f, 8, 64)); - settingsMenu.Builder.AddSeparator(); - settingsMenu.Builder.AddText("Swiftlys2 向这广袤世界致以温柔问候", overflowStyle: MenuHorizontalStyle.ScrollRightLoop(26f, 8)); - settingsMenu.Builder.AddText("Swiftlys2 からこの広大なる世界へ温かい挨拶を"); - settingsMenu.Builder.AddText("Swiftlys2 가 이 넓은 세상에 따뜻한 인사를 전합니다"); - settingsMenu.Builder.AddText("Swiftlys2 приветствует этот прекрасный мир"); - settingsMenu.Builder.AddText("Swiftlys2 salută această lume minunată"); - settingsMenu.Builder.AddText("Swiftlys2 extends warmest greetings to this wondrous world"); - settingsMenu.Builder.AddText("Swiftlys2 sendas korajn salutojn al ĉi tiu mirinda mondo"); - settingsMenu.Builder.AddSeparator(); - settingsMenu.Builder.AddAsyncButton("AsyncButton|AsyncButton|AsyncButton", async ( p ) => await Task.Delay(2000)); - settingsMenu.Builder.AddButton("Button|Button|Button|Button", ( p ) => { }); - settingsMenu.Builder.AddChoice("Choice|Choice|Choice|Choice", ["Option 1", "Option 2", "Option 3"], "Option 1", ( p, value ) => { }, overflowStyle: MenuHorizontalStyle.TruncateEnd(8f)); - settingsMenu.Builder.AddProgressBar("ProgressBar|ProgressBar|ProgressBar", () => (float)Random.Shared.NextDouble(), overflowStyle: MenuHorizontalStyle.ScrollLeftLoop(26f, 12)); - settingsMenu.Builder.AddSlider("Slider|Slider|Slider|Slider", 0f, 100f, 0f, 1f, ( p, value ) => { }, overflowStyle: MenuHorizontalStyle.ScrollRightLoop(8f, 12)); - // settingsMenu.Builder.AddSubmenu("Submenu"); - settingsMenu.Builder.AddToggle("Toggle|Toggle|Toggle|Toggle", true, ( p, value ) => { }); - settingsMenu.Builder.AddSeparator(); - - Core.Menus.OpenMenu(player, settingsMenu); - } - - [Command("menu")] - public void MenuCommand( ICommandContext context ) - { - var player = context.Sender!; - var menu = Core.Menus.CreateMenu("Test Menu"); - - menu.Builder - .AddButton("Button 1", ( ctx ) => - { - player.SendMessage(MessageType.Chat, "You clicked Button 1"); - }) - .AddButton("Button 2", ( ctx ) => - { - player.SendMessage(MessageType.Chat, "You clicked Button 2"); - }) - .AddButton("Button 3", ( ctx ) => - { - player.SendMessage(MessageType.Chat, "You clicked Button 3"); - }) - .AddButton("Button 4", ( ctx ) => + var player = context.Sender!; + + IMenu settingsMenu = Core.Menus.CreateMenu("MenuTest"); + + settingsMenu.Builder.Design.MaxVisibleItems(5); + + // settingsMenu.Builder.Design.MaxVisibleItems(Random.Shared.Next(-2, 8)); + if (context.Args.Length < 1 || !int.TryParse(context.Args[0], out int vtype)) vtype = 0; + settingsMenu.Builder.Design.SetVerticalScrollStyle(vtype switch { + 1 => MenuVerticalScrollStyle.LinearScroll, + 2 => MenuVerticalScrollStyle.WaitingCenter, + _ => MenuVerticalScrollStyle.CenterFixed + }); + + if (context.Args.Length < 2 || !int.TryParse(context.Args[1], out int htype)) htype = 0; + settingsMenu.Builder.Design.SetGlobalHorizontalStyle(htype switch { + 0 => MenuHorizontalStyle.Default, + 1 => MenuHorizontalStyle.TruncateBothEnds(26f), + 2 => MenuHorizontalStyle.ScrollLeftFade(26f, 8, 128), + 3 => MenuHorizontalStyle.ScrollLeftLoop(26f, 8, 128), + 1337 => MenuHorizontalStyle.TruncateEnd(0f), + _ => MenuHorizontalStyle.TruncateEnd(26f) + }); + + settingsMenu.Builder.AddButton("1. AButton", ( p ) => { - player.SendMessage(MessageType.Chat, "You clicked Button 4"); - }) - .AddButton("Button 5", ( ctx ) => - { - player.SendMessage(MessageType.Chat, "You clicked Button 5"); - }) - .AddButton("Button 6", ( ctx ) => - { - player.SendMessage(MessageType.Chat, "You clicked Button 6"); - }) - .AddButton("Button 7", ( ctx ) => + player.SendMessage(MessageType.Chat, "Button"); + }); + + settingsMenu.Builder.AddToggle("2. Toggle", defaultValue: true, ( p, value ) => { - player.SendMessage(MessageType.Chat, "You clicked Button 7"); - }) - .AddButton("Button 8", ( ctx ) => + player.SendMessage(MessageType.Chat, $"AddToggle {value}"); + }); + + settingsMenu.Builder.AddSlider("3. Slider", min: 0, max: 100, defaultValue: 10, step: 10, ( p, value ) => { - player.SendMessage(MessageType.Chat, "You clicked Button 8"); - }) - .AddSeparator() - .AddText("hello!", size: IMenuTextSize.ExtraLarge) - .AutoClose(15f) - .HasSound(true) - .ForceFreeze(); + player.SendMessage(MessageType.Chat, $"AddSlider {value}"); + }); - menu.Builder.Design.SetColor(new(0, 186, 105, 255)); + settingsMenu.Builder.AddAsyncButton("4. AsyncButton", async ( p ) => + { + await Task.Delay(2000); + }); + + settingsMenu.Builder.AddText("5. Text"); + settingsMenu.Builder.AddText("6. Text"); + settingsMenu.Builder.AddText("7. Text"); + settingsMenu.Builder.AddText("8. Text"); + settingsMenu.Builder.AddText("9. Text"); + settingsMenu.Builder.AddSeparator(); + settingsMenu.Builder.AddText($"{HtmlGradient.GenerateGradientText("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", "#FFE4E1", "#FFC0CB", "#FF69B4")}", overflowStyle: MenuHorizontalStyle.TruncateEnd(26f)); + settingsMenu.Builder.AddText($"{HtmlGradient.GenerateGradientText("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", "#FFE5CC", "#FFAB91", "#FF7043")}", overflowStyle: MenuHorizontalStyle.TruncateBothEnds(26f)); + settingsMenu.Builder.AddText($"{HtmlGradient.GenerateGradientText("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", "#E6E6FA", "#00FFFF", "#FF1493")}", overflowStyle: MenuHorizontalStyle.ScrollRightFade(26f, 8)); + settingsMenu.Builder.AddText($"{HtmlGradient.GenerateGradientText("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", "#AFEEEE", "#7FFFD4", "#40E0D0")}", overflowStyle: MenuHorizontalStyle.ScrollLeftLoop(26f, 8)); + settingsMenu.Builder.AddText("12345678901234567890split12345678901234567890", overflowStyle: MenuHorizontalStyle.ScrollLeftFade(26f, 8, 128)); + settingsMenu.Builder.AddText("一二三四五六七八九十分割一二三四五六七八九十", overflowStyle: MenuHorizontalStyle.ScrollRightLoop(26f, 8, 64)); + settingsMenu.Builder.AddSeparator(); + settingsMenu.Builder.AddText("Swiftlys2 向这广袤世界致以温柔问候", overflowStyle: MenuHorizontalStyle.ScrollRightLoop(26f, 8)); + settingsMenu.Builder.AddText("Swiftlys2 からこの広大なる世界へ温かい挨拶を"); + settingsMenu.Builder.AddText("Swiftlys2 가 이 넓은 세상에 따뜻한 인사를 전합니다"); + settingsMenu.Builder.AddText("Swiftlys2 приветствует этот прекрасный мир"); + settingsMenu.Builder.AddText("Swiftlys2 salută această lume minunată"); + settingsMenu.Builder.AddText("Swiftlys2 extends warmest greetings to this wondrous world"); + settingsMenu.Builder.AddText("Swiftlys2 sendas korajn salutojn al ĉi tiu mirinda mondo"); + settingsMenu.Builder.AddSeparator(); + settingsMenu.Builder.AddAsyncButton("AsyncButton|AsyncButton|AsyncButton", async ( p ) => await Task.Delay(2000)); + settingsMenu.Builder.AddButton("Button|Button|Button|Button", ( p ) => { }); + settingsMenu.Builder.AddChoice("Choice|Choice|Choice|Choice", ["Option 1", "Option 2", "Option 3"], "Option 1", ( p, value ) => { }, overflowStyle: MenuHorizontalStyle.TruncateEnd(8f)); + settingsMenu.Builder.AddProgressBar("ProgressBar|ProgressBar|ProgressBar", () => (float)Random.Shared.NextDouble(), overflowStyle: MenuHorizontalStyle.ScrollLeftLoop(26f, 12)); + settingsMenu.Builder.AddSlider("Slider|Slider|Slider|Slider", 0f, 100f, 0f, 1f, ( p, value ) => { }, overflowStyle: MenuHorizontalStyle.ScrollRightLoop(8f, 12)); + // settingsMenu.Builder.AddSubmenu("Submenu"); + settingsMenu.Builder.AddToggle("Toggle|Toggle|Toggle|Toggle", true, ( p, value ) => { }); + settingsMenu.Builder.AddSeparator(); + + Core.Menus.OpenMenu(player, settingsMenu); + } - Core.Menus.OpenMenu(player, menu); + [Command("menu")] + public void MenuCommand( ICommandContext context ) + { + var player = context.Sender!; + var menu = Core.Menus.CreateMenu("Test Menu"); + + menu.Builder + .AddButton("Button 1", ( ctx ) => + { + player.SendMessage(MessageType.Chat, "You clicked Button 1"); + }) + .AddButton("Button 2", ( ctx ) => + { + player.SendMessage(MessageType.Chat, "You clicked Button 2"); + }) + .AddButton("Button 3", ( ctx ) => + { + player.SendMessage(MessageType.Chat, "You clicked Button 3"); + }) + .AddButton("Button 4", ( ctx ) => + { + player.SendMessage(MessageType.Chat, "You clicked Button 4"); + }) + .AddButton("Button 5", ( ctx ) => + { + player.SendMessage(MessageType.Chat, "You clicked Button 5"); + }) + .AddButton("Button 6", ( ctx ) => + { + player.SendMessage(MessageType.Chat, "You clicked Button 6"); + }) + .AddButton("Button 7", ( ctx ) => + { + player.SendMessage(MessageType.Chat, "You clicked Button 7"); + }) + .AddButton("Button 8", ( ctx ) => + { + player.SendMessage(MessageType.Chat, "You clicked Button 8"); + }) + .AddSeparator() + .AddText("hello!", size: IMenuTextSize.ExtraLarge) + .AutoClose(15f) + .HasSound(true) + .ForceFreeze(); + + menu.Builder.Design.SetColor(new(0, 186, 105, 255)); + + Core.Menus.OpenMenu(player, menu); } - public override void Unload() - { - Console.WriteLine("TestPlugin unloaded"); - } + public override void Unload() + { + Console.WriteLine("TestPlugin unloaded"); + } } \ No newline at end of file diff --git a/managed/src/TestPlugin/TestService.cs b/managed/src/TestPlugin/TestService.cs index 35e8574d..1630ce4f 100644 --- a/managed/src/TestPlugin/TestService.cs +++ b/managed/src/TestPlugin/TestService.cs @@ -10,29 +10,24 @@ namespace TestPlugin; public class TestService { + private ISwiftlyCore Core { get; init; } - private ISwiftlyCore Core { get; init; } - - public TestService(ISwiftlyCore core, ILogger logger, IOptionsMonitor config) - { - Core = core; - logger.LogInformation("TestService created"); - logger.LogInformation("Config: {Config}", config.CurrentValue.Age); - - core.Registrator.Register(this); - } - - - [Command("test")] - public void TestCommand(ICommandContext context) - { - Core.NetMessage.Send(um => + public TestService( ISwiftlyCore core, ILogger logger, IOptionsMonitor config ) { - um.Frequency = 1f; - - - um.Recipients.AddAllPlayers(); - }); - context.Reply("Test command"); - } + Core = core; + logger.LogInformation("TestService created"); + logger.LogInformation("Config: {Config}", config.CurrentValue.Age); + core.Registrator.Register(this); + } + + [Command("test")] + public void TestCommand( ICommandContext context ) + { + Core.NetMessage.Send(um => + { + um.Frequency = 1f; + um.Recipients.AddAllPlayers(); + }); + context.Reply("Test command"); + } } \ No newline at end of file