From ef5467debb056224f4bdeb52886d30c5f400e2fe Mon Sep 17 00:00:00 2001 From: MarkenJaden Date: Wed, 29 Nov 2023 03:05:52 +0100 Subject: [PATCH] Updated dependencies Fixed security issues Fixed Mac issues Improved code --- Directory.Packages.props | 22 ++--- .../Client/BlazorGameStorage.cs | 6 +- LandOfSignals-Signalbox/Client/BlazorTimer.cs | 6 +- LandOfSignals-Signalbox/Client/Game.razor.cs | 7 +- .../LandOfSignals-Signalbox.Client.csproj | 14 +++ LandOfSignals-Signalbox/Client/Program.cs | 3 +- .../LandOfSignals-Signalbox.Server.csproj | 14 +++ .../Server/Pages/Error.cshtml.cs | 4 +- .../LandOfSignals-Signalbox.Shared.csproj | 14 +++ Signalbox.Engine/Entity/FilteredLayout.cs | 6 +- Signalbox.Engine/Entity/Layout.cs | 14 +-- Signalbox.Engine/Entity/MovableLayout.cs | 12 +-- Signalbox.Engine/Map/DefaultGenerator.cs | 8 +- Signalbox.Engine/Map/Map.cs | 3 +- Signalbox.Engine/Signalbox.Engine.csproj | 14 +++ .../StateManager/SignalboxStateManager.cs | 10 +- .../Storage/EntityCollectionSerializer.cs | 9 +- Signalbox.Engine/Storage/ITileSerializer.cs | 8 +- .../Storage/UTF8TileSerializer.cs | 27 +++--- .../Tracks/CrossTrack/CrossTrackFactory.cs | 8 +- .../Tracks/CrossTrack/CrossTrackSerializer.cs | 2 +- Signalbox.Engine/Tracks/SingleTrack/Signal.cs | 18 ++-- .../Tracks/SingleTrack/SignalFactory.cs | 12 +-- .../Tracks/SingleTrack/SignalSerializer.cs | 2 +- .../Tracks/SingleTrack/SingleTrack.cs | 38 ++++---- .../Tracks/SingleTrack/SingleTrackFactory.cs | 12 +-- .../SingleTrack/SingleTrackSerializer.cs | 2 +- .../Tracks/TIntersection/TIntersection.cs | 42 ++++---- .../TIntersection/TIntersectionFactory.cs | 48 ++++----- .../TIntersection/TIntersectionSerializer.cs | 2 +- Signalbox.Engine/Tracks/Track.cs | 16 +-- Signalbox.Engine/Tracks/TrackNeighbors.cs | 32 +++--- Signalbox.Engine/Trains/Train.cs | 46 ++++----- Signalbox.Engine/Trains/TrainManager.cs | 20 ++-- Signalbox.Engine/Trains/TrainMovement.cs | 46 ++++----- Signalbox.Engine/Trains/TrainNames.cs | 2 +- Signalbox.Engine/Trains/TrainPosition.cs | 14 +-- Signalbox.Engine/Trains/TrainSerializer.cs | 2 +- Signalbox.Engine/Utilities/GameThreadTimer.cs | 6 +- Signalbox.Engine/Utilities/OrderAttribute.cs | 2 +- .../Signalbox.Instrumentation.csproj | 14 +++ .../Stats/AveragedStat.cs | 8 +- Signalbox.Instrumentation/Stats/CountStat.cs | 6 +- .../Stats/ElapsedMillisecondsTimedStat.cs | 9 +- .../Stats/InformationStat.cs | 4 +- .../Stats/PerSecondTimedStat.cs | 6 +- .../RenderingExtensions.cs | 27 +++--- Signalbox.Rendering.Skia/SKCanvasWrapper.cs | 8 +- Signalbox.Rendering.Skia/SKContextWrapper.cs | 2 +- Signalbox.Rendering.Skia/SKImageFactory.cs | 2 +- .../Signalbox.Rendering.Skia.csproj | 14 +++ Signalbox.Rendering/Drawing/ImageCache.cs | 10 +- Signalbox.Rendering/Drawing/Records.cs | 3 +- .../LayerRenderer/GridRenderer.cs | 4 +- .../LayerRenderer/TileLayerRenderer.cs | 8 +- .../LayerRenderer/TrackLayoutRenderer.cs | 2 +- .../LayerRenderer/TrainsRenderer.cs | 1 - Signalbox.Rendering/Map/MapRenderer.cs | 14 +-- Signalbox.Rendering/PixelMapper.cs | 97 ++++++++++--------- Signalbox.Rendering/PointerTool.cs | 2 +- .../Signalbox.Rendering.csproj | 14 +++ Signalbox.Rendering/Signalbox/Signalbox.cs | 22 ++--- Signalbox.Rendering/Signalbox/ZoomHandler.cs | 2 +- .../StaticEntityCollectionRenderer.cs | 10 +- Signalbox.Rendering/Tracks/SignalRenderer.cs | 2 +- .../Tracks/SingleTrackRenderer.cs | 2 - Signalbox.Rendering/Tracks/TrackParameters.cs | 2 +- .../Tracks/TrackPathBuilder.cs | 28 +++--- Signalbox.Rendering/Tracks/TrackTool.cs | 2 +- Signalbox.Rendering/Trains/TrainPainter.cs | 12 +-- Signalbox.Rendering/Trains/TrainRenderer.cs | 8 +- Signalbox.Rendering/UI/BuildModeButton.cs | 2 +- Signalbox.Rendering/UI/CreditsScreen.cs | 10 +- Signalbox.Rendering/UI/DiagnosticsPanel.cs | 21 ++-- Signalbox.Rendering/UI/MiniMapScreen.cs | 10 +- Signalbox.Rendering/UI/TrackButton.cs | 2 +- Signalbox.Rendering/UI/TrackSelectionPanel.cs | 22 ++--- Signalbox.Rendering/UI/TrainInfoScreen.cs | 38 +++----- Signalbox.Rendering/UIFramework/ButtonBase.cs | 14 +-- .../UIFramework/ButtonPanelBase.cs | 2 +- .../UIFramework/InteractionManager.cs | 11 ++- .../UIFramework/MultiButton.cs | 4 +- Signalbox.Rendering/UIFramework/PanelBase.cs | 90 ++++++++--------- .../UIFramework/PictureButton.cs | 2 +- Signalbox.Rendering/UIFramework/TextButton.cs | 8 +- .../DISourceGenerator.cs | 78 +++++++-------- .../Signalbox.SourceGenerator.csproj | 14 +++ 87 files changed, 676 insertions(+), 570 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 0d9bf53..1ab6487 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -3,20 +3,20 @@ true - + - - - + + + - - - + + + - - - + + + - + \ No newline at end of file diff --git a/LandOfSignals-Signalbox/Client/BlazorGameStorage.cs b/LandOfSignals-Signalbox/Client/BlazorGameStorage.cs index eb75965..75fea83 100644 --- a/LandOfSignals-Signalbox/Client/BlazorGameStorage.cs +++ b/LandOfSignals-Signalbox/Client/BlazorGameStorage.cs @@ -10,11 +10,11 @@ public class BlazorGameStorage : ISignalboxStorage public IServiceProvider? AspNetCoreServices { get; set; } - private ISyncLocalStorageService? SyncLocalStorageService => (_syncLocalStorageService ??= this.AspNetCoreServices?.GetService()); + private ISyncLocalStorageService? SyncLocalStorageService => (_syncLocalStorageService ??= AspNetCoreServices?.GetService()); public string? Read(string key) { - var data = this.SyncLocalStorageService?.GetItemAsString(key); + var data = SyncLocalStorageService?.GetItemAsString(key); return data; } @@ -24,7 +24,7 @@ public void Write(string key, string value) if (!valueExists || previousValue != value) { _lastSavedValue[key] = value; - this.SyncLocalStorageService?.SetItemAsString(key, value); + SyncLocalStorageService?.SetItemAsString(key, value); } } } diff --git a/LandOfSignals-Signalbox/Client/BlazorTimer.cs b/LandOfSignals-Signalbox/Client/BlazorTimer.cs index d90241b..e8b2f42 100644 --- a/LandOfSignals-Signalbox/Client/BlazorTimer.cs +++ b/LandOfSignals-Signalbox/Client/BlazorTimer.cs @@ -29,11 +29,11 @@ public void Start() private async Task StartTimer() { - var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(this.Interval)); + var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(Interval)); while (await timer.WaitForNextTickAsync(_cts!.Token)) { - long time = _stopwatch.ElapsedMilliseconds; - this.TimeSinceLastTick = time - _lastTick; + var time = _stopwatch.ElapsedMilliseconds; + TimeSinceLastTick = time - _lastTick; _lastTick = time; Elapsed?.Invoke(this, EventArgs.Empty); } diff --git a/LandOfSignals-Signalbox/Client/Game.razor.cs b/LandOfSignals-Signalbox/Client/Game.razor.cs index a7e74a7..687fa15 100644 --- a/LandOfSignals-Signalbox/Client/Game.razor.cs +++ b/LandOfSignals-Signalbox/Client/Game.razor.cs @@ -1,4 +1,5 @@ -using Microsoft.AspNetCore.Components.Web; +using DI; +using Microsoft.AspNetCore.Components.Web; using Signalbox.Instrumentation; using Signalbox.Instrumentation.Stats; using Signalbox.Rendering.Signalbox; @@ -19,8 +20,8 @@ public partial class Game protected override async Task OnInitializedAsync() { - _game = DI.ServiceLocator.GetService(); - _interactionManager = DI.ServiceLocator.GetService(); + _game = ServiceLocator.GetService(); + _interactionManager = ServiceLocator.GetService(); await _game.InitializeAsync(200, 200); } diff --git a/LandOfSignals-Signalbox/Client/LandOfSignals-Signalbox.Client.csproj b/LandOfSignals-Signalbox/Client/LandOfSignals-Signalbox.Client.csproj index 9781db4..d90f9ce 100644 --- a/LandOfSignals-Signalbox/Client/LandOfSignals-Signalbox.Client.csproj +++ b/LandOfSignals-Signalbox/Client/LandOfSignals-Signalbox.Client.csproj @@ -33,4 +33,18 @@ + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + all + runtime; build; native; contentfiles; analyzers + + + diff --git a/LandOfSignals-Signalbox/Client/Program.cs b/LandOfSignals-Signalbox/Client/Program.cs index 2925c55..d4e634f 100644 --- a/LandOfSignals-Signalbox/Client/Program.cs +++ b/LandOfSignals-Signalbox/Client/Program.cs @@ -1,4 +1,5 @@ using Blazored.LocalStorage; +using DI; using LandOfSignals_Signalbox.Client; using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; @@ -13,7 +14,7 @@ var host = builder.Build(); -if (DI.ServiceLocator.GetService() is BlazorGameStorage storage) +if (ServiceLocator.GetService() is BlazorGameStorage storage) { storage.AspNetCoreServices = host.Services; } diff --git a/LandOfSignals-Signalbox/Server/LandOfSignals-Signalbox.Server.csproj b/LandOfSignals-Signalbox/Server/LandOfSignals-Signalbox.Server.csproj index 1a5c8dc..62f7c51 100644 --- a/LandOfSignals-Signalbox/Server/LandOfSignals-Signalbox.Server.csproj +++ b/LandOfSignals-Signalbox/Server/LandOfSignals-Signalbox.Server.csproj @@ -17,5 +17,19 @@ + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + all + runtime; build; native; contentfiles; analyzers + + + diff --git a/LandOfSignals-Signalbox/Server/Pages/Error.cshtml.cs b/LandOfSignals-Signalbox/Server/Pages/Error.cshtml.cs index e7b6ad2..05ff5b0 100644 --- a/LandOfSignals-Signalbox/Server/Pages/Error.cshtml.cs +++ b/LandOfSignals-Signalbox/Server/Pages/Error.cshtml.cs @@ -1,6 +1,6 @@ -using Microsoft.AspNetCore.Mvc; +using System.Diagnostics; +using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; -using System.Diagnostics; namespace LandOfSignals_Signalbox.Server.Pages { diff --git a/LandOfSignals-Signalbox/Shared/LandOfSignals-Signalbox.Shared.csproj b/LandOfSignals-Signalbox/Shared/LandOfSignals-Signalbox.Shared.csproj index a5b78ac..22b8d4c 100644 --- a/LandOfSignals-Signalbox/Shared/LandOfSignals-Signalbox.Shared.csproj +++ b/LandOfSignals-Signalbox/Shared/LandOfSignals-Signalbox.Shared.csproj @@ -9,4 +9,18 @@ + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + all + runtime; build; native; contentfiles; analyzers + + diff --git a/Signalbox.Engine/Entity/FilteredLayout.cs b/Signalbox.Engine/Entity/FilteredLayout.cs index 0e7b834..c57e7d5 100644 --- a/Signalbox.Engine/Entity/FilteredLayout.cs +++ b/Signalbox.Engine/Entity/FilteredLayout.cs @@ -37,7 +37,7 @@ public bool TryGet(int column, int row, [NotNullWhen(true)] out T? entity) public IEnumerator GetEnumerator() { - foreach (T entity in _layout.OfType()) + foreach (var entity in _layout.OfType()) { yield return entity; } @@ -60,7 +60,7 @@ public void Set(int column, int row, T entity) public void Add(int column, int row, IEnumerable> entityFactories, int fromColumn, int fromRow) { - T? entity = CreateNewStaticEntity(column, row, entityFactories, fromColumn, fromRow); + var entity = CreateNewStaticEntity(column, row, entityFactories, fromColumn, fromRow); if (entity is null) { @@ -83,7 +83,7 @@ public void Add(int column, int row, IEnumerable> entity public bool IsAvailable(int column, int row) { - _layout.TryGet(column, row, out IStaticEntity? entity); + _layout.TryGet(column, row, out var entity); return entity == null || entity is T; } diff --git a/Signalbox.Engine/Entity/Layout.cs b/Signalbox.Engine/Entity/Layout.cs index b64b731..9ee750e 100644 --- a/Signalbox.Engine/Entity/Layout.cs +++ b/Signalbox.Engine/Entity/Layout.cs @@ -122,7 +122,7 @@ private static bool IsInvalid(int column, int row) public bool TryGet(int column, int row, [NotNullWhen(true)] out T? entity) where T : class, IStaticEntity { - TryGet(column, row, out IStaticEntity? staticEntity); + TryGet(column, row, out var staticEntity); entity = staticEntity as T; return entity != null; } @@ -130,7 +130,7 @@ public bool TryGet(int column, int row, [NotNullWhen(true)] out T? entity) public bool IsEmptyOrT(int column, int row) where T : class, IStaticEntity { - TryGet(column, row, out IStaticEntity? staticEntity); + TryGet(column, row, out var staticEntity); return staticEntity == null || staticEntity is T; } @@ -138,7 +138,7 @@ private void ResetArrays() { lock (_gate) { - for (int i = 0; i < _entities.Length; i++) + for (var i = 0; i < _entities.Length; i++) { _entities[i] = new IStaticEntity?[_rows]; } @@ -148,9 +148,9 @@ private void ResetArrays() public IEnumerator GetEnumerator() { if (_entities == null) yield break; - for (int i = 0; i < _entities.Length; i++) + for (var i = 0; i < _entities.Length; i++) { - for (int j = 0; j < _rows; j++) + for (var j = 0; j < _rows; j++) { var track = _entities[i][j]; if (track is not null) @@ -181,7 +181,7 @@ public bool Load(ISignalboxStorage storage) ResetArrays(); - foreach (IStaticEntity entity in staticEntites) + foreach (var entity in staticEntites) { StoreEntity(entity.Column, entity.Row, entity); } @@ -206,7 +206,7 @@ void ISignalboxState.Reset() public void Update(long timeSinceLastTick) { - foreach (IUpdatableEntity entity in this.OfType()) + foreach (var entity in this.OfType()) { entity.Update(); } diff --git a/Signalbox.Engine/Entity/MovableLayout.cs b/Signalbox.Engine/Entity/MovableLayout.cs index 04ac9e1..610e65d 100644 --- a/Signalbox.Engine/Entity/MovableLayout.cs +++ b/Signalbox.Engine/Entity/MovableLayout.cs @@ -1,20 +1,20 @@ -using System.Collections.Immutable; +using System.Collections; +using System.Collections.Immutable; using Signalbox.Engine.MainManager; using Signalbox.Engine.StateManager; using Signalbox.Engine.Storage; using Signalbox.Engine.Tracks; using Signalbox.Engine.Trains; -using IMovable = Signalbox.Engine.Trains.IMovable; namespace Signalbox.Engine.Entity; public class MovableLayout : IMovableLayout, ISignalboxState, ISignalboxStep { private ImmutableList _movables = ImmutableList.Empty; - private Dictionary _lastTrackLeases = new(); + private Dictionary _lastTrackLeases = new(); private readonly ILayout _layout; private readonly IEntityCollectionSerializer _gameSerializer; - private readonly Trains.Train _reservedTrain; + private readonly Train _reservedTrain; public int Count => _movables.Count; @@ -30,7 +30,7 @@ public MovableLayout(ILayout layout, IEntityCollectionSerializer gameSerializer) public int IndexOf(IMovable movable) => _movables.IndexOf(movable); - public IEnumerable<(Track, Trains.Train, float)> LastTrackLeases => _lastTrackLeases.Select(kvp => (kvp.Key, kvp.Value.Item1, kvp.Value.Item2)); + public IEnumerable<(Track, Train, float)> LastTrackLeases => _lastTrackLeases.Select(kvp => (kvp.Key, kvp.Value.Item1, kvp.Value.Item2)); public void Add(IMovable movable) => _movables = _movables.Add(movable); @@ -89,6 +89,6 @@ public void Update(long timeSinceLastTick) public IEnumerator GetEnumerator() => _movables.GetEnumerator(); - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + IEnumerator IEnumerable.GetEnumerator() => _movables.GetEnumerator(); } diff --git a/Signalbox.Engine/Map/DefaultGenerator.cs b/Signalbox.Engine/Map/DefaultGenerator.cs index 39c1bf1..782c48d 100644 --- a/Signalbox.Engine/Map/DefaultGenerator.cs +++ b/Signalbox.Engine/Map/DefaultGenerator.cs @@ -1,15 +1,13 @@ -using System.Numerics; - -namespace Signalbox.Engine.Map; +namespace Signalbox.Engine.Map; internal static class DefaultGenerator { public static Dictionary<(int x, int y), string> GenerateDefaultMap(int width, int height) { var points = new Dictionary<(int x, int y), string>(); - for (int i = 0; i < width; i++) + for (var i = 0; i < width; i++) { - for (int j = 0; j < height; j++) + for (var j = 0; j < height; j++) { points.Add((i, j), string.Empty); } diff --git a/Signalbox.Engine/Map/Map.cs b/Signalbox.Engine/Map/Map.cs index 0f2c191..6ac3273 100644 --- a/Signalbox.Engine/Map/Map.cs +++ b/Signalbox.Engine/Map/Map.cs @@ -2,7 +2,6 @@ using System.Collections.Immutable; using Signalbox.Engine.StateManager; using Signalbox.Engine.Storage; -using Signalbox.Engine.Trains; using Signalbox.Engine.Utilities; namespace Signalbox.Engine.Map; @@ -24,7 +23,7 @@ public void Reset() Dictionary<(int x, int y), string>? defaultMap = DefaultGenerator.GenerateDefaultMap(_columns, _rows); ImmutableDictionary<(int, int), Tile>.Builder builder = ImmutableDictionary.CreateBuilder<(int, int), Tile>(); - foreach ((int x, int y) coord in defaultMap.Keys) + foreach (var coord in defaultMap.Keys) { builder.Add(coord, new() { diff --git a/Signalbox.Engine/Signalbox.Engine.csproj b/Signalbox.Engine/Signalbox.Engine.csproj index 61f92d8..8abe390 100644 --- a/Signalbox.Engine/Signalbox.Engine.csproj +++ b/Signalbox.Engine/Signalbox.Engine.csproj @@ -10,4 +10,18 @@ + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + all + runtime; build; native; contentfiles; analyzers + + + diff --git a/Signalbox.Engine/StateManager/SignalboxStateManager.cs b/Signalbox.Engine/StateManager/SignalboxStateManager.cs index 4128026..ba3d50d 100644 --- a/Signalbox.Engine/StateManager/SignalboxStateManager.cs +++ b/Signalbox.Engine/StateManager/SignalboxStateManager.cs @@ -36,7 +36,7 @@ public bool AutosaveEnabled // if they're turning off autosave, we want to at least save that // otherwise if they leave before the next save, it could be back on // on load - _storage.Write("Autosave", this.AutosaveEnabled.ToString()); + _storage.Write("Autosave", AutosaveEnabled.ToString()); } } } @@ -65,7 +65,7 @@ public void Load() break; } } - this.AutosaveEnabled = _storage.Read("Autosave")?.Equals("True") ?? true; + AutosaveEnabled = _storage.Read("Autosave")?.Equals("True") ?? true; } public void Reset() @@ -84,15 +84,15 @@ public void Save() { gameState.Save(_storage); } - _storage.Write("Autosave", this.AutosaveEnabled.ToString()); + _storage.Write("Autosave", AutosaveEnabled.ToString()); } } public void Update(long timeSinceLastTick) { - _autosaveStat.Information = this.AutosaveEnabled ? "On" : "Off"; + _autosaveStat.Information = AutosaveEnabled ? "On" : "Off"; - if (this.AutosaveEnabled && + if (AutosaveEnabled && ++_autosaveCounter > AutosaveInterval) { Save(); diff --git a/Signalbox.Engine/Storage/EntityCollectionSerializer.cs b/Signalbox.Engine/Storage/EntityCollectionSerializer.cs index bf1414c..c7c4ecf 100644 --- a/Signalbox.Engine/Storage/EntityCollectionSerializer.cs +++ b/Signalbox.Engine/Storage/EntityCollectionSerializer.cs @@ -1,4 +1,5 @@ -using System.Text; +using System.Diagnostics.CodeAnalysis; +using System.Text; using Signalbox.Engine.Entity; namespace Signalbox.Engine.Storage; @@ -12,12 +13,12 @@ public EntityCollectionSerializer(IEnumerable serializer) _serializers = serializer; } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "")] + [SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "")] public IEnumerable Deserialize(string lines) { List entities = new(); - foreach (var line in lines.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)) + foreach (var line in lines.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)) { string[] bits = line.Split('|', 3); foreach (var serializer in _serializers) @@ -44,7 +45,7 @@ public string Serialize(IEnumerable entities) { StringBuilder sb = new(); - foreach (IEntity entity in entities) + foreach (var entity in entities) { foreach (var serializer in _serializers) { diff --git a/Signalbox.Engine/Storage/ITileSerializer.cs b/Signalbox.Engine/Storage/ITileSerializer.cs index 31fec4c..eab5faa 100644 --- a/Signalbox.Engine/Storage/ITileSerializer.cs +++ b/Signalbox.Engine/Storage/ITileSerializer.cs @@ -1,7 +1,9 @@ -namespace Signalbox.Engine.Storage; +using Signalbox.Engine.Map; + +namespace Signalbox.Engine.Storage; public interface ITileSerializer { - IEnumerable Deserialize(string[] lines); - string Serialize(IEnumerable contentList); + IEnumerable Deserialize(string[] lines); + string Serialize(IEnumerable contentList); } diff --git a/Signalbox.Engine/Storage/UTF8TileSerializer.cs b/Signalbox.Engine/Storage/UTF8TileSerializer.cs index 69d197a..2d5db1c 100644 --- a/Signalbox.Engine/Storage/UTF8TileSerializer.cs +++ b/Signalbox.Engine/Storage/UTF8TileSerializer.cs @@ -1,26 +1,27 @@ using System.Text; +using Signalbox.Engine.Map; namespace Signalbox.Engine.Storage; public class UTF8TileSerializer : ITileSerializer { - public IEnumerable Deserialize(string[] lines) + public IEnumerable Deserialize(string[] lines) { - var contentList = new List(); + var contentList = new List(); - for (int r = 0; r < lines.Length; r++) + for (var r = 0; r < lines.Length; r++) { - string? line = lines[r]; + var line = lines[r]; string[]? heights = line.Split(','); - for (int c = 0; c < heights.Length; c++) + for (var c = 0; c < heights.Length; c++) { - if (!int.TryParse(heights[c], out int height)) + if (!int.TryParse(heights[c], out var height)) { throw new("Invalid height read from file"); } - contentList.Add(new Map.Tile + contentList.Add(new Tile { Row = r, Column = c, @@ -31,7 +32,7 @@ public class UTF8TileSerializer : ITileSerializer return contentList; } - public string Serialize(IEnumerable contentList) + public string Serialize(IEnumerable contentList) { if (!contentList.Any()) return string.Empty; @@ -39,15 +40,15 @@ public string Serialize(IEnumerable contentList) var sb = new StringBuilder(); - int maxColumn = contentList.Max(t => t.Column); - int maxRow = contentList.Max(t => t.Row); + var maxColumn = contentList.Max(t => t.Column); + var maxRow = contentList.Max(t => t.Row); - for (int r = 0; r <= maxRow; r++) + for (var r = 0; r <= maxRow; r++) { var contents = new List(); - for (int c = 0; c <= maxColumn; c++) + for (var c = 0; c <= maxColumn; c++) { - if (!dict.TryGetValue((c, r), out string content)) + if (!dict.TryGetValue((c, r), out var content)) { content = string.Empty; } diff --git a/Signalbox.Engine/Tracks/CrossTrack/CrossTrackFactory.cs b/Signalbox.Engine/Tracks/CrossTrack/CrossTrackFactory.cs index 6fc9575..693bdfe 100644 --- a/Signalbox.Engine/Tracks/CrossTrack/CrossTrackFactory.cs +++ b/Signalbox.Engine/Tracks/CrossTrack/CrossTrackFactory.cs @@ -44,7 +44,7 @@ public bool TryCreateEntity(int column, int row, int fromColumn, int fromRow, [N neighbours = TrackNeighbors.GetConnectedNeighbours(_layout, column - 1, row); if (neighbours.Count == 3 && neighbours.Right is null) { - entity = new SingleTrack.SingleTrack() { Direction = SingleTrackDirection.Horizontal }; + entity = new SingleTrack.SingleTrack { Direction = SingleTrackDirection.Horizontal }; _layout.Set(column - 1, row, new CrossTrack()); return true; } @@ -52,7 +52,7 @@ public bool TryCreateEntity(int column, int row, int fromColumn, int fromRow, [N neighbours = TrackNeighbors.GetConnectedNeighbours(_layout, column, row - 1); if (neighbours.Count == 3 && neighbours.Down is null) { - entity = new SingleTrack.SingleTrack() { Direction = SingleTrackDirection.Vertical }; + entity = new SingleTrack.SingleTrack { Direction = SingleTrackDirection.Vertical }; _layout.Set(column, row - 1, new CrossTrack()); return true; } @@ -60,7 +60,7 @@ public bool TryCreateEntity(int column, int row, int fromColumn, int fromRow, [N neighbours = TrackNeighbors.GetConnectedNeighbours(_layout, column + 1, row); if (neighbours.Count == 3 && neighbours.Left is null) { - entity = new SingleTrack.SingleTrack() { Direction = SingleTrackDirection.Horizontal }; + entity = new SingleTrack.SingleTrack { Direction = SingleTrackDirection.Horizontal }; _layout.Set(column + 1, row, new CrossTrack()); return true; } @@ -68,7 +68,7 @@ public bool TryCreateEntity(int column, int row, int fromColumn, int fromRow, [N neighbours = TrackNeighbors.GetConnectedNeighbours(_layout, column, row + 1); if (neighbours.Count == 3 && neighbours.Up is null) { - entity = new SingleTrack.SingleTrack() { Direction = SingleTrackDirection.Vertical }; + entity = new SingleTrack.SingleTrack { Direction = SingleTrackDirection.Vertical }; _layout.Set(column, row + 1, new CrossTrack()); return true; } diff --git a/Signalbox.Engine/Tracks/CrossTrack/CrossTrackSerializer.cs b/Signalbox.Engine/Tracks/CrossTrack/CrossTrackSerializer.cs index d3c0dd9..6d17237 100644 --- a/Signalbox.Engine/Tracks/CrossTrack/CrossTrackSerializer.cs +++ b/Signalbox.Engine/Tracks/CrossTrack/CrossTrackSerializer.cs @@ -20,7 +20,7 @@ public bool TryDeserialize(string data, [NotNullWhen(true)] out IEntity? entity) return false; } - var track = new CrossTrack() + var track = new CrossTrack { Happy = bool.Parse(bits[1]) }; diff --git a/Signalbox.Engine/Tracks/SingleTrack/Signal.cs b/Signalbox.Engine/Tracks/SingleTrack/Signal.cs index 3d3bcc1..6d598bc 100644 --- a/Signalbox.Engine/Tracks/SingleTrack/Signal.cs +++ b/Signalbox.Engine/Tracks/SingleTrack/Signal.cs @@ -11,18 +11,18 @@ public class Signal : SingleTrack, IUpdatableEntity public int TemporaryStopCounter { get; set; } public override string Identifier - => $"{base.Identifier}.{this.SignalState}"; + => $"{base.Identifier}.{SignalState}"; public override bool HasMultipleStates => true; - public Signal() : base() + public Signal() { - this.SignalState = SignalState.Go; + SignalState = SignalState.Go; } public override void NextState() { - this.SignalState = this.SignalState switch + SignalState = SignalState switch { SignalState.Go => SignalState.TemporaryStop, SignalState.TemporaryStop => SignalState.Stop, @@ -35,16 +35,16 @@ public override void NextState() public void Update() { - if (this.SignalState == SignalState.TemporaryStop && - ++this.TemporaryStopCounter >= TemporaryStopTime) + if (SignalState == SignalState.TemporaryStop && + ++TemporaryStopCounter >= TemporaryStopTime) { - this.SignalState = SignalState.Go; - this.TemporaryStopCounter = 0; + SignalState = SignalState.Go; + TemporaryStopCounter = 0; OnChanged(); } } public override bool IsBlocked() - => this.SignalState != SignalState.Go; + => SignalState != SignalState.Go; } diff --git a/Signalbox.Engine/Tracks/SingleTrack/SignalFactory.cs b/Signalbox.Engine/Tracks/SingleTrack/SignalFactory.cs index ea55044..ae526d3 100644 --- a/Signalbox.Engine/Tracks/SingleTrack/SignalFactory.cs +++ b/Signalbox.Engine/Tracks/SingleTrack/SignalFactory.cs @@ -20,15 +20,15 @@ public IEnumerable GetPossibleReplacements(int column, int row, Track tra var neighbours = track.GetAllNeighbors(); if (neighbours.Left is not null || neighbours.Right is not null) { - yield return new Signal() { Direction = SingleTrackDirection.Horizontal, SignalState = SignalState.Go }; - yield return new Signal() { Direction = SingleTrackDirection.Horizontal, SignalState = SignalState.TemporaryStop }; - yield return new Signal() { Direction = SingleTrackDirection.Horizontal, SignalState = SignalState.Stop }; + yield return new Signal { Direction = SingleTrackDirection.Horizontal, SignalState = SignalState.Go }; + yield return new Signal { Direction = SingleTrackDirection.Horizontal, SignalState = SignalState.TemporaryStop }; + yield return new Signal { Direction = SingleTrackDirection.Horizontal, SignalState = SignalState.Stop }; } if (neighbours.Up is not null || neighbours.Down is not null) { - yield return new Signal() { Direction = SingleTrackDirection.Vertical, SignalState = SignalState.Go }; - yield return new Signal() { Direction = SingleTrackDirection.Vertical, SignalState = SignalState.TemporaryStop }; - yield return new Signal() { Direction = SingleTrackDirection.Vertical, SignalState = SignalState.Stop }; + yield return new Signal { Direction = SingleTrackDirection.Vertical, SignalState = SignalState.Go }; + yield return new Signal { Direction = SingleTrackDirection.Vertical, SignalState = SignalState.TemporaryStop }; + yield return new Signal { Direction = SingleTrackDirection.Vertical, SignalState = SignalState.Stop }; } } diff --git a/Signalbox.Engine/Tracks/SingleTrack/SignalSerializer.cs b/Signalbox.Engine/Tracks/SingleTrack/SignalSerializer.cs index a58bfdc..506a37c 100644 --- a/Signalbox.Engine/Tracks/SingleTrack/SignalSerializer.cs +++ b/Signalbox.Engine/Tracks/SingleTrack/SignalSerializer.cs @@ -20,7 +20,7 @@ public bool TryDeserialize(string data, [NotNullWhen(true)] out IEntity? entity) return false; } - var track = new Signal() + var track = new Signal { Direction = Enum.Parse(bits[1]), SignalState = Enum.Parse(bits[2]), diff --git a/Signalbox.Engine/Tracks/SingleTrack/SingleTrack.cs b/Signalbox.Engine/Tracks/SingleTrack/SingleTrack.cs index 5830608..7e369c1 100644 --- a/Signalbox.Engine/Tracks/SingleTrack/SingleTrack.cs +++ b/Signalbox.Engine/Tracks/SingleTrack/SingleTrack.cs @@ -6,13 +6,13 @@ namespace Signalbox.Engine.Tracks.SingleTrack; [DebuggerDisplay("{Direction,nq}")] public class SingleTrack : Track { - public override string Identifier => this.Direction.ToString(); + public override string Identifier => Direction.ToString(); public SingleTrackDirection Direction { get; set; } public override void Move(TrainPosition position) { - switch (this.Direction) + switch (Direction) { case SingleTrackDirection.Horizontal: TrainMovement.MoveHorizontal(position); break; case SingleTrackDirection.Vertical: TrainMovement.MoveVertical(position); break; @@ -25,7 +25,7 @@ public override void Move(TrainPosition position) } public override bool IsConnectedRight() - => this.Direction switch + => Direction switch { SingleTrackDirection.RightDown => true, SingleTrackDirection.RightUp => true, @@ -34,7 +34,7 @@ public override bool IsConnectedRight() }; public override bool IsConnectedDown() - => this.Direction switch + => Direction switch { SingleTrackDirection.RightDown => true, SingleTrackDirection.LeftDown => true, @@ -43,7 +43,7 @@ public override bool IsConnectedDown() }; public override bool IsConnectedLeft() - => this.Direction switch + => Direction switch { SingleTrackDirection.LeftDown => true, SingleTrackDirection.LeftUp => true, @@ -52,7 +52,7 @@ public override bool IsConnectedLeft() }; public override bool IsConnectedUp() - => this.Direction switch + => Direction switch { SingleTrackDirection.LeftUp => true, SingleTrackDirection.RightUp => true, @@ -62,19 +62,19 @@ public override bool IsConnectedUp() public void SetBestTrackDirection(bool ignoreHappyness) { - SingleTrackDirection newDirection = GetBestTrackDirection(ignoreHappyness); + var newDirection = GetBestTrackDirection(ignoreHappyness); - if (this.Direction != newDirection) + if (Direction != newDirection) { - this.Direction = newDirection; + Direction = newDirection; RefreshNeighbors(false); } } public virtual SingleTrackDirection GetBestTrackDirection(bool ignoreHappyness) { - TrackNeighbors neighbors = GetPotentialNeighbors(); - SingleTrackDirection newDirection = this.Direction; + var neighbors = GetPotentialNeighbors(); + var newDirection = Direction; if (neighbors.Count > 2) { @@ -86,7 +86,7 @@ public virtual SingleTrackDirection GetBestTrackDirection(bool ignoreHappyness) { newDirection = SingleTrackDirection.Horizontal; } - else if (!this.Happy || ignoreHappyness) + else if (!Happy || ignoreHappyness) { // 2-way connections if (neighbors.Up != null && neighbors.Left != null) @@ -121,7 +121,7 @@ public virtual SingleTrackDirection GetBestTrackDirection(bool ignoreHappyness) public void RefreshNeighbors(bool ignoreHappyness) { - TrackNeighbors neighbors = GetAllNeighbors(); + var neighbors = GetAllNeighbors(); (neighbors.Up as SingleTrack)?.SetBestTrackDirection(ignoreHappyness); (neighbors.Down as SingleTrack)?.SetBestTrackDirection(ignoreHappyness); (neighbors.Right as SingleTrack)?.SetBestTrackDirection(ignoreHappyness); @@ -130,13 +130,13 @@ public void RefreshNeighbors(bool ignoreHappyness) private TrackNeighbors GetPotentialNeighbors() { - _ = this.TrackLayout ?? throw new InvalidOperationException("Game board can't be null"); + _ = TrackLayout ?? throw new InvalidOperationException("Game board can't be null"); return new( - this.TrackLayout.TryGet(this.Column - 1, this.Row, out Track? left) && left.CanConnectRight() ? left : null, - this.TrackLayout.TryGet(this.Column, this.Row - 1, out Track? up) && up.CanConnectDown() ? up : null, - this.TrackLayout.TryGet(this.Column + 1, this.Row, out Track? right) && right.CanConnectLeft() ? right : null, - this.TrackLayout.TryGet(this.Column, this.Row + 1, out Track? down) && down.CanConnectUp() ? down : null + TrackLayout.TryGet(Column - 1, Row, out Track? left) && left.CanConnectRight() ? left : null, + TrackLayout.TryGet(Column, Row - 1, out Track? up) && up.CanConnectDown() ? up : null, + TrackLayout.TryGet(Column + 1, Row, out Track? right) && right.CanConnectLeft() ? right : null, + TrackLayout.TryGet(Column, Row + 1, out Track? down) && down.CanConnectUp() ? down : null ); } @@ -154,7 +154,7 @@ public override void Removed() { // We need to assume that we've already been removed from our parent, but before we go, // tell the neighbours we won't be back in the morning - if (this.TrackLayout != null) + if (TrackLayout != null) { RefreshNeighbors(true); } diff --git a/Signalbox.Engine/Tracks/SingleTrack/SingleTrackFactory.cs b/Signalbox.Engine/Tracks/SingleTrack/SingleTrackFactory.cs index 036ca2d..7cdd937 100644 --- a/Signalbox.Engine/Tracks/SingleTrack/SingleTrackFactory.cs +++ b/Signalbox.Engine/Tracks/SingleTrack/SingleTrackFactory.cs @@ -33,27 +33,27 @@ public bool TryCreateEntity(int column, int row, int fromColumn, int fromRow, [N public IEnumerable GetPossibleReplacements(int column, int row, Track track) { - yield return new SingleTrack() { Direction = SingleTrackDirection.Horizontal }; + yield return new SingleTrack { Direction = SingleTrackDirection.Horizontal }; var neighbours = track.GetAllNeighbors(); if (neighbours.Up is not null || neighbours.Down is not null) { - yield return new SingleTrack() { Direction = SingleTrackDirection.Vertical }; + yield return new SingleTrack { Direction = SingleTrackDirection.Vertical }; } if (neighbours.Up is not null && neighbours.Left is not null) { - yield return new SingleTrack() { Direction = SingleTrackDirection.LeftUp }; + yield return new SingleTrack { Direction = SingleTrackDirection.LeftUp }; } if (neighbours.Up is not null && neighbours.Right is not null) { - yield return new SingleTrack() { Direction = SingleTrackDirection.RightUp }; + yield return new SingleTrack { Direction = SingleTrackDirection.RightUp }; } if (neighbours.Down is not null && neighbours.Left is not null) { - yield return new SingleTrack() { Direction = SingleTrackDirection.LeftDown }; + yield return new SingleTrack { Direction = SingleTrackDirection.LeftDown }; } if (neighbours.Down is not null && neighbours.Right is not null) { - yield return new SingleTrack() { Direction = SingleTrackDirection.RightDown }; + yield return new SingleTrack { Direction = SingleTrackDirection.RightDown }; } } } diff --git a/Signalbox.Engine/Tracks/SingleTrack/SingleTrackSerializer.cs b/Signalbox.Engine/Tracks/SingleTrack/SingleTrackSerializer.cs index f528209..d01a328 100644 --- a/Signalbox.Engine/Tracks/SingleTrack/SingleTrackSerializer.cs +++ b/Signalbox.Engine/Tracks/SingleTrack/SingleTrackSerializer.cs @@ -20,7 +20,7 @@ public bool TryDeserialize(string data, [NotNullWhen(true)] out IEntity? entity) return false; } - var track = new SingleTrack() + var track = new SingleTrack { Direction = Enum.Parse(bits[1]), Happy = bool.Parse(bits[2]) diff --git a/Signalbox.Engine/Tracks/TIntersection/TIntersection.cs b/Signalbox.Engine/Tracks/TIntersection/TIntersection.cs index aba5286..b669010 100644 --- a/Signalbox.Engine/Tracks/TIntersection/TIntersection.cs +++ b/Signalbox.Engine/Tracks/TIntersection/TIntersection.cs @@ -10,15 +10,15 @@ public class TIntersection : Track public TIntersectionDirection Direction { get; set; } - public override string Identifier => $"{this.Direction}.{this.Style}"; + public override string Identifier => $"{Direction}.{Style}"; public override void NextState() { - this.Style = this.Style + 1; + Style = Style + 1; - if (this.Style > TIntersectionStyle.StraightAndSecondary) + if (Style > TIntersectionStyle.StraightAndSecondary) { - this.Style = TIntersectionStyle.CornerAndPrimary; + Style = TIntersectionStyle.CornerAndPrimary; } OnChanged(); @@ -26,7 +26,7 @@ public override void NextState() public override void Move(TrainPosition position) { - switch (this.Direction) + switch (Direction) { case TIntersectionDirection.RightUp_RightDown: MoveRightUp_RightDown(position); break; case TIntersectionDirection.RightDown_LeftDown: MoveRightDown_LeftDown(position); break; @@ -37,7 +37,7 @@ public override void Move(TrainPosition position) } public override bool IsConnectedRight() - => this.Direction switch + => Direction switch { TIntersectionDirection.RightDown_LeftDown => true, TIntersectionDirection.LeftUp_RightUp => true, @@ -46,7 +46,7 @@ public override bool IsConnectedRight() }; public override bool IsConnectedDown() - => this.Direction switch + => Direction switch { TIntersectionDirection.RightDown_LeftDown => true, TIntersectionDirection.LeftDown_LeftUp => true, @@ -55,7 +55,7 @@ public override bool IsConnectedDown() }; public override bool IsConnectedLeft() - => this.Direction switch + => Direction switch { TIntersectionDirection.RightDown_LeftDown => true, TIntersectionDirection.LeftUp_RightUp => true, @@ -64,7 +64,7 @@ public override bool IsConnectedLeft() }; public override bool IsConnectedUp() - => this.Direction switch + => Direction switch { TIntersectionDirection.LeftDown_LeftUp => true, TIntersectionDirection.LeftUp_RightUp => true, @@ -74,13 +74,13 @@ public override bool IsConnectedUp() private void MoveRightDown_LeftDown(TrainPosition position) { - if (this.Style is TIntersectionStyle.StraightAndPrimary or TIntersectionStyle.StraightAndSecondary) + if (Style is TIntersectionStyle.StraightAndPrimary or TIntersectionStyle.StraightAndSecondary) { if (position.Angle is 0 or 180) { TrainMovement.MoveHorizontal(position); } - else if (this.Style is TIntersectionStyle.StraightAndPrimary) + else if (Style is TIntersectionStyle.StraightAndPrimary) { TrainMovement.MoveLeftDown(position); } @@ -103,7 +103,7 @@ private void MoveRightDown_LeftDown(TrainPosition position) } else { - if (this.Style is TIntersectionStyle.CornerAndSecondary) + if (Style is TIntersectionStyle.CornerAndSecondary) { TrainMovement.MoveLeftDown(position); } @@ -116,13 +116,13 @@ private void MoveRightDown_LeftDown(TrainPosition position) private void MoveLeftDown_LeftUp(TrainPosition position) { - if (this.Style is TIntersectionStyle.StraightAndPrimary or TIntersectionStyle.StraightAndSecondary) + if (Style is TIntersectionStyle.StraightAndPrimary or TIntersectionStyle.StraightAndSecondary) { if (position.Angle is 90 or 270) { TrainMovement.MoveVertical(position); } - else if (this.Style is TIntersectionStyle.StraightAndPrimary) + else if (Style is TIntersectionStyle.StraightAndPrimary) { TrainMovement.MoveLeftUp(position); } @@ -145,7 +145,7 @@ private void MoveLeftDown_LeftUp(TrainPosition position) } else { - if (this.Style == TIntersectionStyle.CornerAndSecondary) + if (Style == TIntersectionStyle.CornerAndSecondary) { TrainMovement.MoveLeftUp(position); } @@ -158,13 +158,13 @@ private void MoveLeftDown_LeftUp(TrainPosition position) private void MoveLeftUp_RightUp(TrainPosition position) { - if (this.Style is TIntersectionStyle.StraightAndPrimary or TIntersectionStyle.StraightAndSecondary) + if (Style is TIntersectionStyle.StraightAndPrimary or TIntersectionStyle.StraightAndSecondary) { if (position.Angle is 0 or 180) { TrainMovement.MoveHorizontal(position); } - else if (this.Style is TIntersectionStyle.StraightAndPrimary) + else if (Style is TIntersectionStyle.StraightAndPrimary) { TrainMovement.MoveRightUp(position); } @@ -187,7 +187,7 @@ private void MoveLeftUp_RightUp(TrainPosition position) } else { - if (this.Style == TIntersectionStyle.CornerAndSecondary) + if (Style == TIntersectionStyle.CornerAndSecondary) { TrainMovement.MoveRightUp(position); } @@ -200,13 +200,13 @@ private void MoveLeftUp_RightUp(TrainPosition position) private void MoveRightUp_RightDown(TrainPosition position) { - if (this.Style is TIntersectionStyle.StraightAndPrimary or TIntersectionStyle.StraightAndSecondary) + if (Style is TIntersectionStyle.StraightAndPrimary or TIntersectionStyle.StraightAndSecondary) { if (position.Angle is 90 or 270) { TrainMovement.MoveVertical(position); } - else if (this.Style is TIntersectionStyle.StraightAndPrimary) + else if (Style is TIntersectionStyle.StraightAndPrimary) { TrainMovement.MoveRightDown(position); } @@ -229,7 +229,7 @@ private void MoveRightUp_RightDown(TrainPosition position) } else { - if (this.Style == TIntersectionStyle.CornerAndSecondary) + if (Style == TIntersectionStyle.CornerAndSecondary) { TrainMovement.MoveRightDown(position); } diff --git a/Signalbox.Engine/Tracks/TIntersection/TIntersectionFactory.cs b/Signalbox.Engine/Tracks/TIntersection/TIntersectionFactory.cs index f960664..d8abf4a 100644 --- a/Signalbox.Engine/Tracks/TIntersection/TIntersectionFactory.cs +++ b/Signalbox.Engine/Tracks/TIntersection/TIntersectionFactory.cs @@ -28,31 +28,31 @@ public IEnumerable GetPossibleReplacements(int column, int row, Track tra if (AreAllPresent(neighbours.Up, neighbours.Left, neighbours.Right)) { - yield return new TIntersection() { Direction = TIntersectionDirection.LeftUp_RightUp, Style = TIntersectionStyle.CornerAndPrimary }; - yield return new TIntersection() { Direction = TIntersectionDirection.LeftUp_RightUp, Style = TIntersectionStyle.CornerAndSecondary }; - yield return new TIntersection() { Direction = TIntersectionDirection.LeftUp_RightUp, Style = TIntersectionStyle.StraightAndPrimary }; - yield return new TIntersection() { Direction = TIntersectionDirection.LeftUp_RightUp, Style = TIntersectionStyle.StraightAndSecondary }; + yield return new TIntersection { Direction = TIntersectionDirection.LeftUp_RightUp, Style = TIntersectionStyle.CornerAndPrimary }; + yield return new TIntersection { Direction = TIntersectionDirection.LeftUp_RightUp, Style = TIntersectionStyle.CornerAndSecondary }; + yield return new TIntersection { Direction = TIntersectionDirection.LeftUp_RightUp, Style = TIntersectionStyle.StraightAndPrimary }; + yield return new TIntersection { Direction = TIntersectionDirection.LeftUp_RightUp, Style = TIntersectionStyle.StraightAndSecondary }; } if (AreAllPresent(neighbours.Up, neighbours.Left, neighbours.Down)) { - yield return new TIntersection() { Direction = TIntersectionDirection.LeftDown_LeftUp, Style = TIntersectionStyle.CornerAndPrimary }; - yield return new TIntersection() { Direction = TIntersectionDirection.LeftDown_LeftUp, Style = TIntersectionStyle.CornerAndSecondary }; - yield return new TIntersection() { Direction = TIntersectionDirection.LeftDown_LeftUp, Style = TIntersectionStyle.StraightAndPrimary }; - yield return new TIntersection() { Direction = TIntersectionDirection.LeftDown_LeftUp, Style = TIntersectionStyle.StraightAndSecondary }; + yield return new TIntersection { Direction = TIntersectionDirection.LeftDown_LeftUp, Style = TIntersectionStyle.CornerAndPrimary }; + yield return new TIntersection { Direction = TIntersectionDirection.LeftDown_LeftUp, Style = TIntersectionStyle.CornerAndSecondary }; + yield return new TIntersection { Direction = TIntersectionDirection.LeftDown_LeftUp, Style = TIntersectionStyle.StraightAndPrimary }; + yield return new TIntersection { Direction = TIntersectionDirection.LeftDown_LeftUp, Style = TIntersectionStyle.StraightAndSecondary }; } if (AreAllPresent(neighbours.Up, neighbours.Right, neighbours.Down)) { - yield return new TIntersection() { Direction = TIntersectionDirection.RightUp_RightDown, Style = TIntersectionStyle.CornerAndPrimary }; - yield return new TIntersection() { Direction = TIntersectionDirection.RightUp_RightDown, Style = TIntersectionStyle.CornerAndSecondary }; - yield return new TIntersection() { Direction = TIntersectionDirection.RightUp_RightDown, Style = TIntersectionStyle.StraightAndPrimary }; - yield return new TIntersection() { Direction = TIntersectionDirection.RightUp_RightDown, Style = TIntersectionStyle.StraightAndSecondary }; + yield return new TIntersection { Direction = TIntersectionDirection.RightUp_RightDown, Style = TIntersectionStyle.CornerAndPrimary }; + yield return new TIntersection { Direction = TIntersectionDirection.RightUp_RightDown, Style = TIntersectionStyle.CornerAndSecondary }; + yield return new TIntersection { Direction = TIntersectionDirection.RightUp_RightDown, Style = TIntersectionStyle.StraightAndPrimary }; + yield return new TIntersection { Direction = TIntersectionDirection.RightUp_RightDown, Style = TIntersectionStyle.StraightAndSecondary }; } if (AreAllPresent(neighbours.Down, neighbours.Left, neighbours.Right)) { - yield return new TIntersection() { Direction = TIntersectionDirection.RightDown_LeftDown, Style = TIntersectionStyle.CornerAndPrimary }; - yield return new TIntersection() { Direction = TIntersectionDirection.RightDown_LeftDown, Style = TIntersectionStyle.CornerAndSecondary }; - yield return new TIntersection() { Direction = TIntersectionDirection.RightDown_LeftDown, Style = TIntersectionStyle.StraightAndPrimary }; - yield return new TIntersection() { Direction = TIntersectionDirection.RightDown_LeftDown, Style = TIntersectionStyle.StraightAndSecondary }; + yield return new TIntersection { Direction = TIntersectionDirection.RightDown_LeftDown, Style = TIntersectionStyle.CornerAndPrimary }; + yield return new TIntersection { Direction = TIntersectionDirection.RightDown_LeftDown, Style = TIntersectionStyle.CornerAndSecondary }; + yield return new TIntersection { Direction = TIntersectionDirection.RightDown_LeftDown, Style = TIntersectionStyle.StraightAndPrimary }; + yield return new TIntersection { Direction = TIntersectionDirection.RightDown_LeftDown, Style = TIntersectionStyle.StraightAndSecondary }; } } @@ -71,26 +71,26 @@ public bool TryCreateEntity(int column, int row, int fromColumn, int fromRow, [N { if (AreAllPresent(neighbours.Down, neighbours.Left, neighbours.Right)) { - entity = new TIntersection() { Direction = TIntersectionDirection.RightDown_LeftDown }; + entity = new TIntersection { Direction = TIntersectionDirection.RightDown_LeftDown }; } else if (AreAllPresent(neighbours.Up, neighbours.Left, neighbours.Right)) { - entity = new TIntersection() { Direction = TIntersectionDirection.LeftUp_RightUp }; + entity = new TIntersection { Direction = TIntersectionDirection.LeftUp_RightUp }; } else if (AreAllPresent(neighbours.Up, neighbours.Right, neighbours.Down)) { - entity = new TIntersection() { Direction = TIntersectionDirection.RightUp_RightDown }; + entity = new TIntersection { Direction = TIntersectionDirection.RightUp_RightDown }; } else if (AreAllPresent(neighbours.Up, neighbours.Left, neighbours.Down)) { - entity = new TIntersection() { Direction = TIntersectionDirection.LeftDown_LeftUp }; + entity = new TIntersection { Direction = TIntersectionDirection.LeftDown_LeftUp }; } } else if (neighbours.Count == 2 && allNeighbours.Count == 3) { if (neighbours.Up is not null && neighbours.Down is not null && allNeighbours.Left is SingleTrack.SingleTrack { Happy: false } singleTrack1) { - entity = new TIntersection() { Direction = TIntersectionDirection.LeftDown_LeftUp }; + entity = new TIntersection { Direction = TIntersectionDirection.LeftDown_LeftUp }; if (singleTrack1.IsConnectedDown() && singleTrack1.GetAllNeighbors().Down is not null) { singleTrack1.Direction = SingleTrackDirection.RightDown; @@ -106,7 +106,7 @@ public bool TryCreateEntity(int column, int row, int fromColumn, int fromRow, [N } else if (neighbours.Up is not null && neighbours.Down is not null && allNeighbours.Right is SingleTrack.SingleTrack { Happy: false } singleTrack2) { - entity = new TIntersection() { Direction = TIntersectionDirection.RightUp_RightDown }; + entity = new TIntersection { Direction = TIntersectionDirection.RightUp_RightDown }; if (singleTrack2.IsConnectedDown() && singleTrack2.GetAllNeighbors().Down is not null) { singleTrack2.Direction = SingleTrackDirection.LeftDown; @@ -122,7 +122,7 @@ public bool TryCreateEntity(int column, int row, int fromColumn, int fromRow, [N } else if (neighbours.Left is not null && neighbours.Right is not null && allNeighbours.Up is SingleTrack.SingleTrack { Happy: false } singleTrack3) { - entity = new TIntersection() { Direction = TIntersectionDirection.LeftUp_RightUp }; + entity = new TIntersection { Direction = TIntersectionDirection.LeftUp_RightUp }; if (singleTrack3.IsConnectedLeft() && singleTrack3.GetAllNeighbors().Left is not null) { singleTrack3.Direction = SingleTrackDirection.LeftDown; @@ -138,7 +138,7 @@ public bool TryCreateEntity(int column, int row, int fromColumn, int fromRow, [N } else if (neighbours.Left is not null && neighbours.Right is not null && allNeighbours.Down is SingleTrack.SingleTrack { Happy: false } singleTrack4) { - entity = new TIntersection() { Direction = TIntersectionDirection.RightDown_LeftDown }; + entity = new TIntersection { Direction = TIntersectionDirection.RightDown_LeftDown }; if (singleTrack4.IsConnectedLeft() && singleTrack4.GetAllNeighbors().Left is not null) { singleTrack4.Direction = SingleTrackDirection.LeftUp; diff --git a/Signalbox.Engine/Tracks/TIntersection/TIntersectionSerializer.cs b/Signalbox.Engine/Tracks/TIntersection/TIntersectionSerializer.cs index d558932..d8b28c9 100644 --- a/Signalbox.Engine/Tracks/TIntersection/TIntersectionSerializer.cs +++ b/Signalbox.Engine/Tracks/TIntersection/TIntersectionSerializer.cs @@ -20,7 +20,7 @@ public bool TryDeserialize(string data, [NotNullWhen(true)] out IEntity? entity) return false; } - var track = new TIntersection() + var track = new TIntersection { Direction = Enum.Parse(bits[1]), Style = Enum.Parse(bits[2]), diff --git a/Signalbox.Engine/Tracks/Track.cs b/Signalbox.Engine/Tracks/Track.cs index 4d8d28f..34e3f09 100644 --- a/Signalbox.Engine/Tracks/Track.cs +++ b/Signalbox.Engine/Tracks/Track.cs @@ -32,10 +32,10 @@ public TrackNeighbors GetAllNeighbors() _ = _trackLayout ?? throw new InvalidOperationException("Game board can't be null"); return new( - _trackLayout.TryGet(this.Column - 1, this.Row, out Track? left) ? left : null, - _trackLayout.TryGet(this.Column, this.Row - 1, out Track? up) ? up : null, - _trackLayout.TryGet(this.Column + 1, this.Row, out Track? right) ? right : null, - _trackLayout.TryGet(this.Column, this.Row + 1, out Track? down) ? down : null + _trackLayout.TryGet(Column - 1, Row, out Track? left) ? left : null, + _trackLayout.TryGet(Column, Row - 1, out Track? up) ? up : null, + _trackLayout.TryGet(Column + 1, Row, out Track? right) ? right : null, + _trackLayout.TryGet(Column, Row + 1, out Track? down) ? down : null ); } @@ -74,11 +74,11 @@ public virtual void EnterTrack(Train train) } public bool CanConnectRight() - => !this.Happy || IsConnectedRight(); + => !Happy || IsConnectedRight(); public bool CanConnectDown() - => !this.Happy || IsConnectedDown(); + => !Happy || IsConnectedDown(); public bool CanConnectLeft() - => !this.Happy || IsConnectedLeft(); + => !Happy || IsConnectedLeft(); public bool CanConnectUp() - => !this.Happy || IsConnectedUp(); + => !Happy || IsConnectedUp(); } diff --git a/Signalbox.Engine/Tracks/TrackNeighbors.cs b/Signalbox.Engine/Tracks/TrackNeighbors.cs index b4099f5..6c43daf 100644 --- a/Signalbox.Engine/Tracks/TrackNeighbors.cs +++ b/Signalbox.Engine/Tracks/TrackNeighbors.cs @@ -13,33 +13,33 @@ public IEnumerable All { get { - if (this.Up is not null) yield return this.Up; - if (this.Left is not null) yield return this.Left; - if (this.Right is not null) yield return this.Right; - if (this.Down is not null) yield return this.Down; + if (Up is not null) yield return Up; + if (Left is not null) yield return Left; + if (Right is not null) yield return Right; + if (Down is not null) yield return Down; } } - public int Count => (this.Up == null ? 0 : 1) + - (this.Down == null ? 0 : 1) + - (this.Right == null ? 0 : 1) + - (this.Left == null ? 0 : 1); + public int Count => (Up == null ? 0 : 1) + + (Down == null ? 0 : 1) + + (Right == null ? 0 : 1) + + (Left == null ? 0 : 1); public bool Contains(Track otherTrack) { return otherTrack != null && - (this.Left == otherTrack || - this.Right == otherTrack || - this.Up == otherTrack || - this.Down == otherTrack); + (Left == otherTrack || + Right == otherTrack || + Up == otherTrack || + Down == otherTrack); } public TrackNeighbors(Track? left, Track? up, Track? right, Track? down) { - this.Left = left; - this.Up = up; - this.Right = right; - this.Down = down; + Left = left; + Up = up; + Right = right; + Down = down; } public static TrackNeighbors GetConnectedNeighbours(ILayout trackLayout, int column, int row, bool emptyIsConsideredConnected = false, bool ignoreCurrent = false) diff --git a/Signalbox.Engine/Trains/Train.cs b/Signalbox.Engine/Trains/Train.cs index 77a79e0..9ed68b2 100644 --- a/Signalbox.Engine/Trains/Train.cs +++ b/Signalbox.Engine/Trains/Train.cs @@ -11,23 +11,23 @@ public class Train : IMovable, INotifyPropertyChanged, ISeeded public Train(int seed) { - this.Seed = seed; - this.UniqueID = Guid.NewGuid(); - this.Name = TrainNames.GetName(seed); - this.RelativeLeft = 0.5f; - this.RelativeTop = 0.5f; + Seed = seed; + UniqueID = Guid.NewGuid(); + Name = TrainNames.GetName(seed); + RelativeLeft = 0.5f; + RelativeTop = 0.5f; } private Train(Train other) { - this.Seed = other.Seed; - this.UniqueID = other.UniqueID; - this.Column = other.Column; - this.Name = other.Name; - this.Row = other.Row; - this.Angle = other.Angle; - this.RelativeLeft = other.RelativeLeft; - this.RelativeTop = other.RelativeTop; + Seed = other.Seed; + UniqueID = other.UniqueID; + Column = other.Column; + Name = other.Name; + Row = other.Row; + Angle = other.Angle; + RelativeLeft = other.RelativeLeft; + RelativeTop = other.RelativeTop; } public virtual Guid UniqueID { get; } @@ -48,7 +48,7 @@ public void SetAngle(float angle) { while (angle < 0) angle += 360; while (angle > 360) angle -= 360; - this.Angle = angle; + Angle = angle; } public Train Clone() @@ -56,24 +56,24 @@ public Train Clone() return new(this); } - public void Start() => this.Stopped = false; + public void Start() => Stopped = false; - public void Stop() => this.Stopped = true; + public void Stop() => Stopped = true; internal void Pause() => _collisionAhead = true; internal void Resume() => _collisionAhead = false; - public override string ToString() => $"Train {this.UniqueID} [Column: {this.Column} | Row: {this.Row} | Left: {this.RelativeLeft} | Top: {this.RelativeTop} | Angle: {this.Angle}]"; + public override string ToString() => $"Train {UniqueID} [Column: {Column} | Row: {Row} | Left: {RelativeLeft} | Top: {RelativeTop} | Angle: {Angle}]"; - internal TrainPosition GetPosition() => new(this.Column, this.Row, this.RelativeLeft, this.RelativeTop, this.Angle, 0); + internal TrainPosition GetPosition() => new(Column, Row, RelativeLeft, RelativeTop, Angle, 0); public void ApplyStep(TrainPosition newPosition) { - this.Column = newPosition.Column; - this.Row = newPosition.Row; - this.Angle = newPosition.Angle; - this.RelativeLeft = newPosition.RelativeLeft; - this.RelativeTop = newPosition.RelativeTop; + Column = newPosition.Column; + Row = newPosition.Row; + Angle = newPosition.Angle; + RelativeLeft = newPosition.RelativeLeft; + RelativeTop = newPosition.RelativeTop; } } diff --git a/Signalbox.Engine/Trains/TrainManager.cs b/Signalbox.Engine/Trains/TrainManager.cs index 2e62b9e..8082371 100644 --- a/Signalbox.Engine/Trains/TrainManager.cs +++ b/Signalbox.Engine/Trains/TrainManager.cs @@ -60,9 +60,9 @@ public TrainManager(IMovableLayout movableLayout, ILayout layout) public void ToggleFollow(Train train) { // if we're already following the train specified, toggle it off - Train? trainToSet = train.Follow ? null : train; + var trainToSet = train.Follow ? null : train; - foreach (Train t in _movableLayout.OfType()) + foreach (var t in _movableLayout.OfType()) { t.Follow = (t == trainToSet); } @@ -76,27 +76,27 @@ private void Train_PropertyChanged(object? sender, PropertyChangedEventArgs e) public void PreviousTrain() { - int index = _currentTrain == null ? -1 : _movableLayout.IndexOf(_currentTrain); + var index = _currentTrain == null ? -1 : _movableLayout.IndexOf(_currentTrain); if (index == -1 || index == 0) { - this.CurrentTrain = _movableLayout[^1] as Train; + CurrentTrain = _movableLayout[^1] as Train; } else { - this.CurrentTrain = _movableLayout[index - 1] as Train; + CurrentTrain = _movableLayout[index - 1] as Train; } } public void NextTrain() { - int index = _currentTrain == null ? -1 : _movableLayout.IndexOf(_currentTrain); + var index = _currentTrain == null ? -1 : _movableLayout.IndexOf(_currentTrain); if (index == -1 || index == _movableLayout.Count - 1) { - this.CurrentTrain = _movableLayout[0] as Train; + CurrentTrain = _movableLayout[0] as Train; } else { - this.CurrentTrain = _movableLayout[index + 1] as Train; + CurrentTrain = _movableLayout[index + 1] as Train; } } @@ -104,7 +104,7 @@ public bool TryGetFollowTrainPosition(out int col, out int row) { col = -1; row = -1; - foreach (IMovable vehicle in _movableLayout) + foreach (var vehicle in _movableLayout) { if (vehicle is Train { Follow: true } train) { @@ -127,6 +127,6 @@ public void Save(ISignalboxStorage storage) public void Reset() { - this.CurrentTrain = null; + CurrentTrain = null; } } diff --git a/Signalbox.Engine/Trains/TrainMovement.cs b/Signalbox.Engine/Trains/TrainMovement.cs index f86ae05..6d97ca4 100644 --- a/Signalbox.Engine/Trains/TrainMovement.cs +++ b/Signalbox.Engine/Trains/TrainMovement.cs @@ -28,8 +28,8 @@ public static double PointsToAngle(float x, float y) public static (float x, float y) AngleToPoints(double angle, float radius) { // Sin for Y, Cos for X, multiply them by the radius and we are done! - float y = (float)(radius * Math.Sin(angle)); - float x = (float)(radius * Math.Cos(angle)); + var y = (float)(radius * Math.Sin(angle)); + var x = (float)(radius * Math.Cos(angle)); return (x, y); } @@ -50,7 +50,7 @@ public static void MoveAroundCorner(TrainPosition position, int quadrantPosition { // Find the angle within the tracks circle using the current position // This *should* be perpendicular to angle - double currentAngle = TrainMovement.PointsToAngle(position.RelativeLeft - Math.Abs(quadrantPositionX), position.RelativeTop - Math.Abs(quadrantPositionY)); + var currentAngle = PointsToAngle(position.RelativeLeft - Math.Abs(quadrantPositionX), position.RelativeTop - Math.Abs(quadrantPositionY)); float distance; // In order to figure out if we are moving clockwise or counter-clockwise, look at the angle of the train @@ -59,23 +59,23 @@ public static void MoveAroundCorner(TrainPosition position, int quadrantPosition // We are facing left/up, so we move counter clockwise, with a minimum angle of 90 (currentAngle, distance) = MoveCounterClockwise(currentAngle, position.Distance, DegreeToRad(minimumAngle)); - position.Angle = (float)TrainMovement.RadToDegree(currentAngle) - 90.0f; + position.Angle = (float)RadToDegree(currentAngle) - 90.0f; } else { // We are NOT facing left/up, so we move clockwise, with a maximum angle of 180, Math.PI (currentAngle, distance) = MoveClockwise(currentAngle, position.Distance, DegreeToRad(maximumAngle)); - position.Angle = (float)TrainMovement.RadToDegree(currentAngle) + 90.0f; + position.Angle = (float)RadToDegree(currentAngle) + 90.0f; } position.Distance = distance; // Double check to keep our angle in range, this makes our angle checks easier!: - position.Angle = TrainMovement.KeepWithin0and360(position.Angle); + position.Angle = KeepWithin0and360(position.Angle); // Find our new position on the track - (position.RelativeLeft, position.RelativeTop) = TrainMovement.AngleToPoints(currentAngle, 0.5f); + (position.RelativeLeft, position.RelativeTop) = AngleToPoints(currentAngle, 0.5f); position.RelativeLeft += Math.Abs(quadrantPositionX); position.RelativeTop += Math.Abs(quadrantPositionY); @@ -112,23 +112,23 @@ public static void DoAnEdgeSnap(TrainPosition position) } } - public static void MoveLeftDown(TrainPosition position) => TrainMovement.MoveAroundCorner(position, 0, -1, 135, 315, 270, 360); + public static void MoveLeftDown(TrainPosition position) => MoveAroundCorner(position, 0, -1, 135, 315, 270, 360); - public static void MoveRightDown(TrainPosition position) => TrainMovement.MoveAroundCorner(position, -1, -1, 45, 225, 180, 270); + public static void MoveRightDown(TrainPosition position) => MoveAroundCorner(position, -1, -1, 45, 225, 180, 270); - public static void MoveRightUp(TrainPosition position) => TrainMovement.MoveAroundCorner(position, -1, 0, -45, 135, 90, 180); + public static void MoveRightUp(TrainPosition position) => MoveAroundCorner(position, -1, 0, -45, 135, 90, 180); - public static void MoveLeftUp(TrainPosition position) => TrainMovement.MoveAroundCorner(position, 0, 0, 225, 45, 0, 90); + public static void MoveLeftUp(TrainPosition position) => MoveAroundCorner(position, 0, 0, 225, 45, 0, 90); public static (double currentAngle, float distance) MoveCounterClockwise(double currentAngle, float distance, double minimumNewAngle) { if (currentAngle <= 0) currentAngle += Math.PI * 2.0; - double angleToMove = distance / Radius; + var angleToMove = distance / Radius; // If the angle to move is outside our limits, then only move as much as we can - double angleOver = currentAngle - angleToMove - minimumNewAngle; + var angleOver = currentAngle - angleToMove - minimumNewAngle; if (angleOver < -0.00001) { @@ -152,9 +152,9 @@ public static (double currentAngle, float distance) MoveClockwise(double current { if (currentAngle < 0) currentAngle += Math.PI * 2.0; - double angleToMove = distance / Radius; + var angleToMove = distance / Radius; - double angleOver = currentAngle + angleToMove - maximumNewAngle; + var angleOver = currentAngle + angleToMove - maximumNewAngle; if (angleOver > 0.00001) { @@ -183,7 +183,7 @@ public static void MoveVertical(TrainPosition position) if (position.Angle < 180f) { position.Angle = 90f; - float toGo = 1.0f - position.RelativeTop; + var toGo = 1.0f - position.RelativeTop; if (position.Distance < toGo) { @@ -199,7 +199,7 @@ public static void MoveVertical(TrainPosition position) else { position.Angle = 270f; - float toGo = position.RelativeTop; + var toGo = position.RelativeTop; if (position.Distance < toGo) { @@ -223,7 +223,7 @@ public static void MoveHorizontal(TrainPosition position) if (position.Angle < 90f || position.Angle > 270f) { position.Angle = 0f; - float toGo = 1.0f - position.RelativeLeft; + var toGo = 1.0f - position.RelativeLeft; if (position.Distance < toGo) { @@ -239,7 +239,7 @@ public static void MoveHorizontal(TrainPosition position) else { position.Angle = 180f; - float toGo = position.RelativeLeft; + var toGo = position.RelativeLeft; if (position.Distance < toGo) { @@ -257,12 +257,12 @@ public static void MoveHorizontal(TrainPosition position) public static IEnumerable GetNextSteps(ILayout layout, Train train, float distanceToMove) { TrainPosition? last = null; - float distance = distanceToMove; + var distance = distanceToMove; while (distance > 0.0f) { - TrainPosition position = last ?? train.GetPosition(); + var position = last ?? train.GetPosition(); - TrainPosition? newPosition = GetNextPosition(layout, position, distance); + var newPosition = GetNextPosition(layout, position, distance); if (newPosition != null) { last = newPosition; @@ -283,7 +283,7 @@ public static IEnumerable GetNextSteps(ILayout layout, Train trai return null; } - TrainPosition position = currentPosition.Clone(); + var position = currentPosition.Clone(); position.Distance = distance; track.Move(position); diff --git a/Signalbox.Engine/Trains/TrainNames.cs b/Signalbox.Engine/Trains/TrainNames.cs index 85a5dd5..0f7463d 100644 --- a/Signalbox.Engine/Trains/TrainNames.cs +++ b/Signalbox.Engine/Trains/TrainNames.cs @@ -4,7 +4,7 @@ internal static class TrainNames { public static string GetName(int seed) => s_names[Math.Abs(seed) % s_names.Length]; - private static readonly string[] s_names = new string[]{ + private static readonly string[] s_names = { "Test", }; } diff --git a/Signalbox.Engine/Trains/TrainPosition.cs b/Signalbox.Engine/Trains/TrainPosition.cs index 4ede8cf..c0f4591 100644 --- a/Signalbox.Engine/Trains/TrainPosition.cs +++ b/Signalbox.Engine/Trains/TrainPosition.cs @@ -11,18 +11,18 @@ public class TrainPosition public TrainPosition(float relativeLeft, float relativeTop, float angle, float distance) { - this.RelativeLeft = relativeLeft; - this.RelativeTop = relativeTop; - this.Angle = angle; - this.Distance = distance; + RelativeLeft = relativeLeft; + RelativeTop = relativeTop; + Angle = angle; + Distance = distance; } public TrainPosition(int column, int row, float relativeLeft, float relativeTop, float angle, float distance) : this(relativeLeft, relativeTop, angle, distance) { - this.Column = column; - this.Row = row; + Column = column; + Row = row; } - internal TrainPosition Clone() => new(this.Column, this.Row, this.RelativeLeft, this.RelativeTop, this.Angle, this.Distance); + internal TrainPosition Clone() => new(Column, Row, RelativeLeft, RelativeTop, Angle, Distance); } diff --git a/Signalbox.Engine/Trains/TrainSerializer.cs b/Signalbox.Engine/Trains/TrainSerializer.cs index 4e4e537..077e2d7 100644 --- a/Signalbox.Engine/Trains/TrainSerializer.cs +++ b/Signalbox.Engine/Trains/TrainSerializer.cs @@ -20,7 +20,7 @@ public bool TryDeserialize(string data, [NotNullWhen(true)] out IEntity? entity) return false; } - int i = 1; + var i = 1; entity = new Train(int.Parse(bits[i++])) { Angle = float.Parse(bits[i++]), diff --git a/Signalbox.Engine/Utilities/GameThreadTimer.cs b/Signalbox.Engine/Utilities/GameThreadTimer.cs index 1cce335..6646b57 100644 --- a/Signalbox.Engine/Utilities/GameThreadTimer.cs +++ b/Signalbox.Engine/Utilities/GameThreadTimer.cs @@ -45,12 +45,12 @@ private void ThreadLoop() } if (_threadLoopEnabled && _elapsedEventEnabled) { - long time = _stopwatch.ElapsedMilliseconds; - this.TimeSinceLastTick = time - _lastTick; + var time = _stopwatch.ElapsedMilliseconds; + TimeSinceLastTick = time - _lastTick; _lastTick = time; Elapsed?.Invoke(this, EventArgs.Empty); - _nextInvoke = time + (int)this.Interval; + _nextInvoke = time + (int)Interval; } } } diff --git a/Signalbox.Engine/Utilities/OrderAttribute.cs b/Signalbox.Engine/Utilities/OrderAttribute.cs index 84108f9..d388089 100644 --- a/Signalbox.Engine/Utilities/OrderAttribute.cs +++ b/Signalbox.Engine/Utilities/OrderAttribute.cs @@ -7,6 +7,6 @@ public sealed class OrderAttribute : Attribute public OrderAttribute(int order) { - this.Order = order; + Order = order; } } diff --git a/Signalbox.Instrumentation/Signalbox.Instrumentation.csproj b/Signalbox.Instrumentation/Signalbox.Instrumentation.csproj index 132c02c..2311f2c 100644 --- a/Signalbox.Instrumentation/Signalbox.Instrumentation.csproj +++ b/Signalbox.Instrumentation/Signalbox.Instrumentation.csproj @@ -6,4 +6,18 @@ enable + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + all + runtime; build; native; contentfiles; analyzers + + + diff --git a/Signalbox.Instrumentation/Stats/AveragedStat.cs b/Signalbox.Instrumentation/Stats/AveragedStat.cs index a2bbcfd..f658534 100644 --- a/Signalbox.Instrumentation/Stats/AveragedStat.cs +++ b/Signalbox.Instrumentation/Stats/AveragedStat.cs @@ -10,16 +10,16 @@ public AveragedStat(int sampleCount) } protected void SetValue(double value) { - if (this.Value == null) + if (Value == null) { - this.Value = value; + Value = value; } else { - this.Value = (this.Value * (_sampleCount - 1) + value) / _sampleCount; + Value = (Value * (_sampleCount - 1) + value) / _sampleCount; } } public abstract string GetDescription(); - public bool ShouldShow() => this.Value.HasValue; + public bool ShouldShow() => Value.HasValue; } diff --git a/Signalbox.Instrumentation/Stats/CountStat.cs b/Signalbox.Instrumentation/Stats/CountStat.cs index 999a15b..103ff0f 100644 --- a/Signalbox.Instrumentation/Stats/CountStat.cs +++ b/Signalbox.Instrumentation/Stats/CountStat.cs @@ -8,8 +8,8 @@ public CountStat(string nameOfThingYouAreCounting) _thing = nameOfThingYouAreCounting; } public int Value { get; private set; } - public void Add() => this.Value++; - public void Set(int value) => this.Value = value; - public string GetDescription() => this.Value + ' ' + _thing; + public void Add() => Value++; + public void Set(int value) => Value = value; + public string GetDescription() => Value + ' ' + _thing; public bool ShouldShow() => true; } diff --git a/Signalbox.Instrumentation/Stats/ElapsedMillisecondsTimedStat.cs b/Signalbox.Instrumentation/Stats/ElapsedMillisecondsTimedStat.cs index fef5cdb..92658ed 100644 --- a/Signalbox.Instrumentation/Stats/ElapsedMillisecondsTimedStat.cs +++ b/Signalbox.Instrumentation/Stats/ElapsedMillisecondsTimedStat.cs @@ -1,8 +1,9 @@ using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; namespace Signalbox.Instrumentation.Stats; -[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1001:Types that own disposable fields should be disposable", Justification = "Dispose is used to measure")] +[SuppressMessage("Design", "CA1001:Types that own disposable fields should be disposable", Justification = "Dispose is used to measure")] public class ElapsedMillisecondsTimedStat : AveragedStat { private readonly Stopwatch _sw; @@ -27,14 +28,14 @@ public IDisposable Measure() } public override string GetDescription() { - if (this.Value == null) + if (Value == null) { return "null"; } - if (this.Value < 0.01) + if (Value < 0.01) { return "< 0.01ms"; } - return Math.Round(this.Value ?? 0, 2).ToString("0.00") + "ms"; + return Math.Round(Value ?? 0, 2).ToString("0.00") + "ms"; } } diff --git a/Signalbox.Instrumentation/Stats/InformationStat.cs b/Signalbox.Instrumentation/Stats/InformationStat.cs index f85c1aa..4518d8d 100644 --- a/Signalbox.Instrumentation/Stats/InformationStat.cs +++ b/Signalbox.Instrumentation/Stats/InformationStat.cs @@ -3,6 +3,6 @@ public class InformationStat : IStat { public string Information { get; set; } = ""; - public string GetDescription() => this.Information; - public bool ShouldShow() => !string.IsNullOrWhiteSpace(this.Information); + public string GetDescription() => Information; + public bool ShouldShow() => !string.IsNullOrWhiteSpace(Information); } diff --git a/Signalbox.Instrumentation/Stats/PerSecondTimedStat.cs b/Signalbox.Instrumentation/Stats/PerSecondTimedStat.cs index 21dfa38..164d62d 100644 --- a/Signalbox.Instrumentation/Stats/PerSecondTimedStat.cs +++ b/Signalbox.Instrumentation/Stats/PerSecondTimedStat.cs @@ -22,14 +22,14 @@ public void Update() public override string GetDescription() { - if (this.Value == null) + if (Value == null) { return "null"; } - if (this.Value < 0.01) + if (Value < 0.01) { return "< 0.01"; } - return Math.Round(this.Value ?? 0, 2).ToString(); + return Math.Round(Value ?? 0, 2).ToString(); } } diff --git a/Signalbox.Rendering.Skia/RenderingExtensions.cs b/Signalbox.Rendering.Skia/RenderingExtensions.cs index bc97216..c050205 100644 --- a/Signalbox.Rendering.Skia/RenderingExtensions.cs +++ b/Signalbox.Rendering.Skia/RenderingExtensions.cs @@ -1,4 +1,5 @@ using Signalbox.Rendering.Drawing; +using Signalbox.Rendering.Skia.Assets; using Signalbox.Rendering.UIFramework; using SkiaSharp; @@ -9,19 +10,19 @@ public static class RenderingExtensions public static SKPicture ToSkia(this Picture picture) => picture switch { - Picture.Left => Assets.Svg_caret_left.Picture, - Picture.Right => Assets.Svg_caret_right.Picture, - Picture.Backward => Assets.Svg_backward.Picture, - Picture.Forward => Assets.Svg_forward.Picture, - Picture.Eye => Assets.Svg_eye.Picture, - Picture.Trash => Assets.Svg_trash_alt.Picture, - Picture.Play => Assets.Svg_play.Picture, - Picture.Pause => Assets.Svg_pause.Picture, - Picture.Cross => Assets.Svg_times.Picture, - Picture.Tools => Assets.Svg_tools.Picture, - Picture.Eraser => Assets.Svg_eraser.Picture, - Picture.Plus => Assets.Svg_plus_square.Picture, - Picture.Minus => Assets.Svg_minus_square.Picture, + Picture.Left => Svg_caret_left.Picture, + Picture.Right => Svg_caret_right.Picture, + Picture.Backward => Svg_backward.Picture, + Picture.Forward => Svg_forward.Picture, + Picture.Eye => Svg_eye.Picture, + Picture.Trash => Svg_trash_alt.Picture, + Picture.Play => Svg_play.Picture, + Picture.Pause => Svg_pause.Picture, + Picture.Cross => Svg_times.Picture, + Picture.Tools => Svg_tools.Picture, + Picture.Eraser => Svg_eraser.Picture, + Picture.Plus => Svg_plus_square.Picture, + Picture.Minus => Svg_minus_square.Picture, _ => throw new InvalidOperationException($"No idea what picture you want me to draw: {picture}") }; diff --git a/Signalbox.Rendering.Skia/SKCanvasWrapper.cs b/Signalbox.Rendering.Skia/SKCanvasWrapper.cs index 3bf1dc8..fa22697 100644 --- a/Signalbox.Rendering.Skia/SKCanvasWrapper.cs +++ b/Signalbox.Rendering.Skia/SKCanvasWrapper.cs @@ -14,15 +14,15 @@ public class SKCanvasWrapper : ICanvas IsDither = false }; - private readonly SkiaSharp.SKCanvas _canvas; + private readonly SKCanvas _canvas; - public SKCanvasWrapper(SkiaSharp.SKCanvas canvas) + public SKCanvasWrapper(SKCanvas canvas) { _canvas = canvas; } private static SKPaint GetSKPaint(PaintBrush paint) { - if (!s_paintCache.TryGetValue(paint, out SKPaint? skPaint)) + if (!s_paintCache.TryGetValue(paint, out var skPaint)) { skPaint = paint.ToSkia(); s_paintCache.Add(paint, skPaint); @@ -46,7 +46,7 @@ public void DrawPicture(Picture picture, float x, float y, float size) var skPicture = picture.ToSkia(); _canvas.Save(); - float scaleFactor = size / Math.Max(skPicture.CullRect.Width, skPicture.CullRect.Height); + var scaleFactor = size / Math.Max(skPicture.CullRect.Width, skPicture.CullRect.Height); _canvas.Scale(scaleFactor, scaleFactor, x, y); _canvas.DrawPicture(picture.ToSkia()); _canvas.Restore(); diff --git a/Signalbox.Rendering.Skia/SKContextWrapper.cs b/Signalbox.Rendering.Skia/SKContextWrapper.cs index 8b2161f..838e6dd 100644 --- a/Signalbox.Rendering.Skia/SKContextWrapper.cs +++ b/Signalbox.Rendering.Skia/SKContextWrapper.cs @@ -9,6 +9,6 @@ public class SKContextWrapper : IContext public SKContextWrapper(GRContext context) { - this.Context = context; + Context = context; } } diff --git a/Signalbox.Rendering.Skia/SKImageFactory.cs b/Signalbox.Rendering.Skia/SKImageFactory.cs index d173993..6f1553c 100644 --- a/Signalbox.Rendering.Skia/SKImageFactory.cs +++ b/Signalbox.Rendering.Skia/SKImageFactory.cs @@ -16,7 +16,7 @@ public bool SetContext(IContext context) { if (context is SKContextWrapper skContext) { - bool initalSet = _context == null; + var initalSet = _context == null; _context = skContext.Context; return initalSet; } diff --git a/Signalbox.Rendering.Skia/Signalbox.Rendering.Skia.csproj b/Signalbox.Rendering.Skia/Signalbox.Rendering.Skia.csproj index c9ebf3b..f7094e2 100644 --- a/Signalbox.Rendering.Skia/Signalbox.Rendering.Skia.csproj +++ b/Signalbox.Rendering.Skia/Signalbox.Rendering.Skia.csproj @@ -19,4 +19,18 @@ + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + all + runtime; build; native; contentfiles; analyzers + + + diff --git a/Signalbox.Rendering/Drawing/ImageCache.cs b/Signalbox.Rendering/Drawing/ImageCache.cs index 3546e87..786fd72 100644 --- a/Signalbox.Rendering/Drawing/ImageCache.cs +++ b/Signalbox.Rendering/Drawing/ImageCache.cs @@ -60,7 +60,7 @@ public void SetDirtyAll(IEnumerable keys) { lock (_cacheLock) { - foreach (object key in keys) + foreach (var key in keys) { SetDirty(key); } @@ -72,13 +72,13 @@ public void Set(object key, IImage image) lock (_cacheLock) { // If we have anything waiting to be disposed, dispose it - if (_disposeBuffer.TryGetValue(key, out IImage? oldImage)) + if (_disposeBuffer.TryGetValue(key, out var oldImage)) { oldImage.Dispose(); } // Move the current image into the dispose buffer, this way if anyone is still holding on // to it we won't be disposing it out from under them - if (_imageBuffer.TryGetValue(key, out IImage? previousImage)) + if (_imageBuffer.TryGetValue(key, out var previousImage)) { _disposeBuffer[key] = previousImage; } @@ -91,11 +91,11 @@ public void Dispose() { lock (_cacheLock) { - foreach (IImage image in _disposeBuffer.Values) + foreach (var image in _disposeBuffer.Values) { image.Dispose(); } - foreach (IImage image in _imageBuffer.Values) + foreach (var image in _imageBuffer.Values) { image.Dispose(); } diff --git a/Signalbox.Rendering/Drawing/Records.cs b/Signalbox.Rendering/Drawing/Records.cs index 3812f74..437abb8 100644 --- a/Signalbox.Rendering/Drawing/Records.cs +++ b/Signalbox.Rendering/Drawing/Records.cs @@ -25,7 +25,8 @@ private static Color HtmlToArgb(string htmlColor) Convert.ToByte(htmlColor.Substring(3, 2), 16), Convert.ToByte(htmlColor.Substring(5, 2), 16)); } - else if (htmlColor.Length == 9) + + if (htmlColor.Length == 9) { return new( Convert.ToByte(htmlColor.Substring(1, 2), 16), diff --git a/Signalbox.Rendering/LayerRenderer/GridRenderer.cs b/Signalbox.Rendering/LayerRenderer/GridRenderer.cs index 194ed0f..1595b8d 100644 --- a/Signalbox.Rendering/LayerRenderer/GridRenderer.cs +++ b/Signalbox.Rendering/LayerRenderer/GridRenderer.cs @@ -21,12 +21,12 @@ public void Render(ICanvas canvas, int width, int height, IPixelMapper pixelMapp Style = PaintStyle.Stroke }; - for (int x = pixelMapper.ViewPortX; x < pixelMapper.ViewPortWidth + 1; x += pixelMapper.CellSize) + for (var x = pixelMapper.ViewPortX; x < pixelMapper.ViewPortWidth + 1; x += pixelMapper.CellSize) { canvas.DrawLine(x, 0, x, height, grid); } - for (int y = pixelMapper.ViewPortY; y < pixelMapper.ViewPortHeight + 1; y += pixelMapper.CellSize) + for (var y = pixelMapper.ViewPortY; y < pixelMapper.ViewPortHeight + 1; y += pixelMapper.CellSize) { canvas.DrawLine(0, y, width, y, grid); } diff --git a/Signalbox.Rendering/LayerRenderer/TileLayerRenderer.cs b/Signalbox.Rendering/LayerRenderer/TileLayerRenderer.cs index a3e65c9..f287060 100644 --- a/Signalbox.Rendering/LayerRenderer/TileLayerRenderer.cs +++ b/Signalbox.Rendering/LayerRenderer/TileLayerRenderer.cs @@ -21,16 +21,16 @@ public TileLayerRenderer(IMapRenderer mapRenderer) public void Render(ICanvas canvas, int width, int height, IPixelMapper pixelMapper) { - (int topLeftColumn, int topLeftRow) = pixelMapper.ViewPortPixelsToCoords(0, 0); - (int bottomRightColumn, int bottomRightRow) = pixelMapper.ViewPortPixelsToCoords(pixelMapper.ViewPortWidth, pixelMapper.ViewPortHeight); + var (topLeftColumn, topLeftRow) = pixelMapper.ViewPortPixelsToCoords(0, 0); + var (bottomRightColumn, bottomRightRow) = pixelMapper.ViewPortPixelsToCoords(pixelMapper.ViewPortWidth, pixelMapper.ViewPortHeight); bottomRightColumn += 1; bottomRightRow += 1; var source = new Rectangle(topLeftColumn, topLeftRow, bottomRightColumn, bottomRightRow); - (int destinationTopLeftX, int destinationTopLeftY, _) = pixelMapper.CoordsToViewPortPixels(topLeftColumn, topLeftRow); - (int destinationBottomRightX, int destinationBottomRightY, _) = pixelMapper.CoordsToViewPortPixels(bottomRightColumn, bottomRightRow); + var (destinationTopLeftX, destinationTopLeftY, _) = pixelMapper.CoordsToViewPortPixels(topLeftColumn, topLeftRow); + var (destinationBottomRightX, destinationBottomRightY, _) = pixelMapper.CoordsToViewPortPixels(bottomRightColumn, bottomRightRow); var destination = new Rectangle(destinationTopLeftX, destinationTopLeftY, destinationBottomRightX, destinationBottomRightY); diff --git a/Signalbox.Rendering/LayerRenderer/TrackLayoutRenderer.cs b/Signalbox.Rendering/LayerRenderer/TrackLayoutRenderer.cs index 9e17cc4..caa56d6 100644 --- a/Signalbox.Rendering/LayerRenderer/TrackLayoutRenderer.cs +++ b/Signalbox.Rendering/LayerRenderer/TrackLayoutRenderer.cs @@ -12,6 +12,6 @@ public class TrackLayoutRenderer : StaticEntityCollectionRenderer public TrackLayoutRenderer(ILayout layout, IEnumerable> renderers, IImageFactory imageFactory, IImageCache imageCache) : base(layout, renderers, imageFactory, imageCache) { - this.Name = "Tracks"; + Name = "Tracks"; } } diff --git a/Signalbox.Rendering/LayerRenderer/TrainsRenderer.cs b/Signalbox.Rendering/LayerRenderer/TrainsRenderer.cs index f872a9b..7e8b289 100644 --- a/Signalbox.Rendering/LayerRenderer/TrainsRenderer.cs +++ b/Signalbox.Rendering/LayerRenderer/TrainsRenderer.cs @@ -3,7 +3,6 @@ using Signalbox.Engine.Utilities; using Signalbox.Rendering.Drawing; using Signalbox.Rendering.LayerRenderer.Bases; -using Signalbox.Rendering.Trains; namespace Signalbox.Rendering.LayerRenderer; diff --git a/Signalbox.Rendering/Map/MapRenderer.cs b/Signalbox.Rendering/Map/MapRenderer.cs index 242df56..5a25427 100644 --- a/Signalbox.Rendering/Map/MapRenderer.cs +++ b/Signalbox.Rendering/Map/MapRenderer.cs @@ -25,15 +25,15 @@ public IImage GetMapImage() { if (_imageCache.IsDirty(this)) { - int width = _pixelMapper.Columns; - int _height = _pixelMapper.Rows; + var width = _pixelMapper.Columns; + var _height = _pixelMapper.Rows; - using IImageCanvas textureImage = _imageFactory.CreateImageCanvas(width, _height); + using var textureImage = _imageFactory.CreateImageCanvas(width, _height); - foreach (global::Signalbox.Engine.Map.Tile tile in _map) + foreach (var tile in _map) { - Color colour = GetTileColour(tile); - PaintBrush paint = GetPaint(colour); + var colour = GetTileColour(tile); + var paint = GetPaint(colour); textureImage.Canvas.DrawRect(tile.Column, tile.Row, 1, 1, paint); } @@ -52,5 +52,5 @@ private static PaintBrush GetPaint(Color colour) Color = colour }; - public static Color GetTileColour(global::Signalbox.Engine.Map.Tile tile) => string.IsNullOrWhiteSpace(tile.Content) ? Colors.Empty : Colors.Black; + public static Color GetTileColour(Tile tile) => string.IsNullOrWhiteSpace(tile.Content) ? Colors.Empty : Colors.Black; } diff --git a/Signalbox.Rendering/PixelMapper.cs b/Signalbox.Rendering/PixelMapper.cs index 571a77b..52ccaea 100644 --- a/Signalbox.Rendering/PixelMapper.cs +++ b/Signalbox.Rendering/PixelMapper.cs @@ -15,8 +15,8 @@ public class PixelMapper : IPixelMapper, IInitializeAsync, ISignalboxState public int Columns => _columns; public int Rows => _rows; - public int MaxGridWidth => _columns * this.CellSize; - public int MaxGridHeight => _rows * this.CellSize; + public int MaxGridWidth => _columns * CellSize; + public int MaxGridHeight => _rows * CellSize; public float GameScale { get; private set; } = 1.0f; public int ViewPortX { get; private set; } @@ -24,7 +24,7 @@ public class PixelMapper : IPixelMapper, IInitializeAsync, ISignalboxState public int ViewPortWidth { get; private set; } public int ViewPortHeight { get; private set; } - public int CellSize => (int)(40 * this.GameScale); + public int CellSize => (int)(40 * GameScale); public event EventHandler? ViewPortChanged; @@ -38,8 +38,8 @@ public Task InitializeAsync(int columns, int rows) public void SetViewPortSize(int width, int height) { - this.ViewPortWidth = width; - this.ViewPortHeight = height; + ViewPortWidth = width; + ViewPortHeight = height; if (_firstViewPortAdjustment && _initialViewPortX.HasValue && _initialViewPortY.HasValue) { @@ -47,7 +47,7 @@ public void SetViewPortSize(int width, int height) } else if (_firstViewPortAdjustment) { - SetViewPort((this.MaxGridWidth - width) / 2, (this.MaxGridHeight - height) / 2); + SetViewPort((MaxGridWidth - width) / 2, (MaxGridHeight - height) / 2); } else { @@ -59,12 +59,12 @@ public void SetViewPortSize(int width, int height) public void SetViewPort(int x, int y) { - int oldX = this.ViewPortX; - int oldY = this.ViewPortY; - this.ViewPortX = Math.Max(Math.Min(-x, 0), -1 * (this.MaxGridWidth - this.ViewPortWidth)); - this.ViewPortY = Math.Max(Math.Min(-y, 0), -1 * (this.MaxGridHeight - this.ViewPortHeight)); + var oldX = ViewPortX; + var oldY = ViewPortY; + ViewPortX = Math.Max(Math.Min(-x, 0), -1 * (MaxGridWidth - ViewPortWidth)); + ViewPortY = Math.Max(Math.Min(-y, 0), -1 * (MaxGridHeight - ViewPortHeight)); - if (this.ViewPortX != oldX || this.ViewPortY != oldY) + if (ViewPortX != oldX || ViewPortY != oldY) { ViewPortChanged?.Invoke(this, EventArgs.Empty); } @@ -72,95 +72,96 @@ public void SetViewPort(int x, int y) public void AdjustViewPort(int x, int y) { - SetViewPort(-1 * (this.ViewPortX + x), -1 * (this.ViewPortY + y)); + SetViewPort(-1 * (ViewPortX + x), -1 * (ViewPortY + y)); } public (int, int) ViewPortPixelsToCoords(int x, int y) { - return ((x - this.ViewPortX) / this.CellSize, (y - this.ViewPortY) / this.CellSize); + return ((x - ViewPortX) / CellSize, (y - ViewPortY) / CellSize); } public (int, int, bool) CoordsToViewPortPixels(int column, int row) { - int x = (column * this.CellSize) + this.ViewPortX; - int y = (row * this.CellSize) + this.ViewPortY; - bool onScreen = x > -this.CellSize && - y > -this.CellSize && - x <= this.ViewPortWidth && - y <= this.ViewPortHeight; + var x = (column * CellSize) + ViewPortX; + var y = (row * CellSize) + ViewPortY; + var onScreen = x > -CellSize && + y > -CellSize && + x <= ViewPortWidth && + y <= ViewPortHeight; return (x, y, onScreen); } public (int, int) WorldPixelsToCoords(int x, int y) { - return (x / this.CellSize, y / this.CellSize); + return (x / CellSize, y / CellSize); } public (int, int) CoordsToWorldPixels(int column, int row) { - return (column * this.CellSize, row * this.CellSize); + return (column * CellSize, row * CellSize); } public IPixelMapper Snapshot() { - return new PixelMapper() + return new PixelMapper { _columns = _columns, _rows = _rows, - ViewPortX = this.ViewPortX, - ViewPortY = this.ViewPortY, - ViewPortHeight = this.ViewPortHeight, - ViewPortWidth = this.ViewPortWidth, - GameScale = this.GameScale + ViewPortX = ViewPortX, + ViewPortY = ViewPortY, + ViewPortHeight = ViewPortHeight, + ViewPortWidth = ViewPortWidth, + GameScale = GameScale }; } private (float, float) GetScaledViewPortSize() - => GetScaledViewPortSize(this.GameScale); + => GetScaledViewPortSize(GameScale); private (float, float) GetScaledViewPortSize(float scale) - => (this.ViewPortWidth / scale, - this.ViewPortHeight / scale); + => (ViewPortWidth / scale, + ViewPortHeight / scale); public bool AdjustGameScale(float delta) { - float newGameScale = this.GameScale * delta; + var newGameScale = GameScale * delta; // Check to see if it is TOO FAR! if (newGameScale < 0.1 || - this.MaxGridWidth / this.GameScale * newGameScale < this.ViewPortWidth || - this.MaxGridHeight / this.GameScale * newGameScale < this.ViewPortHeight) + MaxGridWidth / GameScale * newGameScale < ViewPortWidth || + MaxGridHeight / GameScale * newGameScale < ViewPortHeight) { return false; } - else if (newGameScale > 5) + + if (newGameScale > 5) { newGameScale = 5.0f; } - if (this.GameScale == newGameScale) + if (GameScale == newGameScale) { return false; } // Viewport X & Y will be negative, as they are canvas transations, so swap em! - float currentX = -this.ViewPortX / this.GameScale; - float currentY = -this.ViewPortY / this.GameScale; + var currentX = -ViewPortX / GameScale; + var currentY = -ViewPortY / GameScale; - (float svpWidth, float svpHeight) = GetScaledViewPortSize(); + var (svpWidth, svpHeight) = GetScaledViewPortSize(); - float currentCenterX = currentX + svpWidth / 2.0f; - float currentCenterY = currentY + svpHeight / 2.0f; + var currentCenterX = currentX + svpWidth / 2.0f; + var currentCenterY = currentY + svpHeight / 2.0f; - (float newSvpWidth, float newSvpHeight) = GetScaledViewPortSize(newGameScale); + var (newSvpWidth, newSvpHeight) = GetScaledViewPortSize(newGameScale); - float newX = currentCenterX - newSvpWidth / 2.0f; - float newY = currentCenterY - newSvpHeight / 2.0f; + var newX = currentCenterX - newSvpWidth / 2.0f; + var newY = currentCenterY - newSvpHeight / 2.0f; - this.ViewPortX = -(int)Math.Round(newX * newGameScale); - this.ViewPortY = -(int)Math.Round(newY * newGameScale); + ViewPortX = -(int)Math.Round(newX * newGameScale); + ViewPortY = -(int)Math.Round(newY * newGameScale); - this.GameScale = newGameScale; + GameScale = newGameScale; AdjustViewPort(0, 0); @@ -193,14 +194,14 @@ public bool Load(ISignalboxStorage storage) _initialViewPortX = -x; _initialViewPortY = -y; - this.GameScale = gameScale; + GameScale = gameScale; return true; } public void Save(ISignalboxStorage storage) { - storage.Write(nameof(PixelMapper), $"{this.ViewPortX},{this.ViewPortY},{this.GameScale}"); + storage.Write(nameof(PixelMapper), $"{ViewPortX},{ViewPortY},{GameScale}"); } public void Reset() diff --git a/Signalbox.Rendering/PointerTool.cs b/Signalbox.Rendering/PointerTool.cs index 0c6751e..d1bb6a1 100644 --- a/Signalbox.Rendering/PointerTool.cs +++ b/Signalbox.Rendering/PointerTool.cs @@ -41,7 +41,7 @@ public void Execute(int column, int row, ExecuteInfo info) } else { - if (_trackLayout.TryGet(column, row, out Track? track)) + if (_trackLayout.TryGet(column, row, out var track)) { track.NextState(); } diff --git a/Signalbox.Rendering/Signalbox.Rendering.csproj b/Signalbox.Rendering/Signalbox.Rendering.csproj index dec12a6..a9f8e03 100644 --- a/Signalbox.Rendering/Signalbox.Rendering.csproj +++ b/Signalbox.Rendering/Signalbox.Rendering.csproj @@ -11,4 +11,18 @@ + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + all + runtime; build; native; contentfiles; analyzers + + + diff --git a/Signalbox.Rendering/Signalbox/Signalbox.cs b/Signalbox.Rendering/Signalbox/Signalbox.cs index a5f6382..68674ad 100644 --- a/Signalbox.Rendering/Signalbox/Signalbox.cs +++ b/Signalbox.Rendering/Signalbox/Signalbox.cs @@ -47,11 +47,11 @@ public Signalbox(ISignalboxManager signalboxManager, _screens = screens; _imageCache = imageCache; _initializers = initializers; - foreach (IScreen screen in _screens) + foreach (var screen in _screens) { screen.Changed += (s, e) => _imageCache.SetDirty(screen); } - foreach (ICachableLayerRenderer renderer in _boardRenderers.OfType()) + foreach (var renderer in _boardRenderers.OfType()) { renderer.Changed += (s, e) => _imageCache.SetDirty(renderer); } @@ -94,7 +94,7 @@ public void SetSize(int width, int height) _imageCache.SetDirtyAll(_screens); - (int columns, int rows) = _pixelMapper.ViewPortPixelsToCoords(width, height); + var (columns, rows) = _pixelMapper.ViewPortPixelsToCoords(width, height); columns = Math.Max(columns, 1); rows = Math.Max(rows, 1); @@ -135,14 +135,14 @@ public void Render(ICanvas canvas) canvas.Clear(Colors.White); - IPixelMapper pixelMapper = _pixelMapper.Snapshot(); + var pixelMapper = _pixelMapper.Snapshot(); using (canvas.Scope()) { RenderFrame(canvas, pixelMapper); } - foreach (IScreen screen in _screens) + foreach (var screen in _screens) { using (_screenDrawTimes[screen].Measure()) { @@ -159,7 +159,7 @@ private void RenderFrame(ICanvas canvas, IPixelMapper pixelMapper) using (_skiaDrawTime.Measure()) using (canvas.Scope()) { - foreach (ILayerRenderer renderer in _boardRenderers) + foreach (var renderer in _boardRenderers) { if (!renderer.Enabled) { @@ -183,7 +183,7 @@ private void RenderLayer(ICanvas canvas, IPixelMapper pixelMapper, ILayerRendere { using (_renderCacheDrawTimes[renderer].Measure()) { - using IImageCanvas imageCanvas = _imageFactory.CreateImageCanvas(_width, _height); + using var imageCanvas = _imageFactory.CreateImageCanvas(_width, _height); renderer.Render(imageCanvas.Canvas, _width, _height, pixelMapper); _imageCache.Set(renderer, imageCanvas.Render()); } @@ -207,13 +207,13 @@ public void AdjustViewPortIfNecessary() { if (_signalboxManager.BuildMode) return; - if (!_trainManager.TryGetFollowTrainPosition(out int col, out int row)) return; + if (!_trainManager.TryGetFollowTrainPosition(out var col, out var row)) return; - (int x, int y, _) = _pixelMapper.CoordsToViewPortPixels(col, row); + var (x, y, _) = _pixelMapper.CoordsToViewPortPixels(col, row); double easing = 10; - int adjustX = Convert.ToInt32(((_pixelMapper.ViewPortWidth / 2) - x) / easing); - int adjustY = Convert.ToInt32(((_pixelMapper.ViewPortHeight / 2) - y) / easing); + var adjustX = Convert.ToInt32(((_pixelMapper.ViewPortWidth / 2) - x) / easing); + var adjustY = Convert.ToInt32(((_pixelMapper.ViewPortHeight / 2) - y) / easing); if (adjustX != 0 || adjustY != 0) { diff --git a/Signalbox.Rendering/Signalbox/ZoomHandler.cs b/Signalbox.Rendering/Signalbox/ZoomHandler.cs index f2d094b..53e3b46 100644 --- a/Signalbox.Rendering/Signalbox/ZoomHandler.cs +++ b/Signalbox.Rendering/Signalbox/ZoomHandler.cs @@ -18,7 +18,7 @@ public ZoomHandler(IPixelMapper pixelMapper) public bool HandlePointerAction(int x, int y, int width, int height, PointerAction action) { - bool didAdjust = false; + var didAdjust = false; if (action == PointerAction.ZoomIn) { didAdjust = _pixelMapper.AdjustGameScale(ZoomInDelta); diff --git a/Signalbox.Rendering/StaticEntityRenderer/StaticEntityCollectionRenderer.cs b/Signalbox.Rendering/StaticEntityRenderer/StaticEntityCollectionRenderer.cs index cc8e744..d89f49b 100644 --- a/Signalbox.Rendering/StaticEntityRenderer/StaticEntityCollectionRenderer.cs +++ b/Signalbox.Rendering/StaticEntityRenderer/StaticEntityCollectionRenderer.cs @@ -37,7 +37,7 @@ public void Render(ICanvas canvas, int width, int height, IPixelMapper pixelMapp _lastCellSize = pixelMapper.CellSize; } - foreach (T entity in _layout) + foreach (var entity in _layout) { var renderer = _renderers.FirstOrDefault(r => r.ShouldRender(entity)); if (renderer is null) @@ -46,19 +46,19 @@ public void Render(ICanvas canvas, int width, int height, IPixelMapper pixelMapp continue; } - (int x, int y, bool onScreen) = pixelMapper.CoordsToViewPortPixels(entity.Column, entity.Row); + var (x, y, onScreen) = pixelMapper.CoordsToViewPortPixels(entity.Column, entity.Row); if (!onScreen) { continue; } - string key = $"{entity.GetType().Name}.{entity.Identifier}"; + var key = $"{entity.GetType().Name}.{entity.Identifier}"; if (_imageCache.IsDirty(key)) { - using IImageCanvas imageCanvas = _imageFactory.CreateImageCanvas(pixelMapper.CellSize, pixelMapper.CellSize); + using var imageCanvas = _imageFactory.CreateImageCanvas(pixelMapper.CellSize, pixelMapper.CellSize); - float scale = pixelMapper.CellSize / 100.0f; + var scale = pixelMapper.CellSize / 100.0f; imageCanvas.Canvas.Scale(scale, scale); diff --git a/Signalbox.Rendering/Tracks/SignalRenderer.cs b/Signalbox.Rendering/Tracks/SignalRenderer.cs index 004b168..6ba0107 100644 --- a/Signalbox.Rendering/Tracks/SignalRenderer.cs +++ b/Signalbox.Rendering/Tracks/SignalRenderer.cs @@ -53,7 +53,7 @@ private static IPath BuildLightPath(IPathFactory pathFactory) { const int halfLightSpread = LightSpread / 2; - IPath path = pathFactory.Create(); + var path = pathFactory.Create(); path.LineTo(-LightLength, -halfLightSpread); path.ConicTo(-LightCurveLength, 0, -LightLength, halfLightSpread, 0.75f); diff --git a/Signalbox.Rendering/Tracks/SingleTrackRenderer.cs b/Signalbox.Rendering/Tracks/SingleTrackRenderer.cs index f4e3234..0031fb0 100644 --- a/Signalbox.Rendering/Tracks/SingleTrackRenderer.cs +++ b/Signalbox.Rendering/Tracks/SingleTrackRenderer.cs @@ -76,8 +76,6 @@ public void DrawSingleTrack(ICanvas canvas, SingleTrack track) case SingleTrackDirection.LeftDown: DrawCorner(canvas, track); break; - default: - break; } } diff --git a/Signalbox.Rendering/Tracks/TrackParameters.cs b/Signalbox.Rendering/Tracks/TrackParameters.cs index c1cf42b..9dea82c 100644 --- a/Signalbox.Rendering/Tracks/TrackParameters.cs +++ b/Signalbox.Rendering/Tracks/TrackParameters.cs @@ -3,7 +3,7 @@ public class TrackParameters : ITrackParameters { public int NumPlanks { get; } = 3; - public int NumCornerPlanks => this.NumPlanks + 1; + public int NumCornerPlanks => NumPlanks + 1; public float PlankLength { get; } = 65; public float PlankWidth { get; } = 10.0f; diff --git a/Signalbox.Rendering/Tracks/TrackPathBuilder.cs b/Signalbox.Rendering/Tracks/TrackPathBuilder.cs index f91a86f..bda2c07 100644 --- a/Signalbox.Rendering/Tracks/TrackPathBuilder.cs +++ b/Signalbox.Rendering/Tracks/TrackPathBuilder.cs @@ -23,7 +23,7 @@ public TrackPathBuilder(ITrackParameters trackParameters, IPathFactory pathFacto } public IPath BuildCornerTrackPath() { - IPath trackPath = _pathFactory.Create(); + var trackPath = _pathFactory.Create(); trackPath.MoveTo(0, _innerTrackOffset); trackPath.ConicTo(_innerTrackOffset, _innerTrackOffset, _innerTrackOffset, 0, 0.75f); @@ -35,7 +35,7 @@ public IPath BuildCornerTrackPath() public IPath BuildHorizontalTrackPath() { - IPath trackPath = _pathFactory.Create(); + var trackPath = _pathFactory.Create(); trackPath.MoveTo(0, _innerTrackOffset); trackPath.LineTo(100.0f, _innerTrackOffset); @@ -47,13 +47,13 @@ public IPath BuildHorizontalTrackPath() public IPath BuildHorizontalPlankPath() { - float plankGap = 100.0f / _trackParameters.NumPlanks; + var plankGap = 100.0f / _trackParameters.NumPlanks; - IPath path = _pathFactory.Create(); + var path = _pathFactory.Create(); - for (int i = 1; i < _trackParameters.NumPlanks + 1; i++) + for (var i = 1; i < _trackParameters.NumPlanks + 1; i++) { - float pos = (i * plankGap) - (plankGap / 2); + var pos = (i * plankGap) - (plankGap / 2); path.MoveTo(pos, _innerPlankOffset); path.LineTo(pos, _outerPlankOffset); @@ -66,18 +66,18 @@ public IPath BuildHorizontalPlankPath() public IPath BuildCornerPlankPath(int plankCount) { - IPath path = _pathFactory.Create(); + var path = _pathFactory.Create(); - double step = Math.PI / 2.0 / _trackParameters.NumCornerPlanks; + var step = Math.PI / 2.0 / _trackParameters.NumCornerPlanks; - for (int i = 0; i < plankCount; i++) + for (var i = 0; i < plankCount; i++) { - double angle = step * (i + 0.5f); + var angle = step * (i + 0.5f); - float innerX = (float)(_innerPlankOffset * Math.Cos(angle)); - float innerY = (float)(_innerPlankOffset * Math.Sin(angle)); - float outerX = (float)(_outerPlankOffset * Math.Cos(angle)); - float outerY = (float)(_outerPlankOffset * Math.Sin(angle)); + var innerX = (float)(_innerPlankOffset * Math.Cos(angle)); + var innerY = (float)(_innerPlankOffset * Math.Sin(angle)); + var outerX = (float)(_outerPlankOffset * Math.Cos(angle)); + var outerY = (float)(_outerPlankOffset * Math.Sin(angle)); path.MoveTo(innerX, innerY); path.LineTo(outerX, outerY); diff --git a/Signalbox.Rendering/Tracks/TrackTool.cs b/Signalbox.Rendering/Tracks/TrackTool.cs index 0343789..2be44bd 100644 --- a/Signalbox.Rendering/Tracks/TrackTool.cs +++ b/Signalbox.Rendering/Tracks/TrackTool.cs @@ -22,7 +22,7 @@ public TrackTool(ILayout trackLayout, IEnumerable this.Visible; + get => Visible; set { - this.Visible = value; + Visible = value; OnChanged(); } } @@ -32,13 +31,13 @@ public bool Enabled public DiagnosticsPanel() { - this.Left = 10; - this.Visible = false; + Left = 10; + Visible = false; } protected override void PreRender(ICanvas canvas) { - this.Top = int.MaxValue; + Top = int.MaxValue; } protected override void Render(ICanvas canvas) @@ -47,20 +46,20 @@ protected override void Render(ICanvas canvas) float maxWidth = 0; var strings = new List(); - foreach ((string name, IStat stat) in InstrumentationBag.Stats.OrderBy(i => i.Name)) + foreach (var (name, stat) in InstrumentationBag.Stats.OrderBy(i => i.Name)) { if (stat.ShouldShow()) { - string line = name + ": " + stat.GetDescription(); + var line = name + ": " + stat.GetDescription(); strings.Add(line); maxWidth = Math.Max(maxWidth, canvas.MeasureText(line, Brushes.Label)); } } - this.InnerWidth = (int)maxWidth; - this.InnerHeight = strings.Count * (lineHeight + LineGap); + InnerWidth = (int)maxWidth; + InnerHeight = strings.Count * (lineHeight + LineGap); - foreach (string line in strings) + foreach (var line in strings) { canvas.DrawText(line, 0, lineHeight, Brushes.Label); canvas.Translate(0, LineGap + lineHeight); diff --git a/Signalbox.Rendering/UI/MiniMapScreen.cs b/Signalbox.Rendering/UI/MiniMapScreen.cs index ae1e451..78d30eb 100644 --- a/Signalbox.Rendering/UI/MiniMapScreen.cs +++ b/Signalbox.Rendering/UI/MiniMapScreen.cs @@ -62,7 +62,7 @@ public MiniMapScreen(IMapRenderer mapRenderer, ILayout trackLayout, IPixe public bool HandlePointerAction(int x, int y, int width, int height, PointerAction action) { - if (!this.Enabled) + if (!Enabled) { return false; } @@ -94,7 +94,7 @@ public bool HandlePointerAction(int x, int y, int width, int height, PointerActi public void Render(ICanvas canvas, int width, int height) { - if (!this.Enabled) + if (!Enabled) { return; } @@ -103,13 +103,13 @@ public void Render(ICanvas canvas, int width, int height) canvas.DrawImage(_mapRenderer.GetMapImage(), 0, 0); - foreach (Track track in _trackLayout) + foreach (var track in _trackLayout) { canvas.DrawRect(track.Column, track.Row, 1, 1, _paint); } - (int left, int top) = _pixelMapper.ViewPortPixelsToCoords(0, 0); - (int right, int bottom) = _pixelMapper.ViewPortPixelsToCoords(_pixelMapper.ViewPortWidth, _pixelMapper.ViewPortHeight); + var (left, top) = _pixelMapper.ViewPortPixelsToCoords(0, 0); + var (right, bottom) = _pixelMapper.ViewPortPixelsToCoords(_pixelMapper.ViewPortWidth, _pixelMapper.ViewPortHeight); canvas.DrawRect(left, top, right - left, bottom - top, _viewPortPaint); diff --git a/Signalbox.Rendering/UI/TrackButton.cs b/Signalbox.Rendering/UI/TrackButton.cs index bcfba11..58511da 100644 --- a/Signalbox.Rendering/UI/TrackButton.cs +++ b/Signalbox.Rendering/UI/TrackButton.cs @@ -25,7 +25,7 @@ protected override void RenderButtonLabel(ICanvas canvas) { if (renderer.ShouldRender(_track)) { - float scale = 32 / 100.0f; + var scale = 32 / 100.0f; using (canvas.Scope()) { canvas.Translate(4, 4); diff --git a/Signalbox.Rendering/UI/TrackSelectionPanel.cs b/Signalbox.Rendering/UI/TrackSelectionPanel.cs index 04306ab..53a1aa7 100644 --- a/Signalbox.Rendering/UI/TrackSelectionPanel.cs +++ b/Signalbox.Rendering/UI/TrackSelectionPanel.cs @@ -27,18 +27,18 @@ public TrackSelectionPanel(ILayout layout, IPixelMapper pixelMapper, IEnu _pixelMapper = pixelMapper; _entityFactories = entityFactories; _renderers = renderers; - this.InnerHeight = 40; + InnerHeight = 40; - this.Visible = false; + Visible = false; _layout.SelectionChanged += (s, e) => { - this.Visible = false; + Visible = false; var track = _layout.SelectedEntity; if (track is not null) { CreateMultiButton(track); - this.Visible = true; + Visible = true; } OnChanged(); @@ -51,12 +51,12 @@ private void CreateMultiButton(Track track) var row = track.Row; var (x, y, _) = _pixelMapper.CoordsToViewPortPixels(column, row + 1); - int maxButtons = 0; + var maxButtons = 0; _multiButtons.Clear(); foreach (var factory in _entityFactories.Reverse()) { var buttons = new List(); - foreach (Track newEntity in factory.GetPossibleReplacements(column, row, track)) + foreach (var newEntity in factory.GetPossibleReplacements(column, row, track)) { buttons.Add(new TrackButton(newEntity, () => IsActive(track, newEntity), () => OnClick(column, row, newEntity), _renderers) { @@ -75,8 +75,8 @@ private void CreateMultiButton(Track track) TransparentBackground = true })); - this.InnerWidth = maxButtons * 40; - this.InnerHeight = _multiButtons.Count * 40; + InnerWidth = maxButtons * 40; + InnerHeight = _multiButtons.Count * 40; } private void Erase(int column, int row) @@ -105,7 +105,7 @@ protected override bool HandlePointerAction(int x, int y, PointerAction action) } if (action == PointerAction.Click) { - this.Visible = false; + Visible = false; } return true; } @@ -126,8 +126,8 @@ protected override void PreRender(ICanvas canvas) } canvas.DrawRect(x, y, _pixelMapper.CellSize, _pixelMapper.CellSize, s_trackHighlightBrush); - this.Top = y + _pixelMapper.CellSize + 5; - this.Left = x - this.InnerWidth / 2 + _pixelMapper.CellSize / 2 - (GetPanelWidth() - this.InnerWidth) / 2; + Top = y + _pixelMapper.CellSize + 5; + Left = x - InnerWidth / 2 + _pixelMapper.CellSize / 2 - (GetPanelWidth() - InnerWidth) / 2; } } diff --git a/Signalbox.Rendering/UI/TrainInfoScreen.cs b/Signalbox.Rendering/UI/TrainInfoScreen.cs index 43ecb70..44d02c0 100644 --- a/Signalbox.Rendering/UI/TrainInfoScreen.cs +++ b/Signalbox.Rendering/UI/TrainInfoScreen.cs @@ -40,35 +40,23 @@ public TrainInfoScreen(ITrainManager trainManager, ISignalboxManager signalboxMa _trainPainter = trainPainter; _trainManager.Changed += (_, _) => { - this.Visible = _trainManager.CurrentTrain is not null; + Visible = _trainManager.CurrentTrain is not null; OnChanged(); }; _signalboxManager.Changed += (_, _) => OnChanged(); _trainManager.CurrentTrainPropertyChanged += (_, _) => OnChanged(); - _controlButton = new(20, new ButtonBase[] - { - CreateButton(Picture.Play, () => _trainManager.CurrentTrain?.Stopped != true, () => _trainManager.CurrentTrain?.Start()), - CreateButton(Picture.Pause, () => _trainManager.CurrentTrain?.Stopped == true, () => _trainManager.CurrentTrain?.Stop()), - }); - - _actionButton = new(20, new ButtonBase[] - { - CreateButton(Picture.Eye, () => _trainManager.CurrentTrain?.Follow ?? false, () => _trainManager.ToggleFollow(_trainManager.CurrentTrain!)), - CreateButton(Picture.Trash, () => false, () => - { - _movableLayout.Remove(_trainManager.CurrentTrain!); - Close(); - }), - }); - - _trainSelectionButton = new(20, new ButtonBase[] - { - CreateButton(Picture.Left, () => false, () => _trainManager.PreviousTrain()), - CreateButton(Picture.Right, () => false, () => _trainManager.NextTrain()) - }); - - this.Visible = _trainManager.CurrentTrain is not null; + _controlButton = new(20, CreateButton(Picture.Play, () => _trainManager.CurrentTrain?.Stopped != true, () => _trainManager.CurrentTrain?.Start()), CreateButton(Picture.Pause, () => _trainManager.CurrentTrain?.Stopped == true, () => _trainManager.CurrentTrain?.Stop())); + + _actionButton = new(20, CreateButton(Picture.Eye, () => _trainManager.CurrentTrain?.Follow ?? false, () => _trainManager.ToggleFollow(_trainManager.CurrentTrain!)), CreateButton(Picture.Trash, () => false, () => + { + _movableLayout.Remove(_trainManager.CurrentTrain!); + Close(); + })); + + _trainSelectionButton = new(20, CreateButton(Picture.Left, () => false, () => _trainManager.PreviousTrain()), CreateButton(Picture.Right, () => false, () => _trainManager.NextTrain())); + + Visible = _trainManager.CurrentTrain is not null; } private static ButtonBase CreateButton(Picture picture, Func isActive, Action onClick) @@ -105,7 +93,7 @@ protected override bool HandlePointerAction(int x, int y, PointerAction action) protected override void Render(ICanvas canvas) { - Train train = _trainManager.CurrentTrain ?? throw new NullReferenceException("Current train is null so we shouldn't be rendering"); + var train = _trainManager.CurrentTrain ?? throw new NullReferenceException("Current train is null so we shouldn't be rendering"); using (canvas.Scope()) { diff --git a/Signalbox.Rendering/UIFramework/ButtonBase.cs b/Signalbox.Rendering/UIFramework/ButtonBase.cs index 6987577..3d3305e 100644 --- a/Signalbox.Rendering/UIFramework/ButtonBase.cs +++ b/Signalbox.Rendering/UIFramework/ButtonBase.cs @@ -27,7 +27,7 @@ protected ButtonBase(Func isActive, Action onClick) public virtual bool HandleMouseAction(int x, int y, PointerAction action) { - if (x is >= 0 && x <= this.Width && y >= 0 && y <= this.Height) + if (x is >= 0 && x <= Width && y >= 0 && y <= Height) { if (action == PointerAction.Click) { @@ -45,21 +45,21 @@ public virtual bool HandleMouseAction(int x, int y, PointerAction action) public virtual void Render(ICanvas canvas) { - if (this.Width == 0) + if (Width == 0) { - this.Width = GetMinimumWidth(canvas); + Width = GetMinimumWidth(canvas); } var isActive = _isActive?.Invoke() ?? false; - PaintBrush brush = isActive ? Brushes.ButtonActiveBackground : Brushes.ButtonBackground; - if (!this.TransparentBackground || isActive) + var brush = isActive ? Brushes.ButtonActiveBackground : Brushes.ButtonBackground; + if (!TransparentBackground || isActive) { - canvas.DrawRect(0, 0, this.Width, this.Height, brush); + canvas.DrawRect(0, 0, Width, Height, brush); } if (_isHovered) { - canvas.DrawRect(0, 0, this.Width, this.Height, Brushes.ButtonHoverBackground); + canvas.DrawRect(0, 0, Width, Height, Brushes.ButtonHoverBackground); } RenderButtonLabel(canvas); diff --git a/Signalbox.Rendering/UIFramework/ButtonPanelBase.cs b/Signalbox.Rendering/UIFramework/ButtonPanelBase.cs index 57ca8f8..cef453e 100644 --- a/Signalbox.Rendering/UIFramework/ButtonPanelBase.cs +++ b/Signalbox.Rendering/UIFramework/ButtonPanelBase.cs @@ -2,7 +2,7 @@ namespace Signalbox.Rendering.UIFramework; -public abstract partial class ButtonPanelBase : PanelBase +public abstract class ButtonPanelBase : PanelBase { private const int ButtonGap = 10; private const int ButtonLeft = 5; diff --git a/Signalbox.Rendering/UIFramework/InteractionManager.cs b/Signalbox.Rendering/UIFramework/InteractionManager.cs index c289880..578a3d9 100644 --- a/Signalbox.Rendering/UIFramework/InteractionManager.cs +++ b/Signalbox.Rendering/UIFramework/InteractionManager.cs @@ -49,7 +49,7 @@ public bool PointerZoomOut(int x, int y) public bool PointerRelease(int x, int y) { - (int column, int row) = _pixelMapper.ViewPortPixelsToCoords(x, y); + var (column, row) = _pixelMapper.ViewPortPixelsToCoords(x, y); if (_capturedHandler is null && !_hasDragged && @@ -73,14 +73,15 @@ _signalboxManager.CurrentTool is not null && private bool HandleInteraction(int x, int y, PointerAction action) { - (int width, int height) = _signalbox.GetScreenSize(); + var (width, height) = _signalbox.GetScreenSize(); if (_capturedHandler != null) { _capturedHandler.HandlePointerAction(x, y, width, height, action); return true; } - else if (_capturedTool != null) + + if (_capturedTool != null) { ExecuteTool(_capturedTool, x, y, action); return true; @@ -90,7 +91,7 @@ private bool HandleInteraction(int x, int y, PointerAction action) { case PointerAction.Click: { - bool preHandled = false; + var preHandled = false; foreach (var handler in _handler.Where(handler => handler.PreHandleNextClick && action is PointerAction.Click)) { _capturedHandler = handler; @@ -133,7 +134,7 @@ private bool HandleInteraction(int x, int y, PointerAction action) private bool ExecuteTool(ITool tool, int x, int y, PointerAction action) { - (int column, int row) = _pixelMapper.ViewPortPixelsToCoords(x, y); + var (column, row) = _pixelMapper.ViewPortPixelsToCoords(x, y); var inSameCell = (column == _lastToolColumn && row == _lastToolRow); diff --git a/Signalbox.Rendering/UIFramework/MultiButton.cs b/Signalbox.Rendering/UIFramework/MultiButton.cs index 582fe06..66f95aa 100644 --- a/Signalbox.Rendering/UIFramework/MultiButton.cs +++ b/Signalbox.Rendering/UIFramework/MultiButton.cs @@ -12,8 +12,8 @@ public MultiButton(int buttonSize, params ButtonBase[] buttons) _buttonSize = buttonSize; _buttons = buttons; - this.Height = _buttonSize; - this.Width = _buttonSize * _buttons.Length; + Height = _buttonSize; + Width = _buttonSize * _buttons.Length; } public override int GetMinimumWidth(ICanvas canvas) => _buttonSize * _buttons.Length; diff --git a/Signalbox.Rendering/UIFramework/PanelBase.cs b/Signalbox.Rendering/UIFramework/PanelBase.cs index 577fc5e..1b5f58f 100644 --- a/Signalbox.Rendering/UIFramework/PanelBase.cs +++ b/Signalbox.Rendering/UIFramework/PanelBase.cs @@ -38,7 +38,7 @@ public bool Visible set { _visible = value; - this.PreHandleNextClick = value && this.AutoClose; + PreHandleNextClick = value && AutoClose; _mouseHasBeenWithin = false; } } @@ -46,15 +46,15 @@ public bool Visible public event EventHandler? Changed; private int GetLeft(int width) - => this.Left < 0 - ? width - (-1 * this.Left) - : this.Left; + => Left < 0 + ? width - (-1 * Left) + : Left; public bool HandlePointerAction(int x, int y, int width, int height, PointerAction action) { - if (!this.Visible) + if (!Visible) { - this.PreHandleNextClick = false; + PreHandleNextClick = false; return false; } @@ -66,9 +66,9 @@ public bool HandlePointerAction(int x, int y, int width, int height, PointerActi var panelHeight = GetPanelHeight(); var panelWidth = GetPanelWidth(); - y -= this.Top; + y -= Top; - if (this.Position == PanelPosition.Right) + if (Position == PanelPosition.Right) { if (IsCollapsed()) { @@ -79,7 +79,7 @@ public bool HandlePointerAction(int x, int y, int width, int height, PointerActi x -= (width - panelWidth); } } - else if (this.Position == PanelPosition.Left) + else if (Position == PanelPosition.Left) { if (IsCollapsed()) { @@ -98,16 +98,17 @@ public bool HandlePointerAction(int x, int y, int width, int height, PointerActi _collapsed = !_collapsed; OnChanged(); } - else if (action == PointerAction.Click && y <= 10 + CloseButtonWidth && this.CanClose) + else if (action == PointerAction.Click && y <= 10 + CloseButtonWidth && CanClose) { - this.Visible = false; + Visible = false; Close(); } return true; } - else if (!IsCollapsed() && x is >= 0 && x <= panelWidth && y >= 0 && y <= panelHeight) + + if (!IsCollapsed() && x is >= 0 && x <= panelWidth && y >= 0 && y <= panelHeight) { - if (this.Position == PanelPosition.Left) + if (Position == PanelPosition.Left) { x -= 5; } @@ -115,24 +116,25 @@ public bool HandlePointerAction(int x, int y, int width, int height, PointerActi { x -= 10; } - y -= this.TopPadding; + y -= TopPadding; - if (this.AutoClose) + if (AutoClose) { _mouseHasBeenWithin = true; } return HandlePointerAction(x, y, action); } - else if (this.IsCollapsable && !_collapsed) + + if (IsCollapsable && !_collapsed) { _collapsed = true; OnChanged(); } - if ((_mouseHasBeenWithin || action is PointerAction.Click) && this.AutoClose) + if ((_mouseHasBeenWithin || action is PointerAction.Click) && AutoClose) { - this.Visible = false; + Visible = false; } return false; @@ -144,7 +146,7 @@ protected virtual void Close() public void Render(ICanvas canvas, int width, int height) { - if (!this.Visible) + if (!Visible) { return; } @@ -154,35 +156,35 @@ public void Render(ICanvas canvas, int width, int height) PreRender(canvas); } - if (this.Position == PanelPosition.Floating) + if (Position == PanelPosition.Floating) { - this.Left = Math.Max(10, this.Left); - this.Left = Math.Min(width - GetPanelWidth() - 10, this.Left); + Left = Math.Max(10, Left); + Left = Math.Min(width - GetPanelWidth() - 10, Left); } - this.Top = Math.Max(10, this.Top); - this.Top = Math.Min(height - GetPanelHeight() - 10, this.Top); + Top = Math.Max(10, Top); + Top = Math.Min(height - GetPanelHeight() - 10, Top); - canvas.Translate(0, this.Top); + canvas.Translate(0, Top); _titleWidth = 0; - if (this.Title is { Length: > 0 }) + if (Title is { Length: > 0 }) { - _titleWidth = (int)canvas.MeasureText(this.Title, Brushes.Label); + _titleWidth = (int)canvas.MeasureText(Title, Brushes.Label); } - if (this.CanClose) + if (CanClose) { _titleWidth += CloseButtonWidth; } var panelHeight = GetPanelHeight(); var panelWidth = GetPanelWidth(); - if (this.Position != PanelPosition.Floating) + if (Position != PanelPosition.Floating) { panelWidth += 20; } - if (this.Position == PanelPosition.Right) + if (Position == PanelPosition.Right) { if (IsCollapsed()) { @@ -193,7 +195,7 @@ public void Render(ICanvas canvas, int width, int height) canvas.Translate(width - panelWidth + 20, 0); } } - else if (this.Position == PanelPosition.Left) + else if (Position == PanelPosition.Left) { if (IsCollapsed()) { @@ -209,13 +211,13 @@ public void Render(ICanvas canvas, int width, int height) canvas.Translate(GetLeft(width), 0); } - canvas.DrawRoundRect(0, 0, panelWidth, panelHeight, this.CornerRadius, this.CornerRadius, Brushes.PanelBackground); + canvas.DrawRoundRect(0, 0, panelWidth, panelHeight, CornerRadius, CornerRadius, Brushes.PanelBackground); - if (this.Title is { Length: > 0 } || this.CanClose) + if (Title is { Length: > 0 } || CanClose) { canvas.Save(); - if (this.Position == PanelPosition.Left) + if (Position == PanelPosition.Left) { canvas.Save(); canvas.RotateDegrees(180, panelWidth / 2, 10 + ((_titleWidth + 10) / 2)); @@ -228,18 +230,18 @@ public void Render(ICanvas canvas, int width, int height) canvas.DrawRoundRect(-TitleAreaWidth, 10, TitleAreaWidth + 3, _titleWidth + 10, 5, 5, Brushes.PanelBorder); } - var title = this.Title ?? ""; + var title = Title ?? ""; using (canvas.Scope()) { canvas.RotateDegrees(270); canvas.DrawText(title, -15 - _titleWidth, -5, Brushes.Label); } - if (this.CanClose) + if (CanClose) { canvas.DrawPicture(Picture.Cross, -TitleAreaWidth + 5, 10 + (CloseButtonWidth - CloseButtonSize) / 2, CloseButtonSize); } - if (this.Position != PanelPosition.Left) + if (Position != PanelPosition.Left) { canvas.ClipRect(new(-2, 10, TitleAreaWidth / 2, _titleWidth + 20), true, true); } @@ -250,20 +252,20 @@ public void Render(ICanvas canvas, int width, int height) } } - canvas.DrawRoundRect(0, 0, panelWidth, panelHeight, this.CornerRadius, this.CornerRadius, this.PanelBorderBrush); + canvas.DrawRoundRect(0, 0, panelWidth, panelHeight, CornerRadius, CornerRadius, PanelBorderBrush); if (_titleWidth > 0) { canvas.Restore(); } - if (this.Position == PanelPosition.Left) + if (Position == PanelPosition.Left) { - canvas.Translate(25, this.TopPadding); + canvas.Translate(25, TopPadding); } else { - canvas.Translate(10, this.TopPadding); + canvas.Translate(10, TopPadding); } if (IsCollapsed()) @@ -296,11 +298,11 @@ protected bool IsCollapsed() => CanCollapse() && _collapsed; private bool CanCollapse() - => this.IsCollapsable && this.Title is { Length: > 0 } && this.Position != PanelPosition.Floating; + => IsCollapsable && Title is { Length: > 0 } && Position != PanelPosition.Floating; protected int GetPanelHeight() - => Math.Max(_titleWidth, this.InnerHeight) + this.TopPadding + this.BottomPadding; + => Math.Max(_titleWidth, InnerHeight) + TopPadding + BottomPadding; protected int GetPanelWidth() - => this.InnerWidth + 20; + => InnerWidth + 20; } diff --git a/Signalbox.Rendering/UIFramework/PictureButton.cs b/Signalbox.Rendering/UIFramework/PictureButton.cs index 784026f..819f4dd 100644 --- a/Signalbox.Rendering/UIFramework/PictureButton.cs +++ b/Signalbox.Rendering/UIFramework/PictureButton.cs @@ -19,6 +19,6 @@ public override int GetMinimumWidth(ICanvas canvas) protected override void RenderButtonLabel(ICanvas canvas) { - canvas.DrawPicture(_picture, (this.Width - _pictureSize) / 2, (this.Height - _pictureSize) / 2, _pictureSize); + canvas.DrawPicture(_picture, (Width - _pictureSize) / 2, (Height - _pictureSize) / 2, _pictureSize); } } diff --git a/Signalbox.Rendering/UIFramework/TextButton.cs b/Signalbox.Rendering/UIFramework/TextButton.cs index ba0e484..cd4638f 100644 --- a/Signalbox.Rendering/UIFramework/TextButton.cs +++ b/Signalbox.Rendering/UIFramework/TextButton.cs @@ -15,15 +15,15 @@ public TextButton(string label, Func isActive, Action onClick) public override int GetMinimumWidth(ICanvas canvas) { - return (int)canvas.MeasureText(_label, this.LabelBrush) + (this.PaddingX * 2); + return (int)canvas.MeasureText(_label, LabelBrush) + (PaddingX * 2); } protected override void RenderButtonLabel(ICanvas canvas) { - var textWidth = canvas.MeasureText(_label, this.LabelBrush); + var textWidth = canvas.MeasureText(_label, LabelBrush); - int textHeight = this.LabelBrush.TextSize ?? throw new NullReferenceException("Must set a text size on the label brush"); + var textHeight = LabelBrush.TextSize ?? throw new NullReferenceException("Must set a text size on the label brush"); - canvas.DrawText(_label, (this.Width - textWidth) / 2, textHeight + (float)(this.Height - textHeight) / 2 - 2, this.LabelBrush); + canvas.DrawText(_label, (Width - textWidth) / 2, textHeight + (float)(Height - textHeight) / 2 - 2, LabelBrush); } } diff --git a/Signalbox.SourceGenerator/DISourceGenerator.cs b/Signalbox.SourceGenerator/DISourceGenerator.cs index b04cdee..8422933 100644 --- a/Signalbox.SourceGenerator/DISourceGenerator.cs +++ b/Signalbox.SourceGenerator/DISourceGenerator.cs @@ -1,4 +1,4 @@ -using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -16,15 +16,15 @@ public void Initialize(GeneratorInitializationContext context) public void Execute(GeneratorExecutionContext context) { - Compilation? compilation = context.Compilation; + var compilation = context.Compilation; - string sourceBuilder = Generate(context, compilation); + var sourceBuilder = Generate(context, compilation); context.AddSource("ServiceLocator.cs", SourceText.From(sourceBuilder, Encoding.UTF8)); } public static string Generate(GeneratorExecutionContext context, Compilation compilation) { - string stub = @" + var stub = @" // namespace DI { @@ -42,32 +42,32 @@ public static T GetService() var options = (compilation as CSharpCompilation)?.SyntaxTrees[0].Options as CSharpParseOptions; compilation = compilation.AddSyntaxTrees(CSharpSyntaxTree.ParseText(SourceText.From(stub, Encoding.UTF8), options)); - ImmutableArray diags = compilation.GetDiagnostics(); + var diags = compilation.GetDiagnostics(); var sourceBuilder = new StringBuilder(); var services = new List(); - INamedTypeSymbol? serviceLocatorClass = compilation.GetTypeByMetadataName("DI.ServiceLocator")!; - INamedTypeSymbol? transientAttribute = compilation.GetTypeByMetadataName("Signalbox.Engine.Utilities.TransientAttribute")!; - INamedTypeSymbol? orderAttribute = compilation.GetTypeByMetadataName("Signalbox.Engine.Utilities.OrderAttribute")!; - INamedTypeSymbol? layoutOfT = compilation.GetTypeByMetadataName("Signalbox.Engine.Entity.ILayout`1")!.ConstructUnboundGenericType(); - INamedTypeSymbol? filteredLayout = compilation.GetTypeByMetadataName("Signalbox.Engine.Entity.FilteredLayout`1")!; - INamedTypeSymbol? iEnumerableOfT = compilation.GetTypeByMetadataName("System.Collections.Generic.IEnumerable`1")!.ConstructUnboundGenericType(); - INamedTypeSymbol? listOfT = compilation.GetTypeByMetadataName("System.Collections.Generic.List`1")!; + var serviceLocatorClass = compilation.GetTypeByMetadataName("DI.ServiceLocator")!; + var transientAttribute = compilation.GetTypeByMetadataName("Signalbox.Engine.Utilities.TransientAttribute")!; + var orderAttribute = compilation.GetTypeByMetadataName("Signalbox.Engine.Utilities.OrderAttribute")!; + var layoutOfT = compilation.GetTypeByMetadataName("Signalbox.Engine.Entity.ILayout`1")!.ConstructUnboundGenericType(); + var filteredLayout = compilation.GetTypeByMetadataName("Signalbox.Engine.Entity.FilteredLayout`1")!; + var iEnumerableOfT = compilation.GetTypeByMetadataName("System.Collections.Generic.IEnumerable`1")!.ConstructUnboundGenericType(); + var listOfT = compilation.GetTypeByMetadataName("System.Collections.Generic.List`1")!; var knownTypes = new KnownTypes(transientAttribute, orderAttribute, layoutOfT, filteredLayout, iEnumerableOfT, listOfT); - foreach (SyntaxTree? tree in compilation.SyntaxTrees) + foreach (var tree in compilation.SyntaxTrees) { - SemanticModel? semanticModel = compilation.GetSemanticModel(tree); + var semanticModel = compilation.GetSemanticModel(tree); IEnumerable? typesToCreate = from i in tree.GetRoot().DescendantNodesAndSelf().OfType() let symbol = semanticModel.GetSymbolInfo(i).Symbol as IMethodSymbol where symbol != null where SymbolEqualityComparer.Default.Equals(symbol.ContainingType, serviceLocatorClass) select symbol.ReturnType as INamedTypeSymbol; - foreach (INamedTypeSymbol? typeToCreate in typesToCreate) + foreach (var typeToCreate in typesToCreate) { Generate(context, typeToCreate, compilation, services, null, knownTypes); } @@ -87,7 +87,7 @@ internal static class ServiceLocator public static T GetService() {"); - foreach (Service? service in services) + foreach (var service in services) { sourceBuilder.AppendLine(" if (typeof(T) == typeof(" + service.Type + "))"); sourceBuilder.AppendLine(" {"); @@ -106,7 +106,7 @@ public static T GetService() private static void GenerateFields(StringBuilder sourceBuilder, List services, List fields) { - foreach (Service? service in services) + foreach (var service in services) { GenerateFields(sourceBuilder, service.ConstructorArguments, fields); if (service.IsTransient) continue; @@ -124,7 +124,7 @@ private static string GetTypeConstruction(Service service, List fields) { var sb = new StringBuilder(); - Service? field = fields.FirstOrDefault(f => SymbolEqualityComparer.Default.Equals(f.ImplementationType, service.ImplementationType)); + var field = fields.FirstOrDefault(f => SymbolEqualityComparer.Default.Equals(f.ImplementationType, service.ImplementationType)); if (field != null) { if (service.Parent?.ElementType is not null) @@ -145,8 +145,8 @@ private static string GetTypeConstruction(Service service, List fields) sb.Append(')'); sb.Append('{'); } - bool first = true; - foreach (Service? arg in service.ConstructorArguments) + var first = true; + foreach (var arg in service.ConstructorArguments) { if (!first) { @@ -170,12 +170,12 @@ private static string GetTypeConstruction(Service service, List fields) private static string GetVariableName(Service service, List fields) { - string typeName = service.ImplementationType.ToString().Replace("<", "").Replace(">", "").Replace("?", ""); + var typeName = service.ImplementationType.ToString().Replace("<", "").Replace(">", "").Replace("?", ""); string[] parts = typeName.Split('.'); - for (int i = parts.Length - 1; i >= 0; i--) + for (var i = parts.Length - 1; i >= 0; i--) { - string? candidate = string.Join("", parts.Skip(i)); + var candidate = string.Join("", parts.Skip(i)); candidate = "_" + char.ToLowerInvariant(candidate[0]) + candidate.Substring(1); if (!fields.Any(f => string.Equals(f.VariableName, candidate, StringComparison.Ordinal))) { @@ -193,7 +193,7 @@ private static void Generate(GeneratorExecutionContext context, INamedTypeSymbol if (typeToCreate.IsGenericType && SymbolEqualityComparer.Default.Equals(typeToCreate.ConstructUnboundGenericType(), knownTypes.IEnumerableOfT)) { - ITypeSymbol? typeToFind = typeToCreate.TypeArguments[0]; + var typeToFind = typeToCreate.TypeArguments[0]; var types = FindImplementations(context, compilation, knownTypes, typeToFind); if (!types.Any()) @@ -201,7 +201,7 @@ private static void Generate(GeneratorExecutionContext context, INamedTypeSymbol context.ReportDiagnostic(Diagnostic.Create("TRAINS2", "DI", $"Can't find an implemnentation for {typeToFind} to construct an IEnumerable", DiagnosticSeverity.Error, DiagnosticSeverity.Error, true, 0, false)); } - INamedTypeSymbol? list = knownTypes.ListOfT.Construct(typeToFind); + var list = knownTypes.ListOfT.Construct(typeToFind); var listService = new Service(typeToCreate, parent) { ImplementationType = list, @@ -215,16 +215,16 @@ private static void Generate(GeneratorExecutionContext context, INamedTypeSymbol } services.Add(listService); - foreach (INamedTypeSymbol? thingy in types) + foreach (var thingy in types) { Generate(context, thingy, compilation, listService.ConstructorArguments, listService, knownTypes); } } else if (typeToCreate.IsGenericType && SymbolEqualityComparer.Default.Equals(typeToCreate.ConstructUnboundGenericType(), knownTypes.ILayoutOfT)) { - ITypeSymbol? entityType = typeToCreate.TypeArguments[0]; + var entityType = typeToCreate.TypeArguments[0]; - INamedTypeSymbol? layout = knownTypes.FilteredLayout.Construct(entityType); + var layout = knownTypes.FilteredLayout.Construct(entityType); var layoutService = new Service(typeToCreate, parent); services.Add(layoutService); @@ -233,7 +233,7 @@ private static void Generate(GeneratorExecutionContext context, INamedTypeSymbol } else { - INamedTypeSymbol? realType = typeToCreate.IsAbstract ? FindImplementation(context, compilation, knownTypes, typeToCreate) : typeToCreate; + var realType = typeToCreate.IsAbstract ? FindImplementation(context, compilation, knownTypes, typeToCreate) : typeToCreate; if (realType == null) { @@ -253,10 +253,10 @@ private static void Generate(GeneratorExecutionContext context, INamedTypeSymbol } services.Add(service); - IMethodSymbol? constructor = realType?.Constructors.FirstOrDefault(); + var constructor = realType?.Constructors.FirstOrDefault(); if (constructor != null) { - foreach (IParameterSymbol? parametr in constructor.Parameters) + foreach (var parametr in constructor.Parameters) { if (parametr.Type is INamedTypeSymbol paramType) { @@ -296,16 +296,16 @@ private static IOrderedEnumerable FindImplementations(Generato return FindImplementations(context, typeToFind, compilation).OrderBy(t => (int)(t.GetAttributes().FirstOrDefault(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, knownTypes.OrderAttribute))?.ConstructorArguments[0].Value ?? 0)); } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "CA1801:Review unused parameters", Justification = "")] - [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "")] + [SuppressMessage("Usage", "CA1801:Review unused parameters", Justification = "")] + [SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "")] private static IEnumerable FindImplementations(GeneratorExecutionContext context, ITypeSymbol typeToFind, Compilation compilation) { - foreach (INamespaceSymbol? ns in compilation.GlobalNamespace.GetNamespaceMembers()) + foreach (var ns in compilation.GlobalNamespace.GetNamespaceMembers()) { if (ns.Name == "System" || ns.Name == "Microsoft" || ns.Name == "SkiaSharp" || ns.Name == "OpenTK") continue; - int count = 0; - foreach (INamedTypeSymbol? x in GetAllTypes(new[] { ns })) + var count = 0; + foreach (var x in GetAllTypes(new[] { ns })) { count++; if (!x.IsAbstract && x.AllInterfaces.Any(i => SymbolEqualityComparer.Default.Equals(i, typeToFind))) @@ -318,14 +318,14 @@ private static IEnumerable FindImplementations(GeneratorExecut private static IEnumerable GetAllTypes(IEnumerable namespaces) { - foreach (INamespaceSymbol? ns in namespaces) + foreach (var ns in namespaces) { - foreach (INamedTypeSymbol? t in ns.GetTypeMembers()) + foreach (var t in ns.GetTypeMembers()) { yield return t; } - foreach (INamedTypeSymbol? subType in GetAllTypes(ns.GetNamespaceMembers())) + foreach (var subType in GetAllTypes(ns.GetNamespaceMembers())) { yield return subType; } diff --git a/Signalbox.SourceGenerator/Signalbox.SourceGenerator.csproj b/Signalbox.SourceGenerator/Signalbox.SourceGenerator.csproj index 601a4b2..3501032 100644 --- a/Signalbox.SourceGenerator/Signalbox.SourceGenerator.csproj +++ b/Signalbox.SourceGenerator/Signalbox.SourceGenerator.csproj @@ -13,4 +13,18 @@ + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + all + runtime; build; native; contentfiles; analyzers + + + \ No newline at end of file