From a5df1c7fae80de097b09112e2e08ad4f0d478b4f Mon Sep 17 00:00:00 2001 From: WeylonSantana <63019821+WeylonSantana@users.noreply.github.com> Date: Tue, 16 Jul 2024 18:21:22 -0300 Subject: [PATCH] chore: client cleanup (core and entities) (#2326) * cleaning controls and input * cleaning audio * cleaning core files * cleaning fade * cleaning graphics * cleaning entity * cleaning events * cleaning projectiles * cleaning animation * cleaning chat bubble * cleaning friend instance * cleaning hotbar instance * cleaning party member * cleaning critter * cleaning dash * cleaning resource * cleaning status * cleaning player --- .../Entities/IAnimation.cs | 4 +- .../Entities/IEntity.cs | 8 +- .../Entities/IFriendInstance.cs | 4 +- .../Entities/IPlayer.cs | 2 +- .../Entities/IResource.cs | 5 +- .../Graphics/GameRenderer.cs | 20 +- Intersect.Client/Core/Audio.cs | 42 +- Intersect.Client/Core/Bootstrapper.cs | 12 +- .../Core/ClientCommandLineOptions.cs | 9 +- Intersect.Client/Core/ClientContext.cs | 6 +- Intersect.Client/Core/Controls/ControlEnum.cs | 13 +- Intersect.Client/Core/Controls/ControlMap.cs | 2 +- .../Core/Controls/ControlValue.cs | 14 +- Intersect.Client/Core/Controls/Controls.cs | 16 +- Intersect.Client/Core/Fade.cs | 6 +- Intersect.Client/Core/Graphics.cs | 180 +++++--- Intersect.Client/Core/Input.cs | 76 ++-- Intersect.Client/Core/Main.cs | 73 +-- Intersect.Client/Core/Sounds/MapSound.cs | 85 ++-- Intersect.Client/Core/Sounds/Sound.cs | 9 +- Intersect.Client/Entities/Animation.cs | 41 +- Intersect.Client/Entities/ChatBubble.cs | 27 +- Intersect.Client/Entities/Critter.cs | 20 +- Intersect.Client/Entities/Dash.cs | 17 +- Intersect.Client/Entities/Entity.cs | 239 +++++----- Intersect.Client/Entities/Events/Dialog.cs | 5 +- Intersect.Client/Entities/Events/Event.cs | 61 +-- Intersect.Client/Entities/Events/Hold.cs | 17 - Intersect.Client/Entities/FriendInstance.cs | 8 +- Intersect.Client/Entities/HotbarInstance.cs | 4 +- Intersect.Client/Entities/PartyMember.cs | 5 +- Intersect.Client/Entities/Player.cs | 419 ++++++++++-------- .../Entities/Projectiles/Projectile.cs | 74 +++- .../Entities/Projectiles/ProjectileSpawns.cs | 4 +- Intersect.Client/Entities/Resource.cs | 53 ++- Intersect.Client/Entities/Status.cs | 3 +- Intersect.Client/General/Globals.cs | 10 +- .../Interface/Game/EntityPanel/EntityBox.cs | 4 +- .../Interface/Game/EventWindow.cs | 2 +- .../Interface/Game/Friends/FriendsWindow.cs | 4 +- Intersect.Client/Interface/Game/InputBox.cs | 8 +- .../Interface/Game/MapItem/MapItemIcon.cs | 3 +- .../Interface/Game/MapItem/MapItemWindow.cs | 11 +- .../MonoGame/Graphics/MonoRenderer.cs | 14 +- Intersect.Client/Networking/PacketHandler.cs | 12 +- 45 files changed, 801 insertions(+), 850 deletions(-) delete mode 100644 Intersect.Client/Entities/Events/Hold.cs diff --git a/Intersect.Client.Framework/Entities/IAnimation.cs b/Intersect.Client.Framework/Entities/IAnimation.cs index b32010a60..aa8fb141f 100644 --- a/Intersect.Client.Framework/Entities/IAnimation.cs +++ b/Intersect.Client.Framework/Entities/IAnimation.cs @@ -1,4 +1,4 @@ -using Intersect.GameObjects; +using Intersect.GameObjects; using Intersect.Enums; namespace Intersect.Client.Framework.Entities; @@ -8,7 +8,7 @@ public interface IAnimation : IDisposable bool AutoRotate { get; set; } bool Hidden { get; set; } bool InfiniteLoop { get; set; } - AnimationBase MyBase { get; set; } + AnimationBase? MyBase { get; set; } Point Size { get; } void Hide(); diff --git a/Intersect.Client.Framework/Entities/IEntity.cs b/Intersect.Client.Framework/Entities/IEntity.cs index 29ff97c8f..d2e64f5bf 100644 --- a/Intersect.Client.Framework/Entities/IEntity.cs +++ b/Intersect.Client.Framework/Entities/IEntity.cs @@ -12,14 +12,14 @@ public interface IEntity : IDisposable EntityType Type { get; } string Name { get; } Gender Gender { get; } - Color NameColor { get; } + Color? NameColor { get; } Label FooterLabel { get; } Label HeaderLabel { get; } bool IsHidden { get; } string Sprite { get; } string TransformedSprite { get; } string Face { get; } - GameTexture Texture { get; } + GameTexture? Texture { get; } Color Color { get; } FloatRect WorldPos { get; } float OffsetX { get; } @@ -30,10 +30,10 @@ public interface IEntity : IDisposable bool IsStealthed { get; } bool IsBlocking { get; } bool IsDashing { get; } - IDash CurrentDash { get; } + IDash? CurrentDash { get; } bool IsCasting { get; } bool InView { get; } - IMapInstance MapInstance { get; } + IMapInstance? MapInstance { get; } Guid MapId { get; } Direction Dir { get; } byte X { get; } diff --git a/Intersect.Client.Framework/Entities/IFriendInstance.cs b/Intersect.Client.Framework/Entities/IFriendInstance.cs index 79ae42f81..78a9c9cbb 100644 --- a/Intersect.Client.Framework/Entities/IFriendInstance.cs +++ b/Intersect.Client.Framework/Entities/IFriendInstance.cs @@ -1,8 +1,8 @@ -namespace Intersect.Client.Framework.Entities; +namespace Intersect.Client.Framework.Entities; public interface IFriendInstance { - string Map { get; set; } + string? Map { get; set; } string Name { get; set; } bool Online { get; set; } } \ No newline at end of file diff --git a/Intersect.Client.Framework/Entities/IPlayer.cs b/Intersect.Client.Framework/Entities/IPlayer.cs index 2513778a7..9ef05b839 100644 --- a/Intersect.Client.Framework/Entities/IPlayer.cs +++ b/Intersect.Client.Framework/Entities/IPlayer.cs @@ -23,7 +23,7 @@ public interface IPlayer : IEntity Guid[] HiddenQuests { get; } bool IsInGuild { get; } string GuildName { get; } - GuildRank GuildRank { get; } + GuildRank? GuildRank { get; } bool IsBusy { get; } bool TryGetRealLocation(ref int x, ref int y, ref Guid mapId); diff --git a/Intersect.Client.Framework/Entities/IResource.cs b/Intersect.Client.Framework/Entities/IResource.cs index a789df00e..0c56c73ba 100644 --- a/Intersect.Client.Framework/Entities/IResource.cs +++ b/Intersect.Client.Framework/Entities/IResource.cs @@ -1,11 +1,10 @@ -using Intersect.GameObjects; +using Intersect.GameObjects; namespace Intersect.Client.Framework.Entities; public interface IResource : IEntity { - ResourceBase BaseResource { get; } + ResourceBase? BaseResource { get; } bool IsDepleted { get; } - } \ No newline at end of file diff --git a/Intersect.Client.Framework/Graphics/GameRenderer.cs b/Intersect.Client.Framework/Graphics/GameRenderer.cs index 419b473b7..a57f2b90f 100644 --- a/Intersect.Client.Framework/Graphics/GameRenderer.cs +++ b/Intersect.Client.Framework/Graphics/GameRenderer.cs @@ -1,4 +1,4 @@ -using Intersect.Client.Framework.GenericClasses; +using Intersect.Client.Framework.GenericClasses; namespace Intersect.Client.Framework.Graphics; @@ -85,9 +85,9 @@ public abstract void DrawTexture( float tw, float th, Color renderColor, - GameRenderTexture renderTarget = null, + GameRenderTexture? renderTarget = null, GameBlendModes blendMode = GameBlendModes.None, - GameShader shader = null, + GameShader? shader = null, float rotationDegrees = 0.0f, bool isUi = false, bool drawImmediate = false @@ -118,9 +118,9 @@ void IGameRenderer.DrawTexture( float tw, float th, Color renderColor, - GameRenderTexture renderTarget = null, + GameRenderTexture? renderTarget = null, GameBlendModes blendMode = GameBlendModes.None, - GameShader shader = null, + GameShader? shader = null, float rotationDegrees = 0.0f ) => DrawTexture(tex, sx, sy, sw, sh, tx, ty, tw, th, renderColor, renderTarget, blendMode, shader, rotationDegrees); @@ -141,18 +141,18 @@ Func createStream public abstract GameTexture GetWhiteTexture(); - public abstract Pointf MeasureText(string text, GameFont gameFont, float fontScale); + public abstract Pointf MeasureText(string text, GameFont? gameFont, float fontScale); public abstract void DrawString( string text, - GameFont gameFont, + GameFont? gameFont, float x, float y, float fontScale, - Color fontColor, + Color? fontColor, bool worldPos = true, - GameRenderTexture renderTexture = null, - Color borderColor = null + GameRenderTexture? renderTexture = null, + Color? borderColor = null ); public abstract void DrawString( diff --git a/Intersect.Client/Core/Audio.cs b/Intersect.Client/Core/Audio.cs index 172f78036..0f6e61f17 100644 --- a/Intersect.Client/Core/Audio.cs +++ b/Intersect.Client/Core/Audio.cs @@ -9,10 +9,8 @@ namespace Intersect.Client.Core; - public static partial class Audio { - private static string sCurrentSong = ""; private static int sFadeRate; @@ -22,7 +20,7 @@ public static partial class Audio private static bool sFadingOut; //Sounds - private static List sGameSounds = new List(); + private static readonly List sGameSounds = []; private static bool sIsInitialized; @@ -31,9 +29,9 @@ public static partial class Audio private static bool sQueuedLoop; //Music - private static string sQueuedMusic = ""; + private static string? sQueuedMusic = ""; - private static GameAudioInstance sMyMusic { get; set; } + private static GameAudioInstance? sMyMusic { get; set; } //Init public static void Init() @@ -49,14 +47,10 @@ public static void Init() public static void UpdateGlobalVolume() { - if (sMyMusic != null) - { - sMyMusic.SetVolume(sMyMusic.GetVolume(), true); - } - + sMyMusic?.SetVolume(sMyMusic.GetVolume(), true); for (var i = 0; i < sGameSounds.Count; i++) { - sGameSounds[i].Update(); + _ = sGameSounds[i].Update(); if (!sGameSounds[i].Loaded) { sGameSounds.RemoveAt(i); @@ -75,7 +69,7 @@ public static void Update() if (sFadingOut) { sMyMusic.SetVolume(sMyMusic.GetVolume() - 1, true); - if (sMyMusic.GetVolume() <= 1) + if (sMyMusic.GetVolume() <= 1 && !string.IsNullOrEmpty(sQueuedMusic)) { StopMusic(); PlayMusic(sQueuedMusic, 0, sQueuedFade, sQueuedLoop); @@ -102,7 +96,7 @@ public static void Update() for (var i = 0; i < sGameSounds.Count; i++) { - sGameSounds[i].Update(); + _ = sGameSounds[i].Update(); if (!sGameSounds[i].Loaded) { sGameSounds.RemoveAt(i); @@ -110,16 +104,10 @@ public static void Update() } // Update our pack sound cache if we have any packs loaded. - if (Globals.ContentManager.SoundPacks != null) - { - Globals.ContentManager.SoundPacks.UpdateCache(); - } + Globals.ContentManager.SoundPacks?.UpdateCache(); // Update our pack music cache if we have any packs loaded. - if (Globals.ContentManager.MusicPacks != null) - { - Globals.ContentManager.MusicPacks.UpdateCache(); - } + Globals.ContentManager.MusicPacks?.UpdateCache(); } //Music @@ -239,7 +227,7 @@ public static void StopMusic(int fadeout = 0) } //Sounds - public static MapSound AddMapSound( + public static MapSound? AddMapSound( string filename, int x, int y, @@ -247,7 +235,7 @@ public static MapSound AddMapSound( bool loop, int loopInterval, int distance, - IEntity parent = null + IEntity? parent = null ) { if (sGameSounds?.Count > 128) @@ -261,7 +249,7 @@ public static MapSound AddMapSound( return sound; } - public static Sound AddGameSound(string filename, bool loop) + public static Sound? AddGameSound(string filename, bool loop) { if (sGameSounds?.Count > 128) { @@ -292,11 +280,7 @@ public static void StopAllSounds() { for (var i = 0; i < sGameSounds.Count; i++) { - if (sGameSounds[i] != null) - { - sGameSounds[i].Stop(); - } + sGameSounds[i]?.Stop(); } } - } diff --git a/Intersect.Client/Core/Bootstrapper.cs b/Intersect.Client/Core/Bootstrapper.cs index 937935871..2dc5cbc0a 100644 --- a/Intersect.Client/Core/Bootstrapper.cs +++ b/Intersect.Client/Core/Bootstrapper.cs @@ -9,10 +9,9 @@ namespace Intersect.Client.Core; - internal static partial class Bootstrapper { - public static ClientContext Context { get; private set; } + public static ClientContext? Context { get; private set; } public static void Start(params string[] args) { @@ -42,7 +41,7 @@ public static void Start(params string[] args) var packetHandlerRegistry = new PacketHandlerRegistry(packetTypeRegistry, logger); var packetHelper = new PacketHelper(packetTypeRegistry, packetHandlerRegistry); - FactoryRegistry.RegisterFactory(PluginBootstrapContext.CreateFactory(args, parser, packetHelper)); + _ = FactoryRegistry.RegisterFactory(PluginBootstrapContext.CreateFactory(args, parser, packetHelper)); var commandLineOptions = parser.ParseArguments(args) .MapResult(HandleParsedArguments, HandleParserErrors); @@ -71,12 +70,8 @@ private static ClientCommandLineOptions HandleParsedArguments(ClientCommandLineO private static ClientCommandLineOptions HandleParserErrors(IEnumerable errors) { var errorsAsList = errors?.ToList(); - var fatalParsingError = errorsAsList?.Any(error => error?.StopsProcessing ?? false) ?? false; - - var errorString = string.Join( - ", ", errorsAsList?.ToList().Select(error => error?.ToString()) ?? Array.Empty() - ); + var errorString = string.Join(", ", errorsAsList?.ToList().Select(error => error?.ToString()) ?? []); var exception = new ArgumentException( $@"Error parsing command line arguments, received the following errors: {errorString}" @@ -93,5 +88,4 @@ private static ClientCommandLineOptions HandleParserErrors(IEnumerable er return default; } - } diff --git a/Intersect.Client/Core/ClientCommandLineOptions.cs b/Intersect.Client/Core/ClientCommandLineOptions.cs index cf99e425c..fd74a34df 100644 --- a/Intersect.Client/Core/ClientCommandLineOptions.cs +++ b/Intersect.Client/Core/ClientCommandLineOptions.cs @@ -1,11 +1,11 @@ -using CommandLine; +using CommandLine; using Intersect.Client.Framework.Graphics; using Intersect.Core; namespace Intersect.Client.Core; -internal partial struct ClientCommandLineOptions : ICommandLineOptions +internal readonly partial struct ClientCommandLineOptions : ICommandLineOptions { public ClientCommandLineOptions( bool borderlessWindow, @@ -40,8 +40,7 @@ IEnumerable pluginDirectories public string WorkingDirectory { get; } [Option('p', "plugin-directory", Default = null, Required = false)] - public IEnumerable PluginDirectories { get; } - - public Resolution ScreenResolution => new Resolution(ScreenWidth, ScreenHeight); + public IEnumerable? PluginDirectories { get; } + public Resolution ScreenResolution => new(ScreenWidth, ScreenHeight); } diff --git a/Intersect.Client/Core/ClientContext.cs b/Intersect.Client/Core/ClientContext.cs index adcb194e7..36ea056c5 100644 --- a/Intersect.Client/Core/ClientContext.cs +++ b/Intersect.Client/Core/ClientContext.cs @@ -1,4 +1,4 @@ -using Intersect.Client.Networking; +using Intersect.Client.Networking; using Intersect.Client.Plugins.Contexts; using Intersect.Core; using Intersect.Factories; @@ -16,13 +16,13 @@ internal sealed partial class ClientContext : ApplicationContext.RegisterFactory(new ClientPluginContext.Factory()); + _ = FactoryRegistry.RegisterFactory(new ClientPluginContext.Factory()); } protected override bool UsesMainThread => true; diff --git a/Intersect.Client/Core/Controls/ControlEnum.cs b/Intersect.Client/Core/Controls/ControlEnum.cs index 26b5132db..a5d288b51 100644 --- a/Intersect.Client/Core/Controls/ControlEnum.cs +++ b/Intersect.Client/Core/Controls/ControlEnum.cs @@ -1,9 +1,7 @@ -namespace Intersect.Client.Core.Controls; - +namespace Intersect.Client.Core.Controls; public enum Control { - MoveUp, MoveLeft, @@ -79,13 +77,4 @@ public enum Control HoldToZoomOut, ToggleFullscreen, - - // Submit, - // - // Cancel, - // - // Previous, - // - // Next, - } diff --git a/Intersect.Client/Core/Controls/ControlMap.cs b/Intersect.Client/Core/Controls/ControlMap.cs index 6b132ed63..d0e59f8e1 100644 --- a/Intersect.Client/Core/Controls/ControlMap.cs +++ b/Intersect.Client/Core/Controls/ControlMap.cs @@ -10,7 +10,7 @@ public partial class ControlMap public ControlMap(ControlValue binding, params ControlValue[] alternateBindings) { Bindings = new List(1 + (alternateBindings?.Length ?? 0)) { binding }; - Bindings.AddRange(alternateBindings ?? Array.Empty()); + Bindings.AddRange(alternateBindings ?? []); if (Bindings.Count < 2) { diff --git a/Intersect.Client/Core/Controls/ControlValue.cs b/Intersect.Client/Core/Controls/ControlValue.cs index 1f38302b6..cab0f08e3 100644 --- a/Intersect.Client/Core/Controls/ControlValue.cs +++ b/Intersect.Client/Core/Controls/ControlValue.cs @@ -7,17 +7,17 @@ namespace Intersect.Client.Core.Controls; public partial class ControlValue { - public static ControlValue Default => new ControlValue(Keys.None, Keys.None); + public static ControlValue Default => new(Keys.None, Keys.None); public Keys Modifier { get; set; } public Keys Key { get; set; } - public bool IsMouseKey => Key == Keys.LButton - || Key == Keys.RButton - || Key == Keys.MButton - || Key == Keys.XButton1 - || Key == Keys.XButton2; + public bool IsMouseKey => Key is Keys.LButton + or Keys.RButton + or Keys.MButton + or Keys.XButton1 + or Keys.XButton2; [JsonConstructor] public ControlValue(Keys modifier, Keys key) @@ -100,5 +100,5 @@ public bool IsDown() return false; } - private bool KeyDown(Keys key) => Globals.InputManager.KeyDown(key); + private static bool KeyDown(Keys key) => Globals.InputManager.KeyDown(key); } diff --git a/Intersect.Client/Core/Controls/Controls.cs b/Intersect.Client/Core/Controls/Controls.cs index 7e76f5925..449c5e133 100644 --- a/Intersect.Client/Core/Controls/Controls.cs +++ b/Intersect.Client/Core/Controls/Controls.cs @@ -4,13 +4,12 @@ namespace Intersect.Client.Core.Controls; - public partial class Controls { public readonly IDictionary ControlMapping; - public Controls(Controls gameControls = null) + public Controls(Controls? gameControls = null) { ControlMapping = new Dictionary(); @@ -46,14 +45,18 @@ public Controls(Controls gameControls = null) } else { - bindings[bindingIndex] = JsonConvert.DeserializeObject(preference); + var controlObj = JsonConvert.DeserializeObject(preference); + if (controlObj != null) + { + bindings[bindingIndex] = controlObj; + } } } } } } - public static Controls ActiveControls { get; set; } + public static Controls? ActiveControls { get; set; } public void ResetDefaults() { @@ -95,10 +98,6 @@ public void ResetDefaults() CreateControlMap(Control.HoldToZoomIn, ControlValue.Default, ControlValue.Default); CreateControlMap(Control.HoldToZoomOut, ControlValue.Default, ControlValue.Default); CreateControlMap(Control.ToggleFullscreen, new ControlValue(Keys.Alt, Keys.Enter), ControlValue.Default); - // CreateControlMap(Control.Submit, new ControlValue(Keys.None, Keys.Enter), ControlValue.Default); - // CreateControlMap(Control.Cancel, new ControlValue(Keys.None, Keys.Back), ControlValue.Default); - // CreateControlMap(Control.Next, new ControlValue(Keys.None, Keys.Tab), ControlValue.Default); - // CreateControlMap(Control.Previous, new ControlValue(Keys.Shift, Keys.Tab), ControlValue.Default); } private static void MigrateControlBindings(Control control) @@ -197,5 +196,4 @@ private void CreateControlMap(Control control, ControlMap controlMap) { ControlMapping[control] = new ControlMap(controlMap); } - } diff --git a/Intersect.Client/Core/Fade.cs b/Intersect.Client/Core/Fade.cs index 649e39c2e..0cddd89f8 100644 --- a/Intersect.Client/Core/Fade.cs +++ b/Intersect.Client/Core/Fade.cs @@ -3,19 +3,15 @@ namespace Intersect.Client.Core; - public static partial class Fade { - public enum FadeType { - None = 0, In = 1, Out = 2, - } private static FadeType sCurrentAction; @@ -48,7 +44,7 @@ public static void FadeOut(float durationMs, bool informServer = false) InformServer = informServer; } - public static void Cancel(bool informServer = false) + public static void Cancel() { sCurrentAction = FadeType.None; sFadeAmt = default; diff --git a/Intersect.Client/Core/Graphics.cs b/Intersect.Client/Core/Graphics.cs index 97d527155..057f6b217 100644 --- a/Intersect.Client/Core/Graphics.cs +++ b/Intersect.Client/Core/Graphics.cs @@ -13,18 +13,17 @@ namespace Intersect.Client.Core; - public static partial class Graphics { - public static GameFont ActionMsgFont; + public static GameFont? ActionMsgFont; - public static object AnimationLock = new object(); + public static object AnimationLock = new(); //Darkness Stuff public static float BrightnessLevel; - public static GameFont ChatBubbleFont; + public static GameFont? ChatBubbleFont; private static FloatRect _currentView; @@ -34,27 +33,27 @@ public static FloatRect CurrentView set { _currentView = value; - Renderer.SetView(_currentView); + Renderer?.SetView(_currentView); } } - public static FloatRect WorldViewport => new FloatRect(CurrentView.Position, CurrentView.Size / (Globals.Database?.WorldZoom ?? 1)); + public static FloatRect WorldViewport => new(CurrentView.Position, CurrentView.Size / (Globals.Database?.WorldZoom ?? 1)); - public static GameShader DefaultShader; + public static GameShader? DefaultShader; //Rendering Variables - private static GameTexture sMenuBackground; + private static GameTexture? sMenuBackground; public static int DrawCalls; public static int EntitiesDrawn; - public static GameFont EntityNameFont; + public static GameFont? EntityNameFont; //Screen Values - public static GameFont GameFont; + public static GameFont? GameFont; - public static object GfxLock = new object(); + public static object GfxLock = new(); //Grid Switched public static bool GridSwitched; @@ -62,7 +61,7 @@ public static FloatRect CurrentView public static int LightsDrawn; //Animations - public static List LiveAnimations = new List(); + public static List LiveAnimations = []; public static int MapsDrawn; @@ -76,18 +75,16 @@ public static FloatRect CurrentView public static ColorF PlayerLightColor = ColorF.White; //Game Renderer - public static GameRenderer Renderer; + public static GameRenderer? Renderer; //Cache the Y based rendering - public static HashSet[,] RenderingEntities; - - private static GameContentManager sContentManager; + public static HashSet[,] RenderingEntities = new HashSet[6, Options.MapHeight * 5]; - private static GameRenderTexture sDarknessTexture; + private static GameContentManager sContentManager = null!; - private static long sFadeTimer; + private static GameRenderTexture? sDarknessTexture; - private static List sLightQueue = new List(); + private static readonly List sLightQueue = []; //Player Spotlight Values private static long sLightUpdate; @@ -105,14 +102,14 @@ public static FloatRect CurrentView private static float sPlayerLightSize; - public static GameFont UIFont; + public static GameFont? UIFont; public static float BaseWorldScale => Options.Instance?.MapOpts?.TileScale ?? 1; //Init Functions public static void InitGraphics() { - Renderer.Init(); + Renderer?.Init(); sContentManager = Globals.ContentManager; sContentManager.LoadAll(); GameFont = FindFont(ClientConfiguration.Instance.GameFont); @@ -130,7 +127,7 @@ public static GameFont FindFont(string font) { var parts = font.Split(','); font = parts[0]; - int.TryParse(parts[1], out size); + _ = int.TryParse(parts[1], out size); } return sContentManager.GetFont(font, size); @@ -138,12 +135,11 @@ public static GameFont FindFont(string font) public static void InitInGame() { - RenderingEntities = new HashSet[6, Options.MapHeight * 5]; for (var z = 0; z < 6; z++) { for (var i = 0; i < Options.MapHeight * 5; i++) { - RenderingEntities[z, i] = new HashSet(); + RenderingEntities[z, i] = []; } } } @@ -239,13 +235,12 @@ private static void DrawMenu() public static void DrawInGame(TimeSpan deltaTime) { - var currentMap = Globals.Me.MapInstance as MapInstance; - if (currentMap == null) + if (Globals.Me?.MapInstance is not MapInstance currentMap) { return; } - if (Globals.NeedsMaps) + if (Globals.NeedsMaps || Globals.MapGrid == default) { return; } @@ -359,10 +354,7 @@ public static void DrawInGame(TimeSpan deltaTime) Globals.MapGrid[x1, y1] != Guid.Empty) { var map = MapInstance.Get(Globals.MapGrid[x1, y1]); - if (map != null) - { - map.DrawItemsAndLights(); - } + map?.DrawItemsAndLights(); } } } @@ -434,7 +426,6 @@ public static void DrawInGame(TimeSpan deltaTime) animInstance.Draw(true); } - for (var x = gridX - 1; x <= gridX + 1; x++) { for (var y = gridY - 1; y <= gridY + 1; y++) @@ -458,7 +449,7 @@ public static void DrawInGame(TimeSpan deltaTime) } //Draw the players targets - Globals.Me.DrawTargets(); + Globals.Me?.DrawTargets(); DrawOverlay(); @@ -528,7 +519,7 @@ public static void DrawInGame(TimeSpan deltaTime) } //Game Rendering - public static void Render(TimeSpan deltaTime, TimeSpan totalTime) + public static void Render(TimeSpan deltaTime, TimeSpan _) { var takingScreenshot = false; if (Renderer?.ScreenshotRequests.Count > 0) @@ -655,7 +646,12 @@ private static void DrawMapPanorama(Guid mapId) public static void DrawOverlay() { - var map = MapInstance.Get(Globals.Me.MapId); + if (Renderer == default) + { + return; + } + + var map = MapInstance.Get(Globals.Me?.MapId ?? Guid.Empty); if (map != null) { float ecTime = Timing.Global.MillisecondsUtc - sOverlayUpdate; @@ -776,11 +772,17 @@ public static FloatRect GetSourceRect(GameTexture gameTexture) public static void DrawFullScreenTexture(GameTexture tex, float alpha = 1f) { + if (Renderer == default) + { + return; + } + var bgx = Renderer.GetScreenWidth() / 2 - tex.GetWidth() / 2; var bgy = Renderer.GetScreenHeight() / 2 - tex.GetHeight() / 2; var bgw = tex.GetWidth(); var bgh = tex.GetHeight(); - var diff = 0; + int diff; + if (bgw < Renderer.GetScreenWidth()) { diff = Renderer.GetScreenWidth() - bgw; @@ -804,6 +806,11 @@ public static void DrawFullScreenTexture(GameTexture tex, float alpha = 1f) public static void DrawFullScreenTextureCentered(GameTexture tex, float alpha = 1f) { + if (Renderer == default) + { + return; + } + var bgx = Renderer.GetScreenWidth() / 2 - tex.GetWidth() / 2; var bgy = Renderer.GetScreenHeight() / 2 - tex.GetHeight() / 2; var bgw = tex.GetWidth(); @@ -818,6 +825,11 @@ public static void DrawFullScreenTextureCentered(GameTexture tex, float alpha = public static void DrawFullScreenTextureStretched(GameTexture tex) { + if (Renderer == default) + { + return; + } + DrawGameTexture( tex, GetSourceRect(tex), new FloatRect( @@ -828,6 +840,11 @@ public static void DrawFullScreenTextureStretched(GameTexture tex) public static void DrawFullScreenTextureFitWidth(GameTexture tex) { + if (Renderer == default) + { + return; + } + var scale = Renderer.GetScreenWidth() / (float)tex.GetWidth(); var scaledHeight = tex.GetHeight() * scale; var offsetY = (Renderer.GetScreenHeight() - tex.GetHeight()) / 2f; @@ -841,6 +858,11 @@ public static void DrawFullScreenTextureFitWidth(GameTexture tex) public static void DrawFullScreenTextureFitHeight(GameTexture tex) { + if (Renderer == default) + { + return; + } + var scale = Renderer.GetScreenHeight() / (float)tex.GetHeight(); var scaledWidth = tex.GetWidth() * scale; var offsetX = (Renderer.GetScreenWidth() - scaledWidth) / 2f; @@ -854,6 +876,11 @@ public static void DrawFullScreenTextureFitHeight(GameTexture tex) public static void DrawFullScreenTextureFitMinimum(GameTexture tex) { + if (Renderer == default) + { + return; + } + if (Renderer.GetScreenWidth() > Renderer.GetScreenHeight()) { DrawFullScreenTextureFitHeight(tex); @@ -866,6 +893,11 @@ public static void DrawFullScreenTextureFitMinimum(GameTexture tex) public static void DrawFullScreenTextureFitMaximum(GameTexture tex) { + if (Renderer == default) + { + return; + } + if (Renderer.GetScreenWidth() < Renderer.GetScreenHeight()) { DrawFullScreenTextureFitHeight(tex); @@ -878,14 +910,19 @@ public static void DrawFullScreenTextureFitMaximum(GameTexture tex) private static void UpdateView() { + if (Renderer == default) + { + return; + } + var scale = Renderer.Scale; if (Globals.GameState != GameStates.InGame || !MapInstance.TryGet(Globals.Me?.MapId ?? Guid.Empty, out var map)) { var sw = Renderer.GetScreenWidth(); var sh = Renderer.GetScreenHeight(); - var sx = 0;//sw - (sw / scale); - var sy = 0;//sh - (sh / scale); + var sx = 0; + var sy = 0; CurrentView = new FloatRect(sx, sy, sw / scale, sh / scale); return; } @@ -894,6 +931,12 @@ private static void UpdateView() var mapHeight = Options.MapHeight * Options.TileHeight; var en = Globals.Me; + + if (en == null) + { + return; + } + float x = mapWidth; float y = mapHeight; float x1 = mapWidth * 2; @@ -926,12 +969,7 @@ private static void UpdateView() var w = x1 - x; var h = y1 - y; - var restrictView = new FloatRect( - x, - y, - w, - h - ); + var restrictView = new FloatRect(x, y, w, h ); var newView = new FloatRect( (int)Math.Ceiling(en.Center.X - Renderer.ScreenWidth / scale / 2f), (int)Math.Ceiling(en.Center.Y - Renderer.ScreenHeight / scale / 2f), @@ -977,34 +1015,25 @@ private static void UpdateView() private static void ClearDarknessTexture() { // If we're not allowed to draw lighting, exit out. - if (!Globals.Database.EnableLighting) + if (!Globals.Database.EnableLighting || Renderer == default) { return; } - if (sDarknessTexture == null) - { - sDarknessTexture = Renderer.CreateRenderTexture(Renderer.GetScreenWidth(), Renderer.GetScreenHeight()); - } - + sDarknessTexture ??= Renderer.CreateRenderTexture(Renderer.GetScreenWidth(), Renderer.GetScreenHeight()); sDarknessTexture.Clear(Color.Black); } private static void GenerateLightMap() { // If we're not allowed to draw lighting, exit out. - if (!Globals.Database.EnableLighting) + if (!Globals.Database.EnableLighting || Renderer == default || Globals.Me == default) { return; } var map = MapInstance.Get(Globals.Me.MapId); - if (map == null) - { - return; - } - - if (sDarknessTexture == null) + if (map == null || sDarknessTexture == null) { return; } @@ -1052,7 +1081,7 @@ private static void GenerateLightMap() public static void DrawDarkness() { // If we're not allowed to draw lighting, exit out. - if (!Globals.Database.EnableLighting) + if (!Globals.Database.EnableLighting || sDarknessTexture == default) { return; } @@ -1090,7 +1119,7 @@ public static void AddLight(int x, int y, int size, byte intensity, float expand private static void DrawLights() { // If we're not allowed to draw lighting, exit out. - if (!Globals.Database.EnableLighting) + if (!Globals.Database.EnableLighting || Renderer == default) { return; } @@ -1123,7 +1152,7 @@ private static void DrawLights() public static void UpdatePlayerLight() { // If we're not allowed to draw lighting, exit out. - if (!Globals.Database.EnableLighting) + if (!Globals.Database.EnableLighting || Globals.Me == default) { return; } @@ -1352,19 +1381,23 @@ public static Pointf ConvertToWorldPointNoZoom(Pointf windowPoint) /// Y coordinate on the render target to draw to /// Where to draw to. If null it this will draw to the game screen. /// Which blend mode to use when rendering + /// Which shader to use when rendering + /// How much to rotate the texture in degrees + /// If true, the texture will be drawn immediately. If false, it will be queued for drawing. public static void DrawGameTexture( GameTexture tex, float x, float y, - GameRenderTexture renderTarget = null, + GameRenderTexture? renderTarget = null, GameBlendModes blendMode = GameBlendModes.None, - GameShader shader = null, + GameShader? shader = null, float rotationDegrees = 0.0f, bool drawImmediate = false ) { var destRectangle = new FloatRect(x, y, tex.GetWidth(), tex.GetHeight()); var srcRectangle = new FloatRect(0, 0, tex.GetWidth(), tex.GetHeight()); + DrawGameTexture( tex, srcRectangle, destRectangle, Color.White, renderTarget, blendMode, shader, rotationDegrees, drawImmediate @@ -1381,14 +1414,17 @@ public static void DrawGameTexture( /// Color mask to draw with. Default is Color.White /// Where to draw to. If null it this will draw to the game screen. /// Which blend mode to use when rendering + /// Which shader to use when rendering + /// How much to rotate the texture in degrees + /// If true, the texture will be drawn immediately. If false, it will be queued for drawing. public static void DrawGameTexture( GameTexture tex, float x, float y, Color renderColor, - GameRenderTexture renderTarget = null, + GameRenderTexture? renderTarget = null, GameBlendModes blendMode = GameBlendModes.None, - GameShader shader = null, + GameShader? shader = null, float rotationDegrees = 0.0f, bool drawImmediate = false ) @@ -1414,6 +1450,9 @@ public static void DrawGameTexture( /// Height of the texture part we are rendering. /// >Where to draw to. If null it this will draw to the game screen. /// Which blend mode to use when rendering + /// Which shader to use when rendering + /// How much to rotate the texture in degrees + /// If true, the texture will be drawn immediately. If false, it will be queued for drawing. public static void DrawGameTexture( GameTexture tex, float dx, @@ -1422,9 +1461,9 @@ public static void DrawGameTexture( float sy, float w, float h, - GameRenderTexture renderTarget = null, + GameRenderTexture? renderTarget = null, GameBlendModes blendMode = GameBlendModes.None, - GameShader shader = null, + GameShader? shader = null, float rotationDegrees = 0.0f, bool drawImmediate = false ) @@ -1434,7 +1473,7 @@ public static void DrawGameTexture( return; } - Renderer.DrawTexture( + Renderer?.DrawTexture( tex, sx, sy, w, h, dx, dy, w, h, Color.White, renderTarget, blendMode, shader, rotationDegrees, false, drawImmediate ); @@ -1445,9 +1484,9 @@ public static void DrawGameTexture( FloatRect srcRectangle, FloatRect targetRect, Color renderColor, - GameRenderTexture renderTarget = null, + GameRenderTexture? renderTarget = null, GameBlendModes blendMode = GameBlendModes.None, - GameShader shader = null, + GameShader? shader = null, float rotationDegrees = 0.0f, bool drawImmediate = false ) @@ -1457,12 +1496,11 @@ public static void DrawGameTexture( return; } - Renderer.DrawTexture( + Renderer?.DrawTexture( tex, srcRectangle.X, srcRectangle.Y, srcRectangle.Width, srcRectangle.Height, targetRect.X, targetRect.Y, targetRect.Width, targetRect.Height, Color.FromArgb(renderColor.A, renderColor.R, renderColor.G, renderColor.B), renderTarget, blendMode, shader, rotationDegrees, false, drawImmediate ); } - } diff --git a/Intersect.Client/Core/Input.cs b/Intersect.Client/Core/Input.cs index 0f1aaf610..c3e9fa52f 100644 --- a/Intersect.Client/Core/Input.cs +++ b/Intersect.Client/Core/Input.cs @@ -1,5 +1,6 @@ using Intersect.Admin.Actions; using Intersect.Client.Core.Controls; +using Intersect.Client.Entities; using Intersect.Client.Framework.GenericClasses; using Intersect.Client.Framework.Graphics; using Intersect.Client.Framework.Input; @@ -15,16 +16,23 @@ namespace Intersect.Client.Core; public static partial class Input { - public delegate void HandleKeyEvent(Keys modifier, Keys key); - public static HandleKeyEvent KeyDown; + private static HandleKeyEvent? _keyDown; + + private static HandleKeyEvent? _keyUp; + + private static HandleKeyEvent? _mouseDown; - public static HandleKeyEvent KeyUp; + private static HandleKeyEvent? _mouseUp; - public static HandleKeyEvent MouseDown; + public static HandleKeyEvent? KeyDown { get => _keyDown; set => _keyDown = value; } - public static HandleKeyEvent MouseUp; + public static HandleKeyEvent? KeyUp { get => _keyUp; set => _keyUp = value; } + + public static HandleKeyEvent? MouseDown { get => _mouseDown; set => _mouseDown = value; } + + public static HandleKeyEvent? MouseUp { get => _mouseUp; set => _mouseUp = value; } private static void HandleZoomOut() { @@ -121,7 +129,7 @@ public static void OnKeyPressed(Keys modifier, Keys key) } else if (Globals.Me != null && Globals.Me.TargetIndex != Guid.Empty && !Globals.Me.Status.Any(s => s.Type == Enums.SpellEffect.Taunt)) { - Globals.Me.ClearTarget(); + _ = Globals.Me.ClearTarget(); } else { @@ -179,6 +187,11 @@ public static void OnKeyPressed(Keys modifier, Keys key) case Control.ToggleFullscreen: { + if (Graphics.Renderer == default) + { + break; + } + Globals.Database.FullScreen = !Globals.Database.FullScreen; Globals.Database.SavePreferences(); Graphics.Renderer.OverrideResolution = Resolution.Empty; @@ -187,7 +200,7 @@ public static void OnKeyPressed(Keys modifier, Keys key) } case Control.OpenDebugger: - MutableInterface.ToggleDebug(); + _ = MutableInterface.ToggleDebug(); break; } @@ -218,7 +231,7 @@ public static void OnKeyPressed(Keys modifier, Keys key) break; case Control.Block: - Globals.Me?.TryBlock(); + _ = (Globals.Me?.TryBlock()); break; @@ -228,12 +241,18 @@ public static void OnKeyPressed(Keys modifier, Keys key) break; case Control.PickUp: - Globals.Me?.TryPickupItem(Globals.Me.MapInstance.Id, Globals.Me.Y * Options.MapWidth + Globals.Me.X); + if (Globals.Me != default && Globals.Me.MapInstance != default) + { + _ = Player.TryPickupItem( + Globals.Me.MapInstance.Id, + Globals.Me.Y * Options.MapWidth + Globals.Me.X + ); + } break; case Control.Enter: - if (canFocusChat) + if (canFocusChat && Interface.Interface.GameUi != default) { Interface.Interface.GameUi.FocusChat = true; consumeKey = true; @@ -279,7 +298,7 @@ public static void OnKeyPressed(Keys modifier, Keys key) break; case Control.OpenFriends: - Interface.Interface.GameUi?.GameMenu?.ToggleFriendsWindow(); + _ = (Interface.Interface.GameUi?.GameMenu?.ToggleFriendsWindow()); break; @@ -294,7 +313,7 @@ public static void OnKeyPressed(Keys modifier, Keys key) break; case Control.OpenGuild: - Interface.Interface.GameUi?.GameMenu.ToggleGuildWindow(); + _ = (Interface.Interface.GameUi?.GameMenu.ToggleGuildWindow()); break; } @@ -397,7 +416,9 @@ public static void OnMouseDown(Keys modifier, MouseButtons btn) if (Controls.Controls.ControlHasKey(Control.PickUp, modifier, key)) { - if (Globals.Me.TryPickupItem(Globals.Me.MapInstance.Id, Globals.Me.Y * Options.MapWidth + Globals.Me.X, Guid.Empty, true)) + if (Globals.Me.MapInstance != default && + Player.TryPickupItem(Globals.Me.MapInstance.Id, Globals.Me.Y * Options.MapWidth + Globals.Me.X, Guid.Empty, true) + ) { return; } @@ -481,7 +502,7 @@ public static void OnMouseUp(Keys modifier, MouseButtons btn) var x = (int)mouseInWorld.X; var y = (int)mouseInWorld.Y; - foreach (MapInstance map in MapInstance.Lookup.Values) + foreach (MapInstance map in MapInstance.Lookup.Values.Cast()) { if (!(x >= map.GetX()) || !(x <= map.GetX() + Options.MapWidth * Options.TileWidth)) { @@ -513,21 +534,18 @@ public static void OnMouseUp(Keys modifier, MouseButtons btn) public static bool IsModifier(Keys key) { - switch (key) + return key switch { - case Keys.Control: - case Keys.ControlKey: - case Keys.LControlKey: - case Keys.RControlKey: - case Keys.LShiftKey: - case Keys.RShiftKey: - case Keys.Shift: - case Keys.ShiftKey: - case Keys.Alt: - return true; - - default: - return false; - } + Keys.Control or + Keys.ControlKey or + Keys.LControlKey or + Keys.RControlKey or + Keys.LShiftKey or + Keys.RShiftKey or + Keys.Shift or + Keys.ShiftKey or + Keys.Alt => true, + _ => false, + }; } } diff --git a/Intersect.Client/Core/Main.cs b/Intersect.Client/Core/Main.cs index 23122df88..b2d30bcf7 100644 --- a/Intersect.Client/Core/Main.cs +++ b/Intersect.Client/Core/Main.cs @@ -12,14 +12,11 @@ namespace Intersect.Client.Core; - internal static partial class Main { private static long _animTimer; - private static bool _createdMapTextures; - private static bool _loadedTilesets; internal static void Start(IClientContext context) @@ -40,12 +37,12 @@ internal static void Start(IClientContext context) foreach (var val in Enum.GetValues(typeof(GameObjectType))) { var type = ((GameObjectType) val); - if (type != GameObjectType.Event && type != GameObjectType.Time) + if (type is not GameObjectType.Event and not GameObjectType.Time) { var lookup = type.GetLookup(); var item = lookup.AddNew(type.GetObjectType(), id); item.Load(item.JsonData); - lookup.Delete(item); + _ = lookup.Delete(item); } } } @@ -56,7 +53,7 @@ public static void DestroyGame() //TODO - Destroy Graphics and Networking peacefully //Network.Close(); Interface.Interface.DestroyGwen(true); - Graphics.Renderer.Close(); + Graphics.Renderer?.Close(); } public static void Update(TimeSpan deltaTime) @@ -197,49 +194,9 @@ private static void ProcessGame() //If we are waiting on maps, lets see if we have them if (Globals.NeedsMaps) { - bool canShowWorld = true; - if (MapInstance.TryGet(Globals.Me.MapId, out var mapInstance)) - { - var gridX = mapInstance.GridX; - var gridY = mapInstance.GridY; - for (int x = gridX - 1; x <= gridX + 1; x++) - { - for (int y = gridY - 1; y <= gridY + 1; y++) - { - if (x >= 0 && - x < Globals.MapGridWidth && - y >= 0 && - y < Globals.MapGridHeight && - Globals.MapGrid[x, y] != Guid.Empty) - { - var map = MapInstance.Get(Globals.MapGrid[x, y]); - if (map != null) - { - if (!map.IsLoaded) - { - canShowWorld = false; - } - } - else - { - canShowWorld = false; - } - } - } - } - } - else - { - canShowWorld = false; - } - - canShowWorld = true; - if (canShowWorld) - { - Globals.NeedsMaps = false; - //Send ping to server, so it will resync time if needed as we load in - PacketSender.SendPing(); - } + Globals.NeedsMaps = false; + //Send ping to server, so it will resync time if needed as we load in + PacketSender.SendPing(); } else { @@ -254,18 +211,17 @@ private static void ProcessGame() if (en.Value == null) continue; - en.Value.Update(); + _ = en.Value.Update(); } for (int i = 0; i < Globals.EntitiesToDispose.Count; i++) { - if (Globals.Entities.ContainsKey(Globals.EntitiesToDispose[i])) + if (Globals.Entities.TryGetValue(Globals.EntitiesToDispose[i], out var value)) { - if (Globals.EntitiesToDispose[i] == Globals.Me.Id) + if (Globals.EntitiesToDispose[i] == Globals.Me?.Id) continue; - - Globals.Entities[Globals.EntitiesToDispose[i]].Dispose(); - Globals.Entities.Remove(Globals.EntitiesToDispose[i]); + value.Dispose(); + _ = Globals.Entities.Remove(Globals.EntitiesToDispose[i]); } } @@ -273,7 +229,7 @@ private static void ProcessGame() //Update Maps var maps = MapInstance.Lookup.Values.ToArray(); - foreach (MapInstance map in maps) + foreach (MapInstance map in maps.Cast()) { if (map == null) continue; @@ -307,7 +263,7 @@ private static void ProcessGame() foreach (var hold in removeHolds) { - Globals.EventHolds.Remove(hold); + _ = Globals.EventHolds.Remove(hold); } Graphics.UpdatePlayerLight(); @@ -374,7 +330,7 @@ public static void Logout(bool characterSelect, bool skipFade = false) Globals.Entities.Clear(); Globals.MapGrid = null; Globals.GridMaps.Clear(); - Globals.EventDialogs.Clear(); + Globals.EventDialogs?.Clear(); Globals.EventHolds.Clear(); Globals.PendingEvents.Clear(); @@ -394,5 +350,4 @@ public static void Logout(bool characterSelect, bool skipFade = false) Fade.FadeIn(ClientConfiguration.Instance.FadeDurationMs); } } - } diff --git a/Intersect.Client/Core/Sounds/MapSound.cs b/Intersect.Client/Core/Sounds/MapSound.cs index 283456465..9bd6bebae 100644 --- a/Intersect.Client/Core/Sounds/MapSound.cs +++ b/Intersect.Client/Core/Sounds/MapSound.cs @@ -1,4 +1,4 @@ -using Intersect.Client.Framework.Core.Sounds; +using Intersect.Client.Framework.Core.Sounds; using Intersect.Client.Framework.Entities; using Intersect.Client.Framework.GenericClasses; using Intersect.Client.General; @@ -6,13 +6,11 @@ namespace Intersect.Client.Core.Sounds; - public partial class MapSound : Sound, IMapSound { + private readonly int mDistance; - private int mDistance; - - private IEntity mEntity; + private readonly IEntity? mEntity; private Guid mMapId; @@ -28,7 +26,7 @@ public MapSound( bool loop, int loopInterval, int distance, - IEntity parent = null + IEntity? parent = null ) : base(filename, loop, loopInterval) { if (string.IsNullOrEmpty(filename) || mSound == null) @@ -67,49 +65,20 @@ private void UpdateSoundVolume() { if (mMapId == Guid.Empty) { - mSound.SetVolume(0); - + mSound?.SetVolume(0); return; } var map = MapInstance.Get(mMapId); - if (map == null && mEntity != Globals.Me || Globals.Me == null) + if (map == null && mEntity != Globals.Me || Globals.Me == null || Globals.MapGrid == default) { Stop(); - return; } - var sameMap = mMapId == Globals.Me.MapId; - var inGrid = sameMap; - if (!inGrid && Globals.Me.MapInstance != null) - { - var gridX = Globals.Me.MapInstance.GridX; - var gridY = Globals.Me.MapInstance.GridY; - for (var x = gridX - 1; x <= gridX + 1; x++) - { - for (var y = gridY - 1; y <= gridY + 1; y++) - { - if (x >= 0 && - x < Globals.MapGridWidth && - y >= 0 && - y < Globals.MapGridHeight && - Globals.MapGrid[x, y] != Guid.Empty) - { - if (Globals.MapGrid[x, y] == mMapId) - { - inGrid = true; - - break; - } - } - } - } - } - - if ((mX == -1 || mY == -1 || mDistance <= 0) && sameMap) + if (mX == -1 || mY == -1 || mDistance <= 0) { - mSound.SetVolume(100); + mSound?.SetVolume(100); } else { @@ -121,28 +90,29 @@ private void UpdateSoundVolume() volume = 0f; } - mSound.SetVolume((int)volume); + mSound?.SetVolume((int)volume); } else { - mSound.SetVolume(0); + mSound?.SetVolume(0); } } } private float CalculateSoundDistance() { + if (Globals.Me == null) + { + return 0f; + } + var distance = 0f; - var playerx = 0f; - var playery = 0f; - float soundx = 0; - float soundy = 0; var map = MapInstance.Get(mMapId); var pMap = MapInstance.Get(Globals.Me.MapId); if (map != null && pMap != null) { - playerx = pMap.GetX() + Globals.Me.X * Options.TileWidth + (Options.TileWidth / 2); - playery = pMap.GetY() + Globals.Me.Y * Options.TileHeight + (Options.TileHeight / 2); + var playerx = pMap.GetX() + Globals.Me.X * Options.TileWidth + (Options.TileWidth / 2); + var playery = pMap.GetY() + Globals.Me.Y * Options.TileHeight + (Options.TileHeight / 2); if (mX == -1 || mY == -1 || mDistance == -1) { var player = new Point() { @@ -160,8 +130,8 @@ private float CalculateSoundDistance() } else { - soundx = map.GetX() + mX * Options.TileWidth + (Options.TileWidth / 2); - soundy = map.GetY() + mY * Options.TileHeight + (Options.TileHeight / 2); + var soundx = map.GetX() + mX * Options.TileWidth + (Options.TileWidth / 2); + var soundy = map.GetY() + mY * Options.TileHeight + (Options.TileHeight / 2); distance = (float) Math.Sqrt(Math.Pow(playerx - soundx, 2) + Math.Pow(playery - soundy, 2)) / ((Options.TileHeight + Options.TileWidth) / 2f); } @@ -198,16 +168,16 @@ public static float DistancePointToRectangle(Point point, Rectangle rect) if (point.Y < rect.Y) { // I - point.X = point.X - rect.X; - point.Y = point.Y - rect.Y; + point.X -= rect.X; + point.Y -= rect.Y; return (float)Math.Sqrt(point.X * point.X + point.Y * point.Y); } else if (point.Y > rect.Y + rect.Height) { // VII - point.X = point.X - rect.X; - point.Y = point.Y - (rect.Y + rect.Height); + point.X -= rect.X; + point.Y -= (rect.Y + rect.Height); return (float)Math.Sqrt(point.X * point.X + point.Y * point.Y); } @@ -223,16 +193,16 @@ public static float DistancePointToRectangle(Point point, Rectangle rect) if (point.Y < rect.Y) { // III - point.X = point.X - (rect.X + rect.Width); - point.Y = point.Y - rect.Y; + point.X -= (rect.X + rect.Width); + point.Y -= rect.Y; return (float)Math.Sqrt(point.X * point.X + point.Y * point.Y); } else if (point.Y > rect.Y + rect.Height) { // V - point.X = point.X - (rect.X + rect.Width); - point.Y = point.Y - (rect.Y + rect.Height); + point.X -= (rect.X + rect.Width); + point.Y -= (rect.Y + rect.Height); return (float)Math.Sqrt(point.X * point.X + point.Y * point.Y); } @@ -262,5 +232,4 @@ public static float DistancePointToRectangle(Point point, Rectangle rect) } } } - } diff --git a/Intersect.Client/Core/Sounds/Sound.cs b/Intersect.Client/Core/Sounds/Sound.cs index 0a8a1f2f7..52bea57d6 100644 --- a/Intersect.Client/Core/Sounds/Sound.cs +++ b/Intersect.Client/Core/Sounds/Sound.cs @@ -6,21 +6,20 @@ namespace Intersect.Client.Core.Sounds; - public partial class Sound : ISound { public bool Loaded { get; set; } - protected string mFilename; + protected string? mFilename; - public string Filename => mFilename; + public string? Filename => mFilename; protected bool mLoop; protected int mLoopInterval; - protected GameAudioInstance mSound; + protected GameAudioInstance? mSound; protected float mVolume; @@ -82,6 +81,7 @@ public virtual bool Update() mStoppedTime = -1; } } + return true; } else if (mLoop || mSound?.State != GameAudioInstance.AudioInstanceState.Stopped) @@ -104,5 +104,4 @@ public virtual void Stop() mSound?.Dispose(); Loaded = false; } - } diff --git a/Intersect.Client/Entities/Animation.cs b/Intersect.Client/Entities/Animation.cs index 9dc7de121..c3987a86c 100644 --- a/Intersect.Client/Entities/Animation.cs +++ b/Intersect.Client/Entities/Animation.cs @@ -10,10 +10,8 @@ namespace Intersect.Client.Entities; - public partial class Animation : IAnimation { - public bool AutoRotate { get; set; } private bool disposed = false; @@ -26,11 +24,9 @@ public partial class Animation : IAnimation private int mLowerFrame; - private int mLowerLoop; - - private long mLowerTimer; + private readonly int mLowerLoop; - private Entity mParent; + private readonly Entity? mParent; private Direction mRenderDir; @@ -42,21 +38,19 @@ public partial class Animation : IAnimation private bool mShowUpper = true; - private MapSound mSound; + private MapSound? mSound; - private long mStartTime = Timing.Global.MillisecondsUtc; + private readonly long mStartTime = Timing.Global.MillisecondsUtc; private int mUpperFrame; - private int mUpperLoop; - - private long mUpperTimer; + private readonly int mUpperLoop; private bool mUseExternalRotation; private float mExternalRotation; - public AnimationBase MyBase { get; set; } + public AnimationBase? MyBase { get; set; } public Point Size => CalculateAnimationSize(); @@ -67,7 +61,7 @@ public Animation( bool loopForever, bool autoRotate = false, int zDimension = -1, - Entity parent = null + Entity? parent = null ) { MyBase = animBase; @@ -76,8 +70,6 @@ public Animation( { mLowerLoop = animBase.Lower.LoopCount; mUpperLoop = animBase.Upper.LoopCount; - mLowerTimer = Timing.Global.MillisecondsUtc + animBase.Lower.FrameSpeed; - mUpperTimer = Timing.Global.MillisecondsUtc + animBase.Upper.FrameSpeed; InfiniteLoop = loopForever; AutoRotate = autoRotate; mZDimension = zDimension; @@ -95,7 +87,7 @@ public Animation( public void Draw(bool upper = false, bool alternate = false) { - if (Hidden) + if (Hidden || MyBase == default) { return; } @@ -295,7 +287,7 @@ public void Dispose() if (mSound != null) { mSound.Loop = false; - if (!MyBase.CompleteSound) + if (MyBase?.CompleteSound == false) { mSound.Stop(); } @@ -303,8 +295,9 @@ public void Dispose() mSound = null; } - Graphics.LiveAnimations.Remove(this); + _ = Graphics.LiveAnimations.Remove(this); disposed = true; + GC.SuppressFinalize(this); } } @@ -322,10 +315,7 @@ public void SetPosition(float worldX, float worldY, int mapx, int mapy, Guid map { mRenderX = worldX; mRenderY = worldY; - if (mSound != null) - { - mSound.UpdatePosition(mapx, mapy, mapId); - } + mSound?.UpdatePosition(mapx, mapy, mapId); if (dir > Direction.None) { @@ -346,7 +336,7 @@ public void Update() { if (mSound != null) { - mSound.Update(); + _ = mSound.Update(); } //Calculate Frames @@ -395,6 +385,11 @@ public Point CalculateAnimationSize() { var size = new Point(0, 0); + if (MyBase == default) + { + return size; + } + var tex = Globals.ContentManager.GetTexture(Framework.Content.TextureType.Animation, MyBase.Lower.Sprite); if (tex != null) { diff --git a/Intersect.Client/Entities/ChatBubble.cs b/Intersect.Client/Entities/ChatBubble.cs index ecb223c35..8e87c57f7 100644 --- a/Intersect.Client/Entities/ChatBubble.cs +++ b/Intersect.Client/Entities/ChatBubble.cs @@ -7,25 +7,21 @@ namespace Intersect.Client.Entities; - public partial class ChatBubble { + private readonly GameTexture? mBubbleTex; - private GameTexture mBubbleTex; - - private Entity mOwner; - - private Color mRenderColor; + private readonly Entity? mOwner; - private long mRenderTimer; + private readonly long mRenderTimer; - private string mSourceText; + private readonly string? mSourceText; - private Point[,] mTexSections; + private Point[,]? mTexSections; - private string[] mText; + private string[]? mText; - private Rectangle mTextBounds; + private Rectangle mTextBounds = new(); private Rectangle mTextureBounds; @@ -54,12 +50,12 @@ public bool Update() public float Draw(float yoffset = 0f) { - if (mText == null && mSourceText.Trim().Length > 0) + if (mText == null && mSourceText?.Trim().Length > 0 && Graphics.ChatBubbleFont != default) { mText = Interface.Interface.WrapText(mSourceText, 200, Graphics.ChatBubbleFont); } - if (mText == null) + if (mText == null || Graphics.Renderer == default || mOwner == default) { return 0f; } @@ -72,7 +68,7 @@ public float Draw(float yoffset = 0f) //Gotta Calculate Bounds for (var i = (mText?.Length ?? 0) - 1; i > -1; i--) { - var textSize = Graphics.Renderer.MeasureText(mText[i], Graphics.ChatBubbleFont, 1); + var textSize = Graphics.Renderer.MeasureText(mText![i], Graphics.ChatBubbleFont, 1); if (textSize.X > mTextureBounds.Width) { mTextureBounds.Width = (int) textSize.X + 16; @@ -163,7 +159,7 @@ public float Draw(float yoffset = 0f) } } - if (mBubbleTex != null) + if (mBubbleTex != null && mText != null && mTexSections != null) { //Draw Background if available //Draw Top Left @@ -196,5 +192,4 @@ public float Draw(float yoffset = 0f) return yoffset; } - } diff --git a/Intersect.Client/Entities/Critter.cs b/Intersect.Client/Entities/Critter.cs index c9ebf7eed..e40f70496 100644 --- a/Intersect.Client/Entities/Critter.cs +++ b/Intersect.Client/Entities/Critter.cs @@ -12,7 +12,7 @@ namespace Intersect.Client.Entities; public partial class Critter : Entity { - private MapCritterAttribute mAttribute; + private readonly MapCritterAttribute mAttribute; private long mLastMove = -1; public Critter(MapInstance map, byte x, byte y, MapCritterAttribute att) : base(Guid.NewGuid(), null, EntityType.GlobalEntity) @@ -20,7 +20,7 @@ public Critter(MapInstance map, byte x, byte y, MapCritterAttribute att) : base( mAttribute = att; //setup Sprite & Animation - Sprite = att?.Sprite; + Sprite = att.Sprite; var anim = AnimationBase.Get(att.AnimationId); if (anim != null) { @@ -66,8 +66,10 @@ public override bool Update() mLastMove = Timing.Global.MillisecondsUtc + mAttribute.Frequency + Globals.Random.Next((int)(mAttribute.Frequency * .5f)); } + return true; } + return false; } @@ -76,7 +78,7 @@ private void MoveRandomly() MoveDir = Randomization.NextDirection(); var tmpX = (sbyte)X; var tmpY = (sbyte)Y; - IEntity blockedBy = null; + IEntity? blockedBy = null; if (IsMoving || MoveTimer >= Timing.Global.MillisecondsUtc) { @@ -204,18 +206,19 @@ public bool PlayerOnTile(Guid mapId, int x, int y) } } } + return false; } - public override HashSet DetermineRenderOrder(HashSet renderList, IMapInstance map) + public override HashSet? DetermineRenderOrder(HashSet? renderList, IMapInstance? map) { if (mAttribute.Layer == 1) { return base.DetermineRenderOrder(renderList, map); } - renderList?.Remove(this); - if (map == null || Globals.Me == null || Globals.Me.MapInstance == null) + _ = (renderList?.Remove(this)); + if (map == null || Globals.Me == null || Globals.Me.MapInstance == null || Globals.MapGrid == default) { return null; } @@ -250,7 +253,7 @@ public override HashSet DetermineRenderOrder(HashSet renderList, priority += 3; } - HashSet renderSet = null; + HashSet? renderSet = null; if (y == gridY - 2) { @@ -273,9 +276,8 @@ public override HashSet DetermineRenderOrder(HashSet renderList, renderSet = Graphics.RenderingEntities[priority, Options.MapHeight * 4 + Y]; } - renderSet?.Add(this); + _ = (renderSet?.Add(this)); renderList = renderSet; - return renderList; } } diff --git a/Intersect.Client/Entities/Dash.cs b/Intersect.Client/Entities/Dash.cs index 407e309e8..6ae284d1a 100644 --- a/Intersect.Client/Entities/Dash.cs +++ b/Intersect.Client/Entities/Dash.cs @@ -1,25 +1,23 @@ -using Intersect.Client.Framework.Entities; +using Intersect.Client.Framework.Entities; using Intersect.Client.Maps; using Intersect.Enums; using Intersect.Utilities; namespace Intersect.Client.Entities; - public partial class Dash : IDash { + private readonly Direction mChangeDirection = Direction.None; - private Direction mChangeDirection = Direction.None; - - private int mDashTime; + private readonly int mDashTime; - private Guid mEndMapId; + private readonly Guid mEndMapId; - private byte mEndX; + private readonly byte mEndX; private float mEndXCoord; - private byte mEndY; + private readonly byte mEndY; private float mEndYCoord; @@ -33,7 +31,7 @@ public partial class Dash : IDash public float OffsetY => GetYOffset(); - public Dash(Entity en, Guid endMapId, byte endX, byte endY, int dashTime, Direction changeDirection = Direction.None) + public Dash(Guid endMapId, byte endX, byte endY, int dashTime, Direction changeDirection = Direction.None) { mChangeDirection = changeDirection; mEndMapId = endMapId; @@ -104,5 +102,4 @@ public bool Update(Entity en) return en.Dashing != null; } - } diff --git a/Intersect.Client/Entities/Entity.cs b/Intersect.Client/Entities/Entity.cs index 5bf4ca354..670db2a51 100644 --- a/Intersect.Client/Entities/Entity.cs +++ b/Intersect.Client/Entities/Entity.cs @@ -26,7 +26,7 @@ public partial class Entity : IEntity public int AnimationFrame { get; set; } //Entity Animations - public List Animations { get; set; } = new List(); + public List Animations { get; set; } = []; //Animation Timer (for animated sprites) public long AnimationTimer { get; set; } @@ -50,9 +50,9 @@ public partial class Entity : IEntity public bool IsDashing => Dashing != null; //Dashing instance - public Dash Dashing { get; set; } + public Dash? Dashing { get; set; } - public IDash CurrentDash => Dashing as IDash; + public IDash? CurrentDash => Dashing; public Queue DashQueue { get; set; } = new Queue(); @@ -77,18 +77,18 @@ public Guid[] Equipment } } - IReadOnlyList IEntity.EquipmentSlots => MyEquipment.ToList(); + IReadOnlyList IEntity.EquipmentSlots => [.. MyEquipment]; - public Animation[] EquipmentAnimations { get; set; } = new Animation[Options.EquipmentSlots.Count]; + public Animation?[] EquipmentAnimations { get; set; } = new Animation[Options.EquipmentSlots.Count]; //Extras public string Face { get; set; } = ""; - public Label FooterLabel { get; set; } + public Label FooterLabel { get; set; } = new(string.Empty, Color.White); public Gender Gender { get; set; } = Gender.Male; - public Label HeaderLabel { get; set; } + public Label HeaderLabel { get; set; } = new(string.Empty, Color.White); public bool IsHidden { get; set; } = false; @@ -100,26 +100,26 @@ public Guid[] Equipment //Inventory/Spells/Equipment public IItem[] Inventory { get; set; } = new IItem[Options.MaxInvItems]; - IReadOnlyList IEntity.Items => Inventory.ToList(); + IReadOnlyList IEntity.Items => [.. Inventory]; public bool InView { get; set; } = true; public bool IsMoving { get; set; } //Caching - public IMapInstance LatestMap { get; set; } + public IMapInstance? LatestMap { get; set; } public int Level { get; set; } = 1; //Vitals & Stats public long[] MaxVital { get; set; } = new long[Enum.GetValues().Length]; - IReadOnlyList IEntity.MaxVitals => MaxVital.ToList(); + IReadOnlyList IEntity.MaxVitals => [.. MaxVital]; protected Pointf mOrigin = Pointf.Empty; //Chat - private List mChatBubbles = new List(); + private readonly List mChatBubbles = []; private Direction mDir; @@ -145,7 +145,7 @@ public Guid[] Equipment public string Name { get; set; } = ""; - public Color NameColor { get; set; } = null; + public Color? NameColor { get; set; } = null; public float OffsetX { get; set; } @@ -154,7 +154,7 @@ public Guid[] Equipment public bool Passable { get; set; } //Rendering Variables - public HashSet RenderList { get; set; } + public HashSet? RenderList { get; set; } private Guid _spellCast; @@ -179,16 +179,15 @@ public Guid SpellCast public int[] Stat { get; set; } = new int[Enum.GetValues().Length]; - IReadOnlyList IEntity.Stats => Stat.ToList(); + IReadOnlyList IEntity.Stats => [.. Stat]; - public GameTexture Texture { get; set; } + public GameTexture? Texture { get; set; } #region "Animation Textures and Timing" public SpriteAnimations SpriteAnimation { get; set; } = SpriteAnimations.Normal; - public Dictionary AnimatedTextures { get; set; } = - new Dictionary(); + public Dictionary AnimatedTextures { get; set; } = []; public int SpriteFrame { get; set; } = 0; @@ -206,7 +205,7 @@ public Guid SpellCast public long[] Vital { get; set; } = new long[Enum.GetValues().Length]; - IReadOnlyList IEntity.Vitals => Vital.ToList(); + IReadOnlyList IEntity.Vitals => [.. Vital]; public int WalkFrame { get; set; } @@ -221,7 +220,7 @@ public Guid SpellCast public byte Z { get; set; } - public Entity(Guid id, EntityPacket packet, EntityType entityType) + public Entity(Guid id, EntityPacket? packet, EntityType entityType) { Id = id; Type = entityType; @@ -258,7 +257,7 @@ public Entity(Guid id, EntityPacket packet, EntityType entityType) } //Status effects - public List Status { get; private set; } = new List(); + public List Status { get; private set; } = []; IReadOnlyList IEntity.Status => Status; @@ -312,24 +311,16 @@ public virtual int SpriteFrames { get { - switch (SpriteAnimation) + return SpriteAnimation switch { - case SpriteAnimations.Normal: - return Options.Instance.Sprites.NormalFrames; - case SpriteAnimations.Idle: - return Options.Instance.Sprites.IdleFrames; - case SpriteAnimations.Attack: - return Options.Instance.Sprites.AttackFrames; - case SpriteAnimations.Shoot: - return Options.Instance.Sprites.ShootFrames; - case SpriteAnimations.Cast: - return Options.Instance.Sprites.CastFrames; - case SpriteAnimations.Weapon: - return Options.Instance.Sprites.WeaponFrames; - } - - return Options.Instance.Sprites.NormalFrames; - + SpriteAnimations.Normal => Options.Instance.Sprites.NormalFrames, + SpriteAnimations.Idle => Options.Instance.Sprites.IdleFrames, + SpriteAnimations.Attack => Options.Instance.Sprites.AttackFrames, + SpriteAnimations.Shoot => Options.Instance.Sprites.ShootFrames, + SpriteAnimations.Cast => Options.Instance.Sprites.CastFrames, + SpriteAnimations.Weapon => Options.Instance.Sprites.WeaponFrames, + _ => Options.Instance.Sprites.NormalFrames, + }; } } @@ -338,7 +329,7 @@ public virtual int SpriteFrames public virtual Guid MapId { get; set; } //Deserializing - public virtual void Load(EntityPacket packet) + public virtual void Load(EntityPacket? packet) { if (packet == null) { @@ -378,16 +369,16 @@ public virtual void Load(EntityPacket packet) animsToClear.Add(anim); if (!anim.InfiniteLoop) { - animsToClear.Remove(anim); + _ = animsToClear.Remove(anim); } else { foreach (var addedAnim in animsToAdd) { - if (addedAnim.Id == anim.MyBase.Id) + if (addedAnim.Id == anim?.MyBase?.Id) { - animsToClear.Remove(anim); - animsToAdd.Remove(addedAnim); + _ = animsToClear.Remove(anim); + _ = animsToAdd.Remove(addedAnim); break; } @@ -395,9 +386,9 @@ public virtual void Load(EntityPacket packet) foreach (var equipAnim in EquipmentAnimations) { - if (equipAnim == anim) + if (equipAnim == anim && anim != null) { - animsToClear.Remove(anim); + _ = animsToClear.Remove(anim); } } } @@ -513,19 +504,15 @@ public virtual bool IsAllyOf(Player en) return false; } - public void ClearAnimations(List anims) + public void ClearAnimations(List? anims) { - if (anims == null) - { - anims = Animations; - } - + anims ??= Animations; if (anims.Count > 0) { for (var i = 0; i < anims.Count; i++) { anims[i].Dispose(); - Animations.Remove(anims[i]); + _ = Animations.Remove(anims[i]); } } } @@ -539,10 +526,11 @@ public virtual void Dispose() { if (RenderList != null) { - RenderList.Remove(this); + _ = RenderList.Remove(this); } ClearAnimations(null); + GC.SuppressFinalize(this); mDisposed = true; } @@ -571,7 +559,6 @@ public virtual bool Update() if (mDisposed) { LatestMap = null; - return false; } @@ -583,7 +570,6 @@ public virtual bool Update() if (LatestMap == null || !LatestMap.InView()) { Globals.EntitiesToDispose.Add(Id); - return false; } @@ -736,7 +722,6 @@ public virtual bool Update() OffsetX = 0; } - break; case Direction.DownRight: OffsetY += displacementTime; @@ -782,7 +767,7 @@ public virtual bool Update() } var itm = ItemBase.Get(itemId); - AnimationBase anim = null; + AnimationBase? anim = null; if (itm != null) { anim = itm.EquipmentAnimation; @@ -791,25 +776,25 @@ public virtual bool Update() if (anim != null) { if (EquipmentAnimations[z] != null && - (EquipmentAnimations[z].MyBase != anim || EquipmentAnimations[z].Disposed())) + (EquipmentAnimations[z]!.MyBase != anim || EquipmentAnimations[z]!.Disposed())) { - EquipmentAnimations[z].Dispose(); - Animations.Remove(EquipmentAnimations[z]); + EquipmentAnimations[z]!.Dispose(); + _ = Animations.Remove(EquipmentAnimations[z]!); EquipmentAnimations[z] = null; } if (EquipmentAnimations[z] == null) { EquipmentAnimations[z] = new Animation(anim, true, true, -1, this); - Animations.Add(EquipmentAnimations[z]); + Animations.Add(EquipmentAnimations[z]!); } } else { if (EquipmentAnimations[z] != null) { - EquipmentAnimations[z].Dispose(); - Animations.Remove(EquipmentAnimations[z]); + EquipmentAnimations[z]!.Dispose(); + _ = Animations.Remove(EquipmentAnimations[z]!); EquipmentAnimations[z] = null; } } @@ -818,8 +803,8 @@ public virtual bool Update() { if (EquipmentAnimations[z] != null) { - EquipmentAnimations[z].Dispose(); - Animations.Remove(EquipmentAnimations[z]); + EquipmentAnimations[z]!.Dispose(); + _ = Animations.Remove(EquipmentAnimations[z]!); EquipmentAnimations[z] = null; } } @@ -831,7 +816,7 @@ public virtual bool Update() { if (!chatbubble.Update()) { - mChatBubbles.Remove(chatbubble); + _ = mChatBubbles.Remove(chatbubble); } } @@ -847,7 +832,7 @@ public virtual bool Update() CalculateOrigin(); - List animsToRemove = null; + List? animsToRemove = null; foreach (var animInstance in Animations) { animInstance.Update(); @@ -855,13 +840,8 @@ public virtual bool Update() //If disposed mark to be removed and continue onward if (animInstance.Disposed()) { - if (animsToRemove == null) - { - animsToRemove = new List(); - } - + animsToRemove ??= []; animsToRemove.Add(animInstance); - continue; } @@ -889,7 +869,7 @@ public virtual bool Update() { foreach (var anim in animsToRemove) { - Animations.Remove(anim); + _ = Animations.Remove(anim); } } @@ -923,7 +903,7 @@ public virtual int CalculateAttackTime() /// /// Returns whether this entity should be drawn. /// - public virtual bool ShouldDraw => !IsHidden && (!IsStealthed || this == Globals.Me || Globals.Me.IsInMyParty(Id)); + public virtual bool ShouldDraw => !IsHidden && (!IsStealthed || this == Globals.Me || Globals.Me?.IsInMyParty(Id) == true); /// /// Returns whether the name of this entity should be drawn. @@ -962,6 +942,11 @@ public virtual bool ShouldDrawName var me = Globals.Me; + if (me == default) + { + return false; + } + if (Globals.Database.MyOverheadInfo && player.Id == me.Id) { return true; @@ -992,10 +977,10 @@ public virtual bool ShouldDrawName public virtual HashSet? DetermineRenderOrder(HashSet? existingRenderSet, IMapInstance? map) { - existingRenderSet?.Remove(this); + _ = (existingRenderSet?.Remove(this)); var playerMap = Globals.Me?.MapInstance; - if (map == default || playerMap == default) + if (map == default || playerMap == default || Globals.MapGrid == default) { return default; } @@ -1048,7 +1033,7 @@ public virtual bool ShouldDrawName } renderSet = renderingEntities[priority, entityY]; - renderSet.Add(this); + _ = renderSet.Add(this); return renderSet; } @@ -1092,7 +1077,7 @@ public virtual void Draw() // If entity is stealth, don't render unless the entity is the player or is within their party. case SpellEffect.Stealth: - if (this != Globals.Me && !(this is Player player && Globals.Me.IsInMyParty(player))) + if (this != Globals.Me && !(this is Player player && Globals.Me?.IsInMyParty(player) == true)) { return; } @@ -1328,23 +1313,23 @@ public virtual void DrawEquipment(string filename, Color renderColor) } // Paperdoll textures and Frames. - GameTexture paperdollTex = null; + GameTexture? paperdollTex = null; var spriteFrames = SpriteFrames; // Extract filename without it's extension. var filenameNoExt = Path.GetFileNameWithoutExtension(filename); // Equipment's custom paperdoll texture. - if (SpriteAnimation == SpriteAnimations.Attack || - SpriteAnimation == SpriteAnimations.Cast || - SpriteAnimation == SpriteAnimations.Weapon) + if (SpriteAnimation is SpriteAnimations.Attack or + SpriteAnimations.Cast or + SpriteAnimations.Weapon) { // Extract animation name from the AnimatedTextures list. var animationName = Path.GetFileNameWithoutExtension(AnimatedTextures[SpriteAnimation].Name); // Extract the substring after the separator. var separatorIndex = animationName.IndexOf('_') + 1; - var customAnimationName = animationName.Substring(separatorIndex); + var customAnimationName = animationName[separatorIndex..]; // Try to get custom paperdoll texture. var customPaperdollTex = @@ -1442,12 +1427,12 @@ public void DrawLabels( int position, Color labelColor, Color textColor, - Color borderColor = null, - Color backgroundColor = null + Color? borderColor = null, + Color? backgroundColor = null ) { // Are we supposed to hide this Label? - if (!ShouldDrawName || string.IsNullOrWhiteSpace(label)) + if (!ShouldDrawName || string.IsNullOrWhiteSpace(label) || Graphics.Renderer == default) { return; } @@ -1493,10 +1478,10 @@ public void DrawLabels( ); } - public virtual void DrawName(Color textColor, Color borderColor = null, Color backgroundColor = null) + public virtual void DrawName(Color? textColor, Color? borderColor = null, Color? backgroundColor = null) { // Are we really supposed to draw this name? - if (!ShouldDrawName) + if (!ShouldDrawName || Graphics.Renderer == default) { return; } @@ -1504,36 +1489,20 @@ public virtual void DrawName(Color textColor, Color borderColor = null, Color ba //Check for npc colors if (textColor == null) { - LabelColor? color; - switch (Aggression) + var color = Aggression switch { - case NpcAggression.Aggressive: - color = CustomColors.Names.Npcs["Aggressive"]; - break; - - case NpcAggression.AttackWhenAttacked: - color = CustomColors.Names.Npcs["AttackWhenAttacked"]; - break; - - case NpcAggression.AttackOnSight: - color = CustomColors.Names.Npcs["AttackOnSight"]; - break; - - case NpcAggression.Guard: - color = CustomColors.Names.Npcs["Guard"]; - break; - - case NpcAggression.Neutral: - default: - color = CustomColors.Names.Npcs["Neutral"]; - break; - } + NpcAggression.Aggressive => (LabelColor?)CustomColors.Names.Npcs["Aggressive"], + NpcAggression.AttackWhenAttacked => (LabelColor?)CustomColors.Names.Npcs["AttackWhenAttacked"], + NpcAggression.AttackOnSight => (LabelColor?)CustomColors.Names.Npcs["AttackOnSight"], + NpcAggression.Guard => (LabelColor?)CustomColors.Names.Npcs["Guard"], + _ => (LabelColor?)CustomColors.Names.Npcs["Neutral"], + }; if (color != null) { textColor = color?.Name; - backgroundColor = backgroundColor ?? color?.Background; - borderColor = borderColor ?? color?.Outline; + backgroundColor ??= color?.Background; + borderColor ??= color?.Outline; } } @@ -1568,16 +1537,21 @@ public virtual void DrawName(Color textColor, Color borderColor = null, Color ba Graphics.Renderer.DrawString( name, Graphics.EntityNameFont, x - (int)Math.Ceiling(textSize.X / 2f), (int)y, 1, - Color.FromArgb(textColor.ToArgb()), true, null, Color.FromArgb(borderColor.ToArgb()) + textColor, true, null, Color.FromArgb(borderColor.ToArgb()) ); } public float GetLabelLocation(LabelType type) { + if (Graphics.Renderer == default) + { + return 0f; + } + var y = GetTop() - 8; //Need room for HP bar if not an event. - if (!(this is Event) && ShouldDrawHpBar) + if (this is not Event && ShouldDrawHpBar) { y -= GetBoundingHpBarTexture().Height + 2; } @@ -1637,6 +1611,7 @@ public float GetLabelLocation(LabelType type) var guildSize = Graphics.Renderer.MeasureText(player.Guild, Graphics.EntityNameFont, 1); y -= 2 + guildSize.Y; } + break; } @@ -1653,6 +1628,7 @@ public long GetShieldSize() shieldSize += status.Shield[(int)Enums.Vital.Health]; } } + return shieldSize; } @@ -1837,7 +1813,7 @@ public void DrawCastingBar() } } - public bool ShouldDrawTarget => !(this is Projectile) && LatestMap != default; + public bool ShouldDrawTarget => this is not Projectile && LatestMap != default; public void DrawTarget(int priority) { @@ -1897,7 +1873,7 @@ public bool StatusActive(Guid guid) return false; } - public IStatus GetStatus(Guid guid) + public IStatus? GetStatus(Guid guid) { foreach (var status in Status) { @@ -1913,7 +1889,7 @@ public IStatus GetStatus(Guid guid) public void SortStatuses() { //Sort Status effects by remaining time - Status = Status.OrderByDescending(x => x.RemainingMs).ToList(); + Status = [.. Status.OrderByDescending(x => x.RemainingMs)]; } private void UpdateSpriteAnimation() @@ -2083,7 +2059,7 @@ public virtual void LoadTextures(string textureName) protected virtual void LoadAnimationTexture(string textureName, SpriteAnimations spriteAnimation) { SpriteAnimations spriteAnimationOveride = spriteAnimation; - string textureOverride = default; + string? textureOverride = default; switch (spriteAnimation) { @@ -2096,6 +2072,7 @@ protected virtual void LoadAnimationTexture(string textureName, SpriteAnimations { textureOverride = classDescriptor.AttackSpriteOverride; } + break; case SpriteAnimations.Shoot: @@ -2116,6 +2093,7 @@ protected virtual void LoadAnimationTexture(string textureName, SpriteAnimations spriteAnimationOveride = SpriteAnimations.Weapon; } } + break; case SpriteAnimations.Cast: @@ -2123,6 +2101,7 @@ protected virtual void LoadAnimationTexture(string textureName, SpriteAnimations { textureOverride = spellDescriptor.CastSpriteOverride; } + break; case SpriteAnimations.Weapon: @@ -2138,13 +2117,14 @@ protected virtual void LoadAnimationTexture(string textureName, SpriteAnimations textureOverride = itemDescriptor.WeaponSpriteOverride; } } + break; default: throw new ArgumentOutOfRangeException(nameof(spriteAnimation)); } - if (TryGetAnimationTexture(textureName, spriteAnimationOveride, textureOverride, out var texture)) + if (!string.IsNullOrEmpty(textureOverride) && TryGetAnimationTexture(textureName, spriteAnimationOveride, textureOverride, out var texture)) { AnimatedTextures[spriteAnimation] = texture; } @@ -2182,6 +2162,11 @@ public Direction DirectionToTarget(Entity en) var originMapController = MapInstance; var targetMapController = en.MapInstance; + if (originMapController == null || targetMapController == null) + { + return Dir; + } + var originY = Y + originMapController.GridY * Options.MapHeight; var originX = X + originMapController.GridX * Options.MapWidth; var targetY = en.Y + targetMapController.GridY * Options.MapHeight; @@ -2230,7 +2215,7 @@ public int IsTileBlocked( Point delta, int z, Guid mapId, - ref IEntity blockedBy, + ref IEntity? blockedBy, bool ignoreAliveResources = true, bool ignoreDeadResources = true, bool ignoreNpcAvoids = true, @@ -2274,7 +2259,7 @@ public int IsTileBlocked( tmpY = delta.Y - Options.MapHeight; } - if (gridX < 0 || gridY < 0 || gridX >= Globals.MapGridWidth || gridY >= Globals.MapGridHeight) + if (Globals.MapGrid == default || gridX < 0 || gridY < 0 || gridX >= Globals.MapGridWidth || gridY >= Globals.MapGridHeight) { return -2; } @@ -2299,7 +2284,7 @@ public int IsTileBlocked( en.Value.Y == tmpY && en.Value.Z == Z) { - if (!(en.Value is Projectile)) + if (en.Value is not Projectile) { switch (en.Value) { @@ -2326,6 +2311,7 @@ public int IsTileBlocked( continue; } } + break; case Player player: @@ -2335,6 +2321,7 @@ public int IsTileBlocked( { continue; } + break; } @@ -2380,7 +2367,7 @@ public int IsTileBlocked( en.Value.Z == Z && !en.Value.Passable) { - blockedBy = en.Value as Critter; + blockedBy = en.Value; return -4; } @@ -2429,8 +2416,4 @@ public int IsTileBlocked( { Dispose(); } - - - - } diff --git a/Intersect.Client/Entities/Events/Dialog.cs b/Intersect.Client/Entities/Events/Dialog.cs index 93f47a7a7..d9f118cb6 100644 --- a/Intersect.Client/Entities/Events/Dialog.cs +++ b/Intersect.Client/Entities/Events/Dialog.cs @@ -1,9 +1,7 @@ -namespace Intersect.Client.Entities.Events; - +namespace Intersect.Client.Entities.Events; public partial class Dialog { - public Guid EventId; public string Face = ""; @@ -21,5 +19,4 @@ public partial class Dialog public int ResponseSent; public int Type; - } diff --git a/Intersect.Client/Entities/Events/Event.cs b/Intersect.Client/Entities/Events/Event.cs index 4f16e1414..6c156e389 100644 --- a/Intersect.Client/Entities/Events/Event.cs +++ b/Intersect.Client/Entities/Events/Event.cs @@ -3,7 +3,6 @@ using Intersect.Client.Framework.Graphics; using Intersect.Client.Framework.Maps; using Intersect.Client.General; -using Intersect.Client.Maps; using Intersect.Enums; using Intersect.GameObjects.Events; using Intersect.Logging; @@ -21,18 +20,8 @@ public partial class Event : Entity public bool DisablePreview { get; set; } - public string FaceGraphic { get; set; } = string.Empty; - public EventGraphic Graphic { get; set; } = new EventGraphic(); - public int Layer { get; set; } - - private int mOldRenderLevel { get; set; } - - private MapInstance mOldRenderMap { get; set; } - - private int mOldRenderY { get; set; } - public int RenderLevel { get; set; } = 1; public bool WalkingAnim { get; set; } = true; @@ -66,13 +55,14 @@ public Event(Guid id, EventEntityPacket packet) : base(id, packet, EntityType.Ev mRenderPriority = 1; } - public override void Load(EntityPacket packet) + public override void Load(EntityPacket? packet) { - if (!(packet is EventEntityPacket eventEntityPacket)) + if (packet is not EventEntityPacket eventEntityPacket) { Log.Error($"Received invalid packet for {nameof(Event)}: {packet?.GetType()?.FullName}"); return; } + DirectionFix = eventEntityPacket.DirectionFix; WalkingAnim = eventEntityPacket.WalkingAnim; DisablePreview = eventEntityPacket.DisablePreview; @@ -102,7 +92,7 @@ public override bool Update() return success; } - protected bool TryEnsureTexture(out GameTexture texture) + protected bool TryEnsureTexture(out GameTexture? texture) { if (_drawCompletedWithoutTexture) { @@ -173,6 +163,11 @@ public override void Draw() // If we're smaller than a tile, force the target size to a tile. WorldPos = destRectangle; + if (texture == default) + { + return; + } + Graphics.DrawGameTexture(texture, srcRectangle, destRectangle, Color.White); } @@ -193,15 +188,15 @@ public override void LoadTextures(string textureName) } } - public override HashSet DetermineRenderOrder(HashSet renderList, IMapInstance map) + public override HashSet? DetermineRenderOrder(HashSet? renderList, IMapInstance? map) { if (RenderLevel == 1) { return base.DetermineRenderOrder(renderList, map); } - renderList?.Remove(this); - if (map == null || Globals.Me == null || Globals.Me.MapInstance == null) + _ = (renderList?.Remove(this)); + if (map == null || Globals.Me == null || Globals.Me.MapInstance == null || Globals.MapGrid == default) { return null; } @@ -241,31 +236,11 @@ public override HashSet DetermineRenderOrder(HashSet renderList, var maps = y - (gridY - 2); var renderSet = Graphics.RenderingEntities[priority, Options.MapHeight * maps + Y]; - // If bugs arise from switching to the above, remove and uncomment this - //HashSet renderSet = null; - //if (y == gridY - 2) - //{ - // renderSet = Graphics.RenderingEntities[priority, Y]; - //} - //else if (y == gridY - 1) - //{ - // renderSet = Graphics.RenderingEntities[priority, Options.MapHeight + Y]; - //} - //else if (y == gridY) - //{ - // renderSet = Graphics.RenderingEntities[priority, Options.MapHeight * 2 + Y]; - //} - //else if (y == gridY + 1) - //{ - // renderSet = Graphics.RenderingEntities[priority, Options.MapHeight * 3 + Y]; - //} - //else if (y == gridY + 2) - //{ - // renderSet = Graphics.RenderingEntities[priority, Options.MapHeight * 4 + Y]; - //} - - renderSet?.Add(this); - renderList = renderSet; + _ = (renderSet?.Add(this)); + if(renderSet != default) + { + renderList = renderSet; + } return renderList; } @@ -300,7 +275,7 @@ public override float GetTop(int overrideHeight = -1) return top - offset; } - public override void DrawName(Color textColor, Color borderColor, Color backgroundColor) + public override void DrawName(Color? textColor, Color? borderColor, Color? backgroundColor) { base.DrawName( textColor: textColor ?? new Color(CustomColors.Names.Events.Name), diff --git a/Intersect.Client/Entities/Events/Hold.cs b/Intersect.Client/Entities/Events/Hold.cs deleted file mode 100644 index d07508f8d..000000000 --- a/Intersect.Client/Entities/Events/Hold.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace Intersect.Client.Entities.Events; - - -public partial class Hold -{ - - public Guid EventId; - - public Guid MapId; - - public Hold(Guid eventId, Guid mapId) - { - EventId = eventId; - MapId = mapId; - } - -} diff --git a/Intersect.Client/Entities/FriendInstance.cs b/Intersect.Client/Entities/FriendInstance.cs index e27f810d1..db9cc1076 100644 --- a/Intersect.Client/Entities/FriendInstance.cs +++ b/Intersect.Client/Entities/FriendInstance.cs @@ -1,14 +1,12 @@ -using Intersect.Client.Framework.Entities; +using Intersect.Client.Framework.Entities; namespace Intersect.Client.Entities; public partial class FriendInstance : IFriendInstance { + public string? Map { get; set; } - public string Map { get; set; } - - public string Name { get; set; } + public string Name { get; set; } = null!; public bool Online { get; set; } = false; - } diff --git a/Intersect.Client/Entities/HotbarInstance.cs b/Intersect.Client/Entities/HotbarInstance.cs index 7d39792ca..a3edfa506 100644 --- a/Intersect.Client/Entities/HotbarInstance.cs +++ b/Intersect.Client/Entities/HotbarInstance.cs @@ -1,4 +1,4 @@ -using Intersect.Client.Framework.Entities; +using Intersect.Client.Framework.Entities; using Intersect.Enums; using Newtonsoft.Json; @@ -6,7 +6,6 @@ namespace Intersect.Client.Entities; public partial class HotbarInstance : IHotbarInstance { - public Guid BagId { get; set; } = Guid.Empty; public Guid ItemOrSpellId { get; set; } = Guid.Empty; @@ -17,5 +16,4 @@ public void Load(string data) { JsonConvert.PopulateObject(data, this); } - } diff --git a/Intersect.Client/Entities/PartyMember.cs b/Intersect.Client/Entities/PartyMember.cs index b35334345..75a2e7b64 100644 --- a/Intersect.Client/Entities/PartyMember.cs +++ b/Intersect.Client/Entities/PartyMember.cs @@ -1,12 +1,10 @@ -using Intersect.Client.Framework.Entities; +using Intersect.Client.Framework.Entities; using Intersect.Enums; namespace Intersect.Client.Entities; - public partial class PartyMember : IPartyMember { - public Guid Id { get; set; } public int Level { get; set; } @@ -25,5 +23,4 @@ public PartyMember(Guid id, string name, long[] vital, long[] maxVital, int leve MaxVital = maxVital; Level = level; } - } diff --git a/Intersect.Client/Entities/Player.cs b/Intersect.Client/Entities/Player.cs index e7c6e03dd..d84be7630 100644 --- a/Intersect.Client/Entities/Player.cs +++ b/Intersect.Client/Entities/Player.cs @@ -25,10 +25,8 @@ namespace Intersect.Client.Entities; - public partial class Player : Entity, IPlayer { - public delegate void InventoryUpdated(); private Guid _class; @@ -56,49 +54,46 @@ public Guid Class IReadOnlyList IPlayer.Friends => Friends; - public List Friends { get; set; } = new(); + public List Friends { get; set; } = []; IReadOnlyList IPlayer.HotbarSlots => Hotbar.ToList(); public HotbarInstance[] Hotbar { get; set; } = new HotbarInstance[Options.Instance.PlayerOpts.HotbarSlotCount]; - public InventoryUpdated InventoryUpdatedDelegate { get; set; } + public InventoryUpdated? InventoryUpdatedDelegate { get; set; } IReadOnlyDictionary IPlayer.ItemCooldowns => ItemCooldowns; - public Dictionary ItemCooldowns { get; set; } = new(); - - private Entity mLastBumpedEvent; + public Dictionary ItemCooldowns { get; set; } = []; - private List mParty; + private Entity? mLastBumpedEvent; - private Direction _lastMoveDirection; + private List? mParty; public override Direction MoveDir { get => base.MoveDir; set { - _lastMoveDirection = base.MoveDir; base.MoveDir = value; } } IReadOnlyDictionary IPlayer.QuestProgress => QuestProgress; - public Dictionary QuestProgress { get; set; } = new(); + public Dictionary QuestProgress { get; set; } = []; - public Guid[] HiddenQuests { get; set; } = new Guid[0]; + public Guid[] HiddenQuests { get; set; } = []; IReadOnlyDictionary IPlayer.SpellCooldowns => SpellCooldowns; - public Dictionary SpellCooldowns { get; set; } = new(); + public Dictionary SpellCooldowns { get; set; } = []; public int StatPoints { get; set; } = 0; - public EntityBox TargetBox { get; set; } + public EntityBox? TargetBox { get; set; } - public PlayerStatusWindow StatusWindow { get; set; } + public PlayerStatusWindow? StatusWindow { get; set; } public Guid TargetIndex { get; set; } @@ -119,19 +114,19 @@ public override Direction MoveDir Point mlastTargetScanLocation = new(-1, -1); - Dictionary mlastTargetList = new(); // Entity, Last Time Selected + readonly Dictionary mlastTargetList = []; // Entity, Last Time Selected - Entity mLastEntitySelected; + Entity? mLastEntitySelected; - private Dictionary mLastHotbarUseTime = new(); - private int mHotbarUseDelay = 150; + private readonly Dictionary mLastHotbarUseTime = []; + private readonly int mHotbarUseDelay = 150; /// /// Name of our guild if we are in one. /// - public string Guild { get; set; } + public string? Guild { get; set; } - string IPlayer.GuildName => Guild; + string IPlayer.GuildName => Guild ?? string.Empty; /// /// Index of our rank where 0 is the leader @@ -146,12 +141,14 @@ public override Direction MoveDir /// /// Obtains our rank and permissions from the game config /// - public GuildRank GuildRank => IsInGuild ? Options.Instance.Guild.Ranks[Math.Max(0, Math.Min(Rank, Options.Instance.Guild.Ranks.Length - 1))] : null; + public GuildRank? GuildRank => IsInGuild + ? Options.Instance.Guild.Ranks[Math.Max(0, Math.Min(Rank, Options.Instance.Guild.Ranks.Length - 1))] + : null; /// /// Contains a record of all members of this player's guild. /// - public GuildMember[] GuildMembers = new GuildMember[0]; + public GuildMember[] GuildMembers = []; public Player(Guid id, PlayerEntityPacket packet) : base(id, packet, EntityType.Player) { @@ -169,11 +166,7 @@ public List Party { get { - if (mParty == null) - { - mParty = new List(); - } - + mParty ??= []; return mParty; } } @@ -248,7 +241,6 @@ public override bool Update() HandleInput(); } - if (!IsBusy) { if (this == Globals.Me && IsMoving == false) @@ -268,7 +260,7 @@ public override bool Update() IsCastingCheckTimer = Timing.Global.Milliseconds + 350; } } - else if (!Globals.Me.TryAttack()) + else if (Globals.Me?.TryAttack() == false) { if (!Globals.Me.IsAttacking && (!IsMoving || Options.Instance.PlayerOpts.AllowCombatMovement)) { @@ -280,7 +272,7 @@ public override bool Update() //Holding block button for "auto blocking" if (Controls.KeyDown(Control.Block)) { - TryBlock(); + _ = TryBlock(); } } @@ -294,12 +286,12 @@ public override bool Update() { if (!Globals.Entities.TryGetValue(TargetIndex, out var foundEntity)) { - foundEntity = TargetBox.MyEntity?.MapInstance?.Entities.FirstOrDefault(entity => entity.Id == TargetIndex) as Entity; + foundEntity = TargetBox?.MyEntity?.MapInstance?.Entities.FirstOrDefault(entity => entity.Id == TargetIndex) as Entity; } if (foundEntity == default || foundEntity.IsHidden || foundEntity.IsStealthed) { - ClearTarget(); + _ = ClearTarget(); } } @@ -323,10 +315,16 @@ public override bool Update() } //Loading - public override void Load(EntityPacket packet) + public override void Load(EntityPacket? packet) { base.Load(packet); - var playerPacket = (PlayerEntityPacket)packet; + var playerPacket = packet as PlayerEntityPacket; + + if (playerPacket == default) + { + return; + } + Gender = playerPacket.Gender; Class = playerPacket.ClassId; AccessLevel = playerPacket.AccessLevel; @@ -410,12 +408,15 @@ public void TryDropItem(int inventorySlotIndex) ); } - private void DropInputBoxOkay(object sender, EventArgs e) + private void DropInputBoxOkay(object? sender, EventArgs e) { - var value = (int)Math.Round(((InputBox)sender).Value); - if (value > 0) + if (sender is InputBox inputBox) { - PacketSender.SendDropItem((int)((InputBox)sender).UserData, value); + var value = (int)Math.Round(inputBox.Value); + if (value > 0) + { + PacketSender.SendDropItem((int)inputBox.UserData, value); + } } } @@ -432,11 +433,11 @@ public int FindItem(Guid itemId, int itemVal = 1) return -1; } - private int GetQuantityOfItemIn(IEnumerable items, Guid itemId) + private static int GetQuantityOfItemIn(IEnumerable items, Guid itemId) { long count = 0; - foreach (var slot in (items ?? Enumerable.Empty())) + foreach (var slot in items ?? []) { if (slot?.ItemId == itemId) { @@ -447,14 +448,14 @@ private int GetQuantityOfItemIn(IEnumerable items, Guid itemId) return (int)Math.Min(count, int.MaxValue); } - public int GetQuantityOfItemInBank(Guid itemId) => GetQuantityOfItemIn(Globals.Bank, itemId); + public static int GetQuantityOfItemInBank(Guid itemId) => GetQuantityOfItemIn(Globals.Bank, itemId); public int GetQuantityOfItemInInventory(Guid itemId) => GetQuantityOfItemIn(Inventory, itemId); public void TryUseItem(int index) { if (!IsItemOnCooldown(index) && - index >= 0 && index < Globals.Me.Inventory.Length && Globals.Me.Inventory[index]?.Quantity > 0) + index >= 0 && index < Globals.Me?.Inventory.Length && Globals.Me.Inventory[index]?.Quantity > 0) { PacketSender.SendUseItem(index, TargetIndex); } @@ -462,9 +463,9 @@ public void TryUseItem(int index) public long GetItemCooldown(Guid id) { - if (ItemCooldowns.ContainsKey(id)) + if (ItemCooldowns.TryGetValue(id, out var value)) { - return ItemCooldowns[id]; + return value; } return 0; @@ -543,12 +544,12 @@ public bool IsItemOnCooldown(int slot) var itm = Inventory[slot]; if (itm.ItemId != Guid.Empty) { - if (ItemCooldowns.ContainsKey(itm.ItemId) && ItemCooldowns[itm.ItemId] > Timing.Global.Milliseconds) + if (ItemCooldowns.TryGetValue(itm.ItemId, out var value) && value > Timing.Global.Milliseconds) { return true; } - if ((ItemBase.TryGet(itm.ItemId, out var itemBase) && !itemBase.IgnoreGlobalCooldown) && Globals.Me.GlobalCooldown > Timing.Global.Milliseconds) + if ((ItemBase.TryGet(itm.ItemId, out var itemBase) && !itemBase.IgnoreGlobalCooldown) && Globals.Me?.GlobalCooldown > Timing.Global.Milliseconds) { return true; } @@ -565,12 +566,12 @@ public long GetItemRemainingCooldown(int slot) var itm = Inventory[slot]; if (itm.ItemId != Guid.Empty) { - if (ItemCooldowns.ContainsKey(itm.ItemId) && ItemCooldowns[itm.ItemId] > Timing.Global.Milliseconds) + if (ItemCooldowns.TryGetValue(itm.ItemId, out var value) && value > Timing.Global.Milliseconds) { - return ItemCooldowns[itm.ItemId] - Timing.Global.Milliseconds; + return value - Timing.Global.Milliseconds; } - if ((ItemBase.TryGet(itm.ItemId, out var itemBase) && !itemBase.IgnoreGlobalCooldown) && Globals.Me.GlobalCooldown > Timing.Global.Milliseconds) + if ((ItemBase.TryGet(itm.ItemId, out var itemBase) && !itemBase.IgnoreGlobalCooldown) && Globals.Me?.GlobalCooldown > Timing.Global.Milliseconds) { return Globals.Me.GlobalCooldown - Timing.Global.Milliseconds; } @@ -587,12 +588,12 @@ public bool IsSpellOnCooldown(int slot) var spl = Spells[slot]; if (spl.Id != Guid.Empty) { - if (SpellCooldowns.ContainsKey(spl.Id) && SpellCooldowns[spl.Id] > Timing.Global.Milliseconds) + if (SpellCooldowns.TryGetValue(spl.Id, out var value) && value > Timing.Global.Milliseconds) { return true; } - if ((SpellBase.TryGet(spl.Id, out var spellBase) && !spellBase.IgnoreGlobalCooldown) && Globals.Me.GlobalCooldown > Timing.Global.Milliseconds) + if ((SpellBase.TryGet(spl.Id, out var spellBase) && !spellBase.IgnoreGlobalCooldown) && Globals.Me?.GlobalCooldown > Timing.Global.Milliseconds) { return true; } @@ -624,7 +625,7 @@ public long GetSpellRemainingCooldown(int slot) return cd - now; } - if (SpellBase.TryGet(spell.Id, out var spellBase) && !spellBase.IgnoreGlobalCooldown && Globals.Me.GlobalCooldown > now) + if (SpellBase.TryGet(spell.Id, out var spellBase) && !spellBase.IgnoreGlobalCooldown && Globals.Me?.GlobalCooldown > now) { return Globals.Me.GlobalCooldown - now; } @@ -642,12 +643,12 @@ public void TrySellItem(int inventorySlotIndex) var shop = Globals.GameShop; var shopCanBuyItem = - shop.BuyingWhitelist && shop.BuyingItems.Any(buyingItem => buyingItem.ItemId == itemDescriptor.Id) - || !shop.BuyingWhitelist && !shop.BuyingItems.Any(buyingItem => buyingItem.ItemId == itemDescriptor.Id); + shop?.BuyingWhitelist == true && shop.BuyingItems.Any(buyingItem => buyingItem.ItemId == itemDescriptor.Id) + || shop?.BuyingWhitelist == false && !shop.BuyingItems.Any(buyingItem => buyingItem.ItemId == itemDescriptor.Id); var prompt = Strings.Shop.SellPrompt; var inputType = InputBox.InputType.YesNo; - EventHandler onSuccess = SellInputBoxOkay; + EventHandler? onSuccess = SellInputBoxOkay; var userData = inventorySlotIndex; var slotQuantity = inventorySlot.Quantity; var maxQuantity = slotQuantity; @@ -688,8 +689,8 @@ public void TrySellItem(int inventorySlotIndex) public void TryBuyItem(int shopSlotIndex) { //Confirm the purchase - var shopSlot = Globals.GameShop.SellingItems[shopSlotIndex]; - if (!ItemBase.TryGet(shopSlot.ItemId, out var itemDescriptor)) + var shopSlot = Globals.GameShop?.SellingItems[shopSlotIndex]; + if (shopSlot == default || !ItemBase.TryGet(shopSlot.ItemId, out var itemDescriptor)) { return; } @@ -731,27 +732,36 @@ public void TryBuyItem(int shopSlotIndex) ); } - private void BuyItemInputBoxOkay(object sender, EventArgs e) + private void BuyItemInputBoxOkay(object? sender, EventArgs e) { - var value = (int)Math.Round(((InputBox)sender).Value); - if (value > 0) + if (sender is InputBox inputBox) { - PacketSender.SendBuyItem((int)((InputBox)sender).UserData, value); + var value = (int)Math.Round(inputBox.Value); + if (value > 0) + { + PacketSender.SendBuyItem((int)inputBox.UserData, value); + } } } - private void SellItemInputBoxOkay(object sender, EventArgs e) + private void SellItemInputBoxOkay(object? sender, EventArgs e) { - var value = (int)Math.Round(((InputBox)sender).Value); - if (value > 0) + if (sender is InputBox inputBox) { - PacketSender.SendSellItem((int)((InputBox)sender).UserData, value); + var value = (int)Math.Round(inputBox.Value); + if (value > 0) + { + PacketSender.SendSellItem((int)inputBox.UserData, value); + } } } - private void SellInputBoxOkay(object sender, EventArgs e) + private void SellInputBoxOkay(object? sender, EventArgs e) { - PacketSender.SendSellItem((int)((InputBox)sender).UserData, 1); + if (sender is InputBox inputBox) + { + PacketSender.SendSellItem((int)inputBox.UserData, 1); + } } /// @@ -774,7 +784,7 @@ public bool TryDepositItem( // Permission Check for Guild Bank if (Globals.GuildBank && !IsGuildBankDepositAllowed()) { - ChatboxMsg.AddMessage(new ChatboxMsg(Strings.Guilds.NotAllowedDeposit.ToString(Globals.Me.Guild), CustomColors.Alerts.Error, ChatMessageType.Bank)); + ChatboxMsg.AddMessage(new ChatboxMsg(Strings.Guilds.NotAllowedDeposit.ToString(Globals.Me?.Guild), CustomColors.Alerts.Error, ChatMessageType.Bank)); return false; } @@ -858,20 +868,23 @@ public bool TryDepositItem( return true; } - private bool IsGuildBankDepositAllowed() + private static bool IsGuildBankDepositAllowed() { - return !string.IsNullOrWhiteSpace(Globals.Me.Guild) && - (Globals.Me.GuildRank.Permissions.BankDeposit || Globals.Me.Rank == 0); + return !string.IsNullOrWhiteSpace(Globals.Me?.Guild) && + (Globals.Me?.GuildRank?.Permissions.BankDeposit == true || Globals.Me?.Rank == 0); } - private void DepositItemInputBoxOkay(object sender, EventArgs e) + private void DepositItemInputBoxOkay(object? sender, EventArgs e) { - var value = (int)Math.Round(((InputBox)sender).Value); - if (value > 0) + if (sender is InputBox inputBox) { - var userData = (int[])((InputBox)sender).UserData; + var value = (int)Math.Round(inputBox.Value); + if (value > 0) + { + var userData = (int[])inputBox.UserData; - PacketSender.SendDepositItem(userData[0], value, userData[1]); + PacketSender.SendDepositItem(userData[0], value, userData[1]); + } } } @@ -895,7 +908,7 @@ public bool TryWithdrawItem( // Permission Check for Guild Bank if (Globals.GuildBank && !IsGuildBankWithdrawAllowed()) { - ChatboxMsg.AddMessage(new ChatboxMsg(Strings.Guilds.NotAllowedWithdraw.ToString(Globals.Me.Guild), CustomColors.Alerts.Error, ChatMessageType.Bank)); + ChatboxMsg.AddMessage(new ChatboxMsg(Strings.Guilds.NotAllowedWithdraw.ToString(Globals.Me?.Guild), CustomColors.Alerts.Error, ChatMessageType.Bank)); return false; } @@ -978,19 +991,22 @@ public bool TryWithdrawItem( return true; } - private bool IsGuildBankWithdrawAllowed() + private static bool IsGuildBankWithdrawAllowed() { - return !string.IsNullOrWhiteSpace(Globals.Me.Guild) && - (Globals.Me.GuildRank.Permissions.BankRetrieve || Globals.Me.Rank == 0); + return !string.IsNullOrWhiteSpace(Globals.Me?.Guild) && + (Globals.Me?.GuildRank?.Permissions.BankRetrieve == true || Globals.Me?.Rank == 0); } - private void WithdrawItemInputBoxOkay(object sender, EventArgs e) + private void WithdrawItemInputBoxOkay(object? sender, EventArgs e) { - var value = (int)Math.Round(((InputBox)sender).Value); - if (value > 0) + if (sender is InputBox inputBox) { - int[] userData = (int[])((InputBox)sender).UserData; - PacketSender.SendWithdrawItem(userData[0], value, userData[1]); + var value = (int)Math.Round(inputBox.Value); + if (value > 0) + { + int[] userData = (int[])inputBox.UserData; + PacketSender.SendWithdrawItem(userData[0], value, userData[1]); + } } } @@ -1003,7 +1019,7 @@ public void TryStoreBagItem(int inventorySlotIndex, int bagSlotIndex) return; } - int[] userData = new int[2] { inventorySlotIndex, bagSlotIndex }; + int[] userData = [inventorySlotIndex, bagSlotIndex]; var quantity = inventorySlot.Quantity; var maxQuantity = quantity; @@ -1032,13 +1048,16 @@ public void TryStoreBagItem(int inventorySlotIndex, int bagSlotIndex) ); } - private void StoreBagItemInputBoxOkay(object sender, EventArgs e) + private void StoreBagItemInputBoxOkay(object? sender, EventArgs e) { - var value = (int)Math.Round(((InputBox)sender).Value); - if (value > 0) + if (sender is InputBox inputBox) { - int[] userData = (int[])((InputBox)sender).UserData; - PacketSender.SendStoreBagItem(userData[0], value, userData[1]); + var value = (int)Math.Round(inputBox.Value); + if (value > 0) + { + int[] userData = (int[])inputBox.UserData; + PacketSender.SendStoreBagItem(userData[0], value, userData[1]); + } } } @@ -1085,13 +1104,16 @@ public void TryRetreiveBagItem(int bagSlotIndex, int inventorySlotIndex) ); } - private void RetreiveBagItemInputBoxOkay(object sender, EventArgs e) + private void RetreiveBagItemInputBoxOkay(object? sender, EventArgs e) { - var value = (int)Math.Round(((InputBox)sender).Value); - if (value > 0) + if (sender is InputBox inputBox) { - int[] userData = (int[])((InputBox)sender).UserData; - PacketSender.SendRetrieveBagItem(userData[0], value, userData[1]); + var value = (int)Math.Round(inputBox.Value); + if (value > 0) + { + int[] userData = (int[])inputBox.UserData; + PacketSender.SendRetrieveBagItem(userData[0], value, userData[1]); + } } } @@ -1125,12 +1147,15 @@ public void TryTradeItem(int index) ); } - private void TradeItemInputBoxOkay(object sender, EventArgs e) + private void TradeItemInputBoxOkay(object? sender, EventArgs e) { - var value = (int)Math.Round(((InputBox)sender).Value); - if (value > 0) + if (sender is InputBox inputBox) { - PacketSender.SendOfferTradeItem((int)((InputBox)sender).UserData, value); + var value = (int)Math.Round(inputBox.Value); + if (value > 0) + { + PacketSender.SendOfferTradeItem((int)inputBox.UserData, value); + } } } @@ -1163,12 +1188,15 @@ public void TryRevokeItem(int index) ); } - private void RevokeItemInputBoxOkay(object sender, EventArgs e) + private void RevokeItemInputBoxOkay(object? sender, EventArgs? e) { - var value = (int)Math.Round(((InputBox)sender).Value); - if (value > 0) + if (sender is InputBox inputBox) { - PacketSender.SendRevokeTradeItem((int)((InputBox)sender).UserData, value); + var value = (int)Math.Round(inputBox.Value); + if (value > 0) + { + PacketSender.SendRevokeTradeItem((int)inputBox.UserData, value); + } } } @@ -1176,9 +1204,7 @@ private void RevokeItemInputBoxOkay(object sender, EventArgs e) public void SwapSpells(int fromSpellIndex, int toSpellIndex) { PacketSender.SendSwapSpells(fromSpellIndex, toSpellIndex); - var tmpInstance = Spells[toSpellIndex]; - Spells[toSpellIndex] = Spells[fromSpellIndex]; - Spells[fromSpellIndex] = tmpInstance; + (Spells[fromSpellIndex], Spells[toSpellIndex]) = (Spells[toSpellIndex], Spells[fromSpellIndex]); } public void TryForgetSpell(int spellIndex) @@ -1198,9 +1224,12 @@ public void TryForgetSpell(int spellIndex) } } - private void ForgetSpellInputBoxOkay(object sender, EventArgs e) + private void ForgetSpellInputBoxOkay(object? sender, EventArgs? e) { - PacketSender.SendForgetSpell((int)((InputBox)sender).UserData); + if (sender is InputBox inputBox) + { + PacketSender.SendForgetSpell((int)inputBox.UserData); + } } public void TryUseSpell(int index) @@ -1210,7 +1239,7 @@ public void TryUseSpell(int index) { var spellBase = SpellBase.Get(Spells[index].Id); - if (spellBase.CastDuration > 0 && (Options.Instance.CombatOpts.MovementCancelsCast && Globals.Me.IsMoving)) + if (spellBase.CastDuration > 0 && (Options.Instance.CombatOpts.MovementCancelsCast && Globals.Me?.IsMoving == true)) { return; } @@ -1226,7 +1255,7 @@ public long GetSpellCooldown(Guid id) return cd; } - if ((SpellBase.TryGet(id, out var spellBase) && !spellBase.IgnoreGlobalCooldown) && Globals.Me.GlobalCooldown > Timing.Global.Milliseconds) + if ((SpellBase.TryGet(id, out var spellBase) && !spellBase.IgnoreGlobalCooldown) && Globals.Me?.GlobalCooldown > Timing.Global.Milliseconds) { return Globals.Me.GlobalCooldown; } @@ -1415,7 +1444,10 @@ private void HandleInput() } } - Globals.Me.MoveDir = inputDirection; + if (Globals.Me != default) + { + Globals.Me.MoveDir = inputDirection; + } TurnAround(); @@ -1480,12 +1512,13 @@ public void AutoTarget() // Do we need to account for players? // Depends on what type of map we're currently on. - if (Globals.Me.MapInstance == null) + if (Globals.Me?.MapInstance == null) { return; } + var currentMap = Globals.Me.MapInstance as MapInstance; - var canTargetPlayers = currentMap.ZoneType != MapZone.Safe; + var canTargetPlayers = currentMap?.ZoneType != MapZone.Safe; // Build a list of Entities to select from with positions if our list is either old, we've moved or changed maps somehow. if ( @@ -1525,18 +1558,18 @@ public void AutoTarget() if (canTargetPlayers && en.Value.Type == EntityType.Player) { var player = en.Value as Player; - if (IsInMyParty(player)) + if (player != default && IsInMyParty(player)) { continue; } } - if (en.Value.Type == EntityType.GlobalEntity || en.Value.Type == EntityType.Player) + if (en.Value.Type is EntityType.GlobalEntity or EntityType.Player) { // Already in our list? - if (mlastTargetList.ContainsKey(en.Value)) + if (mlastTargetList.TryGetValue(en.Value, out var value)) { - mlastTargetList[en.Value].DistanceTo = GetDistanceTo(en.Value); + value.DistanceTo = GetDistanceTo(en.Value); } else { @@ -1550,7 +1583,7 @@ public void AutoTarget() var toRemove = mlastTargetList.Where(en => !Globals.Entities.ContainsValue(en.Key)).ToArray(); foreach (var en in toRemove) { - mlastTargetList.Remove(en.Key); + _ = mlastTargetList.Remove(en.Key); } // Skip scanning for another second or so.. And set up other values. @@ -1567,7 +1600,7 @@ public void AutoTarget() int currentDistance = 9999; long currentTime = Timing.Global.Milliseconds; - Entity currentEntity = mLastEntitySelected; + Entity? currentEntity = mLastEntitySelected; foreach (var entity in validEntities) { if (currentEntity == entity.Key) @@ -1623,6 +1656,7 @@ public void AutoTarget() { lastTarget.LastTimeSelected = Timing.Global.Milliseconds; } + mLastEntitySelected = targetedEntity; if (TargetIndex != targetedEntity.Id) @@ -1633,7 +1667,7 @@ public void AutoTarget() } } - private void SetTargetBox(Entity en) + private void SetTargetBox(Entity? en) { if (en == null) { @@ -1736,7 +1770,7 @@ public bool TryBlock() public bool TryAttack() { - if (IsAttacking || IsBlocking || (IsMoving && !Options.Instance.PlayerOpts.AllowCombatMovement)) + if (IsAttacking || IsBlocking || (IsMoving && !Options.Instance.PlayerOpts.AllowCombatMovement) || Globals.Me == default) { return false; } @@ -1820,7 +1854,7 @@ public bool TryAttack() } } - foreach (MapInstance eventMap in Maps.MapInstance.Lookup.Values) + foreach (MapInstance eventMap in Maps.MapInstance.Lookup.Values.Cast()) { foreach (var en in eventMap.LocalEntities) { @@ -1852,9 +1886,13 @@ public bool TryAttack() public bool TryGetRealLocation(ref int x, ref int y, ref Guid mapId) { + if (Globals.MapGrid == default) + { + return false; + } + var tmpX = x; var tmpY = y; - var tmpI = -1; if (Maps.MapInstance.Get(mapId) != null) { var gridX = Maps.MapInstance.Get(mapId).GridX; @@ -1916,11 +1954,10 @@ public bool TryTarget() var y = (int)mouseInWorld.Y; var targetRect = new FloatRect(x - 8, y - 8, 16, 16); //Adjust to allow more/less error - IEntity bestMatch = null; + IEntity? bestMatch = null; var bestAreaMatch = 0f; - - foreach (MapInstance map in Maps.MapInstance.Lookup.Values) + foreach (MapInstance map in Maps.MapInstance.Lookup.Values.Cast()) { if (x >= map.GetX() && x <= map.GetX() + Options.MapWidth * Options.TileWidth) { @@ -1939,7 +1976,11 @@ public bool TryTarget() { foreach (var en in Globals.Entities) { - if (en.Value == null || en.Value.MapId != mapId || en.Value is Projectile || en.Value is Resource || (en.Value.IsStealthed && !Globals.Me.IsInMyParty(en.Value.Id))) + if (en.Value == null || + en.Value.MapId != mapId || + (en.Value is Projectile or Resource) || + (en.Value.IsStealthed && Globals.Me?.IsInMyParty(en.Value.Id) == false) + ) { continue; } @@ -1952,7 +1993,7 @@ public bool TryTarget() } } - foreach (MapInstance eventMap in Maps.MapInstance.Lookup.Values) + foreach (MapInstance eventMap in Maps.MapInstance.Lookup.Values.Cast()) { foreach (var en in eventMap.LocalEntities) { @@ -1974,7 +2015,6 @@ public bool TryTarget() { var targetType = bestMatch is Event ? 1 : 0; - SetTargetBox(bestMatch as Entity); if (bestMatch is Player) @@ -2069,12 +2109,11 @@ public bool ClearTarget() /// Attempts to pick up an item at the specified location. /// /// The Id of the map we are trying to loot from. - /// The X location on the current map. - /// The Y location on the current map. + /// The index of the tile we are trying to loot from. /// The Unique Id of the specific item we want to pick up, leave to not specificy an item and pick up the first thing we can find. /// Defines whether we only want to pick up the first item we can find when true, or all items when false. - /// - public bool TryPickupItem(Guid mapId, int tileIndex, Guid uniqueId = new(), bool firstOnly = false) + /// Whether the action was successful or not + public static bool TryPickupItem(Guid mapId, int tileIndex, Guid uniqueId = new(), bool firstOnly = false) { var map = Maps.MapInstance.Get(mapId); if (map == null || tileIndex < 0 || tileIndex >= Options.MapWidth * Options.MapHeight) @@ -2085,12 +2124,12 @@ public bool ClearTarget() // Are we trying to pick up anything in particular, or everything? if (uniqueId != Guid.Empty || firstOnly) { - if (!map.MapItems.ContainsKey(tileIndex) || map.MapItems[tileIndex].Count < 1) + if (!map.MapItems.TryGetValue(tileIndex, out var value) || value.Count < 1) { return false; } - foreach (var item in map.MapItems[tileIndex]) + foreach (var item in value) { // Check if we are trying to pick up a specific item, and if this is the one. if (uniqueId != Guid.Empty && item.Id != uniqueId) @@ -2099,7 +2138,6 @@ public bool ClearTarget() } PacketSender.SendPickupItem(mapId, tileIndex, item.Id); - return true; } } @@ -2107,7 +2145,6 @@ public bool ClearTarget() { // Let the server worry about what we can and can not pick up. PacketSender.SendPickupItem(mapId, tileIndex, uniqueId); - return true; } @@ -2122,7 +2159,7 @@ public long GetNextLevelExperience() public override int CalculateAttackTime() { - ItemBase weapon = null; + ItemBase? weapon = null; var attackTime = base.CalculateAttackTime(); var cls = ClassBase.Get(Class); @@ -2181,6 +2218,11 @@ public virtual int CalculateAttackTime(int speed) //Movement Processing private void ProcessDirectionalInput() { + if (Globals.Me == default || Globals.MapGrid == default) + { + return; + } + //Check if player is crafting if (Globals.InCraft) { @@ -2190,9 +2232,7 @@ private void ProcessDirectionalInput() //check if player is stunned or snared, if so don't let them move. for (var n = 0; n < Status.Count; n++) { - if (Status[n].Type == SpellEffect.Stun || - Status[n].Type == SpellEffect.Snare || - Status[n].Type == SpellEffect.Sleep) + if (Status[n].Type is SpellEffect.Stun or SpellEffect.Snare or SpellEffect.Sleep) { return; } @@ -2210,7 +2250,7 @@ private void ProcessDirectionalInput() } Point position = new(X, Y); - IEntity blockedBy = null; + IEntity? blockedBy = null; if (MoveDir <= Direction.None || Globals.EventDialogs.Count != 0) { @@ -2363,12 +2403,12 @@ private void ProcessDirectionalInput() if (blockedBy != null && mLastBumpedEvent != blockedBy && blockedBy is Event) { PacketSender.SendBumpEvent(blockedBy.MapId, blockedBy.Id); - mLastBumpedEvent = blockedBy as Entity; + mLastBumpedEvent = (Entity)blockedBy; } } } - public void FetchNewMaps() + public static void FetchNewMaps() { if (Globals.MapGridWidth == 0 || Globals.MapGridHeight == 0) { @@ -2393,7 +2433,7 @@ public override void DrawEquipment(string filename, Color renderColor) } //Override of the original function, used for rendering the color of a player based on rank - public override void DrawName(Color textColor, Color borderColor, Color backgroundColor) + public override void DrawName(Color? textColor, Color? borderColor, Color? backgroundColor) { if (textColor == null) { @@ -2430,7 +2470,7 @@ public override void DrawName(Color textColor, Color borderColor, Color backgrou } } - if (Globals.Me.Id != Id) + if (Globals.Me != default && Globals.Me.Id != Id) { // Party member names if (Globals.Me.IsInMyParty(this) && CustomColors.Names.Players.TryGetValue(nameof(Party), out var partyColors)) @@ -2439,6 +2479,7 @@ public override void DrawName(Color textColor, Color borderColor, Color backgrou borderColor = partyColors.Outline; backgroundColor = partyColors.Background; } + // Guildies else if (Globals.Me.IsInGuild && Guild == Globals.Me.Guild && CustomColors.Names.Players.TryGetValue(nameof(Guild), out var guildColors)) { @@ -2448,7 +2489,7 @@ public override void DrawName(Color textColor, Color borderColor, Color backgrou } // Enemies in PvP - if (!Globals.Me.IsAllyOf(this) && Globals.Me.MapInstance.ZoneType != MapZone.Safe && CustomColors.Names.Players.TryGetValue("Hostile", out var hostileColors)) + if (Globals.Me.IsAllyOf(this) && Globals.Me.MapInstance?.ZoneType != MapZone.Safe && CustomColors.Names.Players.TryGetValue("Hostile", out var hostileColors)) { textColor = hostileColors.Name; borderColor = hostileColors.Outline; @@ -2466,10 +2507,10 @@ public override bool IsAllyOf(Player en) return true; } - return IsInMyParty(en) || IsInMyGuild(en) || en.MapInstance.ZoneType == MapZone.Safe; + return IsInMyParty(en) || IsInMyGuild(en) || en.MapInstance?.ZoneType == MapZone.Safe; } - private void DrawNameAndLabels(Color textColor, Color borderColor, Color backgroundColor) + private void DrawNameAndLabels(Color textColor, Color? borderColor, Color? backgroundColor) { base.DrawName(textColor, borderColor, backgroundColor); DrawLabels(HeaderLabel.Text, 0, HeaderLabel.Color, textColor, borderColor, backgroundColor); @@ -2479,6 +2520,11 @@ private void DrawNameAndLabels(Color textColor, Color borderColor, Color backgro public virtual void DrawGuildName(Color textColor, Color? borderColor = default, Color? backgroundColor = default) { + if (Graphics.Renderer == default || Globals.Me == default) + { + return; + } + var guildLabel = Guild?.Trim(); if (!ShouldDrawName || string.IsNullOrWhiteSpace(guildLabel) || !Options.Instance.Guild.ShowGuildNameTagsOverMembers) { @@ -2542,6 +2588,11 @@ protected override bool ShouldDrawHpBar var me = Globals.Me; + if (me == default) + { + return false; + } + if (Globals.Database.MyOverheadHpBar && Id == me.Id) { return true; @@ -2580,12 +2631,12 @@ public void DrawTargets() continue; } - if (en.Value.IsStealthed && (!(en.Value is Player player) || !Globals.Me.IsInMyParty(player))) + if (en.Value.IsStealthed && (en.Value is not Player player || Globals.Me?.IsInMyParty(player) == false)) { continue; } - if (en.Value is Projectile || en.Value is Resource) + if (en.Value is Projectile or Resource) { continue; } @@ -2599,7 +2650,7 @@ public void DrawTargets() AutoTurnToTarget(en.Value); } - foreach (MapInstance eventMap in Maps.MapInstance.Lookup.Values) + foreach (MapInstance eventMap in Maps.MapInstance.Lookup.Values.Cast()) { foreach (var en in eventMap.LocalEntities) { @@ -2623,7 +2674,7 @@ public void DrawTargets() continue; } - if (en.Value.IsStealthed && (!(en.Value is Player player) || !Globals.Me.IsInMyParty(player))) + if (en.Value.IsStealthed && (en.Value is not Player player || Globals.Me?.IsInMyParty(player) == false)) { continue; } @@ -2641,7 +2692,7 @@ public void DrawTargets() if (!Interface.Interface.MouseHitGui()) { var mouseInWorld = Graphics.ConvertToWorldPoint(Globals.InputManager.GetMousePosition()); - foreach (MapInstance map in Maps.MapInstance.Lookup.Values) + foreach (MapInstance map in Maps.MapInstance.Lookup.Values.Cast()) { if (mouseInWorld.X >= map.GetX() && mouseInWorld.X <= map.GetX() + Options.MapWidth * Options.TileWidth) { @@ -2660,10 +2711,10 @@ public void DrawTargets() if (en.Value.MapId == mapId && !en.Value.HideName && (!en.Value.IsStealthed || - en.Value is Player player && Globals.Me.IsInMyParty(player)) && + en.Value is Player player && Globals.Me?.IsInMyParty(player) == true) && en.Value.WorldPos.Contains(mouseInWorld.X, mouseInWorld.Y)) { - if (!(en.Value is Projectile || en.Value is Resource)) + if (en.Value is not (Projectile or Resource)) { if (TargetType != 0 || TargetIndex != en.Value.Id) { @@ -2673,7 +2724,7 @@ public void DrawTargets() } } - foreach (MapInstance eventMap in Maps.MapInstance.Lookup.Values) + foreach (MapInstance eventMap in Maps.MapInstance.Lookup.Values.Cast()) { foreach (var en in eventMap.LocalEntities) { @@ -2683,10 +2734,10 @@ public void DrawTargets() } if (en.Value.MapId == mapId && - !(en.Value as Event).DisablePreview && + !((Event)en.Value).DisablePreview && !en.Value.IsHidden && (!en.Value.IsStealthed || - en.Value is Player player && Globals.Me.IsInMyParty(player)) && + en.Value is Player player && Globals.Me?.IsInMyParty(player) == true) && en.Value.WorldPos.Contains(mouseInWorld.X, mouseInWorld.Y)) { if (TargetType != 1 || TargetIndex != en.Value.Id) @@ -2713,6 +2764,11 @@ private class TargetInfo private void TurnAround() { + if (Globals.Me == default) + { + return; + } + // If players hold the 'TurnAround' Control Key and tap to any direction, they will turn on their own axis. for (var direction = 0; direction < Options.Instance.MapOpts.MovementDirections; direction++) { @@ -2748,20 +2804,16 @@ private static bool IsTargetAtOppositeDirection(Direction currentDir, Direction switch (currentDir) { case Direction.Up: - return targetDir == Direction.Down || targetDir == Direction.DownLeft || - targetDir == Direction.DownRight; + return targetDir is Direction.Down or Direction.DownLeft or Direction.DownRight; case Direction.Down: - return targetDir == Direction.Up || targetDir == Direction.UpLeft || - targetDir == Direction.UpRight; + return targetDir is Direction.Up or Direction.UpLeft or Direction.UpRight; case Direction.Left: - return targetDir == Direction.Right || targetDir == Direction.UpRight || - targetDir == Direction.DownRight; + return targetDir is Direction.Right or Direction.UpRight or Direction.DownRight; case Direction.Right: - return targetDir == Direction.Left || targetDir == Direction.UpLeft || - targetDir == Direction.DownLeft; + return targetDir is Direction.Left or Direction.UpLeft or Direction.DownLeft; default: if (!Options.Instance.MapOpts.EnableDiagonalMovement) @@ -2774,26 +2826,13 @@ private static bool IsTargetAtOppositeDirection(Direction currentDir, Direction } // If diagonal movement is enabled, check opposite directions on 8 directions. - switch (currentDir) - { - case Direction.UpLeft: - return targetDir == Direction.DownRight || targetDir == Direction.Right || - targetDir == Direction.Down; - - case Direction.UpRight: - return targetDir == Direction.DownLeft || targetDir == Direction.Left || - targetDir == Direction.Down; - - case Direction.DownLeft: - return targetDir == Direction.UpRight || targetDir == Direction.Right || - targetDir == Direction.Up; - - case Direction.DownRight: - return targetDir == Direction.UpLeft || targetDir == Direction.Left || - targetDir == Direction.Up; - - default: - return false; - } + return currentDir switch + { + Direction.UpLeft => targetDir is Direction.DownRight or Direction.Right or Direction.Down, + Direction.UpRight => targetDir is Direction.DownLeft or Direction.Left or Direction.Down, + Direction.DownLeft => targetDir is Direction.UpRight or Direction.Right or Direction.Up, + Direction.DownRight => targetDir is Direction.UpLeft or Direction.Left or Direction.Up, + _ => false, + }; } } diff --git a/Intersect.Client/Entities/Projectiles/Projectile.cs b/Intersect.Client/Entities/Projectiles/Projectile.cs index 0d6441eda..2d4a1d835 100644 --- a/Intersect.Client/Entities/Projectiles/Projectile.cs +++ b/Intersect.Client/Entities/Projectiles/Projectile.cs @@ -9,17 +9,15 @@ namespace Intersect.Client.Entities.Projectiles; - public partial class Projectile : Entity { - private bool _isDisposing; private bool _isLoaded; - private readonly object _lock = new object(); + private readonly object _lock = new(); - private ProjectileBase _myBase; + private ProjectileBase? _myBase; private Guid _owner; @@ -36,7 +34,7 @@ public partial class Projectile : Entity private Guid _projectileId; // Individual Spawns - private ProjectileSpawns[] _spawns; + private ProjectileSpawns?[]? _spawns; private Guid _targetId; @@ -58,7 +56,7 @@ public Projectile(Guid id, ProjectileEntityPacket packet) : base(id, packet, Ent IsMoving = true; } - public override void Load(EntityPacket packet) + public override void Load(EntityPacket? packet) { if (_isLoaded) { @@ -66,6 +64,12 @@ public override void Load(EntityPacket packet) } base.Load(packet); + + if (packet == null) + { + return; + } + var pkt = (ProjectileEntityPacket)packet; _projectileId = pkt.ProjectileId; Dir = (Direction)pkt.ProjectileDirection; @@ -109,7 +113,7 @@ public override void Dispose() // Perform a final update if no projectiles have been spawned. if (_spawnedAmount == 0) { - Update(); + _ = Update(); } if (_spawns != null) @@ -142,6 +146,11 @@ public override bool CanBeAttacked /// The index of the animation data to use for the current spawn wave. private int FindSpawnAnimationData() { + if (_myBase == default) + { + return 0; + } + var start = 0; for (var i = 0; i < _myBase.Animations.Count; i++) { @@ -164,6 +173,11 @@ private int FindSpawnAnimationData() /// private void AddProjectileSpawns() { + if (_myBase == default || _spawns == default) + { + return; + } + var spawn = FindSpawnAnimationData(); var animBase = AnimationBase.Get(_myBase.Animations[spawn].AnimationId); @@ -276,6 +290,11 @@ private static float GetRange(Direction direction, float range, bool isXAxis) /// The displacement from the co-ordinates if placed on a Options.TileHeight grid. private float GetDisplacement(long spawnTime) { + if (_myBase == default) + { + return 0f; + } + var elapsedTime = Timing.Global.Milliseconds - spawnTime; var displacementPercent = elapsedTime / (float)_myBase.Speed; var calculatedDisplacement = displacementPercent * Options.TileHeight * _myBase.Range; @@ -290,7 +309,7 @@ private float GetDisplacement(long spawnTime) /// public override bool Update() { - if (_myBase == null) + if (_myBase == null || _spawns == default) { return false; } @@ -313,9 +332,11 @@ public override bool Update() if (spawn != null && Maps.MapInstance.Get(spawn.SpawnMapId) != null) { - if (_targetId != Guid.Empty && _targetId != _owner && Globals.Entities.ContainsKey(_targetId) && (_myBase.HomingBehavior || _myBase.DirectShotBehavior)) + if (_targetId != Guid.Empty && _targetId != _owner && + Globals.Entities.TryGetValue(_targetId, out var target) && + (_myBase.HomingBehavior || _myBase.DirectShotBehavior) + ) { - var target = Globals.Entities[_targetId]; _lastTargetX = target.X; _lastTargetY = target.Y; _lastTargetMapId = target.MapId; @@ -367,7 +388,11 @@ public override bool Update() /// The calculated offset value. private float GetProjectileOffset(ProjectileSpawns spawn, bool isXAxis) { - if (_lastTargetMapId == Guid.Empty || _lastTargetMapId == spawn.SpawnMapId || !Maps.MapInstance.TryGet(spawn.SpawnMapId, out var map)) + if (_lastTargetMapId == Guid.Empty || + _lastTargetMapId == spawn.SpawnMapId || + !Maps.MapInstance.TryGet(spawn.SpawnMapId, out var map) || + Globals.MapGrid == default + ) { return isXAxis ? _lastTargetX - spawn.SpawnX : _lastTargetY - spawn.SpawnY; } @@ -436,6 +461,11 @@ private float GetProjectileOffset(ProjectileSpawns spawn, bool isXAxis) /// private float GetProjectileLerping(ProjectileSpawns spawn, bool isXAxis) { + if (_myBase == default) + { + return 0f; + } + var (directionX, directionY) = (GetProjectileOffset(spawn, true), GetProjectileOffset(spawn, false)); var distance = MathF.Sqrt(directionX * directionX + directionY * directionY); if (distance == 0) return 0; @@ -472,7 +502,7 @@ private void SetProjectileRotation(ProjectileSpawns spawn) /// public void CheckForCollision() { - if (_spawnCount == 0 && _quantity > _myBase.Quantity) + if (_myBase == default || _spawns == default || _spawnCount == 0 && _quantity > _myBase.Quantity) { Globals.Entities[Id].Dispose(); return; @@ -678,10 +708,20 @@ private static void AdjustPositionOnMapBoundaries(ref float newx, ref float newy /// True if the projectile spawn has collided and should be destroyed; otherwise, false. private bool Collided(int i) { + if (Globals.Me == default || _spawns == default) + { + return true; + } + var killSpawn = false; IEntity? blockedBy = default; var spawn = _spawns[i]; + if (spawn == null) + { + return true; + } + // Check if the tile at the projectile's location is blocked. var tileBlocked = Globals.Me.IsTileBlocked( delta: new Point(spawn.X, spawn.Y), @@ -706,18 +746,21 @@ private bool Collided(int i) killSpawn = true; } } + break; case -2: // Collision with a map block if (!spawn.ProjectileBase.IgnoreMapBlocks) { killSpawn = true; } + break; case -3: // Collision with a Z-dimension block if (!spawn.ProjectileBase.IgnoreZDimension) { killSpawn = true; } + break; case -5: // Collision with an unspecified block type or out of map bounds killSpawn = true; @@ -740,7 +783,7 @@ public override void Draw() public void SpawnDead(int spawnIndex) { - if (spawnIndex < _spawnedAmount && _spawns[spawnIndex] != null) + if (spawnIndex < _spawnedAmount && _spawns?[spawnIndex] != null) { TryRemoveSpawn(spawnIndex); } @@ -748,11 +791,10 @@ public void SpawnDead(int spawnIndex) private void TryRemoveSpawn(int spawnIndex) { - if (spawnIndex < _spawnedAmount && _spawns[spawnIndex] != null) + if (spawnIndex < _spawnedAmount && _spawns?[spawnIndex] != null) { - _spawns[spawnIndex].Dispose(); + _spawns[spawnIndex]!.Dispose(); _spawns[spawnIndex] = null; } } - } diff --git a/Intersect.Client/Entities/Projectiles/ProjectileSpawns.cs b/Intersect.Client/Entities/Projectiles/ProjectileSpawns.cs index 3ef616796..79ab188e8 100644 --- a/Intersect.Client/Entities/Projectiles/ProjectileSpawns.cs +++ b/Intersect.Client/Entities/Projectiles/ProjectileSpawns.cs @@ -1,10 +1,9 @@ -using Intersect.Enums; +using Intersect.Enums; using Intersect.GameObjects; using Intersect.Utilities; namespace Intersect.Client.Entities.Projectiles; - public partial class ProjectileSpawns { @@ -71,5 +70,4 @@ public void Dispose() { Anim.DisposeNextDraw(); } - } diff --git a/Intersect.Client/Entities/Resource.cs b/Intersect.Client/Entities/Resource.cs index 7a9fe3fa6..a60e7b406 100644 --- a/Intersect.Client/Entities/Resource.cs +++ b/Intersect.Client/Entities/Resource.cs @@ -10,13 +10,11 @@ namespace Intersect.Client.Entities; - public partial class Resource : Entity, IResource { - private bool _waitingForTilesets; - public ResourceBase BaseResource { get; set; } + public ResourceBase? BaseResource { get; set; } bool IResource.IsDepleted => IsDead; @@ -65,21 +63,33 @@ public override string Sprite } } - public override void Load(EntityPacket packet) + public override void Load(EntityPacket? packet) { base.Load(packet); - var pkt = (ResourceEntityPacket) packet; + var pkt = packet as ResourceEntityPacket; + + if (pkt == default) + { + return; + } + IsDead = pkt.IsDead; var baseId = pkt.ResourceId; BaseResource = ResourceBase.Get(baseId); + + if (BaseResource == default) + { + return; + } + HideName = true; if (IsDead) { - Sprite = BaseResource?.Exhausted.Graphic; + Sprite = BaseResource.Exhausted.Graphic; } else { - Sprite = BaseResource?.Initial.Graphic; + Sprite = BaseResource.Initial.Graphic; } } @@ -87,11 +97,12 @@ public override void Dispose() { if (RenderList != null) { - RenderList.Remove(this); + _ = RenderList.Remove(this); RenderList = null; } ClearAnimations(null); + GC.SuppressFinalize(this); mDisposed = true; } @@ -124,7 +135,7 @@ public override bool Update() { if (RenderList != null) { - RenderList.Remove(this); + _ = RenderList.Remove(this); } return true; @@ -135,7 +146,7 @@ public override bool Update() { if (RenderList != null) { - RenderList.Remove(this); + _ = RenderList.Remove(this); } } @@ -145,14 +156,12 @@ public override bool Update() /// public override bool CanBeAttacked => !IsDead; - public override HashSet DetermineRenderOrder(HashSet renderList, IMapInstance map) + public override HashSet? DetermineRenderOrder(HashSet? renderList, IMapInstance? map) { - if (IsDead && !BaseResource.Exhausted.RenderBelowEntities) - { - return base.DetermineRenderOrder(renderList, map); - } - - if (!IsDead && !BaseResource.Initial.RenderBelowEntities) + if (BaseResource == default || + (IsDead && !BaseResource.Exhausted.RenderBelowEntities) || + (!IsDead && !BaseResource.Initial.RenderBelowEntities) + ) { return base.DetermineRenderOrder(renderList, map); } @@ -160,10 +169,10 @@ public override HashSet DetermineRenderOrder(HashSet renderList, //Otherwise we are alive or dead and we want to render below players/npcs if (renderList != null) { - renderList.Remove(this); + _ = renderList.Remove(this); } - if (map == null || Globals.Me == null || Globals.Me.MapInstance == null) + if (map == null || Globals.Me == null || Globals.Me.MapInstance == null || Globals.MapGrid == default) { return null; } @@ -203,7 +212,7 @@ public override HashSet DetermineRenderOrder(HashSet renderList, renderSet = Graphics.RenderingEntities[priority, Options.MapHeight * 2 + Y]; } - renderSet.Add(this); + _ = renderSet.Add(this); renderList = renderSet; return renderList; @@ -219,7 +228,7 @@ public override HashSet DetermineRenderOrder(HashSet renderList, private void CalculateRenderBounds() { var map = MapInstance; - if (map == null) + if (map == null || BaseResource == default) { return; } @@ -232,7 +241,6 @@ private void CalculateRenderBounds() if (_waitingForTilesets && GameContentManager.Current.TilesetsLoaded) { _waitingForTilesets = false; - Sprite = Sprite; } if (Texture != null) @@ -290,5 +298,4 @@ public override void Draw() Graphics.DrawGameTexture(Texture, mSrcRectangle, mDestRectangle, Intersect.Color.White); } } - } diff --git a/Intersect.Client/Entities/Status.cs b/Intersect.Client/Entities/Status.cs index 2a6597d82..705d7ff26 100644 --- a/Intersect.Client/Entities/Status.cs +++ b/Intersect.Client/Entities/Status.cs @@ -1,10 +1,9 @@ -using Intersect.Client.Framework.Entities; +using Intersect.Client.Framework.Entities; using Intersect.Enums; using Intersect.Utilities; namespace Intersect.Client.Entities; - public partial class Status : IStatus { diff --git a/Intersect.Client/General/Globals.cs b/Intersect.Client/General/Globals.cs index bd69fea61..64550dac1 100644 --- a/Intersect.Client/General/Globals.cs +++ b/Intersect.Client/General/Globals.cs @@ -1,4 +1,4 @@ -using Intersect.Client.Entities; +using Intersect.Client.Entities; using Intersect.Client.Entities.Events; using Intersect.Client.Framework.Database; using Intersect.Client.Framework.Entities; @@ -62,7 +62,7 @@ public static partial class Globals //Game Shop //Only need 1 shop, and that is the one we see at a given moment in time. - public static ShopBase GameShop; + public static ShopBase? GameShop; //Crucial game variables @@ -181,14 +181,14 @@ public static GameStates GameState public static bool LoggedIn = false; //Map/Chunk Array - public static Guid[,] MapGrid; + public static Guid[,]? MapGrid; public static long MapGridHeight; public static long MapGridWidth; //Local player information - public static Player Me; + public static Player? Me; public static bool MoveRouteActive = false; @@ -199,7 +199,7 @@ public static GameStates GameState new Dictionary>(); //Event Show Pictures - public static ShowPicturePacket Picture; + public static ShowPicturePacket? Picture; public static List QuestOffers = new List(); diff --git a/Intersect.Client/Interface/Game/EntityPanel/EntityBox.cs b/Intersect.Client/Interface/Game/EntityPanel/EntityBox.cs index e626f5dfe..3369a9631 100644 --- a/Intersect.Client/Interface/Game/EntityPanel/EntityBox.cs +++ b/Intersect.Client/Interface/Game/EntityPanel/EntityBox.cs @@ -112,7 +112,7 @@ public partial class EntityBox private MenuItem _guildMenuItem; //Init - public EntityBox(Canvas gameCanvas, EntityType entityType, Entity myEntity, bool isPlayerBox = false) + public EntityBox(Canvas gameCanvas, EntityType entityType, Entity? myEntity, bool isPlayerBox = false) { MyEntity = myEntity; EntityType = entityType; @@ -238,7 +238,7 @@ public EntityBox(Canvas gameCanvas, EntityType entityType, Entity myEntity, bool mLastUpdateTime = Timing.Global.MillisecondsUtc; } - public void SetEntity(Entity entity) + public void SetEntity(Entity? entity) { MyEntity = entity; if (MyEntity != null) diff --git a/Intersect.Client/Interface/Game/EventWindow.cs b/Intersect.Client/Interface/Game/EventWindow.cs index ab2c9de15..e329bde0d 100644 --- a/Intersect.Client/Interface/Game/EventWindow.cs +++ b/Intersect.Client/Interface/Game/EventWindow.cs @@ -367,7 +367,7 @@ void EventResponse2_Clicked(Base sender, ClickedEventArgs arguments) base.Hide(); } - public void EventResponse1_Clicked(Base sender, ClickedEventArgs arguments) + public void EventResponse1_Clicked(Base? sender, ClickedEventArgs? arguments) { var ed = Globals.EventDialogs[0]; if (ed.ResponseSent != 0) diff --git a/Intersect.Client/Interface/Game/Friends/FriendsWindow.cs b/Intersect.Client/Interface/Game/Friends/FriendsWindow.cs index 5a18a659c..27abfc514 100644 --- a/Intersect.Client/Interface/Game/Friends/FriendsWindow.cs +++ b/Intersect.Client/Interface/Game/Friends/FriendsWindow.cs @@ -1,4 +1,4 @@ -using Intersect.Client.Core; +using Intersect.Client.Core; using Intersect.Client.Framework.File_Management; using Intersect.Client.Framework.Gwen.Control; using Intersect.Client.Framework.Gwen.Control.EventArguments; @@ -88,7 +88,7 @@ public void UpdateList() var count = 0; foreach (var friend in Globals.Me.Friends) { - var control = new FriendsRow(mFriendContainer, friend.Name, friend.Map, friend.Online); + var control = new FriendsRow(mFriendContainer, friend.Name, friend?.Map ?? string.Empty, friend.Online); control.SetPosition(mFriendListAnchor.Bounds.X, mFriendListAnchor.Bounds.Y + (count * control.Bounds.Height)); mRows.Add(control); diff --git a/Intersect.Client/Interface/Game/InputBox.cs b/Intersect.Client/Interface/Game/InputBox.cs index 49144597d..070491e87 100644 --- a/Intersect.Client/Interface/Game/InputBox.cs +++ b/Intersect.Client/Interface/Game/InputBox.cs @@ -15,12 +15,12 @@ public static void Open( string prompt, bool modal, InputType inputType, - EventHandler onSuccess, - EventHandler onCancel, + EventHandler? onSuccess, + EventHandler? onCancel, object userData, int quantity = 0, int maxQuantity = int.MaxValue, - Base parent = null, + Base? parent = null, GameContentManager.UI stage = GameContentManager.UI.InGame ) => new InputBox( title: title, @@ -329,7 +329,7 @@ void cancelBtn_Clicked(Base sender, ClickedEventArgs arguments) Dispose(); } - public void okayBtn_Clicked(Base sender, ClickedEventArgs arguments) + public void okayBtn_Clicked(Base? sender, ClickedEventArgs? arguments) { SubmitInput(); } diff --git a/Intersect.Client/Interface/Game/MapItem/MapItemIcon.cs b/Intersect.Client/Interface/Game/MapItem/MapItemIcon.cs index db405637b..3c78a7dfc 100644 --- a/Intersect.Client/Interface/Game/MapItem/MapItemIcon.cs +++ b/Intersect.Client/Interface/Game/MapItem/MapItemIcon.cs @@ -1,3 +1,4 @@ +using Intersect.Client.Entities; using Intersect.Client.Framework.GenericClasses; using Intersect.Client.Framework.Gwen.Control; using Intersect.Client.Framework.Gwen.Control.EventArguments; @@ -48,7 +49,7 @@ void pnl_Clicked(Base sender, ClickedEventArgs arguments) return; } - Globals.Me.TryPickupItem(MapId, TileIndex, MyItem.Id); + _ = Player.TryPickupItem(MapId, TileIndex, MyItem.Id); } void pnl_HoverLeave(Base sender, EventArgs arguments) diff --git a/Intersect.Client/Interface/Game/MapItem/MapItemWindow.cs b/Intersect.Client/Interface/Game/MapItem/MapItemWindow.cs index dde2a111a..dcd58178d 100644 --- a/Intersect.Client/Interface/Game/MapItem/MapItemWindow.cs +++ b/Intersect.Client/Interface/Game/MapItem/MapItemWindow.cs @@ -1,4 +1,5 @@ -using Intersect.Client.Core; +using Intersect.Client.Core; +using Intersect.Client.Entities; using Intersect.Client.Framework.File_Management; using Intersect.Client.Framework.Gwen.Control; using Intersect.Client.Framework.Gwen.Control.EventArguments; @@ -195,7 +196,13 @@ private void MBtnLootAll_Clicked(Base sender, ClickedEventArgs arguments) // Try and pick up everything on our location. var currentMap = Globals.Me.MapInstance as MapInstance; - Globals.Me.TryPickupItem(currentMap.Id, Globals.Me.Y * Options.MapWidth + Globals.Me.X); + + if (currentMap == default) + { + return; + } + + _ = Player.TryPickupItem(currentMap.Id, Globals.Me.Y * Options.MapWidth + Globals.Me.X); } diff --git a/Intersect.Client/MonoGame/Graphics/MonoRenderer.cs b/Intersect.Client/MonoGame/Graphics/MonoRenderer.cs index 47f38c58b..1e228ca42 100644 --- a/Intersect.Client/MonoGame/Graphics/MonoRenderer.cs +++ b/Intersect.Client/MonoGame/Graphics/MonoRenderer.cs @@ -430,14 +430,14 @@ public override GameRenderTexture CreateRenderTexture(int width, int height) public override void DrawString( string text, - GameFont gameFont, + GameFont? gameFont, float x, float y, float fontScale, - Color fontColor, + Color? fontColor, bool worldPos = true, - GameRenderTexture renderTexture = null, - Color borderColor = null + GameRenderTexture? renderTexture = null, + Color? borderColor = null ) { var font = (SpriteFont)gameFont?.GetFont(); @@ -577,9 +577,9 @@ public override void DrawTexture( float tw, float th, Color renderColor, - GameRenderTexture renderTarget = null, + GameRenderTexture? renderTarget = null, GameBlendModes blendMode = GameBlendModes.None, - GameShader shader = null, + GameShader? shader = null, float rotationDegrees = 0, bool isUi = false, bool drawImmediate = false @@ -920,7 +920,7 @@ public override GameTexture LoadTexture(string filename, string realFilename) public override GameTexture LoadTexture(string assetName, Func createStream) => new MonoTexture(mGraphicsDevice, assetName, createStream); - public override Pointf MeasureText(string text, GameFont gameFont, float fontScale) + public override Pointf MeasureText(string text, GameFont? gameFont, float fontScale) { var font = (SpriteFont)gameFont?.GetFont(); if (font == null) diff --git a/Intersect.Client/Networking/PacketHandler.cs b/Intersect.Client/Networking/PacketHandler.cs index e53ad602a..d548ef619 100644 --- a/Intersect.Client/Networking/PacketHandler.cs +++ b/Intersect.Client/Networking/PacketHandler.cs @@ -299,7 +299,7 @@ private void HandleMap(IPacketSender packetSender, MapPacket packet, bool skipSa public void HandlePacket(IPacketSender packetSender, MapPacket packet) { HandleMap(packetSender, packet); - Globals.Me.FetchNewMaps(); + Player.FetchNewMaps(); } //PlayerEntityPacket @@ -508,7 +508,7 @@ public void HandlePacket(IPacketSender packetSender, EntityPositionPacket packet { Globals.Me.MapId = mapId; Globals.NeedsMaps = true; - Globals.Me.FetchNewMaps(); + Player.FetchNewMaps(); } else { @@ -1729,7 +1729,7 @@ public void HandlePacket(IPacketSender packetSender, EntityDashPacket packet) Globals.Entities[packet.EntityId] .DashQueue.Enqueue( new Dash( - Globals.Entities[packet.EntityId] as Entity, packet.EndMapId, packet.EndX, packet.EndY, + packet.EndMapId, packet.EndX, packet.EndY, packet.DashTime, packet.Direction ) ); @@ -1768,7 +1768,7 @@ public void HandlePacket(IPacketSender packetSender, MapGridPacket packet) if (Globals.Me != null) { - Globals.Me.FetchNewMaps(); + Player.FetchNewMaps(); } Graphics.GridSwitched = true; @@ -2107,7 +2107,7 @@ public void HandlePacket(IPacketSender packetSender, TargetOverridePacket packet { if (Globals.Entities.ContainsKey(packet.TargetId)) { - Globals.Me.TryTarget(Globals.Entities[packet.TargetId] as Entity, true); + Globals.Me.TryTarget(Globals.Entities[packet.TargetId], true); } } @@ -2157,7 +2157,7 @@ public void HandlePacket(IPacketSender packetSender, FadePacket packet) switch (packet.FadeType) { case GameObjects.Events.FadeType.None: - Fade.Cancel(packet.WaitForCompletion); + Fade.Cancel(); break; case GameObjects.Events.FadeType.FadeIn: Fade.FadeIn(packet.DurationMs, packet.WaitForCompletion);