diff --git a/src/Ryujinx.Audio/AudioManager.cs b/src/Ryujinx.Audio/AudioManager.cs index 9f2a05b09..370d3d098 100644 --- a/src/Ryujinx.Audio/AudioManager.cs +++ b/src/Ryujinx.Audio/AudioManager.cs @@ -16,17 +16,17 @@ namespace Ryujinx.Audio /// /// Events signaled when the driver played audio buffers. /// - private ManualResetEvent[] _updateRequiredEvents; + private readonly ManualResetEvent[] _updateRequiredEvents; /// /// Action to execute when the driver played audio buffers. /// - private Action[] _actions; + private readonly Action[] _actions; /// /// The worker thread in charge of handling sessions update. /// - private Thread _workerThread; + private readonly Thread _workerThread; private bool _isRunning; @@ -44,7 +44,7 @@ namespace Ryujinx.Audio _workerThread = new Thread(Update) { - Name = "AudioManager.Worker" + Name = "AudioManager.Worker", }; } @@ -115,6 +115,7 @@ namespace Ryujinx.Audio public void Dispose() { + GC.SuppressFinalize(this); Dispose(true); } @@ -129,4 +130,4 @@ namespace Ryujinx.Audio } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Backends/Common/BackendHelper.cs b/src/Ryujinx.Audio/Backends/Common/BackendHelper.cs index 30db340fa..124d8364f 100644 --- a/src/Ryujinx.Audio/Backends/Common/BackendHelper.cs +++ b/src/Ryujinx.Audio/Backends/Common/BackendHelper.cs @@ -23,4 +23,4 @@ namespace Ryujinx.Audio.Backends.Common return bufferSize / GetSampleSize(format) / channelCount; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Backends/Common/DynamicRingBuffer.cs b/src/Ryujinx.Audio/Backends/Common/DynamicRingBuffer.cs index d17303cd3..05dd2162a 100644 --- a/src/Ryujinx.Audio/Backends/Common/DynamicRingBuffer.cs +++ b/src/Ryujinx.Audio/Backends/Common/DynamicRingBuffer.cs @@ -163,4 +163,4 @@ namespace Ryujinx.Audio.Backends.Common } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Backends/Common/HardwareDeviceSessionOutputBase.cs b/src/Ryujinx.Audio/Backends/Common/HardwareDeviceSessionOutputBase.cs index 6fb3bee02..5599c0827 100644 --- a/src/Ryujinx.Audio/Backends/Common/HardwareDeviceSessionOutputBase.cs +++ b/src/Ryujinx.Audio/Backends/Common/HardwareDeviceSessionOutputBase.cs @@ -66,14 +66,11 @@ namespace Ryujinx.Audio.Backends.Common return false; } - if (buffer.Data == null) - { - buffer.Data = samples; - } + buffer.Data ??= samples; return true; } public virtual void UnregisterBuffer(AudioBuffer buffer) { } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Backends/CompatLayer/CompatLayerHardwareDeviceDriver.cs b/src/Ryujinx.Audio/Backends/CompatLayer/CompatLayerHardwareDeviceDriver.cs index 22919f1e1..3f3806c3e 100644 --- a/src/Ryujinx.Audio/Backends/CompatLayer/CompatLayerHardwareDeviceDriver.cs +++ b/src/Ryujinx.Audio/Backends/CompatLayer/CompatLayerHardwareDeviceDriver.cs @@ -6,14 +6,13 @@ using Ryujinx.Common.Logging; using Ryujinx.Memory; using System; using System.Threading; - using static Ryujinx.Audio.Integration.IHardwareDeviceDriver; namespace Ryujinx.Audio.Backends.CompatLayer { public class CompatLayerHardwareDeviceDriver : IHardwareDeviceDriver { - private IHardwareDeviceDriver _realDriver; + private readonly IHardwareDeviceDriver _realDriver; public static bool IsSupported => true; @@ -24,6 +23,7 @@ namespace Ryujinx.Audio.Backends.CompatLayer public void Dispose() { + GC.SuppressFinalize(this); _realDriver.Dispose(); } @@ -49,7 +49,7 @@ namespace Ryujinx.Audio.Backends.CompatLayer 6 => SelectHardwareChannelCount(2), 2 => SelectHardwareChannelCount(1), 1 => throw new ArgumentException("No valid channel configuration found!"), - _ => throw new ArgumentException($"Invalid targetChannelCount {targetChannelCount}") + _ => throw new ArgumentException($"Invalid targetChannelCount {targetChannelCount}"), }; } @@ -110,7 +110,7 @@ namespace Ryujinx.Audio.Backends.CompatLayer { Logger.Warning?.Print(LogClass.Audio, "The selected audio backend doesn't support audio input, fallback to dummy..."); - return new DummyHardwareDeviceSessionInput(this, memoryManager, sampleFormat, sampleRate, channelCount); + return new DummyHardwareDeviceSessionInput(this, memoryManager); } throw new NotImplementedException(); @@ -138,12 +138,12 @@ namespace Ryujinx.Audio.Backends.CompatLayer if (direction == Direction.Input) { - Logger.Warning?.Print(LogClass.Audio, $"The selected audio backend doesn't support the requested audio input configuration, fallback to dummy..."); + Logger.Warning?.Print(LogClass.Audio, "The selected audio backend doesn't support the requested audio input configuration, fallback to dummy..."); // TODO: We currently don't support audio input upsampling/downsampling, implement this. realSession.Dispose(); - return new DummyHardwareDeviceSessionInput(this, memoryManager, sampleFormat, sampleRate, channelCount); + return new DummyHardwareDeviceSessionInput(this, memoryManager); } // It must be a HardwareDeviceSessionOutputBase. @@ -183,4 +183,4 @@ namespace Ryujinx.Audio.Backends.CompatLayer return direction == Direction.Input || direction == Direction.Output; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Backends/CompatLayer/CompatLayerHardwareDeviceSession.cs b/src/Ryujinx.Audio/Backends/CompatLayer/CompatLayerHardwareDeviceSession.cs index f22a7a690..a9acabec9 100644 --- a/src/Ryujinx.Audio/Backends/CompatLayer/CompatLayerHardwareDeviceSession.cs +++ b/src/Ryujinx.Audio/Backends/CompatLayer/CompatLayerHardwareDeviceSession.cs @@ -8,9 +8,9 @@ namespace Ryujinx.Audio.Backends.CompatLayer { class CompatLayerHardwareDeviceSession : HardwareDeviceSessionOutputBase { - private HardwareDeviceSessionOutputBase _realSession; - private SampleFormat _userSampleFormat; - private uint _userChannelCount; + private readonly HardwareDeviceSessionOutputBase _realSession; + private readonly SampleFormat _userSampleFormat; + private readonly uint _userChannelCount; public CompatLayerHardwareDeviceSession(HardwareDeviceSessionOutputBase realSession, SampleFormat userSampleFormat, uint userChannelCount) : base(realSession.MemoryManager, realSession.RequestedSampleFormat, realSession.RequestedSampleRate, userChannelCount) { @@ -116,11 +116,11 @@ namespace Ryujinx.Audio.Backends.CompatLayer samples = MemoryMarshal.Cast(samplesPCM16).ToArray(); } - AudioBuffer fakeBuffer = new AudioBuffer + AudioBuffer fakeBuffer = new() { BufferTag = buffer.BufferTag, DataPointer = buffer.DataPointer, - DataSize = (ulong)samples.Length + DataSize = (ulong)samples.Length, }; bool result = _realSession.RegisterBuffer(fakeBuffer, samples); @@ -159,4 +159,4 @@ namespace Ryujinx.Audio.Backends.CompatLayer return _realSession.WasBufferFullyConsumed(buffer); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Backends/CompatLayer/Downmixing.cs b/src/Ryujinx.Audio/Backends/CompatLayer/Downmixing.cs index 6959c1588..ffd427a5e 100644 --- a/src/Ryujinx.Audio/Backends/CompatLayer/Downmixing.cs +++ b/src/Ryujinx.Audio/Backends/CompatLayer/Downmixing.cs @@ -31,18 +31,18 @@ namespace Ryujinx.Audio.Backends.CompatLayer private const int Minus6dBInQ15 = (int)(0.501f * RawQ15One); private const int Minus12dBInQ15 = (int)(0.251f * RawQ15One); - private static readonly int[] DefaultSurroundToStereoCoefficients = new int[4] + private static readonly int[] _defaultSurroundToStereoCoefficients = new int[4] { RawQ15One, Minus3dBInQ15, Minus12dBInQ15, - Minus3dBInQ15 + Minus3dBInQ15, }; - private static readonly int[] DefaultStereoToMonoCoefficients = new int[2] + private static readonly int[] _defaultStereoToMonoCoefficients = new int[2] { Minus6dBInQ15, - Minus6dBInQ15 + Minus6dBInQ15, }; private const int SurroundChannelCount = 6; @@ -114,12 +114,12 @@ namespace Ryujinx.Audio.Backends.CompatLayer public static short[] DownMixStereoToMono(ReadOnlySpan data) { - return DownMixStereoToMono(DefaultStereoToMonoCoefficients, data); + return DownMixStereoToMono(_defaultStereoToMonoCoefficients, data); } public static short[] DownMixSurroundToStereo(ReadOnlySpan data) { - return DownMixSurroundToStereo(DefaultSurroundToStereoCoefficients, data); + return DownMixSurroundToStereo(_defaultSurroundToStereoCoefficients, data); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Backends/Dummy/DummyHardwareDeviceDriver.cs b/src/Ryujinx.Audio/Backends/Dummy/DummyHardwareDeviceDriver.cs index 641640f0e..bac21c448 100644 --- a/src/Ryujinx.Audio/Backends/Dummy/DummyHardwareDeviceDriver.cs +++ b/src/Ryujinx.Audio/Backends/Dummy/DummyHardwareDeviceDriver.cs @@ -1,16 +1,16 @@ using Ryujinx.Audio.Common; using Ryujinx.Audio.Integration; using Ryujinx.Memory; +using System; using System.Threading; - using static Ryujinx.Audio.Integration.IHardwareDeviceDriver; namespace Ryujinx.Audio.Backends.Dummy { public class DummyHardwareDeviceDriver : IHardwareDeviceDriver { - private ManualResetEvent _updateRequiredEvent; - private ManualResetEvent _pauseEvent; + private readonly ManualResetEvent _updateRequiredEvent; + private readonly ManualResetEvent _pauseEvent; public static bool IsSupported => true; @@ -36,10 +36,8 @@ namespace Ryujinx.Audio.Backends.Dummy { return new DummyHardwareDeviceSessionOutput(this, memoryManager, sampleFormat, sampleRate, channelCount, volume); } - else - { - return new DummyHardwareDeviceSessionInput(this, memoryManager, sampleFormat, sampleRate, channelCount); - } + + return new DummyHardwareDeviceSessionInput(this, memoryManager); } public ManualResetEvent GetUpdateRequiredEvent() @@ -54,6 +52,7 @@ namespace Ryujinx.Audio.Backends.Dummy public void Dispose() { + GC.SuppressFinalize(this); Dispose(true); } @@ -86,4 +85,4 @@ namespace Ryujinx.Audio.Backends.Dummy return channelCount == 1 || channelCount == 2 || channelCount == 6; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Backends/Dummy/DummyHardwareDeviceSessionInput.cs b/src/Ryujinx.Audio/Backends/Dummy/DummyHardwareDeviceSessionInput.cs index 845713a19..f51a63393 100644 --- a/src/Ryujinx.Audio/Backends/Dummy/DummyHardwareDeviceSessionInput.cs +++ b/src/Ryujinx.Audio/Backends/Dummy/DummyHardwareDeviceSessionInput.cs @@ -8,10 +8,10 @@ namespace Ryujinx.Audio.Backends.Dummy class DummyHardwareDeviceSessionInput : IHardwareDeviceSession { private float _volume; - private IHardwareDeviceDriver _manager; - private IVirtualMemoryManager _memoryManager; + private readonly IHardwareDeviceDriver _manager; + private readonly IVirtualMemoryManager _memoryManager; - public DummyHardwareDeviceSessionInput(IHardwareDeviceDriver manager, IVirtualMemoryManager memoryManager, SampleFormat requestedSampleFormat, uint requestedSampleRate, uint requestedChannelCount) + public DummyHardwareDeviceSessionInput(IHardwareDeviceDriver manager, IVirtualMemoryManager memoryManager) { _volume = 1.0f; _manager = manager; @@ -64,4 +64,4 @@ namespace Ryujinx.Audio.Backends.Dummy return true; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Backends/Dummy/DummyHardwareDeviceSessionOutput.cs b/src/Ryujinx.Audio/Backends/Dummy/DummyHardwareDeviceSessionOutput.cs index 8e2c949ec..1c248faaa 100644 --- a/src/Ryujinx.Audio/Backends/Dummy/DummyHardwareDeviceSessionOutput.cs +++ b/src/Ryujinx.Audio/Backends/Dummy/DummyHardwareDeviceSessionOutput.cs @@ -9,7 +9,7 @@ namespace Ryujinx.Audio.Backends.Dummy internal class DummyHardwareDeviceSessionOutput : HardwareDeviceSessionOutputBase { private float _volume; - private IHardwareDeviceDriver _manager; + private readonly IHardwareDeviceDriver _manager; private ulong _playedSampleCount; @@ -59,4 +59,4 @@ namespace Ryujinx.Audio.Backends.Dummy return true; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Common/AudioBuffer.cs b/src/Ryujinx.Audio/Common/AudioBuffer.cs index b79401b77..87a7d5f32 100644 --- a/src/Ryujinx.Audio/Common/AudioBuffer.cs +++ b/src/Ryujinx.Audio/Common/AudioBuffer.cs @@ -34,4 +34,4 @@ namespace Ryujinx.Audio.Common /// public byte[] Data; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Common/AudioDeviceSession.cs b/src/Ryujinx.Audio/Common/AudioDeviceSession.cs index 0191f7ccd..a0e04c80d 100644 --- a/src/Ryujinx.Audio/Common/AudioDeviceSession.cs +++ b/src/Ryujinx.Audio/Common/AudioDeviceSession.cs @@ -23,7 +23,7 @@ namespace Ryujinx.Audio.Common /// /// Array of all buffers currently used or released. /// - private AudioBuffer[] _buffers; + private readonly AudioBuffer[] _buffers; /// /// The server index inside (appended but not queued to device driver). @@ -58,17 +58,17 @@ namespace Ryujinx.Audio.Common /// /// The released buffer event. /// - private IWritableEvent _bufferEvent; + private readonly IWritableEvent _bufferEvent; /// /// The session on the device driver. /// - private IHardwareDeviceSession _hardwareDeviceSession; + private readonly IHardwareDeviceSession _hardwareDeviceSession; /// /// Max number of buffers that can be registered to the device driver at a time. /// - private uint _bufferRegisteredLimit; + private readonly uint _bufferRegisteredLimit; /// /// Create a new . @@ -311,9 +311,9 @@ namespace Ryujinx.Audio.Common return false; } - public bool AppendUacBuffer(AudioBuffer buffer, uint handle) + public static bool AppendUacBuffer(AudioBuffer buffer, uint handle) { - // NOTE: On hardware, there is another RegisterBuffer method taking an handle. + // NOTE: On hardware, there is another RegisterBuffer method taking a handle. // This variant of the call always return false (stubbed?) as a result this logic will never succeed. return false; @@ -425,10 +425,8 @@ namespace Ryujinx.Audio.Common { return 0; } - else - { - return _hardwareDeviceSession.GetPlayedSampleCount(); - } + + return _hardwareDeviceSession.GetPlayedSampleCount(); } /// @@ -515,4 +513,4 @@ namespace Ryujinx.Audio.Common } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Common/AudioDeviceState.cs b/src/Ryujinx.Audio/Common/AudioDeviceState.cs index b3f968da2..8705e802e 100644 --- a/src/Ryujinx.Audio/Common/AudioDeviceState.cs +++ b/src/Ryujinx.Audio/Common/AudioDeviceState.cs @@ -13,6 +13,6 @@ namespace Ryujinx.Audio.Common /// /// The audio device is stopped. /// - Stopped + Stopped, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Common/AudioInputConfiguration.cs b/src/Ryujinx.Audio/Common/AudioInputConfiguration.cs index d3cfdd47b..078c3a394 100644 --- a/src/Ryujinx.Audio/Common/AudioInputConfiguration.cs +++ b/src/Ryujinx.Audio/Common/AudioInputConfiguration.cs @@ -24,6 +24,6 @@ namespace Ryujinx.Audio.Common /// /// Reserved/unused. /// - private ushort _reserved; + private readonly ushort _reserved; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Common/AudioOutputConfiguration.cs b/src/Ryujinx.Audio/Common/AudioOutputConfiguration.cs index e17e17576..594f12250 100644 --- a/src/Ryujinx.Audio/Common/AudioOutputConfiguration.cs +++ b/src/Ryujinx.Audio/Common/AudioOutputConfiguration.cs @@ -34,4 +34,4 @@ namespace Ryujinx.Audio.Common /// public AudioDeviceState AudioOutState; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Common/AudioUserBuffer.cs b/src/Ryujinx.Audio/Common/AudioUserBuffer.cs index 50ab67fa3..bb71165ff 100644 --- a/src/Ryujinx.Audio/Common/AudioUserBuffer.cs +++ b/src/Ryujinx.Audio/Common/AudioUserBuffer.cs @@ -33,4 +33,4 @@ namespace Ryujinx.Audio.Common /// public ulong DataOffset; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Common/SampleFormat.cs b/src/Ryujinx.Audio/Common/SampleFormat.cs index 901410a24..39e525e87 100644 --- a/src/Ryujinx.Audio/Common/SampleFormat.cs +++ b/src/Ryujinx.Audio/Common/SampleFormat.cs @@ -38,6 +38,6 @@ namespace Ryujinx.Audio.Common /// /// ADPCM sample format. (Also known as GC-ADPCM) /// - Adpcm = 6 + Adpcm = 6, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Constants.cs b/src/Ryujinx.Audio/Constants.cs index cde87744f..eb5b39013 100644 --- a/src/Ryujinx.Audio/Constants.cs +++ b/src/Ryujinx.Audio/Constants.cs @@ -172,4 +172,4 @@ namespace Ryujinx.Audio 0.707f, }; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Input/AudioInputManager.cs b/src/Ryujinx.Audio/Input/AudioInputManager.cs index 63cbe031f..4d1796c96 100644 --- a/src/Ryujinx.Audio/Input/AudioInputManager.cs +++ b/src/Ryujinx.Audio/Input/AudioInputManager.cs @@ -24,7 +24,7 @@ namespace Ryujinx.Audio.Input /// /// The session ids allocation table. /// - private int[] _sessionIds; + private readonly int[] _sessionIds; /// /// The device driver. @@ -39,7 +39,7 @@ namespace Ryujinx.Audio.Input /// /// The session instances. /// - private AudioInputSystem[] _sessions; + private readonly AudioInputSystem[] _sessions; /// /// The count of active sessions. @@ -166,6 +166,7 @@ namespace Ryujinx.Audio.Input /// /// If true, filter disconnected devices /// The list of all audio inputs name +#pragma warning disable CA1822 // Mark member as static public string[] ListAudioIns(bool filtered) { if (filtered) @@ -173,8 +174,9 @@ namespace Ryujinx.Audio.Input // TODO: Detect if the driver supports audio input } - return new string[] { Constants.DefaultDeviceInputName }; + return new[] { Constants.DefaultDeviceInputName }; } +#pragma warning restore CA1822 /// /// Open a new . @@ -205,7 +207,7 @@ namespace Ryujinx.Audio.Input IHardwareDeviceSession deviceSession = _deviceDriver.OpenDeviceSession(IHardwareDeviceDriver.Direction.Input, memoryManager, sampleFormat, parameter.SampleRate, parameter.ChannelCount); - AudioInputSystem audioIn = new AudioInputSystem(this, _lock, deviceSession, _sessionsBufferEvents[sessionId]); + AudioInputSystem audioIn = new(this, _lock, deviceSession, _sessionsBufferEvents[sessionId]); ResultCode result = audioIn.Initialize(inputDeviceName, sampleFormat, ref parameter, sessionId); @@ -238,6 +240,8 @@ namespace Ryujinx.Audio.Input public void Dispose() { + GC.SuppressFinalize(this); + if (Interlocked.CompareExchange(ref _disposeState, 1, 0) == 0) { Dispose(true); @@ -263,4 +267,4 @@ namespace Ryujinx.Audio.Input } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Input/AudioInputSystem.cs b/src/Ryujinx.Audio/Input/AudioInputSystem.cs index 33364e28a..34623b34f 100644 --- a/src/Ryujinx.Audio/Input/AudioInputSystem.cs +++ b/src/Ryujinx.Audio/Input/AudioInputSystem.cs @@ -18,7 +18,7 @@ namespace Ryujinx.Audio.Input /// /// The session the . /// - private AudioDeviceSession _session; + private readonly AudioDeviceSession _session; /// /// The target device name of the . @@ -43,7 +43,7 @@ namespace Ryujinx.Audio.Input /// /// The owning this. /// - private AudioInputManager _manager; + private readonly AudioInputManager _manager; /// /// The lock of the parent. @@ -90,11 +90,13 @@ namespace Ryujinx.Audio.Input { return ResultCode.DeviceNotFound; } - else if (configuration.SampleRate != 0 && configuration.SampleRate != Constants.TargetSampleRate) + + if (configuration.SampleRate != 0 && configuration.SampleRate != Constants.TargetSampleRate) { return ResultCode.UnsupportedSampleRate; } - else if (configuration.ChannelCount != 0 && configuration.ChannelCount != 1 && configuration.ChannelCount != 2 && configuration.ChannelCount != 6) + + if (configuration.ChannelCount != 0 && configuration.ChannelCount != 1 && configuration.ChannelCount != 2 && configuration.ChannelCount != 6) { return ResultCode.UnsupportedChannelConfiguration; } @@ -185,11 +187,11 @@ namespace Ryujinx.Audio.Input { lock (_parentLock) { - AudioBuffer buffer = new AudioBuffer + AudioBuffer buffer = new() { BufferTag = bufferTag, DataPointer = userBuffer.Data, - DataSize = userBuffer.DataSize + DataSize = userBuffer.DataSize, }; if (_session.AppendBuffer(buffer)) @@ -213,14 +215,14 @@ namespace Ryujinx.Audio.Input { lock (_parentLock) { - AudioBuffer buffer = new AudioBuffer + AudioBuffer buffer = new() { BufferTag = bufferTag, DataPointer = userBuffer.Data, - DataSize = userBuffer.DataSize + DataSize = userBuffer.DataSize, }; - if (_session.AppendUacBuffer(buffer, handle)) + if (AudioDeviceSession.AppendUacBuffer(buffer, handle)) { return ResultCode.Success; } @@ -373,6 +375,8 @@ namespace Ryujinx.Audio.Input public void Dispose() { + GC.SuppressFinalize(this); + if (Interlocked.CompareExchange(ref _disposeState, 1, 0) == 0) { Dispose(true); @@ -389,4 +393,4 @@ namespace Ryujinx.Audio.Input } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Integration/HardwareDeviceImpl.cs b/src/Ryujinx.Audio/Integration/HardwareDeviceImpl.cs index 552f1ab24..576954b96 100644 --- a/src/Ryujinx.Audio/Integration/HardwareDeviceImpl.cs +++ b/src/Ryujinx.Audio/Integration/HardwareDeviceImpl.cs @@ -6,12 +6,12 @@ namespace Ryujinx.Audio.Integration { public class HardwareDeviceImpl : IHardwareDevice { - private IHardwareDeviceSession _session; - private uint _channelCount; - private uint _sampleRate; + private readonly IHardwareDeviceSession _session; + private readonly uint _channelCount; + private readonly uint _sampleRate; private uint _currentBufferTag; - private byte[] _buffer; + private readonly byte[] _buffer; public HardwareDeviceImpl(IHardwareDeviceDriver deviceDriver, uint channelCount, uint sampleRate, float volume) { @@ -36,7 +36,7 @@ namespace Ryujinx.Audio.Integration DataSize = (ulong)_buffer.Length, }); - _currentBufferTag = _currentBufferTag % 4; + _currentBufferTag %= 4; } public void SetVolume(float volume) @@ -61,6 +61,7 @@ namespace Ryujinx.Audio.Integration public void Dispose() { + GC.SuppressFinalize(this); Dispose(true); } @@ -72,4 +73,4 @@ namespace Ryujinx.Audio.Integration } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Integration/IHardwareDevice.cs b/src/Ryujinx.Audio/Integration/IHardwareDevice.cs index 300de8c5d..f9ade9dbc 100644 --- a/src/Ryujinx.Audio/Integration/IHardwareDevice.cs +++ b/src/Ryujinx.Audio/Integration/IHardwareDevice.cs @@ -52,4 +52,4 @@ namespace Ryujinx.Audio.Integration return channelCount != Constants.ChannelCountMax; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Integration/IHardwareDeviceDriver.cs b/src/Ryujinx.Audio/Integration/IHardwareDeviceDriver.cs index 4ed179519..9c812fb9a 100644 --- a/src/Ryujinx.Audio/Integration/IHardwareDeviceDriver.cs +++ b/src/Ryujinx.Audio/Integration/IHardwareDeviceDriver.cs @@ -13,7 +13,7 @@ namespace Ryujinx.Audio.Integration public enum Direction { Input, - Output + Output, } IHardwareDeviceSession OpenDeviceSession(Direction direction, IVirtualMemoryManager memoryManager, SampleFormat sampleFormat, uint sampleRate, uint channelCount, float volume = 1f); @@ -33,4 +33,4 @@ namespace Ryujinx.Audio.Integration return this; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Integration/IHardwareDeviceSession.cs b/src/Ryujinx.Audio/Integration/IHardwareDeviceSession.cs index 400daec00..f29c109cb 100644 --- a/src/Ryujinx.Audio/Integration/IHardwareDeviceSession.cs +++ b/src/Ryujinx.Audio/Integration/IHardwareDeviceSession.cs @@ -25,4 +25,4 @@ namespace Ryujinx.Audio.Integration void PrepareToClose(); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Integration/IWritableEvent.cs b/src/Ryujinx.Audio/Integration/IWritableEvent.cs index 9a12e3d28..a3b3bc0bc 100644 --- a/src/Ryujinx.Audio/Integration/IWritableEvent.cs +++ b/src/Ryujinx.Audio/Integration/IWritableEvent.cs @@ -15,4 +15,4 @@ namespace Ryujinx.Audio.Integration /// void Clear(); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Output/AudioOutputManager.cs b/src/Ryujinx.Audio/Output/AudioOutputManager.cs index bc2fc6f43..5232357bb 100644 --- a/src/Ryujinx.Audio/Output/AudioOutputManager.cs +++ b/src/Ryujinx.Audio/Output/AudioOutputManager.cs @@ -24,7 +24,7 @@ namespace Ryujinx.Audio.Output /// /// The session ids allocation table. /// - private int[] _sessionIds; + private readonly int[] _sessionIds; /// /// The device driver. @@ -39,7 +39,7 @@ namespace Ryujinx.Audio.Output /// /// The session instances. /// - private AudioOutputSystem[] _sessions; + private readonly AudioOutputSystem[] _sessions; /// /// The count of active sessions. @@ -165,10 +165,12 @@ namespace Ryujinx.Audio.Output /// Get the list of all audio outputs name. /// /// The list of all audio outputs name +#pragma warning disable CA1822 // Mark member as static public string[] ListAudioOuts() { - return new string[] { Constants.DefaultDeviceOutputName }; + return new[] { Constants.DefaultDeviceOutputName }; } +#pragma warning restore CA1822 /// /// Open a new . @@ -182,6 +184,7 @@ namespace Ryujinx.Audio.Output /// The user configuration /// The applet resource user id of the application /// The process handle of the application + /// The volume level to request /// A reporting an error or a success public ResultCode OpenAudioOut(out string outputDeviceName, out AudioOutputConfiguration outputConfiguration, @@ -200,7 +203,7 @@ namespace Ryujinx.Audio.Output IHardwareDeviceSession deviceSession = _deviceDriver.OpenDeviceSession(IHardwareDeviceDriver.Direction.Output, memoryManager, sampleFormat, parameter.SampleRate, parameter.ChannelCount, volume); - AudioOutputSystem audioOut = new AudioOutputSystem(this, _lock, deviceSession, _sessionsBufferEvents[sessionId]); + AudioOutputSystem audioOut = new(this, _lock, deviceSession, _sessionsBufferEvents[sessionId]); ResultCode result = audioOut.Initialize(inputDeviceName, sampleFormat, ref parameter, sessionId); @@ -268,6 +271,8 @@ namespace Ryujinx.Audio.Output public void Dispose() { + GC.SuppressFinalize(this); + if (Interlocked.CompareExchange(ref _disposeState, 1, 0) == 0) { Dispose(true); @@ -293,4 +298,4 @@ namespace Ryujinx.Audio.Output } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Output/AudioOutputSystem.cs b/src/Ryujinx.Audio/Output/AudioOutputSystem.cs index 8378f33f8..f9b9bdcf1 100644 --- a/src/Ryujinx.Audio/Output/AudioOutputSystem.cs +++ b/src/Ryujinx.Audio/Output/AudioOutputSystem.cs @@ -18,7 +18,7 @@ namespace Ryujinx.Audio.Output /// /// The session the . /// - private AudioDeviceSession _session; + private readonly AudioDeviceSession _session; /// /// The target device name of the . @@ -43,7 +43,7 @@ namespace Ryujinx.Audio.Output /// /// The owning this. /// - private AudioOutputManager _manager; + private readonly AudioOutputManager _manager; /// /// THe lock of the parent. @@ -90,11 +90,13 @@ namespace Ryujinx.Audio.Output { return ResultCode.DeviceNotFound; } - else if (configuration.SampleRate != 0 && configuration.SampleRate != Constants.TargetSampleRate) + + if (configuration.SampleRate != 0 && configuration.SampleRate != Constants.TargetSampleRate) { return ResultCode.UnsupportedSampleRate; } - else if (configuration.ChannelCount != 0 && configuration.ChannelCount != 1 && configuration.ChannelCount != 2 && configuration.ChannelCount != 6) + + if (configuration.ChannelCount != 0 && configuration.ChannelCount != 1 && configuration.ChannelCount != 2 && configuration.ChannelCount != 6) { return ResultCode.UnsupportedChannelConfiguration; } @@ -185,11 +187,11 @@ namespace Ryujinx.Audio.Output { lock (_parentLock) { - AudioBuffer buffer = new AudioBuffer + AudioBuffer buffer = new() { BufferTag = bufferTag, DataPointer = userBuffer.Data, - DataSize = userBuffer.DataSize + DataSize = userBuffer.DataSize, }; if (_session.AppendBuffer(buffer)) @@ -346,6 +348,8 @@ namespace Ryujinx.Audio.Output public void Dispose() { + GC.SuppressFinalize(this); + if (Interlocked.CompareExchange(ref _disposeState, 1, 0) == 0) { Dispose(true); @@ -362,4 +366,4 @@ namespace Ryujinx.Audio.Output } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/AuxiliaryBufferAddresses.cs b/src/Ryujinx.Audio/Renderer/Common/AuxiliaryBufferAddresses.cs index 966474052..b7b97d5d8 100644 --- a/src/Ryujinx.Audio/Renderer/Common/AuxiliaryBufferAddresses.cs +++ b/src/Ryujinx.Audio/Renderer/Common/AuxiliaryBufferAddresses.cs @@ -10,4 +10,4 @@ namespace Ryujinx.Audio.Renderer.Common public ulong ReturnBufferInfo; public ulong ReturnBufferInfoBase; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/BehaviourParameter.cs b/src/Ryujinx.Audio/Renderer/Common/BehaviourParameter.cs index 270f84d5b..b0963c935 100644 --- a/src/Ryujinx.Audio/Renderer/Common/BehaviourParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Common/BehaviourParameter.cs @@ -16,7 +16,7 @@ namespace Ryujinx.Audio.Renderer.Common /// /// Reserved/padding. /// - private uint _padding; + private readonly uint _padding; /// /// The flags given controlling behaviour of the audio renderer @@ -38,7 +38,7 @@ namespace Ryujinx.Audio.Renderer.Common /// /// Reserved/padding. /// - private uint _padding; + private readonly uint _padding; /// /// Extra information given with the @@ -47,4 +47,4 @@ namespace Ryujinx.Audio.Renderer.Common public ulong ExtraErrorInfo; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/EdgeMatrix.cs b/src/Ryujinx.Audio/Renderer/Common/EdgeMatrix.cs index 24a9350fc..3beb62399 100644 --- a/src/Ryujinx.Audio/Renderer/Common/EdgeMatrix.cs +++ b/src/Ryujinx.Audio/Renderer/Common/EdgeMatrix.cs @@ -147,4 +147,4 @@ namespace Ryujinx.Audio.Renderer.Common return _nodeCount; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/EffectType.cs b/src/Ryujinx.Audio/Renderer/Common/EffectType.cs index 7128db4ce..7c8713b12 100644 --- a/src/Ryujinx.Audio/Renderer/Common/EffectType.cs +++ b/src/Ryujinx.Audio/Renderer/Common/EffectType.cs @@ -55,4 +55,4 @@ namespace Ryujinx.Audio.Renderer.Common /// Compressor, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/MemoryPoolUserState.cs b/src/Ryujinx.Audio/Renderer/Common/MemoryPoolUserState.cs index 590731c3b..6d835879c 100644 --- a/src/Ryujinx.Audio/Renderer/Common/MemoryPoolUserState.cs +++ b/src/Ryujinx.Audio/Renderer/Common/MemoryPoolUserState.cs @@ -38,6 +38,6 @@ namespace Ryujinx.Audio.Renderer.Common /// /// The memory pool is released. (client side only) /// - Released = 6 + Released = 6, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/NodeIdHelper.cs b/src/Ryujinx.Audio/Renderer/Common/NodeIdHelper.cs index a999e3ad1..76fba54b6 100644 --- a/src/Ryujinx.Audio/Renderer/Common/NodeIdHelper.cs +++ b/src/Ryujinx.Audio/Renderer/Common/NodeIdHelper.cs @@ -25,4 +25,4 @@ namespace Ryujinx.Audio.Renderer.Common return (nodeId >> 16) & 0xFFF; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/NodeIdType.cs b/src/Ryujinx.Audio/Renderer/Common/NodeIdType.cs index 69b58f6bc..b226da14f 100644 --- a/src/Ryujinx.Audio/Renderer/Common/NodeIdType.cs +++ b/src/Ryujinx.Audio/Renderer/Common/NodeIdType.cs @@ -28,6 +28,6 @@ namespace Ryujinx.Audio.Renderer.Common /// /// Performance monitoring related node id (performance commands) /// - Performance = 15 + Performance = 15, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/NodeStates.cs b/src/Ryujinx.Audio/Renderer/Common/NodeStates.cs index 45748d606..75290a741 100644 --- a/src/Ryujinx.Audio/Renderer/Common/NodeStates.cs +++ b/src/Ryujinx.Audio/Renderer/Common/NodeStates.cs @@ -53,17 +53,17 @@ namespace Ryujinx.Audio.Renderer.Common } private int _nodeCount; - private EdgeMatrix _discovered; - private EdgeMatrix _finished; + private readonly EdgeMatrix _discovered; + private readonly EdgeMatrix _finished; private Memory _resultArray; - private Stack _stack; + private readonly Stack _stack; private int _tsortResultIndex; private enum NodeState : byte { Unknown, Discovered, - Finished + Finished, } public NodeStates() @@ -88,16 +88,16 @@ namespace Ryujinx.Audio.Renderer.Common int edgeMatrixWorkBufferSize = EdgeMatrix.GetWorkBufferSize(nodeCount); - _discovered.Initialize(nodeStatesWorkBuffer.Slice(0, edgeMatrixWorkBufferSize), nodeCount); + _discovered.Initialize(nodeStatesWorkBuffer[..edgeMatrixWorkBufferSize], nodeCount); _finished.Initialize(nodeStatesWorkBuffer.Slice(edgeMatrixWorkBufferSize, edgeMatrixWorkBufferSize), nodeCount); - nodeStatesWorkBuffer = nodeStatesWorkBuffer.Slice(edgeMatrixWorkBufferSize * 2); + nodeStatesWorkBuffer = nodeStatesWorkBuffer[(edgeMatrixWorkBufferSize * 2)..]; - _resultArray = SpanMemoryManager.Cast(nodeStatesWorkBuffer.Slice(0, sizeof(int) * nodeCount)); + _resultArray = SpanMemoryManager.Cast(nodeStatesWorkBuffer[..(sizeof(int) * nodeCount)]); - nodeStatesWorkBuffer = nodeStatesWorkBuffer.Slice(sizeof(int) * nodeCount); + nodeStatesWorkBuffer = nodeStatesWorkBuffer[(sizeof(int) * nodeCount)..]; - Memory stackWorkBuffer = SpanMemoryManager.Cast(nodeStatesWorkBuffer.Slice(0, Stack.CalcBufferSize(nodeCount * nodeCount))); + Memory stackWorkBuffer = SpanMemoryManager.Cast(nodeStatesWorkBuffer[..Stack.CalcBufferSize(nodeCount * nodeCount)]); _stack.Reset(stackWorkBuffer, nodeCount * nodeCount); } @@ -120,7 +120,8 @@ namespace Ryujinx.Audio.Renderer.Common return NodeState.Discovered; } - else if (_finished.Test(index)) + + if (_finished.Test(index)) { Debug.Assert(!_discovered.Test(index)); @@ -158,7 +159,7 @@ namespace Ryujinx.Audio.Renderer.Common public ReadOnlySpan GetTsortResult() { - return _resultArray.Span.Slice(0, _tsortResultIndex); + return _resultArray.Span[.._tsortResultIndex]; } public bool Sort(EdgeMatrix edgeMatrix) @@ -226,4 +227,4 @@ namespace Ryujinx.Audio.Renderer.Common return true; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/PerformanceDetailType.cs b/src/Ryujinx.Audio/Renderer/Common/PerformanceDetailType.cs index 805d55183..bde32a709 100644 --- a/src/Ryujinx.Audio/Renderer/Common/PerformanceDetailType.cs +++ b/src/Ryujinx.Audio/Renderer/Common/PerformanceDetailType.cs @@ -15,6 +15,6 @@ namespace Ryujinx.Audio.Renderer.Common PcmFloat, Limiter, CaptureBuffer, - Compressor + Compressor, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/PerformanceEntryType.cs b/src/Ryujinx.Audio/Renderer/Common/PerformanceEntryType.cs index bde72aaed..e32095e62 100644 --- a/src/Ryujinx.Audio/Renderer/Common/PerformanceEntryType.cs +++ b/src/Ryujinx.Audio/Renderer/Common/PerformanceEntryType.cs @@ -6,6 +6,6 @@ namespace Ryujinx.Audio.Renderer.Common Voice, SubMix, FinalMix, - Sink + Sink, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/PlayState.cs b/src/Ryujinx.Audio/Renderer/Common/PlayState.cs index 4a6929e03..a83d16afb 100644 --- a/src/Ryujinx.Audio/Renderer/Common/PlayState.cs +++ b/src/Ryujinx.Audio/Renderer/Common/PlayState.cs @@ -18,6 +18,6 @@ namespace Ryujinx.Audio.Renderer.Common /// /// The user request the voice to be paused. /// - Pause + Pause, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/ReverbEarlyMode.cs b/src/Ryujinx.Audio/Renderer/Common/ReverbEarlyMode.cs index aa7685621..c7443cc49 100644 --- a/src/Ryujinx.Audio/Renderer/Common/ReverbEarlyMode.cs +++ b/src/Ryujinx.Audio/Renderer/Common/ReverbEarlyMode.cs @@ -28,6 +28,6 @@ namespace Ryujinx.Audio.Renderer.Common /// /// No early reflection. /// - Disabled + Disabled, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/ReverbLateMode.cs b/src/Ryujinx.Audio/Renderer/Common/ReverbLateMode.cs index 8aa88165a..78f91cf08 100644 --- a/src/Ryujinx.Audio/Renderer/Common/ReverbLateMode.cs +++ b/src/Ryujinx.Audio/Renderer/Common/ReverbLateMode.cs @@ -33,6 +33,6 @@ namespace Ryujinx.Audio.Renderer.Common /// /// Max delay. (used for delay line limits) /// - Limit = NoDelay + Limit = NoDelay, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/SinkType.cs b/src/Ryujinx.Audio/Renderer/Common/SinkType.cs index 2e17201e7..5a08df4e1 100644 --- a/src/Ryujinx.Audio/Renderer/Common/SinkType.cs +++ b/src/Ryujinx.Audio/Renderer/Common/SinkType.cs @@ -18,6 +18,6 @@ namespace Ryujinx.Audio.Renderer.Common /// /// The sink is a circular buffer. /// - CircularBuffer + CircularBuffer, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/UpdateDataHeader.cs b/src/Ryujinx.Audio/Renderer/Common/UpdateDataHeader.cs index 70dbfa947..7efe3b02b 100644 --- a/src/Ryujinx.Audio/Renderer/Common/UpdateDataHeader.cs +++ b/src/Ryujinx.Audio/Renderer/Common/UpdateDataHeader.cs @@ -1,3 +1,4 @@ +using Ryujinx.Common.Memory; using System.Runtime.CompilerServices; namespace Ryujinx.Audio.Renderer.Common @@ -19,7 +20,9 @@ namespace Ryujinx.Audio.Renderer.Common public uint Unknown24; public uint RenderInfoSize; - private unsafe fixed int _reserved[4]; +#pragma warning disable IDE0051, CS0169 // Remove unused field + private Array4 _reserved; +#pragma warning restore IDE0051, CS0169 public uint TotalSize; @@ -30,4 +33,4 @@ namespace Ryujinx.Audio.Renderer.Common TotalSize = (uint)Unsafe.SizeOf(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/VoiceUpdateState.cs b/src/Ryujinx.Audio/Renderer/Common/VoiceUpdateState.cs index f52c2f4c4..608381af1 100644 --- a/src/Ryujinx.Audio/Renderer/Common/VoiceUpdateState.cs +++ b/src/Ryujinx.Audio/Renderer/Common/VoiceUpdateState.cs @@ -101,4 +101,4 @@ namespace Ryujinx.Audio.Renderer.Common } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/WaveBuffer.cs b/src/Ryujinx.Audio/Renderer/Common/WaveBuffer.cs index 0d00e8384..5109d3fa0 100644 --- a/src/Ryujinx.Audio/Renderer/Common/WaveBuffer.cs +++ b/src/Ryujinx.Audio/Renderer/Common/WaveBuffer.cs @@ -1,5 +1,4 @@ using System.Runtime.InteropServices; - using DspAddr = System.UInt64; namespace Ryujinx.Audio.Renderer.Common @@ -77,6 +76,6 @@ namespace Ryujinx.Audio.Renderer.Common /// /// Padding/Reserved. /// - private ushort _padding; + private readonly ushort _padding; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/WorkBufferAllocator.cs b/src/Ryujinx.Audio/Renderer/Common/WorkBufferAllocator.cs index f35dbec7f..54673f2f6 100644 --- a/src/Ryujinx.Audio/Renderer/Common/WorkBufferAllocator.cs +++ b/src/Ryujinx.Audio/Renderer/Common/WorkBufferAllocator.cs @@ -23,7 +23,7 @@ namespace Ryujinx.Audio.Renderer.Common if (size != 0) { - ulong alignedOffset = BitUtils.AlignUp(Offset, (ulong)align); + ulong alignedOffset = BitUtils.AlignUp(Offset, (ulong)align); if (alignedOffset + size <= (ulong)BackingMemory.Length) { @@ -32,7 +32,7 @@ namespace Ryujinx.Audio.Renderer.Common Offset = alignedOffset + size; // Clear the memory to be sure that is does not contain any garbage. - result.Span.Fill(0); + result.Span.Clear(); return result; } @@ -55,7 +55,7 @@ namespace Ryujinx.Audio.Renderer.Common public static ulong GetTargetSize(ulong currentSize, ulong count, int align) where T : unmanaged { - return BitUtils.AlignUp(currentSize, (ulong)align) + (ulong)Unsafe.SizeOf() * count; + return BitUtils.AlignUp(currentSize, (ulong)align) + (ulong)Unsafe.SizeOf() * count; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Device/VirtualDevice.cs b/src/Ryujinx.Audio/Renderer/Device/VirtualDevice.cs index 90692b004..91956fda6 100644 --- a/src/Ryujinx.Audio/Renderer/Device/VirtualDevice.cs +++ b/src/Ryujinx.Audio/Renderer/Device/VirtualDevice.cs @@ -12,11 +12,11 @@ namespace Ryujinx.Audio.Renderer.Device /// public static readonly VirtualDevice[] Devices = new VirtualDevice[5] { - new VirtualDevice("AudioStereoJackOutput", 2, true), - new VirtualDevice("AudioBuiltInSpeakerOutput", 2, false), - new VirtualDevice("AudioTvOutput", 6, false), - new VirtualDevice("AudioUsbDeviceOutput", 2, true), - new VirtualDevice("AudioExternalOutput", 6, true), + new("AudioStereoJackOutput", 2, true), + new("AudioBuiltInSpeakerOutput", 2, false), + new("AudioTvOutput", 6, false), + new("AudioUsbDeviceOutput", 2, true), + new("AudioExternalOutput", 6, true), }; /// @@ -86,4 +86,4 @@ namespace Ryujinx.Audio.Renderer.Device return Name; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Device/VirtualDeviceSession.cs b/src/Ryujinx.Audio/Renderer/Device/VirtualDeviceSession.cs index db35d26d2..09fa71eda 100644 --- a/src/Ryujinx.Audio/Renderer/Device/VirtualDeviceSession.cs +++ b/src/Ryujinx.Audio/Renderer/Device/VirtualDeviceSession.cs @@ -24,4 +24,4 @@ namespace Ryujinx.Audio.Renderer.Device Device = virtualDevice; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Device/VirtualDeviceSessionRegistry.cs b/src/Ryujinx.Audio/Renderer/Device/VirtualDeviceSessionRegistry.cs index 696af90fa..4ad70619e 100644 --- a/src/Ryujinx.Audio/Renderer/Device/VirtualDeviceSessionRegistry.cs +++ b/src/Ryujinx.Audio/Renderer/Device/VirtualDeviceSessionRegistry.cs @@ -11,13 +11,15 @@ namespace Ryujinx.Audio.Renderer.Device /// /// The session registry, used to store the sessions of a given AppletResourceId. /// - private Dictionary _sessionsRegistry = new Dictionary(); + private readonly Dictionary _sessionsRegistry = new(); /// /// The default . /// /// This is used when the USB device is the default one on older revision. +#pragma warning disable CA1822 // Mark member as static public VirtualDevice DefaultDevice => VirtualDevice.Devices[0]; +#pragma warning restore CA1822 /// /// The current active . @@ -76,4 +78,4 @@ namespace Ryujinx.Audio.Renderer.Device return virtualDeviceSession; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/AdpcmHelper.cs b/src/Ryujinx.Audio/Renderer/Dsp/AdpcmHelper.cs index 2680dcb1e..5cb4509ff 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/AdpcmHelper.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/AdpcmHelper.cs @@ -12,7 +12,9 @@ namespace Ryujinx.Audio.Renderer.Dsp private const int SamplesPerFrame = 14; private const int NibblesPerFrame = SamplesPerFrame + 2; private const int BytesPerFrame = 8; +#pragma warning disable IDE0051 // Remove unused private member private const int BitsPerFrame = BytesPerFrame * 8; +#pragma warning restore IDE0051 [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint GetAdpcmDataSize(int sampleCount) @@ -64,10 +66,14 @@ namespace Ryujinx.Audio.Renderer.Dsp private static short Saturate(int value) { if (value > short.MaxValue) + { value = short.MaxValue; + } if (value < short.MinValue) + { value = short.MinValue; + } return (short)value; } @@ -109,7 +115,7 @@ namespace Ryujinx.Audio.Renderer.Dsp ReadOnlySpan targetInput; - targetInput = input.Slice(nibbles / 2); + targetInput = input[(nibbles / 2)..]; while (remaining > 0) { @@ -213,4 +219,4 @@ namespace Ryujinx.Audio.Renderer.Dsp return decodedCount; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/AudioProcessor.cs b/src/Ryujinx.Audio/Renderer/Dsp/AudioProcessor.cs index 899c2ef97..9c885b2cf 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/AudioProcessor.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/AudioProcessor.cs @@ -18,7 +18,7 @@ namespace Ryujinx.Audio.Renderer.Dsp Start, Stop, RenderStart, - RenderEnd + RenderEnd, } private class RendererSession @@ -36,7 +36,7 @@ namespace Ryujinx.Audio.Renderer.Dsp private long _lastTime; private long _playbackEnds; - private ManualResetEvent _event; + private readonly ManualResetEvent _event; private ManualResetEvent _pauseEvent; @@ -45,6 +45,7 @@ namespace Ryujinx.Audio.Renderer.Dsp _event = new ManualResetEvent(false); } +#pragma warning disable IDE0051 // Remove unused private member private static uint GetHardwareChannelCount(IHardwareDeviceDriver deviceDriver) { // Get the real device driver (In case the compat layer is on top of it). @@ -54,12 +55,11 @@ namespace Ryujinx.Audio.Renderer.Dsp { return 6; } - else - { - // NOTE: We default to stereo as this will get downmixed to mono by the compat layer if it's not compatible. - return 2; - } + + // NOTE: We default to stereo as this will get downmixed to mono by the compat layer if it's not compatible. + return 2; } +#pragma warning restore IDE0051 public void Start(IHardwareDeviceDriver deviceDriver, float volume) { @@ -110,7 +110,7 @@ namespace Ryujinx.Audio.Renderer.Dsp { CommandList = commands, RenderingLimit = renderingLimit, - AppletResourceId = appletResourceId + AppletResourceId = appletResourceId, }; } @@ -171,7 +171,7 @@ namespace Ryujinx.Audio.Renderer.Dsp { _workerThread = new Thread(Work) { - Name = "AudioProcessor.Worker" + Name = "AudioProcessor.Worker", }; _workerThread.Start(); @@ -260,6 +260,7 @@ namespace Ryujinx.Audio.Renderer.Dsp public void Dispose() { + GC.SuppressFinalize(this); Dispose(true); } @@ -271,4 +272,4 @@ namespace Ryujinx.Audio.Renderer.Dsp } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/BiquadFilterHelper.cs b/src/Ryujinx.Audio/Renderer/Dsp/BiquadFilterHelper.cs index 98460ff1a..1a51a1fbd 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/BiquadFilterHelper.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/BiquadFilterHelper.cs @@ -80,4 +80,4 @@ namespace Ryujinx.Audio.Renderer.Dsp } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/AdpcmDataSourceCommandVersion1.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/AdpcmDataSourceCommandVersion1.cs index 1fe6069f7..51a12b4e7 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/AdpcmDataSourceCommandVersion1.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/AdpcmDataSourceCommandVersion1.cs @@ -1,7 +1,9 @@ using Ryujinx.Audio.Common; using Ryujinx.Audio.Renderer.Common; +using Ryujinx.Audio.Renderer.Server.Voice; using System; using static Ryujinx.Audio.Renderer.Parameter.VoiceInParameter; +using WaveBuffer = Ryujinx.Audio.Renderer.Common.WaveBuffer; namespace Ryujinx.Audio.Renderer.Dsp.Command { @@ -29,7 +31,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command public DecodingBehaviour DecodingBehaviour { get; } - public AdpcmDataSourceCommandVersion1(ref Server.Voice.VoiceState serverState, Memory state, ushort outputBufferIndex, int nodeId) + public AdpcmDataSourceCommandVersion1(ref VoiceState serverState, Memory state, ushort outputBufferIndex, int nodeId) { Enabled = true; NodeId = nodeId; @@ -57,7 +59,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command { Span outputBuffer = context.GetBuffer(OutputBufferIndex); - DataSourceHelper.WaveBufferInformation info = new DataSourceHelper.WaveBufferInformation + DataSourceHelper.WaveBufferInformation info = new() { SourceSampleRate = SampleRate, SampleFormat = SampleFormat.Adpcm, @@ -72,4 +74,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command DataSourceHelper.ProcessWaveBuffers(context.MemoryManager, outputBuffer, ref info, WaveBuffers, ref State.Span[0], context.SampleRate, (int)context.SampleCount); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/AuxiliaryBufferCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/AuxiliaryBufferCommand.cs index 5c3c0324b..7ed32800f 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/AuxiliaryBufferCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/AuxiliaryBufferCommand.cs @@ -155,7 +155,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command if (readResult != context.SampleCount) { - outputBuffer.Slice((int)readResult, (int)context.SampleCount - (int)readResult).Fill(0); + outputBuffer[(int)readResult..(int)context.SampleCount].Clear(); } } else @@ -170,4 +170,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/BiquadFilterCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/BiquadFilterCommand.cs index b994c1cb9..f56dd70e3 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/BiquadFilterCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/BiquadFilterCommand.cs @@ -48,4 +48,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command BiquadFilterHelper.ProcessBiquadFilter(ref _parameter, ref state, outputBuffer, inputBuffer, context.SampleCount); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/CaptureBufferCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/CaptureBufferCommand.cs index da1cb2546..01bff1e7d 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/CaptureBufferCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/CaptureBufferCommand.cs @@ -133,4 +133,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/ClearMixBufferCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/ClearMixBufferCommand.cs index 9e653e804..f0f85b0b2 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/ClearMixBufferCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/ClearMixBufferCommand.cs @@ -21,4 +21,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command context.ClearBuffers(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/CommandList.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/CommandList.cs index 2cbed9c2b..19a9576f7 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/CommandList.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/CommandList.cs @@ -71,7 +71,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command return (IntPtr)((float*)_buffersMemoryHandle.Pointer + index * _sampleCount); } - throw new ArgumentOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(index), index, null); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -149,7 +149,8 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command public void Dispose() { + GC.SuppressFinalize(this); _buffersMemoryHandle.Dispose(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/CommandType.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/CommandType.cs index 9ce181b17..098a04a04 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/CommandType.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/CommandType.cs @@ -32,6 +32,6 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command LimiterVersion2, GroupedBiquadFilter, CaptureBuffer, - Compressor + Compressor, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/CompressorCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/CompressorCommand.cs index 34231e614..01291852e 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/CompressorCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/CompressorCommand.cs @@ -1,6 +1,7 @@ using Ryujinx.Audio.Renderer.Dsp.Effect; using Ryujinx.Audio.Renderer.Dsp.State; using Ryujinx.Audio.Renderer.Parameter.Effect; +using Ryujinx.Audio.Renderer.Server.Effect; using System; using System.Diagnostics; @@ -51,11 +52,11 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command if (IsEffectEnabled) { - if (_parameter.Status == Server.Effect.UsageState.Invalid) + if (_parameter.Status == UsageState.Invalid) { state = new CompressorState(ref _parameter); } - else if (_parameter.Status == Server.Effect.UsageState.New) + else if (_parameter.Status == UsageState.New) { state.UpdateParameter(ref _parameter); } diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/CopyMixBufferCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/CopyMixBufferCommand.cs index 7237fddf6..3f6aa8390 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/CopyMixBufferCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/CopyMixBufferCommand.cs @@ -27,4 +27,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command context.CopyBuffer(OutputBufferIndex, InputBufferIndex); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/DataSourceVersion2Command.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/DataSourceVersion2Command.cs index c1503b6a0..e82d403bf 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/DataSourceVersion2Command.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/DataSourceVersion2Command.cs @@ -1,7 +1,9 @@ using Ryujinx.Audio.Common; using Ryujinx.Audio.Renderer.Common; +using Ryujinx.Audio.Renderer.Server.Voice; using System; using static Ryujinx.Audio.Renderer.Parameter.VoiceInParameter; +using WaveBuffer = Ryujinx.Audio.Renderer.Common.WaveBuffer; namespace Ryujinx.Audio.Renderer.Dsp.Command { @@ -37,7 +39,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command public SampleRateConversionQuality SrcQuality { get; } - public DataSourceVersion2Command(ref Server.Voice.VoiceState serverState, Memory state, ushort outputBufferIndex, ushort channelIndex, int nodeId) + public DataSourceVersion2Command(ref VoiceState serverState, Memory state, ushort outputBufferIndex, ushort channelIndex, int nodeId) { Enabled = true; NodeId = nodeId; @@ -72,24 +74,20 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command private static CommandType GetCommandTypeBySampleFormat(SampleFormat sampleFormat) { - switch (sampleFormat) + return sampleFormat switch { - case SampleFormat.Adpcm: - return CommandType.AdpcmDataSourceVersion2; - case SampleFormat.PcmInt16: - return CommandType.PcmInt16DataSourceVersion2; - case SampleFormat.PcmFloat: - return CommandType.PcmFloatDataSourceVersion2; - default: - throw new NotImplementedException($"{sampleFormat}"); - } + SampleFormat.Adpcm => CommandType.AdpcmDataSourceVersion2, + SampleFormat.PcmInt16 => CommandType.PcmInt16DataSourceVersion2, + SampleFormat.PcmFloat => CommandType.PcmFloatDataSourceVersion2, + _ => throw new NotImplementedException($"{sampleFormat}"), + }; } public void Process(CommandList context) { Span outputBuffer = context.GetBuffer(OutputBufferIndex); - DataSourceHelper.WaveBufferInformation info = new DataSourceHelper.WaveBufferInformation + DataSourceHelper.WaveBufferInformation info = new() { SourceSampleRate = SampleRate, SampleFormat = SampleFormat, @@ -99,10 +97,10 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command ExtraParameterSize = ExtraParameterSize, ChannelIndex = (int)ChannelIndex, ChannelCount = (int)ChannelCount, - SrcQuality = SrcQuality + SrcQuality = SrcQuality, }; DataSourceHelper.ProcessWaveBuffers(context.MemoryManager, outputBuffer, ref info, WaveBuffers, ref State.Span[0], context.SampleRate, (int)context.SampleCount); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/DelayCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/DelayCommand.cs index e7e179389..003806cf7 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/DelayCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/DelayCommand.cs @@ -87,18 +87,18 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command float dryGain = FixedPointHelper.ToFloat(Parameter.DryGain, FixedPointPrecision); float outGain = FixedPointHelper.ToFloat(Parameter.OutGain, FixedPointPrecision); - Matrix2x2 delayFeedback = new Matrix2x2(delayFeedbackBaseGain, delayFeedbackCrossGain, + Matrix2x2 delayFeedback = new(delayFeedbackBaseGain, delayFeedbackCrossGain, delayFeedbackCrossGain, delayFeedbackBaseGain); for (int i = 0; i < sampleCount; i++) { - Vector2 channelInput = new Vector2 + Vector2 channelInput = new() { X = *((float*)inputBuffers[0] + i) * 64, Y = *((float*)inputBuffers[1] + i) * 64, }; - Vector2 delayLineValues = new Vector2() + Vector2 delayLineValues = new() { X = state.DelayLines[0].Read(), Y = state.DelayLines[1].Read(), @@ -124,7 +124,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command float dryGain = FixedPointHelper.ToFloat(Parameter.DryGain, FixedPointPrecision); float outGain = FixedPointHelper.ToFloat(Parameter.OutGain, FixedPointPrecision); - Matrix4x4 delayFeedback = new Matrix4x4(delayFeedbackBaseGain, delayFeedbackCrossGain, delayFeedbackCrossGain, 0.0f, + Matrix4x4 delayFeedback = new(delayFeedbackBaseGain, delayFeedbackCrossGain, delayFeedbackCrossGain, 0.0f, delayFeedbackCrossGain, delayFeedbackBaseGain, 0.0f, delayFeedbackCrossGain, delayFeedbackCrossGain, 0.0f, delayFeedbackBaseGain, delayFeedbackCrossGain, 0.0f, delayFeedbackCrossGain, delayFeedbackCrossGain, delayFeedbackBaseGain); @@ -132,20 +132,20 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command for (int i = 0; i < sampleCount; i++) { - Vector4 channelInput = new Vector4 + Vector4 channelInput = new() { X = *((float*)inputBuffers[0] + i) * 64, Y = *((float*)inputBuffers[1] + i) * 64, Z = *((float*)inputBuffers[2] + i) * 64, - W = *((float*)inputBuffers[3] + i) * 64 + W = *((float*)inputBuffers[3] + i) * 64, }; - Vector4 delayLineValues = new Vector4() + Vector4 delayLineValues = new() { X = state.DelayLines[0].Read(), Y = state.DelayLines[1].Read(), Z = state.DelayLines[2].Read(), - W = state.DelayLines[3].Read() + W = state.DelayLines[3].Read(), }; Vector4 temp = MatrixHelper.Transform(ref delayLineValues, ref delayFeedback) + channelInput * inGain; @@ -171,7 +171,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command float dryGain = FixedPointHelper.ToFloat(Parameter.DryGain, FixedPointPrecision); float outGain = FixedPointHelper.ToFloat(Parameter.OutGain, FixedPointPrecision); - Matrix6x6 delayFeedback = new Matrix6x6(delayFeedbackBaseGain, 0.0f, delayFeedbackCrossGain, 0.0f, delayFeedbackCrossGain, 0.0f, + Matrix6x6 delayFeedback = new(delayFeedbackBaseGain, 0.0f, delayFeedbackCrossGain, 0.0f, delayFeedbackCrossGain, 0.0f, 0.0f, delayFeedbackBaseGain, delayFeedbackCrossGain, 0.0f, 0.0f, delayFeedbackCrossGain, delayFeedbackCrossGain, delayFeedbackCrossGain, delayFeedbackBaseGain, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, feedbackGain, 0.0f, 0.0f, @@ -180,24 +180,24 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command for (int i = 0; i < sampleCount; i++) { - Vector6 channelInput = new Vector6 + Vector6 channelInput = new() { X = *((float*)inputBuffers[0] + i) * 64, Y = *((float*)inputBuffers[1] + i) * 64, Z = *((float*)inputBuffers[2] + i) * 64, W = *((float*)inputBuffers[3] + i) * 64, V = *((float*)inputBuffers[4] + i) * 64, - U = *((float*)inputBuffers[5] + i) * 64 + U = *((float*)inputBuffers[5] + i) * 64, }; - Vector6 delayLineValues = new Vector6 + Vector6 delayLineValues = new() { X = state.DelayLines[0].Read(), Y = state.DelayLines[1].Read(), Z = state.DelayLines[2].Read(), W = state.DelayLines[3].Read(), V = state.DelayLines[4].Read(), - U = state.DelayLines[5].Read() + U = state.DelayLines[5].Read(), }; Vector6 temp = MatrixHelper.Transform(ref delayLineValues, ref delayFeedback) + channelInput * inGain; diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/DepopForMixBuffersCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/DepopForMixBuffersCommand.cs index 1dba56e6c..ff38f38ca 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/DepopForMixBuffersCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/DepopForMixBuffersCommand.cs @@ -55,17 +55,15 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command return -depopValue; } - else + + for (int i = 0; i < sampleCount; i++) { - for (int i = 0; i < sampleCount; i++) - { - depopValue = FloatingPointHelper.MultiplyRoundDown(Decay, depopValue); + depopValue = FloatingPointHelper.MultiplyRoundDown(Decay, depopValue); - buffer[i] += depopValue; - } - - return depopValue; + buffer[i] += depopValue; } + + return depopValue; } public void Process(CommandList context) @@ -89,4 +87,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/DepopPrepareCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/DepopPrepareCommand.cs index d02f7c121..c64bbdc57 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/DepopPrepareCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/DepopPrepareCommand.cs @@ -54,4 +54,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/DownMixSurroundToStereoCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/DownMixSurroundToStereoCommand.cs index 79cefcc53..8997b0dbd 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/DownMixSurroundToStereoCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/DownMixSurroundToStereoCommand.cs @@ -65,4 +65,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command context.ClearBuffer(OutputBufferIndices[5]); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/GroupedBiquadFilterCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/GroupedBiquadFilterCommand.cs index b190cc10d..7af851bdc 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/GroupedBiquadFilterCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/GroupedBiquadFilterCommand.cs @@ -14,11 +14,11 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command public uint EstimatedProcessingTime { get; set; } - private BiquadFilterParameter[] _parameters; - private Memory _biquadFilterStates; - private int _inputBufferIndex; - private int _outputBufferIndex; - private bool[] _isInitialized; + private readonly BiquadFilterParameter[] _parameters; + private readonly Memory _biquadFilterStates; + private readonly int _inputBufferIndex; + private readonly int _outputBufferIndex; + private readonly bool[] _isInitialized; public GroupedBiquadFilterCommand(int baseIndex, ReadOnlySpan filters, Memory biquadFilterStateMemory, int inputBufferOffset, int outputBufferOffset, ReadOnlySpan isInitialized, int nodeId) { @@ -59,4 +59,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/ICommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/ICommand.cs index d281e6e9f..34a62c58d 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/ICommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/ICommand.cs @@ -17,4 +17,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command return false; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/LimiterCommandVersion1.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/LimiterCommandVersion1.cs index a464ad704..3ba0b5884 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/LimiterCommandVersion1.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/LimiterCommandVersion1.cs @@ -1,5 +1,6 @@ using Ryujinx.Audio.Renderer.Dsp.State; using Ryujinx.Audio.Renderer.Parameter.Effect; +using Ryujinx.Audio.Renderer.Server.Effect; using System; using System.Diagnostics; @@ -50,13 +51,13 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command if (IsEffectEnabled) { - if (Parameter.Status == Server.Effect.UsageState.Invalid) + if (Parameter.Status == UsageState.Invalid) { state = new LimiterState(ref _parameter, WorkBuffer); } - else if (Parameter.Status == Server.Effect.UsageState.New) + else if (Parameter.Status == UsageState.New) { - state.UpdateParameter(ref _parameter); + LimiterState.UpdateParameter(ref _parameter); } } @@ -141,4 +142,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/LimiterCommandVersion2.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/LimiterCommandVersion2.cs index 950de97b8..682098670 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/LimiterCommandVersion2.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/LimiterCommandVersion2.cs @@ -1,6 +1,7 @@ using Ryujinx.Audio.Renderer.Dsp.State; using Ryujinx.Audio.Renderer.Parameter; using Ryujinx.Audio.Renderer.Parameter.Effect; +using Ryujinx.Audio.Renderer.Server.Effect; using System; using System.Diagnostics; using System.Runtime.InteropServices; @@ -54,13 +55,13 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command if (IsEffectEnabled) { - if (Parameter.Status == Server.Effect.UsageState.Invalid) + if (Parameter.Status == UsageState.Invalid) { state = new LimiterState(ref _parameter, WorkBuffer); } - else if (Parameter.Status == Server.Effect.UsageState.New) + else if (Parameter.Status == UsageState.New) { - state.UpdateParameter(ref _parameter); + LimiterState.UpdateParameter(ref _parameter); } } @@ -160,4 +161,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/MixCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/MixCommand.cs index 2616bda57..c701f80eb 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/MixCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/MixCommand.cs @@ -134,4 +134,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command ProcessMix(outputBuffer, inputBuffer); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/MixRampCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/MixRampCommand.cs index 76a1aba25..f77a233e1 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/MixRampCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/MixRampCommand.cs @@ -65,4 +65,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command State.Span[0].LastSamples[LastSampleIndex] = ProcessMixRamp(outputBuffer, inputBuffer, (int)context.SampleCount); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/MixRampGroupedCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/MixRampGroupedCommand.cs index e348e3588..3c7dd63b2 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/MixRampGroupedCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/MixRampGroupedCommand.cs @@ -48,7 +48,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private float ProcessMixRampGrouped(Span outputBuffer, ReadOnlySpan inputBuffer, float volume0, float volume1, int sampleCount) + private static float ProcessMixRampGrouped(Span outputBuffer, ReadOnlySpan inputBuffer, float volume0, float volume1, int sampleCount) { float ramp = (volume1 - volume0) / sampleCount; float volume = volume0; @@ -88,4 +88,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/PcmFloatDataSourceCommandVersion1.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/PcmFloatDataSourceCommandVersion1.cs index 7cec7d2ab..585edc058 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/PcmFloatDataSourceCommandVersion1.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/PcmFloatDataSourceCommandVersion1.cs @@ -1,7 +1,9 @@ using Ryujinx.Audio.Common; using Ryujinx.Audio.Renderer.Common; +using Ryujinx.Audio.Renderer.Server.Voice; using System; using static Ryujinx.Audio.Renderer.Parameter.VoiceInParameter; +using WaveBuffer = Ryujinx.Audio.Renderer.Common.WaveBuffer; namespace Ryujinx.Audio.Renderer.Dsp.Command { @@ -28,7 +30,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command public Memory State { get; } public DecodingBehaviour DecodingBehaviour { get; } - public PcmFloatDataSourceCommandVersion1(ref Server.Voice.VoiceState serverState, Memory state, ushort outputBufferIndex, ushort channelIndex, int nodeId) + public PcmFloatDataSourceCommandVersion1(ref VoiceState serverState, Memory state, ushort outputBufferIndex, ushort channelIndex, int nodeId) { Enabled = true; NodeId = nodeId; @@ -56,7 +58,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command { Span outputBuffer = context.GetBuffer(OutputBufferIndex); - DataSourceHelper.WaveBufferInformation info = new DataSourceHelper.WaveBufferInformation + DataSourceHelper.WaveBufferInformation info = new() { SourceSampleRate = SampleRate, SampleFormat = SampleFormat.PcmFloat, @@ -71,4 +73,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command DataSourceHelper.ProcessWaveBuffers(context.MemoryManager, outputBuffer, ref info, WaveBuffers, ref State.Span[0], context.SampleRate, (int)context.SampleCount); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/PcmInt16DataSourceCommandVersion1.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/PcmInt16DataSourceCommandVersion1.cs index dfe9814fe..6f01219f3 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/PcmInt16DataSourceCommandVersion1.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/PcmInt16DataSourceCommandVersion1.cs @@ -1,7 +1,9 @@ using Ryujinx.Audio.Common; using Ryujinx.Audio.Renderer.Common; +using Ryujinx.Audio.Renderer.Server.Voice; using System; using static Ryujinx.Audio.Renderer.Parameter.VoiceInParameter; +using WaveBuffer = Ryujinx.Audio.Renderer.Common.WaveBuffer; namespace Ryujinx.Audio.Renderer.Dsp.Command { @@ -28,7 +30,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command public Memory State { get; } public DecodingBehaviour DecodingBehaviour { get; } - public PcmInt16DataSourceCommandVersion1(ref Server.Voice.VoiceState serverState, Memory state, ushort outputBufferIndex, ushort channelIndex, int nodeId) + public PcmInt16DataSourceCommandVersion1(ref VoiceState serverState, Memory state, ushort outputBufferIndex, ushort channelIndex, int nodeId) { Enabled = true; NodeId = nodeId; @@ -56,7 +58,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command { Span outputBuffer = context.GetBuffer(OutputBufferIndex); - DataSourceHelper.WaveBufferInformation info = new DataSourceHelper.WaveBufferInformation + DataSourceHelper.WaveBufferInformation info = new() { SourceSampleRate = SampleRate, SampleFormat = SampleFormat.PcmInt16, @@ -71,4 +73,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command DataSourceHelper.ProcessWaveBuffers(context.MemoryManager, outputBuffer, ref info, WaveBuffers, ref State.Span[0], context.SampleRate, (int)context.SampleCount); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/PerformanceCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/PerformanceCommand.cs index d3e3f8056..d3d2ee306 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/PerformanceCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/PerformanceCommand.cs @@ -8,7 +8,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command { Invalid, Start, - End + End, } public bool Enabled { get; set; } @@ -44,4 +44,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/Reverb3dCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/Reverb3dCommand.cs index d1177e60f..8cdd4843b 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/Reverb3dCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/Reverb3dCommand.cs @@ -9,21 +9,21 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command { public class Reverb3dCommand : ICommand { - private static readonly int[] OutputEarlyIndicesTableMono = new int[20] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - private static readonly int[] TargetEarlyDelayLineIndicesTableMono = new int[20] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; - private static readonly int[] TargetOutputFeedbackIndicesTableMono = new int[1] { 0 }; + private static readonly int[] _outputEarlyIndicesTableMono = new int[20] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + private static readonly int[] _targetEarlyDelayLineIndicesTableMono = new int[20] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; + private static readonly int[] _targetOutputFeedbackIndicesTableMono = new int[1] { 0 }; - private static readonly int[] OutputEarlyIndicesTableStereo = new int[20] { 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1 }; - private static readonly int[] TargetEarlyDelayLineIndicesTableStereo = new int[20] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; - private static readonly int[] TargetOutputFeedbackIndicesTableStereo = new int[2] { 0, 1 }; + private static readonly int[] _outputEarlyIndicesTableStereo = new int[20] { 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1 }; + private static readonly int[] _targetEarlyDelayLineIndicesTableStereo = new int[20] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; + private static readonly int[] _targetOutputFeedbackIndicesTableStereo = new int[2] { 0, 1 }; - private static readonly int[] OutputEarlyIndicesTableQuadraphonic = new int[20] { 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 3, 3, 3 }; - private static readonly int[] TargetEarlyDelayLineIndicesTableQuadraphonic = new int[20] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; - private static readonly int[] TargetOutputFeedbackIndicesTableQuadraphonic = new int[4] { 0, 1, 2, 3 }; + private static readonly int[] _outputEarlyIndicesTableQuadraphonic = new int[20] { 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 3, 3, 3 }; + private static readonly int[] _targetEarlyDelayLineIndicesTableQuadraphonic = new int[20] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; + private static readonly int[] _targetOutputFeedbackIndicesTableQuadraphonic = new int[4] { 0, 1, 2, 3 }; - private static readonly int[] OutputEarlyIndicesTableSurround = new int[40] { 4, 5, 0, 5, 0, 5, 1, 5, 1, 5, 1, 5, 1, 5, 2, 5, 2, 5, 2, 5, 1, 5, 1, 5, 1, 5, 0, 5, 0, 5, 0, 5, 0, 5, 3, 5, 3, 5, 3, 5 }; - private static readonly int[] TargetEarlyDelayLineIndicesTableSurround = new int[40] { 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19 }; - private static readonly int[] TargetOutputFeedbackIndicesTableSurround = new int[6] { 0, 1, 2, 3, -1, 3 }; + private static readonly int[] _outputEarlyIndicesTableSurround = new int[40] { 4, 5, 0, 5, 0, 5, 1, 5, 1, 5, 1, 5, 1, 5, 2, 5, 2, 5, 2, 5, 1, 5, 1, 5, 1, 5, 0, 5, 0, 5, 0, 5, 0, 5, 3, 5, 3, 5, 3, 5 }; + private static readonly int[] _targetEarlyDelayLineIndicesTableSurround = new int[40] { 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19 }; + private static readonly int[] _targetOutputFeedbackIndicesTableSurround = new int[6] { 0, 1, 2, 3, -1, 3 }; public bool Enabled { get; set; } @@ -73,25 +73,25 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ProcessReverb3dMono(ref Reverb3dState state, ReadOnlySpan outputBuffers, ReadOnlySpan inputBuffers, uint sampleCount) { - ProcessReverb3dGeneric(ref state, outputBuffers, inputBuffers, sampleCount, OutputEarlyIndicesTableMono, TargetEarlyDelayLineIndicesTableMono, TargetOutputFeedbackIndicesTableMono); + ProcessReverb3dGeneric(ref state, outputBuffers, inputBuffers, sampleCount, _outputEarlyIndicesTableMono, _targetEarlyDelayLineIndicesTableMono, _targetOutputFeedbackIndicesTableMono); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ProcessReverb3dStereo(ref Reverb3dState state, ReadOnlySpan outputBuffers, ReadOnlySpan inputBuffers, uint sampleCount) { - ProcessReverb3dGeneric(ref state, outputBuffers, inputBuffers, sampleCount, OutputEarlyIndicesTableStereo, TargetEarlyDelayLineIndicesTableStereo, TargetOutputFeedbackIndicesTableStereo); + ProcessReverb3dGeneric(ref state, outputBuffers, inputBuffers, sampleCount, _outputEarlyIndicesTableStereo, _targetEarlyDelayLineIndicesTableStereo, _targetOutputFeedbackIndicesTableStereo); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ProcessReverb3dQuadraphonic(ref Reverb3dState state, ReadOnlySpan outputBuffers, ReadOnlySpan inputBuffers, uint sampleCount) { - ProcessReverb3dGeneric(ref state, outputBuffers, inputBuffers, sampleCount, OutputEarlyIndicesTableQuadraphonic, TargetEarlyDelayLineIndicesTableQuadraphonic, TargetOutputFeedbackIndicesTableQuadraphonic); + ProcessReverb3dGeneric(ref state, outputBuffers, inputBuffers, sampleCount, _outputEarlyIndicesTableQuadraphonic, _targetEarlyDelayLineIndicesTableQuadraphonic, _targetOutputFeedbackIndicesTableQuadraphonic); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ProcessReverb3dSurround(ref Reverb3dState state, ReadOnlySpan outputBuffers, ReadOnlySpan inputBuffers, uint sampleCount) { - ProcessReverb3dGeneric(ref state, outputBuffers, inputBuffers, sampleCount, OutputEarlyIndicesTableSurround, TargetEarlyDelayLineIndicesTableSurround, TargetOutputFeedbackIndicesTableSurround); + ProcessReverb3dGeneric(ref state, outputBuffers, inputBuffers, sampleCount, _outputEarlyIndicesTableSurround, _targetEarlyDelayLineIndicesTableSurround, _targetOutputFeedbackIndicesTableSurround); } private unsafe void ProcessReverb3dGeneric(ref Reverb3dState state, ReadOnlySpan outputBuffers, ReadOnlySpan inputBuffers, uint sampleCount, ReadOnlySpan outputEarlyIndicesTable, ReadOnlySpan targetEarlyDelayLineIndicesTable, ReadOnlySpan targetOutputFeedbackIndicesTable) @@ -109,7 +109,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command for (int sampleIndex = 0; sampleIndex < sampleCount; sampleIndex++) { - outputValues.Fill(0); + outputValues.Clear(); float tapOut = state.PreDelayLine.TapUnsafe(state.ReflectionDelayTime, DelayLineSampleIndexOffset); diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/ReverbCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/ReverbCommand.cs index cd08b838a..f494b3028 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/ReverbCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/ReverbCommand.cs @@ -1,5 +1,6 @@ using Ryujinx.Audio.Renderer.Dsp.State; using Ryujinx.Audio.Renderer.Parameter.Effect; +using Ryujinx.Audio.Renderer.Server.Effect; using System; using System.Diagnostics; using System.Runtime.CompilerServices; @@ -8,25 +9,25 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command { public class ReverbCommand : ICommand { - private static readonly int[] OutputEarlyIndicesTableMono = new int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - private static readonly int[] TargetEarlyDelayLineIndicesTableMono = new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - private static readonly int[] OutputIndicesTableMono = new int[4] { 0, 0, 0, 0 }; - private static readonly int[] TargetOutputFeedbackIndicesTableMono = new int[4] { 0, 1, 2, 3 }; + private static readonly int[] _outputEarlyIndicesTableMono = new int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + private static readonly int[] _targetEarlyDelayLineIndicesTableMono = new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + private static readonly int[] _outputIndicesTableMono = new int[4] { 0, 0, 0, 0 }; + private static readonly int[] _targetOutputFeedbackIndicesTableMono = new int[4] { 0, 1, 2, 3 }; - private static readonly int[] OutputEarlyIndicesTableStereo = new int[10] { 0, 0, 1, 1, 0, 1, 0, 0, 1, 1 }; - private static readonly int[] TargetEarlyDelayLineIndicesTableStereo = new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - private static readonly int[] OutputIndicesTableStereo = new int[4] { 0, 0, 1, 1 }; - private static readonly int[] TargetOutputFeedbackIndicesTableStereo = new int[4] { 2, 0, 3, 1 }; + private static readonly int[] _outputEarlyIndicesTableStereo = new int[10] { 0, 0, 1, 1, 0, 1, 0, 0, 1, 1 }; + private static readonly int[] _targetEarlyDelayLineIndicesTableStereo = new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + private static readonly int[] _outputIndicesTableStereo = new int[4] { 0, 0, 1, 1 }; + private static readonly int[] _targetOutputFeedbackIndicesTableStereo = new int[4] { 2, 0, 3, 1 }; - private static readonly int[] OutputEarlyIndicesTableQuadraphonic = new int[10] { 0, 0, 1, 1, 0, 1, 2, 2, 3, 3 }; - private static readonly int[] TargetEarlyDelayLineIndicesTableQuadraphonic = new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - private static readonly int[] OutputIndicesTableQuadraphonic = new int[4] { 0, 1, 2, 3 }; - private static readonly int[] TargetOutputFeedbackIndicesTableQuadraphonic = new int[4] { 0, 1, 2, 3 }; + private static readonly int[] _outputEarlyIndicesTableQuadraphonic = new int[10] { 0, 0, 1, 1, 0, 1, 2, 2, 3, 3 }; + private static readonly int[] _targetEarlyDelayLineIndicesTableQuadraphonic = new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + private static readonly int[] _outputIndicesTableQuadraphonic = new int[4] { 0, 1, 2, 3 }; + private static readonly int[] _targetOutputFeedbackIndicesTableQuadraphonic = new int[4] { 0, 1, 2, 3 }; - private static readonly int[] OutputEarlyIndicesTableSurround = new int[20] { 0, 5, 0, 5, 1, 5, 1, 5, 4, 5, 4, 5, 2, 5, 2, 5, 3, 5, 3, 5 }; - private static readonly int[] TargetEarlyDelayLineIndicesTableSurround = new int[20] { 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9 }; - private static readonly int[] OutputIndicesTableSurround = new int[Constants.ChannelCountMax] { 0, 1, 2, 3, 4, 5 }; - private static readonly int[] TargetOutputFeedbackIndicesTableSurround = new int[Constants.ChannelCountMax] { 0, 1, 2, 3, -1, 3 }; + private static readonly int[] _outputEarlyIndicesTableSurround = new int[20] { 0, 5, 0, 5, 1, 5, 1, 5, 4, 5, 4, 5, 2, 5, 2, 5, 3, 5, 3, 5 }; + private static readonly int[] _targetEarlyDelayLineIndicesTableSurround = new int[20] { 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9 }; + private static readonly int[] _outputIndicesTableSurround = new int[Constants.ChannelCountMax] { 0, 1, 2, 3, 4, 5 }; + private static readonly int[] _targetOutputFeedbackIndicesTableSurround = new int[Constants.ChannelCountMax] { 0, 1, 2, 3, -1, 3 }; public bool Enabled { get; set; } @@ -82,10 +83,10 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command outputBuffers, inputBuffers, sampleCount, - OutputEarlyIndicesTableMono, - TargetEarlyDelayLineIndicesTableMono, - TargetOutputFeedbackIndicesTableMono, - OutputIndicesTableMono); + _outputEarlyIndicesTableMono, + _targetEarlyDelayLineIndicesTableMono, + _targetOutputFeedbackIndicesTableMono, + _outputIndicesTableMono); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -95,10 +96,10 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command outputBuffers, inputBuffers, sampleCount, - OutputEarlyIndicesTableStereo, - TargetEarlyDelayLineIndicesTableStereo, - TargetOutputFeedbackIndicesTableStereo, - OutputIndicesTableStereo); + _outputEarlyIndicesTableStereo, + _targetEarlyDelayLineIndicesTableStereo, + _targetOutputFeedbackIndicesTableStereo, + _outputIndicesTableStereo); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -108,10 +109,10 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command outputBuffers, inputBuffers, sampleCount, - OutputEarlyIndicesTableQuadraphonic, - TargetEarlyDelayLineIndicesTableQuadraphonic, - TargetOutputFeedbackIndicesTableQuadraphonic, - OutputIndicesTableQuadraphonic); + _outputEarlyIndicesTableQuadraphonic, + _targetEarlyDelayLineIndicesTableQuadraphonic, + _targetOutputFeedbackIndicesTableQuadraphonic, + _outputIndicesTableQuadraphonic); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -121,10 +122,10 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command outputBuffers, inputBuffers, sampleCount, - OutputEarlyIndicesTableSurround, - TargetEarlyDelayLineIndicesTableSurround, - TargetOutputFeedbackIndicesTableSurround, - OutputIndicesTableSurround); + _outputEarlyIndicesTableSurround, + _targetEarlyDelayLineIndicesTableSurround, + _targetOutputFeedbackIndicesTableSurround, + _outputIndicesTableSurround); } private unsafe void ProcessReverbGeneric(ref ReverbState state, ReadOnlySpan outputBuffers, ReadOnlySpan inputBuffers, uint sampleCount, ReadOnlySpan outputEarlyIndicesTable, ReadOnlySpan targetEarlyDelayLineIndicesTable, ReadOnlySpan targetOutputFeedbackIndicesTable, ReadOnlySpan outputIndicesTable) @@ -143,7 +144,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command for (int sampleIndex = 0; sampleIndex < sampleCount; sampleIndex++) { - outputValues.Fill(0); + outputValues.Clear(); for (int i = 0; i < targetEarlyDelayLineIndicesTable.Length; i++) { @@ -263,11 +264,11 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command if (IsEffectEnabled) { - if (Parameter.Status == Server.Effect.UsageState.Invalid) + if (Parameter.Status == UsageState.Invalid) { state = new ReverbState(ref _parameter, WorkBuffer, IsLongSizePreDelaySupported); } - else if (Parameter.Status == Server.Effect.UsageState.New) + else if (Parameter.Status == UsageState.New) { state.UpdateParameter(ref _parameter); } @@ -276,4 +277,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command ProcessReverb(context, ref state); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/UpsampleCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/UpsampleCommand.cs index 0870d59ce..8882500cd 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/UpsampleCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/UpsampleCommand.cs @@ -67,4 +67,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/VolumeCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/VolumeCommand.cs index 0628f6d81..5deeb07f1 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/VolumeCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/VolumeCommand.cs @@ -134,4 +134,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command ProcessVolume(outputBuffer, inputBuffer); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/VolumeRampCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/VolumeRampCommand.cs index 5c0c88451..bffbcbc63 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/VolumeRampCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/VolumeRampCommand.cs @@ -53,4 +53,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command ProcessVolumeRamp(outputBuffer, inputBuffer, (int)context.SampleCount); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/DataSourceHelper.cs b/src/Ryujinx.Audio/Renderer/Dsp/DataSourceHelper.cs index 12e0f13ff..98657bd13 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/DataSourceHelper.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/DataSourceHelper.cs @@ -76,7 +76,7 @@ namespace Ryujinx.Audio.Renderer.Dsp if (!info.DecodingBehaviour.HasFlag(DecodingBehaviour.SkipPitchAndSampleRateConversion)) { - voiceState.Pitch.AsSpan().Slice(0, pitchMaxLength).CopyTo(tempBuffer); + voiceState.Pitch.AsSpan()[..pitchMaxLength].CopyTo(tempBuffer); tempBufferIndex += pitchMaxLength; } @@ -107,7 +107,7 @@ namespace Ryujinx.Audio.Renderer.Dsp voiceState.LoopContext = memoryManager.Read(waveBuffer.Context); } - Span tempSpan = tempBuffer.Slice(tempBufferIndex + y); + Span tempSpan = tempBuffer[(tempBufferIndex + y)..]; int decodedSampleCount = -1; @@ -168,7 +168,7 @@ namespace Ryujinx.Audio.Renderer.Dsp decodedSampleCount = PcmHelper.Decode(tempSpan, waveBufferPcmFloat, targetSampleStartOffset, targetSampleEndOffset, info.ChannelIndex, info.ChannelCount); break; default: - Logger.Error?.Print(LogClass.AudioRenderer, $"Unsupported sample format " + info.SampleFormat); + Logger.Error?.Print(LogClass.AudioRenderer, "Unsupported sample format " + info.SampleFormat); break; } @@ -220,7 +220,7 @@ namespace Ryujinx.Audio.Renderer.Dsp } } - Span outputSpanInt = MemoryMarshal.Cast(outputBuffer.Slice(i)); + Span outputSpanInt = MemoryMarshal.Cast(outputBuffer[i..]); if (info.DecodingBehaviour.HasFlag(DecodingBehaviour.SkipPitchAndSampleRateConversion)) { @@ -231,9 +231,9 @@ namespace Ryujinx.Audio.Renderer.Dsp } else { - Span tempSpan = tempBuffer.Slice(tempBufferIndex + y); + Span tempSpan = tempBuffer[(tempBufferIndex + y)..]; - tempSpan.Slice(0, sampleCountToDecode - y).Fill(0); + tempSpan[..(sampleCountToDecode - y)].Clear(); ToFloat(outputBuffer, outputSpanInt, sampleCountToProcess); diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Effect/DecayDelay.cs b/src/Ryujinx.Audio/Renderer/Dsp/Effect/DecayDelay.cs index 37e066bf0..7253fdc92 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Effect/DecayDelay.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Effect/DecayDelay.cs @@ -49,4 +49,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Effect return _delayLine.Tap(sampleIndex); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Effect/DelayLine.cs b/src/Ryujinx.Audio/Renderer/Dsp/Effect/DelayLine.cs index 56890ebe8..8a3590a20 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Effect/DelayLine.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Effect/DelayLine.cs @@ -4,8 +4,8 @@ namespace Ryujinx.Audio.Renderer.Dsp.Effect { public class DelayLine : IDelayLine { - private float[] _workBuffer; - private uint _sampleRate; + private readonly float[] _workBuffer; + private readonly uint _sampleRate; private uint _currentSampleIndex; private uint _lastSampleIndex; @@ -75,4 +75,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Effect return TapUnsafe(sampleIndex, -1); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Effect/DelayLineReverb3d.cs b/src/Ryujinx.Audio/Renderer/Dsp/Effect/DelayLineReverb3d.cs index a2ac9d265..ed8e7cfe0 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Effect/DelayLineReverb3d.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Effect/DelayLineReverb3d.cs @@ -4,8 +4,8 @@ namespace Ryujinx.Audio.Renderer.Dsp.Effect { public class DelayLine3d : IDelayLine { - private float[] _workBuffer; - private uint _sampleRate; + private readonly float[] _workBuffer; + private readonly uint _sampleRate; private uint _currentSampleIndex; private uint _lastSampleIndex; @@ -73,4 +73,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Effect return TapUnsafe(sampleIndex, -1); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Effect/ExponentialMovingAverage.cs b/src/Ryujinx.Audio/Renderer/Dsp/Effect/ExponentialMovingAverage.cs index 78e46bf96..253400a5a 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Effect/ExponentialMovingAverage.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Effect/ExponentialMovingAverage.cs @@ -1,6 +1,4 @@ -using System.Runtime.CompilerServices; - -namespace Ryujinx.Audio.Renderer.Dsp.Effect +namespace Ryujinx.Audio.Renderer.Dsp.Effect { public struct ExponentialMovingAverage { @@ -11,7 +9,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Effect _mean = mean; } - public float Read() + public readonly float Read() { return _mean; } diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Effect/IDelayLine.cs b/src/Ryujinx.Audio/Renderer/Dsp/Effect/IDelayLine.cs index fd902525e..b408e294d 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Effect/IDelayLine.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Effect/IDelayLine.cs @@ -34,4 +34,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Effect return (uint)MathF.Round(sampleRate * delayTime); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/FixedPointHelper.cs b/src/Ryujinx.Audio/Renderer/Dsp/FixedPointHelper.cs index 280e47c0c..d519de333 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/FixedPointHelper.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/FixedPointHelper.cs @@ -36,4 +36,4 @@ namespace Ryujinx.Audio.Renderer.Dsp return ToInt(value + half, qBits); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/FloatingPointHelper.cs b/src/Ryujinx.Audio/Renderer/Dsp/FloatingPointHelper.cs index 6645e20a3..b231dbb6a 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/FloatingPointHelper.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/FloatingPointHelper.cs @@ -1,5 +1,4 @@ using System; -using System.Reflection.Metadata; using System.Runtime.CompilerServices; namespace Ryujinx.Audio.Renderer.Dsp @@ -39,7 +38,8 @@ namespace Ryujinx.Audio.Renderer.Dsp { return 1.0f; } - else if (x <= -5.3f) + + if (x <= -5.3f) { return 0.0f; } @@ -112,4 +112,4 @@ namespace Ryujinx.Audio.Renderer.Dsp return MathF.Sin(DegreesToRadians(value)); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/PcmHelper.cs b/src/Ryujinx.Audio/Renderer/Dsp/PcmHelper.cs index 0233a8d71..d209c515b 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/PcmHelper.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/PcmHelper.cs @@ -1,5 +1,4 @@ using System; -using System.Numerics; using System.Runtime.CompilerServices; namespace Ryujinx.Audio.Renderer.Dsp @@ -62,7 +61,7 @@ namespace Ryujinx.Audio.Renderer.Dsp { for (int i = 0; i < input.Length; i++) { - output[i] = ((int)input[i]) << 16; + output[i] = input[i] << 16; } } @@ -127,4 +126,4 @@ namespace Ryujinx.Audio.Renderer.Dsp return (short)value; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/ResamplerHelper.cs b/src/Ryujinx.Audio/Renderer/Dsp/ResamplerHelper.cs index 7873c4d27..e44e9f41e 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/ResamplerHelper.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/ResamplerHelper.cs @@ -1,6 +1,5 @@ using System; using System.Linq; -using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; @@ -11,8 +10,7 @@ namespace Ryujinx.Audio.Renderer.Dsp public static class ResamplerHelper { #region "Default Quality Lookup Tables" - private static short[] _normalCurveLut0 = new short[] - { + private static readonly short[] _normalCurveLut0 = { 6600, 19426, 6722, 3, 6479, 19424, 6845, 9, 6359, 19419, 6968, 15, 6239, 19412, 7093, 22, 6121, 19403, 7219, 28, 6004, 19391, 7345, 34, 5888, 19377, 7472, 41, 5773, 19361, 7600, 48, 5659, 19342, 7728, 55, 5546, 19321, 7857, 62, 5434, 19298, 7987, 69, 5323, 19273, 8118, 77, @@ -44,11 +42,10 @@ namespace Ryujinx.Audio.Renderer.Dsp 109, 8646, 19148, 4890, 101, 8513, 19183, 4997, 92, 8381, 19215, 5104, 84, 8249, 19245, 5213, 77, 8118, 19273, 5323, 69, 7987, 19298, 5434, 62, 7857, 19321, 5546, 55, 7728, 19342, 5659, 48, 7600, 19361, 5773, 41, 7472, 19377, 5888, 34, 7345, 19391, 6004, 28, 7219, 19403, 6121, - 22, 7093, 19412, 6239, 15, 6968, 19419, 6359, 9, 6845, 19424, 6479, 3, 6722, 19426, 6600 + 22, 7093, 19412, 6239, 15, 6968, 19419, 6359, 9, 6845, 19424, 6479, 3, 6722, 19426, 6600, }; - private static short[] _normalCurveLut1 = new short[] - { + private static readonly short[] _normalCurveLut1 = { -68, 32639, 69, -5, -200, 32630, 212, -15, -328, 32613, 359, -26, -450, 32586, 512, -36, -568, 32551, 669, -47, -680, 32507, 832, -58, -788, 32454, 1000, -69, -891, 32393, 1174, -80, -990, 32323, 1352, -92, -1084, 32244, 1536, -103, -1173, 32157, 1724, -115, -1258, 32061, 1919, -128, @@ -80,11 +77,10 @@ namespace Ryujinx.Audio.Renderer.Dsp -180, 2747, 31593, -1554, -167, 2532, 31723, -1486, -153, 2322, 31844, -1414, -140, 2118, 31956, -1338, -128, 1919, 32061, -1258, -115, 1724, 32157, -1173, -103, 1536, 32244, -1084, -92, 1352, 32323, -990, -80, 1174, 32393, -891, -69, 1000, 32454, -788, -58, 832, 32507, -680, -47, 669, 32551, -568, - -36, 512, 32586, -450, -26, 359, 32613, -328, -15, 212, 32630, -200, -5, 69, 32639, -68 + -36, 512, 32586, -450, -26, 359, 32613, -328, -15, 212, 32630, -200, -5, 69, 32639, -68, }; - private static short[] _normalCurveLut2 = new short[] - { + private static readonly short[] _normalCurveLut2 = { 3195, 26287, 3329, -32, 3064, 26281, 3467, -34, 2936, 26270, 3608, -38, 2811, 26253, 3751, -42, 2688, 26230, 3897, -46, 2568, 26202, 4046, -50, 2451, 26169, 4199, -54, 2338, 26130, 4354, -58, 2227, 26085, 4512, -63, 2120, 26035, 4673, -67, 2015, 25980, 4837, -72, 1912, 25919, 5004, -76, @@ -116,13 +112,12 @@ namespace Ryujinx.Audio.Renderer.Dsp -98, 5701, 25621, 1531, -92, 5522, 25704, 1622, -87, 5347, 25780, 1716, -81, 5174, 25852, 1813, -76, 5004, 25919, 1912, -72, 4837, 25980, 2015, -67, 4673, 26035, 2120, -63, 4512, 26085, 2227, -58, 4354, 26130, 2338, -54, 4199, 26169, 2451, -50, 4046, 26202, 2568, -46, 3897, 26230, 2688, - -42, 3751, 26253, 2811, -38, 3608, 26270, 2936, -34, 3467, 26281, 3064, -32, 3329, 26287, 3195 + -42, 3751, 26253, 2811, -38, 3608, 26270, 2936, -34, 3467, 26281, 3064, -32, 3329, 26287, 3195, }; #endregion #region "High Quality Lookup Tables" - private static short[] _highCurveLut0 = new short[] - { + private static readonly short[] _highCurveLut0 = { -582, -23, 8740, 16386, 8833, 8, -590, 0, -573, -54, 8647, 16385, 8925, 40, -598, -1, -565, -84, 8555, 16383, 9018, 72, -606, -1, -557, -113, 8462, 16379, 9110, 105, -614, -2, -549, -142, 8370, 16375, 9203, 139, -622, -2, -541, -170, 8277, 16369, 9295, 173, -630, -3, @@ -189,8 +184,7 @@ namespace Ryujinx.Audio.Renderer.Dsp -1, -598, 40, 8925, 16385, 8647, -54, -573, 0, -590, 8, 8833, 16386, 8740, -23, -582, }; - private static short[] _highCurveLut1 = new short[] - { + private static readonly short[] _highCurveLut1 = { -12, 47, -134, 32767, 81, -16, 2, 0, -26, 108, -345, 32760, 301, -79, 17, -1, -40, 168, -552, 32745, 526, -144, 32, -2, -53, 226, -753, 32723, 755, -210, 47, -3, -66, 284, -950, 32694, 989, -277, 63, -5, -78, 340, -1143, 32658, 1226, -346, 79, -6, @@ -257,8 +251,7 @@ namespace Ryujinx.Audio.Renderer.Dsp -1, 17, -79, 301, 32760, -345, 108, -26, 0, 2, -16, 81, 32767, -134, 47, -12, }; - private static short[] _highCurveLut2 = new short[] - { + private static readonly short[] _highCurveLut2 = { 418, -2538, 6118, 24615, 6298, -2563, 417, 0, 420, -2512, 5939, 24611, 6479, -2588, 415, 1, 421, -2485, 5761, 24605, 6662, -2612, 412, 2, 422, -2458, 5585, 24595, 6846, -2635, 409, 3, 423, -2430, 5410, 24582, 7030, -2658, 406, 4, 423, -2402, 5236, 24565, 7216, -2680, 403, 5, @@ -326,13 +319,13 @@ namespace Ryujinx.Audio.Renderer.Dsp }; #endregion - private static float[] _normalCurveLut0F; - private static float[] _normalCurveLut1F; - private static float[] _normalCurveLut2F; + private static readonly float[] _normalCurveLut0F; + private static readonly float[] _normalCurveLut1F; + private static readonly float[] _normalCurveLut2F; - private static float[] _highCurveLut0F; - private static float[] _highCurveLut1F; - private static float[] _highCurveLut2F; + private static readonly float[] _highCurveLut0F; + private static readonly float[] _highCurveLut1F; + private static readonly float[] _highCurveLut2F; static ResamplerHelper() { @@ -373,7 +366,8 @@ namespace Ryujinx.Audio.Renderer.Dsp { return _normalCurveLut1F; } - else if (ratio > 1.333313f) + + if (ratio > 1.333313f) { return _normalCurveLut0F; } @@ -514,7 +508,8 @@ namespace Ryujinx.Audio.Renderer.Dsp { return _highCurveLut1F; } - else if (ratio > 1.333313f) + + if (ratio > 1.333313f) { return _highCurveLut0F; } @@ -601,4 +596,4 @@ namespace Ryujinx.Audio.Renderer.Dsp } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/State/AdpcmLoopContext.cs b/src/Ryujinx.Audio/Renderer/Dsp/State/AdpcmLoopContext.cs index 821a135ef..f9ef201f2 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/State/AdpcmLoopContext.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/State/AdpcmLoopContext.cs @@ -9,4 +9,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.State public short History0; public short History1; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/State/AuxiliaryBufferHeader.cs b/src/Ryujinx.Audio/Renderer/Dsp/State/AuxiliaryBufferHeader.cs index 4e8d11e4c..97bbc80cc 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/State/AuxiliaryBufferHeader.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/State/AuxiliaryBufferHeader.cs @@ -71,4 +71,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.State public AuxiliaryBufferInfo CpuBufferInfo; public AuxiliaryBufferInfo DspBufferInfo; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/State/BiquadFilterState.cs b/src/Ryujinx.Audio/Renderer/Dsp/State/BiquadFilterState.cs index 4220e6d51..f9a32b3f9 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/State/BiquadFilterState.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/State/BiquadFilterState.cs @@ -10,4 +10,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.State public float State2; public float State3; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/State/DelayState.cs b/src/Ryujinx.Audio/Renderer/Dsp/State/DelayState.cs index 2a1e7f834..c56fa078a 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/State/DelayState.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/State/DelayState.cs @@ -64,4 +64,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.State } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/State/LimiterState.cs b/src/Ryujinx.Audio/Renderer/Dsp/State/LimiterState.cs index 0560757c9..80d1cb62e 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/State/LimiterState.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/State/LimiterState.cs @@ -20,12 +20,12 @@ namespace Ryujinx.Audio.Renderer.Dsp.State DetectorAverage.AsSpan().Fill(new ExponentialMovingAverage(0.0f)); CompressionGainAverage.AsSpan().Fill(new ExponentialMovingAverage(1.0f)); - DelayedSampleBufferPosition.AsSpan().Fill(0); - DelayedSampleBuffer.AsSpan().Fill(0.0f); + DelayedSampleBufferPosition.AsSpan().Clear(); + DelayedSampleBuffer.AsSpan().Clear(); UpdateParameter(ref parameter); } - public void UpdateParameter(ref LimiterParameter parameter) { } + public static void UpdateParameter(ref LimiterParameter parameter) { } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/State/Reverb3dState.cs b/src/Ryujinx.Audio/Renderer/Dsp/State/Reverb3dState.cs index c06466031..5056b750e 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/State/Reverb3dState.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/State/Reverb3dState.cs @@ -6,11 +6,11 @@ namespace Ryujinx.Audio.Renderer.Dsp.State { public class Reverb3dState { - private readonly float[] FdnDelayMinTimes = new float[4] { 5.0f, 6.0f, 13.0f, 14.0f }; - private readonly float[] FdnDelayMaxTimes = new float[4] { 45.704f, 82.782f, 149.94f, 271.58f }; - private readonly float[] DecayDelayMaxTimes1 = new float[4] { 17.0f, 13.0f, 9.0f, 7.0f }; - private readonly float[] DecayDelayMaxTimes2 = new float[4] { 19.0f, 11.0f, 10.0f, 6.0f }; - private readonly float[] EarlyDelayTimes = new float[20] { 0.017136f, 0.059154f, 0.16173f, 0.39019f, 0.42526f, 0.45541f, 0.68974f, 0.74591f, 0.83384f, 0.8595f, 0.0f, 0.075024f, 0.16879f, 0.2999f, 0.33744f, 0.3719f, 0.59901f, 0.71674f, 0.81786f, 0.85166f }; + private readonly float[] _fdnDelayMinTimes = new float[4] { 5.0f, 6.0f, 13.0f, 14.0f }; + private readonly float[] _fdnDelayMaxTimes = new float[4] { 45.704f, 82.782f, 149.94f, 271.58f }; + private readonly float[] _decayDelayMaxTimes1 = new float[4] { 17.0f, 13.0f, 9.0f, 7.0f }; + private readonly float[] _decayDelayMaxTimes2 = new float[4] { 19.0f, 11.0f, 10.0f, 6.0f }; + private readonly float[] _earlyDelayTimes = new float[20] { 0.017136f, 0.059154f, 0.16173f, 0.39019f, 0.42526f, 0.45541f, 0.68974f, 0.74591f, 0.83384f, 0.8595f, 0.0f, 0.075024f, 0.16879f, 0.2999f, 0.33744f, 0.3719f, 0.59901f, 0.71674f, 0.81786f, 0.85166f }; public readonly float[] EarlyGain = new float[20] { 0.67096f, 0.61027f, 1.0f, 0.35680f, 0.68361f, 0.65978f, 0.51939f, 0.24712f, 0.45945f, 0.45021f, 0.64196f, 0.54879f, 0.92925f, 0.38270f, 0.72867f, 0.69794f, 0.5464f, 0.24563f, 0.45214f, 0.44042f }; public IDelayLine[] FdnDelayLines { get; } @@ -46,9 +46,9 @@ namespace Ryujinx.Audio.Renderer.Dsp.State for (int i = 0; i < 4; i++) { - FdnDelayLines[i] = new DelayLine3d(sampleRate, FdnDelayMaxTimes[i]); - DecayDelays1[i] = new DecayDelay(new DelayLine3d(sampleRate, DecayDelayMaxTimes1[i])); - DecayDelays2[i] = new DecayDelay(new DelayLine3d(sampleRate, DecayDelayMaxTimes2[i])); + FdnDelayLines[i] = new DelayLine3d(sampleRate, _fdnDelayMaxTimes[i]); + DecayDelays1[i] = new DecayDelay(new DelayLine3d(sampleRate, _decayDelayMaxTimes1[i])); + DecayDelays2[i] = new DecayDelay(new DelayLine3d(sampleRate, _decayDelayMaxTimes2[i])); } PreDelayLine = new DelayLine3d(sampleRate, 400); @@ -63,7 +63,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.State EarlyDelayTime = new uint[20]; DryGain = parameter.DryGain; - PreviousFeedbackOutputDecayed.AsSpan().Fill(0); + PreviousFeedbackOutputDecayed.AsSpan().Clear(); PreviousPreDelayValue = 0; EarlyReflectionsGain = FloatingPointHelper.Pow10(Math.Min(parameter.RoomGain + parameter.ReflectionsGain, 5000.0f) / 2000.0f); @@ -91,7 +91,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.State for (int i = 0; i < FdnDelayLines.Length; i++) { - FdnDelayLines[i].SetDelay(FdnDelayMinTimes[i] + (parameter.Density / 100 * (FdnDelayMaxTimes[i] - FdnDelayMinTimes[i]))); + FdnDelayLines[i].SetDelay(_fdnDelayMinTimes[i] + (parameter.Density / 100 * (_fdnDelayMaxTimes[i] - _fdnDelayMinTimes[i]))); uint tempSampleCount = FdnDelayLines[i].CurrentSampleCount + DecayDelays1[i].CurrentSampleCount + DecayDelays2[i].CurrentSampleCount; @@ -111,9 +111,9 @@ namespace Ryujinx.Audio.Renderer.Dsp.State for (int i = 0; i < EarlyDelayTime.Length; i++) { - uint sampleCount = Math.Min(IDelayLine.GetSampleCount(sampleRate, (parameter.ReflectionDelay * 1000.0f) + (EarlyDelayTimes[i] * 1000.0f * ((parameter.ReverbDelayTime * 0.9998f) + 0.02f))), PreDelayLine.SampleCountMax); + uint sampleCount = Math.Min(IDelayLine.GetSampleCount(sampleRate, (parameter.ReflectionDelay * 1000.0f) + (_earlyDelayTimes[i] * 1000.0f * ((parameter.ReverbDelayTime * 0.9998f) + 0.02f))), PreDelayLine.SampleCountMax); EarlyDelayTime[i] = sampleCount; } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/State/ReverbState.cs b/src/Ryujinx.Audio/Renderer/Dsp/State/ReverbState.cs index 1ffabe05c..2f574f475 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/State/ReverbState.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/State/ReverbState.cs @@ -7,7 +7,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.State { public class ReverbState { - private static readonly float[] FdnDelayTimes = new float[20] + private static readonly float[] _fdnDelayTimes = new float[20] { // Room 53.953247f, 79.192566f, 116.238770f, 130.615295f, @@ -21,7 +21,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.State 53.953247f, 79.192566f, 116.238770f, 170.615295f, }; - private static readonly float[] DecayDelayTimes = new float[20] + private static readonly float[] _decayDelayTimes = new float[20] { // Room 7f, 9f, 13f, 17f, @@ -35,7 +35,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.State 7f, 9f, 13f, 17f, }; - private static readonly float[] EarlyDelayTimes = new float[50] + private static readonly float[] _earlyDelayTimes = new float[50] { // Room 0.0f, 3.5f, 2.8f, 3.9f, 2.7f, 13.4f, 7.9f, 8.4f, 9.9f, 12.0f, @@ -46,10 +46,10 @@ namespace Ryujinx.Audio.Renderer.Dsp.State // Cathedral 33.1f, 43.3f, 22.8f, 37.9f, 14.9f, 35.3f, 17.9f, 34.2f, 0.0f, 43.3f, // Disabled - 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f + 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, }; - private static readonly float[] EarlyGainBase = new float[50] + private static readonly float[] _earlyGainBase = new float[50] { // Room 0.70f, 0.68f, 0.70f, 0.68f, 0.70f, 0.68f, 0.70f, 0.68f, 0.68f, 0.68f, @@ -60,10 +60,10 @@ namespace Ryujinx.Audio.Renderer.Dsp.State // Cathedral 0.93f, 0.92f, 0.87f, 0.86f, 0.94f, 0.81f, 0.80f, 0.77f, 0.76f, 0.65f, // Disabled - 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f + 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, }; - private static readonly float[] PreDelayTimes = new float[5] + private static readonly float[] _preDelayTimes = new float[5] { // Room 12.5f, @@ -74,7 +74,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.State // Cathedral 50.0f, // Disabled - 0.0f + 0.0f, }; public DelayLine[] FdnDelayLines { get; } @@ -93,14 +93,14 @@ namespace Ryujinx.Audio.Renderer.Dsp.State private const int FixedPointPrecision = 14; - private ReadOnlySpan GetFdnDelayTimesByLateMode(ReverbLateMode lateMode) + private static ReadOnlySpan GetFdnDelayTimesByLateMode(ReverbLateMode lateMode) { - return FdnDelayTimes.AsSpan((int)lateMode * 4, 4); + return _fdnDelayTimes.AsSpan((int)lateMode * 4, 4); } - private ReadOnlySpan GetDecayDelayTimesByLateMode(ReverbLateMode lateMode) + private static ReadOnlySpan GetDecayDelayTimesByLateMode(ReverbLateMode lateMode) { - return DecayDelayTimes.AsSpan((int)lateMode * 4, 4); + return _decayDelayTimes.AsSpan((int)lateMode * 4, 4); } public ReverbState(ref ReverbParameter parameter, ulong workBuffer, bool isLongSizePreDelaySupported) @@ -148,8 +148,8 @@ namespace Ryujinx.Audio.Renderer.Dsp.State for (int i = 0; i < 10; i++) { - EarlyDelayTime[i] = Math.Min(IDelayLine.GetSampleCount(sampleRate, EarlyDelayTimes[i] + preDelayTimeInMilliseconds), PreDelayLine.SampleCountMax) + 1; - EarlyGain[i] = EarlyGainBase[i] * earlyGain; + EarlyDelayTime[i] = Math.Min(IDelayLine.GetSampleCount(sampleRate, _earlyDelayTimes[i] + preDelayTimeInMilliseconds), PreDelayLine.SampleCountMax) + 1; + EarlyGain[i] = _earlyGainBase[i] * earlyGain; } if (parameter.ChannelCount == 2) @@ -158,7 +158,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.State EarlyGain[5] = EarlyGain[5] * 0.5f; } - PreDelayLineDelayTime = Math.Min(IDelayLine.GetSampleCount(sampleRate, PreDelayTimes[(int)parameter.EarlyMode] + preDelayTimeInMilliseconds), PreDelayLine.SampleCountMax); + PreDelayLineDelayTime = Math.Min(IDelayLine.GetSampleCount(sampleRate, _preDelayTimes[(int)parameter.EarlyMode] + preDelayTimeInMilliseconds), PreDelayLine.SampleCountMax); ReadOnlySpan fdnDelayTimes = GetFdnDelayTimesByLateMode(parameter.LateMode); ReadOnlySpan decayDelayTimes = GetDecayDelayTimesByLateMode(parameter.LateMode); @@ -201,4 +201,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.State } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/UpsamplerHelper.cs b/src/Ryujinx.Audio/Renderer/Dsp/UpsamplerHelper.cs index 54a63ace0..5732cdb21 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/UpsamplerHelper.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/UpsamplerHelper.cs @@ -13,11 +13,11 @@ namespace Ryujinx.Audio.Renderer.Dsp private const int FilterBankLength = 20; // Bank0 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; private const int Bank0CenterIndex = 9; - private static readonly Array20 Bank1 = PrecomputeFilterBank(1.0f / 6.0f); - private static readonly Array20 Bank2 = PrecomputeFilterBank(2.0f / 6.0f); - private static readonly Array20 Bank3 = PrecomputeFilterBank(3.0f / 6.0f); - private static readonly Array20 Bank4 = PrecomputeFilterBank(4.0f / 6.0f); - private static readonly Array20 Bank5 = PrecomputeFilterBank(5.0f / 6.0f); + private static readonly Array20 _bank1 = PrecomputeFilterBank(1.0f / 6.0f); + private static readonly Array20 _bank2 = PrecomputeFilterBank(2.0f / 6.0f); + private static readonly Array20 _bank3 = PrecomputeFilterBank(3.0f / 6.0f); + private static readonly Array20 _bank4 = PrecomputeFilterBank(4.0f / 6.0f); + private static readonly Array20 _bank5 = PrecomputeFilterBank(5.0f / 6.0f); private static Array20 PrecomputeFilterBank(float offset) { @@ -39,7 +39,7 @@ namespace Ryujinx.Audio.Renderer.Dsp return A0 + A1 * MathF.Cos(2 * MathF.PI * x) + A2 * MathF.Cos(4 * MathF.PI * x); } - Array20 result = new Array20(); + Array20 result = new(); for (int i = 0; i < FilterBankLength; i++) { @@ -58,10 +58,10 @@ namespace Ryujinx.Audio.Renderer.Dsp { state.Scale = inputSampleCount switch { - 40 => 6.0f, - 80 => 3.0f, + 40 => 6.0f, + 80 => 3.0f, 160 => 1.5f, - _ => throw new ArgumentOutOfRangeException() + _ => throw new ArgumentOutOfRangeException(nameof(inputSampleCount), inputSampleCount, null), }; state.Initialized = true; } @@ -105,7 +105,7 @@ namespace Ryujinx.Audio.Renderer.Dsp [MethodImpl(MethodImplOptions.AggressiveInlining)] void NextInput(ref UpsamplerBufferState state, float input) { - state.History.AsSpan().Slice(1).CopyTo(state.History.AsSpan()); + state.History.AsSpan()[1..].CopyTo(state.History.AsSpan()); state.History[HistoryLength - 1] = input; } @@ -123,19 +123,19 @@ namespace Ryujinx.Audio.Renderer.Dsp outputBuffer[i] = state.History[Bank0CenterIndex]; break; case 1: - outputBuffer[i] = DoFilterBank(ref state, Bank1); + outputBuffer[i] = DoFilterBank(ref state, _bank1); break; case 2: - outputBuffer[i] = DoFilterBank(ref state, Bank2); + outputBuffer[i] = DoFilterBank(ref state, _bank2); break; case 3: - outputBuffer[i] = DoFilterBank(ref state, Bank3); + outputBuffer[i] = DoFilterBank(ref state, _bank3); break; case 4: - outputBuffer[i] = DoFilterBank(ref state, Bank4); + outputBuffer[i] = DoFilterBank(ref state, _bank4); break; case 5: - outputBuffer[i] = DoFilterBank(ref state, Bank5); + outputBuffer[i] = DoFilterBank(ref state, _bank5); break; } @@ -152,10 +152,10 @@ namespace Ryujinx.Audio.Renderer.Dsp outputBuffer[i] = state.History[Bank0CenterIndex]; break; case 1: - outputBuffer[i] = DoFilterBank(ref state, Bank2); + outputBuffer[i] = DoFilterBank(ref state, _bank2); break; case 2: - outputBuffer[i] = DoFilterBank(ref state, Bank4); + outputBuffer[i] = DoFilterBank(ref state, _bank4); break; } @@ -173,11 +173,11 @@ namespace Ryujinx.Audio.Renderer.Dsp outputBuffer[i] = state.History[Bank0CenterIndex]; break; case 1: - outputBuffer[i] = DoFilterBank(ref state, Bank4); + outputBuffer[i] = DoFilterBank(ref state, _bank4); break; case 2: NextInput(ref state, inputBuffer[inputBufferIndex++]); - outputBuffer[i] = DoFilterBank(ref state, Bank2); + outputBuffer[i] = DoFilterBank(ref state, _bank2); break; } @@ -185,7 +185,7 @@ namespace Ryujinx.Audio.Renderer.Dsp } break; default: - throw new ArgumentOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(state), state.Scale, null); } } } diff --git a/src/Ryujinx.Audio/Renderer/Parameter/AudioRendererConfiguration.cs b/src/Ryujinx.Audio/Renderer/Parameter/AudioRendererConfiguration.cs index 359cd4c02..491a05c86 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/AudioRendererConfiguration.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/AudioRendererConfiguration.cs @@ -60,7 +60,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/unused /// - private byte _reserved; + private readonly byte _reserved; /// /// The target rendering device. @@ -96,4 +96,4 @@ namespace Ryujinx.Audio.Renderer.Parameter /// public int Revision; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/BehaviourErrorInfoOutStatus.cs b/src/Ryujinx.Audio/Renderer/Parameter/BehaviourErrorInfoOutStatus.cs index aba7dcd61..5a0565dc6 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/BehaviourErrorInfoOutStatus.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/BehaviourErrorInfoOutStatus.cs @@ -27,4 +27,4 @@ namespace Ryujinx.Audio.Renderer.Parameter /// private unsafe fixed uint _reserved[3]; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/BiquadFilterParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/BiquadFilterParameter.cs index ef86015fe..f1492b0b1 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/BiquadFilterParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/BiquadFilterParameter.cs @@ -18,7 +18,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/padding. /// - private byte _reserved; + private readonly byte _reserved; /// /// Biquad filter numerator (b0, b1, b2). @@ -31,4 +31,4 @@ namespace Ryujinx.Audio.Renderer.Parameter /// a0 = 1 public Array2 Denominator; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Effect/AuxiliaryBufferParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/Effect/AuxiliaryBufferParameter.cs index 36f286775..65f265a32 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Effect/AuxiliaryBufferParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Effect/AuxiliaryBufferParameter.cs @@ -81,4 +81,4 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// This is unused. public uint MixBufferSampleCount; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Effect/BiquadFilterEffectParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/Effect/BiquadFilterEffectParameter.cs index 73e0e9bbc..b12a941a5 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Effect/BiquadFilterEffectParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Effect/BiquadFilterEffectParameter.cs @@ -41,4 +41,4 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// public UsageState Status; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Effect/BufferMixerParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/Effect/BufferMixerParameter.cs index b03559eba..49b70e501 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Effect/BufferMixerParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Effect/BufferMixerParameter.cs @@ -29,4 +29,4 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// public uint MixesCount; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Effect/CompressorParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/Effect/CompressorParameter.cs index 0be376088..1a936b0df 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Effect/CompressorParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Effect/CompressorParameter.cs @@ -98,7 +98,7 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// Check if the is valid. /// /// Returns true if the is valid. - public bool IsChannelCountValid() + public readonly bool IsChannelCountValid() { return EffectInParameterVersion1.IsChannelCountValid(ChannelCount); } @@ -107,7 +107,7 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// Check if the is valid. /// /// Returns true if the is valid. - public bool IsChannelCountMaxValid() + public readonly bool IsChannelCountMaxValid() { return EffectInParameterVersion1.IsChannelCountValid(ChannelCountMax); } diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Effect/DelayParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/Effect/DelayParameter.cs index 72332c170..99c97d9d9 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Effect/DelayParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Effect/DelayParameter.cs @@ -84,7 +84,7 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// Check if the is valid. /// /// Returns true if the is valid. - public bool IsChannelCountValid() + public readonly bool IsChannelCountValid() { return EffectInParameterVersion1.IsChannelCountValid(ChannelCount); } @@ -93,9 +93,9 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// Check if the is valid. /// /// Returns true if the is valid. - public bool IsChannelCountMaxValid() + public readonly bool IsChannelCountMaxValid() { return EffectInParameterVersion1.IsChannelCountValid(ChannelCountMax); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Effect/LimiterParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/Effect/LimiterParameter.cs index 0bce94a27..23ccb8c88 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Effect/LimiterParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Effect/LimiterParameter.cs @@ -115,13 +115,13 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// /// Reserved/padding. /// - private byte _reserved; + private readonly byte _reserved; /// /// Check if the is valid. /// /// Returns true if the is valid. - public bool IsChannelCountValid() + public readonly bool IsChannelCountValid() { return EffectInParameterVersion1.IsChannelCountValid(ChannelCount); } @@ -130,9 +130,9 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// Check if the is valid. /// /// Returns true if the is valid. - public bool IsChannelCountMaxValid() + public readonly bool IsChannelCountMaxValid() { return EffectInParameterVersion1.IsChannelCountValid(ChannelCountMax); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Effect/LimiterStatistics.cs b/src/Ryujinx.Audio/Renderer/Parameter/Effect/LimiterStatistics.cs index f353f18d1..97e2f39fc 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Effect/LimiterStatistics.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Effect/LimiterStatistics.cs @@ -24,8 +24,8 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// public void Reset() { - InputMax.AsSpan().Fill(0.0f); + InputMax.AsSpan().Clear(); CompressionGainMin.AsSpan().Fill(1.0f); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Effect/Reverb3dParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/Effect/Reverb3dParameter.cs index c78ce5951..d2cd78707 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Effect/Reverb3dParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Effect/Reverb3dParameter.cs @@ -33,7 +33,7 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// /// Reserved/unused. /// - private uint _reserved; + private readonly uint _reserved; /// /// The target sample rate. @@ -110,7 +110,7 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// Check if the is valid. /// /// Returns true if the is valid. - public bool IsChannelCountValid() + public readonly bool IsChannelCountValid() { return EffectInParameterVersion1.IsChannelCountValid(ChannelCount); } @@ -119,9 +119,9 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// Check if the is valid. /// /// Returns true if the is valid. - public bool IsChannelCountMaxValid() + public readonly bool IsChannelCountMaxValid() { return EffectInParameterVersion1.IsChannelCountValid(ChannelCountMax); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Effect/ReverbParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/Effect/ReverbParameter.cs index baf049fbd..51ab156d2 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Effect/ReverbParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Effect/ReverbParameter.cs @@ -102,7 +102,7 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// Check if the is valid. /// /// Returns true if the is valid. - public bool IsChannelCountValid() + public readonly bool IsChannelCountValid() { return EffectInParameterVersion1.IsChannelCountValid(ChannelCount); } @@ -111,9 +111,9 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// Check if the is valid. /// /// Returns true if the is valid. - public bool IsChannelCountMaxValid() + public readonly bool IsChannelCountMaxValid() { return EffectInParameterVersion1.IsChannelCountValid(ChannelCountMax); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/EffectInParameterVersion1.cs b/src/Ryujinx.Audio/Renderer/Parameter/EffectInParameterVersion1.cs index e5419f70a..46686e3b4 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/EffectInParameterVersion1.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/EffectInParameterVersion1.cs @@ -31,7 +31,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/padding. /// - private byte _reserved1; + private readonly byte _reserved1; /// /// The target mix id of the effect. @@ -58,7 +58,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/padding. /// - private uint _reserved2; + private readonly uint _reserved2; /// /// Specific data storage. @@ -70,19 +70,19 @@ namespace Ryujinx.Audio.Renderer.Parameter public Span SpecificData => SpanHelpers.AsSpan(ref _specificDataStart); - EffectType IEffectInParameter.Type => Type; + readonly EffectType IEffectInParameter.Type => Type; - bool IEffectInParameter.IsNew => IsNew; + readonly bool IEffectInParameter.IsNew => IsNew; - bool IEffectInParameter.IsEnabled => IsEnabled; + readonly bool IEffectInParameter.IsEnabled => IsEnabled; - int IEffectInParameter.MixId => MixId; + readonly int IEffectInParameter.MixId => MixId; - ulong IEffectInParameter.BufferBase => BufferBase; + readonly ulong IEffectInParameter.BufferBase => BufferBase; - ulong IEffectInParameter.BufferSize => BufferSize; + readonly ulong IEffectInParameter.BufferSize => BufferSize; - uint IEffectInParameter.ProcessingOrder => ProcessingOrder; + readonly uint IEffectInParameter.ProcessingOrder => ProcessingOrder; /// /// Check if the given channel count is valid. @@ -94,4 +94,4 @@ namespace Ryujinx.Audio.Renderer.Parameter return channelCount == 1 || channelCount == 2 || channelCount == 4 || channelCount == 6; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/EffectInParameterVersion2.cs b/src/Ryujinx.Audio/Renderer/Parameter/EffectInParameterVersion2.cs index 250012d16..3854c7148 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/EffectInParameterVersion2.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/EffectInParameterVersion2.cs @@ -31,7 +31,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/padding. /// - private byte _reserved1; + private readonly byte _reserved1; /// /// The target mix id of the effect. @@ -58,7 +58,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/padding. /// - private uint _reserved2; + private readonly uint _reserved2; /// /// Specific data storage. @@ -70,19 +70,19 @@ namespace Ryujinx.Audio.Renderer.Parameter public Span SpecificData => SpanHelpers.AsSpan(ref _specificDataStart); - EffectType IEffectInParameter.Type => Type; + readonly EffectType IEffectInParameter.Type => Type; - bool IEffectInParameter.IsNew => IsNew; + readonly bool IEffectInParameter.IsNew => IsNew; - bool IEffectInParameter.IsEnabled => IsEnabled; + readonly bool IEffectInParameter.IsEnabled => IsEnabled; - int IEffectInParameter.MixId => MixId; + readonly int IEffectInParameter.MixId => MixId; - ulong IEffectInParameter.BufferBase => BufferBase; + readonly ulong IEffectInParameter.BufferBase => BufferBase; - ulong IEffectInParameter.BufferSize => BufferSize; + readonly ulong IEffectInParameter.BufferSize => BufferSize; - uint IEffectInParameter.ProcessingOrder => ProcessingOrder; + readonly uint IEffectInParameter.ProcessingOrder => ProcessingOrder; /// /// Check if the given channel count is valid. @@ -94,4 +94,4 @@ namespace Ryujinx.Audio.Renderer.Parameter return channelCount == 1 || channelCount == 2 || channelCount == 4 || channelCount == 6; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/EffectOutStatusVersion1.cs b/src/Ryujinx.Audio/Renderer/Parameter/EffectOutStatusVersion1.cs index 5e6a33ace..3c3e95538 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/EffectOutStatusVersion1.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/EffectOutStatusVersion1.cs @@ -18,6 +18,6 @@ namespace Ryujinx.Audio.Renderer.Parameter /// private unsafe fixed byte _reserved[15]; - EffectState IEffectOutStatus.State { get => State; set => State = value; } + EffectState IEffectOutStatus.State { readonly get => State; set => State = value; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/EffectOutStatusVersion2.cs b/src/Ryujinx.Audio/Renderer/Parameter/EffectOutStatusVersion2.cs index f2c9768b3..ee058d3ae 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/EffectOutStatusVersion2.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/EffectOutStatusVersion2.cs @@ -23,6 +23,6 @@ namespace Ryujinx.Audio.Renderer.Parameter /// public EffectResultState ResultState; - EffectState IEffectOutStatus.State { get => State; set => State = value; } + EffectState IEffectOutStatus.State { readonly get => State; set => State = value; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/EffectResultState.cs b/src/Ryujinx.Audio/Renderer/Parameter/EffectResultState.cs index bd96c22bf..b3a4bae12 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/EffectResultState.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/EffectResultState.cs @@ -23,4 +23,4 @@ namespace Ryujinx.Audio.Renderer.Parameter /// public Span SpecificData => SpanHelpers.AsSpan(ref _specificDataStart); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/EffectState.cs b/src/Ryujinx.Audio/Renderer/Parameter/EffectState.cs index 911ba6d84..c4d06f122 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/EffectState.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/EffectState.cs @@ -13,6 +13,6 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// The effect is disabled. /// - Disabled = 4 + Disabled = 4, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/IEffectInParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/IEffectInParameter.cs index bdd1ca45e..703c3e6db 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/IEffectInParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/IEffectInParameter.cs @@ -50,4 +50,4 @@ namespace Ryujinx.Audio.Renderer.Parameter /// Span SpecificData { get; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/IEffectOutStatus.cs b/src/Ryujinx.Audio/Renderer/Parameter/IEffectOutStatus.cs index a5addbcb7..74d132209 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/IEffectOutStatus.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/IEffectOutStatus.cs @@ -10,4 +10,4 @@ namespace Ryujinx.Audio.Renderer.Parameter /// EffectState State { get; set; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/MemoryPoolInParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/MemoryPoolInParameter.cs index 242e3843c..602508589 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/MemoryPoolInParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/MemoryPoolInParameter.cs @@ -30,4 +30,4 @@ namespace Ryujinx.Audio.Renderer.Parameter /// private unsafe fixed uint _reserved[3]; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/MemoryPoolOutStatus.cs b/src/Ryujinx.Audio/Renderer/Parameter/MemoryPoolOutStatus.cs index 29a6e261f..a78937d01 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/MemoryPoolOutStatus.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/MemoryPoolOutStatus.cs @@ -19,4 +19,4 @@ namespace Ryujinx.Audio.Renderer.Parameter /// private unsafe fixed uint _reserved[3]; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/MixInParameterDirtyOnlyUpdate.cs b/src/Ryujinx.Audio/Renderer/Parameter/MixInParameterDirtyOnlyUpdate.cs index c0954cda0..733b5ad76 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/MixInParameterDirtyOnlyUpdate.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/MixInParameterDirtyOnlyUpdate.cs @@ -24,4 +24,4 @@ namespace Ryujinx.Audio.Renderer.Parameter /// private unsafe fixed byte _reserved[24]; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/MixParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/MixParameter.cs index 5b9a969a0..2eec04a21 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/MixParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/MixParameter.cs @@ -41,7 +41,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/padding. /// - private ushort _reserved1; + private readonly ushort _reserved1; /// /// The id of the mix. @@ -61,7 +61,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/padding. /// - private ulong _reserved2; + private readonly ulong _reserved2; /// /// Mix buffer volumes storage. @@ -81,7 +81,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/padding. /// - private uint _reserved3; + private readonly uint _reserved3; [StructLayout(LayoutKind.Sequential, Size = 4 * Constants.MixBufferCountMax * Constants.MixBufferCountMax, Pack = 1)] private struct MixVolumeArray { } @@ -92,4 +92,4 @@ namespace Ryujinx.Audio.Renderer.Parameter /// Used when no splitter id is specified. public Span MixBufferVolume => SpanHelpers.AsSpan(ref _mixBufferVolumeArray); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Performance/PerformanceInParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/Performance/PerformanceInParameter.cs index 0f9a3aa3e..806f7fa89 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Performance/PerformanceInParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Performance/PerformanceInParameter.cs @@ -18,4 +18,4 @@ namespace Ryujinx.Audio.Renderer.Parameter.Performance /// private unsafe fixed uint _reserved[3]; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Performance/PerformanceOutStatus.cs b/src/Ryujinx.Audio/Renderer/Parameter/Performance/PerformanceOutStatus.cs index 64bbe080a..839d6eb6b 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Performance/PerformanceOutStatus.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Performance/PerformanceOutStatus.cs @@ -18,4 +18,4 @@ namespace Ryujinx.Audio.Renderer.Parameter.Performance /// private unsafe fixed uint _reserved[3]; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/RendererInfoOutStatus.cs b/src/Ryujinx.Audio/Renderer/Parameter/RendererInfoOutStatus.cs index a42ea833f..c97ce2965 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/RendererInfoOutStatus.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/RendererInfoOutStatus.cs @@ -16,6 +16,6 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/Unused. /// - private ulong _reserved; + private readonly ulong _reserved; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Sink/CircularBufferParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/Sink/CircularBufferParameter.cs index 7c02d65ff..0d4b276ef 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Sink/CircularBufferParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Sink/CircularBufferParameter.cs @@ -2,7 +2,6 @@ using Ryujinx.Audio.Common; using Ryujinx.Audio.Renderer.Common; using Ryujinx.Common.Memory; using System.Runtime.InteropServices; - using CpuAddress = System.UInt64; namespace Ryujinx.Audio.Renderer.Parameter.Sink @@ -41,7 +40,7 @@ namespace Ryujinx.Audio.Renderer.Parameter.Sink /// /// The target . /// - /// Only is supported. + /// Only is supported. public SampleFormat SampleFormat; /// @@ -57,6 +56,6 @@ namespace Ryujinx.Audio.Renderer.Parameter.Sink /// /// Reserved/padding. /// - private ushort _reserved2; + private readonly ushort _reserved2; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Sink/DeviceParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/Sink/DeviceParameter.cs index abeadaccf..652d02a63 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Sink/DeviceParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Sink/DeviceParameter.cs @@ -19,7 +19,7 @@ namespace Ryujinx.Audio.Renderer.Parameter.Sink /// /// Reserved/padding. /// - private byte _padding; + private readonly byte _padding; /// /// The total count of channels to output to the device. @@ -34,7 +34,7 @@ namespace Ryujinx.Audio.Renderer.Parameter.Sink /// /// Reserved/padding. /// - private byte _reserved; + private readonly byte _reserved; /// /// Set to true if the user controls Surround to Stereo downmixing coefficients. @@ -55,4 +55,4 @@ namespace Ryujinx.Audio.Renderer.Parameter.Sink /// public Span DeviceName => SpanHelpers.AsSpan(ref _deviceName); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/SinkInParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/SinkInParameter.cs index 1ee4eb532..3c1ac09c0 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/SinkInParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/SinkInParameter.cs @@ -25,7 +25,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/padding. /// - private ushort _reserved1; + private readonly ushort _reserved1; /// /// The node id of the sink. @@ -50,4 +50,4 @@ namespace Ryujinx.Audio.Renderer.Parameter /// public Span SpecificData => SpanHelpers.AsSpan(ref _specificDataStart); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/SinkOutStatus.cs b/src/Ryujinx.Audio/Renderer/Parameter/SinkOutStatus.cs index 426b861ca..dd0f867b5 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/SinkOutStatus.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/SinkOutStatus.cs @@ -16,11 +16,11 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/padding. /// - private uint _padding; + private readonly uint _padding; /// /// Reserved/padding. /// private unsafe fixed ulong _reserved[3]; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/SplitterDestinationInParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/SplitterDestinationInParameter.cs index 96c43092b..b74b67be0 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/SplitterDestinationInParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/SplitterDestinationInParameter.cs @@ -59,9 +59,9 @@ namespace Ryujinx.Audio.Renderer.Parameter /// Check if the magic is valid. /// /// Returns true if the magic is valid. - public bool IsMagicValid() + public readonly bool IsMagicValid() { return Magic == ValidMagic; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/SplitterInParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/SplitterInParameter.cs index 0220497de..2567b15a8 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/SplitterInParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/SplitterInParameter.cs @@ -38,9 +38,9 @@ namespace Ryujinx.Audio.Renderer.Parameter /// Check if the magic is valid. /// /// Returns true if the magic is valid. - public bool IsMagicValid() + public readonly bool IsMagicValid() { return Magic == ValidMagic; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/SplitterInParameterHeader.cs b/src/Ryujinx.Audio/Renderer/Parameter/SplitterInParameterHeader.cs index dbae17a9a..10fa866e7 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/SplitterInParameterHeader.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/SplitterInParameterHeader.cs @@ -37,9 +37,9 @@ namespace Ryujinx.Audio.Renderer.Parameter /// Check if the magic is valid. /// /// Returns true if the magic is valid. - public bool IsMagicValid() + public readonly bool IsMagicValid() { return Magic == ValidMagic; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/VoiceChannelResourceInParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/VoiceChannelResourceInParameter.cs index 6a863237d..6cff1a251 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/VoiceChannelResourceInParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/VoiceChannelResourceInParameter.cs @@ -25,4 +25,4 @@ namespace Ryujinx.Audio.Renderer.Parameter [MarshalAs(UnmanagedType.I1)] public bool IsUsed; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/VoiceInParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/VoiceInParameter.cs index c4b4ba312..86f92442b 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/VoiceInParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/VoiceInParameter.cs @@ -94,7 +94,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/unused. /// - private uint _reserved1; + private readonly uint _reserved1; /// /// User state address required by the data source. @@ -143,7 +143,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/unused. /// - private ushort _reserved2; + private readonly ushort _reserved2; /// /// Change the behaviour of the voice. @@ -222,7 +222,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/unused. /// - private byte _reserved; + private readonly byte _reserved; /// /// If set to anything other than 0, specifies how many times to loop the wavebuffer. @@ -260,7 +260,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// The PCM sample type /// Returns true if the sample offset are in range of the size. [MethodImpl(MethodImplOptions.AggressiveInlining)] - private bool IsSampleOffsetInRangeForPcm() where T : unmanaged + private readonly bool IsSampleOffsetInRangeForPcm() where T : unmanaged { uint dataTypeSize = (uint)Unsafe.SizeOf(); @@ -273,27 +273,15 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// The target /// Returns true if the sample offset are in range of the size. - public bool IsSampleOffsetValid(SampleFormat format) + public readonly bool IsSampleOffsetValid(SampleFormat format) { - bool result; - - switch (format) + return format switch { - case SampleFormat.PcmInt16: - result = IsSampleOffsetInRangeForPcm(); - break; - case SampleFormat.PcmFloat: - result = IsSampleOffsetInRangeForPcm(); - break; - case SampleFormat.Adpcm: - result = AdpcmHelper.GetAdpcmDataSize((int)StartSampleOffset) <= Size && - AdpcmHelper.GetAdpcmDataSize((int)EndSampleOffset) <= Size; - break; - default: - throw new NotImplementedException($"{format} not implemented!"); - } - - return result; + SampleFormat.PcmInt16 => IsSampleOffsetInRangeForPcm(), + SampleFormat.PcmFloat => IsSampleOffsetInRangeForPcm(), + SampleFormat.Adpcm => AdpcmHelper.GetAdpcmDataSize((int)StartSampleOffset) <= Size && AdpcmHelper.GetAdpcmDataSize((int)EndSampleOffset) <= Size, + _ => throw new NotImplementedException($"{format} not implemented!"), + }; } } @@ -316,7 +304,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Skip pitch and Sample Rate Conversion (SRC). /// - SkipPitchAndSampleRateConversion = 2 + SkipPitchAndSampleRateConversion = 2, } /// @@ -338,7 +326,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Resample interpolating 1 samples per output sample. /// - Low + Low, } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/VoiceOutStatus.cs b/src/Ryujinx.Audio/Renderer/Parameter/VoiceOutStatus.cs index be9d35849..a7c749835 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/VoiceOutStatus.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/VoiceOutStatus.cs @@ -32,4 +32,4 @@ namespace Ryujinx.Audio.Renderer.Parameter /// private unsafe fixed byte _reserved[3]; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/AudioRenderSystem.cs b/src/Ryujinx.Audio/Renderer/Server/AudioRenderSystem.cs index 8485fb4c5..7bb8ae5ba 100644 --- a/src/Ryujinx.Audio/Renderer/Server/AudioRenderSystem.cs +++ b/src/Ryujinx.Audio/Renderer/Server/AudioRenderSystem.cs @@ -19,7 +19,6 @@ using System; using System.Buffers; using System.Diagnostics; using System.Threading; - using CpuAddress = System.UInt64; namespace Ryujinx.Audio.Renderer.Server @@ -30,19 +29,21 @@ namespace Ryujinx.Audio.Renderer.Server private AudioRendererRenderingDevice _renderingDevice; private AudioRendererExecutionMode _executionMode; - private IWritableEvent _systemEvent; + private readonly IWritableEvent _systemEvent; private MemoryPoolState _dspMemoryPoolState; - private VoiceContext _voiceContext; - private MixContext _mixContext; - private SinkContext _sinkContext; - private SplitterContext _splitterContext; - private EffectContext _effectContext; + private readonly VoiceContext _voiceContext; + private readonly MixContext _mixContext; + private readonly SinkContext _sinkContext; + private readonly SplitterContext _splitterContext; + private readonly EffectContext _effectContext; private PerformanceManager _performanceManager; private UpsamplerManager _upsamplerManager; private bool _isActive; private BehaviourContext _behaviourContext; +#pragma warning disable IDE0052 // Remove unread private member private ulong _totalElapsedTicksUpdating; private ulong _totalElapsedTicks; +#pragma warning restore IDE0052 private int _sessionId; private Memory _memoryPools; @@ -75,7 +76,7 @@ namespace Ryujinx.Audio.Renderer.Server private ulong _elapsedFrameCount; private ulong _renderingStartTick; - private AudioRendererManager _manager; + private readonly AudioRendererManager _manager; private int _disposeState; @@ -143,12 +144,12 @@ namespace Ryujinx.Audio.Renderer.Server WorkBufferAllocator workBufferAllocator; - workBufferMemory.Span.Fill(0); + workBufferMemory.Span.Clear(); _workBufferMemoryPin = workBufferMemory.Pin(); workBufferAllocator = new WorkBufferAllocator(workBufferMemory); - PoolMapper poolMapper = new PoolMapper(processHandle, false); + PoolMapper poolMapper = new(processHandle, false); poolMapper.InitializeSystemPool(ref _dspMemoryPoolState, workBuffer, workBufferSize); _mixBuffer = workBufferAllocator.Allocate(_sampleCount * (_voiceChannelCountMax + _mixBufferCount), 0x10); @@ -244,9 +245,9 @@ namespace Ryujinx.Audio.Renderer.Server foreach (ref MixState mix in mixes.Span) { - mix = new MixState(effectProcessingOrderArray.Slice(0, (int)parameter.EffectCount), ref _behaviourContext); + mix = new MixState(effectProcessingOrderArray[..(int)parameter.EffectCount], ref _behaviourContext); - effectProcessingOrderArray = effectProcessingOrderArray.Slice((int)parameter.EffectCount); + effectProcessingOrderArray = effectProcessingOrderArray[(int)parameter.EffectCount..]; } } @@ -341,26 +342,15 @@ namespace Ryujinx.Audio.Renderer.Server _elapsedFrameCount = 0; _voiceDropParameter = 1.0f; - switch (_behaviourContext.GetCommandProcessingTimeEstimatorVersion()) + _commandProcessingTimeEstimator = _behaviourContext.GetCommandProcessingTimeEstimatorVersion() switch { - case 1: - _commandProcessingTimeEstimator = new CommandProcessingTimeEstimatorVersion1(_sampleCount, _mixBufferCount); - break; - case 2: - _commandProcessingTimeEstimator = new CommandProcessingTimeEstimatorVersion2(_sampleCount, _mixBufferCount); - break; - case 3: - _commandProcessingTimeEstimator = new CommandProcessingTimeEstimatorVersion3(_sampleCount, _mixBufferCount); - break; - case 4: - _commandProcessingTimeEstimator = new CommandProcessingTimeEstimatorVersion4(_sampleCount, _mixBufferCount); - break; - case 5: - _commandProcessingTimeEstimator = new CommandProcessingTimeEstimatorVersion5(_sampleCount, _mixBufferCount); - break; - default: - throw new NotImplementedException($"Unsupported processing time estimator version {_behaviourContext.GetCommandProcessingTimeEstimatorVersion()}."); - } + 1 => new CommandProcessingTimeEstimatorVersion1(_sampleCount, _mixBufferCount), + 2 => new CommandProcessingTimeEstimatorVersion2(_sampleCount, _mixBufferCount), + 3 => new CommandProcessingTimeEstimatorVersion3(_sampleCount, _mixBufferCount), + 4 => new CommandProcessingTimeEstimatorVersion4(_sampleCount, _mixBufferCount), + 5 => new CommandProcessingTimeEstimatorVersion5(_sampleCount, _mixBufferCount), + _ => throw new NotImplementedException($"Unsupported processing time estimator version {_behaviourContext.GetCommandProcessingTimeEstimatorVersion()}."), + }; return ResultCode.Success; } @@ -402,9 +392,9 @@ namespace Ryujinx.Audio.Renderer.Server { ulong updateStartTicks = GetSystemTicks(); - output.Span.Fill(0); + output.Span.Clear(); - StateUpdater stateUpdater = new StateUpdater(input, output, _processHandle, _behaviourContext); + StateUpdater stateUpdater = new(input, output, _processHandle, _behaviourContext); ResultCode result; @@ -609,9 +599,9 @@ namespace Ryujinx.Audio.Renderer.Server _renderingStartTick = 0; } - CommandBuffer commandBuffer = new CommandBuffer(commandList, _commandProcessingTimeEstimator); + CommandBuffer commandBuffer = new(commandList, _commandProcessingTimeEstimator); - CommandGenerator commandGenerator = new CommandGenerator(commandBuffer, GetContext(), _voiceContext, _mixContext, _effectContext, _sinkContext, _splitterContext, _performanceManager); + CommandGenerator commandGenerator = new(commandBuffer, GetContext(), _voiceContext, _mixContext, _effectContext, _sinkContext, _splitterContext, _performanceManager); _voiceContext.Sort(); commandGenerator.GenerateVoices(); @@ -731,7 +721,7 @@ namespace Ryujinx.Audio.Renderer.Server DepopBuffer = _depopBuffer, MixBufferCount = GetMixBufferCount(), SessionId = _sessionId, - UpsamplerManager = _upsamplerManager + UpsamplerManager = _upsamplerManager, }; } @@ -742,7 +732,7 @@ namespace Ryujinx.Audio.Renderer.Server public static ulong GetWorkBufferSize(ref AudioRendererConfiguration parameter) { - BehaviourContext behaviourContext = new BehaviourContext(); + BehaviourContext behaviourContext = new(); behaviourContext.SetUserRevision(parameter.Revision); @@ -813,6 +803,8 @@ namespace Ryujinx.Audio.Renderer.Server public void Dispose() { + GC.SuppressFinalize(this); + if (Interlocked.CompareExchange(ref _disposeState, 1, 0) == 0) { Dispose(true); @@ -828,7 +820,7 @@ namespace Ryujinx.Audio.Renderer.Server Stop(); } - PoolMapper mapper = new PoolMapper(_processHandle, false); + PoolMapper mapper = new(_processHandle, false); mapper.Unmap(ref _dspMemoryPoolState); PoolMapper.ClearUsageState(_memoryPools); @@ -876,4 +868,4 @@ namespace Ryujinx.Audio.Renderer.Server return ResultCode.UnsupportedOperation; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/AudioRendererManager.cs b/src/Ryujinx.Audio/Renderer/Server/AudioRendererManager.cs index e41d5cc50..0dbbd26c8 100644 --- a/src/Ryujinx.Audio/Renderer/Server/AudioRendererManager.cs +++ b/src/Ryujinx.Audio/Renderer/Server/AudioRendererManager.cs @@ -29,7 +29,7 @@ namespace Ryujinx.Audio.Renderer.Server /// /// The session ids allocation table. /// - private int[] _sessionIds; + private readonly int[] _sessionIds; /// /// The events linked to each session. @@ -39,7 +39,7 @@ namespace Ryujinx.Audio.Renderer.Server /// /// The sessions instances. /// - private AudioRenderSystem[] _sessions; + private readonly AudioRenderSystem[] _sessions; /// /// The count of active sessions. @@ -186,7 +186,7 @@ namespace Ryujinx.Audio.Renderer.Server _workerThread = new Thread(SendCommands) { - Name = "AudioRendererManager.Worker" + Name = "AudioRendererManager.Worker", }; _workerThread.Start(); @@ -317,7 +317,7 @@ namespace Ryujinx.Audio.Renderer.Server { int sessionId = AcquireSessionId(); - AudioRenderSystem audioRenderer = new AudioRenderSystem(this, _sessionsSystemEvent[sessionId]); + AudioRenderSystem audioRenderer = new(this, _sessionsSystemEvent[sessionId]); // TODO: Eventually, we should try to use the guest supplied work buffer instead of allocating // our own. However, it was causing problems on some applications that would unmap the memory @@ -367,6 +367,8 @@ namespace Ryujinx.Audio.Renderer.Server public void Dispose() { + GC.SuppressFinalize(this); + if (Interlocked.CompareExchange(ref _disposeState, 1, 0) == 0) { Dispose(true); @@ -402,4 +404,4 @@ namespace Ryujinx.Audio.Renderer.Server } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/BehaviourContext.cs b/src/Ryujinx.Audio/Renderer/Server/BehaviourContext.cs index 821947a98..3297b5d9f 100644 --- a/src/Ryujinx.Audio/Renderer/Server/BehaviourContext.cs +++ b/src/Ryujinx.Audio/Renderer/Server/BehaviourContext.cs @@ -125,7 +125,7 @@ namespace Ryujinx.Audio.Renderer.Server /// /// Error storage. /// - private ErrorInfo[] _errorInfos; + private readonly ErrorInfo[] _errorInfos; /// /// Current position in the array. @@ -254,7 +254,8 @@ namespace Ryujinx.Audio.Renderer.Server { return 0.80f; } - else if (CheckFeatureSupported(UserRevision, BaseRevisionMagic + Revision4)) + + if (CheckFeatureSupported(UserRevision, BaseRevisionMagic + Revision4)) { return 0.75f; } @@ -299,10 +300,8 @@ namespace Ryujinx.Audio.Renderer.Server { return 2; } - else - { - return 1; - } + + return 1; } /// @@ -436,7 +435,7 @@ namespace Ryujinx.Audio.Renderer.Server errorInfos[i] = new ErrorInfo { ErrorCode = 0, - ExtraErrorInfo = 0 + ExtraErrorInfo = 0, }; } } @@ -450,4 +449,4 @@ namespace Ryujinx.Audio.Renderer.Server _errorIndex = 0; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/CommandBuffer.cs b/src/Ryujinx.Audio/Renderer/Server/CommandBuffer.cs index 905cb2054..f4174a913 100644 --- a/src/Ryujinx.Audio/Renderer/Server/CommandBuffer.cs +++ b/src/Ryujinx.Audio/Renderer/Server/CommandBuffer.cs @@ -20,7 +20,7 @@ namespace Ryujinx.Audio.Renderer.Server /// /// The command processing time estimator in use. /// - private ICommandProcessingTimeEstimator _commandProcessingTimeEstimator; + private readonly ICommandProcessingTimeEstimator _commandProcessingTimeEstimator; /// /// The estimated total processing time. @@ -61,7 +61,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateClearMixBuffer(int nodeId) { - ClearMixBufferCommand command = new ClearMixBufferCommand(nodeId); + ClearMixBufferCommand command = new(nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -79,7 +79,7 @@ namespace Ryujinx.Audio.Renderer.Server /// Set to true if the voice was playing previously. public void GenerateDepopPrepare(Memory state, Memory depopBuffer, uint bufferCount, uint bufferOffset, int nodeId, bool wasPlaying) { - DepopPrepareCommand command = new DepopPrepareCommand(state, depopBuffer, bufferCount, bufferOffset, nodeId, wasPlaying); + DepopPrepareCommand command = new(state, depopBuffer, bufferCount, bufferOffset, nodeId, wasPlaying); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -94,7 +94,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GeneratePerformance(ref PerformanceEntryAddresses performanceEntryAddresses, PerformanceCommand.Type type, int nodeId) { - PerformanceCommand command = new PerformanceCommand(ref performanceEntryAddresses, type, nodeId); + PerformanceCommand command = new(ref performanceEntryAddresses, type, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -110,7 +110,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateVolumeRamp(float previousVolume, float volume, uint bufferIndex, int nodeId) { - VolumeRampCommand command = new VolumeRampCommand(previousVolume, volume, bufferIndex, nodeId); + VolumeRampCommand command = new(previousVolume, volume, bufferIndex, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -127,7 +127,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateDataSourceVersion2(ref VoiceState voiceState, Memory state, ushort outputBufferIndex, ushort channelIndex, int nodeId) { - DataSourceVersion2Command command = new DataSourceVersion2Command(ref voiceState, state, outputBufferIndex, channelIndex, nodeId); + DataSourceVersion2Command command = new(ref voiceState, state, outputBufferIndex, channelIndex, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -144,7 +144,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GeneratePcmInt16DataSourceVersion1(ref VoiceState voiceState, Memory state, ushort outputBufferIndex, ushort channelIndex, int nodeId) { - PcmInt16DataSourceCommandVersion1 command = new PcmInt16DataSourceCommandVersion1(ref voiceState, state, outputBufferIndex, channelIndex, nodeId); + PcmInt16DataSourceCommandVersion1 command = new(ref voiceState, state, outputBufferIndex, channelIndex, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -161,7 +161,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GeneratePcmFloatDataSourceVersion1(ref VoiceState voiceState, Memory state, ushort outputBufferIndex, ushort channelIndex, int nodeId) { - PcmFloatDataSourceCommandVersion1 command = new PcmFloatDataSourceCommandVersion1(ref voiceState, state, outputBufferIndex, channelIndex, nodeId); + PcmFloatDataSourceCommandVersion1 command = new(ref voiceState, state, outputBufferIndex, channelIndex, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -177,7 +177,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateAdpcmDataSourceVersion1(ref VoiceState voiceState, Memory state, ushort outputBufferIndex, int nodeId) { - AdpcmDataSourceCommandVersion1 command = new AdpcmDataSourceCommandVersion1(ref voiceState, state, outputBufferIndex, nodeId); + AdpcmDataSourceCommandVersion1 command = new(ref voiceState, state, outputBufferIndex, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -196,7 +196,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateBiquadFilter(int baseIndex, ref BiquadFilterParameter filter, Memory biquadFilterStateMemory, int inputBufferOffset, int outputBufferOffset, bool needInitialization, int nodeId) { - BiquadFilterCommand command = new BiquadFilterCommand(baseIndex, ref filter, biquadFilterStateMemory, inputBufferOffset, outputBufferOffset, needInitialization, nodeId); + BiquadFilterCommand command = new(baseIndex, ref filter, biquadFilterStateMemory, inputBufferOffset, outputBufferOffset, needInitialization, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -215,7 +215,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateGroupedBiquadFilter(int baseIndex, ReadOnlySpan filters, Memory biquadFilterStatesMemory, int inputBufferOffset, int outputBufferOffset, ReadOnlySpan isInitialized, int nodeId) { - GroupedBiquadFilterCommand command = new GroupedBiquadFilterCommand(baseIndex, filters, biquadFilterStatesMemory, inputBufferOffset, outputBufferOffset, isInitialized, nodeId); + GroupedBiquadFilterCommand command = new(baseIndex, filters, biquadFilterStatesMemory, inputBufferOffset, outputBufferOffset, isInitialized, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -234,7 +234,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateMixRampGrouped(uint mixBufferCount, uint inputBufferIndex, uint outputBufferIndex, Span previousVolume, Span volume, Memory state, int nodeId) { - MixRampGroupedCommand command = new MixRampGroupedCommand(mixBufferCount, inputBufferIndex, outputBufferIndex, previousVolume, volume, state, nodeId); + MixRampGroupedCommand command = new(mixBufferCount, inputBufferIndex, outputBufferIndex, previousVolume, volume, state, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -253,7 +253,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateMixRamp(float previousVolume, float volume, uint inputBufferIndex, uint outputBufferIndex, int lastSampleIndex, Memory state, int nodeId) { - MixRampCommand command = new MixRampCommand(previousVolume, volume, inputBufferIndex, outputBufferIndex, lastSampleIndex, state, nodeId); + MixRampCommand command = new(previousVolume, volume, inputBufferIndex, outputBufferIndex, lastSampleIndex, state, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -270,7 +270,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The target sample rate in use. public void GenerateDepopForMixBuffersCommand(Memory depopBuffer, uint bufferOffset, uint bufferCount, int nodeId, uint sampleRate) { - DepopForMixBuffersCommand command = new DepopForMixBuffersCommand(depopBuffer, bufferOffset, bufferCount, nodeId, sampleRate); + DepopForMixBuffersCommand command = new(depopBuffer, bufferOffset, bufferCount, nodeId, sampleRate); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -285,7 +285,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateCopyMixBuffer(uint inputBufferIndex, uint outputBufferIndex, int nodeId) { - CopyMixBufferCommand command = new CopyMixBufferCommand(inputBufferIndex, outputBufferIndex, nodeId); + CopyMixBufferCommand command = new(inputBufferIndex, outputBufferIndex, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -301,7 +301,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The mix volume. public void GenerateMix(uint inputBufferIndex, uint outputBufferIndex, int nodeId, float volume) { - MixCommand command = new MixCommand(inputBufferIndex, outputBufferIndex, nodeId, volume); + MixCommand command = new(inputBufferIndex, outputBufferIndex, nodeId, volume); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -323,7 +323,7 @@ namespace Ryujinx.Audio.Renderer.Server { if (parameter.IsChannelCountValid()) { - ReverbCommand command = new ReverbCommand(bufferOffset, parameter, state, isEnabled, workBuffer, nodeId, isLongSizePreDelaySupported, newEffectChannelMappingSupported); + ReverbCommand command = new(bufferOffset, parameter, state, isEnabled, workBuffer, nodeId, isLongSizePreDelaySupported, newEffectChannelMappingSupported); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -345,7 +345,7 @@ namespace Ryujinx.Audio.Renderer.Server { if (parameter.IsChannelCountValid()) { - Reverb3dCommand command = new Reverb3dCommand(bufferOffset, parameter, state, isEnabled, workBuffer, nodeId, newEffectChannelMappingSupported); + Reverb3dCommand command = new(bufferOffset, parameter, state, isEnabled, workBuffer, nodeId, newEffectChannelMappingSupported); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -368,7 +368,7 @@ namespace Ryujinx.Audio.Renderer.Server { if (parameter.IsChannelCountValid()) { - DelayCommand command = new DelayCommand(bufferOffset, parameter, state, isEnabled, workBuffer, nodeId, newEffectChannelMappingSupported); + DelayCommand command = new(bufferOffset, parameter, state, isEnabled, workBuffer, nodeId, newEffectChannelMappingSupported); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -389,7 +389,7 @@ namespace Ryujinx.Audio.Renderer.Server { if (parameter.IsChannelCountValid()) { - LimiterCommandVersion1 command = new LimiterCommandVersion1(bufferOffset, parameter, state, isEnabled, workBuffer, nodeId); + LimiterCommandVersion1 command = new(bufferOffset, parameter, state, isEnabled, workBuffer, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -411,7 +411,7 @@ namespace Ryujinx.Audio.Renderer.Server { if (parameter.IsChannelCountValid()) { - LimiterCommandVersion2 command = new LimiterCommandVersion2(bufferOffset, parameter, state, effectResultState, isEnabled, workBuffer, nodeId); + LimiterCommandVersion2 command = new(bufferOffset, parameter, state, effectResultState, isEnabled, workBuffer, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -437,7 +437,7 @@ namespace Ryujinx.Audio.Renderer.Server { if (state.SendBufferInfoBase != 0 && state.ReturnBufferInfoBase != 0) { - AuxiliaryBufferCommand command = new AuxiliaryBufferCommand(bufferOffset, inputBufferOffset, outputBufferOffset, ref state, isEnabled, countMax, outputBuffer, inputBuffer, updateCount, writeOffset, nodeId); + AuxiliaryBufferCommand command = new(bufferOffset, inputBufferOffset, outputBufferOffset, ref state, isEnabled, countMax, outputBuffer, inputBuffer, updateCount, writeOffset, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -461,7 +461,7 @@ namespace Ryujinx.Audio.Renderer.Server { if (sendBufferInfo != 0) { - CaptureBufferCommand command = new CaptureBufferCommand(bufferOffset, inputBufferOffset, sendBufferInfo, isEnabled, countMax, outputBuffer, updateCount, writeOffset, nodeId); + CaptureBufferCommand command = new(bufferOffset, inputBufferOffset, sendBufferInfo, isEnabled, countMax, outputBuffer, updateCount, writeOffset, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -473,7 +473,7 @@ namespace Ryujinx.Audio.Renderer.Server { if (parameter.IsChannelCountValid()) { - CompressorCommand command = new CompressorCommand(bufferOffset, parameter, state, isEnabled, nodeId); + CompressorCommand command = new(bufferOffset, parameter, state, isEnabled, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -489,7 +489,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateVolume(float volume, uint bufferOffset, int nodeId) { - VolumeCommand command = new VolumeCommand(volume, bufferOffset, nodeId); + VolumeCommand command = new(volume, bufferOffset, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -504,7 +504,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateCircularBuffer(uint bufferOffset, CircularBufferSink sink, int nodeId) { - CircularBufferSinkCommand command = new CircularBufferSinkCommand(bufferOffset, ref sink.Parameter, ref sink.CircularBufferAddressInfo, sink.CurrentWriteOffset, nodeId); + CircularBufferSinkCommand command = new(bufferOffset, ref sink.Parameter, ref sink.CircularBufferAddressInfo, sink.CurrentWriteOffset, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -521,7 +521,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateDownMixSurroundToStereo(uint bufferOffset, Span inputBufferOffset, Span outputBufferOffset, float[] downMixParameter, int nodeId) { - DownMixSurroundToStereoCommand command = new DownMixSurroundToStereoCommand(bufferOffset, inputBufferOffset, outputBufferOffset, downMixParameter, nodeId); + DownMixSurroundToStereoCommand command = new(bufferOffset, inputBufferOffset, outputBufferOffset, downMixParameter, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -541,7 +541,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateUpsample(uint bufferOffset, UpsamplerState upsampler, uint inputCount, Span inputBufferOffset, uint bufferCountPerSample, uint sampleCount, uint sampleRate, int nodeId) { - UpsampleCommand command = new UpsampleCommand(bufferOffset, upsampler, inputCount, inputBufferOffset, bufferCountPerSample, sampleCount, sampleRate, nodeId); + UpsampleCommand command = new(bufferOffset, upsampler, inputCount, inputBufferOffset, bufferCountPerSample, sampleCount, sampleRate, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -558,11 +558,11 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateDeviceSink(uint bufferOffset, DeviceSink sink, int sessionId, Memory buffer, int nodeId) { - DeviceSinkCommand command = new DeviceSinkCommand(bufferOffset, sink, sessionId, buffer, nodeId); + DeviceSinkCommand command = new(bufferOffset, sink, sessionId, buffer, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); AddCommand(command); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/CommandGenerator.cs b/src/Ryujinx.Audio/Renderer/Server/CommandGenerator.cs index afc1e39b7..ae8f699f3 100644 --- a/src/Ryujinx.Audio/Renderer/Server/CommandGenerator.cs +++ b/src/Ryujinx.Audio/Renderer/Server/CommandGenerator.cs @@ -17,14 +17,14 @@ namespace Ryujinx.Audio.Renderer.Server { public class CommandGenerator { - private CommandBuffer _commandBuffer; - private RendererSystemContext _rendererContext; - private VoiceContext _voiceContext; - private MixContext _mixContext; - private EffectContext _effectContext; - private SinkContext _sinkContext; - private SplitterContext _splitterContext; - private PerformanceManager _performanceManager; + private readonly CommandBuffer _commandBuffer; + private readonly RendererSystemContext _rendererContext; + private readonly VoiceContext _voiceContext; + private readonly MixContext _mixContext; + private readonly EffectContext _effectContext; + private readonly SinkContext _sinkContext; + private readonly SplitterContext _splitterContext; + private readonly PerformanceManager _performanceManager; public CommandGenerator(CommandBuffer commandBuffer, RendererSystemContext rendererContext, VoiceContext voiceContext, MixContext mixContext, EffectContext effectContext, SinkContext sinkContext, SplitterContext splitterContext, PerformanceManager performanceManager) { @@ -138,7 +138,7 @@ namespace Ryujinx.Audio.Renderer.Server if (supportsOptimizedPath && voiceState.BiquadFilters[0].Enable && voiceState.BiquadFilters[1].Enable) { - Memory biquadStateRawMemory = SpanMemoryManager.Cast(state).Slice(VoiceUpdateState.BiquadStateOffset, VoiceUpdateState.BiquadStateSize * Constants.VoiceBiquadFilterCount); + Memory biquadStateRawMemory = SpanMemoryManager.Cast(state)[..(VoiceUpdateState.BiquadStateSize * Constants.VoiceBiquadFilterCount)]; Memory stateMemory = SpanMemoryManager.Cast(biquadStateRawMemory); _commandBuffer.GenerateGroupedBiquadFilter(baseIndex, voiceState.BiquadFilters.AsSpan(), stateMemory, bufferOffset, bufferOffset, voiceState.BiquadFilterNeedInitialization, nodeId); @@ -151,7 +151,7 @@ namespace Ryujinx.Audio.Renderer.Server if (filter.Enable) { - Memory biquadStateRawMemory = SpanMemoryManager.Cast(state).Slice(VoiceUpdateState.BiquadStateOffset, VoiceUpdateState.BiquadStateSize * Constants.VoiceBiquadFilterCount); + Memory biquadStateRawMemory = SpanMemoryManager.Cast(state)[..(VoiceUpdateState.BiquadStateSize * Constants.VoiceBiquadFilterCount)]; Memory stateMemory = SpanMemoryManager.Cast(biquadStateRawMemory); @@ -224,7 +224,7 @@ namespace Ryujinx.Audio.Renderer.Server bool performanceInitialized = false; - PerformanceEntryAddresses performanceEntry = new PerformanceEntryAddresses(); + PerformanceEntryAddresses performanceEntry = new(); if (_performanceManager != null && _performanceManager.IsTargetNodeId(nodeId) && _performanceManager.GetNextEntry(out performanceEntry, dataSourceDetailType, PerformanceEntryType.Voice, nodeId)) { @@ -371,7 +371,7 @@ namespace Ryujinx.Audio.Renderer.Server { int nodeId = sortedState.NodeId; - PerformanceEntryAddresses performanceEntry = new PerformanceEntryAddresses(); + PerformanceEntryAddresses performanceEntry = new(); bool performanceInitialized = false; @@ -502,9 +502,11 @@ namespace Ryujinx.Audio.Renderer.Server bool needInitialization = effect.Parameter.Status == UsageState.Invalid || (effect.Parameter.Status == UsageState.New && !_rendererContext.BehaviourContext.IsBiquadFilterEffectStateClearBugFixed()); - BiquadFilterParameter parameter = new BiquadFilterParameter(); + BiquadFilterParameter parameter = new() + { + Enable = true, + }; - parameter.Enable = true; effect.Parameter.Denominator.AsSpan().CopyTo(parameter.Denominator.AsSpan()); effect.Parameter.Numerator.AsSpan().CopyTo(parameter.Numerator.AsSpan()); @@ -623,7 +625,7 @@ namespace Ryujinx.Audio.Renderer.Server bool isFinalMix = mix.MixId == Constants.FinalMixId; - PerformanceEntryAddresses performanceEntry = new PerformanceEntryAddresses(); + PerformanceEntryAddresses performanceEntry = new(); bool performanceInitialized = false; @@ -789,7 +791,7 @@ namespace Ryujinx.Audio.Renderer.Server GenerateEffects(ref subMix); - PerformanceEntryAddresses performanceEntry = new PerformanceEntryAddresses(); + PerformanceEntryAddresses performanceEntry = new(); int nodeId = subMix.NodeId; @@ -820,7 +822,7 @@ namespace Ryujinx.Audio.Renderer.Server { int nodeId = sortedState.NodeId; - PerformanceEntryAddresses performanceEntry = new PerformanceEntryAddresses(); + PerformanceEntryAddresses performanceEntry = new(); bool performanceInitialized = false; @@ -853,7 +855,7 @@ namespace Ryujinx.Audio.Renderer.Server GenerateEffects(ref finalMix); - PerformanceEntryAddresses performanceEntry = new PerformanceEntryAddresses(); + PerformanceEntryAddresses performanceEntry = new(); int nodeId = finalMix.NodeId; @@ -901,7 +903,7 @@ namespace Ryujinx.Audio.Renderer.Server { int nodeId = _mixContext.GetFinalState().NodeId; - PerformanceEntryAddresses performanceEntry = new PerformanceEntryAddresses(); + PerformanceEntryAddresses performanceEntry = new(); bool performanceInitialized = false; @@ -977,7 +979,7 @@ namespace Ryujinx.Audio.Renderer.Server { bool performanceInitialized = false; - PerformanceEntryAddresses performanceEntry = new PerformanceEntryAddresses(); + PerformanceEntryAddresses performanceEntry = new(); if (_performanceManager != null && _performanceManager.GetNextEntry(out performanceEntry, PerformanceEntryType.Sink, sink.NodeId)) { @@ -1025,4 +1027,4 @@ namespace Ryujinx.Audio.Renderer.Server } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion1.cs b/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion1.cs index 63dc9ca96..d95e9aa71 100644 --- a/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion1.cs +++ b/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion1.cs @@ -8,8 +8,8 @@ namespace Ryujinx.Audio.Renderer.Server /// public class CommandProcessingTimeEstimatorVersion1 : ICommandProcessingTimeEstimator { - private uint _sampleCount; - private uint _bufferCount; + private readonly uint _sampleCount; + private readonly uint _bufferCount; public CommandProcessingTimeEstimatorVersion1(uint sampleCount, uint bufferCount) { @@ -185,4 +185,4 @@ namespace Ryujinx.Audio.Renderer.Server return 0; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion2.cs b/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion2.cs index d4f28a07d..929aaf383 100644 --- a/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion2.cs +++ b/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion2.cs @@ -9,8 +9,8 @@ namespace Ryujinx.Audio.Renderer.Server /// public class CommandProcessingTimeEstimatorVersion2 : ICommandProcessingTimeEstimator { - private uint _sampleCount; - private uint _bufferCount; + private readonly uint _sampleCount; + private readonly uint _bufferCount; public CommandProcessingTimeEstimatorVersion2(uint sampleCount, uint bufferCount) { @@ -189,71 +189,47 @@ namespace Ryujinx.Audio.Renderer.Server { if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)41636.0f; - case 2: - return (uint)97861.0f; - case 4: - return (uint)192520.0f; - case 6: - return (uint)301760.0f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)41636.0f, + 2 => (uint)97861.0f, + 4 => (uint)192520.0f, + 6 => (uint)301760.0f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)578.53f; - case 2: - return (uint)663.06f; - case 4: - return (uint)703.98f; - case 6: - return (uint)760.03f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)578.53f, + 2 => (uint)663.06f, + 4 => (uint)703.98f, + 6 => (uint)760.03f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)8770.3f; - case 2: - return (uint)25741.0f; - case 4: - return (uint)47551.0f; - case 6: - return (uint)81629.0f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)8770.3f, + 2 => (uint)25741.0f, + 4 => (uint)47551.0f, + 6 => (uint)81629.0f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)521.28f; - case 2: - return (uint)585.4f; - case 4: - return (uint)629.88f; - case 6: - return (uint)713.57f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)521.28f, + 2 => (uint)585.4f, + 4 => (uint)629.88f, + 6 => (uint)713.57f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } public uint Estimate(ReverbCommand command) @@ -264,71 +240,47 @@ namespace Ryujinx.Audio.Renderer.Server { if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)97192.0f; - case 2: - return (uint)103280.0f; - case 4: - return (uint)109580.0f; - case 6: - return (uint)115070.0f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)97192.0f, + 2 => (uint)103280.0f, + 4 => (uint)109580.0f, + 6 => (uint)115070.0f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)492.01f; - case 2: - return (uint)554.46f; - case 4: - return (uint)595.86f; - case 6: - return (uint)656.62f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)492.01f, + 2 => (uint)554.46f, + 4 => (uint)595.86f, + 6 => (uint)656.62f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)136460.0f; - case 2: - return (uint)145750.0f; - case 4: - return (uint)154800.0f; - case 6: - return (uint)161970.0f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)136460.0f, + 2 => (uint)145750.0f, + 4 => (uint)154800.0f, + 6 => (uint)161970.0f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)495.79f; - case 2: - return (uint)527.16f; - case 4: - return (uint)598.75f; - case 6: - return (uint)666.03f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)495.79f, + 2 => (uint)527.16f, + 4 => (uint)598.75f, + 6 => (uint)666.03f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } public uint Estimate(Reverb3dCommand command) @@ -339,70 +291,46 @@ namespace Ryujinx.Audio.Renderer.Server { if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)138840.0f; - case 2: - return (uint)135430.0f; - case 4: - return (uint)199180.0f; - case 6: - return (uint)247350.0f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)138840.0f, + 2 => (uint)135430.0f, + 4 => (uint)199180.0f, + 6 => (uint)247350.0f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)718.7f; - case 2: - return (uint)751.3f; - case 4: - return (uint)797.46f; - case 6: - return (uint)867.43f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)718.7f, + 2 => (uint)751.3f, + 4 => (uint)797.46f, + 6 => (uint)867.43f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)199950.0f; - case 2: - return (uint)195200.0f; - case 4: - return (uint)290580.0f; - case 6: - return (uint)363490.0f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)199950.0f, + 2 => (uint)195200.0f, + 4 => (uint)290580.0f, + 6 => (uint)363490.0f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)534.24f; - case 2: - return (uint)570.87f; - case 4: - return (uint)660.93f; - case 6: - return (uint)694.6f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)534.24f, + 2 => (uint)570.87f, + 4 => (uint)660.93f, + 6 => (uint)694.6f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } public uint Estimate(AuxiliaryBufferCommand command) diff --git a/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion3.cs b/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion3.cs index b79ca1369..8ae4bc059 100644 --- a/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion3.cs +++ b/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion3.cs @@ -12,20 +12,20 @@ namespace Ryujinx.Audio.Renderer.Server /// public class CommandProcessingTimeEstimatorVersion3 : ICommandProcessingTimeEstimator { - protected uint _sampleCount; - protected uint _bufferCount; + protected uint SampleCount; + protected uint BufferCount; public CommandProcessingTimeEstimatorVersion3(uint sampleCount, uint bufferCount) { - _sampleCount = sampleCount; - _bufferCount = bufferCount; + SampleCount = sampleCount; + BufferCount = bufferCount; } public uint Estimate(PerformanceCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)498.17f; } @@ -35,24 +35,24 @@ namespace Ryujinx.Audio.Renderer.Server public uint Estimate(ClearMixBufferCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); float costPerBuffer = 440.68f; float baseCost = 0; - if (_sampleCount == 160) + if (SampleCount == 160) { costPerBuffer = 266.65f; } - return (uint)(baseCost + costPerBuffer * _bufferCount); + return (uint)(baseCost + costPerBuffer * BufferCount); } public uint Estimate(BiquadFilterCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)4173.2f; } @@ -64,9 +64,9 @@ namespace Ryujinx.Audio.Renderer.Server { float costPerSample = 6.4434f; - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { costPerSample = 6.708f; } @@ -81,14 +81,14 @@ namespace Ryujinx.Audio.Renderer.Server } } - return (uint)(_sampleCount * costPerSample * volumeCount); + return (uint)(SampleCount * costPerSample * volumeCount); } public uint Estimate(MixRampCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)1968.7f; } @@ -103,9 +103,9 @@ namespace Ryujinx.Audio.Renderer.Server public uint Estimate(VolumeRampCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)1425.3f; } @@ -115,41 +115,41 @@ namespace Ryujinx.Audio.Renderer.Server public uint Estimate(PcmInt16DataSourceCommandVersion1 command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); float costPerSample = 710.143f; float baseCost = 7853.286f; - if (_sampleCount == 160) + if (SampleCount == 160) { costPerSample = 427.52f; baseCost = 6329.442f; } - return (uint)(baseCost + (costPerSample * (((command.SampleRate / 200.0f) / _sampleCount) * (command.Pitch * 0.000030518f)))); + return (uint)(baseCost + (costPerSample * (((command.SampleRate / 200.0f) / SampleCount) * (command.Pitch * 0.000030518f)))); } public uint Estimate(AdpcmDataSourceCommandVersion1 command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); float costPerSample = 3564.1f; float baseCost = 9736.702f; - if (_sampleCount == 160) + if (SampleCount == 160) { costPerSample = 2125.6f; baseCost = 7913.808f; } - return (uint)(baseCost + (costPerSample * (((command.SampleRate / 200.0f) / _sampleCount) * (command.Pitch * 0.000030518f)))); + return (uint)(baseCost + (costPerSample * (((command.SampleRate / 200.0f) / SampleCount) * (command.Pitch * 0.000030518f)))); } public uint Estimate(DepopForMixBuffersCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)739.64f; } @@ -159,9 +159,9 @@ namespace Ryujinx.Audio.Renderer.Server public uint Estimate(CopyMixBufferCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)842.59f; } @@ -171,9 +171,9 @@ namespace Ryujinx.Audio.Renderer.Server public uint Estimate(MixCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)1402.8f; } @@ -183,231 +183,159 @@ namespace Ryujinx.Audio.Renderer.Server public virtual uint Estimate(DelayCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)8929.04f; - case 2: - return (uint)25500.75f; - case 4: - return (uint)47759.62f; - case 6: - return (uint)82203.07f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)8929.04f, + 2 => (uint)25500.75f, + 4 => (uint)47759.62f, + 6 => (uint)82203.07f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)1295.20f; - case 2: - return (uint)1213.60f; - case 4: - return (uint)942.03f; - case 6: - return (uint)1001.55f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)1295.20f, + 2 => (uint)1213.60f, + 4 => (uint)942.03f, + 6 => (uint)1001.55f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)11941.05f; - case 2: - return (uint)37197.37f; - case 4: - return (uint)69749.84f; - case 6: - return (uint)120042.40f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)11941.05f, + 2 => (uint)37197.37f, + 4 => (uint)69749.84f, + 6 => (uint)120042.40f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)997.67f; - case 2: - return (uint)977.63f; - case 4: - return (uint)792.30f; - case 6: - return (uint)875.43f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)997.67f, + 2 => (uint)977.63f, + 4 => (uint)792.30f, + 6 => (uint)875.43f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } public virtual uint Estimate(ReverbCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)81475.05f; - case 2: - return (uint)84975.0f; - case 4: - return (uint)91625.15f; - case 6: - return (uint)95332.27f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)81475.05f, + 2 => (uint)84975.0f, + 4 => (uint)91625.15f, + 6 => (uint)95332.27f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)536.30f; - case 2: - return (uint)588.70f; - case 4: - return (uint)643.70f; - case 6: - return (uint)706.0f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)536.30f, + 2 => (uint)588.70f, + 4 => (uint)643.70f, + 6 => (uint)706.0f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)120174.47f; - case 2: - return (uint)25262.22f; - case 4: - return (uint)135751.23f; - case 6: - return (uint)141129.23f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)120174.47f, + 2 => (uint)25262.22f, + 4 => (uint)135751.23f, + 6 => (uint)141129.23f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)617.64f; - case 2: - return (uint)659.54f; - case 4: - return (uint)711.43f; - case 6: - return (uint)778.07f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)617.64f, + 2 => (uint)659.54f, + 4 => (uint)711.43f, + 6 => (uint)778.07f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } public virtual uint Estimate(Reverb3dCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)116754.0f; - case 2: - return (uint)125912.05f; - case 4: - return (uint)146336.03f; - case 6: - return (uint)165812.66f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)116754.0f, + 2 => (uint)125912.05f, + 4 => (uint)146336.03f, + 6 => (uint)165812.66f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)734.0f; - case 2: - return (uint)766.62f; - case 4: - return (uint)797.46f; - case 6: - return (uint)867.43f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)734.0f, + 2 => (uint)766.62f, + 4 => (uint)797.46f, + 6 => (uint)867.43f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)170292.34f; - case 2: - return (uint)183875.63f; - case 4: - return (uint)214696.19f; - case 6: - return (uint)243846.77f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)170292.34f, + 2 => (uint)183875.63f, + 4 => (uint)214696.19f, + 6 => (uint)243846.77f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)508.47f; - case 2: - return (uint)582.45f; - case 4: - return (uint)626.42f; - case 6: - return (uint)682.47f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)508.47f, + 2 => (uint)582.45f, + 4 => (uint)626.42f, + 6 => (uint)682.47f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } public uint Estimate(AuxiliaryBufferCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { if (command.Enabled) { @@ -427,9 +355,9 @@ namespace Ryujinx.Audio.Renderer.Server public uint Estimate(VolumeCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)1311.1f; } @@ -439,12 +367,12 @@ namespace Ryujinx.Audio.Renderer.Server public uint Estimate(CircularBufferSinkCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); float costPerBuffer = 770.26f; float baseCost = 0f; - if (_sampleCount == 160) + if (SampleCount == 160) { costPerBuffer = 531.07f; } @@ -454,9 +382,9 @@ namespace Ryujinx.Audio.Renderer.Server public uint Estimate(DownMixSurroundToStereoCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)9949.7f; } @@ -466,9 +394,9 @@ namespace Ryujinx.Audio.Renderer.Server public uint Estimate(UpsampleCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)312990.0f; } @@ -478,12 +406,12 @@ namespace Ryujinx.Audio.Renderer.Server public uint Estimate(DeviceSinkCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); Debug.Assert(command.InputCount == 2 || command.InputCount == 6); if (command.InputCount == 2) { - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)8980.0f; } @@ -491,7 +419,7 @@ namespace Ryujinx.Audio.Renderer.Server return (uint)9221.9f; } - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)9177.9f; } @@ -501,27 +429,27 @@ namespace Ryujinx.Audio.Renderer.Server public uint Estimate(PcmFloatDataSourceCommandVersion1 command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); float costPerSample = 3490.9f; float baseCost = 10090.9f; - if (_sampleCount == 160) + if (SampleCount == 160) { costPerSample = 2310.4f; baseCost = 7845.25f; } - return (uint)(baseCost + (costPerSample * (((command.SampleRate / 200.0f) / _sampleCount) * (command.Pitch * 0.000030518f)))); + return (uint)(baseCost + (costPerSample * (((command.SampleRate / 200.0f) / SampleCount) * (command.Pitch * 0.000030518f)))); } public uint Estimate(DataSourceVersion2Command command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - (float baseCost, float costPerSample) = GetCostByFormat(_sampleCount, command.SampleFormat, command.SrcQuality); + (float baseCost, float costPerSample) = GetCostByFormat(SampleCount, command.SampleFormat, command.SrcQuality); - return (uint)(baseCost + (costPerSample * (((command.SampleRate / 200.0f) / _sampleCount) * (command.Pitch * 0.000030518f) - 1.0f))); + return (uint)(baseCost + (costPerSample * (((command.SampleRate / 200.0f) / SampleCount) * (command.Pitch * 0.000030518f) - 1.0f))); } private static (float, float) GetCostByFormat(uint sampleCount, SampleFormat format, SampleRateConversionQuality quality) @@ -618,124 +546,90 @@ namespace Ryujinx.Audio.Renderer.Server private uint EstimateLimiterCommandCommon(LimiterParameter parameter, bool enabled) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { if (enabled) { - switch (parameter.ChannelCount) + return parameter.ChannelCount switch { - case 1: - return (uint)21392.0f; - case 2: - return (uint)26829.0f; - case 4: - return (uint)32405.0f; - case 6: - return (uint)52219.0f; - default: - throw new NotImplementedException($"{parameter.ChannelCount}"); - } + 1 => (uint)21392.0f, + 2 => (uint)26829.0f, + 4 => (uint)32405.0f, + 6 => (uint)52219.0f, + _ => throw new NotImplementedException($"{parameter.ChannelCount}"), + }; } - else + + return parameter.ChannelCount switch { - switch (parameter.ChannelCount) - { - case 1: - return (uint)897.0f; - case 2: - return (uint)931.55f; - case 4: - return (uint)975.39f; - case 6: - return (uint)1016.8f; - default: - throw new NotImplementedException($"{parameter.ChannelCount}"); - } - } + 1 => (uint)897.0f, + 2 => (uint)931.55f, + 4 => (uint)975.39f, + 6 => (uint)1016.8f, + _ => throw new NotImplementedException($"{parameter.ChannelCount}"), + }; } if (enabled) { - switch (parameter.ChannelCount) + return parameter.ChannelCount switch { - case 1: - return (uint)30556.0f; - case 2: - return (uint)39011.0f; - case 4: - return (uint)48270.0f; - case 6: - return (uint)76712.0f; - default: - throw new NotImplementedException($"{parameter.ChannelCount}"); - } + 1 => (uint)30556.0f, + 2 => (uint)39011.0f, + 4 => (uint)48270.0f, + 6 => (uint)76712.0f, + _ => throw new NotImplementedException($"{parameter.ChannelCount}"), + }; } - else + + return parameter.ChannelCount switch { - switch (parameter.ChannelCount) - { - case 1: - return (uint)874.43f; - case 2: - return (uint)921.55f; - case 4: - return (uint)945.26f; - case 6: - return (uint)992.26f; - default: - throw new NotImplementedException($"{parameter.ChannelCount}"); - } - } + 1 => (uint)874.43f, + 2 => (uint)921.55f, + 4 => (uint)945.26f, + 6 => (uint)992.26f, + _ => throw new NotImplementedException($"{parameter.ChannelCount}"), + }; } public uint Estimate(LimiterCommandVersion1 command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); return EstimateLimiterCommandCommon(command.Parameter, command.IsEffectEnabled); } public uint Estimate(LimiterCommandVersion2 command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); if (!command.Parameter.StatisticsEnabled || !command.IsEffectEnabled) { return EstimateLimiterCommandCommon(command.Parameter, command.IsEffectEnabled); } - if (_sampleCount == 160) + if (SampleCount == 160) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)23309.0f; - case 2: - return (uint)29954.0f; - case 4: - return (uint)35807.0f; - case 6: - return (uint)58340.0f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)23309.0f, + 2 => (uint)29954.0f, + 4 => (uint)35807.0f, + 6 => (uint)58340.0f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)33526.0f; - case 2: - return (uint)43549.0f; - case 4: - return (uint)52190.0f; - case 6: - return (uint)85527.0f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)33526.0f, + 2 => (uint)43549.0f, + 4 => (uint)52190.0f, + 6 => (uint)85527.0f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } public virtual uint Estimate(GroupedBiquadFilterCommand command) @@ -753,4 +647,4 @@ namespace Ryujinx.Audio.Renderer.Server return 0; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion4.cs b/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion4.cs index c60d8ebcb..25bc67cd9 100644 --- a/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion4.cs +++ b/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion4.cs @@ -12,9 +12,9 @@ namespace Ryujinx.Audio.Renderer.Server public override uint Estimate(GroupedBiquadFilterCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)7424.5f; } @@ -24,9 +24,9 @@ namespace Ryujinx.Audio.Renderer.Server public override uint Estimate(CaptureBufferCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { if (command.Enabled) { @@ -44,4 +44,4 @@ namespace Ryujinx.Audio.Renderer.Server return (uint)435.2f; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion5.cs b/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion5.cs index 2ed7e6a5b..7135c1c4f 100644 --- a/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion5.cs +++ b/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion5.cs @@ -13,298 +13,202 @@ namespace Ryujinx.Audio.Renderer.Server public override uint Estimate(DelayCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return 8929; - case 2: - return 25501; - case 4: - return 47760; - case 6: - return 82203; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => 8929, + 2 => 25501, + 4 => 47760, + 6 => 82203, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)1295.20f; - case 2: - return (uint)1213.60f; - case 4: - return (uint)942.03f; - case 6: - return (uint)1001.6f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)1295.20f, + 2 => (uint)1213.60f, + 4 => (uint)942.03f, + 6 => (uint)1001.6f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return 11941; - case 2: - return 37197; - case 4: - return 69750; - case 6: - return 12004; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => 11941, + 2 => 37197, + 4 => 69750, + 6 => 12004, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)997.67f; - case 2: - return (uint)977.63f; - case 4: - return (uint)792.31f; - case 6: - return (uint)875.43f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)997.67f, + 2 => (uint)977.63f, + 4 => (uint)792.31f, + 6 => (uint)875.43f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } public override uint Estimate(ReverbCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return 81475; - case 2: - return 84975; - case 4: - return 91625; - case 6: - return 95332; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => 81475, + 2 => 84975, + 4 => 91625, + 6 => 95332, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)536.30f; - case 2: - return (uint)588.80f; - case 4: - return (uint)643.70f; - case 6: - return (uint)706.0f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)536.30f, + 2 => (uint)588.80f, + 4 => (uint)643.70f, + 6 => (uint)706.0f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return 120170; - case 2: - return 125260; - case 4: - return 135750; - case 6: - return 141130; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => 120170, + 2 => 125260, + 4 => 135750, + 6 => 141130, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)617.64f; - case 2: - return (uint)659.54f; - case 4: - return (uint)711.44f; - case 6: - return (uint)778.07f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)617.64f, + 2 => (uint)659.54f, + 4 => (uint)711.44f, + 6 => (uint)778.07f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } public override uint Estimate(Reverb3dCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return 116750; - case 2: - return 125910; - case 4: - return 146340; - case 6: - return 165810; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => 116750, + 2 => 125910, + 4 => 146340, + 6 => 165810, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return 735; - case 2: - return (uint)766.62f; - case 4: - return (uint)834.07f; - case 6: - return (uint)875.44f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => 735, + 2 => (uint)766.62f, + 4 => (uint)834.07f, + 6 => (uint)875.44f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return 170290; - case 2: - return 183880; - case 4: - return 214700; - case 6: - return 243850; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => 170290, + 2 => 183880, + 4 => 214700, + 6 => 243850, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)508.47f; - case 2: - return (uint)582.45f; - case 4: - return (uint)626.42f; - case 6: - return (uint)682.47f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)508.47f, + 2 => (uint)582.45f, + 4 => (uint)626.42f, + 6 => (uint)682.47f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } public override uint Estimate(CompressorCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return 34431; - case 2: - return 44253; - case 4: - return 63827; - case 6: - return 83361; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => 34431, + 2 => 44253, + 4 => 63827, + 6 => 83361, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)630.12f; - case 2: - return (uint)638.27f; - case 4: - return (uint)705.86f; - case 6: - return (uint)782.02f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)630.12f, + 2 => (uint)638.27f, + 4 => (uint)705.86f, + 6 => (uint)782.02f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return 51095; - case 2: - return 65693; - case 4: - return 95383; - case 6: - return 124510; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => 51095, + 2 => 65693, + 4 => 95383, + 6 => 124510, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)840.14f; - case 2: - return (uint)826.1f; - case 4: - return (uint)901.88f; - case 6: - return (uint)965.29f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)840.14f, + 2 => (uint)826.1f, + 4 => (uint)901.88f, + 6 => (uint)965.29f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Effect/AuxiliaryBufferEffect.cs b/src/Ryujinx.Audio/Renderer/Server/Effect/AuxiliaryBufferEffect.cs index 164065271..57ca266f4 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Effect/AuxiliaryBufferEffect.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Effect/AuxiliaryBufferEffect.cs @@ -58,7 +58,7 @@ namespace Ryujinx.Audio.Renderer.Server.Effect { ulong bufferSize = (ulong)Unsafe.SizeOf() * Parameter.BufferStorageSize + (ulong)Unsafe.SizeOf(); - bool sendBufferUnmapped = !mapper.TryAttachBuffer(out updateErrorInfo, ref WorkBuffers[0], Parameter.SendBufferInfoAddress, bufferSize); + bool sendBufferUnmapped = !mapper.TryAttachBuffer(out _, ref WorkBuffers[0], Parameter.SendBufferInfoAddress, bufferSize); bool returnBufferUnmapped = !mapper.TryAttachBuffer(out updateErrorInfo, ref WorkBuffers[1], Parameter.ReturnBufferInfoAddress, bufferSize); BufferUnmapped = sendBufferUnmapped && returnBufferUnmapped; @@ -82,4 +82,4 @@ namespace Ryujinx.Audio.Renderer.Server.Effect UpdateUsageStateForCommandGeneration(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Effect/BaseEffect.cs b/src/Ryujinx.Audio/Renderer/Server/Effect/BaseEffect.cs index 825b3bf76..a9716db2a 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Effect/BaseEffect.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Effect/BaseEffect.cs @@ -244,29 +244,19 @@ namespace Ryujinx.Audio.Renderer.Server.Effect /// The associated to the of this effect. public PerformanceDetailType GetPerformanceDetailType() { - switch (Type) + return Type switch { - case EffectType.BiquadFilter: - return PerformanceDetailType.BiquadFilter; - case EffectType.AuxiliaryBuffer: - return PerformanceDetailType.Aux; - case EffectType.Delay: - return PerformanceDetailType.Delay; - case EffectType.Reverb: - return PerformanceDetailType.Reverb; - case EffectType.Reverb3d: - return PerformanceDetailType.Reverb3d; - case EffectType.BufferMix: - return PerformanceDetailType.Mix; - case EffectType.Limiter: - return PerformanceDetailType.Limiter; - case EffectType.CaptureBuffer: - return PerformanceDetailType.CaptureBuffer; - case EffectType.Compressor: - return PerformanceDetailType.Compressor; - default: - throw new NotImplementedException($"{Type}"); - } + EffectType.BiquadFilter => PerformanceDetailType.BiquadFilter, + EffectType.AuxiliaryBuffer => PerformanceDetailType.Aux, + EffectType.Delay => PerformanceDetailType.Delay, + EffectType.Reverb => PerformanceDetailType.Reverb, + EffectType.Reverb3d => PerformanceDetailType.Reverb3d, + EffectType.BufferMix => PerformanceDetailType.Mix, + EffectType.Limiter => PerformanceDetailType.Limiter, + EffectType.CaptureBuffer => PerformanceDetailType.CaptureBuffer, + EffectType.Compressor => PerformanceDetailType.Compressor, + _ => throw new NotImplementedException($"{Type}"), + }; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Effect/BiquadFilterEffect.cs b/src/Ryujinx.Audio/Renderer/Server/Effect/BiquadFilterEffect.cs index de91046dc..b987f7c85 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Effect/BiquadFilterEffect.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Effect/BiquadFilterEffect.cs @@ -64,4 +64,4 @@ namespace Ryujinx.Audio.Renderer.Server.Effect Parameter.Status = UsageState.Enabled; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Effect/BufferMixEffect.cs b/src/Ryujinx.Audio/Renderer/Server/Effect/BufferMixEffect.cs index 82c0a055a..d6cb9cfa3 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Effect/BufferMixEffect.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Effect/BufferMixEffect.cs @@ -46,4 +46,4 @@ namespace Ryujinx.Audio.Renderer.Server.Effect UpdateUsageStateForCommandGeneration(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Effect/CaptureBufferEffect.cs b/src/Ryujinx.Audio/Renderer/Server/Effect/CaptureBufferEffect.cs index c445798d4..5be4b4ed5 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Effect/CaptureBufferEffect.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Effect/CaptureBufferEffect.cs @@ -79,4 +79,4 @@ namespace Ryujinx.Audio.Renderer.Server.Effect UpdateUsageStateForCommandGeneration(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Effect/DelayEffect.cs b/src/Ryujinx.Audio/Renderer/Server/Effect/DelayEffect.cs index 3f5d70bcf..43cabb7db 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Effect/DelayEffect.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Effect/DelayEffect.cs @@ -90,4 +90,4 @@ namespace Ryujinx.Audio.Renderer.Server.Effect Parameter.Status = UsageState.Enabled; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Effect/EffectContext.cs b/src/Ryujinx.Audio/Renderer/Server/Effect/EffectContext.cs index bfb6528b4..619f31100 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Effect/EffectContext.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Effect/EffectContext.cs @@ -120,4 +120,4 @@ namespace Ryujinx.Audio.Renderer.Server.Effect } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Effect/LimiterEffect.cs b/src/Ryujinx.Audio/Renderer/Server/Effect/LimiterEffect.cs index 6e17ef3d1..3e2f7326d 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Effect/LimiterEffect.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Effect/LimiterEffect.cs @@ -92,4 +92,4 @@ namespace Ryujinx.Audio.Renderer.Server.Effect destState = srcState; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Effect/Reverb3dEffect.cs b/src/Ryujinx.Audio/Renderer/Server/Effect/Reverb3dEffect.cs index 473fddb84..f9d7f4943 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Effect/Reverb3dEffect.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Effect/Reverb3dEffect.cs @@ -89,4 +89,4 @@ namespace Ryujinx.Audio.Renderer.Server.Effect Parameter.ParameterStatus = UsageState.Enabled; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Effect/ReverbEffect.cs b/src/Ryujinx.Audio/Renderer/Server/Effect/ReverbEffect.cs index e1543fd17..6fdf8fc23 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Effect/ReverbEffect.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Effect/ReverbEffect.cs @@ -92,4 +92,4 @@ namespace Ryujinx.Audio.Renderer.Server.Effect Parameter.Status = UsageState.Enabled; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Effect/UsageState.cs b/src/Ryujinx.Audio/Renderer/Server/Effect/UsageState.cs index 8648aa2ca..da7172244 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Effect/UsageState.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Effect/UsageState.cs @@ -23,6 +23,6 @@ namespace Ryujinx.Audio.Renderer.Server.Effect /// /// The effect is disabled. /// - Disabled + Disabled, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/ICommandProcessingTimeEstimator.cs b/src/Ryujinx.Audio/Renderer/Server/ICommandProcessingTimeEstimator.cs index 4872ddb3a..27b22363a 100644 --- a/src/Ryujinx.Audio/Renderer/Server/ICommandProcessingTimeEstimator.cs +++ b/src/Ryujinx.Audio/Renderer/Server/ICommandProcessingTimeEstimator.cs @@ -37,4 +37,4 @@ namespace Ryujinx.Audio.Renderer.Server uint Estimate(CaptureBufferCommand command); uint Estimate(CompressorCommand command); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/MemoryPool/AddressInfo.cs b/src/Ryujinx.Audio/Renderer/Server/MemoryPool/AddressInfo.cs index 5fd6b2b92..a7ec4cf51 100644 --- a/src/Ryujinx.Audio/Renderer/Server/MemoryPool/AddressInfo.cs +++ b/src/Ryujinx.Audio/Renderer/Server/MemoryPool/AddressInfo.cs @@ -27,9 +27,9 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool /// public DspAddress ForceMappedDspAddress; - private unsafe ref MemoryPoolState MemoryPoolState => ref *_memoryPools; + private readonly unsafe ref MemoryPoolState MemoryPoolState => ref *_memoryPools; - public unsafe bool HasMemoryPoolState => (IntPtr)_memoryPools != IntPtr.Zero; + public readonly unsafe bool HasMemoryPoolState => (IntPtr)_memoryPools != IntPtr.Zero; /// /// Create an new empty . @@ -55,7 +55,7 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool CpuAddress = cpuAddress, _memoryPools = MemoryPoolState.Null, Size = size, - ForceMappedDspAddress = 0 + ForceMappedDspAddress = 0, }; } } @@ -105,7 +105,7 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool /// Check if the is mapped. /// /// Returns true if the is mapped. - public bool HasMappedMemoryPool() + public readonly bool HasMappedMemoryPool() { return HasMemoryPoolState && MemoryPoolState.IsMapped(); } @@ -115,7 +115,7 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool /// /// If true, mark the as used. /// Returns the DSP address associated to the . - public DspAddress GetReference(bool markUsed) + public readonly DspAddress GetReference(bool markUsed) { if (!HasMappedMemoryPool()) { @@ -130,4 +130,4 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool return MemoryPoolState.Translate(CpuAddress, Size); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/MemoryPool/MemoryPoolState.cs b/src/Ryujinx.Audio/Renderer/Server/MemoryPool/MemoryPoolState.cs index 69466bab5..91bd5dbf5 100644 --- a/src/Ryujinx.Audio/Renderer/Server/MemoryPool/MemoryPoolState.cs +++ b/src/Ryujinx.Audio/Renderer/Server/MemoryPool/MemoryPoolState.cs @@ -26,7 +26,7 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool /// /// located on the DSP side for system use. /// - Dsp + Dsp, } /// @@ -69,7 +69,7 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool CpuAddress = 0, DspAddress = 0, Size = 0, - Location = location + Location = location, }; } @@ -90,7 +90,7 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool /// The . /// The size. /// True if the is contained inside the . - public bool Contains(CpuAddress targetCpuAddress, ulong size) + public readonly bool Contains(CpuAddress targetCpuAddress, ulong size) { if (CpuAddress <= targetCpuAddress && size + targetCpuAddress <= Size + CpuAddress) { @@ -106,7 +106,7 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool /// The . /// The size. /// the target DSP address. - public DspAddress Translate(CpuAddress targetCpuAddress, ulong size) + public readonly DspAddress Translate(CpuAddress targetCpuAddress, ulong size) { if (Contains(targetCpuAddress, size) && IsMapped()) { @@ -122,9 +122,9 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool /// Is the mapped on the DSP? /// /// Returns true if the is mapped on the DSP. - public bool IsMapped() + public readonly bool IsMapped() { return DspAddress != 0; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/MemoryPool/PoolMapper.cs b/src/Ryujinx.Audio/Renderer/Server/MemoryPool/PoolMapper.cs index 4a29ead3e..391b80f8d 100644 --- a/src/Ryujinx.Audio/Renderer/Server/MemoryPool/PoolMapper.cs +++ b/src/Ryujinx.Audio/Renderer/Server/MemoryPool/PoolMapper.cs @@ -40,23 +40,23 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool /// /// unmapping failed. /// - UnmapError = 3 + UnmapError = 3, } /// /// The handle of the process owning the CPU memory manipulated. /// - private uint _processHandle; + private readonly uint _processHandle; /// /// The that will be manipulated. /// - private Memory _memoryPools; + private readonly Memory _memoryPools; /// /// If set to true, this will try to force map memory pool even if their state are considered invalid. /// - private bool _isForceMapEnabled; + private readonly bool _isForceMapEnabled; /// /// Create a new used for system mapping. @@ -125,7 +125,8 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool { return CurrentProcessPseudoHandle; } - else if (memoryPool.Location == MemoryPoolState.LocationType.Dsp) + + if (memoryPool.Location == MemoryPoolState.LocationType.Dsp) { return _processHandle; } @@ -234,13 +235,11 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool return true; } - else - { - errorInfo.ErrorCode = ResultCode.InvalidAddressInfo; - errorInfo.ExtraErrorInfo = addressInfo.CpuAddress; - return _isForceMapEnabled; - } + errorInfo.ErrorCode = ResultCode.InvalidAddressInfo; + errorInfo.ExtraErrorInfo = addressInfo.CpuAddress; + + return _isForceMapEnabled; } /// diff --git a/src/Ryujinx.Audio/Renderer/Server/Mix/MixContext.cs b/src/Ryujinx.Audio/Renderer/Server/Mix/MixContext.cs index cda6f737c..8991ceaf9 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Mix/MixContext.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Mix/MixContext.cs @@ -206,7 +206,7 @@ namespace Ryujinx.Audio.Renderer.Server.Mix { UpdateDistancesFromFinalMix(); - int[] sortedMixesTemp = _sortedMixes.Slice(0, (int)GetCount()).ToArray(); + int[] sortedMixesTemp = _sortedMixes[..(int)GetCount()].ToArray(); Array.Sort(sortedMixesTemp, (a, b) => { @@ -248,12 +248,10 @@ namespace Ryujinx.Audio.Renderer.Server.Mix return isValid; } - else - { - UpdateMixBufferOffset(); - return true; - } + UpdateMixBufferOffset(); + + return true; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Mix/MixState.cs b/src/Ryujinx.Audio/Renderer/Server/Mix/MixState.cs index 146e67811..88ae44831 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Mix/MixState.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Mix/MixState.cs @@ -7,7 +7,6 @@ using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; - using static Ryujinx.Audio.Constants; namespace Ryujinx.Audio.Renderer.Server.Mix @@ -66,7 +65,7 @@ namespace Ryujinx.Audio.Renderer.Server.Mix /// /// The effect processing order storage. /// - private IntPtr _effectProcessingOrderArrayPointer; + private readonly IntPtr _effectProcessingOrderArrayPointer; /// /// The max element count that can be found in the effect processing order storage. @@ -120,7 +119,7 @@ namespace Ryujinx.Audio.Renderer.Server.Mix /// /// The array used to order effects associated to this mix. /// - public Span EffectProcessingOrderArray + public readonly Span EffectProcessingOrderArray { get { @@ -175,7 +174,7 @@ namespace Ryujinx.Audio.Renderer.Server.Mix /// /// Clear the to its default state. /// - public void ClearEffectProcessingOrder() + public readonly void ClearEffectProcessingOrder() { EffectProcessingOrderArray.Fill(-1); } @@ -184,7 +183,7 @@ namespace Ryujinx.Audio.Renderer.Server.Mix /// Return true if the mix has any destinations. /// /// True if the mix has any destinations. - public bool HasAnyDestination() + public readonly bool HasAnyDestination() { return DestinationMixId != UnusedMixId || DestinationSplitterId != UnusedSplitterId; } @@ -310,4 +309,4 @@ namespace Ryujinx.Audio.Renderer.Server.Mix return isDirty; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Performance/IPerformanceDetailEntry.cs b/src/Ryujinx.Audio/Renderer/Server/Performance/IPerformanceDetailEntry.cs index dbe59cb0d..ffabf4676 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Performance/IPerformanceDetailEntry.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Performance/IPerformanceDetailEntry.cs @@ -49,4 +49,4 @@ namespace Ryujinx.Audio.Renderer.Server.Performance /// The type to use. void SetDetailType(PerformanceDetailType detailType); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Performance/IPerformanceEntry.cs b/src/Ryujinx.Audio/Renderer/Server/Performance/IPerformanceEntry.cs index 9888a4cc1..a0178187b 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Performance/IPerformanceEntry.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Performance/IPerformanceEntry.cs @@ -43,4 +43,4 @@ namespace Ryujinx.Audio.Renderer.Server.Performance /// The type to use. void SetEntryType(PerformanceEntryType type); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Performance/IPerformanceHeader.cs b/src/Ryujinx.Audio/Renderer/Server/Performance/IPerformanceHeader.cs index 21876b4b4..deacd8ccc 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Performance/IPerformanceHeader.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Performance/IPerformanceHeader.cs @@ -77,4 +77,4 @@ namespace Ryujinx.Audio.Renderer.Server.Performance /// The total count of detailed entries in this frame. void SetEntryDetailCount(int entryDetailCount); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceDetailVersion1.cs b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceDetailVersion1.cs index 22704c0d1..a4024607c 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceDetailVersion1.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceDetailVersion1.cs @@ -34,22 +34,22 @@ namespace Ryujinx.Audio.Renderer.Server.Performance /// public PerformanceEntryType EntryType; - public int GetProcessingTime() + public readonly int GetProcessingTime() { return ProcessingTime; } - public int GetProcessingTimeOffset() + public readonly int GetProcessingTimeOffset() { return 8; } - public int GetStartTime() + public readonly int GetStartTime() { return StartTime; } - public int GetStartTimeOffset() + public readonly int GetStartTimeOffset() { return 4; } @@ -69,4 +69,4 @@ namespace Ryujinx.Audio.Renderer.Server.Performance NodeId = nodeId; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceDetailVersion2.cs b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceDetailVersion2.cs index 05ecda9b6..f10e2937e 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceDetailVersion2.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceDetailVersion2.cs @@ -34,22 +34,22 @@ namespace Ryujinx.Audio.Renderer.Server.Performance /// public PerformanceEntryType EntryType; - public int GetProcessingTime() + public readonly int GetProcessingTime() { return ProcessingTime; } - public int GetProcessingTimeOffset() + public readonly int GetProcessingTimeOffset() { return 8; } - public int GetStartTime() + public readonly int GetStartTime() { return StartTime; } - public int GetStartTimeOffset() + public readonly int GetStartTimeOffset() { return 4; } @@ -69,4 +69,4 @@ namespace Ryujinx.Audio.Renderer.Server.Performance NodeId = nodeId; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceEntryAddresses.cs b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceEntryAddresses.cs index 1b8d8668a..d24b96a27 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceEntryAddresses.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceEntryAddresses.cs @@ -53,4 +53,4 @@ namespace Ryujinx.Audio.Renderer.Server.Performance BaseMemory.Span[(int)ProcessingTimeOffset / 4] = (int)(endTimeNano / 1000) - BaseMemory.Span[(int)StartTimeOffset / 4]; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceEntryVersion1.cs b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceEntryVersion1.cs index fa2d32164..2c407670f 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceEntryVersion1.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceEntryVersion1.cs @@ -29,22 +29,22 @@ namespace Ryujinx.Audio.Renderer.Server.Performance /// public PerformanceEntryType EntryType; - public int GetProcessingTime() + public readonly int GetProcessingTime() { return ProcessingTime; } - public int GetProcessingTimeOffset() + public readonly int GetProcessingTimeOffset() { return 8; } - public int GetStartTime() + public readonly int GetStartTime() { return StartTime; } - public int GetStartTimeOffset() + public readonly int GetStartTimeOffset() { return 4; } @@ -59,4 +59,4 @@ namespace Ryujinx.Audio.Renderer.Server.Performance NodeId = nodeId; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceEntryVersion2.cs b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceEntryVersion2.cs index 49d4b3ce0..eb96a3141 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceEntryVersion2.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceEntryVersion2.cs @@ -29,22 +29,22 @@ namespace Ryujinx.Audio.Renderer.Server.Performance /// public PerformanceEntryType EntryType; - public int GetProcessingTime() + public readonly int GetProcessingTime() { return ProcessingTime; } - public int GetProcessingTimeOffset() + public readonly int GetProcessingTimeOffset() { return 8; } - public int GetStartTime() + public readonly int GetStartTime() { return StartTime; } - public int GetStartTimeOffset() + public readonly int GetStartTimeOffset() { return 4; } @@ -59,4 +59,4 @@ namespace Ryujinx.Audio.Renderer.Server.Performance NodeId = nodeId; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceFrameHeaderVersion1.cs b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceFrameHeaderVersion1.cs index 5fe6bff06..5aeb703c5 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceFrameHeaderVersion1.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceFrameHeaderVersion1.cs @@ -38,22 +38,22 @@ namespace Ryujinx.Audio.Renderer.Server.Performance /// public uint VoiceDropCount; - public int GetEntryCount() + public readonly int GetEntryCount() { return EntryCount; } - public int GetEntryCountOffset() + public readonly int GetEntryCountOffset() { return 4; } - public int GetEntryDetailCount() + public readonly int GetEntryDetailCount() { return EntryDetailCount; } - public void SetDspRunningBehind(bool isRunningBehind) + public readonly void SetDspRunningBehind(bool isRunningBehind) { // NOTE: Not present in version 1 } @@ -68,7 +68,7 @@ namespace Ryujinx.Audio.Renderer.Server.Performance EntryDetailCount = entryDetailCount; } - public void SetIndex(uint index) + public readonly void SetIndex(uint index) { // NOTE: Not present in version 1 } @@ -83,7 +83,7 @@ namespace Ryujinx.Audio.Renderer.Server.Performance NextOffset = nextOffset; } - public void SetStartRenderingTicks(ulong startTicks) + public readonly void SetStartRenderingTicks(ulong startTicks) { // NOTE: not present in version 1 } @@ -98,4 +98,4 @@ namespace Ryujinx.Audio.Renderer.Server.Performance VoiceDropCount = voiceCount; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceFrameHeaderVersion2.cs b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceFrameHeaderVersion2.cs index a18229686..d6e0ffc8b 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceFrameHeaderVersion2.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceFrameHeaderVersion2.cs @@ -54,17 +54,17 @@ namespace Ryujinx.Audio.Renderer.Server.Performance [MarshalAs(UnmanagedType.I1)] public bool IsDspRunningBehind; - public int GetEntryCount() + public readonly int GetEntryCount() { return EntryCount; } - public int GetEntryCountOffset() + public readonly int GetEntryCountOffset() { return 4; } - public int GetEntryDetailCount() + public readonly int GetEntryDetailCount() { return EntryDetailCount; } @@ -114,4 +114,4 @@ namespace Ryujinx.Audio.Renderer.Server.Performance VoiceDropCount = voiceCount; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceManager.cs b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceManager.cs index f996441c0..0a035916c 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceManager.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceManager.cs @@ -22,11 +22,12 @@ namespace Ryujinx.Audio.Renderer.Server.Performance PerformanceEntryVersion2, PerformanceDetailVersion2>.GetRequiredBufferSizeForPerformanceMetricsPerFrame(ref parameter); } - else if (version == 1) + + if (version == 1) { return (ulong)PerformanceManagerGeneric.GetRequiredBufferSizeForPerformanceMetricsPerFrame(ref parameter); + PerformanceEntryVersion1, + PerformanceDetailVersion1>.GetRequiredBufferSizeForPerformanceMetricsPerFrame(ref parameter); } throw new NotImplementedException($"Unknown Performance metrics data format version {version}"); @@ -90,17 +91,12 @@ namespace Ryujinx.Audio.Renderer.Server.Performance { uint version = behaviourContext.GetPerformanceMetricsDataFormat(); - switch (version) + return version switch { - case 1: - return new PerformanceManagerGeneric(performanceBuffer, - ref parameter); - case 2: - return new PerformanceManagerGeneric(performanceBuffer, - ref parameter); - default: - throw new NotImplementedException($"Unknown Performance metrics data format version {version}"); - } + 1 => new PerformanceManagerGeneric(performanceBuffer, ref parameter), + 2 => new PerformanceManagerGeneric(performanceBuffer, ref parameter), + _ => throw new NotImplementedException($"Unknown Performance metrics data format version {version}"), + }; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceManagerGeneric.cs b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceManagerGeneric.cs index 18e77391d..5a70a1bcf 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceManagerGeneric.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceManagerGeneric.cs @@ -25,20 +25,20 @@ namespace Ryujinx.Audio.Renderer.Server.Performance /// private const int MaxFrameDetailCount = 100; - private Memory _buffer; - private Memory _historyBuffer; + private readonly Memory _buffer; + private readonly Memory _historyBuffer; - private Memory CurrentBuffer => _buffer.Slice(0, _frameSize); - private Memory CurrentBufferData => CurrentBuffer.Slice(Unsafe.SizeOf()); + private Memory CurrentBuffer => _buffer[.._frameSize]; + private Memory CurrentBufferData => CurrentBuffer[Unsafe.SizeOf()..]; private ref THeader CurrentHeader => ref MemoryMarshal.Cast(CurrentBuffer.Span)[0]; - private Span Entries => MemoryMarshal.Cast(CurrentBufferData.Span.Slice(0, GetEntriesSize())); + private Span Entries => MemoryMarshal.Cast(CurrentBufferData.Span[..GetEntriesSize()]); private Span EntriesDetail => MemoryMarshal.Cast(CurrentBufferData.Span.Slice(GetEntriesSize(), GetEntriesDetailSize())); - private int _frameSize; - private int _availableFrameCount; - private int _entryCountPerFrame; + private readonly int _frameSize; + private readonly int _availableFrameCount; + private readonly int _entryCountPerFrame; private int _detailTarget; private int _entryIndex; private int _entryDetailIndex; @@ -56,7 +56,7 @@ namespace Ryujinx.Audio.Renderer.Server.Performance _historyFrameIndex = 0; - _historyBuffer = _buffer.Slice(_frameSize); + _historyBuffer = _buffer[_frameSize..]; SetupNewHeader(); } @@ -130,7 +130,7 @@ namespace Ryujinx.Audio.Renderer.Server.Performance Span inputEntries = GetEntriesFromBuffer(_historyBuffer.Span, _indexHistoryRead); Span inputEntriesDetail = GetEntriesDetailFromBuffer(_historyBuffer.Span, _indexHistoryRead); - Span targetSpan = performanceOutput.Slice(nextOffset); + Span targetSpan = performanceOutput[nextOffset..]; // NOTE: We check for the space for two headers for the final blank header. int requiredSpace = Unsafe.SizeOf() + Unsafe.SizeOf() * inputHeader.GetEntryCount() @@ -146,7 +146,7 @@ namespace Ryujinx.Audio.Renderer.Server.Performance nextOffset += Unsafe.SizeOf(); - Span outputEntries = MemoryMarshal.Cast(performanceOutput.Slice(nextOffset)); + Span outputEntries = MemoryMarshal.Cast(performanceOutput[nextOffset..]); int totalProcessingTime = 0; @@ -168,7 +168,7 @@ namespace Ryujinx.Audio.Renderer.Server.Performance } } - Span outputEntriesDetail = MemoryMarshal.Cast(performanceOutput.Slice(nextOffset)); + Span outputEntriesDetail = MemoryMarshal.Cast(performanceOutput[nextOffset..]); int effectiveEntryDetailCount = 0; @@ -198,7 +198,7 @@ namespace Ryujinx.Audio.Renderer.Server.Performance if (nextOffset < performanceOutput.Length && (performanceOutput.Length - nextOffset) >= Unsafe.SizeOf()) { - ref THeader outputHeader = ref MemoryMarshal.Cast(performanceOutput.Slice(nextOffset))[0]; + ref THeader outputHeader = ref MemoryMarshal.Cast(performanceOutput[nextOffset..])[0]; outputHeader = default; } @@ -208,9 +208,11 @@ namespace Ryujinx.Audio.Renderer.Server.Performance public override bool GetNextEntry(out PerformanceEntryAddresses performanceEntry, PerformanceEntryType entryType, int nodeId) { - performanceEntry = new PerformanceEntryAddresses(); - performanceEntry.BaseMemory = SpanMemoryManager.Cast(CurrentBuffer); - performanceEntry.EntryCountOffset = (uint)CurrentHeader.GetEntryCountOffset(); + performanceEntry = new PerformanceEntryAddresses + { + BaseMemory = SpanMemoryManager.Cast(CurrentBuffer), + EntryCountOffset = (uint)CurrentHeader.GetEntryCountOffset(), + }; uint baseEntryOffset = (uint)(Unsafe.SizeOf() + Unsafe.SizeOf() * _entryIndex); @@ -237,9 +239,11 @@ namespace Ryujinx.Audio.Renderer.Server.Performance return false; } - performanceEntry = new PerformanceEntryAddresses(); - performanceEntry.BaseMemory = SpanMemoryManager.Cast(CurrentBuffer); - performanceEntry.EntryCountOffset = (uint)CurrentHeader.GetEntryCountOffset(); + performanceEntry = new PerformanceEntryAddresses + { + BaseMemory = SpanMemoryManager.Cast(CurrentBuffer), + EntryCountOffset = (uint)CurrentHeader.GetEntryCountOffset(), + }; uint baseEntryOffset = (uint)(Unsafe.SizeOf() + GetEntriesSize() + Unsafe.SizeOf() * _entryDetailIndex); @@ -301,4 +305,4 @@ namespace Ryujinx.Audio.Renderer.Server.Performance } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/RendererSystemContext.cs b/src/Ryujinx.Audio/Renderer/Server/RendererSystemContext.cs index 164567806..090850018 100644 --- a/src/Ryujinx.Audio/Renderer/Server/RendererSystemContext.cs +++ b/src/Ryujinx.Audio/Renderer/Server/RendererSystemContext.cs @@ -45,4 +45,4 @@ namespace Ryujinx.Audio.Renderer.Server /// public Memory DepopBuffer; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Sink/BaseSink.cs b/src/Ryujinx.Audio/Renderer/Server/Sink/BaseSink.cs index f7b639975..d36c5e260 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Sink/BaseSink.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Sink/BaseSink.cs @@ -99,4 +99,4 @@ namespace Ryujinx.Audio.Renderer.Server.Sink errorInfo = new ErrorInfo(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Sink/CircularBufferSink.cs b/src/Ryujinx.Audio/Renderer/Server/Sink/CircularBufferSink.cs index 722d8c4b4..097757988 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Sink/CircularBufferSink.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Sink/CircularBufferSink.cs @@ -106,4 +106,4 @@ namespace Ryujinx.Audio.Renderer.Server.Sink base.CleanUp(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Sink/DeviceSink.cs b/src/Ryujinx.Audio/Renderer/Server/Sink/DeviceSink.cs index de345d3ad..e03fe11d4 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Sink/DeviceSink.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Sink/DeviceSink.cs @@ -72,4 +72,4 @@ namespace Ryujinx.Audio.Renderer.Server.Sink outStatus = new SinkOutStatus(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Sink/SinkContext.cs b/src/Ryujinx.Audio/Renderer/Server/Sink/SinkContext.cs index b57d39908..951984d8c 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Sink/SinkContext.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Sink/SinkContext.cs @@ -53,4 +53,4 @@ namespace Ryujinx.Audio.Renderer.Server.Sink return ref _sinks[id]; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Splitter/SplitterContext.cs b/src/Ryujinx.Audio/Renderer/Server/Splitter/SplitterContext.cs index 91877cdda..e408692ab 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Splitter/SplitterContext.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Splitter/SplitterContext.cs @@ -101,10 +101,8 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter return size; } - else - { - return size; - } + + return size; } /// @@ -164,10 +162,10 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter { ref SplitterState splitter = ref GetState(parameter.Id); - splitter.Update(this, ref parameter, input.Slice(Unsafe.SizeOf())); + splitter.Update(this, ref parameter, input[Unsafe.SizeOf()..]); } - input = input.Slice(0x1C + (int)parameter.DestinationCount * 4); + input = input[(0x1C + parameter.DestinationCount * 4)..]; } } } @@ -194,7 +192,7 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter destination.Update(parameter); } - input = input.Slice(Unsafe.SizeOf()); + input = input[Unsafe.SizeOf()..]; } } } @@ -229,12 +227,10 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter return true; } - else - { - consumedSize = 0; - return false; - } + consumedSize = 0; + + return false; } /// @@ -300,4 +296,4 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Splitter/SplitterDestination.cs b/src/Ryujinx.Audio/Renderer/Server/Splitter/SplitterDestination.cs index c074e4a72..1faf7921f 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Splitter/SplitterDestination.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Splitter/SplitterDestination.cs @@ -65,7 +65,7 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter /// /// Get the of the next element or if not present. /// - public Span Next + public readonly Span Next { get { @@ -138,7 +138,7 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter /// Return true if the is used and has a destination. /// /// True if the is used and has a destination. - public bool IsConfigured() + public readonly bool IsConfigured() { return IsUsed && DestinationId != Constants.UnusedMixId; } @@ -160,8 +160,8 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter /// public void ClearVolumes() { - MixBufferVolume.Fill(0); - PreviousMixBufferVolume.Fill(0); + MixBufferVolume.Clear(); + PreviousMixBufferVolume.Clear(); } /// @@ -190,4 +190,4 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Splitter/SplitterState.cs b/src/Ryujinx.Audio/Renderer/Server/Splitter/SplitterState.cs index 15a0c6ba4..e08ee9ea7 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Splitter/SplitterState.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Splitter/SplitterState.cs @@ -43,7 +43,7 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter /// /// Span to the first element of the linked list of . /// - public Span Destinations + public readonly Span Destinations { get { @@ -63,7 +63,7 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter Id = id; } - public Span GetData(int index) + public readonly Span GetData(int index) { int i = 0; @@ -95,7 +95,7 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter /// Utility function to apply a given to all . /// /// The action to execute on each elements. - private void ForEachDestination(SpanAction action) + private readonly void ForEachDestination(SpanAction action) { Span temp = Destinations; @@ -183,7 +183,7 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter /// /// Update the internal state of this instance. /// - public void UpdateInternalState() + public readonly void UpdateInternalState() { ForEachDestination((destination, _) => destination[0].UpdateInternalState()); } @@ -218,4 +218,4 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/StateUpdater.cs b/src/Ryujinx.Audio/Renderer/Server/StateUpdater.cs index 5cf539c6d..22eebc7cc 100644 --- a/src/Ryujinx.Audio/Renderer/Server/StateUpdater.cs +++ b/src/Ryujinx.Audio/Renderer/Server/StateUpdater.cs @@ -22,15 +22,15 @@ namespace Ryujinx.Audio.Renderer.Server public class StateUpdater { private readonly ReadOnlyMemory _inputOrigin; - private ReadOnlyMemory _outputOrigin; + private readonly ReadOnlyMemory _outputOrigin; private ReadOnlyMemory _input; private Memory _output; - private uint _processHandle; + private readonly uint _processHandle; private BehaviourContext _behaviourContext; private UpdateDataHeader _inputHeader; - private Memory _outputHeader; + private readonly Memory _outputHeader; private ref UpdateDataHeader OutputHeader => ref _outputHeader.Span[0]; @@ -45,9 +45,9 @@ namespace Ryujinx.Audio.Renderer.Server _inputHeader = SpanIOHelper.Read(ref _input); - _outputHeader = SpanMemoryManager.Cast(_output.Slice(0, Unsafe.SizeOf())); + _outputHeader = SpanMemoryManager.Cast(_output[..Unsafe.SizeOf()]); OutputHeader.Initialize(_behaviourContext.UserRevision); - _output = _output.Slice(Unsafe.SizeOf()); + _output = _output[Unsafe.SizeOf()..]; } public ResultCode UpdateBehaviourContext() @@ -72,7 +72,7 @@ namespace Ryujinx.Audio.Renderer.Server public ResultCode UpdateMemoryPools(Span memoryPools) { - PoolMapper mapper = new PoolMapper(_processHandle, _behaviourContext.IsMemoryPoolForceMappingEnabled()); + PoolMapper mapper = new(_processHandle, _behaviourContext.IsMemoryPoolForceMappingEnabled()); if (memoryPools.Length * Unsafe.SizeOf() != _inputHeader.MemoryPoolsSize) { @@ -136,11 +136,11 @@ namespace Ryujinx.Audio.Renderer.Server int initialOutputSize = _output.Length; - ReadOnlySpan parameters = MemoryMarshal.Cast(_input.Slice(0, (int)_inputHeader.VoicesSize).Span); + ReadOnlySpan parameters = MemoryMarshal.Cast(_input[..(int)_inputHeader.VoicesSize].Span); - _input = _input.Slice((int)_inputHeader.VoicesSize); + _input = _input[(int)_inputHeader.VoicesSize..]; - PoolMapper mapper = new PoolMapper(_processHandle, memoryPools, _behaviourContext.IsMemoryPoolForceMappingEnabled()); + PoolMapper mapper = new(_processHandle, memoryPools, _behaviourContext.IsMemoryPoolForceMappingEnabled()); // First make everything not in use. for (int i = 0; i < context.GetCount(); i++) @@ -151,7 +151,7 @@ namespace Ryujinx.Audio.Renderer.Server } Memory[] voiceUpdateStatesArray = ArrayPool>.Shared.Rent(Constants.VoiceChannelCountMax); - + Span> voiceUpdateStates = voiceUpdateStatesArray.AsSpan(0, Constants.VoiceChannelCountMax); // Start processing @@ -218,42 +218,20 @@ namespace Ryujinx.Audio.Renderer.Server { effect.ForceUnmapBuffers(mapper); - switch (parameter.Type) + effect = parameter.Type switch { - case EffectType.Invalid: - effect = new BaseEffect(); - break; - case EffectType.BufferMix: - effect = new BufferMixEffect(); - break; - case EffectType.AuxiliaryBuffer: - effect = new AuxiliaryBufferEffect(); - break; - case EffectType.Delay: - effect = new DelayEffect(); - break; - case EffectType.Reverb: - effect = new ReverbEffect(); - break; - case EffectType.Reverb3d: - effect = new Reverb3dEffect(); - break; - case EffectType.BiquadFilter: - effect = new BiquadFilterEffect(); - break; - case EffectType.Limiter: - effect = new LimiterEffect(); - break; - case EffectType.CaptureBuffer: - effect = new CaptureBufferEffect(); - break; - case EffectType.Compressor: - effect = new CompressorEffect(); - break; - - default: - throw new NotImplementedException($"EffectType {parameter.Type} not implemented!"); - } + EffectType.Invalid => new BaseEffect(), + EffectType.BufferMix => new BufferMixEffect(), + EffectType.AuxiliaryBuffer => new AuxiliaryBufferEffect(), + EffectType.Delay => new DelayEffect(), + EffectType.Reverb => new ReverbEffect(), + EffectType.Reverb3d => new Reverb3dEffect(), + EffectType.BiquadFilter => new BiquadFilterEffect(), + EffectType.Limiter => new LimiterEffect(), + EffectType.CaptureBuffer => new CaptureBufferEffect(), + EffectType.Compressor => new CompressorEffect(), + _ => throw new NotImplementedException($"EffectType {parameter.Type} not implemented!"), + }; } public ResultCode UpdateEffects(EffectContext context, bool isAudioRendererActive, Memory memoryPools) @@ -262,10 +240,8 @@ namespace Ryujinx.Audio.Renderer.Server { return UpdateEffectsVersion2(context, isAudioRendererActive, memoryPools); } - else - { - return UpdateEffectsVersion1(context, isAudioRendererActive, memoryPools); - } + + return UpdateEffectsVersion1(context, isAudioRendererActive, memoryPools); } public ResultCode UpdateEffectsVersion2(EffectContext context, bool isAudioRendererActive, Memory memoryPools) @@ -277,11 +253,11 @@ namespace Ryujinx.Audio.Renderer.Server int initialOutputSize = _output.Length; - ReadOnlySpan parameters = MemoryMarshal.Cast(_input.Slice(0, (int)_inputHeader.EffectsSize).Span); + ReadOnlySpan parameters = MemoryMarshal.Cast(_input[..(int)_inputHeader.EffectsSize].Span); - _input = _input.Slice((int)_inputHeader.EffectsSize); + _input = _input[(int)_inputHeader.EffectsSize..]; - PoolMapper mapper = new PoolMapper(_processHandle, memoryPools, _behaviourContext.IsMemoryPoolForceMappingEnabled()); + PoolMapper mapper = new(_processHandle, memoryPools, _behaviourContext.IsMemoryPoolForceMappingEnabled()); for (int i = 0; i < context.GetCount(); i++) { @@ -333,11 +309,11 @@ namespace Ryujinx.Audio.Renderer.Server int initialOutputSize = _output.Length; - ReadOnlySpan parameters = MemoryMarshal.Cast(_input.Slice(0, (int)_inputHeader.EffectsSize).Span); + ReadOnlySpan parameters = MemoryMarshal.Cast(_input[..(int)_inputHeader.EffectsSize].Span); - _input = _input.Slice((int)_inputHeader.EffectsSize); + _input = _input[(int)_inputHeader.EffectsSize..]; - PoolMapper mapper = new PoolMapper(_processHandle, memoryPools, _behaviourContext.IsMemoryPoolForceMappingEnabled()); + PoolMapper mapper = new(_processHandle, memoryPools, _behaviourContext.IsMemoryPoolForceMappingEnabled()); for (int i = 0; i < context.GetCount(); i++) { @@ -376,17 +352,15 @@ namespace Ryujinx.Audio.Renderer.Server { if (context.Update(_input.Span, out int consumedSize)) { - _input = _input.Slice(consumedSize); + _input = _input[consumedSize..]; return ResultCode.Success; } - else - { - return ResultCode.InvalidUpdateInfo; - } + + return ResultCode.InvalidUpdateInfo; } - private bool CheckMixParametersValidity(MixContext mixContext, uint mixBufferCount, uint inputMixCount, ReadOnlySpan parameters) + private static bool CheckMixParametersValidity(MixContext mixContext, uint mixBufferCount, uint inputMixCount, ReadOnlySpan parameters) { uint maxMixStateCount = mixContext.GetCount(); uint totalRequiredMixBufferCount = 0; @@ -439,12 +413,12 @@ namespace Ryujinx.Audio.Renderer.Server if (_behaviourContext.IsMixInParameterDirtyOnlyUpdateSupported()) { - _input = _input.Slice(Unsafe.SizeOf()); + _input = _input[Unsafe.SizeOf()..]; } - ReadOnlySpan parameters = MemoryMarshal.Cast(_input.Span.Slice(0, (int)inputMixSize)); + ReadOnlySpan parameters = MemoryMarshal.Cast(_input.Span[..(int)inputMixSize]); - _input = _input.Slice((int)inputMixSize); + _input = _input[(int)inputMixSize..]; if (CheckMixParametersValidity(mixContext, mixBufferCount, mixCount, parameters)) { @@ -506,25 +480,18 @@ namespace Ryujinx.Audio.Renderer.Server { sink.CleanUp(); - switch (parameter.Type) + sink = parameter.Type switch { - case SinkType.Invalid: - sink = new BaseSink(); - break; - case SinkType.CircularBuffer: - sink = new CircularBufferSink(); - break; - case SinkType.Device: - sink = new DeviceSink(); - break; - default: - throw new NotImplementedException($"SinkType {parameter.Type} not implemented!"); - } + SinkType.Invalid => new BaseSink(), + SinkType.CircularBuffer => new CircularBufferSink(), + SinkType.Device => new DeviceSink(), + _ => throw new NotImplementedException($"SinkType {parameter.Type} not implemented!"), + }; } public ResultCode UpdateSinks(SinkContext context, Memory memoryPools) { - PoolMapper mapper = new PoolMapper(_processHandle, memoryPools, _behaviourContext.IsMemoryPoolForceMappingEnabled()); + PoolMapper mapper = new(_processHandle, memoryPools, _behaviourContext.IsMemoryPoolForceMappingEnabled()); if (context.GetCount() * Unsafe.SizeOf() != _inputHeader.SinksSize) { @@ -533,9 +500,9 @@ namespace Ryujinx.Audio.Renderer.Server int initialOutputSize = _output.Length; - ReadOnlySpan parameters = MemoryMarshal.Cast(_input.Slice(0, (int)_inputHeader.SinksSize).Span); + ReadOnlySpan parameters = MemoryMarshal.Cast(_input[..(int)_inputHeader.SinksSize].Span); - _input = _input.Slice((int)_inputHeader.SinksSize); + _input = _input[(int)_inputHeader.SinksSize..]; for (int i = 0; i < context.GetCount(); i++) { @@ -640,4 +607,4 @@ namespace Ryujinx.Audio.Renderer.Server return ResultCode.Success; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Types/AudioRendererExecutionMode.cs b/src/Ryujinx.Audio/Renderer/Server/Types/AudioRendererExecutionMode.cs index 5d82ce0b6..0db61c5e6 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Types/AudioRendererExecutionMode.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Types/AudioRendererExecutionMode.cs @@ -14,6 +14,6 @@ namespace Ryujinx.Audio.Renderer.Server.Types /// Audio renderer operation needs to be done manually via ExecuteAudioRenderer. /// /// This is not supported on the DSP and is as such stubbed. - Manual + Manual, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Types/AudioRendererRenderingDevice.cs b/src/Ryujinx.Audio/Renderer/Server/Types/AudioRendererRenderingDevice.cs index 5ad27b0b1..fd9e231cf 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Types/AudioRendererRenderingDevice.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Types/AudioRendererRenderingDevice.cs @@ -19,6 +19,6 @@ namespace Ryujinx.Audio.Renderer.Server.Types /// /// Only supports . /// - Cpu + Cpu, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Types/PlayState.cs b/src/Ryujinx.Audio/Renderer/Server/Types/PlayState.cs index 25cc34a8f..46aae05ab 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Types/PlayState.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Types/PlayState.cs @@ -34,6 +34,6 @@ namespace Ryujinx.Audio.Renderer.Server.Types /// /// The user can resume to the state. /// - Paused + Paused, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Upsampler/UpsamplerBufferState.cs b/src/Ryujinx.Audio/Renderer/Server/Upsampler/UpsamplerBufferState.cs index a45fa8e5b..a3c442a45 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Upsampler/UpsamplerBufferState.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Upsampler/UpsamplerBufferState.cs @@ -11,4 +11,4 @@ namespace Ryujinx.Audio.Renderer.Server.Upsampler public bool Initialized; public int Phase; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Upsampler/UpsamplerManager.cs b/src/Ryujinx.Audio/Renderer/Server/Upsampler/UpsamplerManager.cs index 0fee00001..dbc2c9b3f 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Upsampler/UpsamplerManager.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Upsampler/UpsamplerManager.cs @@ -11,22 +11,22 @@ namespace Ryujinx.Audio.Renderer.Server.Upsampler /// /// Work buffer for upsampler. /// - private Memory _upSamplerWorkBuffer; + private readonly Memory _upSamplerWorkBuffer; /// /// Global lock of the object. /// - private readonly object Lock = new(); + private readonly object _lock = new(); /// /// The upsamplers instances. /// - private UpsamplerState[] _upsamplers; + private readonly UpsamplerState[] _upsamplers; /// /// The count of upsamplers. /// - private uint _count; + private readonly uint _count; /// /// Create a new . @@ -49,7 +49,7 @@ namespace Ryujinx.Audio.Renderer.Server.Upsampler { int workBufferOffset = 0; - lock (Lock) + lock (_lock) { for (int i = 0; i < _count; i++) { @@ -73,7 +73,7 @@ namespace Ryujinx.Audio.Renderer.Server.Upsampler /// The index of the to free. public void Free(int index) { - lock (Lock) + lock (_lock) { Debug.Assert(_upsamplers[index] != null); @@ -81,4 +81,4 @@ namespace Ryujinx.Audio.Renderer.Server.Upsampler } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Upsampler/UpsamplerState.cs b/src/Ryujinx.Audio/Renderer/Server/Upsampler/UpsamplerState.cs index e508f35b4..39a58c91a 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Upsampler/UpsamplerState.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Upsampler/UpsamplerState.cs @@ -20,12 +20,12 @@ namespace Ryujinx.Audio.Renderer.Server.Upsampler /// /// The index of the . (used to free it) /// - private int _index; + private readonly int _index; /// /// The . /// - private UpsamplerManager _manager; + private readonly UpsamplerManager _manager; /// /// The source sample count. @@ -65,4 +65,4 @@ namespace Ryujinx.Audio.Renderer.Server.Upsampler _manager.Free(_index); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceChannelResource.cs b/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceChannelResource.cs index 939d92944..e3d5f797d 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceChannelResource.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceChannelResource.cs @@ -37,4 +37,4 @@ namespace Ryujinx.Audio.Renderer.Server.Voice Mix.AsSpan().CopyTo(PreviousMix.AsSpan()); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceContext.cs b/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceContext.cs index 1c57b71be..7ce7143ed 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceContext.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceContext.cs @@ -126,7 +126,7 @@ namespace Ryujinx.Audio.Renderer.Server.Voice _sortedVoices.Span[i] = i; } - int[] sortedVoicesTemp = _sortedVoices.Slice(0, (int)GetCount()).ToArray(); + int[] sortedVoicesTemp = _sortedVoices[..(int)GetCount()].ToArray(); Array.Sort(sortedVoicesTemp, (a, b) => { @@ -146,4 +146,4 @@ namespace Ryujinx.Audio.Renderer.Server.Voice sortedVoicesTemp.AsSpan().CopyTo(_sortedVoices.Span); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceState.cs b/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceState.cs index 0bf53c544..225f7d31b 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceState.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceState.cs @@ -1,5 +1,6 @@ using Ryujinx.Audio.Common; using Ryujinx.Audio.Renderer.Common; +using Ryujinx.Audio.Renderer.Dsp.State; using Ryujinx.Audio.Renderer.Parameter; using Ryujinx.Audio.Renderer.Server.MemoryPool; using Ryujinx.Common.Memory; @@ -9,6 +10,7 @@ using System.Diagnostics; using System.Runtime.InteropServices; using static Ryujinx.Audio.Renderer.Common.BehaviourParameter; using static Ryujinx.Audio.Renderer.Parameter.VoiceInParameter; +using PlayState = Ryujinx.Audio.Renderer.Server.Types.PlayState; namespace Ryujinx.Audio.Renderer.Server.Voice { @@ -65,12 +67,12 @@ namespace Ryujinx.Audio.Renderer.Server.Voice /// /// The current voice . /// - public Types.PlayState PlayState; + public PlayState PlayState; /// /// The previous voice . /// - public Types.PlayState PreviousPlayState; + public PlayState PreviousPlayState; /// /// The priority of the voice. @@ -192,7 +194,7 @@ namespace Ryujinx.Audio.Renderer.Server.Voice DataSourceStateUnmapped = false; BufferInfoUnmapped = false; FlushWaveBufferCount = 0; - PlayState = Types.PlayState.Stopped; + PlayState = PlayState.Stopped; Priority = Constants.VoiceLowestPriority; Id = 0; NodeId = 0; @@ -202,7 +204,7 @@ namespace Ryujinx.Audio.Renderer.Server.Voice Pitch = 0.0f; Volume = 0.0f; PreviousVolume = 0.0f; - BiquadFilters.AsSpan().Fill(new BiquadFilterParameter()); + BiquadFilters.AsSpan().Clear(); WaveBuffersCount = 0; WaveBuffersIndex = 0; MixId = Constants.UnusedMixId; @@ -233,7 +235,7 @@ namespace Ryujinx.Audio.Renderer.Server.Voice /// Check if the voice needs to be skipped. /// /// Returns true if the voice needs to be skipped. - public bool ShouldSkip() + public readonly bool ShouldSkip() { return !InUse || WaveBuffersCount == 0 || DataSourceStateUnmapped || BufferInfoUnmapped || VoiceDropFlag; } @@ -242,7 +244,7 @@ namespace Ryujinx.Audio.Renderer.Server.Voice /// Return true if the mix has any destinations. /// /// True if the mix has any destinations. - public bool HasAnyDestination() + public readonly bool HasAnyDestination() { return MixId != Constants.UnusedMixId || SplitterId != Constants.UnusedSplitterId; } @@ -252,7 +254,7 @@ namespace Ryujinx.Audio.Renderer.Server.Voice /// /// The user parameter. /// Return true, if the server voice information needs to be updated. - private bool ShouldUpdateParameters(ref VoiceInParameter parameter) + private readonly bool ShouldUpdateParameters(ref VoiceInParameter parameter) { if (DataSourceStateAddressInfo.CpuAddress == parameter.DataSourceStateAddress) { @@ -338,31 +340,31 @@ namespace Ryujinx.Audio.Renderer.Server.Voice /// Update the internal play state from user play state. /// /// The target user play state. - public void UpdatePlayState(PlayState userPlayState) + public void UpdatePlayState(Common.PlayState userPlayState) { - Types.PlayState oldServerPlayState = PlayState; + PlayState oldServerPlayState = PlayState; PreviousPlayState = oldServerPlayState; - Types.PlayState newServerPlayState; + PlayState newServerPlayState; switch (userPlayState) { case Common.PlayState.Start: - newServerPlayState = Types.PlayState.Started; + newServerPlayState = PlayState.Started; break; case Common.PlayState.Stop: - if (oldServerPlayState == Types.PlayState.Stopped) + if (oldServerPlayState == PlayState.Stopped) { return; } - newServerPlayState = Types.PlayState.Stopping; + newServerPlayState = PlayState.Stopping; break; case Common.PlayState.Pause: - newServerPlayState = Types.PlayState.Paused; + newServerPlayState = PlayState.Paused; break; default: @@ -434,7 +436,7 @@ namespace Ryujinx.Audio.Renderer.Server.Voice for (int i = 0; i < parameter.ChannelCount; i++) { - voiceUpdateStates[i].Span[0].IsWaveBufferValid.Fill(false); + voiceUpdateStates[i].Span[0].IsWaveBufferValid.Clear(); } } @@ -530,7 +532,7 @@ namespace Ryujinx.Audio.Renderer.Server.Voice Memory dspSharedState = context.GetUpdateStateForDsp(channelResourceId); - MemoryMarshal.Cast(dspSharedState.Span).Fill(0); + MemoryMarshal.Cast(dspSharedState.Span).Clear(); voiceChannelResource.UpdateState(); } @@ -579,7 +581,7 @@ namespace Ryujinx.Audio.Renderer.Server.Voice switch (PlayState) { - case Types.PlayState.Started: + case PlayState.Started: for (int i = 0; i < WaveBuffers.Length; i++) { ref WaveBuffer wavebuffer = ref WaveBuffers[i]; @@ -611,7 +613,7 @@ namespace Ryujinx.Audio.Renderer.Server.Voice return false; - case Types.PlayState.Stopping: + case PlayState.Stopping: for (int i = 0; i < WaveBuffers.Length; i++) { ref WaveBuffer wavebuffer = ref WaveBuffers[i]; @@ -638,18 +640,18 @@ namespace Ryujinx.Audio.Renderer.Server.Voice voiceUpdateState.Offset = 0; voiceUpdateState.PlayedSampleCount = 0; - voiceUpdateState.Pitch.AsSpan().Fill(0); + voiceUpdateState.Pitch.AsSpan().Clear(); voiceUpdateState.Fraction = 0; - voiceUpdateState.LoopContext = new Dsp.State.AdpcmLoopContext(); + voiceUpdateState.LoopContext = new AdpcmLoopContext(); } - PlayState = Types.PlayState.Stopped; - WasPlaying = PreviousPlayState == Types.PlayState.Started; + PlayState = PlayState.Stopped; + WasPlaying = PreviousPlayState == PlayState.Started; return WasPlaying; - case Types.PlayState.Stopped: - case Types.PlayState.Paused: + case PlayState.Stopped: + case PlayState.Paused: foreach (ref WaveBuffer wavebuffer in WaveBuffers.AsSpan()) { wavebuffer.BufferAddressInfo.GetReference(true); @@ -664,7 +666,7 @@ namespace Ryujinx.Audio.Renderer.Server.Voice } } - WasPlaying = PreviousPlayState == Types.PlayState.Started; + WasPlaying = PreviousPlayState == PlayState.Started; return WasPlaying; default: @@ -696,4 +698,4 @@ namespace Ryujinx.Audio.Renderer.Server.Voice return UpdateParametersForCommandGeneration(voiceUpdateStates); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Voice/WaveBuffer.cs b/src/Ryujinx.Audio/Renderer/Server/Voice/WaveBuffer.cs index 4bf7dd280..a9946ba44 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Voice/WaveBuffer.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Voice/WaveBuffer.cs @@ -71,10 +71,11 @@ namespace Ryujinx.Audio.Renderer.Server.Voice /// A new for use by the . public Common.WaveBuffer ToCommon(int version) { - Common.WaveBuffer waveBuffer = new Common.WaveBuffer(); - - waveBuffer.Buffer = BufferAddressInfo.GetReference(true); - waveBuffer.BufferSize = (uint)BufferAddressInfo.Size; + Common.WaveBuffer waveBuffer = new() + { + Buffer = BufferAddressInfo.GetReference(true), + BufferSize = (uint)BufferAddressInfo.Size, + }; if (ContextAddressInfo.CpuAddress != 0) { @@ -101,4 +102,4 @@ namespace Ryujinx.Audio.Renderer.Server.Voice return waveBuffer; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Utils/AudioProcessorMemoryManager.cs b/src/Ryujinx.Audio/Renderer/Utils/AudioProcessorMemoryManager.cs index 973f0672a..8ebf20340 100644 --- a/src/Ryujinx.Audio/Renderer/Utils/AudioProcessorMemoryManager.cs +++ b/src/Ryujinx.Audio/Renderer/Utils/AudioProcessorMemoryManager.cs @@ -54,4 +54,4 @@ namespace Ryujinx.Audio.Renderer.Utils { } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Utils/BitArray.cs b/src/Ryujinx.Audio/Renderer/Utils/BitArray.cs index 8b1054771..8fd0baeae 100644 --- a/src/Ryujinx.Audio/Renderer/Utils/BitArray.cs +++ b/src/Ryujinx.Audio/Renderer/Utils/BitArray.cs @@ -11,7 +11,7 @@ namespace Ryujinx.Audio.Renderer.Utils /// /// The backing storage of the . /// - private Memory _storage; + private readonly Memory _storage; /// /// Create a new from . @@ -97,7 +97,7 @@ namespace Ryujinx.Audio.Renderer.Utils [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Reset() { - _storage.Span.Fill(0); + _storage.Span.Clear(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Utils/FileHardwareDevice.cs b/src/Ryujinx.Audio/Renderer/Utils/FileHardwareDevice.cs index d49313ea1..bc2313ccf 100644 --- a/src/Ryujinx.Audio/Renderer/Utils/FileHardwareDevice.cs +++ b/src/Ryujinx.Audio/Renderer/Utils/FileHardwareDevice.cs @@ -2,7 +2,6 @@ using Ryujinx.Audio.Integration; using System; using System.IO; using System.Runtime.InteropServices; -using System.Text; namespace Ryujinx.Audio.Renderer.Utils { @@ -12,8 +11,8 @@ namespace Ryujinx.Audio.Renderer.Utils public class FileHardwareDevice : IHardwareDevice { private FileStream _stream; - private uint _channelCount; - private uint _sampleRate; + private readonly uint _channelCount; + private readonly uint _sampleRate; private const int HeaderSize = 44; @@ -82,6 +81,7 @@ namespace Ryujinx.Audio.Renderer.Utils public void Dispose() { + GC.SuppressFinalize(this); Dispose(true); } @@ -96,4 +96,4 @@ namespace Ryujinx.Audio.Renderer.Utils } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Utils/Mailbox.cs b/src/Ryujinx.Audio/Renderer/Utils/Mailbox.cs index 35c71ae36..26907af91 100644 --- a/src/Ryujinx.Audio/Renderer/Utils/Mailbox.cs +++ b/src/Ryujinx.Audio/Renderer/Utils/Mailbox.cs @@ -9,8 +9,8 @@ namespace Ryujinx.Audio.Renderer.Utils /// The target unmanaged type used public class Mailbox : IDisposable where T : unmanaged { - private BlockingCollection _messageQueue; - private BlockingCollection _responseQueue; + private readonly BlockingCollection _messageQueue; + private readonly BlockingCollection _responseQueue; public Mailbox() { @@ -40,6 +40,7 @@ namespace Ryujinx.Audio.Renderer.Utils public void Dispose() { + GC.SuppressFinalize(this); Dispose(true); } @@ -52,4 +53,4 @@ namespace Ryujinx.Audio.Renderer.Utils } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Utils/Math/Matrix2x2.cs b/src/Ryujinx.Audio/Renderer/Utils/Math/Matrix2x2.cs index 5b513aff3..7a6edab19 100644 --- a/src/Ryujinx.Audio/Renderer/Utils/Math/Matrix2x2.cs +++ b/src/Ryujinx.Audio/Renderer/Utils/Math/Matrix2x2.cs @@ -68,4 +68,4 @@ namespace Ryujinx.Audio.Renderer.Utils.Math return m; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Utils/Math/Matrix6x6.cs b/src/Ryujinx.Audio/Renderer/Utils/Math/Matrix6x6.cs index 415a81fdf..ff0123026 100644 --- a/src/Ryujinx.Audio/Renderer/Utils/Math/Matrix6x6.cs +++ b/src/Ryujinx.Audio/Renderer/Utils/Math/Matrix6x6.cs @@ -94,4 +94,4 @@ namespace Ryujinx.Audio.Renderer.Utils.Math M66 = m66; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Utils/Math/MatrixHelper.cs b/src/Ryujinx.Audio/Renderer/Utils/Math/MatrixHelper.cs index 209a81c46..7b4b7ad1d 100644 --- a/src/Ryujinx.Audio/Renderer/Utils/Math/MatrixHelper.cs +++ b/src/Ryujinx.Audio/Renderer/Utils/Math/MatrixHelper.cs @@ -28,7 +28,7 @@ namespace Ryujinx.Audio.Renderer.Dsp X = value2.M11 * value1.X + value2.M12 * value1.Y + value2.M13 * value1.Z + value2.M14 * value1.W, Y = value2.M21 * value1.X + value2.M22 * value1.Y + value2.M23 * value1.Z + value2.M24 * value1.W, Z = value2.M31 * value1.X + value2.M32 * value1.Y + value2.M33 * value1.Z + value2.M34 * value1.W, - W = value2.M41 * value1.X + value2.M42 * value1.Y + value2.M43 * value1.Z + value2.M44 * value1.W + W = value2.M41 * value1.X + value2.M42 * value1.Y + value2.M43 * value1.Z + value2.M44 * value1.W, }; } @@ -42,4 +42,4 @@ namespace Ryujinx.Audio.Renderer.Dsp }; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Utils/Math/Vector6.cs b/src/Ryujinx.Audio/Renderer/Utils/Math/Vector6.cs index 81bcb6982..303c5e9d0 100644 --- a/src/Ryujinx.Audio/Renderer/Utils/Math/Vector6.cs +++ b/src/Ryujinx.Audio/Renderer/Utils/Math/Vector6.cs @@ -53,4 +53,4 @@ namespace Ryujinx.Audio.Renderer.Utils.Math return left * new Vector6(right); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Utils/SpanIOHelper.cs b/src/Ryujinx.Audio/Renderer/Utils/SpanIOHelper.cs index 103fb6a04..4771ae4dd 100644 --- a/src/Ryujinx.Audio/Renderer/Utils/SpanIOHelper.cs +++ b/src/Ryujinx.Audio/Renderer/Utils/SpanIOHelper.cs @@ -22,12 +22,12 @@ namespace Ryujinx.Audio.Renderer.Utils if (size > backingMemory.Length) { - throw new ArgumentOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(backingMemory), backingMemory.Length, null); } - MemoryMarshal.Write(backingMemory.Span.Slice(0, size), ref data); + MemoryMarshal.Write(backingMemory.Span[..size], ref data); - backingMemory = backingMemory.Slice(size); + backingMemory = backingMemory[size..]; } /// @@ -42,12 +42,12 @@ namespace Ryujinx.Audio.Renderer.Utils if (size > backingMemory.Length) { - throw new ArgumentOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(backingMemory), backingMemory.Length, null); } - MemoryMarshal.Write(backingMemory.Slice(0, size), ref data); + MemoryMarshal.Write(backingMemory[..size], ref data); - backingMemory = backingMemory.Slice(size); + backingMemory = backingMemory[size..]; } /// @@ -62,12 +62,12 @@ namespace Ryujinx.Audio.Renderer.Utils if (size > backingMemory.Length) { - throw new ArgumentOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(backingMemory), backingMemory.Length, null); } - Span result = MemoryMarshal.Cast(backingMemory.Span.Slice(0, size)); + Span result = MemoryMarshal.Cast(backingMemory.Span[..size]); - backingMemory = backingMemory.Slice(size); + backingMemory = backingMemory[size..]; return result; } @@ -84,12 +84,12 @@ namespace Ryujinx.Audio.Renderer.Utils if (size > backingMemory.Length) { - throw new ArgumentOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(backingMemory), backingMemory.Length, null); } - Span result = MemoryMarshal.Cast(backingMemory.Slice(0, size)); + Span result = MemoryMarshal.Cast(backingMemory[..size]); - backingMemory = backingMemory.Slice(size); + backingMemory = backingMemory[size..]; return result; } @@ -106,12 +106,12 @@ namespace Ryujinx.Audio.Renderer.Utils if (size > backingMemory.Length) { - throw new ArgumentOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(backingMemory), backingMemory.Length, null); } - T result = MemoryMarshal.Read(backingMemory.Span.Slice(0, size)); + T result = MemoryMarshal.Read(backingMemory.Span[..size]); - backingMemory = backingMemory.Slice(size); + backingMemory = backingMemory[size..]; return result; } @@ -128,12 +128,12 @@ namespace Ryujinx.Audio.Renderer.Utils if (size > backingMemory.Length) { - throw new ArgumentOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(backingMemory), backingMemory.Length, null); } - T result = MemoryMarshal.Read(backingMemory.Slice(0, size)); + T result = MemoryMarshal.Read(backingMemory[..size]); - backingMemory = backingMemory.Slice(size); + backingMemory = backingMemory[size..]; return result; } @@ -168,4 +168,4 @@ namespace Ryujinx.Audio.Renderer.Utils return ref GetMemory(memory, id, count).Span[0]; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Utils/SpanMemoryManager.cs b/src/Ryujinx.Audio/Renderer/Utils/SpanMemoryManager.cs index 2c48da6aa..b6bafbe0f 100644 --- a/src/Ryujinx.Audio/Renderer/Utils/SpanMemoryManager.cs +++ b/src/Ryujinx.Audio/Renderer/Utils/SpanMemoryManager.cs @@ -19,7 +19,7 @@ namespace Ryujinx.Audio.Renderer.Utils } } - public override Span GetSpan() => new Span(_pointer, _length); + public override Span GetSpan() => new(_pointer, _length); public override MemoryHandle Pin(int elementIndex = 0) { @@ -40,4 +40,4 @@ namespace Ryujinx.Audio.Renderer.Utils return new SpanMemoryManager(MemoryMarshal.Cast(memory.Span)).Memory; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Utils/SplitterHardwareDevice.cs b/src/Ryujinx.Audio/Renderer/Utils/SplitterHardwareDevice.cs index 183960789..32d50e12f 100644 --- a/src/Ryujinx.Audio/Renderer/Utils/SplitterHardwareDevice.cs +++ b/src/Ryujinx.Audio/Renderer/Utils/SplitterHardwareDevice.cs @@ -5,8 +5,8 @@ namespace Ryujinx.Audio.Renderer.Utils { public class SplitterHardwareDevice : IHardwareDevice { - private IHardwareDevice _baseDevice; - private IHardwareDevice _secondaryDevice; + private readonly IHardwareDevice _baseDevice; + private readonly IHardwareDevice _secondaryDevice; public SplitterHardwareDevice(IHardwareDevice baseDevice, IHardwareDevice secondaryDevice) { @@ -43,6 +43,7 @@ namespace Ryujinx.Audio.Renderer.Utils public void Dispose() { + GC.SuppressFinalize(this); Dispose(true); } @@ -55,4 +56,4 @@ namespace Ryujinx.Audio.Renderer.Utils } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/ResultCode.cs b/src/Ryujinx.Audio/ResultCode.cs index 1d05ac65e..eab27c16d 100644 --- a/src/Ryujinx.Audio/ResultCode.cs +++ b/src/Ryujinx.Audio/ResultCode.cs @@ -19,4 +19,4 @@ namespace Ryujinx.Audio UnsupportedOperation = (513 << ErrorCodeShift) | ModuleId, InvalidExecutionContextOperation = (514 << ErrorCodeShift) | ModuleId, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/ClassId.cs b/src/Ryujinx.Graphics.Gpu/ClassId.cs index 4e475a24d..7c1d1e46b 100644 --- a/src/Ryujinx.Graphics.Gpu/ClassId.cs +++ b/src/Ryujinx.Graphics.Gpu/ClassId.cs @@ -10,6 +10,6 @@ namespace Ryujinx.Graphics.Gpu Compute = 0xb1c0, InlineToMemory = 0xa140, Dma = 0xb0b5, - GPFifo = 0xb06f + GPFifo = 0xb06f, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Constants.cs b/src/Ryujinx.Graphics.Gpu/Constants.cs index ff90e61ba..c553d988e 100644 --- a/src/Ryujinx.Graphics.Gpu/Constants.cs +++ b/src/Ryujinx.Graphics.Gpu/Constants.cs @@ -90,4 +90,4 @@ namespace Ryujinx.Graphics.Gpu /// public const ulong MaxUnknownStorageSize = 0x100000; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Compute/ComputeClass.cs b/src/Ryujinx.Graphics.Gpu/Engine/Compute/ComputeClass.cs index d8103ac71..67743de37 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Compute/ComputeClass.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Compute/ComputeClass.cs @@ -1,9 +1,7 @@ using Ryujinx.Graphics.Device; -using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.Gpu.Engine.InlineToMemory; using Ryujinx.Graphics.Gpu.Engine.Threed; using Ryujinx.Graphics.Gpu.Engine.Types; -using Ryujinx.Graphics.Gpu.Image; using Ryujinx.Graphics.Gpu.Shader; using Ryujinx.Graphics.Shader; using System; @@ -39,7 +37,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute { { nameof(ComputeClassState.LaunchDma), new RwCallback(LaunchDma, null) }, { nameof(ComputeClassState.LoadInlineData), new RwCallback(LoadInlineData, null) }, - { nameof(ComputeClassState.SendSignalingPcasB), new RwCallback(SendSignalingPcasB, null) } + { nameof(ComputeClassState.SendSignalingPcasB), new RwCallback(SendSignalingPcasB, null) }, }); _i2mClass = new InlineToMemoryClass(context, channel, initializeState: false); @@ -128,12 +126,12 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute ulong samplerPoolGpuVa = ((ulong)_state.State.SetTexSamplerPoolAOffsetUpper << 32) | _state.State.SetTexSamplerPoolB; ulong texturePoolGpuVa = ((ulong)_state.State.SetTexHeaderPoolAOffsetUpper << 32) | _state.State.SetTexHeaderPoolB; - GpuChannelPoolState poolState = new GpuChannelPoolState( + GpuChannelPoolState poolState = new( texturePoolGpuVa, _state.State.SetTexHeaderPoolCMaximumIndex, _state.State.SetBindlessTextureConstantBufferSlotSelect); - GpuChannelComputeState computeState = new GpuChannelComputeState( + GpuChannelComputeState computeState = new( qmd.CtaThreadDimension0, qmd.CtaThreadDimension1, qmd.CtaThreadDimension2, @@ -189,8 +187,6 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute cs = memoryManager.Physical.ShaderCache.GetComputeShader(_channel, poolState, computeState, shaderGpuVa); _context.Renderer.Pipeline.SetProgram(cs.HostProgram); - - info = cs.Shaders[0].Info; } _channel.BufferManager.SetComputeBufferBindings(cs.Bindings); diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Compute/ComputeClassState.cs b/src/Ryujinx.Graphics.Gpu/Engine/Compute/ComputeClassState.cs index 73dd31b23..0b192ef6b 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Compute/ComputeClassState.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Compute/ComputeClassState.cs @@ -98,24 +98,24 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute /// unsafe struct ComputeClassState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public uint SetObject; - public int SetObjectClassId => (int)(SetObject & 0xFFFF); - public int SetObjectEngineId => (int)((SetObject >> 16) & 0x1F); + public readonly int SetObjectClassId => (int)(SetObject & 0xFFFF); + public readonly int SetObjectEngineId => (int)((SetObject >> 16) & 0x1F); public fixed uint Reserved04[63]; public uint NoOperation; public uint SetNotifyA; - public int SetNotifyAAddressUpper => (int)(SetNotifyA & 0xFF); + public readonly int SetNotifyAAddressUpper => (int)(SetNotifyA & 0xFF); public uint SetNotifyB; public uint Notify; - public NotifyType NotifyType => (NotifyType)(Notify); + public readonly NotifyType NotifyType => (NotifyType)(Notify); public uint WaitForIdle; public fixed uint Reserved114[7]; public uint SetGlobalRenderEnableA; - public int SetGlobalRenderEnableAOffsetUpper => (int)(SetGlobalRenderEnableA & 0xFF); + public readonly int SetGlobalRenderEnableAOffsetUpper => (int)(SetGlobalRenderEnableA & 0xFF); public uint SetGlobalRenderEnableB; public uint SetGlobalRenderEnableC; - public int SetGlobalRenderEnableCMode => (int)(SetGlobalRenderEnableC & 0x7); + public readonly int SetGlobalRenderEnableCMode => (int)(SetGlobalRenderEnableC & 0x7); public uint SendGoIdle; public uint PmTrigger; public uint PmTriggerWfi; @@ -126,34 +126,34 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute public uint LineLengthIn; public uint LineCount; public uint OffsetOutUpper; - public int OffsetOutUpperValue => (int)(OffsetOutUpper & 0xFF); + public readonly int OffsetOutUpperValue => (int)(OffsetOutUpper & 0xFF); public uint OffsetOut; public uint PitchOut; public uint SetDstBlockSize; - public SetDstBlockSizeWidth SetDstBlockSizeWidth => (SetDstBlockSizeWidth)(SetDstBlockSize & 0xF); - public SetDstBlockSizeHeight SetDstBlockSizeHeight => (SetDstBlockSizeHeight)((SetDstBlockSize >> 4) & 0xF); - public SetDstBlockSizeDepth SetDstBlockSizeDepth => (SetDstBlockSizeDepth)((SetDstBlockSize >> 8) & 0xF); + public readonly SetDstBlockSizeWidth SetDstBlockSizeWidth => (SetDstBlockSizeWidth)(SetDstBlockSize & 0xF); + public readonly SetDstBlockSizeHeight SetDstBlockSizeHeight => (SetDstBlockSizeHeight)((SetDstBlockSize >> 4) & 0xF); + public readonly SetDstBlockSizeDepth SetDstBlockSizeDepth => (SetDstBlockSizeDepth)((SetDstBlockSize >> 8) & 0xF); public uint SetDstWidth; public uint SetDstHeight; public uint SetDstDepth; public uint SetDstLayer; public uint SetDstOriginBytesX; - public int SetDstOriginBytesXV => (int)(SetDstOriginBytesX & 0xFFFFF); + public readonly int SetDstOriginBytesXV => (int)(SetDstOriginBytesX & 0xFFFFF); public uint SetDstOriginSamplesY; - public int SetDstOriginSamplesYV => (int)(SetDstOriginSamplesY & 0xFFFF); + public readonly int SetDstOriginSamplesYV => (int)(SetDstOriginSamplesY & 0xFFFF); public uint LaunchDma; - public LaunchDmaDstMemoryLayout LaunchDmaDstMemoryLayout => (LaunchDmaDstMemoryLayout)(LaunchDma & 0x1); - public LaunchDmaCompletionType LaunchDmaCompletionType => (LaunchDmaCompletionType)((LaunchDma >> 4) & 0x3); - public LaunchDmaInterruptType LaunchDmaInterruptType => (LaunchDmaInterruptType)((LaunchDma >> 8) & 0x3); - public LaunchDmaSemaphoreStructSize LaunchDmaSemaphoreStructSize => (LaunchDmaSemaphoreStructSize)((LaunchDma >> 12) & 0x1); - public bool LaunchDmaReductionEnable => (LaunchDma & 0x2) != 0; - public LaunchDmaReductionOp LaunchDmaReductionOp => (LaunchDmaReductionOp)((LaunchDma >> 13) & 0x7); - public LaunchDmaReductionFormat LaunchDmaReductionFormat => (LaunchDmaReductionFormat)((LaunchDma >> 2) & 0x3); - public bool LaunchDmaSysmembarDisable => (LaunchDma & 0x40) != 0; + public readonly LaunchDmaDstMemoryLayout LaunchDmaDstMemoryLayout => (LaunchDmaDstMemoryLayout)(LaunchDma & 0x1); + public readonly LaunchDmaCompletionType LaunchDmaCompletionType => (LaunchDmaCompletionType)((LaunchDma >> 4) & 0x3); + public readonly LaunchDmaInterruptType LaunchDmaInterruptType => (LaunchDmaInterruptType)((LaunchDma >> 8) & 0x3); + public readonly LaunchDmaSemaphoreStructSize LaunchDmaSemaphoreStructSize => (LaunchDmaSemaphoreStructSize)((LaunchDma >> 12) & 0x1); + public readonly bool LaunchDmaReductionEnable => (LaunchDma & 0x2) != 0; + public readonly LaunchDmaReductionOp LaunchDmaReductionOp => (LaunchDmaReductionOp)((LaunchDma >> 13) & 0x7); + public readonly LaunchDmaReductionFormat LaunchDmaReductionFormat => (LaunchDmaReductionFormat)((LaunchDma >> 2) & 0x3); + public readonly bool LaunchDmaSysmembarDisable => (LaunchDma & 0x40) != 0; public uint LoadInlineData; public fixed uint Reserved1B8[9]; public uint SetI2mSemaphoreA; - public int SetI2mSemaphoreAOffsetUpper => (int)(SetI2mSemaphoreA & 0xFF); + public readonly int SetI2mSemaphoreAOffsetUpper => (int)(SetI2mSemaphoreA & 0xFF); public uint SetI2mSemaphoreB; public uint SetI2mSemaphoreC; public fixed uint Reserved1E8[2]; @@ -162,20 +162,20 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute public uint SetI2mSpareNoop02; public uint SetI2mSpareNoop03; public uint SetValidSpanOverflowAreaA; - public int SetValidSpanOverflowAreaAAddressUpper => (int)(SetValidSpanOverflowAreaA & 0xFF); + public readonly int SetValidSpanOverflowAreaAAddressUpper => (int)(SetValidSpanOverflowAreaA & 0xFF); public uint SetValidSpanOverflowAreaB; public uint SetValidSpanOverflowAreaC; public uint SetCoalesceWaitingPeriodUnit; public uint PerfmonTransfer; public uint SetShaderSharedMemoryWindow; public uint SetSelectMaxwellTextureHeaders; - public bool SetSelectMaxwellTextureHeadersV => (SetSelectMaxwellTextureHeaders & 0x1) != 0; + public readonly bool SetSelectMaxwellTextureHeadersV => (SetSelectMaxwellTextureHeaders & 0x1) != 0; public uint InvalidateShaderCaches; - public bool InvalidateShaderCachesInstruction => (InvalidateShaderCaches & 0x1) != 0; - public bool InvalidateShaderCachesData => (InvalidateShaderCaches & 0x10) != 0; - public bool InvalidateShaderCachesConstant => (InvalidateShaderCaches & 0x1000) != 0; - public bool InvalidateShaderCachesLocks => (InvalidateShaderCaches & 0x2) != 0; - public bool InvalidateShaderCachesFlushData => (InvalidateShaderCaches & 0x4) != 0; + public readonly bool InvalidateShaderCachesInstruction => (InvalidateShaderCaches & 0x1) != 0; + public readonly bool InvalidateShaderCachesData => (InvalidateShaderCaches & 0x10) != 0; + public readonly bool InvalidateShaderCachesConstant => (InvalidateShaderCaches & 0x1000) != 0; + public readonly bool InvalidateShaderCachesLocks => (InvalidateShaderCaches & 0x2) != 0; + public readonly bool InvalidateShaderCachesFlushData => (InvalidateShaderCaches & 0x4) != 0; public uint SetReservedSwMethod00; public uint SetReservedSwMethod01; public uint SetReservedSwMethod02; @@ -185,13 +185,13 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute public uint SetReservedSwMethod06; public uint SetReservedSwMethod07; public uint SetCwdControl; - public SetCwdControlSmSelection SetCwdControlSmSelection => (SetCwdControlSmSelection)(SetCwdControl & 0x1); + public readonly SetCwdControlSmSelection SetCwdControlSmSelection => (SetCwdControlSmSelection)(SetCwdControl & 0x1); public uint InvalidateTextureHeaderCacheNoWfi; - public InvalidateCacheLines InvalidateTextureHeaderCacheNoWfiLines => (InvalidateCacheLines)(InvalidateTextureHeaderCacheNoWfi & 0x1); - public int InvalidateTextureHeaderCacheNoWfiTag => (int)((InvalidateTextureHeaderCacheNoWfi >> 4) & 0x3FFFFF); + public readonly InvalidateCacheLines InvalidateTextureHeaderCacheNoWfiLines => (InvalidateCacheLines)(InvalidateTextureHeaderCacheNoWfi & 0x1); + public readonly int InvalidateTextureHeaderCacheNoWfiTag => (int)((InvalidateTextureHeaderCacheNoWfi >> 4) & 0x3FFFFF); public uint SetCwdRefCounter; - public int SetCwdRefCounterSelect => (int)(SetCwdRefCounter & 0x3F); - public int SetCwdRefCounterValue => (int)((SetCwdRefCounter >> 8) & 0xFFFF); + public readonly int SetCwdRefCounterSelect => (int)(SetCwdRefCounter & 0x3F); + public readonly int SetCwdRefCounterValue => (int)((SetCwdRefCounter >> 8) & 0xFFFF); public uint SetReservedSwMethod08; public uint SetReservedSwMethod09; public uint SetReservedSwMethod10; @@ -201,59 +201,59 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute public uint SetReservedSwMethod14; public uint SetReservedSwMethod15; public uint SetGwcScgType; - public SetGwcScgTypeScgType SetGwcScgTypeScgType => (SetGwcScgTypeScgType)(SetGwcScgType & 0x1); + public readonly SetGwcScgTypeScgType SetGwcScgTypeScgType => (SetGwcScgTypeScgType)(SetGwcScgType & 0x1); public uint SetScgControl; - public int SetScgControlCompute1MaxSmCount => (int)(SetScgControl & 0x1FF); + public readonly int SetScgControlCompute1MaxSmCount => (int)(SetScgControl & 0x1FF); public uint InvalidateConstantBufferCacheA; - public int InvalidateConstantBufferCacheAAddressUpper => (int)(InvalidateConstantBufferCacheA & 0xFF); + public readonly int InvalidateConstantBufferCacheAAddressUpper => (int)(InvalidateConstantBufferCacheA & 0xFF); public uint InvalidateConstantBufferCacheB; public uint InvalidateConstantBufferCacheC; - public int InvalidateConstantBufferCacheCByteCount => (int)(InvalidateConstantBufferCacheC & 0x1FFFF); - public bool InvalidateConstantBufferCacheCThruL2 => (InvalidateConstantBufferCacheC & 0x80000000) != 0; + public readonly int InvalidateConstantBufferCacheCByteCount => (int)(InvalidateConstantBufferCacheC & 0x1FFFF); + public readonly bool InvalidateConstantBufferCacheCThruL2 => (InvalidateConstantBufferCacheC & 0x80000000) != 0; public uint SetComputeClassVersion; - public int SetComputeClassVersionCurrent => (int)(SetComputeClassVersion & 0xFFFF); - public int SetComputeClassVersionOldestSupported => (int)((SetComputeClassVersion >> 16) & 0xFFFF); + public readonly int SetComputeClassVersionCurrent => (int)(SetComputeClassVersion & 0xFFFF); + public readonly int SetComputeClassVersionOldestSupported => (int)((SetComputeClassVersion >> 16) & 0xFFFF); public uint CheckComputeClassVersion; - public int CheckComputeClassVersionCurrent => (int)(CheckComputeClassVersion & 0xFFFF); - public int CheckComputeClassVersionOldestSupported => (int)((CheckComputeClassVersion >> 16) & 0xFFFF); + public readonly int CheckComputeClassVersionCurrent => (int)(CheckComputeClassVersion & 0xFFFF); + public readonly int CheckComputeClassVersionOldestSupported => (int)((CheckComputeClassVersion >> 16) & 0xFFFF); public uint SetQmdVersion; - public int SetQmdVersionCurrent => (int)(SetQmdVersion & 0xFFFF); - public int SetQmdVersionOldestSupported => (int)((SetQmdVersion >> 16) & 0xFFFF); + public readonly int SetQmdVersionCurrent => (int)(SetQmdVersion & 0xFFFF); + public readonly int SetQmdVersionOldestSupported => (int)((SetQmdVersion >> 16) & 0xFFFF); public uint SetWfiConfig; - public bool SetWfiConfigEnableScgTypeWfi => (SetWfiConfig & 0x1) != 0; + public readonly bool SetWfiConfigEnableScgTypeWfi => (SetWfiConfig & 0x1) != 0; public uint CheckQmdVersion; - public int CheckQmdVersionCurrent => (int)(CheckQmdVersion & 0xFFFF); - public int CheckQmdVersionOldestSupported => (int)((CheckQmdVersion >> 16) & 0xFFFF); + public readonly int CheckQmdVersionCurrent => (int)(CheckQmdVersion & 0xFFFF); + public readonly int CheckQmdVersionOldestSupported => (int)((CheckQmdVersion >> 16) & 0xFFFF); public uint WaitForIdleScgType; public uint InvalidateSkedCaches; - public bool InvalidateSkedCachesV => (InvalidateSkedCaches & 0x1) != 0; + public readonly bool InvalidateSkedCachesV => (InvalidateSkedCaches & 0x1) != 0; public uint SetScgRenderEnableControl; - public bool SetScgRenderEnableControlCompute1UsesRenderEnable => (SetScgRenderEnableControl & 0x1) != 0; + public readonly bool SetScgRenderEnableControlCompute1UsesRenderEnable => (SetScgRenderEnableControl & 0x1) != 0; public fixed uint Reserved2A0[4]; public uint SetCwdSlotCount; - public int SetCwdSlotCountV => (int)(SetCwdSlotCount & 0xFF); + public readonly int SetCwdSlotCountV => (int)(SetCwdSlotCount & 0xFF); public uint SendPcasA; public uint SendPcasB; - public int SendPcasBFrom => (int)(SendPcasB & 0xFFFFFF); - public int SendPcasBDelta => (int)((SendPcasB >> 24) & 0xFF); + public readonly int SendPcasBFrom => (int)(SendPcasB & 0xFFFFFF); + public readonly int SendPcasBDelta => (int)((SendPcasB >> 24) & 0xFF); public uint SendSignalingPcasB; - public bool SendSignalingPcasBInvalidate => (SendSignalingPcasB & 0x1) != 0; - public bool SendSignalingPcasBSchedule => (SendSignalingPcasB & 0x2) != 0; + public readonly bool SendSignalingPcasBInvalidate => (SendSignalingPcasB & 0x1) != 0; + public readonly bool SendSignalingPcasBSchedule => (SendSignalingPcasB & 0x2) != 0; public fixed uint Reserved2C0[9]; public uint SetShaderLocalMemoryNonThrottledA; - public int SetShaderLocalMemoryNonThrottledASizeUpper => (int)(SetShaderLocalMemoryNonThrottledA & 0xFF); + public readonly int SetShaderLocalMemoryNonThrottledASizeUpper => (int)(SetShaderLocalMemoryNonThrottledA & 0xFF); public uint SetShaderLocalMemoryNonThrottledB; public uint SetShaderLocalMemoryNonThrottledC; - public int SetShaderLocalMemoryNonThrottledCMaxSmCount => (int)(SetShaderLocalMemoryNonThrottledC & 0x1FF); + public readonly int SetShaderLocalMemoryNonThrottledCMaxSmCount => (int)(SetShaderLocalMemoryNonThrottledC & 0x1FF); public uint SetShaderLocalMemoryThrottledA; - public int SetShaderLocalMemoryThrottledASizeUpper => (int)(SetShaderLocalMemoryThrottledA & 0xFF); + public readonly int SetShaderLocalMemoryThrottledASizeUpper => (int)(SetShaderLocalMemoryThrottledA & 0xFF); public uint SetShaderLocalMemoryThrottledB; public uint SetShaderLocalMemoryThrottledC; - public int SetShaderLocalMemoryThrottledCMaxSmCount => (int)(SetShaderLocalMemoryThrottledC & 0x1FF); + public readonly int SetShaderLocalMemoryThrottledCMaxSmCount => (int)(SetShaderLocalMemoryThrottledC & 0x1FF); public fixed uint Reserved2FC[5]; public uint SetSpaVersion; - public int SetSpaVersionMinor => (int)(SetSpaVersion & 0xFF); - public int SetSpaVersionMajor => (int)((SetSpaVersion >> 8) & 0xFF); + public readonly int SetSpaVersionMinor => (int)(SetSpaVersion & 0xFF); + public readonly int SetSpaVersionMajor => (int)((SetSpaVersion >> 8) & 0xFF); public fixed uint Reserved314[123]; public uint SetFalcon00; public uint SetFalcon01; @@ -291,14 +291,14 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute public uint SetShaderLocalMemoryWindow; public fixed uint Reserved780[4]; public uint SetShaderLocalMemoryA; - public int SetShaderLocalMemoryAAddressUpper => (int)(SetShaderLocalMemoryA & 0xFF); + public readonly int SetShaderLocalMemoryAAddressUpper => (int)(SetShaderLocalMemoryA & 0xFF); public uint SetShaderLocalMemoryB; public fixed uint Reserved798[383]; public uint SetShaderCacheControl; - public bool SetShaderCacheControlIcachePrefetchEnable => (SetShaderCacheControl & 0x1) != 0; + public readonly bool SetShaderCacheControlIcachePrefetchEnable => (SetShaderCacheControl & 0x1) != 0; public fixed uint ReservedD98[19]; public uint SetSmTimeoutInterval; - public int SetSmTimeoutIntervalCounterBit => (int)(SetSmTimeoutInterval & 0x3F); + public readonly int SetSmTimeoutIntervalCounterBit => (int)(SetSmTimeoutInterval & 0x3F); public fixed uint ReservedDE8[87]; public uint SetSpareNoop12; public uint SetSpareNoop13; @@ -319,62 +319,62 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute public uint SetSpareNoop11; public fixed uint Reserved1070[103]; public uint InvalidateSamplerCacheAll; - public bool InvalidateSamplerCacheAllV => (InvalidateSamplerCacheAll & 0x1) != 0; + public readonly bool InvalidateSamplerCacheAllV => (InvalidateSamplerCacheAll & 0x1) != 0; public uint InvalidateTextureHeaderCacheAll; - public bool InvalidateTextureHeaderCacheAllV => (InvalidateTextureHeaderCacheAll & 0x1) != 0; + public readonly bool InvalidateTextureHeaderCacheAllV => (InvalidateTextureHeaderCacheAll & 0x1) != 0; public fixed uint Reserved1214[29]; public uint InvalidateTextureDataCacheNoWfi; - public InvalidateCacheLines InvalidateTextureDataCacheNoWfiLines => (InvalidateCacheLines)(InvalidateTextureDataCacheNoWfi & 0x1); - public int InvalidateTextureDataCacheNoWfiTag => (int)((InvalidateTextureDataCacheNoWfi >> 4) & 0x3FFFFF); + public readonly InvalidateCacheLines InvalidateTextureDataCacheNoWfiLines => (InvalidateCacheLines)(InvalidateTextureDataCacheNoWfi & 0x1); + public readonly int InvalidateTextureDataCacheNoWfiTag => (int)((InvalidateTextureDataCacheNoWfi >> 4) & 0x3FFFFF); public fixed uint Reserved128C[7]; public uint ActivatePerfSettingsForComputeContext; - public bool ActivatePerfSettingsForComputeContextAll => (ActivatePerfSettingsForComputeContext & 0x1) != 0; + public readonly bool ActivatePerfSettingsForComputeContextAll => (ActivatePerfSettingsForComputeContext & 0x1) != 0; public fixed uint Reserved12AC[33]; public uint InvalidateSamplerCache; - public InvalidateCacheLines InvalidateSamplerCacheLines => (InvalidateCacheLines)(InvalidateSamplerCache & 0x1); - public int InvalidateSamplerCacheTag => (int)((InvalidateSamplerCache >> 4) & 0x3FFFFF); + public readonly InvalidateCacheLines InvalidateSamplerCacheLines => (InvalidateCacheLines)(InvalidateSamplerCache & 0x1); + public readonly int InvalidateSamplerCacheTag => (int)((InvalidateSamplerCache >> 4) & 0x3FFFFF); public uint InvalidateTextureHeaderCache; - public InvalidateCacheLines InvalidateTextureHeaderCacheLines => (InvalidateCacheLines)(InvalidateTextureHeaderCache & 0x1); - public int InvalidateTextureHeaderCacheTag => (int)((InvalidateTextureHeaderCache >> 4) & 0x3FFFFF); + public readonly InvalidateCacheLines InvalidateTextureHeaderCacheLines => (InvalidateCacheLines)(InvalidateTextureHeaderCache & 0x1); + public readonly int InvalidateTextureHeaderCacheTag => (int)((InvalidateTextureHeaderCache >> 4) & 0x3FFFFF); public uint InvalidateTextureDataCache; - public InvalidateCacheLines InvalidateTextureDataCacheLines => (InvalidateCacheLines)(InvalidateTextureDataCache & 0x1); - public int InvalidateTextureDataCacheTag => (int)((InvalidateTextureDataCache >> 4) & 0x3FFFFF); + public readonly InvalidateCacheLines InvalidateTextureDataCacheLines => (InvalidateCacheLines)(InvalidateTextureDataCache & 0x1); + public readonly int InvalidateTextureDataCacheTag => (int)((InvalidateTextureDataCache >> 4) & 0x3FFFFF); public fixed uint Reserved133C[58]; public uint InvalidateSamplerCacheNoWfi; - public InvalidateCacheLines InvalidateSamplerCacheNoWfiLines => (InvalidateCacheLines)(InvalidateSamplerCacheNoWfi & 0x1); - public int InvalidateSamplerCacheNoWfiTag => (int)((InvalidateSamplerCacheNoWfi >> 4) & 0x3FFFFF); + public readonly InvalidateCacheLines InvalidateSamplerCacheNoWfiLines => (InvalidateCacheLines)(InvalidateSamplerCacheNoWfi & 0x1); + public readonly int InvalidateSamplerCacheNoWfiTag => (int)((InvalidateSamplerCacheNoWfi >> 4) & 0x3FFFFF); public fixed uint Reserved1428[64]; public uint SetShaderExceptions; - public bool SetShaderExceptionsEnable => (SetShaderExceptions & 0x1) != 0; + public readonly bool SetShaderExceptionsEnable => (SetShaderExceptions & 0x1) != 0; public fixed uint Reserved152C[9]; public uint SetRenderEnableA; - public int SetRenderEnableAOffsetUpper => (int)(SetRenderEnableA & 0xFF); + public readonly int SetRenderEnableAOffsetUpper => (int)(SetRenderEnableA & 0xFF); public uint SetRenderEnableB; public uint SetRenderEnableC; - public int SetRenderEnableCMode => (int)(SetRenderEnableC & 0x7); + public readonly int SetRenderEnableCMode => (int)(SetRenderEnableC & 0x7); public uint SetTexSamplerPoolA; - public int SetTexSamplerPoolAOffsetUpper => (int)(SetTexSamplerPoolA & 0xFF); + public readonly int SetTexSamplerPoolAOffsetUpper => (int)(SetTexSamplerPoolA & 0xFF); public uint SetTexSamplerPoolB; public uint SetTexSamplerPoolC; - public int SetTexSamplerPoolCMaximumIndex => (int)(SetTexSamplerPoolC & 0xFFFFF); + public readonly int SetTexSamplerPoolCMaximumIndex => (int)(SetTexSamplerPoolC & 0xFFFFF); public fixed uint Reserved1568[3]; public uint SetTexHeaderPoolA; - public int SetTexHeaderPoolAOffsetUpper => (int)(SetTexHeaderPoolA & 0xFF); + public readonly int SetTexHeaderPoolAOffsetUpper => (int)(SetTexHeaderPoolA & 0xFF); public uint SetTexHeaderPoolB; public uint SetTexHeaderPoolC; - public int SetTexHeaderPoolCMaximumIndex => (int)(SetTexHeaderPoolC & 0x3FFFFF); + public readonly int SetTexHeaderPoolCMaximumIndex => (int)(SetTexHeaderPoolC & 0x3FFFFF); public fixed uint Reserved1580[34]; public uint SetProgramRegionA; - public int SetProgramRegionAAddressUpper => (int)(SetProgramRegionA & 0xFF); + public readonly int SetProgramRegionAAddressUpper => (int)(SetProgramRegionA & 0xFF); public uint SetProgramRegionB; public fixed uint Reserved1610[34]; public uint InvalidateShaderCachesNoWfi; - public bool InvalidateShaderCachesNoWfiInstruction => (InvalidateShaderCachesNoWfi & 0x1) != 0; - public bool InvalidateShaderCachesNoWfiGlobalData => (InvalidateShaderCachesNoWfi & 0x10) != 0; - public bool InvalidateShaderCachesNoWfiConstant => (InvalidateShaderCachesNoWfi & 0x1000) != 0; + public readonly bool InvalidateShaderCachesNoWfiInstruction => (InvalidateShaderCachesNoWfi & 0x1) != 0; + public readonly bool InvalidateShaderCachesNoWfiGlobalData => (InvalidateShaderCachesNoWfi & 0x10) != 0; + public readonly bool InvalidateShaderCachesNoWfiConstant => (InvalidateShaderCachesNoWfi & 0x1000) != 0; public fixed uint Reserved169C[170]; public uint SetRenderEnableOverride; - public SetRenderEnableOverrideMode SetRenderEnableOverrideMode => (SetRenderEnableOverrideMode)(SetRenderEnableOverride & 0x3); + public readonly SetRenderEnableOverrideMode SetRenderEnableOverrideMode => (SetRenderEnableOverrideMode)(SetRenderEnableOverride & 0x3); public fixed uint Reserved1948[57]; public uint PipeNop; public uint SetSpare00; @@ -383,20 +383,20 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute public uint SetSpare03; public fixed uint Reserved1A40[48]; public uint SetReportSemaphoreA; - public int SetReportSemaphoreAOffsetUpper => (int)(SetReportSemaphoreA & 0xFF); + public readonly int SetReportSemaphoreAOffsetUpper => (int)(SetReportSemaphoreA & 0xFF); public uint SetReportSemaphoreB; public uint SetReportSemaphoreC; public uint SetReportSemaphoreD; - public SetReportSemaphoreDOperation SetReportSemaphoreDOperation => (SetReportSemaphoreDOperation)(SetReportSemaphoreD & 0x3); - public bool SetReportSemaphoreDAwakenEnable => (SetReportSemaphoreD & 0x100000) != 0; - public SetReportSemaphoreDStructureSize SetReportSemaphoreDStructureSize => (SetReportSemaphoreDStructureSize)((SetReportSemaphoreD >> 28) & 0x1); - public bool SetReportSemaphoreDFlushDisable => (SetReportSemaphoreD & 0x4) != 0; - public bool SetReportSemaphoreDReductionEnable => (SetReportSemaphoreD & 0x8) != 0; - public SetReportSemaphoreDReductionOp SetReportSemaphoreDReductionOp => (SetReportSemaphoreDReductionOp)((SetReportSemaphoreD >> 9) & 0x7); - public SetReportSemaphoreDReductionFormat SetReportSemaphoreDReductionFormat => (SetReportSemaphoreDReductionFormat)((SetReportSemaphoreD >> 17) & 0x3); + public readonly SetReportSemaphoreDOperation SetReportSemaphoreDOperation => (SetReportSemaphoreDOperation)(SetReportSemaphoreD & 0x3); + public readonly bool SetReportSemaphoreDAwakenEnable => (SetReportSemaphoreD & 0x100000) != 0; + public readonly SetReportSemaphoreDStructureSize SetReportSemaphoreDStructureSize => (SetReportSemaphoreDStructureSize)((SetReportSemaphoreD >> 28) & 0x1); + public readonly bool SetReportSemaphoreDFlushDisable => (SetReportSemaphoreD & 0x4) != 0; + public readonly bool SetReportSemaphoreDReductionEnable => (SetReportSemaphoreD & 0x8) != 0; + public readonly SetReportSemaphoreDReductionOp SetReportSemaphoreDReductionOp => (SetReportSemaphoreDReductionOp)((SetReportSemaphoreD >> 9) & 0x7); + public readonly SetReportSemaphoreDReductionFormat SetReportSemaphoreDReductionFormat => (SetReportSemaphoreDReductionFormat)((SetReportSemaphoreD >> 17) & 0x3); public fixed uint Reserved1B10[702]; public uint SetBindlessTexture; - public int SetBindlessTextureConstantBufferSlotSelect => (int)(SetBindlessTexture & 0x7); + public readonly int SetBindlessTextureConstantBufferSlotSelect => (int)(SetBindlessTexture & 0x7); public uint SetTrapHandler; public fixed uint Reserved2610[843]; public Array8 SetShaderPerformanceCounterValueUpper; @@ -423,13 +423,13 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute public bool SetShaderPerformanceCounterControlBWindowed(int i) => (SetShaderPerformanceCounterControlB[i] & 0x8) != 0; public int SetShaderPerformanceCounterControlBFunc(int i) => (int)((SetShaderPerformanceCounterControlB[i] >> 4) & 0xFFFF); public uint SetShaderPerformanceCounterTrapControl; - public int SetShaderPerformanceCounterTrapControlMask => (int)(SetShaderPerformanceCounterTrapControl & 0xFF); + public readonly int SetShaderPerformanceCounterTrapControlMask => (int)(SetShaderPerformanceCounterTrapControl & 0xFF); public uint StartShaderPerformanceCounter; - public int StartShaderPerformanceCounterCounterMask => (int)(StartShaderPerformanceCounter & 0xFF); + public readonly int StartShaderPerformanceCounterCounterMask => (int)(StartShaderPerformanceCounter & 0xFF); public uint StopShaderPerformanceCounter; - public int StopShaderPerformanceCounterCounterMask => (int)(StopShaderPerformanceCounter & 0xFF); + public readonly int StopShaderPerformanceCounterCounterMask => (int)(StopShaderPerformanceCounter & 0xFF); public fixed uint Reserved33E8[6]; - public MmeShadowScratch SetMmeShadowScratch; + public Array256 SetMmeShadowScratch; #pragma warning restore CS0649 } } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Compute/ComputeQmd.cs b/src/Ryujinx.Graphics.Gpu/Engine/Compute/ComputeQmd.cs index 1b20e41c2..4e750ff5d 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Compute/ComputeQmd.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Compute/ComputeQmd.cs @@ -10,7 +10,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute enum DependentQmdType { Queue, - Grid + Grid, } /// @@ -19,7 +19,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute enum ReleaseMembarType { FeNone, - FeSysmembar + FeSysmembar, } /// @@ -29,7 +29,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute { L1None, L1Sysmembar, - L1Membar + L1Membar, } /// @@ -38,7 +38,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute enum Fp32NanBehavior { Legacy, - Fp64Compatible + Fp64Compatible, } /// @@ -47,7 +47,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute enum Fp32F2iNanBehavior { PassZero, - PassIndefinite + PassIndefinite, } /// @@ -56,7 +56,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute enum ApiVisibleCallLimit { _32, - NoCheck + NoCheck, } /// @@ -65,7 +65,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute enum SharedMemoryBankMapping { FourBytesPerBank, - EightBytesPerBank + EightBytesPerBank, } /// @@ -74,7 +74,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute enum Fp32NarrowInstruction { KeepDenorms, - FlushDenorms + FlushDenorms, } /// @@ -84,7 +84,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute { DirectlyAddressableMemorySize16kb, DirectlyAddressableMemorySize32kb, - DirectlyAddressableMemorySize48kb + DirectlyAddressableMemorySize48kb, } /// @@ -99,7 +99,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute RedDec, RedAnd, RedOr, - RedXor + RedXor, } /// @@ -108,7 +108,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute enum ReductionFormat { Unsigned32, - Signed32 + Signed32, } /// @@ -117,7 +117,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute enum StructureSize { FourWords, - OneWord + OneWord, } /// @@ -127,129 +127,129 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute { private fixed int _words[64]; - public int OuterPut => BitRange(30, 0); - public bool OuterOverflow => Bit(31); - public int OuterGet => BitRange(62, 32); - public bool OuterStickyOverflow => Bit(63); - public int InnerGet => BitRange(94, 64); - public bool InnerOverflow => Bit(95); - public int InnerPut => BitRange(126, 96); - public bool InnerStickyOverflow => Bit(127); - public int QmdReservedAA => BitRange(159, 128); - public int DependentQmdPointer => BitRange(191, 160); - public int QmdGroupId => BitRange(197, 192); - public bool SmGlobalCachingEnable => Bit(198); - public bool RunCtaInOneSmPartition => Bit(199); - public bool IsQueue => Bit(200); - public bool AddToHeadOfQmdGroupLinkedList => Bit(201); - public bool SemaphoreReleaseEnable0 => Bit(202); - public bool SemaphoreReleaseEnable1 => Bit(203); - public bool RequireSchedulingPcas => Bit(204); - public bool DependentQmdScheduleEnable => Bit(205); - public DependentQmdType DependentQmdType => (DependentQmdType)BitRange(206, 206); - public bool DependentQmdFieldCopy => Bit(207); - public int QmdReservedB => BitRange(223, 208); - public int CircularQueueSize => BitRange(248, 224); - public bool QmdReservedC => Bit(249); - public bool InvalidateTextureHeaderCache => Bit(250); - public bool InvalidateTextureSamplerCache => Bit(251); - public bool InvalidateTextureDataCache => Bit(252); - public bool InvalidateShaderDataCache => Bit(253); - public bool InvalidateInstructionCache => Bit(254); - public bool InvalidateShaderConstantCache => Bit(255); - public int ProgramOffset => BitRange(287, 256); - public int CircularQueueAddrLower => BitRange(319, 288); - public int CircularQueueAddrUpper => BitRange(327, 320); - public int QmdReservedD => BitRange(335, 328); - public int CircularQueueEntrySize => BitRange(351, 336); - public int CwdReferenceCountId => BitRange(357, 352); - public int CwdReferenceCountDeltaMinusOne => BitRange(365, 358); - public ReleaseMembarType ReleaseMembarType => (ReleaseMembarType)BitRange(366, 366); - public bool CwdReferenceCountIncrEnable => Bit(367); - public CwdMembarType CwdMembarType => (CwdMembarType)BitRange(369, 368); - public bool SequentiallyRunCtas => Bit(370); - public bool CwdReferenceCountDecrEnable => Bit(371); - public bool Throttled => Bit(372); - public Fp32NanBehavior Fp32NanBehavior => (Fp32NanBehavior)BitRange(376, 376); - public Fp32F2iNanBehavior Fp32F2iNanBehavior => (Fp32F2iNanBehavior)BitRange(377, 377); - public ApiVisibleCallLimit ApiVisibleCallLimit => (ApiVisibleCallLimit)BitRange(378, 378); - public SharedMemoryBankMapping SharedMemoryBankMapping => (SharedMemoryBankMapping)BitRange(379, 379); - public SamplerIndex SamplerIndex => (SamplerIndex)BitRange(382, 382); - public Fp32NarrowInstruction Fp32NarrowInstruction => (Fp32NarrowInstruction)BitRange(383, 383); - public int CtaRasterWidth => BitRange(415, 384); - public int CtaRasterHeight => BitRange(431, 416); - public int CtaRasterDepth => BitRange(447, 432); - public int CtaRasterWidthResume => BitRange(479, 448); - public int CtaRasterHeightResume => BitRange(495, 480); - public int CtaRasterDepthResume => BitRange(511, 496); - public int QueueEntriesPerCtaMinusOne => BitRange(518, 512); - public int CoalesceWaitingPeriod => BitRange(529, 522); - public int SharedMemorySize => BitRange(561, 544); - public int QmdReservedG => BitRange(575, 562); - public int QmdVersion => BitRange(579, 576); - public int QmdMajorVersion => BitRange(583, 580); - public int QmdReservedH => BitRange(591, 584); - public int CtaThreadDimension0 => BitRange(607, 592); - public int CtaThreadDimension1 => BitRange(623, 608); - public int CtaThreadDimension2 => BitRange(639, 624); - public bool ConstantBufferValid(int i) => Bit(640 + i * 1); - public int QmdReservedI => BitRange(668, 648); - public L1Configuration L1Configuration => (L1Configuration)BitRange(671, 669); - public int SmDisableMaskLower => BitRange(703, 672); - public int SmDisableMaskUpper => BitRange(735, 704); - public int Release0AddressLower => BitRange(767, 736); - public int Release0AddressUpper => BitRange(775, 768); - public int QmdReservedJ => BitRange(783, 776); - public ReductionOp Release0ReductionOp => (ReductionOp)BitRange(790, 788); - public bool QmdReservedK => Bit(791); - public ReductionFormat Release0ReductionFormat => (ReductionFormat)BitRange(793, 792); - public bool Release0ReductionEnable => Bit(794); - public StructureSize Release0StructureSize => (StructureSize)BitRange(799, 799); - public int Release0Payload => BitRange(831, 800); - public int Release1AddressLower => BitRange(863, 832); - public int Release1AddressUpper => BitRange(871, 864); - public int QmdReservedL => BitRange(879, 872); - public ReductionOp Release1ReductionOp => (ReductionOp)BitRange(886, 884); - public bool QmdReservedM => Bit(887); - public ReductionFormat Release1ReductionFormat => (ReductionFormat)BitRange(889, 888); - public bool Release1ReductionEnable => Bit(890); - public StructureSize Release1StructureSize => (StructureSize)BitRange(895, 895); - public int Release1Payload => BitRange(927, 896); - public int ConstantBufferAddrLower(int i) => BitRange(959 + i * 64, 928 + i * 64); - public int ConstantBufferAddrUpper(int i) => BitRange(967 + i * 64, 960 + i * 64); - public int ConstantBufferReservedAddr(int i) => BitRange(973 + i * 64, 968 + i * 64); - public bool ConstantBufferInvalidate(int i) => Bit(974 + i * 64); - public int ConstantBufferSize(int i) => BitRange(991 + i * 64, 975 + i * 64); - public int ShaderLocalMemoryLowSize => BitRange(1463, 1440); - public int QmdReservedN => BitRange(1466, 1464); - public int BarrierCount => BitRange(1471, 1467); - public int ShaderLocalMemoryHighSize => BitRange(1495, 1472); - public int RegisterCount => BitRange(1503, 1496); - public int ShaderLocalMemoryCrsSize => BitRange(1527, 1504); - public int SassVersion => BitRange(1535, 1528); - public int HwOnlyInnerGet => BitRange(1566, 1536); - public bool HwOnlyRequireSchedulingPcas => Bit(1567); - public int HwOnlyInnerPut => BitRange(1598, 1568); - public bool HwOnlyScgType => Bit(1599); - public int HwOnlySpanListHeadIndex => BitRange(1629, 1600); - public bool QmdReservedQ => Bit(1630); - public bool HwOnlySpanListHeadIndexValid => Bit(1631); - public int HwOnlySkedNextQmdPointer => BitRange(1663, 1632); - public int QmdSpareE => BitRange(1695, 1664); - public int QmdSpareF => BitRange(1727, 1696); - public int QmdSpareG => BitRange(1759, 1728); - public int QmdSpareH => BitRange(1791, 1760); - public int QmdSpareI => BitRange(1823, 1792); - public int QmdSpareJ => BitRange(1855, 1824); - public int QmdSpareK => BitRange(1887, 1856); - public int QmdSpareL => BitRange(1919, 1888); - public int QmdSpareM => BitRange(1951, 1920); - public int QmdSpareN => BitRange(1983, 1952); - public int DebugIdUpper => BitRange(2015, 1984); - public int DebugIdLower => BitRange(2047, 2016); + public readonly int OuterPut => BitRange(30, 0); + public readonly bool OuterOverflow => Bit(31); + public readonly int OuterGet => BitRange(62, 32); + public readonly bool OuterStickyOverflow => Bit(63); + public readonly int InnerGet => BitRange(94, 64); + public readonly bool InnerOverflow => Bit(95); + public readonly int InnerPut => BitRange(126, 96); + public readonly bool InnerStickyOverflow => Bit(127); + public readonly int QmdReservedAA => BitRange(159, 128); + public readonly int DependentQmdPointer => BitRange(191, 160); + public readonly int QmdGroupId => BitRange(197, 192); + public readonly bool SmGlobalCachingEnable => Bit(198); + public readonly bool RunCtaInOneSmPartition => Bit(199); + public readonly bool IsQueue => Bit(200); + public readonly bool AddToHeadOfQmdGroupLinkedList => Bit(201); + public readonly bool SemaphoreReleaseEnable0 => Bit(202); + public readonly bool SemaphoreReleaseEnable1 => Bit(203); + public readonly bool RequireSchedulingPcas => Bit(204); + public readonly bool DependentQmdScheduleEnable => Bit(205); + public readonly DependentQmdType DependentQmdType => (DependentQmdType)BitRange(206, 206); + public readonly bool DependentQmdFieldCopy => Bit(207); + public readonly int QmdReservedB => BitRange(223, 208); + public readonly int CircularQueueSize => BitRange(248, 224); + public readonly bool QmdReservedC => Bit(249); + public readonly bool InvalidateTextureHeaderCache => Bit(250); + public readonly bool InvalidateTextureSamplerCache => Bit(251); + public readonly bool InvalidateTextureDataCache => Bit(252); + public readonly bool InvalidateShaderDataCache => Bit(253); + public readonly bool InvalidateInstructionCache => Bit(254); + public readonly bool InvalidateShaderConstantCache => Bit(255); + public readonly int ProgramOffset => BitRange(287, 256); + public readonly int CircularQueueAddrLower => BitRange(319, 288); + public readonly int CircularQueueAddrUpper => BitRange(327, 320); + public readonly int QmdReservedD => BitRange(335, 328); + public readonly int CircularQueueEntrySize => BitRange(351, 336); + public readonly int CwdReferenceCountId => BitRange(357, 352); + public readonly int CwdReferenceCountDeltaMinusOne => BitRange(365, 358); + public readonly ReleaseMembarType ReleaseMembarType => (ReleaseMembarType)BitRange(366, 366); + public readonly bool CwdReferenceCountIncrEnable => Bit(367); + public readonly CwdMembarType CwdMembarType => (CwdMembarType)BitRange(369, 368); + public readonly bool SequentiallyRunCtas => Bit(370); + public readonly bool CwdReferenceCountDecrEnable => Bit(371); + public readonly bool Throttled => Bit(372); + public readonly Fp32NanBehavior Fp32NanBehavior => (Fp32NanBehavior)BitRange(376, 376); + public readonly Fp32F2iNanBehavior Fp32F2iNanBehavior => (Fp32F2iNanBehavior)BitRange(377, 377); + public readonly ApiVisibleCallLimit ApiVisibleCallLimit => (ApiVisibleCallLimit)BitRange(378, 378); + public readonly SharedMemoryBankMapping SharedMemoryBankMapping => (SharedMemoryBankMapping)BitRange(379, 379); + public readonly SamplerIndex SamplerIndex => (SamplerIndex)BitRange(382, 382); + public readonly Fp32NarrowInstruction Fp32NarrowInstruction => (Fp32NarrowInstruction)BitRange(383, 383); + public readonly int CtaRasterWidth => BitRange(415, 384); + public readonly int CtaRasterHeight => BitRange(431, 416); + public readonly int CtaRasterDepth => BitRange(447, 432); + public readonly int CtaRasterWidthResume => BitRange(479, 448); + public readonly int CtaRasterHeightResume => BitRange(495, 480); + public readonly int CtaRasterDepthResume => BitRange(511, 496); + public readonly int QueueEntriesPerCtaMinusOne => BitRange(518, 512); + public readonly int CoalesceWaitingPeriod => BitRange(529, 522); + public readonly int SharedMemorySize => BitRange(561, 544); + public readonly int QmdReservedG => BitRange(575, 562); + public readonly int QmdVersion => BitRange(579, 576); + public readonly int QmdMajorVersion => BitRange(583, 580); + public readonly int QmdReservedH => BitRange(591, 584); + public readonly int CtaThreadDimension0 => BitRange(607, 592); + public readonly int CtaThreadDimension1 => BitRange(623, 608); + public readonly int CtaThreadDimension2 => BitRange(639, 624); + public readonly bool ConstantBufferValid(int i) => Bit(640 + i * 1); + public readonly int QmdReservedI => BitRange(668, 648); + public readonly L1Configuration L1Configuration => (L1Configuration)BitRange(671, 669); + public readonly int SmDisableMaskLower => BitRange(703, 672); + public readonly int SmDisableMaskUpper => BitRange(735, 704); + public readonly int Release0AddressLower => BitRange(767, 736); + public readonly int Release0AddressUpper => BitRange(775, 768); + public readonly int QmdReservedJ => BitRange(783, 776); + public readonly ReductionOp Release0ReductionOp => (ReductionOp)BitRange(790, 788); + public readonly bool QmdReservedK => Bit(791); + public readonly ReductionFormat Release0ReductionFormat => (ReductionFormat)BitRange(793, 792); + public readonly bool Release0ReductionEnable => Bit(794); + public readonly StructureSize Release0StructureSize => (StructureSize)BitRange(799, 799); + public readonly int Release0Payload => BitRange(831, 800); + public readonly int Release1AddressLower => BitRange(863, 832); + public readonly int Release1AddressUpper => BitRange(871, 864); + public readonly int QmdReservedL => BitRange(879, 872); + public readonly ReductionOp Release1ReductionOp => (ReductionOp)BitRange(886, 884); + public readonly bool QmdReservedM => Bit(887); + public readonly ReductionFormat Release1ReductionFormat => (ReductionFormat)BitRange(889, 888); + public readonly bool Release1ReductionEnable => Bit(890); + public readonly StructureSize Release1StructureSize => (StructureSize)BitRange(895, 895); + public readonly int Release1Payload => BitRange(927, 896); + public readonly int ConstantBufferAddrLower(int i) => BitRange(959 + i * 64, 928 + i * 64); + public readonly int ConstantBufferAddrUpper(int i) => BitRange(967 + i * 64, 960 + i * 64); + public readonly int ConstantBufferReservedAddr(int i) => BitRange(973 + i * 64, 968 + i * 64); + public readonly bool ConstantBufferInvalidate(int i) => Bit(974 + i * 64); + public readonly int ConstantBufferSize(int i) => BitRange(991 + i * 64, 975 + i * 64); + public readonly int ShaderLocalMemoryLowSize => BitRange(1463, 1440); + public readonly int QmdReservedN => BitRange(1466, 1464); + public readonly int BarrierCount => BitRange(1471, 1467); + public readonly int ShaderLocalMemoryHighSize => BitRange(1495, 1472); + public readonly int RegisterCount => BitRange(1503, 1496); + public readonly int ShaderLocalMemoryCrsSize => BitRange(1527, 1504); + public readonly int SassVersion => BitRange(1535, 1528); + public readonly int HwOnlyInnerGet => BitRange(1566, 1536); + public readonly bool HwOnlyRequireSchedulingPcas => Bit(1567); + public readonly int HwOnlyInnerPut => BitRange(1598, 1568); + public readonly bool HwOnlyScgType => Bit(1599); + public readonly int HwOnlySpanListHeadIndex => BitRange(1629, 1600); + public readonly bool QmdReservedQ => Bit(1630); + public readonly bool HwOnlySpanListHeadIndexValid => Bit(1631); + public readonly int HwOnlySkedNextQmdPointer => BitRange(1663, 1632); + public readonly int QmdSpareE => BitRange(1695, 1664); + public readonly int QmdSpareF => BitRange(1727, 1696); + public readonly int QmdSpareG => BitRange(1759, 1728); + public readonly int QmdSpareH => BitRange(1791, 1760); + public readonly int QmdSpareI => BitRange(1823, 1792); + public readonly int QmdSpareJ => BitRange(1855, 1824); + public readonly int QmdSpareK => BitRange(1887, 1856); + public readonly int QmdSpareL => BitRange(1919, 1888); + public readonly int QmdSpareM => BitRange(1951, 1920); + public readonly int QmdSpareN => BitRange(1983, 1952); + public readonly int DebugIdUpper => BitRange(2015, 1984); + public readonly int DebugIdLower => BitRange(2047, 2016); [MethodImpl(MethodImplOptions.AggressiveInlining)] - private bool Bit(int bit) + private readonly bool Bit(int bit) { if ((uint)bit >= 64 * 32) { @@ -260,7 +260,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private int BitRange(int upper, int lower) + private readonly int BitRange(int upper, int lower) { if ((uint)lower >= 64 * 32) { @@ -272,4 +272,4 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute return (_words[lower >> 5] >> (lower & 31)) & mask; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Engine/ConditionalRenderEnabled.cs b/src/Ryujinx.Graphics.Gpu/Engine/ConditionalRenderEnabled.cs index 5581b5cc1..52d7f69f2 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/ConditionalRenderEnabled.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/ConditionalRenderEnabled.cs @@ -7,6 +7,6 @@ { False, True, - Host + Host, } } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Dma/DmaClass.cs b/src/Ryujinx.Graphics.Gpu/Engine/Dma/DmaClass.cs index fd93cd8ba..e6557780b 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Dma/DmaClass.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Dma/DmaClass.cs @@ -30,13 +30,13 @@ namespace Ryujinx.Graphics.Gpu.Engine.Dma SrcLinear = 1 << 7, DstLinear = 1 << 8, MultiLineEnable = 1 << 9, - RemapEnable = 1 << 10 + RemapEnable = 1 << 10, } /// /// Texture parameters for copy. /// - private struct TextureParams + private readonly struct TextureParams { /// /// Copy region X coordinate. @@ -109,7 +109,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Dma _3dEngine = threedEngine; _state = new DeviceState(new Dictionary { - { nameof(DmaClassState.LaunchDma), new RwCallback(LaunchDma, null) } + { nameof(DmaClassState.LaunchDma), new RwCallback(LaunchDma, null) }, }); } @@ -345,8 +345,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Dma // all be rewritten to use pooled arrays, but that gets complicated with packed data and strides Span dstSpan = memoryManager.GetSpan(dstGpuVa + (ulong)dstBaseOffset, dstSize).ToArray(); - TextureParams srcParams = new TextureParams(srcRegionX, srcRegionY, srcBaseOffset, srcBpp, srcLinear, srcCalculator); - TextureParams dstParams = new TextureParams(dstRegionX, dstRegionY, dstBaseOffset, dstBpp, dstLinear, dstCalculator); + TextureParams srcParams = new(srcRegionX, srcRegionY, srcBaseOffset, srcBpp, srcLinear, srcCalculator); + TextureParams dstParams = new(dstRegionX, dstRegionY, dstBaseOffset, dstBpp, dstLinear, dstCalculator); // If remapping is enabled, we always copy the components directly, in order. // If it's enabled, but the mapping is just XYZW, we also copy them in order. @@ -363,13 +363,26 @@ namespace Ryujinx.Graphics.Gpu.Engine.Dma switch (srcBpp) { - case 1: Copy(dstSpan, srcSpan, dstParams, srcParams); break; - case 2: Copy(dstSpan, srcSpan, dstParams, srcParams); break; - case 4: Copy(dstSpan, srcSpan, dstParams, srcParams); break; - case 8: Copy(dstSpan, srcSpan, dstParams, srcParams); break; - case 12: Copy(dstSpan, srcSpan, dstParams, srcParams); break; - case 16: Copy>(dstSpan, srcSpan, dstParams, srcParams); break; - default: throw new NotSupportedException($"Unable to copy ${srcBpp} bpp pixel format."); + case 1: + Copy(dstSpan, srcSpan, dstParams, srcParams); + break; + case 2: + Copy(dstSpan, srcSpan, dstParams, srcParams); + break; + case 4: + Copy(dstSpan, srcSpan, dstParams, srcParams); + break; + case 8: + Copy(dstSpan, srcSpan, dstParams, srcParams); + break; + case 12: + Copy(dstSpan, srcSpan, dstParams, srcParams); + break; + case 16: + Copy>(dstSpan, srcSpan, dstParams, srcParams); + break; + default: + throw new NotSupportedException($"Unable to copy ${srcBpp} bpp pixel format."); } } else @@ -378,11 +391,20 @@ namespace Ryujinx.Graphics.Gpu.Engine.Dma switch (componentSize) { - case 1: CopyShuffle(dstSpan, srcSpan, dstParams, srcParams); break; - case 2: CopyShuffle(dstSpan, srcSpan, dstParams, srcParams); break; - case 3: CopyShuffle(dstSpan, srcSpan, dstParams, srcParams); break; - case 4: CopyShuffle(dstSpan, srcSpan, dstParams, srcParams); break; - default: throw new NotSupportedException($"Unable to copy ${componentSize} component size."); + case 1: + CopyShuffle(dstSpan, srcSpan, dstParams, srcParams); + break; + case 2: + CopyShuffle(dstSpan, srcSpan, dstParams, srcParams); + break; + case 3: + CopyShuffle(dstSpan, srcSpan, dstParams, srcParams); + break; + case 4: + CopyShuffle(dstSpan, srcSpan, dstParams, srcParams); + break; + default: + throw new NotSupportedException($"Unable to copy ${componentSize} component size."); } } @@ -526,28 +548,28 @@ namespace Ryujinx.Graphics.Gpu.Engine.Dma 0 => _state.State.SetRemapComponentsDstX, 1 => _state.State.SetRemapComponentsDstY, 2 => _state.State.SetRemapComponentsDstZ, - _ => _state.State.SetRemapComponentsDstW + _ => _state.State.SetRemapComponentsDstW, }; switch (componentsDst) { case SetRemapComponentsDst.SrcX: - Copy(dstSpan.Slice(Unsafe.SizeOf() * i), srcSpan, dst, src); + Copy(dstSpan[(Unsafe.SizeOf() * i)..], srcSpan, dst, src); break; case SetRemapComponentsDst.SrcY: - Copy(dstSpan.Slice(Unsafe.SizeOf() * i), srcSpan.Slice(Unsafe.SizeOf()), dst, src); + Copy(dstSpan[(Unsafe.SizeOf() * i)..], srcSpan[Unsafe.SizeOf()..], dst, src); break; case SetRemapComponentsDst.SrcZ: - Copy(dstSpan.Slice(Unsafe.SizeOf() * i), srcSpan.Slice(Unsafe.SizeOf() * 2), dst, src); + Copy(dstSpan[(Unsafe.SizeOf() * i)..], srcSpan[(Unsafe.SizeOf() * 2)..], dst, src); break; case SetRemapComponentsDst.SrcW: - Copy(dstSpan.Slice(Unsafe.SizeOf() * i), srcSpan.Slice(Unsafe.SizeOf() * 3), dst, src); + Copy(dstSpan[(Unsafe.SizeOf() * i)..], srcSpan[(Unsafe.SizeOf() * 3)..], dst, src); break; case SetRemapComponentsDst.ConstA: - Fill(dstSpan.Slice(Unsafe.SizeOf() * i), dst, Unsafe.As(ref _state.State.SetRemapConstA)); + Fill(dstSpan[(Unsafe.SizeOf() * i)..], dst, Unsafe.As(ref _state.State.SetRemapConstA)); break; case SetRemapComponentsDst.ConstB: - Fill(dstSpan.Slice(Unsafe.SizeOf() * i), dst, Unsafe.As(ref _state.State.SetRemapConstB)); + Fill(dstSpan[(Unsafe.SizeOf() * i)..], dst, Unsafe.As(ref _state.State.SetRemapConstB)); break; } } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Dma/DmaClassState.cs b/src/Ryujinx.Graphics.Gpu/Engine/Dma/DmaClassState.cs index 6f3b91f2c..d85887368 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Dma/DmaClassState.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Dma/DmaClassState.cs @@ -179,49 +179,49 @@ namespace Ryujinx.Graphics.Gpu.Engine.Dma /// unsafe struct DmaClassState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public fixed uint Reserved00[64]; public uint Nop; public fixed uint Reserved104[15]; public uint PmTrigger; public fixed uint Reserved144[63]; public uint SetSemaphoreA; - public int SetSemaphoreAUpper => (int)(SetSemaphoreA & 0xFF); + public readonly int SetSemaphoreAUpper => (int)(SetSemaphoreA & 0xFF); public uint SetSemaphoreB; public uint SetSemaphorePayload; public fixed uint Reserved24C[2]; public uint SetRenderEnableA; - public int SetRenderEnableAUpper => (int)(SetRenderEnableA & 0xFF); + public readonly int SetRenderEnableAUpper => (int)(SetRenderEnableA & 0xFF); public uint SetRenderEnableB; public uint SetRenderEnableC; - public int SetRenderEnableCMode => (int)(SetRenderEnableC & 0x7); + public readonly int SetRenderEnableCMode => (int)(SetRenderEnableC & 0x7); public uint SetSrcPhysMode; - public SetPhysModeTarget SetSrcPhysModeTarget => (SetPhysModeTarget)(SetSrcPhysMode & 0x3); + public readonly SetPhysModeTarget SetSrcPhysModeTarget => (SetPhysModeTarget)(SetSrcPhysMode & 0x3); public uint SetDstPhysMode; - public SetPhysModeTarget SetDstPhysModeTarget => (SetPhysModeTarget)(SetDstPhysMode & 0x3); + public readonly SetPhysModeTarget SetDstPhysModeTarget => (SetPhysModeTarget)(SetDstPhysMode & 0x3); public fixed uint Reserved268[38]; public uint LaunchDma; - public LaunchDmaDataTransferType LaunchDmaDataTransferType => (LaunchDmaDataTransferType)(LaunchDma & 0x3); - public bool LaunchDmaFlushEnable => (LaunchDma & 0x4) != 0; - public LaunchDmaSemaphoreType LaunchDmaSemaphoreType => (LaunchDmaSemaphoreType)((LaunchDma >> 3) & 0x3); - public LaunchDmaInterruptType LaunchDmaInterruptType => (LaunchDmaInterruptType)((LaunchDma >> 5) & 0x3); - public LaunchDmaMemoryLayout LaunchDmaSrcMemoryLayout => (LaunchDmaMemoryLayout)((LaunchDma >> 7) & 0x1); - public LaunchDmaMemoryLayout LaunchDmaDstMemoryLayout => (LaunchDmaMemoryLayout)((LaunchDma >> 8) & 0x1); - public bool LaunchDmaMultiLineEnable => (LaunchDma & 0x200) != 0; - public bool LaunchDmaRemapEnable => (LaunchDma & 0x400) != 0; - public bool LaunchDmaForceRmwdisable => (LaunchDma & 0x800) != 0; - public LaunchDmaType LaunchDmaSrcType => (LaunchDmaType)((LaunchDma >> 12) & 0x1); - public LaunchDmaType LaunchDmaDstType => (LaunchDmaType)((LaunchDma >> 13) & 0x1); - public LaunchDmaSemaphoreReduction LaunchDmaSemaphoreReduction => (LaunchDmaSemaphoreReduction)((LaunchDma >> 14) & 0xF); - public LaunchDmaSemaphoreReductionSign LaunchDmaSemaphoreReductionSign => (LaunchDmaSemaphoreReductionSign)((LaunchDma >> 18) & 0x1); - public bool LaunchDmaSemaphoreReductionEnable => (LaunchDma & 0x80000) != 0; - public LaunchDmaBypassL2 LaunchDmaBypassL2 => (LaunchDmaBypassL2)((LaunchDma >> 20) & 0x1); + public readonly LaunchDmaDataTransferType LaunchDmaDataTransferType => (LaunchDmaDataTransferType)(LaunchDma & 0x3); + public readonly bool LaunchDmaFlushEnable => (LaunchDma & 0x4) != 0; + public readonly LaunchDmaSemaphoreType LaunchDmaSemaphoreType => (LaunchDmaSemaphoreType)((LaunchDma >> 3) & 0x3); + public readonly LaunchDmaInterruptType LaunchDmaInterruptType => (LaunchDmaInterruptType)((LaunchDma >> 5) & 0x3); + public readonly LaunchDmaMemoryLayout LaunchDmaSrcMemoryLayout => (LaunchDmaMemoryLayout)((LaunchDma >> 7) & 0x1); + public readonly LaunchDmaMemoryLayout LaunchDmaDstMemoryLayout => (LaunchDmaMemoryLayout)((LaunchDma >> 8) & 0x1); + public readonly bool LaunchDmaMultiLineEnable => (LaunchDma & 0x200) != 0; + public readonly bool LaunchDmaRemapEnable => (LaunchDma & 0x400) != 0; + public readonly bool LaunchDmaForceRmwdisable => (LaunchDma & 0x800) != 0; + public readonly LaunchDmaType LaunchDmaSrcType => (LaunchDmaType)((LaunchDma >> 12) & 0x1); + public readonly LaunchDmaType LaunchDmaDstType => (LaunchDmaType)((LaunchDma >> 13) & 0x1); + public readonly LaunchDmaSemaphoreReduction LaunchDmaSemaphoreReduction => (LaunchDmaSemaphoreReduction)((LaunchDma >> 14) & 0xF); + public readonly LaunchDmaSemaphoreReductionSign LaunchDmaSemaphoreReductionSign => (LaunchDmaSemaphoreReductionSign)((LaunchDma >> 18) & 0x1); + public readonly bool LaunchDmaSemaphoreReductionEnable => (LaunchDma & 0x80000) != 0; + public readonly LaunchDmaBypassL2 LaunchDmaBypassL2 => (LaunchDmaBypassL2)((LaunchDma >> 20) & 0x1); public fixed uint Reserved304[63]; public uint OffsetInUpper; - public int OffsetInUpperUpper => (int)(OffsetInUpper & 0xFF); + public readonly int OffsetInUpperUpper => (int)(OffsetInUpper & 0xFF); public uint OffsetInLower; public uint OffsetOutUpper; - public int OffsetOutUpperUpper => (int)(OffsetOutUpper & 0xFF); + public readonly int OffsetOutUpperUpper => (int)(OffsetOutUpper & 0xFF); public uint OffsetOutLower; public uint PitchIn; public uint PitchOut; @@ -231,38 +231,38 @@ namespace Ryujinx.Graphics.Gpu.Engine.Dma public uint SetRemapConstA; public uint SetRemapConstB; public uint SetRemapComponents; - public SetRemapComponentsDst SetRemapComponentsDstX => (SetRemapComponentsDst)(SetRemapComponents & 0x7); - public SetRemapComponentsDst SetRemapComponentsDstY => (SetRemapComponentsDst)((SetRemapComponents >> 4) & 0x7); - public SetRemapComponentsDst SetRemapComponentsDstZ => (SetRemapComponentsDst)((SetRemapComponents >> 8) & 0x7); - public SetRemapComponentsDst SetRemapComponentsDstW => (SetRemapComponentsDst)((SetRemapComponents >> 12) & 0x7); - public SetRemapComponentsComponentSize SetRemapComponentsComponentSize => (SetRemapComponentsComponentSize)((SetRemapComponents >> 16) & 0x3); - public SetRemapComponentsNumComponents SetRemapComponentsNumSrcComponents => (SetRemapComponentsNumComponents)((SetRemapComponents >> 20) & 0x3); - public SetRemapComponentsNumComponents SetRemapComponentsNumDstComponents => (SetRemapComponentsNumComponents)((SetRemapComponents >> 24) & 0x3); + public readonly SetRemapComponentsDst SetRemapComponentsDstX => (SetRemapComponentsDst)(SetRemapComponents & 0x7); + public readonly SetRemapComponentsDst SetRemapComponentsDstY => (SetRemapComponentsDst)((SetRemapComponents >> 4) & 0x7); + public readonly SetRemapComponentsDst SetRemapComponentsDstZ => (SetRemapComponentsDst)((SetRemapComponents >> 8) & 0x7); + public readonly SetRemapComponentsDst SetRemapComponentsDstW => (SetRemapComponentsDst)((SetRemapComponents >> 12) & 0x7); + public readonly SetRemapComponentsComponentSize SetRemapComponentsComponentSize => (SetRemapComponentsComponentSize)((SetRemapComponents >> 16) & 0x3); + public readonly SetRemapComponentsNumComponents SetRemapComponentsNumSrcComponents => (SetRemapComponentsNumComponents)((SetRemapComponents >> 20) & 0x3); + public readonly SetRemapComponentsNumComponents SetRemapComponentsNumDstComponents => (SetRemapComponentsNumComponents)((SetRemapComponents >> 24) & 0x3); public uint SetDstBlockSize; - public SetBlockSizeWidth SetDstBlockSizeWidth => (SetBlockSizeWidth)(SetDstBlockSize & 0xF); - public SetBlockSizeHeight SetDstBlockSizeHeight => (SetBlockSizeHeight)((SetDstBlockSize >> 4) & 0xF); - public SetBlockSizeDepth SetDstBlockSizeDepth => (SetBlockSizeDepth)((SetDstBlockSize >> 8) & 0xF); - public SetBlockSizeGobHeight SetDstBlockSizeGobHeight => (SetBlockSizeGobHeight)((SetDstBlockSize >> 12) & 0xF); + public readonly SetBlockSizeWidth SetDstBlockSizeWidth => (SetBlockSizeWidth)(SetDstBlockSize & 0xF); + public readonly SetBlockSizeHeight SetDstBlockSizeHeight => (SetBlockSizeHeight)((SetDstBlockSize >> 4) & 0xF); + public readonly SetBlockSizeDepth SetDstBlockSizeDepth => (SetBlockSizeDepth)((SetDstBlockSize >> 8) & 0xF); + public readonly SetBlockSizeGobHeight SetDstBlockSizeGobHeight => (SetBlockSizeGobHeight)((SetDstBlockSize >> 12) & 0xF); public uint SetDstWidth; public uint SetDstHeight; public uint SetDstDepth; public uint SetDstLayer; public uint SetDstOrigin; - public int SetDstOriginX => (int)(SetDstOrigin & 0xFFFF); - public int SetDstOriginY => (int)((SetDstOrigin >> 16) & 0xFFFF); + public readonly int SetDstOriginX => (int)(SetDstOrigin & 0xFFFF); + public readonly int SetDstOriginY => (int)((SetDstOrigin >> 16) & 0xFFFF); public uint Reserved724; public uint SetSrcBlockSize; - public SetBlockSizeWidth SetSrcBlockSizeWidth => (SetBlockSizeWidth)(SetSrcBlockSize & 0xF); - public SetBlockSizeHeight SetSrcBlockSizeHeight => (SetBlockSizeHeight)((SetSrcBlockSize >> 4) & 0xF); - public SetBlockSizeDepth SetSrcBlockSizeDepth => (SetBlockSizeDepth)((SetSrcBlockSize >> 8) & 0xF); - public SetBlockSizeGobHeight SetSrcBlockSizeGobHeight => (SetBlockSizeGobHeight)((SetSrcBlockSize >> 12) & 0xF); + public readonly SetBlockSizeWidth SetSrcBlockSizeWidth => (SetBlockSizeWidth)(SetSrcBlockSize & 0xF); + public readonly SetBlockSizeHeight SetSrcBlockSizeHeight => (SetBlockSizeHeight)((SetSrcBlockSize >> 4) & 0xF); + public readonly SetBlockSizeDepth SetSrcBlockSizeDepth => (SetBlockSizeDepth)((SetSrcBlockSize >> 8) & 0xF); + public readonly SetBlockSizeGobHeight SetSrcBlockSizeGobHeight => (SetBlockSizeGobHeight)((SetSrcBlockSize >> 12) & 0xF); public uint SetSrcWidth; public uint SetSrcHeight; public uint SetSrcDepth; public uint SetSrcLayer; public uint SetSrcOrigin; - public int SetSrcOriginX => (int)(SetSrcOrigin & 0xFFFF); - public int SetSrcOriginY => (int)((SetSrcOrigin >> 16) & 0xFFFF); + public readonly int SetSrcOriginX => (int)(SetSrcOrigin & 0xFFFF); + public readonly int SetSrcOriginY => (int)((SetSrcOrigin >> 16) & 0xFFFF); public fixed uint Reserved740[629]; public uint PmTriggerEnd; public fixed uint Reserved1118[2490]; diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Dma/DmaTexture.cs b/src/Ryujinx.Graphics.Gpu/Engine/Dma/DmaTexture.cs index 6873ff40f..8193c4a2c 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Dma/DmaTexture.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Dma/DmaTexture.cs @@ -7,7 +7,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Dma /// struct DmaTexture { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public MemoryLayout MemoryLayout; public int Width; public int Height; @@ -17,4 +17,4 @@ namespace Ryujinx.Graphics.Gpu.Engine.Dma public ushort RegionY; #pragma warning restore CS0649 } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/CompressedMethod.cs b/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/CompressedMethod.cs index d082ee9dd..afa4db5ec 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/CompressedMethod.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/CompressedMethod.cs @@ -8,7 +8,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo Grp0SetSubDevMask = 1, Grp0StoreSubDevMask = 2, Grp0UseSubDevMask = 3, - Grp2NonIncMethod = 0 + Grp2NonIncMethod = Grp0IncMethod, } enum SecOp @@ -20,22 +20,22 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo ImmdDataMethod = 4, OneInc = 5, Reserved6 = 6, - EndPbSegment = 7 + EndPbSegment = 7, } struct CompressedMethod { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public uint Method; #pragma warning restore CS0649 - public int MethodAddressOld => (int)((Method >> 2) & 0x7FF); - public int MethodAddress => (int)(Method & 0xFFF); - public int SubdeviceMask => (int)((Method >> 4) & 0xFFF); - public int MethodSubchannel => (int)((Method >> 13) & 0x7); - public TertOp TertOp => (TertOp)((Method >> 16) & 0x3); - public int MethodCountOld => (int)((Method >> 18) & 0x7FF); - public int MethodCount => (int)((Method >> 16) & 0x1FFF); - public int ImmdData => (int)((Method >> 16) & 0x1FFF); - public SecOp SecOp => (SecOp)((Method >> 29) & 0x7); + public readonly int MethodAddressOld => (int)((Method >> 2) & 0x7FF); + public readonly int MethodAddress => (int)(Method & 0xFFF); + public readonly int SubdeviceMask => (int)((Method >> 4) & 0xFFF); + public readonly int MethodSubchannel => (int)((Method >> 13) & 0x7); + public readonly TertOp TertOp => (TertOp)((Method >> 16) & 0x3); + public readonly int MethodCountOld => (int)((Method >> 18) & 0x7FF); + public readonly int MethodCount => (int)((Method >> 16) & 0x1FFF); + public readonly int ImmdData => (int)((Method >> 16) & 0x1FFF); + public readonly SecOp SecOp => (SecOp)((Method >> 29) & 0x7); } } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPEntry.cs b/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPEntry.cs index 31ba3217d..81e28acf4 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPEntry.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPEntry.cs @@ -36,20 +36,20 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo struct GPEntry { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public uint Entry0; #pragma warning restore CS0649 - public Entry0Fetch Entry0Fetch => (Entry0Fetch)(Entry0 & 0x1); - public int Entry0Get => (int)((Entry0 >> 2) & 0x3FFFFFFF); - public int Entry0Operand => (int)(Entry0); -#pragma warning disable CS0649 + public readonly Entry0Fetch Entry0Fetch => (Entry0Fetch)(Entry0 & 0x1); + public readonly int Entry0Get => (int)((Entry0 >> 2) & 0x3FFFFFFF); + public readonly int Entry0Operand => (int)(Entry0); +#pragma warning disable CS0649 // Field is never assigned to public uint Entry1; #pragma warning restore CS0649 - public int Entry1GetHi => (int)(Entry1 & 0xFF); - public Entry1Priv Entry1Priv => (Entry1Priv)((Entry1 >> 8) & 0x1); - public Entry1Level Entry1Level => (Entry1Level)((Entry1 >> 9) & 0x1); - public int Entry1Length => (int)((Entry1 >> 10) & 0x1FFFFF); - public Entry1Sync Entry1Sync => (Entry1Sync)((Entry1 >> 31) & 0x1); - public Entry1Opcode Entry1Opcode => (Entry1Opcode)(Entry1 & 0xFF); + public readonly int Entry1GetHi => (int)(Entry1 & 0xFF); + public readonly Entry1Priv Entry1Priv => (Entry1Priv)((Entry1 >> 8) & 0x1); + public readonly Entry1Level Entry1Level => (Entry1Level)((Entry1 >> 9) & 0x1); + public readonly int Entry1Length => (int)((Entry1 >> 10) & 0x1FFFFF); + public readonly Entry1Sync Entry1Sync => (Entry1Sync)((Entry1 >> 31) & 0x1); + public readonly Entry1Opcode Entry1Opcode => (Entry1Opcode)(Entry1 & 0xFF); } } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPFifoClass.cs b/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPFifoClass.cs index 7a11c649c..4bdbd1a03 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPFifoClass.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPFifoClass.cs @@ -16,7 +16,6 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo private readonly GPFifoProcessor _parent; private readonly DeviceState _state; - private int _previousSubChannel; private bool _createSyncPending; private const int MacrosCount = 0x80; @@ -45,7 +44,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo { nameof(GPFifoClassState.SetReference), new RwCallback(SetReference, null) }, { nameof(GPFifoClassState.LoadMmeInstructionRam), new RwCallback(LoadMmeInstructionRam, null) }, { nameof(GPFifoClassState.LoadMmeStartAddressRam), new RwCallback(LoadMmeStartAddressRam, null) }, - { nameof(GPFifoClassState.SetMmeShadowRamControl), new RwCallback(SetMmeShadowRamControl, null) } + { nameof(GPFifoClassState.SetMmeShadowRamControl), new RwCallback(SetMmeShadowRamControl, null) }, }); _macros = new Macro[MacrosCount]; diff --git a/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPFifoClassState.cs b/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPFifoClassState.cs index ebfe15664..dd6ae1b40 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPFifoClassState.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPFifoClassState.cs @@ -13,7 +13,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo Release = 2, AcqGeq = 4, AcqAnd = 8, - Reduction = 16 + Reduction = 16, } /// @@ -22,7 +22,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo enum SemaphoredAcquireSwitch { Disabled = 0, - Enabled = 1 + Enabled = 1, } /// @@ -31,7 +31,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo enum SemaphoredReleaseWfi { En = 0, - Dis = 1 + Dis = 1, } /// @@ -40,7 +40,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo enum SemaphoredReleaseSize { SixteenBytes = 0, - FourBytes = 1 + FourBytes = 1, } /// @@ -55,7 +55,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo Or = 4, Add = 5, Inc = 6, - Dec = 7 + Dec = 7, } /// @@ -64,7 +64,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo enum SemaphoredFormat { Signed = 0, - Unsigned = 1 + Unsigned = 1, } /// @@ -73,7 +73,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo enum MemOpCTlbInvalidatePdb { One = 0, - All = 1 + All = 1, } /// @@ -82,7 +82,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo enum MemOpCTlbInvalidateGpc { Enable = 0, - Disable = 1 + Disable = 1, } /// @@ -92,7 +92,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo { VidMem = 0, SysMemCoherent = 2, - SysMemNoncoherent = 3 + SysMemNoncoherent = 3, } /// @@ -105,7 +105,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo L2PeermemInvalidate = 13, L2SysmemInvalidate = 14, L2CleanComptags = 15, - L2FlushDirty = 16 + L2FlushDirty = 16, } /// @@ -114,7 +114,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo enum SyncpointbOperation { Wait = 0, - Incr = 1 + Incr = 1, } /// @@ -123,7 +123,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo enum SyncpointbWaitSwitch { Dis = 0, - En = 1 + En = 1, } /// @@ -132,7 +132,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo enum WfiScope { CurrentScgType = 0, - All = 1 + All = 1, } /// @@ -143,7 +143,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo Nop = 0, PbdmaTimeslice = 1, RunlistTimeslice = 2, - Tsg = 3 + Tsg = 3, } /// @@ -151,44 +151,44 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo /// struct GPFifoClassState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public uint SetObject; - public int SetObjectNvclass => (int)(SetObject & 0xFFFF); - public int SetObjectEngine => (int)((SetObject >> 16) & 0x1F); + public readonly int SetObjectNvclass => (int)(SetObject & 0xFFFF); + public readonly int SetObjectEngine => (int)((SetObject >> 16) & 0x1F); public uint Illegal; - public int IllegalHandle => (int)(Illegal); + public readonly int IllegalHandle => (int)(Illegal); public uint Nop; - public int NopHandle => (int)(Nop); + public readonly int NopHandle => (int)(Nop); public uint Reserved0C; public uint Semaphorea; - public int SemaphoreaOffsetUpper => (int)(Semaphorea & 0xFF); + public readonly int SemaphoreaOffsetUpper => (int)(Semaphorea & 0xFF); public uint Semaphoreb; - public int SemaphorebOffsetLower => (int)((Semaphoreb >> 2) & 0x3FFFFFFF); + public readonly int SemaphorebOffsetLower => (int)((Semaphoreb >> 2) & 0x3FFFFFFF); public uint Semaphorec; - public int SemaphorecPayload => (int)(Semaphorec); + public readonly int SemaphorecPayload => (int)(Semaphorec); public uint Semaphored; - public SemaphoredOperation SemaphoredOperation => (SemaphoredOperation)(Semaphored & 0x1F); - public SemaphoredAcquireSwitch SemaphoredAcquireSwitch => (SemaphoredAcquireSwitch)((Semaphored >> 12) & 0x1); - public SemaphoredReleaseWfi SemaphoredReleaseWfi => (SemaphoredReleaseWfi)((Semaphored >> 20) & 0x1); - public SemaphoredReleaseSize SemaphoredReleaseSize => (SemaphoredReleaseSize)((Semaphored >> 24) & 0x1); - public SemaphoredReduction SemaphoredReduction => (SemaphoredReduction)((Semaphored >> 27) & 0xF); - public SemaphoredFormat SemaphoredFormat => (SemaphoredFormat)((Semaphored >> 31) & 0x1); + public readonly SemaphoredOperation SemaphoredOperation => (SemaphoredOperation)(Semaphored & 0x1F); + public readonly SemaphoredAcquireSwitch SemaphoredAcquireSwitch => (SemaphoredAcquireSwitch)((Semaphored >> 12) & 0x1); + public readonly SemaphoredReleaseWfi SemaphoredReleaseWfi => (SemaphoredReleaseWfi)((Semaphored >> 20) & 0x1); + public readonly SemaphoredReleaseSize SemaphoredReleaseSize => (SemaphoredReleaseSize)((Semaphored >> 24) & 0x1); + public readonly SemaphoredReduction SemaphoredReduction => (SemaphoredReduction)((Semaphored >> 27) & 0xF); + public readonly SemaphoredFormat SemaphoredFormat => (SemaphoredFormat)((Semaphored >> 31) & 0x1); public uint NonStallInterrupt; - public int NonStallInterruptHandle => (int)(NonStallInterrupt); + public readonly int NonStallInterruptHandle => (int)(NonStallInterrupt); public uint FbFlush; - public int FbFlushHandle => (int)(FbFlush); + public readonly int FbFlushHandle => (int)(FbFlush); public uint Reserved28; public uint Reserved2C; public uint MemOpC; - public int MemOpCOperandLow => (int)((MemOpC >> 2) & 0x3FFFFFFF); - public MemOpCTlbInvalidatePdb MemOpCTlbInvalidatePdb => (MemOpCTlbInvalidatePdb)(MemOpC & 0x1); - public MemOpCTlbInvalidateGpc MemOpCTlbInvalidateGpc => (MemOpCTlbInvalidateGpc)((MemOpC >> 1) & 0x1); - public MemOpCTlbInvalidateTarget MemOpCTlbInvalidateTarget => (MemOpCTlbInvalidateTarget)((MemOpC >> 10) & 0x3); - public int MemOpCTlbInvalidateAddrLo => (int)((MemOpC >> 12) & 0xFFFFF); + public readonly int MemOpCOperandLow => (int)((MemOpC >> 2) & 0x3FFFFFFF); + public readonly MemOpCTlbInvalidatePdb MemOpCTlbInvalidatePdb => (MemOpCTlbInvalidatePdb)(MemOpC & 0x1); + public readonly MemOpCTlbInvalidateGpc MemOpCTlbInvalidateGpc => (MemOpCTlbInvalidateGpc)((MemOpC >> 1) & 0x1); + public readonly MemOpCTlbInvalidateTarget MemOpCTlbInvalidateTarget => (MemOpCTlbInvalidateTarget)((MemOpC >> 10) & 0x3); + public readonly int MemOpCTlbInvalidateAddrLo => (int)((MemOpC >> 12) & 0xFFFFF); public uint MemOpD; - public int MemOpDOperandHigh => (int)(MemOpD & 0xFF); - public MemOpDOperation MemOpDOperation => (MemOpDOperation)((MemOpD >> 27) & 0x1F); - public int MemOpDTlbInvalidateAddrHi => (int)(MemOpD & 0xFF); + public readonly int MemOpDOperandHigh => (int)(MemOpD & 0xFF); + public readonly MemOpDOperation MemOpDOperation => (MemOpDOperation)((MemOpD >> 27) & 0x1F); + public readonly int MemOpDTlbInvalidateAddrHi => (int)(MemOpD & 0xFF); public uint Reserved38; public uint Reserved3C; public uint Reserved40; @@ -196,7 +196,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo public uint Reserved48; public uint Reserved4C; public uint SetReference; - public int SetReferenceCount => (int)(SetReference); + public readonly int SetReferenceCount => (int)(SetReference); public uint Reserved54; public uint Reserved58; public uint Reserved5C; @@ -205,17 +205,17 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo public uint Reserved68; public uint Reserved6C; public uint Syncpointa; - public int SyncpointaPayload => (int)(Syncpointa); + public readonly int SyncpointaPayload => (int)(Syncpointa); public uint Syncpointb; - public SyncpointbOperation SyncpointbOperation => (SyncpointbOperation)(Syncpointb & 0x1); - public SyncpointbWaitSwitch SyncpointbWaitSwitch => (SyncpointbWaitSwitch)((Syncpointb >> 4) & 0x1); - public int SyncpointbSyncptIndex => (int)((Syncpointb >> 8) & 0xFFF); + public readonly SyncpointbOperation SyncpointbOperation => (SyncpointbOperation)(Syncpointb & 0x1); + public readonly SyncpointbWaitSwitch SyncpointbWaitSwitch => (SyncpointbWaitSwitch)((Syncpointb >> 4) & 0x1); + public readonly int SyncpointbSyncptIndex => (int)((Syncpointb >> 8) & 0xFFF); public uint Wfi; - public WfiScope WfiScope => (WfiScope)(Wfi & 0x1); + public readonly WfiScope WfiScope => (WfiScope)(Wfi & 0x1); public uint CrcCheck; - public int CrcCheckValue => (int)(CrcCheck); + public readonly int CrcCheckValue => (int)(CrcCheck); public uint Yield; - public YieldOp YieldOp => (YieldOp)(Yield & 0x3); + public readonly YieldOp YieldOp => (YieldOp)(Yield & 0x3); // TODO: Eventually move this to per-engine state. public Array31 Reserved84; public uint NoOperation; diff --git a/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPFifoDevice.cs b/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPFifoDevice.cs index 09bcdec11..bb5bc21cb 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPFifoDevice.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPFifoDevice.cs @@ -18,7 +18,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo private enum CommandBufferType { Prefetch, - NoPrefetch + NoPrefetch, } /// @@ -57,7 +57,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo /// The memory manager used to fetch the data /// If true, flushes potential GPU written data before reading the command buffer /// The fetched data - private ReadOnlySpan GetWords(MemoryManager memoryManager, bool flush) + private readonly ReadOnlySpan GetWords(MemoryManager memoryManager, bool flush) { return MemoryMarshal.Cast(memoryManager.GetSpan(EntryAddress, (int)EntryCount * 4, flush)); } @@ -77,7 +77,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo /// The memory manager used to fetch the data /// If true, flushes potential GPU written data before reading the command buffer /// The command buffer words - public ReadOnlySpan Fetch(MemoryManager memoryManager, bool flush) + public readonly ReadOnlySpan Fetch(MemoryManager memoryManager, bool flush) { return Words ?? GetWords(memoryManager, flush); } @@ -85,7 +85,6 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo private readonly ConcurrentQueue _commandBufferQueue; - private CommandBuffer _currentCommandBuffer; private GPFifoProcessor _prevChannelProcessor; private readonly bool _ibEnable; @@ -129,7 +128,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo Type = CommandBufferType.Prefetch, Words = commandBuffer, EntryAddress = ulong.MaxValue, - EntryCount = (uint)commandBuffer.Length + EntryCount = (uint)commandBuffer.Length, }); } @@ -156,7 +155,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo Type = type, Words = null, EntryAddress = startAddress, - EntryCount = (uint)entry.Entry1Length + EntryCount = (uint)entry.Entry1Length, }; } @@ -217,7 +216,6 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo flushCommandBuffer = false; } - _currentCommandBuffer = entry; ReadOnlySpan words = entry.Fetch(entry.Processor.MemoryManager, flushCommandBuffer); // If we are changing the current channel, diff --git a/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPFifoProcessor.cs b/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPFifoProcessor.cs index 3fb3feeea..6ba1bc22e 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPFifoProcessor.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPFifoProcessor.cs @@ -243,7 +243,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo { 0 => _3dClass, 3 => _2dClass, - _ => null + _ => null, }; if (state != null) diff --git a/src/Ryujinx.Graphics.Gpu/Engine/InlineToMemory/InlineToMemoryClass.cs b/src/Ryujinx.Graphics.Gpu/Engine/InlineToMemory/InlineToMemoryClass.cs index e1d7e9407..e417b9a0a 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/InlineToMemory/InlineToMemoryClass.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/InlineToMemory/InlineToMemoryClass.cs @@ -53,7 +53,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.InlineToMemory _state = new DeviceState(new Dictionary { { nameof(InlineToMemoryClassState.LaunchDma), new RwCallback(LaunchDma, null) }, - { nameof(InlineToMemoryClassState.LoadInlineData), new RwCallback(LoadInlineData, null) } + { nameof(InlineToMemoryClassState.LoadInlineData), new RwCallback(LoadInlineData, null) }, }); } } @@ -134,7 +134,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.InlineToMemory if (!_finished) { int copySize = Math.Min(data.Length, _buffer.Length - _offset); - data.Slice(0, copySize).CopyTo(new Span(_buffer).Slice(_offset, copySize)); + data[..copySize].CopyTo(new Span(_buffer).Slice(_offset, copySize)); _offset += copySize; @@ -169,11 +169,11 @@ namespace Ryujinx.Graphics.Gpu.Engine.InlineToMemory { var memoryManager = _channel.MemoryManager; - var data = MemoryMarshal.Cast(_buffer).Slice(0, _size); + var data = MemoryMarshal.Cast(_buffer)[.._size]; if (_isLinear && _lineCount == 1) { - memoryManager.WriteTrackedResource(_dstGpuVa, data.Slice(0, _lineLengthIn)); + memoryManager.WriteTrackedResource(_dstGpuVa, data[.._lineLengthIn]); _context.AdvanceSequence(); } else diff --git a/src/Ryujinx.Graphics.Gpu/Engine/InlineToMemory/InlineToMemoryClassState.cs b/src/Ryujinx.Graphics.Gpu/Engine/InlineToMemory/InlineToMemoryClassState.cs index f6d9602a6..ec5042fda 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/InlineToMemory/InlineToMemoryClassState.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/InlineToMemory/InlineToMemoryClassState.cs @@ -1,5 +1,7 @@ // This file was auto-generated from NVIDIA official Maxwell definitions. +using Ryujinx.Common.Memory; + namespace Ryujinx.Graphics.Gpu.Engine.InlineToMemory { /// @@ -111,24 +113,24 @@ namespace Ryujinx.Graphics.Gpu.Engine.InlineToMemory /// unsafe struct InlineToMemoryClassState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public uint SetObject; - public int SetObjectClassId => (int)(SetObject & 0xFFFF); - public int SetObjectEngineId => (int)((SetObject >> 16) & 0x1F); + public readonly int SetObjectClassId => (int)(SetObject & 0xFFFF); + public readonly int SetObjectEngineId => (int)((SetObject >> 16) & 0x1F); public fixed uint Reserved04[63]; public uint NoOperation; public uint SetNotifyA; - public int SetNotifyAAddressUpper => (int)(SetNotifyA & 0xFF); + public readonly int SetNotifyAAddressUpper => (int)(SetNotifyA & 0xFF); public uint SetNotifyB; public uint Notify; - public NotifyType NotifyType => (NotifyType)(Notify); + public readonly NotifyType NotifyType => (NotifyType)(Notify); public uint WaitForIdle; public fixed uint Reserved114[7]; public uint SetGlobalRenderEnableA; - public int SetGlobalRenderEnableAOffsetUpper => (int)(SetGlobalRenderEnableA & 0xFF); + public readonly int SetGlobalRenderEnableAOffsetUpper => (int)(SetGlobalRenderEnableA & 0xFF); public uint SetGlobalRenderEnableB; public uint SetGlobalRenderEnableC; - public int SetGlobalRenderEnableCMode => (int)(SetGlobalRenderEnableC & 0x7); + public readonly int SetGlobalRenderEnableCMode => (int)(SetGlobalRenderEnableC & 0x7); public uint SendGoIdle; public uint PmTrigger; public uint PmTriggerWfi; @@ -139,34 +141,34 @@ namespace Ryujinx.Graphics.Gpu.Engine.InlineToMemory public uint LineLengthIn; public uint LineCount; public uint OffsetOutUpper; - public int OffsetOutUpperValue => (int)(OffsetOutUpper & 0xFF); + public readonly int OffsetOutUpperValue => (int)(OffsetOutUpper & 0xFF); public uint OffsetOut; public uint PitchOut; public uint SetDstBlockSize; - public SetDstBlockSizeWidth SetDstBlockSizeWidth => (SetDstBlockSizeWidth)(SetDstBlockSize & 0xF); - public SetDstBlockSizeHeight SetDstBlockSizeHeight => (SetDstBlockSizeHeight)((SetDstBlockSize >> 4) & 0xF); - public SetDstBlockSizeDepth SetDstBlockSizeDepth => (SetDstBlockSizeDepth)((SetDstBlockSize >> 8) & 0xF); + public readonly SetDstBlockSizeWidth SetDstBlockSizeWidth => (SetDstBlockSizeWidth)(SetDstBlockSize & 0xF); + public readonly SetDstBlockSizeHeight SetDstBlockSizeHeight => (SetDstBlockSizeHeight)((SetDstBlockSize >> 4) & 0xF); + public readonly SetDstBlockSizeDepth SetDstBlockSizeDepth => (SetDstBlockSizeDepth)((SetDstBlockSize >> 8) & 0xF); public uint SetDstWidth; public uint SetDstHeight; public uint SetDstDepth; public uint SetDstLayer; public uint SetDstOriginBytesX; - public int SetDstOriginBytesXV => (int)(SetDstOriginBytesX & 0xFFFFF); + public readonly int SetDstOriginBytesXV => (int)(SetDstOriginBytesX & 0xFFFFF); public uint SetDstOriginSamplesY; - public int SetDstOriginSamplesYV => (int)(SetDstOriginSamplesY & 0xFFFF); + public readonly int SetDstOriginSamplesYV => (int)(SetDstOriginSamplesY & 0xFFFF); public uint LaunchDma; - public LaunchDmaDstMemoryLayout LaunchDmaDstMemoryLayout => (LaunchDmaDstMemoryLayout)(LaunchDma & 0x1); - public LaunchDmaCompletionType LaunchDmaCompletionType => (LaunchDmaCompletionType)((LaunchDma >> 4) & 0x3); - public LaunchDmaInterruptType LaunchDmaInterruptType => (LaunchDmaInterruptType)((LaunchDma >> 8) & 0x3); - public LaunchDmaSemaphoreStructSize LaunchDmaSemaphoreStructSize => (LaunchDmaSemaphoreStructSize)((LaunchDma >> 12) & 0x1); - public bool LaunchDmaReductionEnable => (LaunchDma & 0x2) != 0; - public LaunchDmaReductionOp LaunchDmaReductionOp => (LaunchDmaReductionOp)((LaunchDma >> 13) & 0x7); - public LaunchDmaReductionFormat LaunchDmaReductionFormat => (LaunchDmaReductionFormat)((LaunchDma >> 2) & 0x3); - public bool LaunchDmaSysmembarDisable => (LaunchDma & 0x40) != 0; + public readonly LaunchDmaDstMemoryLayout LaunchDmaDstMemoryLayout => (LaunchDmaDstMemoryLayout)(LaunchDma & 0x1); + public readonly LaunchDmaCompletionType LaunchDmaCompletionType => (LaunchDmaCompletionType)((LaunchDma >> 4) & 0x3); + public readonly LaunchDmaInterruptType LaunchDmaInterruptType => (LaunchDmaInterruptType)((LaunchDma >> 8) & 0x3); + public readonly LaunchDmaSemaphoreStructSize LaunchDmaSemaphoreStructSize => (LaunchDmaSemaphoreStructSize)((LaunchDma >> 12) & 0x1); + public readonly bool LaunchDmaReductionEnable => (LaunchDma & 0x2) != 0; + public readonly LaunchDmaReductionOp LaunchDmaReductionOp => (LaunchDmaReductionOp)((LaunchDma >> 13) & 0x7); + public readonly LaunchDmaReductionFormat LaunchDmaReductionFormat => (LaunchDmaReductionFormat)((LaunchDma >> 2) & 0x3); + public readonly bool LaunchDmaSysmembarDisable => (LaunchDma & 0x40) != 0; public uint LoadInlineData; public fixed uint Reserved1B8[9]; public uint SetI2mSemaphoreA; - public int SetI2mSemaphoreAOffsetUpper => (int)(SetI2mSemaphoreA & 0xFF); + public readonly int SetI2mSemaphoreAOffsetUpper => (int)(SetI2mSemaphoreA & 0xFF); public uint SetI2mSemaphoreB; public uint SetI2mSemaphoreC; public fixed uint Reserved1E8[2]; @@ -175,7 +177,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.InlineToMemory public uint SetI2mSpareNoop02; public uint SetI2mSpareNoop03; public fixed uint Reserved200[3200]; - public MmeShadowScratch SetMmeShadowScratch; + public Array256 SetMmeShadowScratch; #pragma warning restore CS0649 } } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/MME/AluOperation.cs b/src/Ryujinx.Graphics.Gpu/Engine/MME/AluOperation.cs index eeef9c67e..43faa788b 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/MME/AluOperation.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/MME/AluOperation.cs @@ -10,6 +10,6 @@ BitfieldReplace = 2, BitfieldExtractLslImm = 3, BitfieldExtractLslReg = 4, - ReadImmediate = 5 + ReadImmediate = 5, } } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/MME/AluRegOperation.cs b/src/Ryujinx.Graphics.Gpu/Engine/MME/AluRegOperation.cs index f3e05d38e..c878bd41f 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/MME/AluRegOperation.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/MME/AluRegOperation.cs @@ -13,6 +13,6 @@ BitwiseOr = 9, BitwiseAnd = 10, BitwiseAndNot = 11, - BitwiseNotAnd = 12 + BitwiseNotAnd = 12, } } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/MME/AssignmentOperation.cs b/src/Ryujinx.Graphics.Gpu/Engine/MME/AssignmentOperation.cs index dc3360266..592aa5a68 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/MME/AssignmentOperation.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/MME/AssignmentOperation.cs @@ -12,6 +12,6 @@ MoveAndSend = 4, FetchAndSetMaddr = 5, MoveAndSetMaddrThenFetchAndSend = 6, - MoveAndSetMaddrThenSendHigh = 7 + MoveAndSetMaddrThenSendHigh = 7, } } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/MME/Macro.cs b/src/Ryujinx.Graphics.Gpu/Engine/MME/Macro.cs index 12a3ac028..65c6aab4a 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/MME/Macro.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/MME/Macro.cs @@ -48,7 +48,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME if (_executionEngine == null) { - if (GraphicsConfig.EnableMacroHLE && MacroHLETable.TryGetMacroHLEFunction(code.Slice(Position), context.Capabilities, out _hleFunction)) + if (GraphicsConfig.EnableMacroHLE && MacroHLETable.TryGetMacroHLEFunction(code[Position..], context.Capabilities, out _hleFunction)) { _executionEngine = new MacroHLE(processor, _hleFunction); } @@ -84,7 +84,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME if (_executionPending) { _executionPending = false; - _executionEngine?.Execute(code.Slice(Position), state, _argument); + _executionEngine?.Execute(code[Position..], state, _argument); } } @@ -93,7 +93,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME /// /// GPU virtual address where the command word is located /// Argument to be pushed - public void PushArgument(ulong gpuVa, int argument) + public readonly void PushArgument(ulong gpuVa, int argument) { _executionEngine?.Fifo.Enqueue(new FifoWord(gpuVa, argument)); } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLE.cs b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLE.cs index 8630bbc42..a4c4dd106 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLE.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLE.cs @@ -16,7 +16,6 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME private const int ColorStructSize = 0x40; private const int ZetaLayerCountOffset = 0x1230; - private const int IndirectDataEntrySize = 0x10; private const int IndirectIndexedDataEntrySize = 0x14; private readonly GPFifoProcessor _processor; @@ -262,10 +261,12 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME for (int i = 0; i < maxDrawCount; i++) { var count = FetchParam(); +#pragma warning disable IDE0059 // Remove unnecessary value assignment var instanceCount = FetchParam(); var firstIndex = FetchParam(); var firstVertex = FetchParam(); var firstInstance = FetchParam(); +#pragma warning restore IDE0059 if (i == 0) { diff --git a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLEFunctionName.cs b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLEFunctionName.cs index 751867fc7..9e71761b4 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLEFunctionName.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLEFunctionName.cs @@ -11,6 +11,6 @@ DrawArraysInstanced, DrawElementsInstanced, DrawElementsIndirect, - MultiDrawElementsIndirectCount + MultiDrawElementsIndirectCount, } } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLETable.cs b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLETable.cs index 719e170fd..5630756cb 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLETable.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLETable.cs @@ -46,12 +46,12 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME private static readonly TableEntry[] _table = new TableEntry[] { - new TableEntry(MacroHLEFunctionName.ClearColor, new Hash128(0xA9FB28D1DC43645A, 0xB177E5D2EAE67FB0), 0x28), - new TableEntry(MacroHLEFunctionName.ClearDepthStencil, new Hash128(0x1B96CB77D4879F4F, 0x8557032FE0C965FB), 0x24), - new TableEntry(MacroHLEFunctionName.DrawArraysInstanced, new Hash128(0x197FB416269DBC26, 0x34288C01DDA82202), 0x48), - new TableEntry(MacroHLEFunctionName.DrawElementsInstanced, new Hash128(0x1A501FD3D54EC8E0, 0x6CF570CF79DA74D6), 0x5c), - new TableEntry(MacroHLEFunctionName.DrawElementsIndirect, new Hash128(0x86A3E8E903AF8F45, 0xD35BBA07C23860A4), 0x7c), - new TableEntry(MacroHLEFunctionName.MultiDrawElementsIndirectCount, new Hash128(0x890AF57ED3FB1C37, 0x35D0C95C61F5386F), 0x19C) + new(MacroHLEFunctionName.ClearColor, new Hash128(0xA9FB28D1DC43645A, 0xB177E5D2EAE67FB0), 0x28), + new(MacroHLEFunctionName.ClearDepthStencil, new Hash128(0x1B96CB77D4879F4F, 0x8557032FE0C965FB), 0x24), + new(MacroHLEFunctionName.DrawArraysInstanced, new Hash128(0x197FB416269DBC26, 0x34288C01DDA82202), 0x48), + new(MacroHLEFunctionName.DrawElementsInstanced, new Hash128(0x1A501FD3D54EC8E0, 0x6CF570CF79DA74D6), 0x5c), + new(MacroHLEFunctionName.DrawElementsIndirect, new Hash128(0x86A3E8E903AF8F45, 0xD35BBA07C23860A4), 0x7c), + new(MacroHLEFunctionName.MultiDrawElementsIndirectCount, new Hash128(0x890AF57ED3FB1C37, 0x35D0C95C61F5386F), 0x19C), }; /// @@ -93,7 +93,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME { ref var entry = ref _table[i]; - var hash = XXHash128.ComputeHash(mc.Slice(0, entry.Length)); + var hash = XXHash128.ComputeHash(mc[..entry.Length]); if (hash == entry.Hash) { if (IsMacroHLESupported(caps, entry.Name)) diff --git a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroInterpreter.cs b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroInterpreter.cs index df6ee040e..dd60688d6 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroInterpreter.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroInterpreter.cs @@ -15,7 +15,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME /// public Queue Fifo { get; } - private int[] _gprs; + private readonly int[] _gprs; private int _methAddr; private int _methIncr; @@ -291,11 +291,16 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME return (int)result; - case AluRegOperation.BitwiseExclusiveOr: return a ^ b; - case AluRegOperation.BitwiseOr: return a | b; - case AluRegOperation.BitwiseAnd: return a & b; - case AluRegOperation.BitwiseAndNot: return a & ~b; - case AluRegOperation.BitwiseNotAnd: return ~(a & b); + case AluRegOperation.BitwiseExclusiveOr: + return a ^ b; + case AluRegOperation.BitwiseOr: + return a | b; + case AluRegOperation.BitwiseAnd: + return a & b; + case AluRegOperation.BitwiseAndNot: + return a & ~b; + case AluRegOperation.BitwiseNotAnd: + return ~(a & b); } throw new InvalidOperationException($"Invalid operation \"{aluOp}\" on instruction 0x{_opCode:X8}."); @@ -380,7 +385,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME /// Current GPU state /// Register offset to read /// GPU register value - private int Read(IDeviceState state, int reg) + private static int Read(IDeviceState state, int reg) { return state.Read(reg * 4); } @@ -397,4 +402,4 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME _methAddr += _methIncr; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroJit.cs b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroJit.cs index 4077f74ec..a23bfef12 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroJit.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroJit.cs @@ -9,7 +9,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME /// class MacroJit : IMacroEE { - private readonly MacroJitContext _context = new MacroJitContext(); + private readonly MacroJitContext _context = new(); /// /// Arguments FIFO. @@ -28,7 +28,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME { if (_execute == null) { - MacroJitCompiler compiler = new MacroJitCompiler(); + MacroJitCompiler compiler = new(); _execute = compiler.Compile(code); } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroJitCompiler.cs b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroJitCompiler.cs index f8d839fa0..d9c26c587 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroJitCompiler.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroJitCompiler.cs @@ -48,7 +48,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME /// Delegate of the host compiled code public MacroExecute Compile(ReadOnlySpan code) { - Dictionary labels = new Dictionary(); + Dictionary labels = new(); int lastTarget = 0; int i; diff --git a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroJitContext.cs b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroJitContext.cs index 52c2a11b2..5a71e3f47 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroJitContext.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroJitContext.cs @@ -12,7 +12,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME /// /// Arguments FIFO. /// - public Queue Fifo { get; } = new Queue(); + public Queue Fifo { get; } = new(); /// /// Fetches a arguments from the arguments FIFO. diff --git a/src/Ryujinx.Graphics.Gpu/Engine/MmeShadowScratch.cs b/src/Ryujinx.Graphics.Gpu/Engine/MmeShadowScratch.cs index 44cd82130..0aa6b82af 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/MmeShadowScratch.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/MmeShadowScratch.cs @@ -9,7 +9,7 @@ namespace Ryujinx.Graphics.Gpu.Engine [StructLayout(LayoutKind.Sequential, Size = 1024)] struct MmeShadowScratch { -#pragma warning disable CS0169 +#pragma warning disable CS0169 // The private field is never used private uint _e0; #pragma warning restore CS0169 public ref uint this[int index] => ref AsSpan()[index]; diff --git a/src/Ryujinx.Graphics.Gpu/Engine/SetMmeShadowRamControlMode.cs b/src/Ryujinx.Graphics.Gpu/Engine/SetMmeShadowRamControlMode.cs index 060d35cad..ebb0ff33e 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/SetMmeShadowRamControlMode.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/SetMmeShadowRamControlMode.cs @@ -10,4 +10,4 @@ namespace Ryujinx.Graphics.Gpu.Engine MethodPassthrough = 2, MethodReplay = 3, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Engine/ShaderTexture.cs b/src/Ryujinx.Graphics.Gpu/Engine/ShaderTexture.cs index e1e3085b9..40d9a97df 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/ShaderTexture.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/ShaderTexture.cs @@ -65,6 +65,7 @@ namespace Ryujinx.Graphics.Gpu.Engine { return format switch { +#pragma warning disable IDE0055 // Disable formatting TextureFormat.R8Unorm => Format.R8Unorm, TextureFormat.R8Snorm => Format.R8Snorm, TextureFormat.R8Uint => Format.R8Uint, @@ -104,7 +105,8 @@ namespace Ryujinx.Graphics.Gpu.Engine TextureFormat.R10G10B10A2Unorm => Format.R10G10B10A2Unorm, TextureFormat.R10G10B10A2Uint => Format.R10G10B10A2Uint, TextureFormat.R11G11B10Float => Format.R11G11B10Float, - _ => 0 + _ => 0, +#pragma warning restore IDE0055 }; } } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendFunctions.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendFunctions.cs index a40b9cc47..0aca39075 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendFunctions.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendFunctions.cs @@ -209,14 +209,14 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.Blender new AdvancedBlendUcode(AdvancedBlendOp.HslHue, AdvancedBlendOverlap.Conjoint, false, GenConjointHslHue), new AdvancedBlendUcode(AdvancedBlendOp.HslSaturation, AdvancedBlendOverlap.Conjoint, false, GenConjointHslSaturation), new AdvancedBlendUcode(AdvancedBlendOp.HslColor, AdvancedBlendOverlap.Conjoint, false, GenConjointHslColor), - new AdvancedBlendUcode(AdvancedBlendOp.HslLuminosity, AdvancedBlendOverlap.Conjoint, false, GenConjointHslLuminosity) + new AdvancedBlendUcode(AdvancedBlendOp.HslLuminosity, AdvancedBlendOverlap.Conjoint, false, GenConjointHslLuminosity), }; public static string GenTable() { // This can be used to generate the table on AdvancedBlendPreGenTable. - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); sb.AppendLine($"private static Dictionary _entries = new()"); sb.AppendLine("{"); @@ -4223,4 +4223,4 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.Blender return new FixedFunctionAlpha(BlendOp.MaximumGl, BlendFactor.OneGl, BlendFactor.OneGl); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendManager.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendManager.cs index 8072c6af2..b336382d4 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendManager.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendManager.cs @@ -54,12 +54,12 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.Blender /// True if the function was found, false otherwise public bool TryGetAdvancedBlend(out AdvancedBlendDescriptor descriptor) { - Span currentCode = new Span(_code); + Span currentCode = new(_code); byte codeLength = (byte)_state.State.BlendUcodeSize; if (currentCode.Length > codeLength) { - currentCode = currentCode.Slice(0, codeLength); + currentCode = currentCode[..codeLength]; } Hash128 hash = XXHash128.ComputeHash(MemoryMarshal.Cast(currentCode)); @@ -112,4 +112,4 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.Blender return true; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendPreGenTable.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendPreGenTable.cs index d35d8abf4..b6cd9def9 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendPreGenTable.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendPreGenTable.cs @@ -8,7 +8,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.Blender /// /// Advanced blend function entry. /// - struct AdvancedBlendEntry + readonly struct AdvancedBlendEntry { /// /// Advanced blend operation. @@ -270,4 +270,4 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.Blender { new Hash128(0x8652300E32D93050, 0x9460E7B449132371), new AdvancedBlendEntry(AdvancedBlendOp.HslLuminosity, AdvancedBlendOverlap.Conjoint, false, new[] { new RgbFloat(0.3f, 0.59f, 0.11f) }, new FixedFunctionAlpha(BlendUcodeEnable.EnableRGB, BlendOp.MaximumGl, BlendFactor.OneGl, BlendFactor.OneGl)) }, }; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendUcode.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendUcode.cs index f06b4bf74..d3e3abbc1 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendUcode.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendUcode.cs @@ -5,12 +5,12 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.Blender /// /// Fixed function alpha state used for a advanced blend function. /// - struct FixedFunctionAlpha + readonly struct FixedFunctionAlpha { /// /// Fixed function alpha state with alpha blending disabled. /// - public static FixedFunctionAlpha Disabled => new FixedFunctionAlpha(BlendUcodeEnable.EnableRGBA, default, default, default); + public static FixedFunctionAlpha Disabled => new(BlendUcodeEnable.EnableRGBA, default, default, default); /// /// Individual enable bits for the RGB and alpha components. @@ -68,7 +68,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.Blender /// /// Advanced blend microcode state. /// - struct AdvancedBlendUcode + readonly struct AdvancedBlendUcode { /// /// Advanced blend operation. @@ -117,10 +117,10 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.Blender Overlap = overlap; SrcPreMultiplied = srcPreMultiplied; - UcodeAssembler asm = new UcodeAssembler(); + UcodeAssembler asm = new(); Alpha = genFunc(ref asm); Code = asm.GetCode(); Constants = asm.GetConstants(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/UcodeAssembler.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/UcodeAssembler.cs index f854787e0..8e0209062 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/UcodeAssembler.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/UcodeAssembler.cs @@ -14,7 +14,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.Blender Max = 3, Rcp = 4, Add = 5, - Sub = 6 + Sub = 6, } /// @@ -29,7 +29,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.Blender LT = 4, LE = 5, GT = 6, - GE = 7 + GE = 7, } /// @@ -49,7 +49,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.Blender Temp1 = 0xa, Temp2 = 0xb, PBR = 0xc, - ConstantRGB = 0xd + ConstantRGB = 0xd, } /// @@ -64,7 +64,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.Blender Temp0 = 4, Temp1 = 5, Temp2 = 6, - PBR = 7 + PBR = 7, } /// @@ -75,7 +75,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.Blender Temp0 = 0, Temp1 = 1, Temp2 = 2, - PBR = 3 + PBR = 3, } /// @@ -88,7 +88,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.Blender RRR = 2, GGG = 3, BBB = 4, - RToA = 5 + RToA = 5, } /// @@ -99,13 +99,13 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.Blender RGB = 0, R = 1, G = 2, - B = 3 + B = 3, } /// /// Floating-point RGB color values. /// - struct RgbFloat + readonly struct RgbFloat { /// /// Red component value. @@ -139,24 +139,24 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.Blender /// /// Blend microcode destination operand, including swizzle, write mask and condition code update flag. /// - struct Dest + readonly struct Dest { - public static Dest Temp0 => new Dest(OpDst.Temp0, Swizzle.RGB, WriteMask.RGB, false); - public static Dest Temp1 => new Dest(OpDst.Temp1, Swizzle.RGB, WriteMask.RGB, false); - public static Dest Temp2 => new Dest(OpDst.Temp2, Swizzle.RGB, WriteMask.RGB, false); - public static Dest PBR => new Dest(OpDst.PBR, Swizzle.RGB, WriteMask.RGB, false); + public static Dest Temp0 => new(OpDst.Temp0, Swizzle.RGB, WriteMask.RGB, false); + public static Dest Temp1 => new(OpDst.Temp1, Swizzle.RGB, WriteMask.RGB, false); + public static Dest Temp2 => new(OpDst.Temp2, Swizzle.RGB, WriteMask.RGB, false); + public static Dest PBR => new(OpDst.PBR, Swizzle.RGB, WriteMask.RGB, false); - public Dest GBR => new Dest(Dst, Swizzle.GBR, WriteMask, WriteCC); - public Dest RRR => new Dest(Dst, Swizzle.RRR, WriteMask, WriteCC); - public Dest GGG => new Dest(Dst, Swizzle.GGG, WriteMask, WriteCC); - public Dest BBB => new Dest(Dst, Swizzle.BBB, WriteMask, WriteCC); - public Dest RToA => new Dest(Dst, Swizzle.RToA, WriteMask, WriteCC); + public Dest GBR => new(Dst, Swizzle.GBR, WriteMask, WriteCC); + public Dest RRR => new(Dst, Swizzle.RRR, WriteMask, WriteCC); + public Dest GGG => new(Dst, Swizzle.GGG, WriteMask, WriteCC); + public Dest BBB => new(Dst, Swizzle.BBB, WriteMask, WriteCC); + public Dest RToA => new(Dst, Swizzle.RToA, WriteMask, WriteCC); - public Dest R => new Dest(Dst, Swizzle, WriteMask.R, WriteCC); - public Dest G => new Dest(Dst, Swizzle, WriteMask.G, WriteCC); - public Dest B => new Dest(Dst, Swizzle, WriteMask.B, WriteCC); + public Dest R => new(Dst, Swizzle, WriteMask.R, WriteCC); + public Dest G => new(Dst, Swizzle, WriteMask.G, WriteCC); + public Dest B => new(Dst, Swizzle, WriteMask.B, WriteCC); - public Dest CC => new Dest(Dst, Swizzle, WriteMask, true); + public Dest CC => new(Dst, Swizzle, WriteMask, true); public OpDst Dst { get; } public Swizzle Swizzle { get; } @@ -182,7 +182,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.Blender /// /// Blend microcode operaiton. /// - struct UcodeOp + readonly struct UcodeOp { public readonly uint Word; @@ -292,14 +292,14 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.Blender _constantIndex = index; } - public uint[] GetCode() + public readonly uint[] GetCode() { return _code?.ToArray(); } - public RgbFloat[] GetConstants() + public readonly RgbFloat[] GetConstants() { return _constants; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/ConstantBufferUpdater.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/ConstantBufferUpdater.cs index 5c9366160..e30092cee 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/ConstantBufferUpdater.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/ConstantBufferUpdater.cs @@ -19,7 +19,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed private ulong _ubFollowUpAddress = 0; private ulong _ubByteCount = 0; private int _ubIndex = 0; - private int[] _ubData = new int[UniformDataCacheSize]; + private readonly int[] _ubData = new int[UniformDataCacheSize]; /// /// Creates a new instance of the constant buffer updater. diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/DrawManager.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/DrawManager.cs index 9c4921c8b..d7ee24b19 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/DrawManager.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/DrawManager.cs @@ -186,7 +186,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed { int firstVertex = (int)_state.State.FirstVertex; - BufferRange br = new BufferRange(_drawState.IbStreamer.GetInlineIndexBuffer(), 0, inlineIndexCount * 4); + BufferRange br = new(_drawState.IbStreamer.GetInlineIndexBuffer(), 0, inlineIndexCount * 4); _channel.BufferManager.SetIndexBuffer(br, IndexType.UInt); @@ -200,7 +200,9 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed } else { +#pragma warning disable IDE0059 // Remove unnecessary value assignment var drawState = _state.State.VertexBufferDrawState; +#pragma warning restore IDE0059 _context.Renderer.Pipeline.Draw(drawVertexCount, 1, drawFirstVertex, firstInstance); } @@ -679,7 +681,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed if (indexedInline) { int inlineIndexCount = _drawState.IbStreamer.GetAndResetInlineIndexCount(_context.Renderer); - BufferRange br = new BufferRange(_drawState.IbStreamer.GetInlineIndexBuffer(), 0, inlineIndexCount * 4); + BufferRange br = new(_drawState.IbStreamer.GetInlineIndexBuffer(), 0, inlineIndexCount * 4); _channel.BufferManager.SetIndexBuffer(br, IndexType.UInt); } @@ -809,7 +811,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed Span> scissors = stackalloc Rectangle[] { - new Rectangle(scissorX, scissorY, scissorW, scissorH) + new Rectangle(scissorX, scissorY, scissorW, scissorH), }; _context.Renderer.Pipeline.SetScissors(scissors); @@ -821,7 +823,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed { var clearColor = _state.State.ClearColors; - ColorF color = new ColorF(clearColor.Red, clearColor.Green, clearColor.Blue, clearColor.Alpha); + ColorF color = new(clearColor.Red, clearColor.Green, clearColor.Blue, clearColor.Alpha); _context.Renderer.Pipeline.ClearRenderTargetColor(index, layer, layerCount, componentMask, color); } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/DrawState.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/DrawState.cs index 42ec2442e..12099aef9 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/DrawState.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/DrawState.cs @@ -60,6 +60,6 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// /// Index buffer data streamer for inline index buffer updates, such as those used in legacy OpenGL. /// - public IbStreamer IbStreamer = new IbStreamer(); + public IbStreamer IbStreamer = new(); } } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/IbStreamer.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/IbStreamer.cs index 80d8c00b9..022e12f57 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/IbStreamer.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/IbStreamer.cs @@ -1,6 +1,5 @@ using Ryujinx.Common; using Ryujinx.Graphics.GAL; -using System; using System.Runtime.InteropServices; namespace Ryujinx.Graphics.Gpu.Engine.Threed @@ -17,33 +16,35 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed private int _inlineIndexBufferSize; private int _inlineIndexCount; private uint[] _buffer; - private int _bufferOffset; +#pragma warning disable IDE0051 // Remove unused private member + private readonly int _bufferOffset; +#pragma warning restore IDE0051 /// /// Indicates if any index buffer data has been pushed. /// - public bool HasInlineIndexData => _inlineIndexCount != 0; + public readonly bool HasInlineIndexData => _inlineIndexCount != 0; /// /// Total numbers of indices that have been pushed. /// - public int InlineIndexCount => _inlineIndexCount; + public readonly int InlineIndexCount => _inlineIndexCount; /// /// Gets the handle for the host buffer currently holding the inline index buffer data. /// /// Host buffer handle - public BufferHandle GetInlineIndexBuffer() + public readonly BufferHandle GetInlineIndexBuffer() { return _inlineIndexBuffer; } /// /// Gets the number of elements on the current inline index buffer, - /// while also reseting it to zero for the next draw. + /// while also resetting it to zero for the next draw. /// /// Host renderer - /// Inline index bufffer count + /// Inline index buffer count public int GetAndResetInlineIndexCount(IRenderer renderer) { UpdateRemaining(renderer); @@ -114,10 +115,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Index value to be written private void PushData(IRenderer renderer, int offset, uint value) { - if (_buffer == null) - { - _buffer = new uint[BufferCapacity]; - } + _buffer ??= new uint[BufferCapacity]; // We upload data in chunks. // If we are at the start of a chunk, then the buffer might be full, @@ -155,7 +153,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed int baseOffset = (offset - count) * sizeof(uint); int length = count * sizeof(uint); BufferHandle buffer = GetInlineIndexBuffer(renderer, baseOffset, length); - renderer.SetBufferData(buffer, baseOffset, MemoryMarshal.Cast(_buffer).Slice(0, length)); + renderer.SetBufferData(buffer, baseOffset, MemoryMarshal.Cast(_buffer)[..length]); } /// diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/IndirectDrawType.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/IndirectDrawType.cs index d78aa4982..331b1976b 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/IndirectDrawType.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/IndirectDrawType.cs @@ -1,8 +1,11 @@ +using System.Diagnostics.CodeAnalysis; + namespace Ryujinx.Graphics.Gpu.Engine.Threed { /// /// Indirect draw type, which can be indexed or non-indexed, with or without a draw count. /// + [SuppressMessage("Design", "CA1069: Enums values should not be duplicated")] enum IndirectDrawType { /// @@ -33,6 +36,6 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// /// Draw count flag. /// - Count = 1 << 1 + Count = 1 << 1, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/RenderTargetUpdateFlags.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/RenderTargetUpdateFlags.cs index cf2e818ce..e575923d9 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/RenderTargetUpdateFlags.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/RenderTargetUpdateFlags.cs @@ -36,6 +36,6 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// /// Default update flags for draw. /// - UpdateAll = UseControl | UpdateDepthStencil + UpdateAll = UseControl | UpdateDepthStencil, } } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/SemaphoreUpdater.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/SemaphoreUpdater.cs index 63a2c841c..0a813ee55 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/SemaphoreUpdater.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/SemaphoreUpdater.cs @@ -1,5 +1,4 @@ using Ryujinx.Graphics.GAL; -using System; namespace Ryujinx.Graphics.Gpu.Engine.Threed { @@ -15,7 +14,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed { Release = 0, Acquire = 1, - Counter = 2 + Counter = 2, } /// @@ -37,7 +36,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed ClipperInputPrimitives = 0x1c, ClipperOutputPrimitives = 0x1d, FragmentShaderInvocations = 0x1e, - PrimitivesGenerated = 0x1f + PrimitivesGenerated = 0x1f, } /// @@ -64,7 +63,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed TransformFeedbackOffset = 0x1a, TessControlShaderInvocations = 0x1b, TessEvaluationShaderInvocations = 0x1d, - TessEvaluationShaderPrimitives = 0x1f + TessEvaluationShaderPrimitives = 0x1f, } private readonly GpuContext _context; @@ -117,8 +116,12 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed switch (op) { - case SemaphoreOperation.Release: ReleaseSemaphore(); break; - case SemaphoreOperation.Counter: ReportCounter(type); break; + case SemaphoreOperation.Release: + ReleaseSemaphore(); + break; + case SemaphoreOperation.Counter: + ReportCounter(type); + break; } } @@ -156,10 +159,10 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed void resultHandler(object evt, ulong result) { - CounterData counterData = new CounterData + CounterData counterData = new() { Counter = result, - Timestamp = ticks + Timestamp = ticks, }; if (counter?.Invalid != true) diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/SpecializationStateUpdater.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/SpecializationStateUpdater.cs index a8af54970..cbf1573cd 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/SpecializationStateUpdater.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/SpecializationStateUpdater.cs @@ -227,7 +227,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed { VertexAttribType.Sint => AttributeType.Sint, VertexAttribType.Uint => AttributeType.Uint, - _ => AttributeType.Float + _ => AttributeType.Float, }; if (attributeTypes[location] != value) diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/StateUpdater.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/StateUpdater.cs index 92e980ced..34439657e 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/StateUpdater.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/StateUpdater.cs @@ -33,7 +33,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed private readonly ShaderProgramInfo[] _currentProgramInfo; private ShaderSpecializationState _shaderSpecState; - private SpecializationStateUpdater _currentSpecState; + private readonly SpecializationStateUpdater _currentSpecState; private ProgramPipelineState _pipeline; @@ -43,7 +43,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed private uint _vbEnableMask; private bool _prevDrawIndexed; - private bool _prevDrawIndirect; + private readonly bool _prevDrawIndirect; private IndexType _prevIndexType; private uint _prevFirstVertex; private bool _prevTfEnable; @@ -448,7 +448,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed int samplesInY = msaaMode.SamplesInY(); var scissor = _state.State.ScreenScissorState; - Size sizeHint = new Size((scissor.X + scissor.Width) * samplesInX, (scissor.Y + scissor.Height) * samplesInY, 1); + Size sizeHint = new((scissor.X + scissor.Width) * samplesInX, (scissor.Y + scissor.Height) * samplesInY, 1); int clipRegionWidth = int.MaxValue; int clipRegionHeight = int.MaxValue; @@ -669,7 +669,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// private void UpdateDepthTestState() { - DepthTestDescriptor descriptor = new DepthTestDescriptor( + DepthTestDescriptor descriptor = new( _state.State.DepthTestEnable, _state.State.DepthWriteEnable, _state.State.DepthTestFunc); @@ -739,7 +739,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed height *= scale; } - Rectangle region = new Rectangle(x, y, width, height); + Rectangle region = new(x, y, width, height); ViewportSwizzle swizzleX = transform.UnpackSwizzleX(); ViewportSwizzle swizzleY = transform.UnpackSwizzleY(); @@ -751,9 +751,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed if (transform.ScaleZ < 0) { - float temp = depthNear; - depthNear = depthFar; - depthFar = temp; + (depthFar, depthNear) = (depthNear, depthFar); } viewports[index] = new Viewport(region, swizzleX, swizzleY, swizzleZ, swizzleW, depthNear, depthFar); @@ -845,7 +843,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed backMask = test.FrontMask; } - StencilTestDescriptor descriptor = new StencilTestDescriptor( + StencilTestDescriptor descriptor = new( test.Enable, test.FrontFunc, test.FrontSFail, @@ -939,7 +937,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed { VertexAttribType.Sint => Format.R32G32B32A32Sint, VertexAttribType.Uint => Format.R32G32B32A32Uint, - _ => Format.R32G32B32A32Float + _ => Format.R32G32B32A32Float, }; } @@ -1017,8 +1015,12 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed switch (indexBuffer.Type) { - case IndexType.UShort: size *= 2; break; - case IndexType.UInt: size *= 4; break; + case IndexType.UShort: + size *= 2; + break; + case IndexType.UInt: + size *= 4; + break; } _channel.BufferManager.SetIndexBuffer(gpuVa, size, indexBuffer.Type); @@ -1338,7 +1340,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed _vtgWritesRtLayer = false; - ShaderAddresses addresses = new ShaderAddresses(); + ShaderAddresses addresses = new(); Span addressesSpan = addresses.AsSpan(); ulong baseAddress = _state.State.ShaderBaseAddress.Pack(); @@ -1453,7 +1455,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed // ScaleZ = (Far - Near) / 2 // DepthNear/Far are sorted such as that Near is always less than Far. depthMode = extents.DepthNear != transform.TranslateZ && - extents.DepthFar != transform.TranslateZ + extents.DepthFar != transform.TranslateZ ? DepthMode.MinusOneToOne : DepthMode.ZeroToOne; } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/ThreedClass.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/ThreedClass.cs index 1386071cf..1f6628909 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/ThreedClass.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/ThreedClass.cs @@ -71,7 +71,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed { nameof(ThreedClassState.UniformBufferBindTessControl), new RwCallback(ConstantBufferBindTessControl, null) }, { nameof(ThreedClassState.UniformBufferBindTessEvaluation), new RwCallback(ConstantBufferBindTessEvaluation, null) }, { nameof(ThreedClassState.UniformBufferBindGeometry), new RwCallback(ConstantBufferBindGeometry, null) }, - { nameof(ThreedClassState.UniformBufferBindFragment), new RwCallback(ConstantBufferBindFragment, null) } + { nameof(ThreedClassState.UniformBufferBindFragment), new RwCallback(ConstantBufferBindFragment, null) }, }); _i2mClass = new InlineToMemoryClass(context, channel, initializeState: false); diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/ThreedClassState.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/ThreedClassState.cs index beda2dbfe..f2997678c 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/ThreedClassState.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/ThreedClassState.cs @@ -18,7 +18,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed TessellationControl, TessellationEvaluation, Geometry, - Fragment + Fragment, } /// @@ -26,7 +26,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct TessMode { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public uint Packed; #pragma warning restore CS0649 @@ -34,7 +34,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Unpacks the tessellation abstract patch type. /// /// Abtract patch type - public TessPatchType UnpackPatchType() + public readonly TessPatchType UnpackPatchType() { return (TessPatchType)(Packed & 3); } @@ -43,7 +43,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Unpacks the spacing between tessellated vertices of the patch. /// /// Spacing between tessellated vertices - public TessSpacing UnpackSpacing() + public readonly TessSpacing UnpackSpacing() { return (TessSpacing)((Packed >> 4) & 3); } @@ -52,7 +52,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Unpacks the primitive winding order. /// /// True if clockwise, false if counter-clockwise - public bool UnpackCw() + public readonly bool UnpackCw() { return (Packed & (1 << 8)) != 0; } @@ -63,7 +63,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct TfBufferState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public Boolean32 Enable; public GpuVa Address; public int Size; @@ -79,7 +79,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct TfState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public int BufferIndex; public int VaryingsCount; public int Stride; @@ -92,7 +92,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct RtColorState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public GpuVa Address; public int WidthOrStride; public int Height; @@ -116,7 +116,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct ViewportTransform { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public float ScaleX; public float ScaleY; public float ScaleZ; @@ -131,7 +131,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Unpacks viewport swizzle of the position X component. /// /// Swizzle enum value - public ViewportSwizzle UnpackSwizzleX() + public readonly ViewportSwizzle UnpackSwizzleX() { return (ViewportSwizzle)(Swizzle & 7); } @@ -140,7 +140,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Unpacks viewport swizzle of the position Y component. /// /// Swizzle enum value - public ViewportSwizzle UnpackSwizzleY() + public readonly ViewportSwizzle UnpackSwizzleY() { return (ViewportSwizzle)((Swizzle >> 4) & 7); } @@ -149,7 +149,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Unpacks viewport swizzle of the position Z component. /// /// Swizzle enum value - public ViewportSwizzle UnpackSwizzleZ() + public readonly ViewportSwizzle UnpackSwizzleZ() { return (ViewportSwizzle)((Swizzle >> 8) & 7); } @@ -158,7 +158,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Unpacks viewport swizzle of the position W component. /// /// Swizzle enum value - public ViewportSwizzle UnpackSwizzleW() + public readonly ViewportSwizzle UnpackSwizzleW() { return (ViewportSwizzle)((Swizzle >> 12) & 7); } @@ -169,7 +169,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct ViewportExtents { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public ushort X; public ushort Width; public ushort Y; @@ -184,7 +184,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct VertexBufferDrawState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public int First; public int Count; #pragma warning restore CS0649 @@ -195,7 +195,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct ClearColors { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public float Red; public float Green; public float Blue; @@ -208,7 +208,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct DepthBiasState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public Boolean32 PointEnable; public Boolean32 LineEnable; public Boolean32 FillEnable; @@ -223,7 +223,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed Disabled = 0, EnableRGB = 1, EnableAlpha = 2, - EnableRGBA = 3 + EnableRGBA = 3, } /// @@ -231,7 +231,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct ScissorState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public Boolean32 Enable; public ushort X1; public ushort X2; @@ -246,7 +246,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct StencilBackMasks { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public int FuncRef; public int Mask; public int FuncMask; @@ -258,7 +258,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct RtDepthStencilState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public GpuVa Address; public ZetaFormat Format; public MemoryLayout MemoryLayout; @@ -271,7 +271,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct ScreenScissorState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public ushort X; public ushort Width; public ushort Y; @@ -297,7 +297,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed Size16 = 0x1b, Size8 = 0x1d, Rgb10A2 = 0x30, - Rg11B10 = 0x31 + Rg11B10 = 0x31, } /// @@ -311,7 +311,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed Uint = 4, Uscaled = 5, Sscaled = 6, - Float = 7 + Float = 7, } /// @@ -319,7 +319,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct VertexAttribState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public uint Attribute; #pragma warning restore CS0649 @@ -327,7 +327,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Unpacks the index of the vertex buffer this attribute belongs to. /// /// Vertex buffer index - public int UnpackBufferIndex() + public readonly int UnpackBufferIndex() { return (int)(Attribute & 0x1f); } @@ -336,7 +336,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Unpacks the attribute constant flag. /// /// True if the attribute is constant, false otherwise - public bool UnpackIsConstant() + public readonly bool UnpackIsConstant() { return (Attribute & 0x40) != 0; } @@ -345,7 +345,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Unpacks the offset, in bytes, of the attribute on the vertex buffer. /// /// Attribute offset in bytes - public int UnpackOffset() + public readonly int UnpackOffset() { return (int)((Attribute >> 7) & 0x3fff); } @@ -354,7 +354,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Unpacks the Maxwell attribute format integer. /// /// Attribute format integer - public uint UnpackFormat() + public readonly uint UnpackFormat() { return Attribute & 0x3fe00000; } @@ -363,7 +363,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Unpacks the Maxwell attribute size. /// /// Attribute size - public VertexAttribSize UnpackSize() + public readonly VertexAttribSize UnpackSize() { return (VertexAttribSize)((Attribute >> 21) & 0x3f); } @@ -372,7 +372,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Unpacks the Maxwell attribute component type. /// /// Attribute component type - public VertexAttribType UnpackType() + public readonly VertexAttribType UnpackType() { return (VertexAttribType)((Attribute >> 27) & 7); } @@ -383,7 +383,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct RtControl { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public uint Packed; #pragma warning restore CS0649 @@ -391,7 +391,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Unpacks the number of active draw buffers. /// /// Number of active draw buffers - public int UnpackCount() + public readonly int UnpackCount() { return (int)(Packed & 0xf); } @@ -401,7 +401,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// /// Index of the draw buffer /// Attachment index - public int UnpackPermutationIndex(int index) + public readonly int UnpackPermutationIndex(int index) { return (int)((Packed >> (4 + index * 3)) & 7); } @@ -412,7 +412,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct Size3D { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public int Width; public int Height; public int Depth; @@ -424,7 +424,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct StencilTestState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public Boolean32 Enable; public StencilOp FrontSFail; public StencilOp FrontDpFail; @@ -443,7 +443,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed enum YControl { NegateY = 1 << 0, - TriangleRastFlip = 1 << 4 + TriangleRastFlip = 1 << 4, } /// @@ -451,7 +451,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct RgbHalf { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public uint R; public uint G; public uint B; @@ -462,7 +462,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Unpacks the red color component as a 16-bit float value. /// /// The component value - public Half UnpackR() + public readonly Half UnpackR() { ushort value = (ushort)R; return Unsafe.As(ref value); @@ -472,7 +472,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Unpacks the green color component as a 16-bit float value. /// /// The component value - public Half UnpackG() + public readonly Half UnpackG() { ushort value = (ushort)G; return Unsafe.As(ref value); @@ -482,7 +482,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Unpacks the blue color component as a 16-bit float value. /// /// The component value - public Half UnpackB() + public readonly Half UnpackB() { ushort value = (ushort)B; return Unsafe.As(ref value); @@ -498,7 +498,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed Always, ResultNonZero, Equal, - NotEqual + NotEqual, } /// @@ -506,7 +506,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct PoolState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public GpuVa Address; public int MaximumId; #pragma warning restore CS0649 @@ -517,7 +517,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct StencilBackTestState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public Boolean32 TwoSided; public StencilOp BackSFail; public StencilOp BackDpFail; @@ -531,7 +531,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct PrimitiveRestartState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public Boolean32 Enable; public int Index; #pragma warning restore CS0649 @@ -543,7 +543,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct IndexBufferState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public GpuVa Address; public GpuVa EndAddress; public IndexType Type; @@ -556,7 +556,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct FaceState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public Boolean32 CullEnable; public FrontFace FrontFace; public Face CullFace; @@ -570,7 +570,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed enum ViewVolumeClipControl { ForceDepthRangeZeroToOne = 1 << 0, - DepthClampDisabled = 1 << 11 + DepthClampDisabled = 1 << 11, } /// @@ -578,7 +578,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct LogicalOpState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public Boolean32 Enable; public LogicalOp LogicalOp; #pragma warning restore CS0649 @@ -590,7 +590,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct RtColorMask { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public uint Packed; #pragma warning restore CS0649 @@ -598,7 +598,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Unpacks red channel enable. /// /// True to write the new red channel color, false to keep the old value - public bool UnpackRed() + public readonly bool UnpackRed() { return (Packed & 0x1) != 0; } @@ -607,7 +607,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Unpacks green channel enable. /// /// True to write the new green channel color, false to keep the old value - public bool UnpackGreen() + public readonly bool UnpackGreen() { return (Packed & 0x10) != 0; } @@ -616,7 +616,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Unpacks blue channel enable. /// /// True to write the new blue channel color, false to keep the old value - public bool UnpackBlue() + public readonly bool UnpackBlue() { return (Packed & 0x100) != 0; } @@ -625,7 +625,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Unpacks alpha channel enable. /// /// True to write the new alpha channel color, false to keep the old value - public bool UnpackAlpha() + public readonly bool UnpackAlpha() { return (Packed & 0x1000) != 0; } @@ -636,7 +636,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct VertexBufferState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public uint Control; public GpuVa Address; public int Divisor; @@ -646,7 +646,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Vertex buffer stride, defined as the number of bytes occupied by each vertex in memory. /// /// Vertex buffer stride - public int UnpackStride() + public readonly int UnpackStride() { return (int)(Control & 0xfff); } @@ -655,7 +655,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Vertex buffer enable. /// /// True if the vertex buffer is enabled, false otherwise - public bool UnpackEnable() + public readonly bool UnpackEnable() { return (Control & (1 << 12)) != 0; } @@ -666,7 +666,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct BlendStateCommon { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public Boolean32 SeparateAlpha; public BlendOp ColorOp; public BlendFactor ColorSrcFactor; @@ -683,7 +683,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct BlendState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public Boolean32 SeparateAlpha; public BlendOp ColorOp; public BlendFactor ColorSrcFactor; @@ -700,7 +700,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct ShaderState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public uint Control; public uint Offset; public uint Unknown0x8; @@ -724,7 +724,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Must be ignored for vertex shaders, those are always enabled. /// /// True if the stage is enabled, false otherwise - public bool UnpackEnable() + public readonly bool UnpackEnable() { return (Control & 1) != 0; } @@ -735,7 +735,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// struct UniformBufferState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public int Size; public GpuVa Address; public int Offset; @@ -744,30 +744,30 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed unsafe struct ThreedClassState : IShadowState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public uint SetObject; - public int SetObjectClassId => (int)(SetObject & 0xFFFF); - public int SetObjectEngineId => (int)((SetObject >> 16) & 0x1F); + public readonly int SetObjectClassId => (int)(SetObject & 0xFFFF); + public readonly int SetObjectEngineId => (int)((SetObject >> 16) & 0x1F); public fixed uint Reserved04[63]; public uint NoOperation; public uint SetNotifyA; - public int SetNotifyAAddressUpper => (int)(SetNotifyA & 0xFF); + public readonly int SetNotifyAAddressUpper => (int)(SetNotifyA & 0xFF); public uint SetNotifyB; public uint Notify; - public NotifyType NotifyType => (NotifyType)(Notify); + public readonly NotifyType NotifyType => (NotifyType)(Notify); public uint WaitForIdle; public uint LoadMmeInstructionRamPointer; public uint LoadMmeInstructionRam; public uint LoadMmeStartAddressRamPointer; public uint LoadMmeStartAddressRam; public uint SetMmeShadowRamControl; - public SetMmeShadowRamControlMode SetMmeShadowRamControlMode => (SetMmeShadowRamControlMode)(SetMmeShadowRamControl & 0x3); + public readonly SetMmeShadowRamControlMode SetMmeShadowRamControlMode => (SetMmeShadowRamControlMode)(SetMmeShadowRamControl & 0x3); public fixed uint Reserved128[2]; public uint SetGlobalRenderEnableA; - public int SetGlobalRenderEnableAOffsetUpper => (int)(SetGlobalRenderEnableA & 0xFF); + public readonly int SetGlobalRenderEnableAOffsetUpper => (int)(SetGlobalRenderEnableA & 0xFF); public uint SetGlobalRenderEnableB; public uint SetGlobalRenderEnableC; - public int SetGlobalRenderEnableCMode => (int)(SetGlobalRenderEnableC & 0x7); + public readonly int SetGlobalRenderEnableCMode => (int)(SetGlobalRenderEnableC & 0x7); public uint SendGoIdle; public uint PmTrigger; public uint PmTriggerWfi; @@ -778,30 +778,30 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed public uint LineLengthIn; public uint LineCount; public uint OffsetOutUpper; - public int OffsetOutUpperValue => (int)(OffsetOutUpper & 0xFF); + public readonly int OffsetOutUpperValue => (int)(OffsetOutUpper & 0xFF); public uint OffsetOut; public uint PitchOut; public uint SetDstBlockSize; - public SetDstBlockSizeWidth SetDstBlockSizeWidth => (SetDstBlockSizeWidth)(SetDstBlockSize & 0xF); - public SetDstBlockSizeHeight SetDstBlockSizeHeight => (SetDstBlockSizeHeight)((SetDstBlockSize >> 4) & 0xF); - public SetDstBlockSizeDepth SetDstBlockSizeDepth => (SetDstBlockSizeDepth)((SetDstBlockSize >> 8) & 0xF); + public readonly SetDstBlockSizeWidth SetDstBlockSizeWidth => (SetDstBlockSizeWidth)(SetDstBlockSize & 0xF); + public readonly SetDstBlockSizeHeight SetDstBlockSizeHeight => (SetDstBlockSizeHeight)((SetDstBlockSize >> 4) & 0xF); + public readonly SetDstBlockSizeDepth SetDstBlockSizeDepth => (SetDstBlockSizeDepth)((SetDstBlockSize >> 8) & 0xF); public uint SetDstWidth; public uint SetDstHeight; public uint SetDstDepth; public uint SetDstLayer; public uint SetDstOriginBytesX; - public int SetDstOriginBytesXV => (int)(SetDstOriginBytesX & 0xFFFFF); + public readonly int SetDstOriginBytesXV => (int)(SetDstOriginBytesX & 0xFFFFF); public uint SetDstOriginSamplesY; - public int SetDstOriginSamplesYV => (int)(SetDstOriginSamplesY & 0xFFFF); + public readonly int SetDstOriginSamplesYV => (int)(SetDstOriginSamplesY & 0xFFFF); public uint LaunchDma; - public LaunchDmaDstMemoryLayout LaunchDmaDstMemoryLayout => (LaunchDmaDstMemoryLayout)(LaunchDma & 0x1); - public LaunchDmaCompletionType LaunchDmaCompletionType => (LaunchDmaCompletionType)((LaunchDma >> 4) & 0x3); - public LaunchDmaInterruptType LaunchDmaInterruptType => (LaunchDmaInterruptType)((LaunchDma >> 8) & 0x3); - public LaunchDmaSemaphoreStructSize LaunchDmaSemaphoreStructSize => (LaunchDmaSemaphoreStructSize)((LaunchDma >> 12) & 0x1); - public bool LaunchDmaReductionEnable => (LaunchDma & 0x2) != 0; - public LaunchDmaReductionOp LaunchDmaReductionOp => (LaunchDmaReductionOp)((LaunchDma >> 13) & 0x7); - public LaunchDmaReductionFormat LaunchDmaReductionFormat => (LaunchDmaReductionFormat)((LaunchDma >> 2) & 0x3); - public bool LaunchDmaSysmembarDisable => (LaunchDma & 0x40) != 0; + public readonly LaunchDmaDstMemoryLayout LaunchDmaDstMemoryLayout => (LaunchDmaDstMemoryLayout)(LaunchDma & 0x1); + public readonly LaunchDmaCompletionType LaunchDmaCompletionType => (LaunchDmaCompletionType)((LaunchDma >> 4) & 0x3); + public readonly LaunchDmaInterruptType LaunchDmaInterruptType => (LaunchDmaInterruptType)((LaunchDma >> 8) & 0x3); + public readonly LaunchDmaSemaphoreStructSize LaunchDmaSemaphoreStructSize => (LaunchDmaSemaphoreStructSize)((LaunchDma >> 12) & 0x1); + public readonly bool LaunchDmaReductionEnable => (LaunchDma & 0x2) != 0; + public readonly LaunchDmaReductionOp LaunchDmaReductionOp => (LaunchDmaReductionOp)((LaunchDma >> 13) & 0x7); + public readonly LaunchDmaReductionFormat LaunchDmaReductionFormat => (LaunchDmaReductionFormat)((LaunchDma >> 2) & 0x3); + public readonly bool LaunchDmaSysmembarDisable => (LaunchDma & 0x40) != 0; public uint LoadInlineData; public fixed uint Reserved1B8[22]; public Boolean32 EarlyZForce; @@ -1042,7 +1042,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed public fixed uint Reserved260C[125]; public Array4> TfVaryingLocations; public fixed uint Reserved2A00[640]; - public MmeShadowScratch SetMmeShadowScratch; + public Array256 SetMmeShadowScratch; #pragma warning restore CS0649 } } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Twod/TwodClass.cs b/src/Ryujinx.Graphics.Gpu/Engine/Twod/TwodClass.cs index 2ac84ab50..b33fb7f73 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Twod/TwodClass.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Twod/TwodClass.cs @@ -30,7 +30,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod _channel = channel; _state = new DeviceState(new Dictionary { - { nameof(TwodClassState.PixelsFromMemorySrcY0Int), new RwCallback(PixelsFromMemorySrcY0Int, null) } + { nameof(TwodClassState.PixelsFromMemorySrcY0Int), new RwCallback(PixelsFromMemorySrcY0Int, null) }, }); } @@ -57,7 +57,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod /// Format of the first texture /// Format of the second texture /// True if the data is compatible, false otherwise - private bool IsDataCompatible(TwodTexture lhs, TwodTexture rhs, FormatInfo lhsFormat, FormatInfo rhsFormat) + private static bool IsDataCompatible(TwodTexture lhs, TwodTexture rhs, FormatInfo lhsFormat, FormatInfo rhsFormat) { if (lhsFormat.BytesPerPixel != rhsFormat.BytesPerPixel || lhs.Height != rhs.Height || @@ -88,7 +88,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod /// Region end x /// Region end y /// True if the region covers the full texture, false otherwise - private bool IsCopyRegionComplete(TwodTexture texture, FormatInfo formatInfo, int x1, int y1, int x2, int y2) + private static bool IsCopyRegionComplete(TwodTexture texture, FormatInfo formatInfo, int x1, int y1, int x2, int y2) { if (x1 != 0 || y1 != 0 || y2 != texture.Height) { @@ -172,7 +172,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod for (int y = 0; y < height; y++) { - srcSpan.Slice(offset, lineSize).CopyTo(dstSpan.Slice(offset)); + srcSpan.Slice(offset, lineSize).CopyTo(dstSpan[offset..]); offset += stride; } @@ -364,13 +364,13 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod float scale = srcTexture.ScaleFactor; float dstScale = dstTexture.ScaleFactor; - Extents2D srcRegion = new Extents2D( + Extents2D srcRegion = new( (int)Math.Ceiling(scale * (srcX1 / srcTexture.Info.SamplesInX)), (int)Math.Ceiling(scale * (srcY1 / srcTexture.Info.SamplesInY)), (int)Math.Ceiling(scale * (srcX2 / srcTexture.Info.SamplesInX)), (int)Math.Ceiling(scale * (srcY2 / srcTexture.Info.SamplesInY))); - Extents2D dstRegion = new Extents2D( + Extents2D dstRegion = new( (int)Math.Ceiling(dstScale * (dstX1 / dstTexture.Info.SamplesInX)), (int)Math.Ceiling(dstScale * (dstY1 / dstTexture.Info.SamplesInY)), (int)Math.Ceiling(dstScale * (dstX2 / dstTexture.Info.SamplesInX)), diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Twod/TwodClassState.cs b/src/Ryujinx.Graphics.Gpu/Engine/Twod/TwodClassState.cs index 55e5019fc..edea73273 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Twod/TwodClassState.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Twod/TwodClassState.cs @@ -486,7 +486,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod /// struct RenderSolidPrimPoint { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public uint SetX; public uint Y; #pragma warning restore CS0649 @@ -497,30 +497,30 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod /// unsafe struct TwodClassState : IShadowState { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public uint SetObject; - public int SetObjectClassId => (int)(SetObject & 0xFFFF); - public int SetObjectEngineId => (int)((SetObject >> 16) & 0x1F); + public readonly int SetObjectClassId => (int)(SetObject & 0xFFFF); + public readonly int SetObjectEngineId => (int)((SetObject >> 16) & 0x1F); public fixed uint Reserved04[63]; public uint NoOperation; public uint SetNotifyA; - public int SetNotifyAAddressUpper => (int)(SetNotifyA & 0x1FFFFFF); + public readonly int SetNotifyAAddressUpper => (int)(SetNotifyA & 0x1FFFFFF); public uint SetNotifyB; public uint Notify; - public NotifyType NotifyType => (NotifyType)(Notify); + public readonly NotifyType NotifyType => (NotifyType)(Notify); public uint WaitForIdle; public uint LoadMmeInstructionRamPointer; public uint LoadMmeInstructionRam; public uint LoadMmeStartAddressRamPointer; public uint LoadMmeStartAddressRam; public uint SetMmeShadowRamControl; - public SetMmeShadowRamControlMode SetMmeShadowRamControlMode => (SetMmeShadowRamControlMode)(SetMmeShadowRamControl & 0x3); + public readonly SetMmeShadowRamControlMode SetMmeShadowRamControlMode => (SetMmeShadowRamControlMode)(SetMmeShadowRamControl & 0x3); public fixed uint Reserved128[2]; public uint SetGlobalRenderEnableA; - public int SetGlobalRenderEnableAOffsetUpper => (int)(SetGlobalRenderEnableA & 0xFF); + public readonly int SetGlobalRenderEnableAOffsetUpper => (int)(SetGlobalRenderEnableA & 0xFF); public uint SetGlobalRenderEnableB; public uint SetGlobalRenderEnableC; - public int SetGlobalRenderEnableCMode => (int)(SetGlobalRenderEnableC & 0x7); + public readonly int SetGlobalRenderEnableCMode => (int)(SetGlobalRenderEnableC & 0x7); public uint SendGoIdle; public uint PmTrigger; public fixed uint Reserved144[3]; @@ -528,54 +528,54 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod public uint SetInstrumentationMethodData; public fixed uint Reserved158[37]; public uint SetMmeSwitchState; - public bool SetMmeSwitchStateValid => (SetMmeSwitchState & 0x1) != 0; - public int SetMmeSwitchStateSaveMacro => (int)((SetMmeSwitchState >> 4) & 0xFF); - public int SetMmeSwitchStateRestoreMacro => (int)((SetMmeSwitchState >> 12) & 0xFF); + public readonly bool SetMmeSwitchStateValid => (SetMmeSwitchState & 0x1) != 0; + public readonly int SetMmeSwitchStateSaveMacro => (int)((SetMmeSwitchState >> 4) & 0xFF); + public readonly int SetMmeSwitchStateRestoreMacro => (int)((SetMmeSwitchState >> 12) & 0xFF); public fixed uint Reserved1F0[4]; public uint SetDstFormat; - public SetDstFormatV SetDstFormatV => (SetDstFormatV)(SetDstFormat & 0xFF); + public readonly SetDstFormatV SetDstFormatV => (SetDstFormatV)(SetDstFormat & 0xFF); public uint SetDstMemoryLayout; - public SetDstMemoryLayoutV SetDstMemoryLayoutV => (SetDstMemoryLayoutV)(SetDstMemoryLayout & 0x1); + public readonly SetDstMemoryLayoutV SetDstMemoryLayoutV => (SetDstMemoryLayoutV)(SetDstMemoryLayout & 0x1); public uint SetDstBlockSize; - public SetDstBlockSizeHeight SetDstBlockSizeHeight => (SetDstBlockSizeHeight)((SetDstBlockSize >> 4) & 0x7); - public SetDstBlockSizeDepth SetDstBlockSizeDepth => (SetDstBlockSizeDepth)((SetDstBlockSize >> 8) & 0x7); + public readonly SetDstBlockSizeHeight SetDstBlockSizeHeight => (SetDstBlockSizeHeight)((SetDstBlockSize >> 4) & 0x7); + public readonly SetDstBlockSizeDepth SetDstBlockSizeDepth => (SetDstBlockSizeDepth)((SetDstBlockSize >> 8) & 0x7); public uint SetDstDepth; public uint SetDstLayer; public uint SetDstPitch; public uint SetDstWidth; public uint SetDstHeight; public uint SetDstOffsetUpper; - public int SetDstOffsetUpperV => (int)(SetDstOffsetUpper & 0xFF); + public readonly int SetDstOffsetUpperV => (int)(SetDstOffsetUpper & 0xFF); public uint SetDstOffsetLower; public uint FlushAndInvalidateRopMiniCache; - public bool FlushAndInvalidateRopMiniCacheV => (FlushAndInvalidateRopMiniCache & 0x1) != 0; + public readonly bool FlushAndInvalidateRopMiniCacheV => (FlushAndInvalidateRopMiniCache & 0x1) != 0; public uint SetSpareNoop06; public uint SetSrcFormat; - public SetSrcFormatV SetSrcFormatV => (SetSrcFormatV)(SetSrcFormat & 0xFF); + public readonly SetSrcFormatV SetSrcFormatV => (SetSrcFormatV)(SetSrcFormat & 0xFF); public uint SetSrcMemoryLayout; - public SetSrcMemoryLayoutV SetSrcMemoryLayoutV => (SetSrcMemoryLayoutV)(SetSrcMemoryLayout & 0x1); + public readonly SetSrcMemoryLayoutV SetSrcMemoryLayoutV => (SetSrcMemoryLayoutV)(SetSrcMemoryLayout & 0x1); public uint SetSrcBlockSize; - public SetSrcBlockSizeHeight SetSrcBlockSizeHeight => (SetSrcBlockSizeHeight)((SetSrcBlockSize >> 4) & 0x7); - public SetSrcBlockSizeDepth SetSrcBlockSizeDepth => (SetSrcBlockSizeDepth)((SetSrcBlockSize >> 8) & 0x7); + public readonly SetSrcBlockSizeHeight SetSrcBlockSizeHeight => (SetSrcBlockSizeHeight)((SetSrcBlockSize >> 4) & 0x7); + public readonly SetSrcBlockSizeDepth SetSrcBlockSizeDepth => (SetSrcBlockSizeDepth)((SetSrcBlockSize >> 8) & 0x7); public uint SetSrcDepth; public uint TwodInvalidateTextureDataCache; - public TwodInvalidateTextureDataCacheV TwodInvalidateTextureDataCacheV => (TwodInvalidateTextureDataCacheV)(TwodInvalidateTextureDataCache & 0x3); + public readonly TwodInvalidateTextureDataCacheV TwodInvalidateTextureDataCacheV => (TwodInvalidateTextureDataCacheV)(TwodInvalidateTextureDataCache & 0x3); public uint SetSrcPitch; public uint SetSrcWidth; public uint SetSrcHeight; public uint SetSrcOffsetUpper; - public int SetSrcOffsetUpperV => (int)(SetSrcOffsetUpper & 0xFF); + public readonly int SetSrcOffsetUpperV => (int)(SetSrcOffsetUpper & 0xFF); public uint SetSrcOffsetLower; public uint SetPixelsFromMemorySectorPromotion; - public SetPixelsFromMemorySectorPromotionV SetPixelsFromMemorySectorPromotionV => (SetPixelsFromMemorySectorPromotionV)(SetPixelsFromMemorySectorPromotion & 0x3); + public readonly SetPixelsFromMemorySectorPromotionV SetPixelsFromMemorySectorPromotionV => (SetPixelsFromMemorySectorPromotionV)(SetPixelsFromMemorySectorPromotion & 0x3); public uint SetSpareNoop12; public uint SetNumProcessingClusters; - public SetNumProcessingClustersV SetNumProcessingClustersV => (SetNumProcessingClustersV)(SetNumProcessingClusters & 0x1); + public readonly SetNumProcessingClustersV SetNumProcessingClustersV => (SetNumProcessingClustersV)(SetNumProcessingClusters & 0x1); public uint SetRenderEnableA; - public int SetRenderEnableAOffsetUpper => (int)(SetRenderEnableA & 0xFF); + public readonly int SetRenderEnableAOffsetUpper => (int)(SetRenderEnableA & 0xFF); public uint SetRenderEnableB; public uint SetRenderEnableC; - public int SetRenderEnableCMode => (int)(SetRenderEnableC & 0x7); + public readonly int SetRenderEnableCMode => (int)(SetRenderEnableC & 0x7); public uint SetSpareNoop08; public uint SetSpareNoop01; public uint SetSpareNoop11; @@ -585,29 +585,29 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod public uint SetClipWidth; public uint SetClipHeight; public uint SetClipEnable; - public bool SetClipEnableV => (SetClipEnable & 0x1) != 0; + public readonly bool SetClipEnableV => (SetClipEnable & 0x1) != 0; public uint SetColorKeyFormat; - public SetColorKeyFormatV SetColorKeyFormatV => (SetColorKeyFormatV)(SetColorKeyFormat & 0x7); + public readonly SetColorKeyFormatV SetColorKeyFormatV => (SetColorKeyFormatV)(SetColorKeyFormat & 0x7); public uint SetColorKey; public uint SetColorKeyEnable; - public bool SetColorKeyEnableV => (SetColorKeyEnable & 0x1) != 0; + public readonly bool SetColorKeyEnableV => (SetColorKeyEnable & 0x1) != 0; public uint SetRop; - public int SetRopV => (int)(SetRop & 0xFF); + public readonly int SetRopV => (int)(SetRop & 0xFF); public uint SetBeta1; public uint SetBeta4; - public int SetBeta4B => (int)(SetBeta4 & 0xFF); - public int SetBeta4G => (int)((SetBeta4 >> 8) & 0xFF); - public int SetBeta4R => (int)((SetBeta4 >> 16) & 0xFF); - public int SetBeta4A => (int)((SetBeta4 >> 24) & 0xFF); + public readonly int SetBeta4B => (int)(SetBeta4 & 0xFF); + public readonly int SetBeta4G => (int)((SetBeta4 >> 8) & 0xFF); + public readonly int SetBeta4R => (int)((SetBeta4 >> 16) & 0xFF); + public readonly int SetBeta4A => (int)((SetBeta4 >> 24) & 0xFF); public uint SetOperation; - public SetOperationV SetOperationV => (SetOperationV)(SetOperation & 0x7); + public readonly SetOperationV SetOperationV => (SetOperationV)(SetOperation & 0x7); public uint SetPatternOffset; - public int SetPatternOffsetX => (int)(SetPatternOffset & 0x3F); - public int SetPatternOffsetY => (int)((SetPatternOffset >> 8) & 0x3F); + public readonly int SetPatternOffsetX => (int)(SetPatternOffset & 0x3F); + public readonly int SetPatternOffsetY => (int)((SetPatternOffset >> 8) & 0x3F); public uint SetPatternSelect; - public SetPatternSelectV SetPatternSelectV => (SetPatternSelectV)(SetPatternSelect & 0x3); + public readonly SetPatternSelectV SetPatternSelectV => (SetPatternSelectV)(SetPatternSelect & 0x3); public uint SetDstColorRenderToZetaSurface; - public bool SetDstColorRenderToZetaSurfaceV => (SetDstColorRenderToZetaSurface & 0x1) != 0; + public readonly bool SetDstColorRenderToZetaSurfaceV => (SetDstColorRenderToZetaSurface & 0x1) != 0; public uint SetSpareNoop04; public uint SetSpareNoop15; public uint SetSpareNoop13; @@ -615,18 +615,18 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod public uint SetSpareNoop14; public uint SetSpareNoop02; public uint SetCompression; - public bool SetCompressionEnable => (SetCompression & 0x1) != 0; + public readonly bool SetCompressionEnable => (SetCompression & 0x1) != 0; public uint SetSpareNoop09; public uint SetRenderEnableOverride; - public SetRenderEnableOverrideMode SetRenderEnableOverrideMode => (SetRenderEnableOverrideMode)(SetRenderEnableOverride & 0x3); + public readonly SetRenderEnableOverrideMode SetRenderEnableOverrideMode => (SetRenderEnableOverrideMode)(SetRenderEnableOverride & 0x3); public uint SetPixelsFromMemoryDirection; - public SetPixelsFromMemoryDirectionHorizontal SetPixelsFromMemoryDirectionHorizontal => (SetPixelsFromMemoryDirectionHorizontal)(SetPixelsFromMemoryDirection & 0x3); - public SetPixelsFromMemoryDirectionVertical SetPixelsFromMemoryDirectionVertical => (SetPixelsFromMemoryDirectionVertical)((SetPixelsFromMemoryDirection >> 4) & 0x3); + public readonly SetPixelsFromMemoryDirectionHorizontal SetPixelsFromMemoryDirectionHorizontal => (SetPixelsFromMemoryDirectionHorizontal)(SetPixelsFromMemoryDirection & 0x3); + public readonly SetPixelsFromMemoryDirectionVertical SetPixelsFromMemoryDirectionVertical => (SetPixelsFromMemoryDirectionVertical)((SetPixelsFromMemoryDirection >> 4) & 0x3); public uint SetSpareNoop10; public uint SetMonochromePatternColorFormat; - public SetMonochromePatternColorFormatV SetMonochromePatternColorFormatV => (SetMonochromePatternColorFormatV)(SetMonochromePatternColorFormat & 0x7); + public readonly SetMonochromePatternColorFormatV SetMonochromePatternColorFormatV => (SetMonochromePatternColorFormatV)(SetMonochromePatternColorFormat & 0x7); public uint SetMonochromePatternFormat; - public SetMonochromePatternFormatV SetMonochromePatternFormatV => (SetMonochromePatternFormatV)(SetMonochromePatternFormat & 0x1); + public readonly SetMonochromePatternFormatV SetMonochromePatternFormatV => (SetMonochromePatternFormatV)(SetMonochromePatternFormat & 0x1); public uint SetMonochromePatternColor0; public uint SetMonochromePatternColor1; public uint SetMonochromePattern0; @@ -662,52 +662,52 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod public uint SetRenderSolidPrimColor2; public uint SetRenderSolidPrimColor3; public uint SetMmeMemAddressA; - public int SetMmeMemAddressAUpper => (int)(SetMmeMemAddressA & 0x1FFFFFF); + public readonly int SetMmeMemAddressAUpper => (int)(SetMmeMemAddressA & 0x1FFFFFF); public uint SetMmeMemAddressB; public uint SetMmeDataRamAddress; public uint MmeDmaRead; public uint MmeDmaReadFifoed; public uint MmeDmaWrite; public uint MmeDmaReduction; - public MmeDmaReductionReductionOp MmeDmaReductionReductionOp => (MmeDmaReductionReductionOp)(MmeDmaReduction & 0x7); - public MmeDmaReductionReductionFormat MmeDmaReductionReductionFormat => (MmeDmaReductionReductionFormat)((MmeDmaReduction >> 4) & 0x3); - public MmeDmaReductionReductionSize MmeDmaReductionReductionSize => (MmeDmaReductionReductionSize)((MmeDmaReduction >> 8) & 0x1); + public readonly MmeDmaReductionReductionOp MmeDmaReductionReductionOp => (MmeDmaReductionReductionOp)(MmeDmaReduction & 0x7); + public readonly MmeDmaReductionReductionFormat MmeDmaReductionReductionFormat => (MmeDmaReductionReductionFormat)((MmeDmaReduction >> 4) & 0x3); + public readonly MmeDmaReductionReductionSize MmeDmaReductionReductionSize => (MmeDmaReductionReductionSize)((MmeDmaReduction >> 8) & 0x1); public uint MmeDmaSysmembar; - public bool MmeDmaSysmembarV => (MmeDmaSysmembar & 0x1) != 0; + public readonly bool MmeDmaSysmembarV => (MmeDmaSysmembar & 0x1) != 0; public uint MmeDmaSync; public uint SetMmeDataFifoConfig; - public SetMmeDataFifoConfigFifoSize SetMmeDataFifoConfigFifoSize => (SetMmeDataFifoConfigFifoSize)(SetMmeDataFifoConfig & 0x7); + public readonly SetMmeDataFifoConfigFifoSize SetMmeDataFifoConfigFifoSize => (SetMmeDataFifoConfigFifoSize)(SetMmeDataFifoConfig & 0x7); public fixed uint Reserved578[2]; public uint RenderSolidPrimMode; - public RenderSolidPrimModeV RenderSolidPrimModeV => (RenderSolidPrimModeV)(RenderSolidPrimMode & 0x7); + public readonly RenderSolidPrimModeV RenderSolidPrimModeV => (RenderSolidPrimModeV)(RenderSolidPrimMode & 0x7); public uint SetRenderSolidPrimColorFormat; - public SetRenderSolidPrimColorFormatV SetRenderSolidPrimColorFormatV => (SetRenderSolidPrimColorFormatV)(SetRenderSolidPrimColorFormat & 0xFF); + public readonly SetRenderSolidPrimColorFormatV SetRenderSolidPrimColorFormatV => (SetRenderSolidPrimColorFormatV)(SetRenderSolidPrimColorFormat & 0xFF); public uint SetRenderSolidPrimColor; public uint SetRenderSolidLineTieBreakBits; - public bool SetRenderSolidLineTieBreakBitsXmajXincYinc => (SetRenderSolidLineTieBreakBits & 0x1) != 0; - public bool SetRenderSolidLineTieBreakBitsXmajXdecYinc => (SetRenderSolidLineTieBreakBits & 0x10) != 0; - public bool SetRenderSolidLineTieBreakBitsYmajXincYinc => (SetRenderSolidLineTieBreakBits & 0x100) != 0; - public bool SetRenderSolidLineTieBreakBitsYmajXdecYinc => (SetRenderSolidLineTieBreakBits & 0x1000) != 0; + public readonly bool SetRenderSolidLineTieBreakBitsXmajXincYinc => (SetRenderSolidLineTieBreakBits & 0x1) != 0; + public readonly bool SetRenderSolidLineTieBreakBitsXmajXdecYinc => (SetRenderSolidLineTieBreakBits & 0x10) != 0; + public readonly bool SetRenderSolidLineTieBreakBitsYmajXincYinc => (SetRenderSolidLineTieBreakBits & 0x100) != 0; + public readonly bool SetRenderSolidLineTieBreakBitsYmajXdecYinc => (SetRenderSolidLineTieBreakBits & 0x1000) != 0; public fixed uint Reserved590[20]; public uint RenderSolidPrimPointXY; - public int RenderSolidPrimPointXYX => (int)(RenderSolidPrimPointXY & 0xFFFF); - public int RenderSolidPrimPointXYY => (int)((RenderSolidPrimPointXY >> 16) & 0xFFFF); + public readonly int RenderSolidPrimPointXYX => (int)(RenderSolidPrimPointXY & 0xFFFF); + public readonly int RenderSolidPrimPointXYY => (int)((RenderSolidPrimPointXY >> 16) & 0xFFFF); public fixed uint Reserved5E4[7]; public Array64 RenderSolidPrimPoint; public uint SetPixelsFromCpuDataType; - public SetPixelsFromCpuDataTypeV SetPixelsFromCpuDataTypeV => (SetPixelsFromCpuDataTypeV)(SetPixelsFromCpuDataType & 0x1); + public readonly SetPixelsFromCpuDataTypeV SetPixelsFromCpuDataTypeV => (SetPixelsFromCpuDataTypeV)(SetPixelsFromCpuDataType & 0x1); public uint SetPixelsFromCpuColorFormat; - public SetPixelsFromCpuColorFormatV SetPixelsFromCpuColorFormatV => (SetPixelsFromCpuColorFormatV)(SetPixelsFromCpuColorFormat & 0xFF); + public readonly SetPixelsFromCpuColorFormatV SetPixelsFromCpuColorFormatV => (SetPixelsFromCpuColorFormatV)(SetPixelsFromCpuColorFormat & 0xFF); public uint SetPixelsFromCpuIndexFormat; - public SetPixelsFromCpuIndexFormatV SetPixelsFromCpuIndexFormatV => (SetPixelsFromCpuIndexFormatV)(SetPixelsFromCpuIndexFormat & 0x3); + public readonly SetPixelsFromCpuIndexFormatV SetPixelsFromCpuIndexFormatV => (SetPixelsFromCpuIndexFormatV)(SetPixelsFromCpuIndexFormat & 0x3); public uint SetPixelsFromCpuMonoFormat; - public SetPixelsFromCpuMonoFormatV SetPixelsFromCpuMonoFormatV => (SetPixelsFromCpuMonoFormatV)(SetPixelsFromCpuMonoFormat & 0x1); + public readonly SetPixelsFromCpuMonoFormatV SetPixelsFromCpuMonoFormatV => (SetPixelsFromCpuMonoFormatV)(SetPixelsFromCpuMonoFormat & 0x1); public uint SetPixelsFromCpuWrap; - public SetPixelsFromCpuWrapV SetPixelsFromCpuWrapV => (SetPixelsFromCpuWrapV)(SetPixelsFromCpuWrap & 0x3); + public readonly SetPixelsFromCpuWrapV SetPixelsFromCpuWrapV => (SetPixelsFromCpuWrapV)(SetPixelsFromCpuWrap & 0x3); public uint SetPixelsFromCpuColor0; public uint SetPixelsFromCpuColor1; public uint SetPixelsFromCpuMonoOpacity; - public SetPixelsFromCpuMonoOpacityV SetPixelsFromCpuMonoOpacityV => (SetPixelsFromCpuMonoOpacityV)(SetPixelsFromCpuMonoOpacity & 0x1); + public readonly SetPixelsFromCpuMonoOpacityV SetPixelsFromCpuMonoOpacityV => (SetPixelsFromCpuMonoOpacityV)(SetPixelsFromCpuMonoOpacity & 0x1); public fixed uint Reserved820[6]; public uint SetPixelsFromCpuSrcWidth; public uint SetPixelsFromCpuSrcHeight; @@ -722,45 +722,45 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod public uint PixelsFromCpuData; public fixed uint Reserved864[3]; public uint SetBigEndianControl; - public bool SetBigEndianControlX32Swap1 => (SetBigEndianControl & 0x1) != 0; - public bool SetBigEndianControlX32Swap4 => (SetBigEndianControl & 0x2) != 0; - public bool SetBigEndianControlX32Swap8 => (SetBigEndianControl & 0x4) != 0; - public bool SetBigEndianControlX32Swap16 => (SetBigEndianControl & 0x8) != 0; - public bool SetBigEndianControlX16Swap1 => (SetBigEndianControl & 0x10) != 0; - public bool SetBigEndianControlX16Swap4 => (SetBigEndianControl & 0x20) != 0; - public bool SetBigEndianControlX16Swap8 => (SetBigEndianControl & 0x40) != 0; - public bool SetBigEndianControlX16Swap16 => (SetBigEndianControl & 0x80) != 0; - public bool SetBigEndianControlX8Swap1 => (SetBigEndianControl & 0x100) != 0; - public bool SetBigEndianControlX8Swap4 => (SetBigEndianControl & 0x200) != 0; - public bool SetBigEndianControlX8Swap8 => (SetBigEndianControl & 0x400) != 0; - public bool SetBigEndianControlX8Swap16 => (SetBigEndianControl & 0x800) != 0; - public bool SetBigEndianControlI1X8Cga6Swap1 => (SetBigEndianControl & 0x1000) != 0; - public bool SetBigEndianControlI1X8Cga6Swap4 => (SetBigEndianControl & 0x2000) != 0; - public bool SetBigEndianControlI1X8Cga6Swap8 => (SetBigEndianControl & 0x4000) != 0; - public bool SetBigEndianControlI1X8Cga6Swap16 => (SetBigEndianControl & 0x8000) != 0; - public bool SetBigEndianControlI1X8LeSwap1 => (SetBigEndianControl & 0x10000) != 0; - public bool SetBigEndianControlI1X8LeSwap4 => (SetBigEndianControl & 0x20000) != 0; - public bool SetBigEndianControlI1X8LeSwap8 => (SetBigEndianControl & 0x40000) != 0; - public bool SetBigEndianControlI1X8LeSwap16 => (SetBigEndianControl & 0x80000) != 0; - public bool SetBigEndianControlI4Swap1 => (SetBigEndianControl & 0x100000) != 0; - public bool SetBigEndianControlI4Swap4 => (SetBigEndianControl & 0x200000) != 0; - public bool SetBigEndianControlI4Swap8 => (SetBigEndianControl & 0x400000) != 0; - public bool SetBigEndianControlI4Swap16 => (SetBigEndianControl & 0x800000) != 0; - public bool SetBigEndianControlI8Swap1 => (SetBigEndianControl & 0x1000000) != 0; - public bool SetBigEndianControlI8Swap4 => (SetBigEndianControl & 0x2000000) != 0; - public bool SetBigEndianControlI8Swap8 => (SetBigEndianControl & 0x4000000) != 0; - public bool SetBigEndianControlI8Swap16 => (SetBigEndianControl & 0x8000000) != 0; - public bool SetBigEndianControlOverride => (SetBigEndianControl & 0x10000000) != 0; + public readonly bool SetBigEndianControlX32Swap1 => (SetBigEndianControl & 0x1) != 0; + public readonly bool SetBigEndianControlX32Swap4 => (SetBigEndianControl & 0x2) != 0; + public readonly bool SetBigEndianControlX32Swap8 => (SetBigEndianControl & 0x4) != 0; + public readonly bool SetBigEndianControlX32Swap16 => (SetBigEndianControl & 0x8) != 0; + public readonly bool SetBigEndianControlX16Swap1 => (SetBigEndianControl & 0x10) != 0; + public readonly bool SetBigEndianControlX16Swap4 => (SetBigEndianControl & 0x20) != 0; + public readonly bool SetBigEndianControlX16Swap8 => (SetBigEndianControl & 0x40) != 0; + public readonly bool SetBigEndianControlX16Swap16 => (SetBigEndianControl & 0x80) != 0; + public readonly bool SetBigEndianControlX8Swap1 => (SetBigEndianControl & 0x100) != 0; + public readonly bool SetBigEndianControlX8Swap4 => (SetBigEndianControl & 0x200) != 0; + public readonly bool SetBigEndianControlX8Swap8 => (SetBigEndianControl & 0x400) != 0; + public readonly bool SetBigEndianControlX8Swap16 => (SetBigEndianControl & 0x800) != 0; + public readonly bool SetBigEndianControlI1X8Cga6Swap1 => (SetBigEndianControl & 0x1000) != 0; + public readonly bool SetBigEndianControlI1X8Cga6Swap4 => (SetBigEndianControl & 0x2000) != 0; + public readonly bool SetBigEndianControlI1X8Cga6Swap8 => (SetBigEndianControl & 0x4000) != 0; + public readonly bool SetBigEndianControlI1X8Cga6Swap16 => (SetBigEndianControl & 0x8000) != 0; + public readonly bool SetBigEndianControlI1X8LeSwap1 => (SetBigEndianControl & 0x10000) != 0; + public readonly bool SetBigEndianControlI1X8LeSwap4 => (SetBigEndianControl & 0x20000) != 0; + public readonly bool SetBigEndianControlI1X8LeSwap8 => (SetBigEndianControl & 0x40000) != 0; + public readonly bool SetBigEndianControlI1X8LeSwap16 => (SetBigEndianControl & 0x80000) != 0; + public readonly bool SetBigEndianControlI4Swap1 => (SetBigEndianControl & 0x100000) != 0; + public readonly bool SetBigEndianControlI4Swap4 => (SetBigEndianControl & 0x200000) != 0; + public readonly bool SetBigEndianControlI4Swap8 => (SetBigEndianControl & 0x400000) != 0; + public readonly bool SetBigEndianControlI4Swap16 => (SetBigEndianControl & 0x800000) != 0; + public readonly bool SetBigEndianControlI8Swap1 => (SetBigEndianControl & 0x1000000) != 0; + public readonly bool SetBigEndianControlI8Swap4 => (SetBigEndianControl & 0x2000000) != 0; + public readonly bool SetBigEndianControlI8Swap8 => (SetBigEndianControl & 0x4000000) != 0; + public readonly bool SetBigEndianControlI8Swap16 => (SetBigEndianControl & 0x8000000) != 0; + public readonly bool SetBigEndianControlOverride => (SetBigEndianControl & 0x10000000) != 0; public fixed uint Reserved874[3]; public uint SetPixelsFromMemoryBlockShape; - public SetPixelsFromMemoryBlockShapeV SetPixelsFromMemoryBlockShapeV => (SetPixelsFromMemoryBlockShapeV)(SetPixelsFromMemoryBlockShape & 0x7); + public readonly SetPixelsFromMemoryBlockShapeV SetPixelsFromMemoryBlockShapeV => (SetPixelsFromMemoryBlockShapeV)(SetPixelsFromMemoryBlockShape & 0x7); public uint SetPixelsFromMemoryCorralSize; - public int SetPixelsFromMemoryCorralSizeV => (int)(SetPixelsFromMemoryCorralSize & 0x3FF); + public readonly int SetPixelsFromMemoryCorralSizeV => (int)(SetPixelsFromMemoryCorralSize & 0x3FF); public uint SetPixelsFromMemorySafeOverlap; - public bool SetPixelsFromMemorySafeOverlapV => (SetPixelsFromMemorySafeOverlap & 0x1) != 0; + public readonly bool SetPixelsFromMemorySafeOverlapV => (SetPixelsFromMemorySafeOverlap & 0x1) != 0; public uint SetPixelsFromMemorySampleMode; - public SetPixelsFromMemorySampleModeOrigin SetPixelsFromMemorySampleModeOrigin => (SetPixelsFromMemorySampleModeOrigin)(SetPixelsFromMemorySampleMode & 0x1); - public SetPixelsFromMemorySampleModeFilter SetPixelsFromMemorySampleModeFilter => (SetPixelsFromMemorySampleModeFilter)((SetPixelsFromMemorySampleMode >> 4) & 0x1); + public readonly SetPixelsFromMemorySampleModeOrigin SetPixelsFromMemorySampleModeOrigin => (SetPixelsFromMemorySampleModeOrigin)(SetPixelsFromMemorySampleMode & 0x1); + public readonly SetPixelsFromMemorySampleModeFilter SetPixelsFromMemorySampleModeFilter => (SetPixelsFromMemorySampleModeFilter)((SetPixelsFromMemorySampleMode >> 4) & 0x1); public fixed uint Reserved890[8]; public uint SetPixelsFromMemoryDstX0; public uint SetPixelsFromMemoryDstY0; @@ -808,9 +808,9 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod public uint SetFalcon31; public fixed uint Reserved960[291]; public uint MmeDmaWriteMethodBarrier; - public bool MmeDmaWriteMethodBarrierV => (MmeDmaWriteMethodBarrier & 0x1) != 0; + public readonly bool MmeDmaWriteMethodBarrierV => (MmeDmaWriteMethodBarrier & 0x1) != 0; public fixed uint ReservedDF0[2436]; - public MmeShadowScratch SetMmeShadowScratch; + public Array256 SetMmeShadowScratch; #pragma warning restore CS0649 } } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Twod/TwodTexture.cs b/src/Ryujinx.Graphics.Gpu/Engine/Twod/TwodTexture.cs index c28da0948..dd6b69000 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Twod/TwodTexture.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Twod/TwodTexture.cs @@ -7,7 +7,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod /// struct TwodTexture { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public ColorFormat Format; public Boolean32 LinearLayout; public MemoryLayout MemoryLayout; diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Types/Boolean32.cs b/src/Ryujinx.Graphics.Gpu/Engine/Types/Boolean32.cs index c982347a1..911ad53b4 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Types/Boolean32.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Types/Boolean32.cs @@ -3,10 +3,10 @@ /// /// Boolean value, stored as a 32-bits integer in memory. /// - struct Boolean32 + readonly struct Boolean32 { -#pragma warning disable CS0649 - private uint _value; +#pragma warning disable CS0649 // Field is never assigned to + private readonly uint _value; #pragma warning restore CS0649 public static implicit operator bool(Boolean32 value) diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Types/ColorFormat.cs b/src/Ryujinx.Graphics.Gpu/Engine/Types/ColorFormat.cs index 889b5c8b0..c798384f0 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Types/ColorFormat.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Types/ColorFormat.cs @@ -9,58 +9,58 @@ namespace Ryujinx.Graphics.Gpu.Engine.Types enum ColorFormat { R32G32B32A32Float = 0xc0, - R32G32B32A32Sint = 0xc1, - R32G32B32A32Uint = 0xc2, + R32G32B32A32Sint = 0xc1, + R32G32B32A32Uint = 0xc2, R32G32B32X32Float = 0xc3, - R32G32B32X32Sint = 0xc4, - R32G32B32X32Uint = 0xc5, + R32G32B32X32Sint = 0xc4, + R32G32B32X32Uint = 0xc5, R16G16B16X16Unorm = 0xc6, R16G16B16X16Snorm = 0xc7, - R16G16B16X16Sint = 0xc8, - R16G16B16X16Uint = 0xc9, + R16G16B16X16Sint = 0xc8, + R16G16B16X16Uint = 0xc9, R16G16B16A16Float = 0xca, - R32G32Float = 0xcb, - R32G32Sint = 0xcc, - R32G32Uint = 0xcd, + R32G32Float = 0xcb, + R32G32Sint = 0xcc, + R32G32Uint = 0xcd, R16G16B16X16Float = 0xce, - B8G8R8A8Unorm = 0xcf, - B8G8R8A8Srgb = 0xd0, - R10G10B10A2Unorm = 0xd1, - R10G10B10A2Uint = 0xd2, - R8G8B8A8Unorm = 0xd5, - R8G8B8A8Srgb = 0xd6, - R8G8B8X8Snorm = 0xd7, - R8G8B8X8Sint = 0xd8, - R8G8B8X8Uint = 0xd9, - R16G16Unorm = 0xda, - R16G16Snorm = 0xdb, - R16G16Sint = 0xdc, - R16G16Uint = 0xdd, - R16G16Float = 0xde, - R11G11B10Float = 0xe0, - R32Sint = 0xe3, - R32Uint = 0xe4, - R32Float = 0xe5, - B8G8R8X8Unorm = 0xe6, - B8G8R8X8Srgb = 0xe7, - B5G6R5Unorm = 0xe8, - B5G5R5A1Unorm = 0xe9, - R8G8Unorm = 0xea, - R8G8Snorm = 0xeb, - R8G8Sint = 0xec, - R8G8Uint = 0xed, - R16Unorm = 0xee, - R16Snorm = 0xef, - R16Sint = 0xf0, - R16Uint = 0xf1, - R16Float = 0xf2, - R8Unorm = 0xf3, - R8Snorm = 0xf4, - R8Sint = 0xf5, - R8Uint = 0xf6, - B5G5R5X1Unorm = 0xf8, - R8G8B8X8Unorm = 0xf9, - R8G8B8X8Srgb = 0xfa + B8G8R8A8Unorm = 0xcf, + B8G8R8A8Srgb = 0xd0, + R10G10B10A2Unorm = 0xd1, + R10G10B10A2Uint = 0xd2, + R8G8B8A8Unorm = 0xd5, + R8G8B8A8Srgb = 0xd6, + R8G8B8X8Snorm = 0xd7, + R8G8B8X8Sint = 0xd8, + R8G8B8X8Uint = 0xd9, + R16G16Unorm = 0xda, + R16G16Snorm = 0xdb, + R16G16Sint = 0xdc, + R16G16Uint = 0xdd, + R16G16Float = 0xde, + R11G11B10Float = 0xe0, + R32Sint = 0xe3, + R32Uint = 0xe4, + R32Float = 0xe5, + B8G8R8X8Unorm = 0xe6, + B8G8R8X8Srgb = 0xe7, + B5G6R5Unorm = 0xe8, + B5G5R5A1Unorm = 0xe9, + R8G8Unorm = 0xea, + R8G8Snorm = 0xeb, + R8G8Sint = 0xec, + R8G8Uint = 0xed, + R16Unorm = 0xee, + R16Snorm = 0xef, + R16Sint = 0xf0, + R16Uint = 0xf1, + R16Float = 0xf2, + R8Unorm = 0xf3, + R8Snorm = 0xf4, + R8Sint = 0xf5, + R8Uint = 0xf6, + B5G5R5X1Unorm = 0xf8, + R8G8B8X8Unorm = 0xf9, + R8G8B8X8Srgb = 0xfa, } static class ColorFormatConverter @@ -74,6 +74,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Types { return format switch { +#pragma warning disable IDE0055 // Disable formatting ColorFormat.R32G32B32A32Float => new FormatInfo(Format.R32G32B32A32Float, 1, 1, 16, 4), ColorFormat.R32G32B32A32Sint => new FormatInfo(Format.R32G32B32A32Sint, 1, 1, 16, 4), ColorFormat.R32G32B32A32Uint => new FormatInfo(Format.R32G32B32A32Uint, 1, 1, 16, 4), @@ -127,7 +128,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Types ColorFormat.B5G5R5X1Unorm => new FormatInfo(Format.B5G5R5A1Unorm, 1, 1, 2, 4), ColorFormat.R8G8B8X8Unorm => new FormatInfo(Format.R8G8B8A8Unorm, 1, 1, 4, 4), ColorFormat.R8G8B8X8Srgb => new FormatInfo(Format.R8G8B8A8Srgb, 1, 1, 4, 4), - _ => FormatInfo.Default + _ => FormatInfo.Default, +#pragma warning restore IDE0055 }; } @@ -157,9 +159,9 @@ namespace Ryujinx.Graphics.Gpu.Engine.Types case ColorFormat.R8G8B8X8Unorm: case ColorFormat.R8G8B8X8Srgb: return true; + default: + return false; } - - return false; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Types/GpuVa.cs b/src/Ryujinx.Graphics.Gpu/Engine/Types/GpuVa.cs index 839faac9b..b3b0c41ad 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Types/GpuVa.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Types/GpuVa.cs @@ -5,7 +5,7 @@ /// struct GpuVa { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public uint High; public uint Low; #pragma warning restore CS0649 @@ -14,7 +14,7 @@ /// Packs the split address into a 64-bits address value. /// /// The 64-bits address value - public ulong Pack() + public readonly ulong Pack() { return Low | ((ulong)High << 32); } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Types/MemoryLayout.cs b/src/Ryujinx.Graphics.Gpu/Engine/Types/MemoryLayout.cs index 6da96bd44..5a4253734 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Types/MemoryLayout.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Types/MemoryLayout.cs @@ -5,31 +5,31 @@ /// struct MemoryLayout { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public uint Packed; #pragma warning restore CS0649 - public int UnpackGobBlocksInX() + public readonly int UnpackGobBlocksInX() { return 1 << (int)(Packed & 0xf); } - public int UnpackGobBlocksInY() + public readonly int UnpackGobBlocksInY() { return 1 << (int)((Packed >> 4) & 0xf); } - public int UnpackGobBlocksInZ() + public readonly int UnpackGobBlocksInZ() { return 1 << (int)((Packed >> 8) & 0xf); } - public bool UnpackIsLinear() + public readonly bool UnpackIsLinear() { return (Packed & 0x1000) != 0; } - public bool UnpackIsTarget3D() + public readonly bool UnpackIsTarget3D() { return (Packed & 0x10000) != 0; } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Types/PrimitiveType.cs b/src/Ryujinx.Graphics.Gpu/Engine/Types/PrimitiveType.cs index dae631248..5abbc9235 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Types/PrimitiveType.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Types/PrimitiveType.cs @@ -21,7 +21,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Types LineStripAdjacency, TrianglesAdjacency, TriangleStripAdjacency, - Patches + Patches, } /// @@ -39,7 +39,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Types LineStripAdjacency = 11, TrianglesAdjacency = 12, TriangleStripAdjacency = 13, - Patches = 14 + Patches = 14, } static class PrimitiveTypeConverter @@ -53,6 +53,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Types { return type switch { +#pragma warning disable IDE0055 // Disable formatting PrimitiveType.Points => PrimitiveTopology.Points, PrimitiveType.Lines => PrimitiveTopology.Lines, PrimitiveType.LineLoop => PrimitiveTopology.LineLoop, @@ -68,7 +69,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Types PrimitiveType.TrianglesAdjacency => PrimitiveTopology.TrianglesAdjacency, PrimitiveType.TriangleStripAdjacency => PrimitiveTopology.TriangleStripAdjacency, PrimitiveType.Patches => PrimitiveTopology.Patches, - _ => PrimitiveTopology.Triangles + _ => PrimitiveTopology.Triangles, +#pragma warning restore IDE0055 }; } @@ -81,6 +83,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Types { return type switch { +#pragma warning disable IDE0055 // Disable formatting PrimitiveTypeOverride.Points => PrimitiveTopology.Points, PrimitiveTypeOverride.Lines => PrimitiveTopology.Lines, PrimitiveTypeOverride.LineStrip => PrimitiveTopology.LineStrip, @@ -92,8 +95,9 @@ namespace Ryujinx.Graphics.Gpu.Engine.Types PrimitiveTypeOverride.TrianglesAdjacency => PrimitiveTopology.TrianglesAdjacency, PrimitiveTypeOverride.TriangleStripAdjacency => PrimitiveTopology.TriangleStripAdjacency, PrimitiveTypeOverride.Patches => PrimitiveTopology.Patches, - _ => PrimitiveTopology.Triangles + _ => PrimitiveTopology.Triangles, +#pragma warning restore IDE0055 }; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Types/SamplerIndex.cs b/src/Ryujinx.Graphics.Gpu/Engine/Types/SamplerIndex.cs index 839a4d0af..22fe4a92f 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Types/SamplerIndex.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Types/SamplerIndex.cs @@ -5,7 +5,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Types /// enum SamplerIndex { - Independently = 0, - ViaHeaderIndex = 1 + Independently = 0, + ViaHeaderIndex = 1, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Types/SbDescriptor.cs b/src/Ryujinx.Graphics.Gpu/Engine/Types/SbDescriptor.cs index c457dbf91..e92263df0 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Types/SbDescriptor.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Types/SbDescriptor.cs @@ -5,14 +5,14 @@ /// struct SbDescriptor { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public uint AddressLow; public uint AddressHigh; public int Size; public int Padding; #pragma warning restore CS0649 - public ulong PackAddress() + public readonly ulong PackAddress() { return AddressLow | ((ulong)AddressHigh << 32); } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Types/ZetaFormat.cs b/src/Ryujinx.Graphics.Gpu/Engine/Types/ZetaFormat.cs index 1de1621fc..0fa073d7b 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Types/ZetaFormat.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Types/ZetaFormat.cs @@ -8,13 +8,13 @@ namespace Ryujinx.Graphics.Gpu.Engine.Types /// enum ZetaFormat { - D32Float = 0xa, - D16Unorm = 0x13, + D32Float = 0xa, + D16Unorm = 0x13, D24UnormS8Uint = 0x14, - D24Unorm = 0x15, + D24Unorm = 0x15, S8UintD24Unorm = 0x16, - S8Uint = 0x17, - D32FloatS8Uint = 0x19 + S8Uint = 0x17, + D32FloatS8Uint = 0x19, } static class ZetaFormatConverter @@ -28,6 +28,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Types { return format switch { +#pragma warning disable IDE0055 // Disable formatting ZetaFormat.D32Float => new FormatInfo(Format.D32Float, 1, 1, 4, 1), ZetaFormat.D16Unorm => new FormatInfo(Format.D16Unorm, 1, 1, 2, 1), ZetaFormat.D24UnormS8Uint => new FormatInfo(Format.D24UnormS8Uint, 1, 1, 4, 2), @@ -35,7 +36,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Types ZetaFormat.S8UintD24Unorm => new FormatInfo(Format.S8UintD24Unorm, 1, 1, 4, 2), ZetaFormat.S8Uint => new FormatInfo(Format.S8Uint, 1, 1, 1, 1), ZetaFormat.D32FloatS8Uint => new FormatInfo(Format.D32FloatS8Uint, 1, 1, 8, 2), - _ => FormatInfo.Default + _ => FormatInfo.Default, +#pragma warning restore IDE0055 }; } } diff --git a/src/Ryujinx.Graphics.Gpu/GpuChannel.cs b/src/Ryujinx.Graphics.Gpu/GpuChannel.cs index 43fa8484b..8fe643815 100644 --- a/src/Ryujinx.Graphics.Gpu/GpuChannel.cs +++ b/src/Ryujinx.Graphics.Gpu/GpuChannel.cs @@ -125,6 +125,7 @@ namespace Ryujinx.Graphics.Gpu /// public void Dispose() { + GC.SuppressFinalize(this); _context.DeferredActions.Enqueue(Destroy); } diff --git a/src/Ryujinx.Graphics.Gpu/GpuContext.cs b/src/Ryujinx.Graphics.Gpu/GpuContext.cs index 233227b4d..a5fe8f4c1 100644 --- a/src/Ryujinx.Graphics.Gpu/GpuContext.cs +++ b/src/Ryujinx.Graphics.Gpu/GpuContext.cs @@ -99,7 +99,7 @@ namespace Ryujinx.Graphics.Gpu private bool _pendingSync; private long _modifiedSequence; - private ulong _firstTimestamp; + private readonly ulong _firstTimestamp; /// /// Creates a new instance of the GPU emulation context. @@ -220,7 +220,7 @@ namespace Ryujinx.Graphics.Gpu /// The current GPU timestamp public ulong GetTimestamp() { - // Guest timestamp will start at 0, instead of host value. + // Guest timestamp will start at 0, instead of host value. ulong ticks = ConvertNanosecondsToTicks((ulong)PerformanceCounter.ElapsedNanoseconds) - _firstTimestamp; if (GraphicsConfig.FastGpuTime) @@ -406,4 +406,4 @@ namespace Ryujinx.Graphics.Gpu Renderer.Dispose(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/GraphicsConfig.cs b/src/Ryujinx.Graphics.Gpu/GraphicsConfig.cs index d2f98c7f2..4dfb93381 100644 --- a/src/Ryujinx.Graphics.Gpu/GraphicsConfig.cs +++ b/src/Ryujinx.Graphics.Gpu/GraphicsConfig.cs @@ -1,5 +1,6 @@ namespace Ryujinx.Graphics.Gpu { +#pragma warning disable CA2211 // Non-constant fields should not be visible /// /// General GPU and graphics configuration. /// @@ -67,4 +68,5 @@ namespace Ryujinx.Graphics.Gpu /// public static bool EnableTextureRecompression = false; } -} \ No newline at end of file +#pragma warning restore CA2211 +} diff --git a/src/Ryujinx.Graphics.Gpu/Image/AutoDeleteCache.cs b/src/Ryujinx.Graphics.Gpu/Image/AutoDeleteCache.cs index 2465efb0f..05782605b 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/AutoDeleteCache.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/AutoDeleteCache.cs @@ -54,7 +54,7 @@ namespace Ryujinx.Graphics.Gpu.Image private HashSet _shortCacheBuilder; private HashSet _shortCache; - private Dictionary _shortCacheLookup; + private readonly Dictionary _shortCacheLookup; /// /// Creates a new instance of the automatic deletion cache. @@ -295,4 +295,4 @@ namespace Ryujinx.Graphics.Gpu.Image return _textures.GetEnumerator(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Image/FormatInfo.cs b/src/Ryujinx.Graphics.Gpu/Image/FormatInfo.cs index 9ee649d2d..8a9f37bb0 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/FormatInfo.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/FormatInfo.cs @@ -10,7 +10,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// /// A default, generic RGBA8 texture format. /// - public static FormatInfo Default { get; } = new FormatInfo(Format.R8G8B8A8Unorm, 1, 1, 4, 4); + public static FormatInfo Default { get; } = new(Format.R8G8B8A8Unorm, 1, 1, 4, 4); /// /// The format of the texture data. @@ -57,16 +57,16 @@ namespace Ryujinx.Graphics.Gpu.Image /// The number of bytes occupied by a single pixel in memory of the texture data public FormatInfo( Format format, - int blockWidth, - int blockHeight, - int bytesPerPixel, - int components) + int blockWidth, + int blockHeight, + int bytesPerPixel, + int components) { - Format = format; - BlockWidth = blockWidth; - BlockHeight = blockHeight; + Format = format; + BlockWidth = blockWidth; + BlockHeight = blockHeight; BytesPerPixel = bytesPerPixel; - Components = components; + Components = components; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Image/FormatTable.cs b/src/Ryujinx.Graphics.Gpu/Image/FormatTable.cs index 729016104..ea5e9d002 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/FormatTable.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/FormatTable.cs @@ -1,5 +1,6 @@ using Ryujinx.Graphics.GAL; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; namespace Ryujinx.Graphics.Gpu.Image { @@ -8,6 +9,8 @@ namespace Ryujinx.Graphics.Gpu.Image /// static class FormatTable { +#pragma warning disable IDE0055 // Disable formatting + [SuppressMessage("Design", "CA1069: Enums values should not be duplicated")] private enum TextureFormat : uint { // Formats @@ -244,6 +247,7 @@ namespace Ryujinx.Graphics.Gpu.Image A5B5G5R1Unorm = A5B5G5R1 | RUnorm | GUnorm | BUnorm | AUnorm, // 0x24913 } + [SuppressMessage("Design", "CA1069: Enums values should not be duplicated")] private enum VertexAttributeFormat : uint { // Width @@ -357,7 +361,7 @@ namespace Ryujinx.Graphics.Gpu.Image A2B10G10R10Sscaled = (A2B10G10R10 << 21) | (Sscaled << 27), // 0x36000000 } - private static readonly Dictionary _textureFormats = new Dictionary() + private static readonly Dictionary _textureFormats = new() { { TextureFormat.R8Unorm, new FormatInfo(Format.R8Unorm, 1, 1, 1, 1) }, { TextureFormat.R8Snorm, new FormatInfo(Format.R8Snorm, 1, 1, 1, 1) }, @@ -464,10 +468,10 @@ namespace Ryujinx.Graphics.Gpu.Image { TextureFormat.Astc2D10x10UnormSrgb, new FormatInfo(Format.Astc10x10Srgb, 10, 10, 16, 4) }, { TextureFormat.Astc2D12x10UnormSrgb, new FormatInfo(Format.Astc12x10Srgb, 12, 10, 16, 4) }, { TextureFormat.Astc2D12x12UnormSrgb, new FormatInfo(Format.Astc12x12Srgb, 12, 12, 16, 4) }, - { TextureFormat.A5B5G5R1Unorm, new FormatInfo(Format.A1B5G5R5Unorm, 1, 1, 2, 4) } + { TextureFormat.A5B5G5R1Unorm, new FormatInfo(Format.A1B5G5R5Unorm, 1, 1, 2, 4) }, }; - private static readonly Dictionary _attribFormats = new Dictionary() + private static readonly Dictionary _attribFormats = new() { { VertexAttributeFormat.R8Unorm, Format.R8Unorm }, { VertexAttributeFormat.R8Snorm, Format.R8Snorm }, @@ -547,8 +551,9 @@ namespace Ryujinx.Graphics.Gpu.Image { VertexAttributeFormat.A2B10G10R10Snorm, Format.R10G10B10A2Snorm }, { VertexAttributeFormat.A2B10G10R10Sint, Format.R10G10B10A2Sint }, { VertexAttributeFormat.A2B10G10R10Uscaled, Format.R10G10B10A2Uscaled }, - { VertexAttributeFormat.A2B10G10R10Sscaled, Format.R10G10B10A2Sscaled } + { VertexAttributeFormat.A2B10G10R10Sscaled, Format.R10G10B10A2Sscaled }, }; +#pragma warning restore IDE0055 /// /// Try getting the texture format from an encoded format integer from the Maxwell texture descriptor. @@ -575,4 +580,4 @@ namespace Ryujinx.Graphics.Gpu.Image return _attribFormats.TryGetValue((VertexAttributeFormat)encoded, out format); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Image/Pool.cs b/src/Ryujinx.Graphics.Gpu/Image/Pool.cs index 63be151f3..0c3a219de 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/Pool.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/Pool.cs @@ -67,7 +67,7 @@ namespace Ryujinx.Graphics.Gpu.Image DescriptorCache = new T2[count]; Address = address; - Size = size; + Size = size; _memoryTracking = physicalMemory.BeginGranularTracking(address, size, ResourceKind.Pool); _memoryTracking.RegisterPreciseAction(address, size, PreciseAction); @@ -219,4 +219,4 @@ namespace Ryujinx.Graphics.Gpu.Image _memoryTracking.Dispose(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Image/PoolCache.cs b/src/Ryujinx.Graphics.Gpu/Image/PoolCache.cs index e1493f388..d9881f897 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/PoolCache.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/PoolCache.cs @@ -126,4 +126,4 @@ namespace Ryujinx.Graphics.Gpu.Image _pools.Clear(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Image/ReductionFilter.cs b/src/Ryujinx.Graphics.Gpu/Image/ReductionFilter.cs index 1f7d9b070..01553e50c 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/ReductionFilter.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/ReductionFilter.cs @@ -10,6 +10,6 @@ namespace Ryujinx.Graphics.Gpu.Image { Average, Minimum, - Maximum + Maximum, } } diff --git a/src/Ryujinx.Graphics.Gpu/Image/Sampler.cs b/src/Ryujinx.Graphics.Gpu/Image/Sampler.cs index b70ac9eb9..d6a3d975b 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/Sampler.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/Sampler.cs @@ -40,16 +40,16 @@ namespace Ryujinx.Graphics.Gpu.Image AddressMode addressP = descriptor.UnpackAddressP(); CompareMode compareMode = descriptor.UnpackCompareMode(); - CompareOp compareOp = descriptor.UnpackCompareOp(); + CompareOp compareOp = descriptor.UnpackCompareOp(); - ColorF color = new ColorF( + ColorF color = new( descriptor.BorderColorR, descriptor.BorderColorG, descriptor.BorderColorB, descriptor.BorderColorA); - float minLod = descriptor.UnpackMinLod(); - float maxLod = descriptor.UnpackMaxLod(); + float minLod = descriptor.UnpackMinLod(); + float maxLod = descriptor.UnpackMaxLod(); float mipLodBias = descriptor.UnpackMipLodBias(); float maxRequestedAnisotropy = descriptor.UnpackMaxAnisotropy(); @@ -112,4 +112,4 @@ namespace Ryujinx.Graphics.Gpu.Image _anisoSampler?.Dispose(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Image/SamplerDescriptor.cs b/src/Ryujinx.Graphics.Gpu/Image/SamplerDescriptor.cs index 64a146fb3..e04c31dfa 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/SamplerDescriptor.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/SamplerDescriptor.cs @@ -43,17 +43,17 @@ namespace Ryujinx.Graphics.Gpu.Image 0.45833334f, 0.46153846f, 0.4642857f, - 0.46666667f + 0.46666667f, }; private static readonly float[] _maxAnisotropyLut = new float[] { - 1, 2, 4, 6, 8, 10, 12, 16 + 1, 2, 4, 6, 8, 10, 12, 16, }; private const float Frac8ToF32 = 1.0f / 256.0f; -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public uint Word0; public uint Word1; public uint Word2; @@ -68,7 +68,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Unpacks the texture wrap mode along the X axis. /// /// The texture wrap mode enum - public AddressMode UnpackAddressU() + public readonly AddressMode UnpackAddressU() { return (AddressMode)(Word0 & 7); } @@ -77,7 +77,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Unpacks the texture wrap mode along the Y axis. /// /// The texture wrap mode enum - public AddressMode UnpackAddressV() + public readonly AddressMode UnpackAddressV() { return (AddressMode)((Word0 >> 3) & 7); } @@ -86,7 +86,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Unpacks the texture wrap mode along the Z axis. /// /// The texture wrap mode enum - public AddressMode UnpackAddressP() + public readonly AddressMode UnpackAddressP() { return (AddressMode)((Word0 >> 6) & 7); } @@ -97,7 +97,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// This is only relevant for shaders with shadow samplers. /// /// The depth comparison mode enum - public CompareMode UnpackCompareMode() + public readonly CompareMode UnpackCompareMode() { return (CompareMode)((Word0 >> 9) & 1); } @@ -108,7 +108,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// This is only relevant for shaders with shadow samplers. /// /// The depth comparison operation enum - public CompareOp UnpackCompareOp() + public readonly CompareOp UnpackCompareOp() { return (CompareOp)(((Word0 >> 10) & 7) + 1); } @@ -117,7 +117,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Unpacks and converts the maximum anisotropy value used for texture anisotropic filtering. /// /// The maximum anisotropy - public float UnpackMaxAnisotropy() + public readonly float UnpackMaxAnisotropy() { return _maxAnisotropyLut[(Word0 >> 20) & 7]; } @@ -128,7 +128,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// that is larger than the texture size. /// /// The magnification filter - public MagFilter UnpackMagFilter() + public readonly MagFilter UnpackMagFilter() { return (MagFilter)(Word1 & 3); } @@ -139,7 +139,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// that is smaller than the texture size. /// /// The minification filter - public MinFilter UnpackMinFilter() + public readonly MinFilter UnpackMinFilter() { SamplerMinFilter minFilter = (SamplerMinFilter)((Word1 >> 4) & 3); SamplerMipFilter mipFilter = (SamplerMipFilter)((Word1 >> 6) & 3); @@ -161,24 +161,30 @@ namespace Ryujinx.Graphics.Gpu.Image case SamplerMipFilter.None: switch (minFilter) { - case SamplerMinFilter.Nearest: return MinFilter.Nearest; - case SamplerMinFilter.Linear: return MinFilter.Linear; + case SamplerMinFilter.Nearest: + return MinFilter.Nearest; + case SamplerMinFilter.Linear: + return MinFilter.Linear; } break; case SamplerMipFilter.Nearest: switch (minFilter) { - case SamplerMinFilter.Nearest: return MinFilter.NearestMipmapNearest; - case SamplerMinFilter.Linear: return MinFilter.LinearMipmapNearest; + case SamplerMinFilter.Nearest: + return MinFilter.NearestMipmapNearest; + case SamplerMinFilter.Linear: + return MinFilter.LinearMipmapNearest; } break; case SamplerMipFilter.Linear: switch (minFilter) { - case SamplerMinFilter.Nearest: return MinFilter.NearestMipmapLinear; - case SamplerMinFilter.Linear: return MinFilter.LinearMipmapLinear; + case SamplerMinFilter.Nearest: + return MinFilter.NearestMipmapLinear; + case SamplerMinFilter.Linear: + return MinFilter.LinearMipmapLinear; } break; } @@ -190,7 +196,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Unpacks the seamless cubemap flag. /// /// The seamless cubemap flag - public bool UnpackSeamlessCubemap() + public readonly bool UnpackSeamlessCubemap() { return (Word1 & (1 << 9)) != 0; } @@ -200,7 +206,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// This describes how the final value will be computed from neighbouring pixels. /// /// The reduction filter - public ReductionFilter UnpackReductionFilter() + public readonly ReductionFilter UnpackReductionFilter() { return (ReductionFilter)((Word1 >> 10) & 3); } @@ -211,7 +217,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// which mipmap level to use from a given texture. /// /// The level-of-detail bias value - public float UnpackMipLodBias() + public readonly float UnpackMipLodBias() { int fixedValue = (int)(Word1 >> 12) & 0x1fff; @@ -224,7 +230,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Unpacks the level-of-detail snap value. /// /// The level-of-detail snap value - public float UnpackLodSnap() + public readonly float UnpackLodSnap() { return _f5ToF32ConversionLut[(Word1 >> 26) & 0x1f]; } @@ -233,7 +239,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Unpacks the minimum level-of-detail value. /// /// The minimum level-of-detail value - public float UnpackMinLod() + public readonly float UnpackMinLod() { return (Word2 & 0xfff) * Frac8ToF32; } @@ -242,7 +248,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Unpacks the maximum level-of-detail value. /// /// The maximum level-of-detail value - public float UnpackMaxLod() + public readonly float UnpackMaxLod() { return ((Word2 >> 12) & 0xfff) * Frac8ToF32; } diff --git a/src/Ryujinx.Graphics.Gpu/Image/SamplerMinFilter.cs b/src/Ryujinx.Graphics.Gpu/Image/SamplerMinFilter.cs index 17beb1293..d3009219a 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/SamplerMinFilter.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/SamplerMinFilter.cs @@ -6,6 +6,6 @@ namespace Ryujinx.Graphics.Gpu.Image enum SamplerMinFilter { Nearest = 1, - Linear + Linear, } } diff --git a/src/Ryujinx.Graphics.Gpu/Image/SamplerMipFilter.cs b/src/Ryujinx.Graphics.Gpu/Image/SamplerMipFilter.cs index 319d41960..b965f0c36 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/SamplerMipFilter.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/SamplerMipFilter.cs @@ -7,6 +7,6 @@ namespace Ryujinx.Graphics.Gpu.Image { None = 1, Nearest, - Linear + Linear, } } diff --git a/src/Ryujinx.Graphics.Gpu/Image/SamplerPool.cs b/src/Ryujinx.Graphics.Gpu/Image/SamplerPool.cs index eb7222f9c..3efcad760 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/SamplerPool.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/SamplerPool.cs @@ -159,4 +159,4 @@ namespace Ryujinx.Graphics.Gpu.Image item?.Dispose(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Image/SamplerPoolCache.cs b/src/Ryujinx.Graphics.Gpu/Image/SamplerPoolCache.cs index 3b3350fb5..881c37af4 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/SamplerPoolCache.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/SamplerPoolCache.cs @@ -27,4 +27,4 @@ namespace Ryujinx.Graphics.Gpu.Image return new SamplerPool(context, channel.MemoryManager.Physical, address, maximumId); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Image/Texture.cs b/src/Ryujinx.Graphics.Gpu/Image/Texture.cs index a7af1aad7..c0d45cbd1 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/Texture.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/Texture.cs @@ -119,7 +119,7 @@ namespace Ryujinx.Graphics.Gpu.Image private bool _modifiedStale = true; private ITexture _arrayViewTexture; - private Target _arrayViewTarget; + private Target _arrayViewTarget; private ITexture _flushHostTexture; private ITexture _setHostTexture; @@ -334,7 +334,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// The child texture public Texture CreateView(TextureInfo info, SizeInfo sizeInfo, MultiRange range, int firstLayer, int firstLevel) { - Texture texture = new Texture( + Texture texture = new( _context, _physicalMemory, info, @@ -523,7 +523,7 @@ namespace Ryujinx.Graphics.Gpu.Image if (ScaleFactor != scale) { - Logger.Debug?.Print(LogClass.Gpu, $"Rescaling {Info.Width}x{Info.Height} {Info.FormatInfo.Format.ToString()} to ({ScaleFactor} to {scale}). "); + Logger.Debug?.Print(LogClass.Gpu, $"Rescaling {Info.Width}x{Info.Height} {Info.FormatInfo.Format} to ({ScaleFactor} to {scale}). "); ScaleFactor = scale; @@ -537,7 +537,7 @@ namespace Ryujinx.Graphics.Gpu.Image foreach (var view in _views) { - Logger.Debug?.Print(LogClass.Gpu, $" Recreating view {Info.Width}x{Info.Height} {Info.FormatInfo.Format.ToString()}."); + Logger.Debug?.Print(LogClass.Gpu, $" Recreating view {Info.Width}x{Info.Height} {Info.FormatInfo.Format}."); view.ScaleFactor = scale; TextureCreateInfo viewCreateInfo = TextureCache.GetCreateInfo(view.Info, _context.Capabilities, scale); @@ -1254,7 +1254,7 @@ namespace Ryujinx.Graphics.Gpu.Image { FormatInfo formatInfo = TextureCompatibility.ToHostCompatibleFormat(Info, _context.Capabilities); - TextureCreateInfo createInfo = new TextureCreateInfo( + TextureCreateInfo createInfo = new( Info.Width, Info.Height, target == Target.CubemapArray ? 6 : 1, @@ -1274,7 +1274,7 @@ namespace Ryujinx.Graphics.Gpu.Image ITexture viewTexture = HostTexture.CreateView(createInfo, 0, 0); _arrayViewTexture = viewTexture; - _arrayViewTarget = target; + _arrayViewTarget = target; return viewTexture; } @@ -1317,29 +1317,21 @@ namespace Ryujinx.Graphics.Gpu.Image { case Target.Texture1D: case Target.Texture1DArray: - return target == Target.Texture1D || - target == Target.Texture1DArray; - + return target == Target.Texture1D || target == Target.Texture1DArray; case Target.Texture2D: case Target.Texture2DArray: - return target == Target.Texture2D || - target == Target.Texture2DArray; - + return target == Target.Texture2D || target == Target.Texture2DArray; case Target.Cubemap: case Target.CubemapArray: - return target == Target.Cubemap || - target == Target.CubemapArray; - + return target == Target.Cubemap || target == Target.CubemapArray; case Target.Texture2DMultisample: case Target.Texture2DMultisampleArray: - return target == Target.Texture2DMultisample || - target == Target.Texture2DMultisampleArray; - + return target == Target.Texture2DMultisample || target == Target.Texture2DMultisampleArray; case Target.Texture3D: return target == Target.Texture3D; + default: + return false; } - - return false; } /// @@ -1398,7 +1390,7 @@ namespace Ryujinx.Graphics.Gpu.Image Height = info.Height; CanForceAnisotropy = CanTextureForceAnisotropy(); - _depth = info.GetDepth(); + _depth = info.GetDepth(); _layers = info.GetLayers(); } @@ -1714,4 +1706,4 @@ namespace Ryujinx.Graphics.Gpu.Image } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Image/TextureBindingInfo.cs b/src/Ryujinx.Graphics.Gpu/Image/TextureBindingInfo.cs index febe508be..606842d6d 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TextureBindingInfo.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TextureBindingInfo.cs @@ -50,12 +50,12 @@ namespace Ryujinx.Graphics.Gpu.Image /// The texture's usage flags, indicating how it is used in the shader public TextureBindingInfo(Target target, Format format, int binding, int cbufSlot, int handle, TextureUsageFlags flags) { - Target = target; - Format = format; - Binding = binding; + Target = target; + Format = format; + Binding = binding; CbufSlot = cbufSlot; - Handle = handle; - Flags = flags; + Handle = handle; + Flags = flags; } /// @@ -70,4 +70,4 @@ namespace Ryujinx.Graphics.Gpu.Image { } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Image/TextureBindingsManager.cs b/src/Ryujinx.Graphics.Gpu/Image/TextureBindingsManager.cs index b08fb3eb1..e5df17760 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TextureBindingsManager.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TextureBindingsManager.cs @@ -93,10 +93,10 @@ namespace Ryujinx.Graphics.Gpu.Image int stages = isCompute ? 1 : Constants.ShaderStages; _textureBindings = new TextureBindingInfo[stages][]; - _imageBindings = new TextureBindingInfo[stages][]; + _imageBindings = new TextureBindingInfo[stages][]; _textureState = new TextureState[InitialTextureStateSize]; - _imageState = new TextureState[InitialImageStateSize]; + _imageState = new TextureState[InitialImageStateSize]; for (int stage = 0; stage < stages; stage++) { @@ -418,6 +418,7 @@ namespace Ryujinx.Graphics.Gpu.Image } } +#pragma warning disable IDE0051 // Remove unused private member /// /// Counts the total number of texture bindings used by all shader stages. /// @@ -426,16 +427,17 @@ namespace Ryujinx.Graphics.Gpu.Image { int count = 0; - for (int i = 0; i < _textureBindings.Length; i++) + foreach (TextureBindingInfo[] textureInfo in _textureBindings) { - if (_textureBindings[i] != null) + if (textureInfo != null) { - count += _textureBindings[i].Length; + count += textureInfo.Length; } } return count; } +#pragma warning restore IDE0051 /// /// Ensures that the texture bindings are visible to the host GPU. diff --git a/src/Ryujinx.Graphics.Gpu/Image/TextureCache.cs b/src/Ryujinx.Graphics.Gpu/Image/TextureCache.cs index bccd3fd72..3f215a4ac 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TextureCache.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TextureCache.cs @@ -31,7 +31,7 @@ namespace Ryujinx.Graphics.Gpu.Image } private const int OverlapsBufferInitialCapacity = 10; - private const int OverlapsBufferMaxCapacity = 10000; + private const int OverlapsBufferMaxCapacity = 10000; private readonly GpuContext _context; private readonly PhysicalMemory _physicalMemory; @@ -224,7 +224,7 @@ namespace Ryujinx.Graphics.Gpu.Image for (int i = 0; i < overlapCount; i++) { var other = _textureOverlaps[i]; - + if (texture != other && (texture.IsViewCompatible(other.Info, other.Range, true, other.LayerSize, _context.Capabilities, out _, out _) != TextureViewCompatibility.Incompatible || other.IsViewCompatible(texture.Info, texture.Range, true, texture.LayerSize, _context.Capabilities, out _, out _) != TextureViewCompatibility.Incompatible)) @@ -278,7 +278,7 @@ namespace Ryujinx.Graphics.Gpu.Image width = copyTexture.Width; } - TextureInfo info = new TextureInfo( + TextureInfo info = new( copyTexture.Address.Pack() + offset, GetMinimumWidthInGob(width, sizeHint.Width, formatInfo.BytesPerPixel, copyTexture.LinearLayout), copyTexture.Height, @@ -371,16 +371,16 @@ namespace Ryujinx.Graphics.Gpu.Image // so the width we get here is the aligned width. if (isLinear) { - width = colorState.WidthOrStride / formatInfo.BytesPerPixel; + width = colorState.WidthOrStride / formatInfo.BytesPerPixel; stride = colorState.WidthOrStride; } else { - width = colorState.WidthOrStride; + width = colorState.WidthOrStride; stride = 0; } - TextureInfo info = new TextureInfo( + TextureInfo info = new( colorState.Address.Pack(), GetMinimumWidthInGob(width, sizeHint.Width, formatInfo.BytesPerPixel, isLinear), colorState.Height, @@ -449,7 +449,7 @@ namespace Ryujinx.Graphics.Gpu.Image FormatInfo formatInfo = dsState.Format.Convert(); - TextureInfo info = new TextureInfo( + TextureInfo info = new( dsState.Address.Pack(), GetMinimumWidthInGob(size.Width, sizeHint.Width, formatInfo.BytesPerPixel, false), size.Height, @@ -1136,14 +1136,14 @@ namespace Ryujinx.Graphics.Gpu.Image } } - int width = info.Width / info.SamplesInX; + int width = info.Width / info.SamplesInX; int height = info.Height / info.SamplesInY; int depth = info.GetDepth() * info.GetLayers(); if (scale != 1f) { - width = (int)MathF.Ceiling(width * scale); + width = (int)MathF.Ceiling(width * scale); height = (int)MathF.Ceiling(height * scale); } diff --git a/src/Ryujinx.Graphics.Gpu/Image/TextureCompatibility.cs b/src/Ryujinx.Graphics.Gpu/Image/TextureCompatibility.cs index 9a8d048ed..eafa50b2e 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TextureCompatibility.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TextureCompatibility.cs @@ -35,7 +35,7 @@ namespace Ryujinx.Graphics.Gpu.Image Astc10x8, Astc10x10, Astc12x10, - Astc12x12 + Astc12x12, } /// @@ -629,7 +629,7 @@ namespace Ryujinx.Graphics.Gpu.Image { TextureMatchQuality.Perfect => TextureViewCompatibility.Full, TextureMatchQuality.FormatAlias => TextureViewCompatibility.FormatAlias, - _ => TextureViewCompatibility.Incompatible + _ => TextureViewCompatibility.Incompatible, }; } @@ -783,80 +783,33 @@ namespace Ryujinx.Graphics.Gpu.Image /// Format class private static FormatClass GetFormatClass(Format format) { - switch (format) + return format switch { - case Format.Bc1RgbaSrgb: - case Format.Bc1RgbaUnorm: - return FormatClass.Bc1Rgba; - case Format.Bc2Srgb: - case Format.Bc2Unorm: - return FormatClass.Bc2; - case Format.Bc3Srgb: - case Format.Bc3Unorm: - return FormatClass.Bc3; - case Format.Bc4Snorm: - case Format.Bc4Unorm: - return FormatClass.Bc4; - case Format.Bc5Snorm: - case Format.Bc5Unorm: - return FormatClass.Bc5; - case Format.Bc6HSfloat: - case Format.Bc6HUfloat: - return FormatClass.Bc6; - case Format.Bc7Srgb: - case Format.Bc7Unorm: - return FormatClass.Bc7; - case Format.Etc2RgbSrgb: - case Format.Etc2RgbUnorm: - return FormatClass.Etc2Rgb; - case Format.Etc2RgbaSrgb: - case Format.Etc2RgbaUnorm: - return FormatClass.Etc2Rgba; - case Format.Astc4x4Srgb: - case Format.Astc4x4Unorm: - return FormatClass.Astc4x4; - case Format.Astc5x4Srgb: - case Format.Astc5x4Unorm: - return FormatClass.Astc5x4; - case Format.Astc5x5Srgb: - case Format.Astc5x5Unorm: - return FormatClass.Astc5x5; - case Format.Astc6x5Srgb: - case Format.Astc6x5Unorm: - return FormatClass.Astc6x5; - case Format.Astc6x6Srgb: - case Format.Astc6x6Unorm: - return FormatClass.Astc6x6; - case Format.Astc8x5Srgb: - case Format.Astc8x5Unorm: - return FormatClass.Astc8x5; - case Format.Astc8x6Srgb: - case Format.Astc8x6Unorm: - return FormatClass.Astc8x6; - case Format.Astc8x8Srgb: - case Format.Astc8x8Unorm: - return FormatClass.Astc8x8; - case Format.Astc10x5Srgb: - case Format.Astc10x5Unorm: - return FormatClass.Astc10x5; - case Format.Astc10x6Srgb: - case Format.Astc10x6Unorm: - return FormatClass.Astc10x6; - case Format.Astc10x8Srgb: - case Format.Astc10x8Unorm: - return FormatClass.Astc10x8; - case Format.Astc10x10Srgb: - case Format.Astc10x10Unorm: - return FormatClass.Astc10x10; - case Format.Astc12x10Srgb: - case Format.Astc12x10Unorm: - return FormatClass.Astc12x10; - case Format.Astc12x12Srgb: - case Format.Astc12x12Unorm: - return FormatClass.Astc12x12; - } - - return FormatClass.Unclassified; + Format.Bc1RgbaSrgb or Format.Bc1RgbaUnorm => FormatClass.Bc1Rgba, + Format.Bc2Srgb or Format.Bc2Unorm => FormatClass.Bc2, + Format.Bc3Srgb or Format.Bc3Unorm => FormatClass.Bc3, + Format.Bc4Snorm or Format.Bc4Unorm => FormatClass.Bc4, + Format.Bc5Snorm or Format.Bc5Unorm => FormatClass.Bc5, + Format.Bc6HSfloat or Format.Bc6HUfloat => FormatClass.Bc6, + Format.Bc7Srgb or Format.Bc7Unorm => FormatClass.Bc7, + Format.Etc2RgbSrgb or Format.Etc2RgbUnorm => FormatClass.Etc2Rgb, + Format.Etc2RgbaSrgb or Format.Etc2RgbaUnorm => FormatClass.Etc2Rgba, + Format.Astc4x4Srgb or Format.Astc4x4Unorm => FormatClass.Astc4x4, + Format.Astc5x4Srgb or Format.Astc5x4Unorm => FormatClass.Astc5x4, + Format.Astc5x5Srgb or Format.Astc5x5Unorm => FormatClass.Astc5x5, + Format.Astc6x5Srgb or Format.Astc6x5Unorm => FormatClass.Astc6x5, + Format.Astc6x6Srgb or Format.Astc6x6Unorm => FormatClass.Astc6x6, + Format.Astc8x5Srgb or Format.Astc8x5Unorm => FormatClass.Astc8x5, + Format.Astc8x6Srgb or Format.Astc8x6Unorm => FormatClass.Astc8x6, + Format.Astc8x8Srgb or Format.Astc8x8Unorm => FormatClass.Astc8x8, + Format.Astc10x5Srgb or Format.Astc10x5Unorm => FormatClass.Astc10x5, + Format.Astc10x6Srgb or Format.Astc10x6Unorm => FormatClass.Astc10x6, + Format.Astc10x8Srgb or Format.Astc10x8Unorm => FormatClass.Astc10x8, + Format.Astc10x10Srgb or Format.Astc10x10Unorm => FormatClass.Astc10x10, + Format.Astc12x10Srgb or Format.Astc12x10Unorm => FormatClass.Astc12x10, + Format.Astc12x12Srgb or Format.Astc12x12Unorm => FormatClass.Astc12x12, + _ => FormatClass.Unclassified, + }; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Image/TextureComponent.cs b/src/Ryujinx.Graphics.Gpu/Image/TextureComponent.cs index 359069bcf..172d11a83 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TextureComponent.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TextureComponent.cs @@ -7,13 +7,13 @@ namespace Ryujinx.Graphics.Gpu.Image /// enum TextureComponent { - Zero = 0, - Red = 2, + Zero = 0, + Red = 2, Green = 3, - Blue = 4, + Blue = 4, Alpha = 5, OneSI = 6, - OneF = 7 + OneF = 7, } static class TextureComponentConverter @@ -25,19 +25,16 @@ namespace Ryujinx.Graphics.Gpu.Image /// Converted enum public static SwizzleComponent Convert(this TextureComponent component) { - switch (component) + return component switch { - case TextureComponent.Zero: return SwizzleComponent.Zero; - case TextureComponent.Red: return SwizzleComponent.Red; - case TextureComponent.Green: return SwizzleComponent.Green; - case TextureComponent.Blue: return SwizzleComponent.Blue; - case TextureComponent.Alpha: return SwizzleComponent.Alpha; - case TextureComponent.OneSI: - case TextureComponent.OneF: - return SwizzleComponent.One; - } - - return SwizzleComponent.Zero; + TextureComponent.Zero => SwizzleComponent.Zero, + TextureComponent.Red => SwizzleComponent.Red, + TextureComponent.Green => SwizzleComponent.Green, + TextureComponent.Blue => SwizzleComponent.Blue, + TextureComponent.Alpha => SwizzleComponent.Alpha, + TextureComponent.OneSI or TextureComponent.OneF => SwizzleComponent.One, + _ => SwizzleComponent.Zero, + }; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Image/TextureDescriptor.cs b/src/Ryujinx.Graphics.Gpu/Image/TextureDescriptor.cs index 3e35f8d2c..c82a555ee 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TextureDescriptor.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TextureDescriptor.cs @@ -9,7 +9,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// struct TextureDescriptor : ITextureDescriptor, IEquatable { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public uint Word0; public uint Word1; public uint Word2; @@ -24,7 +24,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Unpacks Maxwell texture format integer. /// /// The texture format integer - public uint UnpackFormat() + public readonly uint UnpackFormat() { return Word0 & 0x8007ffff; } @@ -33,43 +33,43 @@ namespace Ryujinx.Graphics.Gpu.Image /// Unpacks the swizzle component for the texture red color channel. /// /// The swizzle component - public TextureComponent UnpackSwizzleR() + public readonly TextureComponent UnpackSwizzleR() { - return(TextureComponent)((Word0 >> 19) & 7); + return (TextureComponent)((Word0 >> 19) & 7); } /// /// Unpacks the swizzle component for the texture green color channel. /// /// The swizzle component - public TextureComponent UnpackSwizzleG() + public readonly TextureComponent UnpackSwizzleG() { - return(TextureComponent)((Word0 >> 22) & 7); + return (TextureComponent)((Word0 >> 22) & 7); } /// /// Unpacks the swizzle component for the texture blue color channel. /// /// The swizzle component - public TextureComponent UnpackSwizzleB() + public readonly TextureComponent UnpackSwizzleB() { - return(TextureComponent)((Word0 >> 25) & 7); + return (TextureComponent)((Word0 >> 25) & 7); } /// /// Unpacks the swizzle component for the texture alpha color channel. /// /// The swizzle component - public TextureComponent UnpackSwizzleA() + public readonly TextureComponent UnpackSwizzleA() { - return(TextureComponent)((Word0 >> 28) & 7); + return (TextureComponent)((Word0 >> 28) & 7); } /// /// Unpacks the 40-bits texture GPU virtual address. /// /// The GPU virtual address - public ulong UnpackAddress() + public readonly ulong UnpackAddress() { return Word1 | ((ulong)(Word2 & 0xffff) << 32); } @@ -79,7 +79,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// This defines the texture layout, among other things. /// /// The texture descriptor type - public TextureDescriptorType UnpackTextureDescriptorType() + public readonly TextureDescriptorType UnpackTextureDescriptorType() { return (TextureDescriptorType)((Word2 >> 21) & 7); } @@ -89,7 +89,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Always 32-bytes aligned. /// /// The linear texture stride - public int UnpackStride() + public readonly int UnpackStride() { return (int)(Word3 & 0xffff) << 5; } @@ -99,7 +99,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Must be always 1, ignored by the GPU. /// /// THe GOB block X size - public int UnpackGobBlocksInX() + public readonly int UnpackGobBlocksInX() { return 1 << (int)(Word3 & 7); } @@ -109,7 +109,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Must be always a power of 2, with a maximum value of 32. /// /// THe GOB block Y size - public int UnpackGobBlocksInY() + public readonly int UnpackGobBlocksInY() { return 1 << (int)((Word3 >> 3) & 7); } @@ -120,7 +120,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Must be 1 for any texture target other than 3D textures. /// /// The GOB block Z size - public int UnpackGobBlocksInZ() + public readonly int UnpackGobBlocksInZ() { return 1 << (int)((Word3 >> 6) & 7); } @@ -130,7 +130,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// This is only used for sparse textures, should be 1 otherwise. /// /// The number of GOB blocks per tile - public int UnpackGobBlocksInTileX() + public readonly int UnpackGobBlocksInTileX() { return 1 << (int)((Word3 >> 10) & 7); } @@ -139,7 +139,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Unpacks the number of mipmap levels of the texture. /// /// The number of mipmap levels - public int UnpackLevels() + public readonly int UnpackLevels() { return (int)(Word3 >> 28) + 1; } @@ -148,7 +148,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Unpack the base level texture width size. /// /// The texture width - public int UnpackWidth() + public readonly int UnpackWidth() { return (int)(Word4 & 0xffff) + 1; } @@ -157,7 +157,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Unpack the width of a buffer texture. /// /// The texture width - public int UnpackBufferTextureWidth() + public readonly int UnpackBufferTextureWidth() { return (int)((Word4 & 0xffff) | (Word3 << 16)) + 1; } @@ -166,7 +166,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Unpacks the texture sRGB format flag. /// /// True if the texture is sRGB, false otherwise - public bool UnpackSrgb() + public readonly bool UnpackSrgb() { return (Word4 & (1 << 22)) != 0; } @@ -175,7 +175,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Unpacks the texture target. /// /// The texture target - public TextureTarget UnpackTextureTarget() + public readonly TextureTarget UnpackTextureTarget() { return (TextureTarget)((Word4 >> 23) & 0xf); } @@ -185,7 +185,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Should be ignored for 1D or buffer textures. /// /// The texture height or layers count - public int UnpackHeight() + public readonly int UnpackHeight() { return (int)(Word5 & 0xffff) + 1; } @@ -195,7 +195,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// The meaning of this value depends on the texture target. /// /// The texture depth, layer or faces count - public int UnpackDepth() + public readonly int UnpackDepth() { return (int)((Word5 >> 16) & 0x3fff) + 1; } @@ -207,7 +207,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// It must be set to false (by the guest driver) for rectangle textures. /// /// The texture coordinates normalized flag - public bool UnpackTextureCoordNormalized() + public readonly bool UnpackTextureCoordNormalized() { return (Word5 & (1 << 31)) != 0; } @@ -216,7 +216,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Unpacks the base mipmap level of the texture. /// /// The base mipmap level of the texture - public int UnpackBaseLevel() + public readonly int UnpackBaseLevel() { return (int)(Word7 & 0xf); } @@ -226,7 +226,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Usually equal to Levels minus 1. /// /// The maximum mipmap level (inclusive) of the texture - public int UnpackMaxLevelInclusive() + public readonly int UnpackMaxLevelInclusive() { return (int)((Word7 >> 4) & 0xf); } @@ -236,7 +236,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Must be ignored for non-multisample textures. /// /// The multisample counts enum - public TextureMsaaMode UnpackTextureMsaaMode() + public readonly TextureMsaaMode UnpackTextureMsaaMode() { return (TextureMsaaMode)((Word7 >> 8) & 0xf); } @@ -269,5 +269,10 @@ namespace Ryujinx.Graphics.Gpu.Image { return Unsafe.As>(ref this).GetHashCode(); } + + public override bool Equals(object obj) + { + return obj is TextureDescriptor descriptor && Equals(descriptor); + } } } diff --git a/src/Ryujinx.Graphics.Gpu/Image/TextureDescriptorType.cs b/src/Ryujinx.Graphics.Gpu/Image/TextureDescriptorType.cs index 8e7d40bbe..ad0715c58 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TextureDescriptorType.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TextureDescriptorType.cs @@ -11,6 +11,6 @@ namespace Ryujinx.Graphics.Gpu.Image LinearColorKey, Linear, BlockLinear, - BlockLinearColorKey + BlockLinearColorKey, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Image/TextureGroup.cs b/src/Ryujinx.Graphics.Gpu/Image/TextureGroup.cs index 2fa1e79e5..1b947cd3b 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TextureGroup.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TextureGroup.cs @@ -78,11 +78,11 @@ namespace Ryujinx.Graphics.Gpu.Image private int[] _allOffsets; private int[] _sliceSizes; - private bool _is3D; + private readonly bool _is3D; private bool _hasMipViews; private bool _hasLayerViews; - private int _layers; - private int _levels; + private readonly int _layers; + private readonly int _levels; private MultiRange TextureRange => Storage.Range; @@ -96,9 +96,9 @@ namespace Ryujinx.Graphics.Gpu.Image /// /// Other texture groups that have incompatible overlaps with this one. /// - private List _incompatibleOverlaps; + private readonly List _incompatibleOverlaps; private bool _incompatibleOverlapsDirty = true; - private bool _flushIncompatibleOverlaps; + private readonly bool _flushIncompatibleOverlaps; private BufferHandle _flushBuffer; private bool _flushBufferImported; @@ -423,7 +423,7 @@ namespace Ryujinx.Graphics.Gpu.Image int offsetIndex = GetOffsetIndex(info.BaseLayer + layer, info.BaseLevel + level); int offset = _allOffsets[offsetIndex]; - ReadOnlySpan data = dataSpan.Slice(offset - spanBase); + ReadOnlySpan data = dataSpan[(offset - spanBase)..]; SpanOrArray result = Storage.ConvertToHostCompatibleFormat(data, info.BaseLevel + level, true); @@ -1500,13 +1500,13 @@ namespace Ryujinx.Graphics.Gpu.Image { for (int i = 0; i < _allOffsets.Length; i++) { - (int layer, int level) = GetLayerLevelForView(i); + (_, int level) = GetLayerLevelForView(i); MultiRange handleRange = Storage.Range.Slice((ulong)_allOffsets[i], 1); ulong handleBase = handleRange.GetSubRange(0).Address; for (int j = 0; j < other._handles.Length; j++) { - (int otherLayer, int otherLevel) = other.GetLayerLevelForView(j); + (_, int otherLevel) = other.GetLayerLevelForView(j); MultiRange otherHandleRange = other.Storage.Range.Slice((ulong)other._allOffsets[j], 1); ulong otherHandleBase = otherHandleRange.GetSubRange(0).Address; diff --git a/src/Ryujinx.Graphics.Gpu/Image/TextureGroupHandle.cs b/src/Ryujinx.Graphics.Gpu/Image/TextureGroupHandle.cs index da8dd849d..ef7198e88 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TextureGroupHandle.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TextureGroupHandle.cs @@ -22,10 +22,10 @@ namespace Ryujinx.Graphics.Gpu.Image private const int FlushBalanceMax = 60; private const int FlushBalanceMin = -10; - private TextureGroup _group; + private readonly TextureGroup _group; private int _bindCount; - private int _firstLevel; - private int _firstLayer; + private readonly int _firstLevel; + private readonly int _firstLayer; // Sync state for texture flush. @@ -463,8 +463,8 @@ namespace Ryujinx.Graphics.Gpu.Image _group.HasCopyDependencies = true; other._group.HasCopyDependencies = true; - TextureDependency dependency = new TextureDependency(this); - TextureDependency otherDependency = new TextureDependency(other); + TextureDependency dependency = new(this); + TextureDependency otherDependency = new(other); dependency.Other = otherDependency; otherDependency.Other = dependency; diff --git a/src/Ryujinx.Graphics.Gpu/Image/TextureInfo.cs b/src/Ryujinx.Graphics.Gpu/Image/TextureInfo.cs index 1994d2263..94d2e0bfc 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TextureInfo.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TextureInfo.cs @@ -134,45 +134,45 @@ namespace Ryujinx.Graphics.Gpu.Image /// Swizzle for the blue color channel /// Swizzle for the alpha color channel public TextureInfo( - ulong gpuAddress, - int width, - int height, - int depthOrLayers, - int levels, - int samplesInX, - int samplesInY, - int stride, - bool isLinear, - int gobBlocksInY, - int gobBlocksInZ, - int gobBlocksInTileX, - Target target, - FormatInfo formatInfo, + ulong gpuAddress, + int width, + int height, + int depthOrLayers, + int levels, + int samplesInX, + int samplesInY, + int stride, + bool isLinear, + int gobBlocksInY, + int gobBlocksInZ, + int gobBlocksInTileX, + Target target, + FormatInfo formatInfo, DepthStencilMode depthStencilMode = DepthStencilMode.Depth, - SwizzleComponent swizzleR = SwizzleComponent.Red, - SwizzleComponent swizzleG = SwizzleComponent.Green, - SwizzleComponent swizzleB = SwizzleComponent.Blue, - SwizzleComponent swizzleA = SwizzleComponent.Alpha) + SwizzleComponent swizzleR = SwizzleComponent.Red, + SwizzleComponent swizzleG = SwizzleComponent.Green, + SwizzleComponent swizzleB = SwizzleComponent.Blue, + SwizzleComponent swizzleA = SwizzleComponent.Alpha) { - GpuAddress = gpuAddress; - Width = width; - Height = height; - DepthOrLayers = depthOrLayers; - Levels = levels; - SamplesInX = samplesInX; - SamplesInY = samplesInY; - Stride = stride; - IsLinear = isLinear; - GobBlocksInY = gobBlocksInY; - GobBlocksInZ = gobBlocksInZ; + GpuAddress = gpuAddress; + Width = width; + Height = height; + DepthOrLayers = depthOrLayers; + Levels = levels; + SamplesInX = samplesInX; + SamplesInY = samplesInY; + Stride = stride; + IsLinear = isLinear; + GobBlocksInY = gobBlocksInY; + GobBlocksInZ = gobBlocksInZ; GobBlocksInTileX = gobBlocksInTileX; - Target = target; - FormatInfo = formatInfo; + Target = target; + FormatInfo = formatInfo; DepthStencilMode = depthStencilMode; - SwizzleR = swizzleR; - SwizzleG = swizzleG; - SwizzleB = swizzleB; - SwizzleA = swizzleA; + SwizzleR = swizzleR; + SwizzleG = swizzleG; + SwizzleB = swizzleB; + SwizzleA = swizzleA; } /// @@ -318,17 +318,17 @@ namespace Ryujinx.Graphics.Gpu.Image // - If the parent format is not compressed, and the view is, the view // size is calculated as described on the first point, but the width and height // of the view must be also multiplied by the block width and height. - int width = Math.Max(1, parent.Info.Width >> firstLevel); + int width = Math.Max(1, parent.Info.Width >> firstLevel); int height = Math.Max(1, parent.Info.Height >> firstLevel); if (parent.Info.FormatInfo.IsCompressed && !FormatInfo.IsCompressed) { - width = BitUtils.DivRoundUp(width, parent.Info.FormatInfo.BlockWidth); + width = BitUtils.DivRoundUp(width, parent.Info.FormatInfo.BlockWidth); height = BitUtils.DivRoundUp(height, parent.Info.FormatInfo.BlockHeight); } else if (!parent.Info.FormatInfo.IsCompressed && FormatInfo.IsCompressed) { - width *= FormatInfo.BlockWidth; + width *= FormatInfo.BlockWidth; height *= FormatInfo.BlockHeight; } @@ -408,4 +408,4 @@ namespace Ryujinx.Graphics.Gpu.Image SwizzleA); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Image/TextureManager.cs b/src/Ryujinx.Graphics.Gpu/Image/TextureManager.cs index 266f62856..63b9b47c3 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TextureManager.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TextureManager.cs @@ -41,8 +41,8 @@ namespace Ryujinx.Graphics.Gpu.Image _context = context; _channel = channel; - TexturePoolCache texturePoolCache = new TexturePoolCache(context); - SamplerPoolCache samplerPoolCache = new SamplerPoolCache(context); + TexturePoolCache texturePoolCache = new(context); + SamplerPoolCache samplerPoolCache = new(context); float[] scales = new float[64]; new Span(scales).Fill(1f); @@ -139,7 +139,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// /// The texture to check /// True if the scale needs updating, false if the scale is up to date - private bool ScaleNeedsUpdated(Texture texture) + private static bool ScaleNeedsUpdated(Texture texture) { return texture != null && !(texture.ScaleMode == TextureScaleMode.Blacklisted || texture.ScaleMode == TextureScaleMode.Undesired) && texture.ScaleFactor != GraphicsConfig.ResScale; } @@ -234,7 +234,11 @@ namespace Ryujinx.Graphics.Gpu.Image void ConsiderTarget(Texture target) { - if (target == null) return; + if (target == null) + { + return; + } + float scale = target.ScaleFactor; switch (target.ScaleMode) @@ -445,7 +449,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// public void UpdateRenderTargetDepthStencil() { - new Span(_rtHostColors).Fill(null); + new Span(_rtHostColors).Clear(); _rtHostDs = _rtDepthStencil?.HostTexture; _context.Renderer.Pipeline.SetRenderTargets(_rtHostColors, _rtHostDs); diff --git a/src/Ryujinx.Graphics.Gpu/Image/TextureMatchQuality.cs b/src/Ryujinx.Graphics.Gpu/Image/TextureMatchQuality.cs index 1351bf242..67835e954 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TextureMatchQuality.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TextureMatchQuality.cs @@ -4,6 +4,6 @@ { NoMatch, FormatAlias, - Perfect + Perfect, } } diff --git a/src/Ryujinx.Graphics.Gpu/Image/TextureMsaaMode.cs b/src/Ryujinx.Graphics.Gpu/Image/TextureMsaaMode.cs index 0461888f1..43b83ae18 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TextureMsaaMode.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TextureMsaaMode.cs @@ -9,7 +9,7 @@ namespace Ryujinx.Graphics.Gpu.Image Ms2x2 = 2, Ms4x2 = 4, Ms2x1 = 5, - Ms4x4 = 6 + Ms4x4 = 6, } static class TextureMsaaModeConverter @@ -27,7 +27,7 @@ namespace Ryujinx.Graphics.Gpu.Image TextureMsaaMode.Ms2x2 => 4, TextureMsaaMode.Ms4x2 => 8, TextureMsaaMode.Ms4x4 => 16, - _ => 1 + _ => 1, }; } @@ -44,7 +44,7 @@ namespace Ryujinx.Graphics.Gpu.Image TextureMsaaMode.Ms2x2 => 2, TextureMsaaMode.Ms4x2 => 4, TextureMsaaMode.Ms4x4 => 4, - _ => 1 + _ => 1, }; } @@ -61,8 +61,8 @@ namespace Ryujinx.Graphics.Gpu.Image TextureMsaaMode.Ms2x2 => 2, TextureMsaaMode.Ms4x2 => 2, TextureMsaaMode.Ms4x4 => 4, - _ => 1 + _ => 1, }; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Image/TexturePool.cs b/src/Ryujinx.Graphics.Gpu/Image/TexturePool.cs index bade9bbb3..0fdb6cd64 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TexturePool.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TexturePool.cs @@ -18,7 +18,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// /// A request to dereference a texture from a pool. /// - private struct DereferenceRequest + private readonly struct DereferenceRequest { /// /// Whether the dereference is due to a mapping change or not. @@ -71,7 +71,7 @@ namespace Ryujinx.Graphics.Gpu.Image } private readonly GpuChannel _channel; - private readonly ConcurrentQueue _dereferenceQueue = new ConcurrentQueue(); + private readonly ConcurrentQueue _dereferenceQueue = new(); private TextureDescriptor _defaultDescriptor; /// @@ -379,10 +379,10 @@ namespace Ryujinx.Graphics.Gpu.Image /// The texture descriptor /// Layer size for textures using a sub-range of mipmap levels, otherwise 0 /// The texture information - private TextureInfo GetInfo(in TextureDescriptor descriptor, out int layerSize) + private static TextureInfo GetInfo(in TextureDescriptor descriptor, out int layerSize) { int depthOrLayers = descriptor.UnpackDepth(); - int levels = descriptor.UnpackLevels(); + int levels = descriptor.UnpackLevels(); TextureMsaaMode msaaMode = descriptor.UnpackTextureMsaaMode(); @@ -424,7 +424,7 @@ namespace Ryujinx.Graphics.Gpu.Image } uint format = descriptor.UnpackFormat(); - bool srgb = descriptor.UnpackSrgb(); + bool srgb = descriptor.UnpackSrgb(); ulong gpuVa = descriptor.UnpackAddress(); @@ -451,7 +451,7 @@ namespace Ryujinx.Graphics.Gpu.Image // Linear textures don't support mipmaps, so we don't handle this case here. if ((minLod != 0 || maxLod + 1 != levels) && target != Target.TextureBuffer && !isLinear) { - int depth = TextureInfo.GetDepth(target, depthOrLayers); + int depth = TextureInfo.GetDepth(target, depthOrLayers); int layers = TextureInfo.GetLayers(target, depthOrLayers); SizeInfo sizeInfo = SizeCalculator.GetBlockLinearTextureSize( @@ -476,7 +476,7 @@ namespace Ryujinx.Graphics.Gpu.Image // address if there is a overlapping texture on the cache that can contain the new texture. gpuVa += (ulong)sizeInfo.GetMipOffset(minLod); - width = Math.Max(1, width >> minLod); + width = Math.Max(1, width >> minLod); height = Math.Max(1, height >> minLod); if (target == Target.Texture3D) @@ -608,4 +608,4 @@ namespace Ryujinx.Graphics.Gpu.Image base.Dispose(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Image/TexturePoolCache.cs b/src/Ryujinx.Graphics.Gpu/Image/TexturePoolCache.cs index 0017f4cc5..5da2c439c 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TexturePoolCache.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TexturePoolCache.cs @@ -27,4 +27,4 @@ namespace Ryujinx.Graphics.Gpu.Image return new TexturePool(context, channel, address, maximumId); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Image/TextureScaleMode.cs b/src/Ryujinx.Graphics.Gpu/Image/TextureScaleMode.cs index b937f5778..5d8e14db3 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TextureScaleMode.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TextureScaleMode.cs @@ -11,6 +11,6 @@ Eligible = 0, Scaled = 1, Blacklisted = 2, - Undesired = 3 + Undesired = 3, } } diff --git a/src/Ryujinx.Graphics.Gpu/Image/TextureSearchFlags.cs b/src/Ryujinx.Graphics.Gpu/Image/TextureSearchFlags.cs index d7b99a173..fb2a97b0b 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TextureSearchFlags.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TextureSearchFlags.cs @@ -8,11 +8,11 @@ namespace Ryujinx.Graphics.Gpu.Image [Flags] enum TextureSearchFlags { - None = 0, - ForSampler = 1 << 1, - ForCopy = 1 << 2, - DepthAlias = 1 << 3, + None = 0, + ForSampler = 1 << 1, + ForCopy = 1 << 2, + DepthAlias = 1 << 3, WithUpscale = 1 << 4, - NoCreate = 1 << 5 + NoCreate = 1 << 5, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Image/TextureTarget.cs b/src/Ryujinx.Graphics.Gpu/Image/TextureTarget.cs index 5e0a0721f..b46b42046 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TextureTarget.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TextureTarget.cs @@ -16,7 +16,7 @@ namespace Ryujinx.Graphics.Gpu.Image Texture2DArray, TextureBuffer, Texture2DRect, - CubemapArray + CubemapArray, } static class TextureTargetConverter @@ -33,23 +33,34 @@ namespace Ryujinx.Graphics.Gpu.Image { switch (target) { - case TextureTarget.Texture2D: return Target.Texture2DMultisample; - case TextureTarget.Texture2DArray: return Target.Texture2DMultisampleArray; + case TextureTarget.Texture2D: + return Target.Texture2DMultisample; + case TextureTarget.Texture2DArray: + return Target.Texture2DMultisampleArray; } } else { switch (target) { - case TextureTarget.Texture1D: return Target.Texture1D; - case TextureTarget.Texture2D: return Target.Texture2D; - case TextureTarget.Texture2DRect: return Target.Texture2D; - case TextureTarget.Texture3D: return Target.Texture3D; - case TextureTarget.Texture1DArray: return Target.Texture1DArray; - case TextureTarget.Texture2DArray: return Target.Texture2DArray; - case TextureTarget.Cubemap: return Target.Cubemap; - case TextureTarget.CubemapArray: return Target.CubemapArray; - case TextureTarget.TextureBuffer: return Target.TextureBuffer; + case TextureTarget.Texture1D: + return Target.Texture1D; + case TextureTarget.Texture2D: + return Target.Texture2D; + case TextureTarget.Texture2DRect: + return Target.Texture2D; + case TextureTarget.Texture3D: + return Target.Texture3D; + case TextureTarget.Texture1DArray: + return Target.Texture1DArray; + case TextureTarget.Texture2DArray: + return Target.Texture2DArray; + case TextureTarget.Cubemap: + return Target.Cubemap; + case TextureTarget.CubemapArray: + return Target.CubemapArray; + case TextureTarget.TextureBuffer: + return Target.TextureBuffer; } } @@ -65,17 +76,17 @@ namespace Ryujinx.Graphics.Gpu.Image { return target switch { - TextureTarget.Texture1D => SamplerType.Texture1D, - TextureTarget.Texture2D => SamplerType.Texture2D, - TextureTarget.Texture3D => SamplerType.Texture3D, - TextureTarget.Cubemap => SamplerType.TextureCube, + TextureTarget.Texture1D => SamplerType.Texture1D, + TextureTarget.Texture2D => SamplerType.Texture2D, + TextureTarget.Texture3D => SamplerType.Texture3D, + TextureTarget.Cubemap => SamplerType.TextureCube, TextureTarget.Texture1DArray => SamplerType.Texture1D | SamplerType.Array, TextureTarget.Texture2DArray => SamplerType.Texture2D | SamplerType.Array, - TextureTarget.TextureBuffer => SamplerType.TextureBuffer, - TextureTarget.Texture2DRect => SamplerType.Texture2D, - TextureTarget.CubemapArray => SamplerType.TextureCube | SamplerType.Array, - _ => SamplerType.Texture2D + TextureTarget.TextureBuffer => SamplerType.TextureBuffer, + TextureTarget.Texture2DRect => SamplerType.Texture2D, + TextureTarget.CubemapArray => SamplerType.TextureCube | SamplerType.Array, + _ => SamplerType.Texture2D, }; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Image/TextureViewCompatibility.cs b/src/Ryujinx.Graphics.Gpu/Image/TextureViewCompatibility.cs index dfa688c45..3f3bfdfef 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TextureViewCompatibility.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TextureViewCompatibility.cs @@ -10,6 +10,6 @@ LayoutIncompatible, CopyOnly, FormatAlias, - Full + Full, } } diff --git a/src/Ryujinx.Graphics.Gpu/Memory/Buffer.cs b/src/Ryujinx.Graphics.Gpu/Memory/Buffer.cs index dc5037c56..e27c14a16 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/Buffer.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/Buffer.cs @@ -62,7 +62,7 @@ namespace Ryujinx.Graphics.Gpu.Memory private int _sequenceNumber; - private bool _useGranular; + private readonly bool _useGranular; private bool _syncActionRegistered; private int _referenceCount = 1; @@ -80,10 +80,10 @@ namespace Ryujinx.Graphics.Gpu.Memory /// Buffers which this buffer contains, and will inherit tracking handles from public Buffer(GpuContext context, PhysicalMemory physicalMemory, ulong address, ulong size, IEnumerable baseBuffers = null) { - _context = context; + _context = context; _physicalMemory = physicalMemory; - Address = address; - Size = size; + Address = address; + Size = size; Handle = context.Renderer.CreateBuffer((int)size, baseBuffers?.MaxBy(x => x.Size).Handle ?? BufferHandle.Null); @@ -252,10 +252,7 @@ namespace Ryujinx.Graphics.Gpu.Memory /// private void EnsureRangeList() { - if (_modifiedRanges == null) - { - _modifiedRanges = new BufferModifiedRangeList(_context, this, Flush); - } + _modifiedRanges ??= new BufferModifiedRangeList(_context, this, Flush); } /// @@ -326,7 +323,7 @@ namespace Ryujinx.Graphics.Gpu.Memory _syncActionRegistered = true; } - Action registerRangeAction = (ulong address, ulong size) => + void registerRangeAction(ulong address, ulong size) { if (_useGranular) { @@ -336,7 +333,7 @@ namespace Ryujinx.Graphics.Gpu.Memory { _memoryTracking.RegisterAction(_externalFlushDelegate); } - }; + } EnsureRangeList(); @@ -643,4 +640,4 @@ namespace Ryujinx.Graphics.Gpu.Memory DecrementReferenceCount(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Memory/BufferBounds.cs b/src/Ryujinx.Graphics.Gpu/Memory/BufferBounds.cs index d513b7adf..a9ea04cef 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/BufferBounds.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/BufferBounds.cs @@ -35,4 +35,4 @@ namespace Ryujinx.Graphics.Gpu.Memory Flags = flags; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Memory/BufferCache.cs b/src/Ryujinx.Graphics.Gpu/Memory/BufferCache.cs index a5a9b75e9..99c571ba5 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/BufferCache.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/BufferCache.cs @@ -12,7 +12,7 @@ namespace Ryujinx.Graphics.Gpu.Memory class BufferCache : IDisposable { private const int OverlapsBufferInitialCapacity = 10; - private const int OverlapsBufferMaxCapacity = 10000; + private const int OverlapsBufferMaxCapacity = 10000; private const ulong BufferAlignmentSize = 0x1000; private const ulong BufferAlignmentMask = BufferAlignmentSize - 1; @@ -246,7 +246,7 @@ namespace Ryujinx.Graphics.Gpu.Memory { Buffer buffer = _bufferOverlaps[index]; - address = Math.Min(address, buffer.Address); + address = Math.Min(address, buffer.Address); endAddress = Math.Max(endAddress, buffer.EndAddress); lock (_buffers) @@ -257,7 +257,7 @@ namespace Ryujinx.Graphics.Gpu.Memory ulong newSize = endAddress - address; - Buffer newBuffer = new Buffer(_context, _physicalMemory, address, newSize, _bufferOverlaps.Take(overlapsCount)); + Buffer newBuffer = new(_context, _physicalMemory, address, newSize, _bufferOverlaps.Take(overlapsCount)); lock (_buffers) { @@ -285,7 +285,7 @@ namespace Ryujinx.Graphics.Gpu.Memory else { // No overlap, just create a new buffer. - Buffer buffer = new Buffer(_context, _physicalMemory, address, size); + Buffer buffer = new(_context, _physicalMemory, address, size); lock (_buffers) { @@ -446,7 +446,7 @@ namespace Ryujinx.Graphics.Gpu.Memory /// /// Dictionary to prune /// List used to track entries to delete - private void Prune(Dictionary dictionary, ref List toDelete) + private static void Prune(Dictionary dictionary, ref List toDelete) { foreach (var entry in dictionary) { @@ -504,4 +504,4 @@ namespace Ryujinx.Graphics.Gpu.Memory } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Memory/BufferManager.cs b/src/Ryujinx.Graphics.Gpu/Memory/BufferManager.cs index 07429cfe8..4cd3710b9 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/BufferManager.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/BufferManager.cs @@ -105,7 +105,7 @@ namespace Ryujinx.Graphics.Gpu.Memory private readonly BuffersPerStage[] _gpUniformBuffers; private BufferHandle _tfInfoBuffer; - private int[] _tfInfoData; + private readonly int[] _tfInfoData; private bool _gpStorageBuffersDirty; private bool _gpUniformBuffersDirty; @@ -777,11 +777,11 @@ namespace Ryujinx.Graphics.Gpu.Memory { if (isStorage) { - _context.Renderer.Pipeline.SetStorageBuffers(ranges.Slice(0, count)); + _context.Renderer.Pipeline.SetStorageBuffers(ranges[..count]); } else { - _context.Renderer.Pipeline.SetUniformBuffers(ranges.Slice(0, count)); + _context.Renderer.Pipeline.SetUniformBuffers(ranges[..count]); } } diff --git a/src/Ryujinx.Graphics.Gpu/Memory/BufferModifiedRangeList.cs b/src/Ryujinx.Graphics.Gpu/Memory/BufferModifiedRangeList.cs index 03504b11f..160a9aff7 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/BufferModifiedRangeList.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/BufferModifiedRangeList.cs @@ -1,5 +1,4 @@ -using Ryujinx.Common.Logging; -using Ryujinx.Common.Pools; +using Ryujinx.Common.Pools; using Ryujinx.Memory.Range; using System; using System.Collections.Generic; @@ -71,9 +70,9 @@ namespace Ryujinx.Graphics.Gpu.Memory { private const int BackingInitialSize = 8; - private GpuContext _context; - private Buffer _parent; - private Action _flushAction; + private readonly GpuContext _context; + private readonly Buffer _parent; + private readonly Action _flushAction; private List _sources; private BufferMigration _migrationTarget; diff --git a/src/Ryujinx.Graphics.Gpu/Memory/CounterCache.cs b/src/Ryujinx.Graphics.Gpu/Memory/CounterCache.cs index e763a899c..6dcc52cb6 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/CounterCache.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/CounterCache.cs @@ -34,11 +34,12 @@ namespace Ryujinx.Graphics.Gpu.Memory /// Adds a new counter to the counter cache, or updates a existing one. /// /// GPU virtual address where the counter will be written in memory + /// The new counter public void AddOrUpdate(ulong gpuVa, ICounterEvent evt) { int index = BinarySearch(gpuVa); - CounterEntry entry = new CounterEntry(gpuVa, evt); + CounterEntry entry = new(gpuVa, evt); if (index < 0) { @@ -127,7 +128,7 @@ namespace Ryujinx.Graphics.Gpu.Memory _items[index].Event?.Flush(); return true; - } + } else { return false; @@ -168,7 +169,7 @@ namespace Ryujinx.Graphics.Gpu.Memory int middle = left + (range >> 1); - CounterEntry item = _items[middle]; + CounterEntry item = _items[middle]; if (item.Address == address) { diff --git a/src/Ryujinx.Graphics.Gpu/Memory/IndexBuffer.cs b/src/Ryujinx.Graphics.Gpu/Memory/IndexBuffer.cs index 7765e8994..c72fa50e5 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/IndexBuffer.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/IndexBuffer.cs @@ -12,4 +12,4 @@ namespace Ryujinx.Graphics.Gpu.Memory public IndexType Type; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Memory/MemoryManager.cs b/src/Ryujinx.Graphics.Gpu/Memory/MemoryManager.cs index c7a138c98..6af12de11 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/MemoryManager.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/MemoryManager.cs @@ -14,15 +14,15 @@ namespace Ryujinx.Graphics.Gpu.Memory { private const int PtLvl0Bits = 14; private const int PtLvl1Bits = 14; - public const int PtPageBits = 12; + public const int PtPageBits = 12; private const ulong PtLvl0Size = 1UL << PtLvl0Bits; private const ulong PtLvl1Size = 1UL << PtLvl1Bits; - public const ulong PageSize = 1UL << PtPageBits; + public const ulong PageSize = 1UL << PtPageBits; private const ulong PtLvl0Mask = PtLvl0Size - 1; private const ulong PtLvl1Mask = PtLvl1Size - 1; - public const ulong PageMask = PageSize - 1; + public const ulong PageMask = PageSize - 1; private const int PtLvl0Bit = PtPageBits + PtLvl1Bits; private const int PtLvl1Bit = PtPageBits; @@ -203,7 +203,7 @@ namespace Ryujinx.Graphics.Gpu.Memory size = Math.Min(data.Length, (int)PageSize - (int)(va & PageMask)); - Physical.GetSpan(pa, size, tracked).CopyTo(data.Slice(0, size)); + Physical.GetSpan(pa, size, tracked).CopyTo(data[..size]); offset += size; } @@ -306,7 +306,7 @@ namespace Ryujinx.Graphics.Gpu.Memory size = Math.Min(data.Length, (int)PageSize - (int)(va & PageMask)); - writeCallback(pa, data.Slice(0, size)); + writeCallback(pa, data[..size]); offset += size; } @@ -345,7 +345,7 @@ namespace Ryujinx.Graphics.Gpu.Memory if (pa != PteUnmapped && Physical.IsMapped(pa)) { - Physical.Write(pa, data.Slice(0, size)); + Physical.Write(pa, data[..size]); } offset += size; @@ -370,7 +370,7 @@ namespace Ryujinx.Graphics.Gpu.Memory /// These must run after the mapping completes. /// /// Event with remap actions - private void RunRemapActions(UnmapEventArgs e) + private static void RunRemapActions(UnmapEventArgs e) { if (e.RemapActions != null) { @@ -759,4 +759,4 @@ namespace Ryujinx.Graphics.Gpu.Memory return pte & 0xffffffffffffffUL; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Memory/PhysicalMemory.cs b/src/Ryujinx.Graphics.Gpu/Memory/PhysicalMemory.cs index cb95b04a8..d0b4478e1 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/PhysicalMemory.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/PhysicalMemory.cs @@ -19,7 +19,7 @@ namespace Ryujinx.Graphics.Gpu.Memory class PhysicalMemory : IDisposable { private readonly GpuContext _context; - private IVirtualMemoryManagerTracked _cpuMemory; + private readonly IVirtualMemoryManagerTracked _cpuMemory; private int _referenceCount; /// @@ -438,4 +438,4 @@ namespace Ryujinx.Graphics.Gpu.Memory DecrementReferenceCount(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Memory/PteKind.cs b/src/Ryujinx.Graphics.Gpu/Memory/PteKind.cs index 4ceb6bcf4..1585328f0 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/PteKind.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/PteKind.cs @@ -250,7 +250,7 @@ namespace Ryujinx.Graphics.Gpu.Memory X8C24 = 0xfc, PitchNoSwizzle = 0xfd, SmSkedMessage = 0xca, - SmHostMessage = 0xcb + SmHostMessage = 0xcb, } static class PteKindExtensions @@ -265,4 +265,4 @@ namespace Ryujinx.Graphics.Gpu.Memory return kind == PteKind.Pitch || kind == PteKind.PitchNoSwizzle; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Memory/ResourceKind.cs b/src/Ryujinx.Graphics.Gpu/Memory/ResourceKind.cs index 55d697b81..5d2ada566 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/ResourceKind.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/ResourceKind.cs @@ -8,6 +8,6 @@ namespace Ryujinx.Graphics.Gpu.Memory None, Buffer, Texture, - Pool + Pool, } } diff --git a/src/Ryujinx.Graphics.Gpu/Memory/VertexBuffer.cs b/src/Ryujinx.Graphics.Gpu/Memory/VertexBuffer.cs index 8f0891251..ac334881d 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/VertexBuffer.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/VertexBuffer.cs @@ -7,7 +7,7 @@ namespace Ryujinx.Graphics.Gpu.Memory { public ulong Address; public ulong Size; - public int Stride; - public int Divisor; + public int Stride; + public int Divisor; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/CachedShaderStage.cs b/src/Ryujinx.Graphics.Gpu/Shader/CachedShaderStage.cs index 22b08dd5a..2381991dd 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/CachedShaderStage.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/CachedShaderStage.cs @@ -35,4 +35,4 @@ namespace Ryujinx.Graphics.Gpu.Shader Cb1Data = cb1Data; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/ComputeShaderCacheHashTable.cs b/src/Ryujinx.Graphics.Gpu/Shader/ComputeShaderCacheHashTable.cs index a67182112..0119a6a33 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/ComputeShaderCacheHashTable.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/ComputeShaderCacheHashTable.cs @@ -50,8 +50,9 @@ namespace Ryujinx.Graphics.Gpu.Shader out byte[] cachedGuestCode) { program = null; - ShaderCodeAccessor codeAccessor = new ShaderCodeAccessor(channel.MemoryManager, gpuVa); + ShaderCodeAccessor codeAccessor = new(channel.MemoryManager, gpuVa); bool hasSpecList = _cache.TryFindItem(codeAccessor, out var specList, out cachedGuestCode); + return hasSpecList && specList.TryFindForCompute(channel, poolState, computeState, out program); } @@ -67,4 +68,4 @@ namespace Ryujinx.Graphics.Gpu.Shader } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/BackgroundDiskCacheWriter.cs b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/BackgroundDiskCacheWriter.cs index 568fe9683..e0f17ba9c 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/BackgroundDiskCacheWriter.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/BackgroundDiskCacheWriter.cs @@ -18,7 +18,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// /// Operation to add a shader to the cache. /// - AddShader + AddShader, } /// diff --git a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/BinarySerializer.cs b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/BinarySerializer.cs index 50e37033e..b08c44d67 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/BinarySerializer.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/BinarySerializer.cs @@ -29,12 +29,12 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// /// Type of the data /// Data read - public void Read(ref T data) where T : unmanaged + public readonly void Read(ref T data) where T : unmanaged { Span buffer = MemoryMarshal.Cast(MemoryMarshal.CreateSpan(ref data, 1)); for (int offset = 0; offset < buffer.Length;) { - offset += _activeStream.Read(buffer.Slice(offset)); + offset += _activeStream.Read(buffer[offset..]); } } @@ -44,7 +44,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// Type of the data /// Data read /// True if the read was successful, false otherwise - public bool TryRead(ref T data) where T : unmanaged + public readonly bool TryRead(ref T data) where T : unmanaged { // Length is unknown on compressed streams. if (_activeStream == _stream) @@ -66,7 +66,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// Type of the data /// Data read /// Expected magic value, for validation - public void ReadWithMagicAndSize(ref T data, uint magic) where T : unmanaged + public readonly void ReadWithMagicAndSize(ref T data, uint magic) where T : unmanaged { uint actualMagic = 0; int size = 0; @@ -84,10 +84,10 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache throw new DiskCacheLoadException(DiskCacheLoadResult.FileCorruptedInvalidLength); } - Span buffer = MemoryMarshal.Cast(MemoryMarshal.CreateSpan(ref data, 1)).Slice(0, size); + Span buffer = MemoryMarshal.Cast(MemoryMarshal.CreateSpan(ref data, 1))[..size]; for (int offset = 0; offset < buffer.Length;) { - offset += _activeStream.Read(buffer.Slice(offset)); + offset += _activeStream.Read(buffer[offset..]); } } @@ -96,7 +96,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// /// Type of the data /// Data to be written - public void Write(ref T data) where T : unmanaged + public readonly void Write(ref T data) where T : unmanaged { Span buffer = MemoryMarshal.Cast(MemoryMarshal.CreateSpan(ref data, 1)); _activeStream.Write(buffer); @@ -108,7 +108,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// Type of the data /// Data to write /// Magic value to write - public void WriteWithMagicAndSize(ref T data, uint magic) where T : unmanaged + public readonly void WriteWithMagicAndSize(ref T data, uint magic) where T : unmanaged { int size = Unsafe.SizeOf(); Write(ref magic); @@ -183,7 +183,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache stream = new DeflateStream(stream, CompressionMode.Decompress, true); for (int offset = 0; offset < data.Length;) { - offset += stream.Read(data.Slice(offset)); + offset += stream.Read(data[offset..]); } stream.Dispose(); break; @@ -213,4 +213,4 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/CompressionAlgorithm.cs b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/CompressionAlgorithm.cs index a46e1ef76..96ddbb513 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/CompressionAlgorithm.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/CompressionAlgorithm.cs @@ -13,6 +13,6 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// /// Deflate compression (RFC 1951). /// - Deflate + Deflate, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheCommon.cs b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheCommon.cs index c8a9f7ff2..c4ce0b870 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheCommon.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheCommon.cs @@ -54,4 +54,4 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache return CompressionAlgorithm.Deflate; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheGpuAccessor.cs b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheGpuAccessor.cs index 537cead0e..7f01aca63 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheGpuAccessor.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheGpuAccessor.cs @@ -19,7 +19,6 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache private readonly ShaderSpecializationState _newSpecState; private readonly int _stageIndex; private readonly bool _isVulkan; - private readonly ResourceCounts _resourceCounts; /// /// Creates a new instance of the cached GPU state accessor for shader translation. @@ -45,7 +44,6 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache _newSpecState = newSpecState; _stageIndex = stageIndex; _isVulkan = context.Capabilities.Api == TargetApi.Vulkan; - _resourceCounts = counts; } /// @@ -56,7 +54,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache throw new DiskCacheLoadException(DiskCacheLoadResult.InvalidCb1DataLength); } - return MemoryMarshal.Cast(_cb1Data.Span.Slice(offset))[0]; + return MemoryMarshal.Cast(_cb1Data.Span[offset..])[0]; } /// @@ -68,7 +66,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// public ReadOnlySpan GetCode(ulong address, int minimumSize) { - return MemoryMarshal.Cast(_data.Span.Slice((int)address)); + return MemoryMarshal.Cast(_data.Span[(int)address..]); } /// @@ -94,7 +92,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache CompareOp.Greater or CompareOp.GreaterGl => AlphaTestOp.Greater, CompareOp.NotEqual or CompareOp.NotEqualGl => AlphaTestOp.NotEqual, CompareOp.GreaterOrEqual or CompareOp.GreaterOrEqualGl => AlphaTestOp.GreaterOrEqual, - _ => AlphaTestOp.Always + _ => AlphaTestOp.Always, }; } diff --git a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheGuestStorage.cs b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheGuestStorage.cs index 01034b495..59d2cfb3f 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheGuestStorage.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheGuestStorage.cs @@ -205,10 +205,10 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache if (guestCode == null || cb1Data == null) { - BinarySerializer tocReader = new BinarySerializer(tocFileStream); + BinarySerializer tocReader = new(tocFileStream); tocFileStream.Seek(Unsafe.SizeOf() + index * Unsafe.SizeOf(), SeekOrigin.Begin); - TocEntry entry = new TocEntry(); + TocEntry entry = new(); tocReader.Read(ref entry); guestCode = new byte[entry.CodeSize]; @@ -261,7 +261,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache using var tocFileStream = DiskCacheCommon.OpenFile(_basePath, TocFileName, writable: true); using var dataFileStream = DiskCacheCommon.OpenFile(_basePath, DataFileName, writable: true); - TocHeader header = new TocHeader(); + TocHeader header = new(); LoadOrCreateToc(tocFileStream, ref header); @@ -299,7 +299,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// Set to the TOC file header private void LoadOrCreateToc(Stream tocFileStream, ref TocHeader header) { - BinarySerializer reader = new BinarySerializer(tocFileStream); + BinarySerializer reader = new(tocFileStream); if (!reader.TryRead(ref header) || header.Magic != TocMagic || header.Version != VersionPacked) { @@ -322,9 +322,9 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// /// Guest TOC file stream /// Set to the TOC header - private void CreateToc(Stream tocFileStream, ref TocHeader header) + private static void CreateToc(Stream tocFileStream, ref TocHeader header) { - BinarySerializer writer = new BinarySerializer(tocFileStream); + BinarySerializer writer = new(tocFileStream); header.Magic = TocMagic; header.Version = VersionPacked; @@ -352,7 +352,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache { _toc = new Dictionary>(); - TocEntry entry = new TocEntry(); + TocEntry entry = new(); int index = 0; while (tocFileStream.Position < tocFileStream.Length) @@ -386,7 +386,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache ReadOnlySpan cb1Data, uint hash) { - BinarySerializer tocWriter = new BinarySerializer(tocFileStream); + BinarySerializer tocWriter = new(tocFileStream); dataFileStream.Seek(0, SeekOrigin.End); uint dataOffset = checked((uint)dataFileStream.Position); @@ -399,12 +399,12 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache tocFileStream.Seek(0, SeekOrigin.Begin); tocWriter.Write(ref header); - TocEntry entry = new TocEntry() + TocEntry entry = new() { Offset = dataOffset, CodeSize = codeSize, Cb1DataSize = cb1DataSize, - Hash = hash + Hash = hash, }; tocFileStream.Seek(0, SeekOrigin.End); @@ -456,4 +456,4 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache return (uint)XXHash128.ComputeHash(data).Low; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheHostStorage.cs b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheHostStorage.cs index 267112865..95a0a6bdd 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheHostStorage.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheHostStorage.cs @@ -221,7 +221,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache int indexOfSpace = fileName.IndexOf(' '); if (indexOfSpace >= 0) { - fileName = fileName.Substring(0, indexOfSpace); + fileName = fileName[..indexOfSpace]; } return string.Concat(fileName.Split(Path.GetInvalidFileNameChars(), StringSplitOptions.RemoveEmptyEntries)); @@ -287,10 +287,10 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache using var guestTocFileStream = _guestStorage.OpenTocFileStream(); using var guestDataFileStream = _guestStorage.OpenDataFileStream(); - BinarySerializer tocReader = new BinarySerializer(tocFileStream); - BinarySerializer dataReader = new BinarySerializer(dataFileStream); + BinarySerializer tocReader = new(tocFileStream); + BinarySerializer dataReader = new(dataFileStream); - TocHeader header = new TocHeader(); + TocHeader header = new(); if (!tocReader.TryRead(ref header) || header.Magic != TocsMagic) { @@ -306,7 +306,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache int programIndex = 0; - DataEntry entry = new DataEntry(); + DataEntry entry = new(); while (tocFileStream.Position < tocFileStream.Length && loader.Active) { @@ -337,7 +337,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache GuestCodeAndCbData?[] guestShaders = new GuestCodeAndCbData?[isCompute ? 1 : Constants.ShaderStages + 1]; - DataEntryPerStage stageEntry = new DataEntryPerStage(); + DataEntryPerStage stageEntry = new(); while (stagesBitMask != 0) { @@ -389,7 +389,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache hostProgram = context.Renderer.LoadProgramBinary(hostCode, hasFragmentShader, shaderInfo); } - CachedShaderProgram program = new CachedShaderProgram(hostProgram, specState, shaders); + CachedShaderProgram program = new(hostProgram, specState, shaders); loader.QueueHostProgram(program, hostCode, programIndex, isCompute); } @@ -448,9 +448,9 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache tocFileStream = DiskCacheCommon.OpenFile(_basePath, GetHostTocFileName(context), writable: false); dataFileStream = DiskCacheCommon.OpenFile(_basePath, GetHostDataFileName(context), writable: false); - BinarySerializer tempTocReader = new BinarySerializer(tocFileStream); + BinarySerializer tempTocReader = new(tocFileStream); - TocHeader header = new TocHeader(); + TocHeader header = new(); tempTocReader.Read(ref header); @@ -473,9 +473,9 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache tocFileStream.Seek(offset, SeekOrigin.Begin); - BinarySerializer tocReader = new BinarySerializer(tocFileStream); + BinarySerializer tocReader = new(tocFileStream); - OffsetAndSize offsetAndSize = new OffsetAndSize(); + OffsetAndSize offsetAndSize = new(); tocReader.Read(ref offsetAndSize); if (offsetAndSize.Offset >= (ulong)dataFileStream.Length) @@ -490,7 +490,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache BinarySerializer.ReadCompressed(dataFileStream, hostCode); CachedShaderStage[] shaders = new CachedShaderStage[guestShaders.Length]; - BinarySerializer dataReader = new BinarySerializer(dataFileStream); + BinarySerializer dataReader = new(dataFileStream); dataFileStream.Seek((long)(offsetAndSize.Offset + offsetAndSize.CompressedSize), SeekOrigin.Begin); @@ -559,27 +559,28 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache if (tocFileStream.Length == 0) { - TocHeader header = new TocHeader(); + TocHeader header = new(); CreateToc(tocFileStream, ref header, TocsMagic, CodeGenVersion, timestamp); } tocFileStream.Seek(0, SeekOrigin.End); dataFileStream.Seek(0, SeekOrigin.End); - BinarySerializer tocWriter = new BinarySerializer(tocFileStream); - BinarySerializer dataWriter = new BinarySerializer(dataFileStream); + BinarySerializer tocWriter = new(tocFileStream); + BinarySerializer dataWriter = new(dataFileStream); ulong dataOffset = (ulong)dataFileStream.Position; tocWriter.Write(ref dataOffset); - DataEntry entry = new DataEntry(); - - entry.StagesBitMask = stagesBitMask; + DataEntry entry = new() + { + StagesBitMask = stagesBitMask, + }; dataWriter.BeginCompression(DiskCacheCommon.GetCompressionAlgorithm()); dataWriter.Write(ref entry); - DataEntryPerStage stageEntry = new DataEntryPerStage(); + DataEntryPerStage stageEntry = new(); for (int index = 0; index < program.Shaders.Length; index++) { @@ -665,19 +666,21 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache if (tocFileStream.Length == 0) { - TocHeader header = new TocHeader(); + TocHeader header = new(); CreateToc(tocFileStream, ref header, TochMagic, 0, timestamp); } tocFileStream.Seek(0, SeekOrigin.End); dataFileStream.Seek(0, SeekOrigin.End); - BinarySerializer tocWriter = new BinarySerializer(tocFileStream); - BinarySerializer dataWriter = new BinarySerializer(dataFileStream); + BinarySerializer tocWriter = new(tocFileStream); + BinarySerializer dataWriter = new(dataFileStream); - OffsetAndSize offsetAndSize = new OffsetAndSize(); - offsetAndSize.Offset = (ulong)dataFileStream.Position; - offsetAndSize.UncompressedSize = (uint)hostCode.Length; + OffsetAndSize offsetAndSize = new() + { + Offset = (ulong)dataFileStream.Position, + UncompressedSize = (uint)hostCode.Length, + }; long dataStartPosition = dataFileStream.Position; @@ -714,9 +717,9 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// Magic value to be written /// Shader codegen version, only valid for the host file /// File creation timestamp - private void CreateToc(Stream tocFileStream, ref TocHeader header, uint magic, uint codegenVersion, ulong timestamp) + private static void CreateToc(Stream tocFileStream, ref TocHeader header, uint magic, uint codegenVersion, ulong timestamp) { - BinarySerializer writer = new BinarySerializer(tocFileStream); + BinarySerializer writer = new(tocFileStream); header.Magic = magic; header.FormatVersion = FileFormatVersionPacked; @@ -741,7 +744,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// Shader program info private static ShaderProgramInfo ReadShaderProgramInfo(ref BinarySerializer dataReader) { - DataShaderInfo dataInfo = new DataShaderInfo(); + DataShaderInfo dataInfo = new(); dataReader.ReadWithMagicAndSize(ref dataInfo, ShdiMagic); @@ -797,18 +800,19 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache return; } - DataShaderInfo dataInfo = new DataShaderInfo(); - - dataInfo.CBuffersCount = (ushort)info.CBuffers.Count; - dataInfo.SBuffersCount = (ushort)info.SBuffers.Count; - dataInfo.TexturesCount = (ushort)info.Textures.Count; - dataInfo.ImagesCount = (ushort)info.Images.Count; - dataInfo.Stage = info.Stage; - dataInfo.UsesInstanceId = info.UsesInstanceId; - dataInfo.UsesDrawParameters = info.UsesDrawParameters; - dataInfo.UsesRtLayer = info.UsesRtLayer; - dataInfo.ClipDistancesWritten = info.ClipDistancesWritten; - dataInfo.FragmentOutputMap = info.FragmentOutputMap; + DataShaderInfo dataInfo = new() + { + CBuffersCount = (ushort)info.CBuffers.Count, + SBuffersCount = (ushort)info.SBuffers.Count, + TexturesCount = (ushort)info.Textures.Count, + ImagesCount = (ushort)info.Images.Count, + Stage = info.Stage, + UsesInstanceId = info.UsesInstanceId, + UsesDrawParameters = info.UsesDrawParameters, + UsesRtLayer = info.UsesRtLayer, + ClipDistancesWritten = info.ClipDistancesWritten, + FragmentOutputMap = info.FragmentOutputMap, + }; dataWriter.WriteWithMagicAndSize(ref dataInfo, ShdiMagic); diff --git a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheLoadException.cs b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheLoadException.cs index d6e23302c..9320638ca 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheLoadException.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheLoadException.cs @@ -45,4 +45,4 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache Result = result; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheLoadResult.cs b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheLoadResult.cs index b3ffa4a73..ba23f70ee 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheLoadResult.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheLoadResult.cs @@ -43,7 +43,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// /// File might be valid, but is incompatible with the current emulator version. /// - IncompatibleVersion + IncompatibleVersion, } static class DiskCacheLoadResultExtensions @@ -65,8 +65,8 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache DiskCacheLoadResult.FileCorruptedInvalidMagic => "Magic check failed, the cache file is corrupted.", DiskCacheLoadResult.FileCorruptedInvalidLength => "Length check failed, the cache file is corrupted.", DiskCacheLoadResult.IncompatibleVersion => "The version of the disk cache is not compatible with this version of the emulator.", - _ => "Unknown error." + _ => "Unknown error.", }; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/GuestCodeAndCbData.cs b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/GuestCodeAndCbData.cs index 959d6e184..f412c62e2 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/GuestCodeAndCbData.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/GuestCodeAndCbData.cs @@ -26,4 +26,4 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache Cb1Data = cb1Data; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/ParallelDiskCacheLoader.cs b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/ParallelDiskCacheLoader.cs index 8df89824b..8c2108bfa 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/ParallelDiskCacheLoader.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/ParallelDiskCacheLoader.cs @@ -190,7 +190,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache private readonly BlockingCollection _asyncTranslationQueue; private readonly SortedList _programList; - private int _backendParallelCompileThreads; + private readonly int _backendParallelCompileThreads; private int _compiledCount; private int _totalCount; @@ -201,22 +201,21 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// Graphics shader cache /// Compute shader cache /// Disk cache host storage - /// Cancellation token /// Function to be called when there is a state change, reporting state, compiled and total shaders count - public ParallelDiskCacheLoader( - GpuContext context, + /// Cancellation token + public ParallelDiskCacheLoader(GpuContext context, ShaderCacheHashTable graphicsCache, ComputeShaderCacheHashTable computeCache, DiskCacheHostStorage hostStorage, - CancellationToken cancellationToken, - Action stateChangeCallback) + Action stateChangeCallback, + CancellationToken cancellationToken) { _context = context; _graphicsCache = graphicsCache; _computeCache = computeCache; _hostStorage = hostStorage; - _cancellationToken = cancellationToken; _stateChangeCallback = stateChangeCallback; + _cancellationToken = cancellationToken; _validationQueue = new Queue(); _compilationQueue = new ConcurrentQueue(); _asyncTranslationQueue = new BlockingCollection(ThreadCount); @@ -235,7 +234,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache { workThreads[index] = new Thread(ProcessAsyncQueue) { - Name = $"GPU.AsyncTranslationThread.{index}" + Name = $"GPU.AsyncTranslationThread.{index}", }; } @@ -367,7 +366,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache { try { - AsyncProgramTranslation asyncTranslation = new AsyncProgramTranslation(guestShaders, specState, programIndex, isCompute); + AsyncProgramTranslation asyncTranslation = new(guestShaders, specState, programIndex, isCompute); _asyncTranslationQueue.Add(asyncTranslation, _cancellationToken); } catch (OperationCanceledException) @@ -491,7 +490,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache { ShaderSource[] shaderSources = new ShaderSource[compilation.TranslatedStages.Length]; - ShaderInfoBuilder shaderInfoBuilder = new ShaderInfoBuilder(_context, compilation.SpecializationState.TransformFeedbackDescriptors != null); + ShaderInfoBuilder shaderInfoBuilder = new(_context, compilation.SpecializationState.TransformFeedbackDescriptors != null); for (int index = 0; index < compilation.TranslatedStages.Length; index++) { @@ -502,7 +501,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache ShaderInfo shaderInfo = shaderInfoBuilder.Build(compilation.SpecializationState.PipelineState, fromCache: true); IProgram hostProgram = _context.Renderer.CreateProgram(shaderSources, shaderInfo); - CachedShaderProgram program = new CachedShaderProgram(hostProgram, compilation.SpecializationState, compilation.Shaders); + CachedShaderProgram program = new(hostProgram, compilation.SpecializationState, compilation.Shaders); // Vulkan's binary code is the SPIR-V used for compilation, so it is ready immediately. Other APIs get this after compilation. byte[] binaryCode = _context.Capabilities.Api == TargetApi.Vulkan ? ShaderBinarySerializer.Pack(shaderSources) : null; @@ -589,12 +588,12 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// Program index private void RecompileGraphicsFromGuestCode(GuestCodeAndCbData?[] guestShaders, ShaderSpecializationState specState, int programIndex) { - ShaderSpecializationState newSpecState = new ShaderSpecializationState( + ShaderSpecializationState newSpecState = new( ref specState.GraphicsState, specState.PipelineState, specState.TransformFeedbackDescriptors); - ResourceCounts counts = new ResourceCounts(); + ResourceCounts counts = new(); TranslatorContext[] translatorContexts = new TranslatorContext[Constants.ShaderStages + 1]; TranslatorContext nextStage = null; @@ -610,7 +609,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache byte[] guestCode = shader.Code; byte[] cb1Data = shader.Cb1Data; - DiskCacheGpuAccessor gpuAccessor = new DiskCacheGpuAccessor(_context, guestCode, cb1Data, specState, newSpecState, counts, stageIndex); + DiskCacheGpuAccessor gpuAccessor = new(_context, guestCode, cb1Data, specState, newSpecState, counts, stageIndex); TranslatorContext currentStage = DecodeGraphicsShader(gpuAccessor, api, DefaultFlags, 0); if (nextStage != null) @@ -623,7 +622,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache byte[] guestCodeA = guestShaders[0].Value.Code; byte[] cb1DataA = guestShaders[0].Value.Cb1Data; - DiskCacheGpuAccessor gpuAccessorA = new DiskCacheGpuAccessor(_context, guestCodeA, cb1DataA, specState, newSpecState, counts, 0); + DiskCacheGpuAccessor gpuAccessorA = new(_context, guestCodeA, cb1DataA, specState, newSpecState, counts, 0); translatorContexts[0] = DecodeGraphicsShader(gpuAccessorA, api, DefaultFlags | TranslationFlags.VertexA, 0); } @@ -638,7 +637,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache } CachedShaderStage[] shaders = new CachedShaderStage[guestShaders.Length]; - List translatedStages = new List(); + List translatedStages = new(); TranslatorContext previousStage = null; @@ -699,9 +698,9 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache private void RecompileComputeFromGuestCode(GuestCodeAndCbData?[] guestShaders, ShaderSpecializationState specState, int programIndex) { GuestCodeAndCbData shader = guestShaders[0].Value; - ResourceCounts counts = new ResourceCounts(); - ShaderSpecializationState newSpecState = new ShaderSpecializationState(ref specState.ComputeState); - DiskCacheGpuAccessor gpuAccessor = new DiskCacheGpuAccessor(_context, shader.Code, shader.Cb1Data, specState, newSpecState, counts, 0); + ResourceCounts counts = new(); + ShaderSpecializationState newSpecState = new(ref specState.ComputeState); + DiskCacheGpuAccessor gpuAccessor = new(_context, shader.Code, shader.Cb1Data, specState, newSpecState, counts, 0); TranslatorContext translatorContext = DecodeComputeShader(gpuAccessor, _context.Capabilities.Api, 0); @@ -721,4 +720,4 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache _stateChangeCallback(ShaderCacheState.Loading, ++_compiledCount, _totalCount); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/ShaderBinarySerializer.cs b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/ShaderBinarySerializer.cs index 2dc5c9719..a18b5780e 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/ShaderBinarySerializer.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/ShaderBinarySerializer.cs @@ -3,7 +3,6 @@ using Ryujinx.Common.Memory; using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.Shader; using Ryujinx.Graphics.Shader.Translation; -using System; using System.Collections.Generic; using System.IO; @@ -29,10 +28,10 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache public static ShaderSource[] Unpack(CachedShaderStage[] stages, byte[] code) { - using MemoryStream input = new MemoryStream(code); - using BinaryReader reader = new BinaryReader(input); + using MemoryStream input = new(code); + using BinaryReader reader = new(input); - List output = new List(); + List output = new(); int count = reader.ReadInt32(); @@ -48,4 +47,4 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache return output.ToArray(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/GpuAccessor.cs b/src/Ryujinx.Graphics.Gpu/Shader/GpuAccessor.cs index 5e18e61f2..ca9c883e3 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/GpuAccessor.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/GpuAccessor.cs @@ -97,7 +97,7 @@ namespace Ryujinx.Graphics.Gpu.Shader CompareOp.Greater or CompareOp.GreaterGl => AlphaTestOp.Greater, CompareOp.NotEqual or CompareOp.NotEqualGl => AlphaTestOp.NotEqual, CompareOp.GreaterOrEqual or CompareOp.GreaterOrEqualGl => AlphaTestOp.GreaterOrEqual, - _ => AlphaTestOp.Always + _ => AlphaTestOp.Always, }; } diff --git a/src/Ryujinx.Graphics.Gpu/Shader/GpuAccessorBase.cs b/src/Ryujinx.Graphics.Gpu/Shader/GpuAccessorBase.cs index 2dd7c631c..07b7ddc28 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/GpuAccessorBase.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/GpuAccessorBase.cs @@ -4,7 +4,6 @@ using Ryujinx.Graphics.Gpu.Engine.Threed; using Ryujinx.Graphics.Gpu.Image; using Ryujinx.Graphics.Shader; using Ryujinx.Graphics.Shader.Translation; -using System; namespace Ryujinx.Graphics.Gpu.Shader { @@ -125,7 +124,7 @@ namespace Ryujinx.Graphics.Gpu.Shader 3 => 2, // Geometry 1 => 3, // Tessellation control 2 => 4, // Tessellation evaluation - _ => 0 // Vertex/Compute + _ => 0, // Vertex/Compute }; } @@ -188,6 +187,7 @@ namespace Ryujinx.Graphics.Gpu.Shader return formatInfo.Format switch { +#pragma warning disable IDE0055 // Disable formatting Format.R8Unorm => TextureFormat.R8Unorm, Format.R8Snorm => TextureFormat.R8Snorm, Format.R8Uint => TextureFormat.R8Uint, @@ -228,7 +228,8 @@ namespace Ryujinx.Graphics.Gpu.Shader Format.R10G10B10A2Unorm => TextureFormat.R10G10B10A2Unorm, Format.R10G10B10A2Uint => TextureFormat.R10G10B10A2Uint, Format.R11G11B10Float => TextureFormat.R11G11B10Float, - _ => TextureFormat.Unknown + _ => TextureFormat.Unknown, +#pragma warning restore IDE0055 }; } @@ -256,7 +257,7 @@ namespace Ryujinx.Graphics.Gpu.Shader PrimitiveTopology.Patches => tessellationMode.UnpackPatchType() == TessPatchType.Isolines ? InputTopology.Lines : InputTopology.Triangles, - _ => InputTopology.Points + _ => InputTopology.Points, }; } } diff --git a/src/Ryujinx.Graphics.Gpu/Shader/GpuAccessorState.cs b/src/Ryujinx.Graphics.Gpu/Shader/GpuAccessorState.cs index 0e8e979c8..cfc4a2ccc 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/GpuAccessorState.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/GpuAccessorState.cs @@ -58,4 +58,4 @@ namespace Ryujinx.Graphics.Gpu.Shader ResourceCounts = new ResourceCounts(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/GpuChannelComputeState.cs b/src/Ryujinx.Graphics.Gpu/Shader/GpuChannelComputeState.cs index b65dd75e3..d8cdbc348 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/GpuChannelComputeState.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/GpuChannelComputeState.cs @@ -62,4 +62,4 @@ namespace Ryujinx.Graphics.Gpu.Shader HasUnalignedStorageBuffer = hasUnalignedStorageBuffer; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/GpuChannelGraphicsState.cs b/src/Ryujinx.Graphics.Gpu/Shader/GpuChannelGraphicsState.cs index 5247a096f..544e689ab 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/GpuChannelGraphicsState.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/GpuChannelGraphicsState.cs @@ -155,4 +155,4 @@ namespace Ryujinx.Graphics.Gpu.Shader DualSourceBlendEnable = dualSourceBlendEnable; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/GpuChannelPoolState.cs b/src/Ryujinx.Graphics.Gpu/Shader/GpuChannelPoolState.cs index 1e34c5ded..ddb45152e 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/GpuChannelPoolState.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/GpuChannelPoolState.cs @@ -2,6 +2,7 @@ using System; namespace Ryujinx.Graphics.Gpu.Shader { +#pragma warning disable CS0659 // Class overrides Object.Equals(object o) but does not override Object.GetHashCode() /// /// State used by the . /// @@ -46,5 +47,11 @@ namespace Ryujinx.Graphics.Gpu.Shader TexturePoolMaximumId == other.TexturePoolMaximumId && TextureBufferIndex == other.TextureBufferIndex; } + + public override bool Equals(object obj) + { + return obj is GpuChannelPoolState state && Equals(state); + } } -} \ No newline at end of file +#pragma warning restore CS0659 +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/HashTable/HashState.cs b/src/Ryujinx.Graphics.Gpu/Shader/HashTable/HashState.cs index 584eefdc6..836b8663a 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/HashTable/HashState.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/HashTable/HashState.cs @@ -21,7 +21,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.HashTable /// Hash of the given data public static uint CalcHash(ReadOnlySpan data) { - HashState state = new HashState(); + HashState state = new(); state.Initialize(); state.Continue(data); @@ -50,7 +50,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.HashTable { ulong h = _hash; - ReadOnlySpan dataAsUlong = MemoryMarshal.Cast(data.Slice(_start)); + ReadOnlySpan dataAsUlong = MemoryMarshal.Cast(data[_start..]); for (int i = 0; i < dataAsUlong.Length; i++) { @@ -75,7 +75,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.HashTable /// /// Data to be hashed /// Hash of all the data hashed with this - public uint Finalize(ReadOnlySpan data) + public readonly uint Finalize(ReadOnlySpan data) { ulong h = _hash; diff --git a/src/Ryujinx.Graphics.Gpu/Shader/HashTable/PartitionHashTable.cs b/src/Ryujinx.Graphics.Gpu/Shader/HashTable/PartitionHashTable.cs index d7cb3d99e..c8c8dfcb3 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/HashTable/PartitionHashTable.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/HashTable/PartitionHashTable.cs @@ -48,7 +48,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.HashTable /// Partial entries have no items associated with them. They just indicates that the data might be present on /// the table, and one must keep looking for the full entry on other tables of larger data size. /// - public bool IsPartial => OwnSize != 0; + public readonly bool IsPartial => OwnSize != 0; /// /// Creates a new partial hash table entry. @@ -82,11 +82,11 @@ namespace Ryujinx.Graphics.Gpu.Shader.HashTable /// Gets the data for this entry, either full or partial. /// /// Data sub-region - public ReadOnlySpan GetData() + public readonly ReadOnlySpan GetData() { if (OwnSize != 0) { - return new ReadOnlySpan(Data).Slice(0, OwnSize); + return new ReadOnlySpan(Data)[..OwnSize]; } return Data; @@ -139,7 +139,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.HashTable return existingItem; } - Entry entry = new Entry(dataHash, data, item); + Entry entry = new(dataHash, data, item); AddToBucket(dataHash, ref entry); @@ -160,7 +160,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.HashTable return false; } - Entry entry = new Entry(dataHash, data, item); + Entry entry = new(dataHash, data, item); AddToBucket(dataHash, ref entry); @@ -175,7 +175,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.HashTable /// True if added, false otherwise public bool AddPartial(byte[] ownerData, int ownSize) { - ReadOnlySpan data = new ReadOnlySpan(ownerData).Slice(0, ownSize); + ReadOnlySpan data = new ReadOnlySpan(ownerData)[..ownSize]; return AddPartial(ownerData, HashState.CalcHash(data), ownSize); } @@ -189,14 +189,14 @@ namespace Ryujinx.Graphics.Gpu.Shader.HashTable /// True if added, false otherwise public bool AddPartial(byte[] ownerData, uint dataHash, int ownSize) { - ReadOnlySpan data = new ReadOnlySpan(ownerData).Slice(0, ownSize); + ReadOnlySpan data = new ReadOnlySpan(ownerData)[..ownSize]; if (TryFindItem(dataHash, data, out _)) { return false; } - Entry entry = new Entry(dataHash, ownerData, ownSize); + Entry entry = new(dataHash, ownerData, ownSize); AddToBucket(dataHash, ref entry); @@ -226,7 +226,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.HashTable /// /// Bucket to add the entry into /// Entry to be added - private void AddToBucket(ref Bucket bucket, ref Entry entry) + private static void AddToBucket(ref Bucket bucket, ref Entry entry) { if (bucket.InlineEntry.Data == null) { @@ -339,7 +339,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.HashTable /// /// A full entry was found, the search was concluded and the item can be retrieved. /// - FoundFull + FoundFull, } /// diff --git a/src/Ryujinx.Graphics.Gpu/Shader/HashTable/PartitionedHashTable.cs b/src/Ryujinx.Graphics.Gpu/Shader/HashTable/PartitionedHashTable.cs index e9a4f6549..341d3114f 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/HashTable/PartitionedHashTable.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/HashTable/PartitionedHashTable.cs @@ -149,12 +149,12 @@ namespace Ryujinx.Graphics.Gpu.Shader.HashTable } } - HashState hashState = new HashState(); + HashState hashState = new(); hashState.Initialize(); for (int i = 0; i < index; i++) { - ReadOnlySpan dataSlice = new ReadOnlySpan(data).Slice(0, _sizeTable[i].Size); + ReadOnlySpan dataSlice = new ReadOnlySpan(data)[.._sizeTable[i].Size]; hashState.Continue(dataSlice); _sizeTable[i].AddPartial(data, hashState.Finalize(dataSlice)); } @@ -208,7 +208,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.HashTable /// True if the item was found on the table, false otherwise public bool TryFindItem(IDataAccessor dataAccessor, out T item, out byte[] data) { - SmartDataAccessor sda = new SmartDataAccessor(dataAccessor); + SmartDataAccessor sda = new(dataAccessor); item = default; data = null; diff --git a/src/Ryujinx.Graphics.Gpu/Shader/HashTable/SmartDataAccessor.cs b/src/Ryujinx.Graphics.Gpu/Shader/HashTable/SmartDataAccessor.cs index 0632add6c..17853e90a 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/HashTable/SmartDataAccessor.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/HashTable/SmartDataAccessor.cs @@ -40,7 +40,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.HashTable } else if (_data.Length > length) { - return _data.Slice(0, length); + return _data[..length]; } return _data; @@ -65,7 +65,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.HashTable /// /// Data to be hashed /// Hash of the data - private uint CalcHashCached(ReadOnlySpan data) + private readonly uint CalcHashCached(ReadOnlySpan data) { HashState state = default; bool found = false; diff --git a/src/Ryujinx.Graphics.Gpu/Shader/ResourceCounts.cs b/src/Ryujinx.Graphics.Gpu/Shader/ResourceCounts.cs index f495229ff..126e3249c 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/ResourceCounts.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/ResourceCounts.cs @@ -25,4 +25,4 @@ namespace Ryujinx.Graphics.Gpu.Shader /// public int ImagesCount; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/ShaderAddresses.cs b/src/Ryujinx.Graphics.Gpu/Shader/ShaderAddresses.cs index 651dfd263..32d92223f 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/ShaderAddresses.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/ShaderAddresses.cs @@ -9,7 +9,7 @@ namespace Ryujinx.Graphics.Gpu.Shader /// struct ShaderAddresses : IEquatable { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public ulong VertexA; public ulong VertexB; public ulong TessControl; @@ -23,7 +23,7 @@ namespace Ryujinx.Graphics.Gpu.Shader /// /// Shader addresses structure to compare with /// True if they are equal, false otherwise - public override bool Equals(object other) + public readonly override bool Equals(object other) { return other is ShaderAddresses addresses && Equals(addresses); } @@ -33,21 +33,21 @@ namespace Ryujinx.Graphics.Gpu.Shader /// /// Shader addresses structure to compare with /// True if they are equal, false otherwise - public bool Equals(ShaderAddresses other) + public readonly bool Equals(ShaderAddresses other) { - return VertexA == other.VertexA && - VertexB == other.VertexB && - TessControl == other.TessControl && + return VertexA == other.VertexA && + VertexB == other.VertexB && + TessControl == other.TessControl && TessEvaluation == other.TessEvaluation && - Geometry == other.Geometry && - Fragment == other.Fragment; + Geometry == other.Geometry && + Fragment == other.Fragment; } /// /// Computes hash code from the addresses. /// /// Hash code - public override int GetHashCode() + public readonly override int GetHashCode() { return HashCode.Combine(VertexA, VertexB, TessControl, TessEvaluation, Geometry, Fragment); } @@ -61,4 +61,4 @@ namespace Ryujinx.Graphics.Gpu.Shader return MemoryMarshal.CreateSpan(ref VertexA, Unsafe.SizeOf() / sizeof(ulong)); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/ShaderCache.cs b/src/Ryujinx.Graphics.Gpu/Shader/ShaderCache.cs index 913f6e9ec..97d7a7206 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/ShaderCache.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/ShaderCache.cs @@ -11,7 +11,6 @@ using Ryujinx.Graphics.Shader.Translation; using System; using System.Collections.Generic; using System.IO; -using System.Linq; using System.Threading; namespace Ryujinx.Graphics.Gpu.Shader @@ -73,7 +72,7 @@ namespace Ryujinx.Graphics.Gpu.Shader } } - private Queue _programsToSaveQueue; + private readonly Queue _programsToSaveQueue; private readonly ComputeShaderCacheHashTable _computeShaderCache; private readonly ShaderCacheHashTable _graphicsShaderCache; @@ -157,13 +156,12 @@ namespace Ryujinx.Graphics.Gpu.Shader { if (_diskCacheHostStorage.CacheEnabled) { - ParallelDiskCacheLoader loader = new ParallelDiskCacheLoader( + ParallelDiskCacheLoader loader = new( _context, _graphicsShaderCache, _computeShaderCache, _diskCacheHostStorage, - cancellationToken, - ShaderCacheStateUpdate); + ShaderCacheStateUpdate, cancellationToken); loader.LoadShaders(); @@ -214,9 +212,9 @@ namespace Ryujinx.Graphics.Gpu.Shader return cpShader; } - ShaderSpecializationState specState = new ShaderSpecializationState(ref computeState); - GpuAccessorState gpuAccessorState = new GpuAccessorState(poolState, computeState, default, specState); - GpuAccessor gpuAccessor = new GpuAccessor(_context, channel, gpuAccessorState); + ShaderSpecializationState specState = new(ref computeState); + GpuAccessorState gpuAccessorState = new(poolState, computeState, default, specState); + GpuAccessor gpuAccessor = new(_context, channel, gpuAccessorState); TranslatorContext translatorContext = DecodeComputeShader(gpuAccessor, _context.Capabilities.Api, gpuVa); TranslatedShader translatedShader = TranslateShader(_dumper, channel, translatorContext, cachedGuestCode); @@ -241,7 +239,7 @@ namespace Ryujinx.Graphics.Gpu.Shader /// Shader pipeline state to be updated /// Current graphics state /// Current GPU channel - private void UpdatePipelineInfo( + private static void UpdatePipelineInfo( ref ThreedClassState state, ref ProgramPipelineState pipeline, GpuChannelGraphicsState graphicsState, @@ -318,8 +316,8 @@ namespace Ryujinx.Graphics.Gpu.Shader UpdatePipelineInfo(ref state, ref pipeline, graphicsState, channel); - ShaderSpecializationState specState = new ShaderSpecializationState(ref graphicsState, ref pipeline, transformFeedbackDescriptors); - GpuAccessorState gpuAccessorState = new GpuAccessorState(poolState, default, graphicsState, specState, transformFeedbackDescriptors); + ShaderSpecializationState specState = new(ref graphicsState, ref pipeline, transformFeedbackDescriptors); + GpuAccessorState gpuAccessorState = new(poolState, default, graphicsState, specState, transformFeedbackDescriptors); ReadOnlySpan addressesSpan = addresses.AsSpan(); @@ -334,7 +332,7 @@ namespace Ryujinx.Graphics.Gpu.Shader if (gpuVa != 0) { - GpuAccessor gpuAccessor = new GpuAccessor(_context, channel, gpuAccessorState, stageIndex); + GpuAccessor gpuAccessor = new(_context, channel, gpuAccessorState, stageIndex); TranslatorContext currentStage = DecodeGraphicsShader(gpuAccessor, api, DefaultFlags, gpuVa); if (nextStage != null) @@ -358,11 +356,11 @@ namespace Ryujinx.Graphics.Gpu.Shader } CachedShaderStage[] shaders = new CachedShaderStage[Constants.ShaderStages + 1]; - List shaderSources = new List(); + List shaderSources = new(); TranslatorContext previousStage = null; - ShaderInfoBuilder infoBuilder = new ShaderInfoBuilder(_context, transformFeedbackDescriptors != null); + ShaderInfoBuilder infoBuilder = new(_context, transformFeedbackDescriptors != null); for (int stageIndex = 0; stageIndex < Constants.ShaderStages; stageIndex++) { @@ -486,7 +484,7 @@ namespace Ryujinx.Graphics.Gpu.Shader if (_diskCacheHostStorage.CacheEnabled) { byte[] binaryCode = _context.Capabilities.Api == TargetApi.Vulkan ? ShaderBinarySerializer.Pack(sources) : null; - ProgramToSave programToSave = new ProgramToSave(program, hostProgram, binaryCode); + ProgramToSave programToSave = new(program, hostProgram, binaryCode); _programsToSaveQueue.Enqueue(programToSave); } @@ -670,8 +668,8 @@ namespace Ryujinx.Graphics.Gpu.Shader pathsB.Prepend(program); pathsA.Prepend(program); - CachedShaderStage vertexAStage = new CachedShaderStage(null, codeA, cb1DataA); - CachedShaderStage vertexBStage = new CachedShaderStage(program.Info, codeB, cb1DataB); + CachedShaderStage vertexAStage = new(null, codeA, cb1DataA); + CachedShaderStage vertexBStage = new(program.Info, codeB, cb1DataB); return new TranslatedShaderVertexPair(vertexAStage, vertexBStage, program); } @@ -716,7 +714,7 @@ namespace Ryujinx.Graphics.Gpu.Shader ShaderStage.TessellationEvaluation => 2, ShaderStage.Geometry => 3, ShaderStage.Fragment => 4, - _ => 0 + _ => 0, }; } diff --git a/src/Ryujinx.Graphics.Gpu/Shader/ShaderCacheHashTable.cs b/src/Ryujinx.Graphics.Gpu/Shader/ShaderCacheHashTable.cs index e35c06b13..e65a1dec9 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/ShaderCacheHashTable.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/ShaderCacheHashTable.cs @@ -23,7 +23,7 @@ namespace Ryujinx.Graphics.Gpu.Shader /// /// Index of the shader stage /// Guest code, or null if not present - public byte[] GetByIndex(int stageIndex) + public readonly byte[] GetByIndex(int stageIndex) { return stageIndex switch { @@ -31,7 +31,7 @@ namespace Ryujinx.Graphics.Gpu.Shader 2 => TessEvaluationCode, 3 => GeometryCode, 4 => FragmentCode, - _ => VertexBCode + _ => VertexBCode, }; } } @@ -85,7 +85,7 @@ namespace Ryujinx.Graphics.Gpu.Shader /// ID of the guest code, if found /// Cached guest code, if found /// True if found, false otherwise - public bool TryFind(IDataAccessor dataAccessor, out int id, out byte[] data) + public readonly bool TryFind(IDataAccessor dataAccessor, out int id, out byte[] data) { return _cache.TryFindItem(dataAccessor, out id, out data); } @@ -103,12 +103,12 @@ namespace Ryujinx.Graphics.Gpu.Shader public int GeometryId; public int FragmentId; - public override bool Equals(object obj) + public readonly override bool Equals(object obj) { return obj is IdTable other && Equals(other); } - public bool Equals(IdTable other) + public readonly bool Equals(IdTable other) { return other.VertexAId == VertexAId && other.VertexBId == VertexBId && @@ -118,7 +118,7 @@ namespace Ryujinx.Graphics.Gpu.Shader other.FragmentId == FragmentId; } - public override int GetHashCode() + public readonly override int GetHashCode() { return HashCode.Combine(VertexAId, VertexBId, TessControlId, TessEvaluationId, GeometryId, FragmentId); } @@ -154,7 +154,7 @@ namespace Ryujinx.Graphics.Gpu.Shader /// Program to be added public void Add(CachedShaderProgram program) { - IdTable idTable = new IdTable(); + IdTable idTable = new(); foreach (var shader in program.Shaders) { @@ -222,7 +222,7 @@ namespace Ryujinx.Graphics.Gpu.Shader out CachedGraphicsGuestCode guestCode) { var memoryManager = channel.MemoryManager; - IdTable idTable = new IdTable(); + IdTable idTable = new(); guestCode = new CachedGraphicsGuestCode(); program = null; @@ -260,7 +260,7 @@ namespace Ryujinx.Graphics.Gpu.Shader return true; } - ShaderCodeAccessor codeAccessor = new ShaderCodeAccessor(memoryManager, baseAddress); + ShaderCodeAccessor codeAccessor = new(memoryManager, baseAddress); return idCache.TryFind(codeAccessor, out id, out data); } @@ -279,4 +279,4 @@ namespace Ryujinx.Graphics.Gpu.Shader } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/ShaderCacheState.cs b/src/Ryujinx.Graphics.Gpu/Shader/ShaderCacheState.cs index b94a6c054..075e3a613 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/ShaderCacheState.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/ShaderCacheState.cs @@ -10,6 +10,6 @@ namespace Ryujinx.Graphics.Gpu.Shader /// Shader cache is written to disk Packaging, /// Shader cache finished loading - Loaded + Loaded, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/ShaderCodeAccessor.cs b/src/Ryujinx.Graphics.Gpu/Shader/ShaderCodeAccessor.cs index e896493c5..240a4ce9f 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/ShaderCodeAccessor.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/ShaderCodeAccessor.cs @@ -29,4 +29,4 @@ namespace Ryujinx.Graphics.Gpu.Shader return _memoryManager.GetSpanMapped(_baseAddress + (ulong)offset, length); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/ShaderDumpPaths.cs b/src/Ryujinx.Graphics.Gpu/Shader/ShaderDumpPaths.cs index 6ca7daef2..d0765963d 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/ShaderDumpPaths.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/ShaderDumpPaths.cs @@ -46,4 +46,4 @@ namespace Ryujinx.Graphics.Gpu.Shader } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/ShaderDumper.cs b/src/Ryujinx.Graphics.Gpu/Shader/ShaderDumper.cs index 93eeb8d72..80d599e9b 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/ShaderDumper.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/ShaderDumper.cs @@ -46,13 +46,13 @@ namespace Ryujinx.Graphics.Gpu.Shader CurrentDumpIndex++; - using MemoryStream stream = new MemoryStream(code); - BinaryReader codeReader = new BinaryReader(stream); + using MemoryStream stream = new(code); + BinaryReader codeReader = new(stream); using FileStream fullFile = File.Create(fullPath); using FileStream codeFile = File.Create(codePath); - BinaryWriter fullWriter = new BinaryWriter(fullFile); - BinaryWriter codeWriter = new BinaryWriter(codeFile); + BinaryWriter fullWriter = new(fullFile); + BinaryWriter codeWriter = new(codeFile); int headerSize = compute ? 0 : 0x50; @@ -126,4 +126,4 @@ namespace Ryujinx.Graphics.Gpu.Shader return dir; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/ShaderInfoBuilder.cs b/src/Ryujinx.Graphics.Gpu/Shader/ShaderInfoBuilder.cs index 83d92edc3..7356410ca 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/ShaderInfoBuilder.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/ShaderInfoBuilder.cs @@ -92,7 +92,7 @@ namespace Ryujinx.Graphics.Gpu.Shader ShaderStage.TessellationEvaluation => 2, ShaderStage.Geometry => 3, ShaderStage.Fragment => 4, - _ => 0 + _ => 0, }); ResourceStages stages = info.Stage switch @@ -103,7 +103,7 @@ namespace Ryujinx.Graphics.Gpu.Shader ShaderStage.TessellationEvaluation => ResourceStages.TessellationEvaluation, ShaderStage.Geometry => ResourceStages.Geometry, ShaderStage.Fragment => ResourceStages.Fragment, - _ => ResourceStages.None + _ => ResourceStages.None, }; int uniformsPerStage = (int)_context.Capabilities.MaximumUniformBuffersPerStage; @@ -236,7 +236,7 @@ namespace Ryujinx.Graphics.Gpu.Shader usages[index] = new ResourceUsageCollection(_resourceUsages[index].ToArray().AsReadOnly()); } - ResourceLayout resourceLayout = new ResourceLayout(descriptors.AsReadOnly(), usages.AsReadOnly()); + ResourceLayout resourceLayout = new(descriptors.AsReadOnly(), usages.AsReadOnly()); if (pipeline.HasValue) { @@ -262,7 +262,7 @@ namespace Ryujinx.Graphics.Gpu.Shader ProgramPipelineState? pipeline, bool tfEnabled) { - ShaderInfoBuilder builder = new ShaderInfoBuilder(context, tfEnabled); + ShaderInfoBuilder builder = new(context, tfEnabled); foreach (CachedShaderStage program in programs) { @@ -284,11 +284,11 @@ namespace Ryujinx.Graphics.Gpu.Shader /// Shader information public static ShaderInfo BuildForCompute(GpuContext context, ShaderProgramInfo info, bool fromCache = false) { - ShaderInfoBuilder builder = new ShaderInfoBuilder(context, tfEnabled: false); + ShaderInfoBuilder builder = new(context, tfEnabled: false); builder.AddStageInfo(info); return builder.Build(null, fromCache); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/ShaderSpecializationList.cs b/src/Ryujinx.Graphics.Gpu/Shader/ShaderSpecializationList.cs index 7d61332e5..e57e1df1a 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/ShaderSpecializationList.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/ShaderSpecializationList.cs @@ -8,7 +8,7 @@ namespace Ryujinx.Graphics.Gpu.Shader /// class ShaderSpecializationList : IEnumerable { - private readonly List _entries = new List(); + private readonly List _entries = new(); /// /// Adds a program to the list. @@ -81,4 +81,4 @@ namespace Ryujinx.Graphics.Gpu.Shader return GetEnumerator(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/ShaderSpecializationState.cs b/src/Ryujinx.Graphics.Gpu/Shader/ShaderSpecializationState.cs index 9b0c8b9b9..775bfb2af 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/ShaderSpecializationState.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/ShaderSpecializationState.cs @@ -31,7 +31,7 @@ namespace Ryujinx.Graphics.Gpu.Shader EarlyZForce = 1 << 0, PrimitiveTopology = 1 << 1, TessellationMode = 1 << 2, - TransformFeedback = 1 << 3 + TransformFeedback = 1 << 3, } private QueriedStateFlags _queriedState; @@ -71,7 +71,7 @@ namespace Ryujinx.Graphics.Gpu.Shader { TextureFormat = 1 << 0, SamplerType = 1 << 1, - CoordNormalized = 1 << 2 + CoordNormalized = 1 << 2, } /// @@ -440,7 +440,7 @@ namespace Ryujinx.Graphics.Gpu.Shader /// Texture specialization state private Box GetOrCreateTextureSpecState(int stageIndex, int handle, int cbufSlot) { - TextureKey key = new TextureKey(stageIndex, handle, cbufSlot); + TextureKey key = new(stageIndex, handle, cbufSlot); if (!_textureSpecialization.TryGetValue(key, out Box state)) { @@ -459,7 +459,7 @@ namespace Ryujinx.Graphics.Gpu.Shader /// Texture specialization state private Box GetTextureSpecState(int stageIndex, int handle, int cbufSlot) { - TextureKey key = new TextureKey(stageIndex, handle, cbufSlot); + TextureKey key = new(stageIndex, handle, cbufSlot); if (_textureSpecialization.TryGetValue(key, out Box state)) { @@ -694,7 +694,7 @@ namespace Ryujinx.Graphics.Gpu.Shader /// Texture descriptor /// True if the state matches, false otherwise [MethodImpl(MethodImplOptions.AggressiveInlining)] - private bool MatchesTexture(Box specializationState, in Image.TextureDescriptor descriptor) + private static bool MatchesTexture(Box specializationState, in Image.TextureDescriptor descriptor) { if (specializationState != null) { @@ -756,7 +756,7 @@ namespace Ryujinx.Graphics.Gpu.Shader /// Shader specialization state public static ShaderSpecializationState Read(ref BinarySerializer dataReader) { - ShaderSpecializationState specState = new ShaderSpecializationState(); + ShaderSpecializationState specState = new(); dataReader.Read(ref specState._queriedState); dataReader.Read(ref specState._compute); @@ -812,7 +812,7 @@ namespace Ryujinx.Graphics.Gpu.Shader for (int index = 0; index < count; index++) { TextureKey textureKey = default; - Box textureState = new Box(); + Box textureState = new(); dataReader.ReadWithMagicAndSize(ref textureKey, TexkMagic); dataReader.ReadWithMagicAndSize(ref textureState.Value, TexsMagic); @@ -886,4 +886,4 @@ namespace Ryujinx.Graphics.Gpu.Shader } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Gpu/Shader/TransformFeedbackDescriptor.cs b/src/Ryujinx.Graphics.Gpu/Shader/TransformFeedbackDescriptor.cs index 5baf2a1a6..1f245881d 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/TransformFeedbackDescriptor.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/TransformFeedbackDescriptor.cs @@ -52,7 +52,7 @@ namespace Ryujinx.Graphics.Gpu.Shader /// Span of varying locations public ReadOnlySpan AsSpan() { - return MemoryMarshal.Cast(VaryingLocations.AsSpan()).Slice(0, Math.Min(128, VaryingCount)); + return MemoryMarshal.Cast(VaryingLocations.AsSpan())[..Math.Min(128, VaryingCount)]; } } } diff --git a/src/Ryujinx.Graphics.Gpu/Synchronization/HostSyncFlags.cs b/src/Ryujinx.Graphics.Gpu/Synchronization/HostSyncFlags.cs index 426669914..1b4df37e2 100644 --- a/src/Ryujinx.Graphics.Gpu/Synchronization/HostSyncFlags.cs +++ b/src/Ryujinx.Graphics.Gpu/Synchronization/HostSyncFlags.cs @@ -25,6 +25,6 @@ namespace Ryujinx.Graphics.Gpu.Synchronization /// Force = 1 << 2, - StrictSyncpoint = Strict | Syncpoint + StrictSyncpoint = Strict | Syncpoint, } } diff --git a/src/Ryujinx.Graphics.Gpu/Synchronization/SynchronizationManager.cs b/src/Ryujinx.Graphics.Gpu/Synchronization/SynchronizationManager.cs index 968de930d..ccec763e3 100644 --- a/src/Ryujinx.Graphics.Gpu/Synchronization/SynchronizationManager.cs +++ b/src/Ryujinx.Graphics.Gpu/Synchronization/SynchronizationManager.cs @@ -17,7 +17,7 @@ namespace Ryujinx.Graphics.Gpu.Synchronization /// /// Array containing all hardware syncpoints. /// - private Syncpoint[] _syncpoints; + private readonly Syncpoint[] _syncpoints; public SynchronizationManager() { @@ -118,26 +118,24 @@ namespace Ryujinx.Graphics.Gpu.Synchronization timeout = TimeSpan.FromSeconds(1); } - using (ManualResetEvent waitEvent = new ManualResetEvent(false)) + using ManualResetEvent waitEvent = new(false); + var info = _syncpoints[id].RegisterCallback(threshold, (x) => waitEvent.Set()); + + if (info == null) { - var info = _syncpoints[id].RegisterCallback(threshold, (x) => waitEvent.Set()); - - if (info == null) - { - return false; - } - - bool signaled = waitEvent.WaitOne(timeout); - - if (!signaled && info != null) - { - Logger.Error?.Print(LogClass.Gpu, $"Wait on syncpoint {id} for threshold {threshold} took more than {timeout.TotalMilliseconds}ms, resuming execution..."); - - _syncpoints[id].UnregisterCallback(info); - } - - return !signaled; + return false; } + + bool signaled = waitEvent.WaitOne(timeout); + + if (!signaled && info != null) + { + Logger.Error?.Print(LogClass.Gpu, $"Wait on syncpoint {id} for threshold {threshold} took more than {timeout.TotalMilliseconds}ms, resuming execution..."); + + _syncpoints[id].UnregisterCallback(info); + } + + return !signaled; } } } diff --git a/src/Ryujinx.Graphics.Gpu/Synchronization/Syncpoint.cs b/src/Ryujinx.Graphics.Gpu/Synchronization/Syncpoint.cs index 39fb83c05..16f4d971b 100644 --- a/src/Ryujinx.Graphics.Gpu/Synchronization/Syncpoint.cs +++ b/src/Ryujinx.Graphics.Gpu/Synchronization/Syncpoint.cs @@ -23,7 +23,7 @@ namespace Ryujinx.Graphics.Gpu.Synchronization public Syncpoint(uint id) { - Id = id; + Id = id; _waiters = new List(); } @@ -46,10 +46,10 @@ namespace Ryujinx.Graphics.Gpu.Synchronization } else { - SyncpointWaiterHandle waiterInformation = new SyncpointWaiterHandle + SyncpointWaiterHandle waiterInformation = new() { Threshold = threshold, - Callback = callback + Callback = callback, }; _waiters.Add(waiterInformation); @@ -92,10 +92,7 @@ namespace Ryujinx.Graphics.Gpu.Synchronization } else { - if (expiredList == null) - { - expiredList = new List(); - } + expiredList ??= new List(); expiredList.Add(item); } diff --git a/src/Ryujinx.Graphics.Gpu/Window.cs b/src/Ryujinx.Graphics.Gpu/Window.cs index 06d0fddf4..5da472b3e 100644 --- a/src/Ryujinx.Graphics.Gpu/Window.cs +++ b/src/Ryujinx.Graphics.Gpu/Window.cs @@ -68,21 +68,21 @@ namespace Ryujinx.Graphics.Gpu /// Texture release callback /// User defined object passed to the release callback, can be used to identify the texture public PresentationTexture( - TextureCache cache, - TextureInfo info, - MultiRange range, - ImageCrop crop, + TextureCache cache, + TextureInfo info, + MultiRange range, + ImageCrop crop, Action acquireCallback, - Action releaseCallback, - object userObj) + Action releaseCallback, + object userObj) { - Cache = cache; - Info = info; - Range = range; - Crop = crop; + Cache = cache; + Info = info; + Range = range; + Crop = crop; AcquireCallback = acquireCallback; ReleaseCallback = releaseCallback; - UserObj = userObj; + UserObj = userObj; } } @@ -125,28 +125,28 @@ namespace Ryujinx.Graphics.Gpu /// Thrown when is invalid /// True if the frame was added to the queue, false otherwise public bool EnqueueFrameThreadSafe( - ulong pid, - ulong address, - int width, - int height, - int stride, - bool isLinear, - int gobBlocksInY, - Format format, - int bytesPerPixel, - ImageCrop crop, + ulong pid, + ulong address, + int width, + int height, + int stride, + bool isLinear, + int gobBlocksInY, + Format format, + int bytesPerPixel, + ImageCrop crop, Action acquireCallback, - Action releaseCallback, - object userObj) + Action releaseCallback, + object userObj) { if (!_context.PhysicalMemoryRegistry.TryGetValue(pid, out var physicalMemory)) { return false; } - FormatInfo formatInfo = new FormatInfo(format, 1, 1, bytesPerPixel, 4); + FormatInfo formatInfo = new(format, 1, 1, bytesPerPixel, 4); - TextureInfo info = new TextureInfo( + TextureInfo info = new( 0UL, width, height, @@ -175,7 +175,7 @@ namespace Ryujinx.Graphics.Gpu 1, 1).TotalSize; - MultiRange range = new MultiRange(address, (ulong)size); + MultiRange range = new(address, (ulong)size); _frameQueue.Enqueue(new PresentationTexture( physicalMemory.TextureCache, @@ -260,4 +260,4 @@ namespace Ryujinx.Graphics.Gpu return false; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Vulkan/AutoFlushCounter.cs b/src/Ryujinx.Graphics.Vulkan/AutoFlushCounter.cs index 4e2a9d6bc..8ac412fe5 100644 --- a/src/Ryujinx.Graphics.Vulkan/AutoFlushCounter.cs +++ b/src/Ryujinx.Graphics.Vulkan/AutoFlushCounter.cs @@ -8,16 +8,16 @@ namespace Ryujinx.Graphics.Vulkan internal class AutoFlushCounter { // How often to flush on framebuffer change. - private readonly static long FramebufferFlushTimer = Stopwatch.Frequency / 1000; // (1ms) + private readonly static long _framebufferFlushTimer = Stopwatch.Frequency / 1000; // (1ms) // How often to flush on draw when fast flush mode is enabled. - private readonly static long DrawFlushTimer = Stopwatch.Frequency / 666; // (1.5ms) + private readonly static long _drawFlushTimer = Stopwatch.Frequency / 666; // (1.5ms) // Average wait time that triggers fast flush mode to be entered. - private readonly static long FastFlushEnterThreshold = Stopwatch.Frequency / 666; // (1.5ms) + private readonly static long _fastFlushEnterThreshold = Stopwatch.Frequency / 666; // (1.5ms) // Average wait time that triggers fast flush mode to be exited. - private readonly static long FastFlushExitThreshold = Stopwatch.Frequency / 10000; // (0.1ms) + private readonly static long _fastFlushExitThreshold = Stopwatch.Frequency / 10000; // (0.1ms) // Number of frames to average waiting times over. private const int SyncWaitAverageCount = 20; @@ -34,11 +34,11 @@ namespace Ryujinx.Graphics.Vulkan private int _consecutiveQueries; private int _queryCount; - private int[] _queryCountHistory = new int[3]; + private readonly int[] _queryCountHistory = new int[3]; private int _queryCountHistoryIndex; private int _remainingQueries; - private long[] _syncWaitHistory = new long[SyncWaitAverageCount]; + private readonly long[] _syncWaitHistory = new long[SyncWaitAverageCount]; private int _syncWaitHistoryIndex; private bool _fastFlushMode; @@ -110,7 +110,7 @@ namespace Ryujinx.Graphics.Vulkan return false; } - long flushTimeout = DrawFlushTimer; + long flushTimeout = _drawFlushTimer; long now = Stopwatch.GetTimestamp(); @@ -144,7 +144,7 @@ namespace Ryujinx.Graphics.Vulkan return false; } - long flushTimeout = FramebufferFlushTimer; + long flushTimeout = _framebufferFlushTimer; long now = Stopwatch.GetTimestamp(); @@ -169,7 +169,7 @@ namespace Ryujinx.Graphics.Vulkan long averageWait = (long)_syncWaitHistory.Average(); - if (_fastFlushMode ? averageWait < FastFlushExitThreshold : averageWait > FastFlushEnterThreshold) + if (_fastFlushMode ? averageWait < _fastFlushExitThreshold : averageWait > _fastFlushEnterThreshold) { _fastFlushMode = !_fastFlushMode; Logger.Debug?.PrintMsg(LogClass.Gpu, $"Switched fast flush mode: ({_fastFlushMode})"); diff --git a/src/Ryujinx.Graphics.Vulkan/BackgroundResources.cs b/src/Ryujinx.Graphics.Vulkan/BackgroundResources.cs index b93b7a250..e9478b438 100644 --- a/src/Ryujinx.Graphics.Vulkan/BackgroundResources.cs +++ b/src/Ryujinx.Graphics.Vulkan/BackgroundResources.cs @@ -7,7 +7,7 @@ namespace Ryujinx.Graphics.Vulkan { class BackgroundResource : IDisposable { - private VulkanRenderer _gd; + private readonly VulkanRenderer _gd; private Device _device; private CommandBufferPool _pool; @@ -38,10 +38,7 @@ namespace Ryujinx.Graphics.Vulkan public PersistentFlushBuffer GetFlushBuffer() { - if (_flushBuffer == null) - { - _flushBuffer = new PersistentFlushBuffer(_gd); - } + _flushBuffer ??= new PersistentFlushBuffer(_gd); return _flushBuffer; } @@ -55,10 +52,10 @@ namespace Ryujinx.Graphics.Vulkan class BackgroundResources : IDisposable { - private VulkanRenderer _gd; + private readonly VulkanRenderer _gd; private Device _device; - private Dictionary _resources; + private readonly Dictionary _resources; public BackgroundResources(VulkanRenderer gd, Device device) { @@ -89,8 +86,7 @@ namespace Ryujinx.Graphics.Vulkan lock (_resources) { - BackgroundResource resource; - if (!_resources.TryGetValue(thread, out resource)) + if (!_resources.TryGetValue(thread, out BackgroundResource resource)) { Cleanup(); diff --git a/src/Ryujinx.Graphics.Vulkan/BitMap.cs b/src/Ryujinx.Graphics.Vulkan/BitMap.cs index efa71fc78..5619fcdf7 100644 --- a/src/Ryujinx.Graphics.Vulkan/BitMap.cs +++ b/src/Ryujinx.Graphics.Vulkan/BitMap.cs @@ -131,7 +131,7 @@ public void Clear(int bit) { int wordIndex = bit >> IntShift; - int wordBit = bit & IntMask; + int wordBit = bit & IntMask; long wordMask = 1L << wordBit; @@ -154,4 +154,4 @@ } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Vulkan/BufferAllocationType.cs b/src/Ryujinx.Graphics.Vulkan/BufferAllocationType.cs index 814890411..00b65714b 100644 --- a/src/Ryujinx.Graphics.Vulkan/BufferAllocationType.cs +++ b/src/Ryujinx.Graphics.Vulkan/BufferAllocationType.cs @@ -7,6 +7,6 @@ HostMappedNoCache, HostMapped, DeviceLocal, - DeviceLocalMapped + DeviceLocalMapped, } } diff --git a/src/Ryujinx.Graphics.Vulkan/BufferHolder.cs b/src/Ryujinx.Graphics.Vulkan/BufferHolder.cs index 6e10fad00..54635631a 100644 --- a/src/Ryujinx.Graphics.Vulkan/BufferHolder.cs +++ b/src/Ryujinx.Graphics.Vulkan/BufferHolder.cs @@ -33,7 +33,7 @@ namespace Ryujinx.Graphics.Vulkan private MemoryAllocation _allocation; private Auto _buffer; private Auto _allocationAuto; - private bool _allocationImported; + private readonly bool _allocationImported; private ulong _bufferHandle; private CacheByRange _cachedConvertedBuffers; @@ -46,7 +46,7 @@ namespace Ryujinx.Graphics.Vulkan private bool _lastAccessIsWrite; - private BufferAllocationType _baseType; + private readonly BufferAllocationType _baseType; private BufferAllocationType _currentType; private bool _swapQueued; @@ -58,7 +58,7 @@ namespace Ryujinx.Graphics.Vulkan private int _flushTemp; private int _lastFlushWrite = -1; - private ReaderWriterLock _flushLock; + private readonly ReaderWriterLock _flushLock; private FenceHolder _flushFence; private int _flushWaiting; @@ -143,10 +143,7 @@ namespace Ryujinx.Graphics.Vulkan } else { - if (cbs == null) - { - cbs = _gd.CommandBufferPool.Rent(); - } + cbs ??= _gd.CommandBufferPool.Rent(); CommandBufferScoped cbsV = cbs.Value; @@ -184,17 +181,13 @@ namespace Ryujinx.Graphics.Vulkan return true; } - else - { - return false; - } - } - else - { - _swapQueued = false; - return true; + return false; } + + _swapQueued = false; + + return true; } private void ConsiderBackingSwap() @@ -251,13 +244,13 @@ namespace Ryujinx.Graphics.Vulkan public unsafe Auto CreateView(VkFormat format, int offset, int size, Action invalidateView) { - var bufferViewCreateInfo = new BufferViewCreateInfo() + var bufferViewCreateInfo = new BufferViewCreateInfo { SType = StructureType.BufferViewCreateInfo, Buffer = new VkBuffer(_bufferHandle), Format = format, Offset = (uint)offset, - Range = (uint)size + Range = (uint)size, }; _gd.Api.CreateBufferView(_device, bufferViewCreateInfo, null, out var bufferView).ThrowOnError(); @@ -288,11 +281,11 @@ namespace Ryujinx.Graphics.Vulkan if (needsBarrier) { - MemoryBarrier memoryBarrier = new MemoryBarrier() + MemoryBarrier memoryBarrier = new() { SType = StructureType.MemoryBarrier, SrcAccessMask = DefaultAccessFlags, - DstAccessMask = DefaultAccessFlags + DstAccessMask = DefaultAccessFlags, }; _gd.Api.CmdPipelineBarrier( @@ -366,14 +359,14 @@ namespace Ryujinx.Graphics.Vulkan return Unsafe.As(ref handle); } - public unsafe IntPtr Map(int offset, int mappingSize) + public IntPtr Map(int offset, int mappingSize) { return _map; } private void ClearFlushFence() { - // Asusmes _flushLock is held as writer. + // Assumes _flushLock is held as writer. if (_flushFence != null) { @@ -421,7 +414,7 @@ namespace Ryujinx.Graphics.Vulkan } } - public unsafe PinnedSpan GetData(int offset, int size) + public PinnedSpan GetData(int offset, int size) { _flushLock.AcquireReaderLock(Timeout.Infinite); @@ -447,26 +440,24 @@ namespace Ryujinx.Graphics.Vulkan return PinnedSpan.UnsafeFromSpan(result, _buffer.DecrementReferenceCount); } + + BackgroundResource resource = _gd.BackgroundResources.Get(); + + if (_gd.CommandBufferPool.OwnedByCurrentThread) + { + _gd.FlushAllCommands(); + + result = resource.GetFlushBuffer().GetBufferData(_gd.CommandBufferPool, this, offset, size); + } else { - BackgroundResource resource = _gd.BackgroundResources.Get(); - - if (_gd.CommandBufferPool.OwnedByCurrentThread) - { - _gd.FlushAllCommands(); - - result = resource.GetFlushBuffer().GetBufferData(_gd.CommandBufferPool, this, offset, size); - } - else - { - result = resource.GetFlushBuffer().GetBufferData(resource.GetPool(), this, offset, size); - } - - _flushLock.ReleaseReaderLock(); - - // Flush buffer is pinned until the next GetBufferData on the thread, which is fine for current uses. - return PinnedSpan.UnsafeFromSpan(result); + result = resource.GetFlushBuffer().GetBufferData(resource.GetPool(), this, offset, size); } + + _flushLock.ReleaseReaderLock(); + + // Flush buffer is pinned until the next GetBufferData on the thread, which is fine for current uses. + return PinnedSpan.UnsafeFromSpan(result); } public unsafe Span GetDataStorage(int offset, int size) @@ -503,7 +494,7 @@ namespace Ryujinx.Graphics.Vulkan { WaitForFences(offset, dataSize); - data.Slice(0, dataSize).CopyTo(new Span((void*)(_map + offset), dataSize)); + data[..dataSize].CopyTo(new Span((void*)(_map + offset), dataSize)); SignalWrite(offset, dataSize); @@ -542,7 +533,7 @@ namespace Ryujinx.Graphics.Vulkan if (_map != IntPtr.Zero) { - data.Slice(0, dataSize).CopyTo(new Span((void*)(_map + offset), dataSize)); + data[..dataSize].CopyTo(new Span((void*)(_map + offset), dataSize)); } else { @@ -657,7 +648,7 @@ namespace Ryujinx.Graphics.Vulkan int offset, int size) { - BufferMemoryBarrier memoryBarrier = new BufferMemoryBarrier() + BufferMemoryBarrier memoryBarrier = new() { SType = StructureType.BufferMemoryBarrier, SrcAccessMask = srcAccessMask, @@ -666,7 +657,7 @@ namespace Ryujinx.Graphics.Vulkan DstQueueFamilyIndex = Vk.QueueFamilyIgnored, Buffer = buffer, Offset = (ulong)offset, - Size = (ulong)size + Size = (ulong)size, }; gd.Api.CmdPipelineBarrier( diff --git a/src/Ryujinx.Graphics.Vulkan/BufferManager.cs b/src/Ryujinx.Graphics.Vulkan/BufferManager.cs index 1b55909d3..b916a1ef2 100644 --- a/src/Ryujinx.Graphics.Vulkan/BufferManager.cs +++ b/src/Ryujinx.Graphics.Vulkan/BufferManager.cs @@ -73,12 +73,12 @@ namespace Ryujinx.Graphics.Vulkan usage |= BufferUsageFlags.IndirectBufferBit; } - var bufferCreateInfo = new BufferCreateInfo() + var bufferCreateInfo = new BufferCreateInfo { SType = StructureType.BufferCreateInfo, Size = (ulong)size, Usage = usage, - SharingMode = SharingMode.Exclusive + SharingMode = SharingMode.Exclusive, }; gd.Api.CreateBuffer(_device, in bufferCreateInfo, null, out var buffer).ThrowOnError(); @@ -134,12 +134,12 @@ namespace Ryujinx.Graphics.Vulkan usage |= BufferUsageFlags.IndirectBufferBit; } - var bufferCreateInfo = new BufferCreateInfo() + var bufferCreateInfo = new BufferCreateInfo { SType = StructureType.BufferCreateInfo, Size = (ulong)Environment.SystemPageSize, Usage = usage, - SharingMode = SharingMode.Exclusive + SharingMode = SharingMode.Exclusive, }; gd.Api.CreateBuffer(_device, in bufferCreateInfo, null, out var buffer).ThrowOnError(); @@ -169,12 +169,12 @@ namespace Ryujinx.Graphics.Vulkan usage |= BufferUsageFlags.IndirectBufferBit; } - var bufferCreateInfo = new BufferCreateInfo() + var bufferCreateInfo = new BufferCreateInfo { SType = StructureType.BufferCreateInfo, Size = (ulong)size, Usage = usage, - SharingMode = SharingMode.Exclusive + SharingMode = SharingMode.Exclusive, }; gd.Api.CreateBuffer(_device, in bufferCreateInfo, null, out var buffer).ThrowOnError(); @@ -190,7 +190,7 @@ namespace Ryujinx.Graphics.Vulkan BufferAllocationType.HostMapped => DefaultBufferMemoryFlags, BufferAllocationType.DeviceLocal => DeviceLocalBufferMemoryFlags, BufferAllocationType.DeviceLocalMapped => DeviceLocalMappedBufferMemoryFlags, - _ => DefaultBufferMemoryFlags + _ => DefaultBufferMemoryFlags, }; // If an allocation with this memory type fails, fall back to the previous one. @@ -216,7 +216,7 @@ namespace Ryujinx.Graphics.Vulkan return (buffer, allocation, type); } - public unsafe BufferHolder Create( + public BufferHolder Create( VulkanRenderer gd, int size, bool forConditionalRendering = false, diff --git a/src/Ryujinx.Graphics.Vulkan/BufferState.cs b/src/Ryujinx.Graphics.Vulkan/BufferState.cs index 6829f8333..ee4badd2f 100644 --- a/src/Ryujinx.Graphics.Vulkan/BufferState.cs +++ b/src/Ryujinx.Graphics.Vulkan/BufferState.cs @@ -4,7 +4,7 @@ namespace Ryujinx.Graphics.Vulkan { struct BufferState : IDisposable { - public static BufferState Null => new BufferState(null, 0, 0); + public static BufferState Null => new(null, 0, 0); private readonly int _offset; private readonly int _size; @@ -19,7 +19,7 @@ namespace Ryujinx.Graphics.Vulkan buffer?.IncrementReferenceCount(); } - public void BindTransformFeedbackBuffer(VulkanRenderer gd, CommandBufferScoped cbs, uint binding) + public readonly void BindTransformFeedbackBuffer(VulkanRenderer gd, CommandBufferScoped cbs, uint binding) { if (_buffer != null) { @@ -40,7 +40,7 @@ namespace Ryujinx.Graphics.Vulkan } } - public void Dispose() + public readonly void Dispose() { _buffer?.DecrementReferenceCount(); } diff --git a/src/Ryujinx.Graphics.Vulkan/BufferUsageBitmap.cs b/src/Ryujinx.Graphics.Vulkan/BufferUsageBitmap.cs index 920501d3a..a8ff7c286 100644 --- a/src/Ryujinx.Graphics.Vulkan/BufferUsageBitmap.cs +++ b/src/Ryujinx.Graphics.Vulkan/BufferUsageBitmap.cs @@ -2,13 +2,13 @@ { internal class BufferUsageBitmap { - private BitMap _bitmap; - private int _size; - private int _granularity; - private int _bits; + private readonly BitMap _bitmap; + private readonly int _size; + private readonly int _granularity; + private readonly int _bits; - private int _intsPerCb; - private int _bitsPerCb; + private readonly int _intsPerCb; + private readonly int _bitsPerCb; public BufferUsageBitmap(int size, int granularity) { diff --git a/src/Ryujinx.Graphics.Vulkan/CacheByRange.cs b/src/Ryujinx.Graphics.Vulkan/CacheByRange.cs index a9d1b0ef7..16954d21b 100644 --- a/src/Ryujinx.Graphics.Vulkan/CacheByRange.cs +++ b/src/Ryujinx.Graphics.Vulkan/CacheByRange.cs @@ -20,7 +20,7 @@ namespace Ryujinx.Graphics.Vulkan _buffer = null; } - public bool KeyEqual(ICacheKey other) + public readonly bool KeyEqual(ICacheKey other) { return other is I8ToI16CacheKey; } @@ -30,7 +30,7 @@ namespace Ryujinx.Graphics.Vulkan _buffer = buffer; } - public void Dispose() + public readonly void Dispose() { _gd.PipelineInternal.DirtyIndexBuffer(_buffer); } @@ -53,7 +53,7 @@ namespace Ryujinx.Graphics.Vulkan _buffer = null; } - public bool KeyEqual(ICacheKey other) + public readonly bool KeyEqual(ICacheKey other) { return other is AlignedVertexBufferCacheKey entry && entry._stride == _stride && @@ -65,7 +65,7 @@ namespace Ryujinx.Graphics.Vulkan _buffer = buffer; } - public void Dispose() + public readonly void Dispose() { _gd.PipelineInternal.DirtyVertexBuffer(_buffer); } @@ -73,8 +73,8 @@ namespace Ryujinx.Graphics.Vulkan struct TopologyConversionCacheKey : ICacheKey { - private IndexBufferPattern _pattern; - private int _indexSize; + private readonly IndexBufferPattern _pattern; + private readonly int _indexSize; // Used to notify the pipeline that bindings have invalidated on dispose. private readonly VulkanRenderer _gd; @@ -88,7 +88,7 @@ namespace Ryujinx.Graphics.Vulkan _buffer = null; } - public bool KeyEqual(ICacheKey other) + public readonly bool KeyEqual(ICacheKey other) { return other is TopologyConversionCacheKey entry && entry._pattern == _pattern && @@ -100,7 +100,7 @@ namespace Ryujinx.Graphics.Vulkan _buffer = buffer; } - public void Dispose() + public readonly void Dispose() { _gd.PipelineInternal.DirtyIndexBuffer(_buffer); } @@ -147,9 +147,9 @@ namespace Ryujinx.Graphics.Vulkan } } - struct IndirectDataCacheKey : ICacheKey + readonly struct IndirectDataCacheKey : ICacheKey { - private IndexBufferPattern _pattern; + private readonly IndexBufferPattern _pattern; public IndirectDataCacheKey(IndexBufferPattern pattern) { @@ -168,12 +168,12 @@ namespace Ryujinx.Graphics.Vulkan struct DrawCountCacheKey : ICacheKey { - public bool KeyEqual(ICacheKey other) + public readonly bool KeyEqual(ICacheKey other) { return other is DrawCountCacheKey; } - public void Dispose() + public readonly void Dispose() { } } @@ -214,7 +214,7 @@ namespace Ryujinx.Graphics.Vulkan DependencyList = null; } - public void InvalidateDependencies() + public readonly void InvalidateDependencies() { if (DependencyList != null) { @@ -317,7 +317,7 @@ namespace Ryujinx.Graphics.Vulkan } } - public void ClearRange(int offset, int size) + public readonly void ClearRange(int offset, int size) { if (_ranges != null && _ranges.Count > 0) { @@ -356,15 +356,11 @@ namespace Ryujinx.Graphics.Vulkan private List GetEntries(int offset, int size) { - if (_ranges == null) - { - _ranges = new Dictionary>(); - } + _ranges ??= new Dictionary>(); ulong key = PackRange(offset, size); - List value; - if (!_ranges.TryGetValue(key, out value)) + if (!_ranges.TryGetValue(key, out List value)) { value = new List(); _ranges.Add(key, value); diff --git a/src/Ryujinx.Graphics.Vulkan/CommandBufferPool.cs b/src/Ryujinx.Graphics.Vulkan/CommandBufferPool.cs index 42b46eaec..17eeef68a 100644 --- a/src/Ryujinx.Graphics.Vulkan/CommandBufferPool.cs +++ b/src/Ryujinx.Graphics.Vulkan/CommandBufferPool.cs @@ -2,7 +2,8 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using Thread = System.Threading.Thread; +using System.Threading; +using Semaphore = Silk.NET.Vulkan.Semaphore; namespace Ryujinx.Graphics.Vulkan { @@ -10,8 +11,8 @@ namespace Ryujinx.Graphics.Vulkan { public const int MaxCommandBuffers = 16; - private int _totalCommandBuffers; - private int _totalCommandBuffersMask; + private readonly int _totalCommandBuffers; + private readonly int _totalCommandBuffersMask; private readonly Vk _api; private readonly Device _device; @@ -36,12 +37,12 @@ namespace Ryujinx.Graphics.Vulkan public void Initialize(Vk api, Device device, CommandPool pool) { - var allocateInfo = new CommandBufferAllocateInfo() + var allocateInfo = new CommandBufferAllocateInfo { SType = StructureType.CommandBufferAllocateInfo, CommandBufferCount = 1, CommandPool = pool, - Level = CommandBufferLevel.Primary + Level = CommandBufferLevel.Primary, }; api.AllocateCommandBuffers(device, allocateInfo, out CommandBuffer); @@ -67,12 +68,12 @@ namespace Ryujinx.Graphics.Vulkan _queueLock = queueLock; _owner = Thread.CurrentThread; - var commandPoolCreateInfo = new CommandPoolCreateInfo() + var commandPoolCreateInfo = new CommandPoolCreateInfo { SType = StructureType.CommandPoolCreateInfo, QueueFamilyIndex = queueFamilyIndex, Flags = CommandPoolCreateFlags.TransientBit | - CommandPoolCreateFlags.ResetCommandBufferBit + CommandPoolCreateFlags.ResetCommandBufferBit, }; api.CreateCommandPool(device, commandPoolCreateInfo, null, out _pool).ThrowOnError(); @@ -243,9 +244,9 @@ namespace Ryujinx.Graphics.Vulkan _inUseCount++; - var commandBufferBeginInfo = new CommandBufferBeginInfo() + var commandBufferBeginInfo = new CommandBufferBeginInfo { - SType = StructureType.CommandBufferBeginInfo + SType = StructureType.CommandBufferBeginInfo, }; _api.BeginCommandBuffer(entry.CommandBuffer, commandBufferBeginInfo).ThrowOnError(); @@ -291,7 +292,7 @@ namespace Ryujinx.Graphics.Vulkan { fixed (PipelineStageFlags* pWaitDstStageMask = waitDstStageMask) { - SubmitInfo sInfo = new SubmitInfo() + SubmitInfo sInfo = new() { SType = StructureType.SubmitInfo, WaitSemaphoreCount = waitSemaphores != null ? (uint)waitSemaphores.Length : 0, @@ -300,7 +301,7 @@ namespace Ryujinx.Graphics.Vulkan CommandBufferCount = 1, PCommandBuffers = &commandBuffer, SignalSemaphoreCount = signalSemaphores != null ? (uint)signalSemaphores.Length : 0, - PSignalSemaphores = pSignalSemaphores + PSignalSemaphores = pSignalSemaphores, }; lock (_queueLock) diff --git a/src/Ryujinx.Graphics.Vulkan/DescriptorSetCollection.cs b/src/Ryujinx.Graphics.Vulkan/DescriptorSetCollection.cs index a185d7871..846dd5c7d 100644 --- a/src/Ryujinx.Graphics.Vulkan/DescriptorSetCollection.cs +++ b/src/Ryujinx.Graphics.Vulkan/DescriptorSetCollection.cs @@ -8,7 +8,7 @@ namespace Ryujinx.Graphics.Vulkan { private DescriptorSetManager.DescriptorPoolHolder _holder; private readonly DescriptorSet[] _descriptorSets; - public int SetsCount => _descriptorSets.Length; + public readonly int SetsCount => _descriptorSets.Length; public DescriptorSetCollection(DescriptorSetManager.DescriptorPoolHolder holder, DescriptorSet[] descriptorSets) { @@ -20,10 +20,10 @@ namespace Ryujinx.Graphics.Vulkan { Span infos = stackalloc DescriptorBufferInfo[count]; - infos.Fill(new DescriptorBufferInfo() + infos.Fill(new DescriptorBufferInfo { Buffer = dummyBuffer, - Range = Vk.WholeSize + Range = Vk.WholeSize, }); UpdateBuffers(setIndex, baseBinding, infos, type); @@ -40,7 +40,7 @@ namespace Ryujinx.Graphics.Vulkan DstBinding = (uint)bindingIndex, DescriptorType = type, DescriptorCount = 1, - PBufferInfo = &bufferInfo + PBufferInfo = &bufferInfo, }; _holder.Api.UpdateDescriptorSets(_holder.Device, 1, writeDescriptorSet, 0, null); @@ -63,7 +63,7 @@ namespace Ryujinx.Graphics.Vulkan DstBinding = (uint)baseBinding, DescriptorType = type, DescriptorCount = (uint)bufferInfo.Length, - PBufferInfo = pBufferInfo + PBufferInfo = pBufferInfo, }; _holder.Api.UpdateDescriptorSets(_holder.Device, 1, writeDescriptorSet, 0, null); @@ -81,7 +81,7 @@ namespace Ryujinx.Graphics.Vulkan DstBinding = (uint)bindingIndex, DescriptorType = type, DescriptorCount = 1, - PImageInfo = &imageInfo + PImageInfo = &imageInfo, }; _holder.Api.UpdateDescriptorSets(_holder.Device, 1, writeDescriptorSet, 0, null); @@ -104,7 +104,7 @@ namespace Ryujinx.Graphics.Vulkan DstBinding = (uint)baseBinding, DescriptorType = type, DescriptorCount = (uint)imageInfo.Length, - PImageInfo = pImageInfo + PImageInfo = pImageInfo, }; _holder.Api.UpdateDescriptorSets(_holder.Device, 1, writeDescriptorSet, 0, null); @@ -141,7 +141,7 @@ namespace Ryujinx.Graphics.Vulkan DstBinding = (uint)(baseBinding + i), DescriptorType = DescriptorType.CombinedImageSampler, DescriptorCount = (uint)count, - PImageInfo = pImageInfo + PImageInfo = pImageInfo, }; _holder.Api.UpdateDescriptorSets(_holder.Device, 1, writeDescriptorSet, 0, null); @@ -163,7 +163,7 @@ namespace Ryujinx.Graphics.Vulkan DstBinding = (uint)bindingIndex, DescriptorType = type, DescriptorCount = 1, - PTexelBufferView = &texelBufferView + PTexelBufferView = &texelBufferView, }; _holder.Api.UpdateDescriptorSets(_holder.Device, 1, writeDescriptorSet, 0, null); @@ -197,7 +197,7 @@ namespace Ryujinx.Graphics.Vulkan DstBinding = (uint)baseBinding + i, DescriptorType = type, DescriptorCount = count, - PTexelBufferView = pTexelBufferView + i + PTexelBufferView = pTexelBufferView + i, }; _holder.Api.UpdateDescriptorSets(_holder.Device, 1, writeDescriptorSet, 0, null); @@ -208,7 +208,7 @@ namespace Ryujinx.Graphics.Vulkan } } - public DescriptorSet[] GetSets() + public readonly DescriptorSet[] GetSets() { return _descriptorSets; } diff --git a/src/Ryujinx.Graphics.Vulkan/DescriptorSetManager.cs b/src/Ryujinx.Graphics.Vulkan/DescriptorSetManager.cs index a88bb7b12..2f7b604c4 100644 --- a/src/Ryujinx.Graphics.Vulkan/DescriptorSetManager.cs +++ b/src/Ryujinx.Graphics.Vulkan/DescriptorSetManager.cs @@ -24,14 +24,14 @@ namespace Ryujinx.Graphics.Vulkan Api = api; Device = device; - var poolSizes = new DescriptorPoolSize[] + var poolSizes = new[] { new DescriptorPoolSize(DescriptorType.UniformBuffer, (1 + Constants.MaxUniformBufferBindings) * DescriptorPoolMultiplier), new DescriptorPoolSize(DescriptorType.StorageBuffer, Constants.MaxStorageBufferBindings * DescriptorPoolMultiplier), new DescriptorPoolSize(DescriptorType.CombinedImageSampler, Constants.MaxTextureBindings * DescriptorPoolMultiplier), new DescriptorPoolSize(DescriptorType.StorageImage, Constants.MaxImageBindings * DescriptorPoolMultiplier), new DescriptorPoolSize(DescriptorType.UniformTexelBuffer, Constants.MaxTextureBindings * DescriptorPoolMultiplier), - new DescriptorPoolSize(DescriptorType.StorageTexelBuffer, Constants.MaxImageBindings * DescriptorPoolMultiplier) + new DescriptorPoolSize(DescriptorType.StorageTexelBuffer, Constants.MaxImageBindings * DescriptorPoolMultiplier), }; uint maxSets = (uint)poolSizes.Length * DescriptorPoolMultiplier; @@ -40,19 +40,19 @@ namespace Ryujinx.Graphics.Vulkan fixed (DescriptorPoolSize* pPoolsSize = poolSizes) { - var descriptorPoolCreateInfo = new DescriptorPoolCreateInfo() + var descriptorPoolCreateInfo = new DescriptorPoolCreateInfo { SType = StructureType.DescriptorPoolCreateInfo, MaxSets = maxSets, PoolSizeCount = (uint)poolSizes.Length, - PPoolSizes = pPoolsSize + PPoolSizes = pPoolsSize, }; Api.CreateDescriptorPool(device, descriptorPoolCreateInfo, null, out _pool).ThrowOnError(); } } - public unsafe DescriptorSetCollection AllocateDescriptorSets(ReadOnlySpan layouts) + public DescriptorSetCollection AllocateDescriptorSets(ReadOnlySpan layouts) { TryAllocateDescriptorSets(layouts, isTry: false, out var dsc); return dsc; @@ -73,12 +73,12 @@ namespace Ryujinx.Graphics.Vulkan { fixed (DescriptorSetLayout* pLayouts = layouts) { - var descriptorSetAllocateInfo = new DescriptorSetAllocateInfo() + var descriptorSetAllocateInfo = new DescriptorSetAllocateInfo { SType = StructureType.DescriptorSetAllocateInfo, DescriptorPool = _pool, DescriptorSetCount = (uint)layouts.Length, - PSetLayouts = pLayouts + PSetLayouts = pLayouts, }; var result = Api.AllocateDescriptorSets(Device, &descriptorSetAllocateInfo, pDescriptorSets); @@ -142,6 +142,7 @@ namespace Ryujinx.Graphics.Vulkan public void Dispose() { + GC.SuppressFinalize(this); Dispose(true); } } @@ -186,15 +187,13 @@ namespace Ryujinx.Graphics.Vulkan { if (disposing) { - unsafe - { - _currentPool?.Dispose(); - } + _currentPool?.Dispose(); } } public void Dispose() { + GC.SuppressFinalize(this); Dispose(true); } } diff --git a/src/Ryujinx.Graphics.Vulkan/DescriptorSetUpdater.cs b/src/Ryujinx.Graphics.Vulkan/DescriptorSetUpdater.cs index b09a0667e..087d90fb8 100644 --- a/src/Ryujinx.Graphics.Vulkan/DescriptorSetUpdater.cs +++ b/src/Ryujinx.Graphics.Vulkan/DescriptorSetUpdater.cs @@ -2,8 +2,11 @@ using Ryujinx.Graphics.Shader; using Silk.NET.Vulkan; using System; -using System.Numerics; using System.Runtime.CompilerServices; +using Buffer = Silk.NET.Vulkan.Buffer; +using CompareOp = Ryujinx.Graphics.GAL.CompareOp; +using Format = Ryujinx.Graphics.GAL.Format; +using SamplerCreateInfo = Ryujinx.Graphics.GAL.SamplerCreateInfo; namespace Ryujinx.Graphics.Vulkan { @@ -14,25 +17,25 @@ namespace Ryujinx.Graphics.Vulkan private ShaderCollection _program; - private Auto[] _uniformBufferRefs; - private Auto[] _storageBufferRefs; - private Auto[] _textureRefs; - private Auto[] _samplerRefs; - private Auto[] _imageRefs; - private TextureBuffer[] _bufferTextureRefs; - private TextureBuffer[] _bufferImageRefs; - private GAL.Format[] _bufferImageFormats; + private readonly Auto[] _uniformBufferRefs; + private readonly Auto[] _storageBufferRefs; + private readonly Auto[] _textureRefs; + private readonly Auto[] _samplerRefs; + private readonly Auto[] _imageRefs; + private readonly TextureBuffer[] _bufferTextureRefs; + private readonly TextureBuffer[] _bufferImageRefs; + private readonly Format[] _bufferImageFormats; - private DescriptorBufferInfo[] _uniformBuffers; - private DescriptorBufferInfo[] _storageBuffers; - private DescriptorImageInfo[] _textures; - private DescriptorImageInfo[] _images; - private BufferView[] _bufferTextures; - private BufferView[] _bufferImages; + private readonly DescriptorBufferInfo[] _uniformBuffers; + private readonly DescriptorBufferInfo[] _storageBuffers; + private readonly DescriptorImageInfo[] _textures; + private readonly DescriptorImageInfo[] _images; + private readonly BufferView[] _bufferTextures; + private readonly BufferView[] _bufferImages; - private bool[] _uniformSet; - private bool[] _storageSet; - private Silk.NET.Vulkan.Buffer _cachedSupportBuffer; + private readonly bool[] _uniformSet; + private readonly bool[] _storageSet; + private Buffer _cachedSupportBuffer; [Flags] private enum DirtyFlags @@ -42,7 +45,7 @@ namespace Ryujinx.Graphics.Vulkan Storage = 1 << 1, Texture = 1 << 2, Image = 1 << 3, - All = Uniform | Storage | Texture | Image + All = Uniform | Storage | Texture | Image, } private DirtyFlags _dirty; @@ -66,7 +69,7 @@ namespace Ryujinx.Graphics.Vulkan _imageRefs = new Auto[Constants.MaxImageBindings * 2]; _bufferTextureRefs = new TextureBuffer[Constants.MaxTextureBindings * 2]; _bufferImageRefs = new TextureBuffer[Constants.MaxImageBindings * 2]; - _bufferImageFormats = new GAL.Format[Constants.MaxImageBindings * 2]; + _bufferImageFormats = new Format[Constants.MaxImageBindings * 2]; _uniformBuffers = new DescriptorBufferInfo[Constants.MaxUniformBufferBindings]; _storageBuffers = new DescriptorBufferInfo[Constants.MaxStorageBufferBindings]; @@ -75,9 +78,9 @@ namespace Ryujinx.Graphics.Vulkan _bufferTextures = new BufferView[Constants.MaxTexturesPerStage]; _bufferImages = new BufferView[Constants.MaxImagesPerStage]; - var initialImageInfo = new DescriptorImageInfo() + var initialImageInfo = new DescriptorImageInfo { - ImageLayout = ImageLayout.General + ImageLayout = ImageLayout.General, }; _textures.AsSpan().Fill(initialImageInfo); @@ -106,7 +109,7 @@ namespace Ryujinx.Graphics.Vulkan 1, 1, 4, - GAL.Format.R8G8B8A8Unorm, + Format.R8G8B8A8Unorm, DepthStencilMode.Depth, Target.Texture2D, SwizzleComponent.Red, @@ -114,7 +117,7 @@ namespace Ryujinx.Graphics.Vulkan SwizzleComponent.Blue, SwizzleComponent.Alpha), 1f); - _dummySampler = (SamplerHolder)gd.CreateSampler(new GAL.SamplerCreateInfo( + _dummySampler = (SamplerHolder)gd.CreateSampler(new SamplerCreateInfo( MinFilter.Nearest, MagFilter.Nearest, false, @@ -122,7 +125,7 @@ namespace Ryujinx.Graphics.Vulkan AddressMode.Repeat, AddressMode.Repeat, CompareMode.None, - GAL.CompareOp.Always, + CompareOp.Always, new ColorF(0, 0, 0, 0), 0, 0, @@ -142,7 +145,7 @@ namespace Ryujinx.Graphics.Vulkan _dirty = DirtyFlags.All; } - public void SetImage(int binding, ITexture image, GAL.Format imageFormat) + public void SetImage(int binding, ITexture image, Format imageFormat) { if (image is TextureBuffer imageBuffer) { @@ -181,10 +184,10 @@ namespace Ryujinx.Graphics.Vulkan Auto vkBuffer = _gd.BufferManager.GetBuffer(commandBuffer, buffer.Handle, false, isSSBO: true); ref Auto currentVkBuffer = ref _storageBufferRefs[index]; - DescriptorBufferInfo info = new DescriptorBufferInfo() + DescriptorBufferInfo info = new() { Offset = (ulong)buffer.Offset, - Range = (ulong)buffer.Size + Range = (ulong)buffer.Size, }; ref DescriptorBufferInfo currentInfo = ref _storageBuffers[index]; @@ -209,10 +212,10 @@ namespace Ryujinx.Graphics.Vulkan ref Auto currentVkBuffer = ref _storageBufferRefs[index]; - DescriptorBufferInfo info = new DescriptorBufferInfo() + DescriptorBufferInfo info = new() { Offset = 0, - Range = Vk.WholeSize + Range = Vk.WholeSize, }; ref DescriptorBufferInfo currentInfo = ref _storageBuffers[index]; @@ -289,10 +292,10 @@ namespace Ryujinx.Graphics.Vulkan Auto vkBuffer = _gd.BufferManager.GetBuffer(commandBuffer, buffer.Handle, false); ref Auto currentVkBuffer = ref _uniformBufferRefs[index]; - DescriptorBufferInfo info = new DescriptorBufferInfo() + DescriptorBufferInfo info = new() { Offset = (ulong)buffer.Offset, - Range = (ulong)buffer.Size + Range = (ulong)buffer.Size, }; ref DescriptorBufferInfo currentInfo = ref _uniformBuffers[index]; @@ -400,11 +403,11 @@ namespace Ryujinx.Graphics.Vulkan _uniformSet[0] = true; } - uniformBuffer[0] = new DescriptorBufferInfo() + uniformBuffer[0] = new DescriptorBufferInfo { Offset = 0, Range = (ulong)SupportBuffer.RequiredSize, - Buffer = _cachedSupportBuffer + Buffer = _cachedSupportBuffer, }; dsc.UpdateBuffers(0, 0, uniformBuffer, DescriptorType.UniformBuffer); @@ -474,7 +477,7 @@ namespace Ryujinx.Graphics.Vulkan } } - dsc.UpdateImages(0, binding, textures.Slice(0, count), DescriptorType.CombinedImageSampler); + dsc.UpdateImages(0, binding, textures[..count], DescriptorType.CombinedImageSampler); } else { @@ -485,7 +488,7 @@ namespace Ryujinx.Graphics.Vulkan bufferTextures[i] = _bufferTextureRefs[binding + i]?.GetBufferView(cbs) ?? default; } - dsc.UpdateBufferImages(0, binding, bufferTextures.Slice(0, count), DescriptorType.UniformTexelBuffer); + dsc.UpdateBufferImages(0, binding, bufferTextures[..count], DescriptorType.UniformTexelBuffer); } } else if (setIndex == PipelineBase.ImageSetIndex) @@ -499,7 +502,7 @@ namespace Ryujinx.Graphics.Vulkan images[i].ImageView = _imageRefs[binding + i]?.Get(cbs).Value ?? default; } - dsc.UpdateImages(0, binding, images.Slice(0, count), DescriptorType.StorageImage); + dsc.UpdateImages(0, binding, images[..count], DescriptorType.StorageImage); } else { @@ -510,7 +513,7 @@ namespace Ryujinx.Graphics.Vulkan bufferImages[i] = _bufferImageRefs[binding + i]?.GetBufferView(cbs, _bufferImageFormats[binding + i]) ?? default; } - dsc.UpdateBufferImages(0, binding, bufferImages.Slice(0, count), DescriptorType.StorageTexelBuffer); + dsc.UpdateBufferImages(0, binding, bufferImages[..count], DescriptorType.StorageTexelBuffer); } } } @@ -540,7 +543,7 @@ namespace Ryujinx.Graphics.Vulkan DstBinding = (uint)baseBinding, DescriptorType = type, DescriptorCount = (uint)bufferInfo.Length, - PBufferInfo = pBufferInfo + PBufferInfo = pBufferInfo, }; _gd.PushDescriptorApi.CmdPushDescriptorSet(cbs.CommandBuffer, pbp, _program.PipelineLayout, 0, 1, &writeDescriptorSet); @@ -554,11 +557,11 @@ namespace Ryujinx.Graphics.Vulkan { Span uniformBuffer = stackalloc DescriptorBufferInfo[1]; - uniformBuffer[0] = new DescriptorBufferInfo() + uniformBuffer[0] = new DescriptorBufferInfo { Offset = 0, Range = (ulong)SupportBuffer.RequiredSize, - Buffer = _gd.BufferManager.GetBuffer(cbs.CommandBuffer, _pipeline.SupportBufferUpdater.Handle, false).Get(cbs, 0, SupportBuffer.RequiredSize).Value + Buffer = _gd.BufferManager.GetBuffer(cbs.CommandBuffer, _pipeline.SupportBufferUpdater.Handle, false).Get(cbs, 0, SupportBuffer.RequiredSize).Value, }; _uniformSet[0] = true; @@ -620,7 +623,7 @@ namespace Ryujinx.Graphics.Vulkan Array.Clear(_storageSet); } - private void SwapBuffer(Auto[] list, Auto from, Auto to) + private static void SwapBuffer(Auto[] list, Auto from, Auto to) { for (int i = 0; i < list.Length; i++) { diff --git a/src/Ryujinx.Graphics.Vulkan/DisposableBuffer.cs b/src/Ryujinx.Graphics.Vulkan/DisposableBuffer.cs index 0f474f970..ba52c2575 100644 --- a/src/Ryujinx.Graphics.Vulkan/DisposableBuffer.cs +++ b/src/Ryujinx.Graphics.Vulkan/DisposableBuffer.cs @@ -1,5 +1,6 @@ using Silk.NET.Vulkan; using System; +using Buffer = Silk.NET.Vulkan.Buffer; namespace Ryujinx.Graphics.Vulkan { @@ -8,9 +9,9 @@ namespace Ryujinx.Graphics.Vulkan private readonly Vk _api; private readonly Device _device; - public Silk.NET.Vulkan.Buffer Value { get; } + public Buffer Value { get; } - public DisposableBuffer(Vk api, Device device, Silk.NET.Vulkan.Buffer buffer) + public DisposableBuffer(Vk api, Device device, Buffer buffer) { _api = api; _device = device; diff --git a/src/Ryujinx.Graphics.Vulkan/Effects/FsrScalingFilter.cs b/src/Ryujinx.Graphics.Vulkan/Effects/FsrScalingFilter.cs index 7317b567a..89a43b12c 100644 --- a/src/Ryujinx.Graphics.Vulkan/Effects/FsrScalingFilter.cs +++ b/src/Ryujinx.Graphics.Vulkan/Effects/FsrScalingFilter.cs @@ -5,10 +5,12 @@ using Ryujinx.Graphics.Shader.Translation; using Silk.NET.Vulkan; using System; using Extent2D = Ryujinx.Graphics.GAL.Extents2D; +using Format = Silk.NET.Vulkan.Format; +using SamplerCreateInfo = Ryujinx.Graphics.GAL.SamplerCreateInfo; namespace Ryujinx.Graphics.Vulkan.Effects { - internal partial class FsrScalingFilter : IScalingFilter + internal class FsrScalingFilter : IScalingFilter { private readonly VulkanRenderer _renderer; private PipelineHelperShader _pipeline; @@ -66,16 +68,16 @@ namespace Ryujinx.Graphics.Vulkan.Effects .Add(ResourceStages.Compute, ResourceType.TextureAndSampler, 1) .Add(ResourceStages.Compute, ResourceType.Image, 0).Build(); - _sampler = _renderer.CreateSampler(GAL.SamplerCreateInfo.Create(MinFilter.Linear, MagFilter.Linear)); + _sampler = _renderer.CreateSampler(SamplerCreateInfo.Create(MinFilter.Linear, MagFilter.Linear)); _scalingProgram = _renderer.CreateProgramWithMinimalLayout(new[] { - new ShaderSource(scalingShader, ShaderStage.Compute, TargetLanguage.Spirv) + new ShaderSource(scalingShader, ShaderStage.Compute, TargetLanguage.Spirv), }, scalingResourceLayout); _sharpeningProgram = _renderer.CreateProgramWithMinimalLayout(new[] { - new ShaderSource(sharpeningShader, ShaderStage.Compute, TargetLanguage.Spirv) + new ShaderSource(sharpeningShader, ShaderStage.Compute, TargetLanguage.Spirv), }, sharpeningResourceLayout); } @@ -83,7 +85,7 @@ namespace Ryujinx.Graphics.Vulkan.Effects TextureView view, CommandBufferScoped cbs, Auto destinationTexture, - Silk.NET.Vulkan.Format format, + Format format, int width, int height, Extent2D source, @@ -136,14 +138,14 @@ namespace Ryujinx.Graphics.Vulkan.Effects destination.Y1, destination.Y2, scaleX, - scaleY + scaleY, }; int rangeSize = dimensionsBuffer.Length * sizeof(float); var bufferHandle = _renderer.BufferManager.CreateWithHandle(_renderer, rangeSize); _renderer.BufferManager.SetData(bufferHandle, 0, dimensionsBuffer); - ReadOnlySpan sharpeningBuffer = stackalloc float[] { 1.5f - (Level * 0.01f * 1.5f)}; + ReadOnlySpan sharpeningBuffer = stackalloc float[] { 1.5f - (Level * 0.01f * 1.5f) }; var sharpeningBufferHandle = _renderer.BufferManager.CreateWithHandle(_renderer, sizeof(float)); _renderer.BufferManager.SetData(sharpeningBufferHandle, 0, sharpeningBuffer); @@ -172,4 +174,4 @@ namespace Ryujinx.Graphics.Vulkan.Effects _renderer.BufferManager.Delete(sharpeningBufferHandle); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Vulkan/Effects/FxaaPostProcessingEffect.cs b/src/Ryujinx.Graphics.Vulkan/Effects/FxaaPostProcessingEffect.cs index 3c3516bbf..2dd991802 100644 --- a/src/Ryujinx.Graphics.Vulkan/Effects/FxaaPostProcessingEffect.cs +++ b/src/Ryujinx.Graphics.Vulkan/Effects/FxaaPostProcessingEffect.cs @@ -4,16 +4,17 @@ using Ryujinx.Graphics.Shader; using Ryujinx.Graphics.Shader.Translation; using Silk.NET.Vulkan; using System; +using SamplerCreateInfo = Ryujinx.Graphics.GAL.SamplerCreateInfo; namespace Ryujinx.Graphics.Vulkan.Effects { - internal partial class FxaaPostProcessingEffect : IPostProcessingEffect + internal class FxaaPostProcessingEffect : IPostProcessingEffect { private readonly VulkanRenderer _renderer; private ISampler _samplerLinear; private ShaderCollection _shaderProgram; - private PipelineHelperShader _pipeline; + private readonly PipelineHelperShader _pipeline; private TextureView _texture; public FxaaPostProcessingEffect(VulkanRenderer renderer, Device device) @@ -43,11 +44,11 @@ namespace Ryujinx.Graphics.Vulkan.Effects .Add(ResourceStages.Compute, ResourceType.TextureAndSampler, 1) .Add(ResourceStages.Compute, ResourceType.Image, 0).Build(); - _samplerLinear = _renderer.CreateSampler(GAL.SamplerCreateInfo.Create(MinFilter.Linear, MagFilter.Linear)); + _samplerLinear = _renderer.CreateSampler(SamplerCreateInfo.Create(MinFilter.Linear, MagFilter.Linear)); _shaderProgram = _renderer.CreateProgramWithMinimalLayout(new[] { - new ShaderSource(shader, ShaderStage.Compute, TargetLanguage.Spirv) + new ShaderSource(shader, ShaderStage.Compute, TargetLanguage.Spirv), }, resourceLayout); } @@ -86,4 +87,4 @@ namespace Ryujinx.Graphics.Vulkan.Effects return _texture; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Vulkan/Effects/IPostProcessingEffect.cs b/src/Ryujinx.Graphics.Vulkan/Effects/IPostProcessingEffect.cs index d36cf01d4..d13641c66 100644 --- a/src/Ryujinx.Graphics.Vulkan/Effects/IPostProcessingEffect.cs +++ b/src/Ryujinx.Graphics.Vulkan/Effects/IPostProcessingEffect.cs @@ -7,4 +7,4 @@ namespace Ryujinx.Graphics.Vulkan.Effects const int LocalGroupSize = 64; TextureView Run(TextureView view, CommandBufferScoped cbs, int width, int height); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Vulkan/Effects/IScalingFilter.cs b/src/Ryujinx.Graphics.Vulkan/Effects/IScalingFilter.cs index 54f809d71..50fc3710c 100644 --- a/src/Ryujinx.Graphics.Vulkan/Effects/IScalingFilter.cs +++ b/src/Ryujinx.Graphics.Vulkan/Effects/IScalingFilter.cs @@ -17,4 +17,4 @@ namespace Ryujinx.Graphics.Vulkan.Effects Extent2D source, Extent2D destination); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Vulkan/Effects/SmaaConstants.cs b/src/Ryujinx.Graphics.Vulkan/Effects/SmaaConstants.cs index a5f060f1b..0383ab237 100644 --- a/src/Ryujinx.Graphics.Vulkan/Effects/SmaaConstants.cs +++ b/src/Ryujinx.Graphics.Vulkan/Effects/SmaaConstants.cs @@ -12,4 +12,4 @@ namespace Ryujinx.Graphics.Vulkan.Effects public float Width; public float Height; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Vulkan/Effects/SmaaPostProcessingEffect.cs b/src/Ryujinx.Graphics.Vulkan/Effects/SmaaPostProcessingEffect.cs index f6de3ac2e..40ab245ee 100644 --- a/src/Ryujinx.Graphics.Vulkan/Effects/SmaaPostProcessingEffect.cs +++ b/src/Ryujinx.Graphics.Vulkan/Effects/SmaaPostProcessingEffect.cs @@ -4,10 +4,12 @@ using Ryujinx.Graphics.Shader; using Ryujinx.Graphics.Shader.Translation; using Silk.NET.Vulkan; using System; +using Format = Ryujinx.Graphics.GAL.Format; +using SamplerCreateInfo = Ryujinx.Graphics.GAL.SamplerCreateInfo; namespace Ryujinx.Graphics.Vulkan.Effects { - internal partial class SmaaPostProcessingEffect : IPostProcessingEffect + internal class SmaaPostProcessingEffect : IPostProcessingEffect { public const int AreaWidth = 160; public const int AreaHeight = 560; @@ -63,7 +65,7 @@ namespace Ryujinx.Graphics.Vulkan.Effects _searchTexture?.Dispose(); } - private unsafe void RecreateShaders(int width, int height) + private void RecreateShaders(int width, int height) { _recreatePipelines = false; @@ -94,9 +96,9 @@ namespace Ryujinx.Graphics.Vulkan.Effects .Add(ResourceStages.Compute, ResourceType.TextureAndSampler, 3) .Add(ResourceStages.Compute, ResourceType.Image, 0).Build(); - _samplerLinear = _renderer.CreateSampler(GAL.SamplerCreateInfo.Create(MinFilter.Linear, MagFilter.Linear)); + _samplerLinear = _renderer.CreateSampler(SamplerCreateInfo.Create(MinFilter.Linear, MagFilter.Linear)); - _specConstants = new SmaaConstants() + _specConstants = new SmaaConstants { Width = width, Height = height, @@ -116,17 +118,17 @@ namespace Ryujinx.Graphics.Vulkan.Effects _edgeProgram = _renderer.CreateProgramWithMinimalLayout(new[] { - new ShaderSource(edgeShader, ShaderStage.Compute, TargetLanguage.Spirv) + new ShaderSource(edgeShader, ShaderStage.Compute, TargetLanguage.Spirv), }, edgeResourceLayout, new[] { specInfo }); _blendProgram = _renderer.CreateProgramWithMinimalLayout(new[] { - new ShaderSource(blendShader, ShaderStage.Compute, TargetLanguage.Spirv) + new ShaderSource(blendShader, ShaderStage.Compute, TargetLanguage.Spirv), }, blendResourceLayout, new[] { specInfo }); _neighbourProgram = _renderer.CreateProgramWithMinimalLayout(new[] { - new ShaderSource(neighbourShader, ShaderStage.Compute, TargetLanguage.Spirv) + new ShaderSource(neighbourShader, ShaderStage.Compute, TargetLanguage.Spirv), }, neighbourResourceLayout, new[] { specInfo }); } @@ -148,7 +150,7 @@ namespace Ryujinx.Graphics.Vulkan.Effects 1, 1, 1, - GAL.Format.R8G8Unorm, + Format.R8G8Unorm, DepthStencilMode.Depth, Target.Texture2D, SwizzleComponent.Red, @@ -164,7 +166,7 @@ namespace Ryujinx.Graphics.Vulkan.Effects 1, 1, 1, - GAL.Format.R8Unorm, + Format.R8Unorm, DepthStencilMode.Depth, Target.Texture2D, SwizzleComponent.Red, @@ -264,4 +266,4 @@ namespace Ryujinx.Graphics.Vulkan.Effects _pipeline.ClearRenderTargetColor(0, 0, 1, new ColorF(0f, 0f, 0f, 1f)); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Vulkan/EnumConversion.cs b/src/Ryujinx.Graphics.Vulkan/EnumConversion.cs index 55868ee35..9323fcf97 100644 --- a/src/Ryujinx.Graphics.Vulkan/EnumConversion.cs +++ b/src/Ryujinx.Graphics.Vulkan/EnumConversion.cs @@ -3,6 +3,14 @@ using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.Shader; using Silk.NET.Vulkan; using System; +using BlendFactor = Silk.NET.Vulkan.BlendFactor; +using BlendOp = Silk.NET.Vulkan.BlendOp; +using CompareOp = Silk.NET.Vulkan.CompareOp; +using Format = Ryujinx.Graphics.GAL.Format; +using FrontFace = Silk.NET.Vulkan.FrontFace; +using IndexType = Silk.NET.Vulkan.IndexType; +using PrimitiveTopology = Silk.NET.Vulkan.PrimitiveTopology; +using StencilOp = Silk.NET.Vulkan.StencilOp; namespace Ryujinx.Graphics.Vulkan { @@ -18,7 +26,7 @@ namespace Ryujinx.Graphics.Vulkan ShaderStage.TessellationEvaluation => ShaderStageFlags.TessellationEvaluationBit, ShaderStage.Fragment => ShaderStageFlags.FragmentBit, ShaderStage.Compute => ShaderStageFlags.ComputeBit, - _ => LogInvalidAndReturn(stage, nameof(ShaderStage), (ShaderStageFlags)0) + _ => LogInvalidAndReturn(stage, nameof(ShaderStage), (ShaderStageFlags)0), }; } @@ -32,7 +40,7 @@ namespace Ryujinx.Graphics.Vulkan ShaderStage.TessellationEvaluation => PipelineStageFlags.TessellationEvaluationShaderBit, ShaderStage.Fragment => PipelineStageFlags.FragmentShaderBit, ShaderStage.Compute => PipelineStageFlags.ComputeShaderBit, - _ => LogInvalidAndReturn(stage, nameof(ShaderStage), (PipelineStageFlags)0) + _ => LogInvalidAndReturn(stage, nameof(ShaderStage), (PipelineStageFlags)0), }; } @@ -82,7 +90,7 @@ namespace Ryujinx.Graphics.Vulkan ResourceType.Image => DescriptorType.StorageImage, ResourceType.BufferTexture => DescriptorType.UniformTexelBuffer, ResourceType.BufferImage => DescriptorType.StorageTexelBuffer, - _ => throw new ArgumentException($"Invalid resource type \"{type}\".") + _ => throw new ArgumentException($"Invalid resource type \"{type}\"."), }; } @@ -98,128 +106,128 @@ namespace Ryujinx.Graphics.Vulkan AddressMode.ClampToBorder => SamplerAddressMode.ClampToBorder, AddressMode.MirroredRepeat => SamplerAddressMode.MirroredRepeat, AddressMode.ClampToEdge => SamplerAddressMode.ClampToEdge, - _ => LogInvalidAndReturn(mode, nameof(AddressMode), SamplerAddressMode.ClampToEdge) // TODO: Should be clamp. + _ => LogInvalidAndReturn(mode, nameof(AddressMode), SamplerAddressMode.ClampToEdge), // TODO: Should be clamp. }; } - public static Silk.NET.Vulkan.BlendFactor Convert(this GAL.BlendFactor factor) + public static BlendFactor Convert(this GAL.BlendFactor factor) { return factor switch { - GAL.BlendFactor.Zero or GAL.BlendFactor.ZeroGl => Silk.NET.Vulkan.BlendFactor.Zero, - GAL.BlendFactor.One or GAL.BlendFactor.OneGl => Silk.NET.Vulkan.BlendFactor.One, - GAL.BlendFactor.SrcColor or GAL.BlendFactor.SrcColorGl => Silk.NET.Vulkan.BlendFactor.SrcColor, - GAL.BlendFactor.OneMinusSrcColor or GAL.BlendFactor.OneMinusSrcColorGl => Silk.NET.Vulkan.BlendFactor.OneMinusSrcColor, - GAL.BlendFactor.SrcAlpha or GAL.BlendFactor.SrcAlphaGl => Silk.NET.Vulkan.BlendFactor.SrcAlpha, - GAL.BlendFactor.OneMinusSrcAlpha or GAL.BlendFactor.OneMinusSrcAlphaGl => Silk.NET.Vulkan.BlendFactor.OneMinusSrcAlpha, - GAL.BlendFactor.DstAlpha or GAL.BlendFactor.DstAlphaGl => Silk.NET.Vulkan.BlendFactor.DstAlpha, - GAL.BlendFactor.OneMinusDstAlpha or GAL.BlendFactor.OneMinusDstAlphaGl => Silk.NET.Vulkan.BlendFactor.OneMinusDstAlpha, - GAL.BlendFactor.DstColor or GAL.BlendFactor.DstColorGl => Silk.NET.Vulkan.BlendFactor.DstColor, - GAL.BlendFactor.OneMinusDstColor or GAL.BlendFactor.OneMinusDstColorGl => Silk.NET.Vulkan.BlendFactor.OneMinusDstColor, - GAL.BlendFactor.SrcAlphaSaturate or GAL.BlendFactor.SrcAlphaSaturateGl => Silk.NET.Vulkan.BlendFactor.SrcAlphaSaturate, - GAL.BlendFactor.Src1Color or GAL.BlendFactor.Src1ColorGl => Silk.NET.Vulkan.BlendFactor.Src1Color, - GAL.BlendFactor.OneMinusSrc1Color or GAL.BlendFactor.OneMinusSrc1ColorGl => Silk.NET.Vulkan.BlendFactor.OneMinusSrc1Color, - GAL.BlendFactor.Src1Alpha or GAL.BlendFactor.Src1AlphaGl => Silk.NET.Vulkan.BlendFactor.Src1Alpha, - GAL.BlendFactor.OneMinusSrc1Alpha or GAL.BlendFactor.OneMinusSrc1AlphaGl => Silk.NET.Vulkan.BlendFactor.OneMinusSrc1Alpha, - GAL.BlendFactor.ConstantColor => Silk.NET.Vulkan.BlendFactor.ConstantColor, - GAL.BlendFactor.OneMinusConstantColor => Silk.NET.Vulkan.BlendFactor.OneMinusConstantColor, - GAL.BlendFactor.ConstantAlpha => Silk.NET.Vulkan.BlendFactor.ConstantAlpha, - GAL.BlendFactor.OneMinusConstantAlpha => Silk.NET.Vulkan.BlendFactor.OneMinusConstantAlpha, - _ => LogInvalidAndReturn(factor, nameof(GAL.BlendFactor), Silk.NET.Vulkan.BlendFactor.Zero) + GAL.BlendFactor.Zero or GAL.BlendFactor.ZeroGl => BlendFactor.Zero, + GAL.BlendFactor.One or GAL.BlendFactor.OneGl => BlendFactor.One, + GAL.BlendFactor.SrcColor or GAL.BlendFactor.SrcColorGl => BlendFactor.SrcColor, + GAL.BlendFactor.OneMinusSrcColor or GAL.BlendFactor.OneMinusSrcColorGl => BlendFactor.OneMinusSrcColor, + GAL.BlendFactor.SrcAlpha or GAL.BlendFactor.SrcAlphaGl => BlendFactor.SrcAlpha, + GAL.BlendFactor.OneMinusSrcAlpha or GAL.BlendFactor.OneMinusSrcAlphaGl => BlendFactor.OneMinusSrcAlpha, + GAL.BlendFactor.DstAlpha or GAL.BlendFactor.DstAlphaGl => BlendFactor.DstAlpha, + GAL.BlendFactor.OneMinusDstAlpha or GAL.BlendFactor.OneMinusDstAlphaGl => BlendFactor.OneMinusDstAlpha, + GAL.BlendFactor.DstColor or GAL.BlendFactor.DstColorGl => BlendFactor.DstColor, + GAL.BlendFactor.OneMinusDstColor or GAL.BlendFactor.OneMinusDstColorGl => BlendFactor.OneMinusDstColor, + GAL.BlendFactor.SrcAlphaSaturate or GAL.BlendFactor.SrcAlphaSaturateGl => BlendFactor.SrcAlphaSaturate, + GAL.BlendFactor.Src1Color or GAL.BlendFactor.Src1ColorGl => BlendFactor.Src1Color, + GAL.BlendFactor.OneMinusSrc1Color or GAL.BlendFactor.OneMinusSrc1ColorGl => BlendFactor.OneMinusSrc1Color, + GAL.BlendFactor.Src1Alpha or GAL.BlendFactor.Src1AlphaGl => BlendFactor.Src1Alpha, + GAL.BlendFactor.OneMinusSrc1Alpha or GAL.BlendFactor.OneMinusSrc1AlphaGl => BlendFactor.OneMinusSrc1Alpha, + GAL.BlendFactor.ConstantColor => BlendFactor.ConstantColor, + GAL.BlendFactor.OneMinusConstantColor => BlendFactor.OneMinusConstantColor, + GAL.BlendFactor.ConstantAlpha => BlendFactor.ConstantAlpha, + GAL.BlendFactor.OneMinusConstantAlpha => BlendFactor.OneMinusConstantAlpha, + _ => LogInvalidAndReturn(factor, nameof(GAL.BlendFactor), BlendFactor.Zero), }; } - public static Silk.NET.Vulkan.BlendOp Convert(this GAL.AdvancedBlendOp op) + public static BlendOp Convert(this AdvancedBlendOp op) { return op switch { - GAL.AdvancedBlendOp.Zero => Silk.NET.Vulkan.BlendOp.ZeroExt, - GAL.AdvancedBlendOp.Src => Silk.NET.Vulkan.BlendOp.SrcExt, - GAL.AdvancedBlendOp.Dst => Silk.NET.Vulkan.BlendOp.DstExt, - GAL.AdvancedBlendOp.SrcOver => Silk.NET.Vulkan.BlendOp.SrcOverExt, - GAL.AdvancedBlendOp.DstOver => Silk.NET.Vulkan.BlendOp.DstOverExt, - GAL.AdvancedBlendOp.SrcIn => Silk.NET.Vulkan.BlendOp.SrcInExt, - GAL.AdvancedBlendOp.DstIn => Silk.NET.Vulkan.BlendOp.DstInExt, - GAL.AdvancedBlendOp.SrcOut => Silk.NET.Vulkan.BlendOp.SrcOutExt, - GAL.AdvancedBlendOp.DstOut => Silk.NET.Vulkan.BlendOp.DstOutExt, - GAL.AdvancedBlendOp.SrcAtop => Silk.NET.Vulkan.BlendOp.SrcAtopExt, - GAL.AdvancedBlendOp.DstAtop => Silk.NET.Vulkan.BlendOp.DstAtopExt, - GAL.AdvancedBlendOp.Xor => Silk.NET.Vulkan.BlendOp.XorExt, - GAL.AdvancedBlendOp.Plus => Silk.NET.Vulkan.BlendOp.PlusExt, - GAL.AdvancedBlendOp.PlusClamped => Silk.NET.Vulkan.BlendOp.PlusClampedExt, - GAL.AdvancedBlendOp.PlusClampedAlpha => Silk.NET.Vulkan.BlendOp.PlusClampedAlphaExt, - GAL.AdvancedBlendOp.PlusDarker => Silk.NET.Vulkan.BlendOp.PlusDarkerExt, - GAL.AdvancedBlendOp.Multiply => Silk.NET.Vulkan.BlendOp.MultiplyExt, - GAL.AdvancedBlendOp.Screen => Silk.NET.Vulkan.BlendOp.ScreenExt, - GAL.AdvancedBlendOp.Overlay => Silk.NET.Vulkan.BlendOp.OverlayExt, - GAL.AdvancedBlendOp.Darken => Silk.NET.Vulkan.BlendOp.DarkenExt, - GAL.AdvancedBlendOp.Lighten => Silk.NET.Vulkan.BlendOp.LightenExt, - GAL.AdvancedBlendOp.ColorDodge => Silk.NET.Vulkan.BlendOp.ColordodgeExt, - GAL.AdvancedBlendOp.ColorBurn => Silk.NET.Vulkan.BlendOp.ColorburnExt, - GAL.AdvancedBlendOp.HardLight => Silk.NET.Vulkan.BlendOp.HardlightExt, - GAL.AdvancedBlendOp.SoftLight => Silk.NET.Vulkan.BlendOp.SoftlightExt, - GAL.AdvancedBlendOp.Difference => Silk.NET.Vulkan.BlendOp.DifferenceExt, - GAL.AdvancedBlendOp.Minus => Silk.NET.Vulkan.BlendOp.MinusExt, - GAL.AdvancedBlendOp.MinusClamped => Silk.NET.Vulkan.BlendOp.MinusClampedExt, - GAL.AdvancedBlendOp.Exclusion => Silk.NET.Vulkan.BlendOp.ExclusionExt, - GAL.AdvancedBlendOp.Contrast => Silk.NET.Vulkan.BlendOp.ContrastExt, - GAL.AdvancedBlendOp.Invert => Silk.NET.Vulkan.BlendOp.InvertExt, - GAL.AdvancedBlendOp.InvertRGB => Silk.NET.Vulkan.BlendOp.InvertRgbExt, - GAL.AdvancedBlendOp.InvertOvg => Silk.NET.Vulkan.BlendOp.InvertOvgExt, - GAL.AdvancedBlendOp.LinearDodge => Silk.NET.Vulkan.BlendOp.LineardodgeExt, - GAL.AdvancedBlendOp.LinearBurn => Silk.NET.Vulkan.BlendOp.LinearburnExt, - GAL.AdvancedBlendOp.VividLight => Silk.NET.Vulkan.BlendOp.VividlightExt, - GAL.AdvancedBlendOp.LinearLight => Silk.NET.Vulkan.BlendOp.LinearlightExt, - GAL.AdvancedBlendOp.PinLight => Silk.NET.Vulkan.BlendOp.PinlightExt, - GAL.AdvancedBlendOp.HardMix => Silk.NET.Vulkan.BlendOp.HardmixExt, - GAL.AdvancedBlendOp.Red => Silk.NET.Vulkan.BlendOp.RedExt, - GAL.AdvancedBlendOp.Green => Silk.NET.Vulkan.BlendOp.GreenExt, - GAL.AdvancedBlendOp.Blue => Silk.NET.Vulkan.BlendOp.BlueExt, - GAL.AdvancedBlendOp.HslHue => Silk.NET.Vulkan.BlendOp.HslHueExt, - GAL.AdvancedBlendOp.HslSaturation => Silk.NET.Vulkan.BlendOp.HslSaturationExt, - GAL.AdvancedBlendOp.HslColor => Silk.NET.Vulkan.BlendOp.HslColorExt, - GAL.AdvancedBlendOp.HslLuminosity => Silk.NET.Vulkan.BlendOp.HslLuminosityExt, - _ => LogInvalidAndReturn(op, nameof(GAL.AdvancedBlendOp), Silk.NET.Vulkan.BlendOp.Add) + AdvancedBlendOp.Zero => BlendOp.ZeroExt, + AdvancedBlendOp.Src => BlendOp.SrcExt, + AdvancedBlendOp.Dst => BlendOp.DstExt, + AdvancedBlendOp.SrcOver => BlendOp.SrcOverExt, + AdvancedBlendOp.DstOver => BlendOp.DstOverExt, + AdvancedBlendOp.SrcIn => BlendOp.SrcInExt, + AdvancedBlendOp.DstIn => BlendOp.DstInExt, + AdvancedBlendOp.SrcOut => BlendOp.SrcOutExt, + AdvancedBlendOp.DstOut => BlendOp.DstOutExt, + AdvancedBlendOp.SrcAtop => BlendOp.SrcAtopExt, + AdvancedBlendOp.DstAtop => BlendOp.DstAtopExt, + AdvancedBlendOp.Xor => BlendOp.XorExt, + AdvancedBlendOp.Plus => BlendOp.PlusExt, + AdvancedBlendOp.PlusClamped => BlendOp.PlusClampedExt, + AdvancedBlendOp.PlusClampedAlpha => BlendOp.PlusClampedAlphaExt, + AdvancedBlendOp.PlusDarker => BlendOp.PlusDarkerExt, + AdvancedBlendOp.Multiply => BlendOp.MultiplyExt, + AdvancedBlendOp.Screen => BlendOp.ScreenExt, + AdvancedBlendOp.Overlay => BlendOp.OverlayExt, + AdvancedBlendOp.Darken => BlendOp.DarkenExt, + AdvancedBlendOp.Lighten => BlendOp.LightenExt, + AdvancedBlendOp.ColorDodge => BlendOp.ColordodgeExt, + AdvancedBlendOp.ColorBurn => BlendOp.ColorburnExt, + AdvancedBlendOp.HardLight => BlendOp.HardlightExt, + AdvancedBlendOp.SoftLight => BlendOp.SoftlightExt, + AdvancedBlendOp.Difference => BlendOp.DifferenceExt, + AdvancedBlendOp.Minus => BlendOp.MinusExt, + AdvancedBlendOp.MinusClamped => BlendOp.MinusClampedExt, + AdvancedBlendOp.Exclusion => BlendOp.ExclusionExt, + AdvancedBlendOp.Contrast => BlendOp.ContrastExt, + AdvancedBlendOp.Invert => BlendOp.InvertExt, + AdvancedBlendOp.InvertRGB => BlendOp.InvertRgbExt, + AdvancedBlendOp.InvertOvg => BlendOp.InvertOvgExt, + AdvancedBlendOp.LinearDodge => BlendOp.LineardodgeExt, + AdvancedBlendOp.LinearBurn => BlendOp.LinearburnExt, + AdvancedBlendOp.VividLight => BlendOp.VividlightExt, + AdvancedBlendOp.LinearLight => BlendOp.LinearlightExt, + AdvancedBlendOp.PinLight => BlendOp.PinlightExt, + AdvancedBlendOp.HardMix => BlendOp.HardmixExt, + AdvancedBlendOp.Red => BlendOp.RedExt, + AdvancedBlendOp.Green => BlendOp.GreenExt, + AdvancedBlendOp.Blue => BlendOp.BlueExt, + AdvancedBlendOp.HslHue => BlendOp.HslHueExt, + AdvancedBlendOp.HslSaturation => BlendOp.HslSaturationExt, + AdvancedBlendOp.HslColor => BlendOp.HslColorExt, + AdvancedBlendOp.HslLuminosity => BlendOp.HslLuminosityExt, + _ => LogInvalidAndReturn(op, nameof(AdvancedBlendOp), BlendOp.Add), }; } - public static Silk.NET.Vulkan.BlendOp Convert(this GAL.BlendOp op) + public static BlendOp Convert(this GAL.BlendOp op) { return op switch { - GAL.BlendOp.Add or GAL.BlendOp.AddGl => Silk.NET.Vulkan.BlendOp.Add, - GAL.BlendOp.Subtract or GAL.BlendOp.SubtractGl => Silk.NET.Vulkan.BlendOp.Subtract, - GAL.BlendOp.ReverseSubtract or GAL.BlendOp.ReverseSubtractGl => Silk.NET.Vulkan.BlendOp.ReverseSubtract, - GAL.BlendOp.Minimum or GAL.BlendOp.MinimumGl => Silk.NET.Vulkan.BlendOp.Min, - GAL.BlendOp.Maximum or GAL.BlendOp.MaximumGl => Silk.NET.Vulkan.BlendOp.Max, - _ => LogInvalidAndReturn(op, nameof(GAL.BlendOp), Silk.NET.Vulkan.BlendOp.Add) + GAL.BlendOp.Add or GAL.BlendOp.AddGl => BlendOp.Add, + GAL.BlendOp.Subtract or GAL.BlendOp.SubtractGl => BlendOp.Subtract, + GAL.BlendOp.ReverseSubtract or GAL.BlendOp.ReverseSubtractGl => BlendOp.ReverseSubtract, + GAL.BlendOp.Minimum or GAL.BlendOp.MinimumGl => BlendOp.Min, + GAL.BlendOp.Maximum or GAL.BlendOp.MaximumGl => BlendOp.Max, + _ => LogInvalidAndReturn(op, nameof(GAL.BlendOp), BlendOp.Add), }; } - public static Silk.NET.Vulkan.BlendOverlapEXT Convert(this GAL.AdvancedBlendOverlap overlap) + public static BlendOverlapEXT Convert(this AdvancedBlendOverlap overlap) { return overlap switch { - GAL.AdvancedBlendOverlap.Uncorrelated => Silk.NET.Vulkan.BlendOverlapEXT.UncorrelatedExt, - GAL.AdvancedBlendOverlap.Disjoint => Silk.NET.Vulkan.BlendOverlapEXT.DisjointExt, - GAL.AdvancedBlendOverlap.Conjoint => Silk.NET.Vulkan.BlendOverlapEXT.ConjointExt, - _ => LogInvalidAndReturn(overlap, nameof(GAL.AdvancedBlendOverlap), Silk.NET.Vulkan.BlendOverlapEXT.UncorrelatedExt) + AdvancedBlendOverlap.Uncorrelated => BlendOverlapEXT.UncorrelatedExt, + AdvancedBlendOverlap.Disjoint => BlendOverlapEXT.DisjointExt, + AdvancedBlendOverlap.Conjoint => BlendOverlapEXT.ConjointExt, + _ => LogInvalidAndReturn(overlap, nameof(AdvancedBlendOverlap), BlendOverlapEXT.UncorrelatedExt), }; } - public static Silk.NET.Vulkan.CompareOp Convert(this GAL.CompareOp op) + public static CompareOp Convert(this GAL.CompareOp op) { return op switch { - GAL.CompareOp.Never or GAL.CompareOp.NeverGl => Silk.NET.Vulkan.CompareOp.Never, - GAL.CompareOp.Less or GAL.CompareOp.LessGl => Silk.NET.Vulkan.CompareOp.Less, - GAL.CompareOp.Equal or GAL.CompareOp.EqualGl => Silk.NET.Vulkan.CompareOp.Equal, - GAL.CompareOp.LessOrEqual or GAL.CompareOp.LessOrEqualGl => Silk.NET.Vulkan.CompareOp.LessOrEqual, - GAL.CompareOp.Greater or GAL.CompareOp.GreaterGl => Silk.NET.Vulkan.CompareOp.Greater, - GAL.CompareOp.NotEqual or GAL.CompareOp.NotEqualGl => Silk.NET.Vulkan.CompareOp.NotEqual, - GAL.CompareOp.GreaterOrEqual or GAL.CompareOp.GreaterOrEqualGl => Silk.NET.Vulkan.CompareOp.GreaterOrEqual, - GAL.CompareOp.Always or GAL.CompareOp.AlwaysGl => Silk.NET.Vulkan.CompareOp.Always, - _ => LogInvalidAndReturn(op, nameof(GAL.CompareOp), Silk.NET.Vulkan.CompareOp.Never) + GAL.CompareOp.Never or GAL.CompareOp.NeverGl => CompareOp.Never, + GAL.CompareOp.Less or GAL.CompareOp.LessGl => CompareOp.Less, + GAL.CompareOp.Equal or GAL.CompareOp.EqualGl => CompareOp.Equal, + GAL.CompareOp.LessOrEqual or GAL.CompareOp.LessOrEqualGl => CompareOp.LessOrEqual, + GAL.CompareOp.Greater or GAL.CompareOp.GreaterGl => CompareOp.Greater, + GAL.CompareOp.NotEqual or GAL.CompareOp.NotEqualGl => CompareOp.NotEqual, + GAL.CompareOp.GreaterOrEqual or GAL.CompareOp.GreaterOrEqualGl => CompareOp.GreaterOrEqual, + GAL.CompareOp.Always or GAL.CompareOp.AlwaysGl => CompareOp.Always, + _ => LogInvalidAndReturn(op, nameof(GAL.CompareOp), CompareOp.Never), }; } @@ -230,29 +238,29 @@ namespace Ryujinx.Graphics.Vulkan Face.Back => CullModeFlags.BackBit, Face.Front => CullModeFlags.FrontBit, Face.FrontAndBack => CullModeFlags.FrontAndBack, - _ => LogInvalidAndReturn(face, nameof(Face), CullModeFlags.BackBit) + _ => LogInvalidAndReturn(face, nameof(Face), CullModeFlags.BackBit), }; } - public static Silk.NET.Vulkan.FrontFace Convert(this GAL.FrontFace frontFace) + public static FrontFace Convert(this GAL.FrontFace frontFace) { // Flipped to account for origin differences. return frontFace switch { - GAL.FrontFace.Clockwise => Silk.NET.Vulkan.FrontFace.CounterClockwise, - GAL.FrontFace.CounterClockwise => Silk.NET.Vulkan.FrontFace.Clockwise, - _ => LogInvalidAndReturn(frontFace, nameof(GAL.FrontFace), Silk.NET.Vulkan.FrontFace.Clockwise) + GAL.FrontFace.Clockwise => FrontFace.CounterClockwise, + GAL.FrontFace.CounterClockwise => FrontFace.Clockwise, + _ => LogInvalidAndReturn(frontFace, nameof(GAL.FrontFace), FrontFace.Clockwise), }; } - public static Silk.NET.Vulkan.IndexType Convert(this GAL.IndexType type) + public static IndexType Convert(this GAL.IndexType type) { return type switch { - GAL.IndexType.UByte => Silk.NET.Vulkan.IndexType.Uint8Ext, - GAL.IndexType.UShort => Silk.NET.Vulkan.IndexType.Uint16, - GAL.IndexType.UInt => Silk.NET.Vulkan.IndexType.Uint32, - _ => LogInvalidAndReturn(type, nameof(GAL.IndexType), Silk.NET.Vulkan.IndexType.Uint16) + GAL.IndexType.UByte => IndexType.Uint8Ext, + GAL.IndexType.UShort => IndexType.Uint16, + GAL.IndexType.UInt => IndexType.Uint32, + _ => LogInvalidAndReturn(type, nameof(GAL.IndexType), IndexType.Uint16), }; } @@ -262,7 +270,7 @@ namespace Ryujinx.Graphics.Vulkan { MagFilter.Nearest => Filter.Nearest, MagFilter.Linear => Filter.Linear, - _ => LogInvalidAndReturn(filter, nameof(MagFilter), Filter.Nearest) + _ => LogInvalidAndReturn(filter, nameof(MagFilter), Filter.Nearest), }; } @@ -276,45 +284,45 @@ namespace Ryujinx.Graphics.Vulkan MinFilter.LinearMipmapNearest => (Filter.Linear, SamplerMipmapMode.Nearest), MinFilter.NearestMipmapLinear => (Filter.Nearest, SamplerMipmapMode.Linear), MinFilter.LinearMipmapLinear => (Filter.Linear, SamplerMipmapMode.Linear), - _ => LogInvalidAndReturn(filter, nameof(MinFilter), (Filter.Nearest, SamplerMipmapMode.Nearest)) + _ => LogInvalidAndReturn(filter, nameof(MinFilter), (Filter.Nearest, SamplerMipmapMode.Nearest)), }; } - public static Silk.NET.Vulkan.PrimitiveTopology Convert(this GAL.PrimitiveTopology topology) + public static PrimitiveTopology Convert(this GAL.PrimitiveTopology topology) { return topology switch { - GAL.PrimitiveTopology.Points => Silk.NET.Vulkan.PrimitiveTopology.PointList, - GAL.PrimitiveTopology.Lines => Silk.NET.Vulkan.PrimitiveTopology.LineList, - GAL.PrimitiveTopology.LineStrip => Silk.NET.Vulkan.PrimitiveTopology.LineStrip, - GAL.PrimitiveTopology.Triangles => Silk.NET.Vulkan.PrimitiveTopology.TriangleList, - GAL.PrimitiveTopology.TriangleStrip => Silk.NET.Vulkan.PrimitiveTopology.TriangleStrip, - GAL.PrimitiveTopology.TriangleFan => Silk.NET.Vulkan.PrimitiveTopology.TriangleFan, - GAL.PrimitiveTopology.LinesAdjacency => Silk.NET.Vulkan.PrimitiveTopology.LineListWithAdjacency, - GAL.PrimitiveTopology.LineStripAdjacency => Silk.NET.Vulkan.PrimitiveTopology.LineStripWithAdjacency, - GAL.PrimitiveTopology.TrianglesAdjacency => Silk.NET.Vulkan.PrimitiveTopology.TriangleListWithAdjacency, - GAL.PrimitiveTopology.TriangleStripAdjacency => Silk.NET.Vulkan.PrimitiveTopology.TriangleStripWithAdjacency, - GAL.PrimitiveTopology.Patches => Silk.NET.Vulkan.PrimitiveTopology.PatchList, - GAL.PrimitiveTopology.Polygon => Silk.NET.Vulkan.PrimitiveTopology.TriangleFan, + GAL.PrimitiveTopology.Points => PrimitiveTopology.PointList, + GAL.PrimitiveTopology.Lines => PrimitiveTopology.LineList, + GAL.PrimitiveTopology.LineStrip => PrimitiveTopology.LineStrip, + GAL.PrimitiveTopology.Triangles => PrimitiveTopology.TriangleList, + GAL.PrimitiveTopology.TriangleStrip => PrimitiveTopology.TriangleStrip, + GAL.PrimitiveTopology.TriangleFan => PrimitiveTopology.TriangleFan, + GAL.PrimitiveTopology.LinesAdjacency => PrimitiveTopology.LineListWithAdjacency, + GAL.PrimitiveTopology.LineStripAdjacency => PrimitiveTopology.LineStripWithAdjacency, + GAL.PrimitiveTopology.TrianglesAdjacency => PrimitiveTopology.TriangleListWithAdjacency, + GAL.PrimitiveTopology.TriangleStripAdjacency => PrimitiveTopology.TriangleStripWithAdjacency, + GAL.PrimitiveTopology.Patches => PrimitiveTopology.PatchList, + GAL.PrimitiveTopology.Polygon => PrimitiveTopology.TriangleFan, GAL.PrimitiveTopology.Quads => throw new NotSupportedException("Quad topology is not available in Vulkan."), GAL.PrimitiveTopology.QuadStrip => throw new NotSupportedException("QuadStrip topology is not available in Vulkan."), - _ => LogInvalidAndReturn(topology, nameof(GAL.PrimitiveTopology), Silk.NET.Vulkan.PrimitiveTopology.TriangleList) + _ => LogInvalidAndReturn(topology, nameof(GAL.PrimitiveTopology), PrimitiveTopology.TriangleList), }; } - public static Silk.NET.Vulkan.StencilOp Convert(this GAL.StencilOp op) + public static StencilOp Convert(this GAL.StencilOp op) { return op switch { - GAL.StencilOp.Keep or GAL.StencilOp.KeepGl => Silk.NET.Vulkan.StencilOp.Keep, - GAL.StencilOp.Zero or GAL.StencilOp.ZeroGl => Silk.NET.Vulkan.StencilOp.Zero, - GAL.StencilOp.Replace or GAL.StencilOp.ReplaceGl => Silk.NET.Vulkan.StencilOp.Replace, - GAL.StencilOp.IncrementAndClamp or GAL.StencilOp.IncrementAndClampGl => Silk.NET.Vulkan.StencilOp.IncrementAndClamp, - GAL.StencilOp.DecrementAndClamp or GAL.StencilOp.DecrementAndClampGl => Silk.NET.Vulkan.StencilOp.DecrementAndClamp, - GAL.StencilOp.Invert or GAL.StencilOp.InvertGl => Silk.NET.Vulkan.StencilOp.Invert, - GAL.StencilOp.IncrementAndWrap or GAL.StencilOp.IncrementAndWrapGl => Silk.NET.Vulkan.StencilOp.IncrementAndWrap, - GAL.StencilOp.DecrementAndWrap or GAL.StencilOp.DecrementAndWrapGl => Silk.NET.Vulkan.StencilOp.DecrementAndWrap, - _ => LogInvalidAndReturn(op, nameof(GAL.StencilOp), Silk.NET.Vulkan.StencilOp.Keep) + GAL.StencilOp.Keep or GAL.StencilOp.KeepGl => StencilOp.Keep, + GAL.StencilOp.Zero or GAL.StencilOp.ZeroGl => StencilOp.Zero, + GAL.StencilOp.Replace or GAL.StencilOp.ReplaceGl => StencilOp.Replace, + GAL.StencilOp.IncrementAndClamp or GAL.StencilOp.IncrementAndClampGl => StencilOp.IncrementAndClamp, + GAL.StencilOp.DecrementAndClamp or GAL.StencilOp.DecrementAndClampGl => StencilOp.DecrementAndClamp, + GAL.StencilOp.Invert or GAL.StencilOp.InvertGl => StencilOp.Invert, + GAL.StencilOp.IncrementAndWrap or GAL.StencilOp.IncrementAndWrapGl => StencilOp.IncrementAndWrap, + GAL.StencilOp.DecrementAndWrap or GAL.StencilOp.DecrementAndWrapGl => StencilOp.DecrementAndWrap, + _ => LogInvalidAndReturn(op, nameof(GAL.StencilOp), StencilOp.Keep), }; } @@ -328,7 +336,7 @@ namespace Ryujinx.Graphics.Vulkan SwizzleComponent.Green => ComponentSwizzle.G, SwizzleComponent.Blue => ComponentSwizzle.B, SwizzleComponent.Alpha => ComponentSwizzle.A, - _ => LogInvalidAndReturn(swizzleComponent, nameof(SwizzleComponent), ComponentSwizzle.Zero) + _ => LogInvalidAndReturn(swizzleComponent, nameof(SwizzleComponent), ComponentSwizzle.Zero), }; } @@ -345,7 +353,7 @@ namespace Ryujinx.Graphics.Vulkan Target.Cubemap or Target.CubemapArray => ImageType.Type2D, Target.Texture3D => ImageType.Type3D, - _ => LogInvalidAndReturn(target, nameof(Target), ImageType.Type2D) + _ => LogInvalidAndReturn(target, nameof(Target), ImageType.Type2D), }; } @@ -360,33 +368,33 @@ namespace Ryujinx.Graphics.Vulkan Target.Texture2DArray => ImageViewType.Type2DArray, Target.Cubemap => ImageViewType.TypeCube, Target.CubemapArray => ImageViewType.TypeCubeArray, - _ => LogInvalidAndReturn(target, nameof(Target), ImageViewType.Type2D) + _ => LogInvalidAndReturn(target, nameof(Target), ImageViewType.Type2D), }; } - public static ImageAspectFlags ConvertAspectFlags(this GAL.Format format) + public static ImageAspectFlags ConvertAspectFlags(this Format format) { return format switch { - GAL.Format.D16Unorm or GAL.Format.D32Float => ImageAspectFlags.DepthBit, - GAL.Format.S8Uint => ImageAspectFlags.StencilBit, - GAL.Format.D24UnormS8Uint or - GAL.Format.D32FloatS8Uint or - GAL.Format.S8UintD24Unorm => ImageAspectFlags.DepthBit | ImageAspectFlags.StencilBit, - _ => ImageAspectFlags.ColorBit + Format.D16Unorm or Format.D32Float => ImageAspectFlags.DepthBit, + Format.S8Uint => ImageAspectFlags.StencilBit, + Format.D24UnormS8Uint or + Format.D32FloatS8Uint or + Format.S8UintD24Unorm => ImageAspectFlags.DepthBit | ImageAspectFlags.StencilBit, + _ => ImageAspectFlags.ColorBit, }; } - public static ImageAspectFlags ConvertAspectFlags(this GAL.Format format, DepthStencilMode depthStencilMode) + public static ImageAspectFlags ConvertAspectFlags(this Format format, DepthStencilMode depthStencilMode) { return format switch { - GAL.Format.D16Unorm or GAL.Format.D32Float => ImageAspectFlags.DepthBit, - GAL.Format.S8Uint => ImageAspectFlags.StencilBit, - GAL.Format.D24UnormS8Uint or - GAL.Format.D32FloatS8Uint or - GAL.Format.S8UintD24Unorm => depthStencilMode == DepthStencilMode.Stencil ? ImageAspectFlags.StencilBit : ImageAspectFlags.DepthBit, - _ => ImageAspectFlags.ColorBit + Format.D16Unorm or Format.D32Float => ImageAspectFlags.DepthBit, + Format.S8Uint => ImageAspectFlags.StencilBit, + Format.D24UnormS8Uint or + Format.D32FloatS8Uint or + Format.S8UintD24Unorm => depthStencilMode == DepthStencilMode.Stencil ? ImageAspectFlags.StencilBit : ImageAspectFlags.DepthBit, + _ => ImageAspectFlags.ColorBit, }; } @@ -410,7 +418,7 @@ namespace Ryujinx.Graphics.Vulkan LogicalOp.OrInverted => LogicOp.OrInverted, LogicalOp.Nand => LogicOp.Nand, LogicalOp.Set => LogicOp.Set, - _ => LogInvalidAndReturn(op, nameof(LogicalOp), LogicOp.Copy) + _ => LogInvalidAndReturn(op, nameof(LogicalOp), LogicOp.Copy), }; } @@ -419,7 +427,7 @@ namespace Ryujinx.Graphics.Vulkan return access switch { BufferAccess.FlushPersistent => BufferAllocationType.HostMapped, - _ => BufferAllocationType.Auto + _ => BufferAllocationType.Auto, }; } diff --git a/src/Ryujinx.Graphics.Vulkan/FenceHolder.cs b/src/Ryujinx.Graphics.Vulkan/FenceHolder.cs index 39d226983..d57d95ec1 100644 --- a/src/Ryujinx.Graphics.Vulkan/FenceHolder.cs +++ b/src/Ryujinx.Graphics.Vulkan/FenceHolder.cs @@ -17,9 +17,9 @@ namespace Ryujinx.Graphics.Vulkan _api = api; _device = device; - var fenceCreateInfo = new FenceCreateInfo() + var fenceCreateInfo = new FenceCreateInfo { - SType = StructureType.FenceCreateInfo + SType = StructureType.FenceCreateInfo, }; api.CreateFence(device, in fenceCreateInfo, null, out _fence).ThrowOnError(); @@ -70,7 +70,7 @@ namespace Ryujinx.Graphics.Vulkan { Span fences = stackalloc Fence[] { - _fence + _fence, }; FenceHelper.WaitAllIndefinitely(_api, _device, fences); @@ -80,7 +80,7 @@ namespace Ryujinx.Graphics.Vulkan { Span fences = stackalloc Fence[] { - _fence + _fence, }; return FenceHelper.AllSignaled(_api, _device, fences); diff --git a/src/Ryujinx.Graphics.Vulkan/FormatCapabilities.cs b/src/Ryujinx.Graphics.Vulkan/FormatCapabilities.cs index a2ebc518e..5f7deeb62 100644 --- a/src/Ryujinx.Graphics.Vulkan/FormatCapabilities.cs +++ b/src/Ryujinx.Graphics.Vulkan/FormatCapabilities.cs @@ -2,6 +2,7 @@ using Ryujinx.Common.Logging; using Ryujinx.Graphics.GAL; using Silk.NET.Vulkan; using System; +using Format = Ryujinx.Graphics.GAL.Format; using VkFormat = Silk.NET.Vulkan.Format; namespace Ryujinx.Graphics.Vulkan @@ -19,15 +20,15 @@ namespace Ryujinx.Graphics.Vulkan _api = api; _physicalDevice = physicalDevice; - int totalFormats = Enum.GetNames(typeof(GAL.Format)).Length; + int totalFormats = Enum.GetNames(typeof(Format)).Length; _bufferTable = new FormatFeatureFlags[totalFormats]; _optimalTable = new FormatFeatureFlags[totalFormats]; } - public bool BufferFormatsSupport(FormatFeatureFlags flags, params GAL.Format[] formats) + public bool BufferFormatsSupport(FormatFeatureFlags flags, params Format[] formats) { - foreach (GAL.Format format in formats) + foreach (Format format in formats) { if (!BufferFormatSupports(flags, format)) { @@ -38,9 +39,9 @@ namespace Ryujinx.Graphics.Vulkan return true; } - public bool OptimalFormatsSupport(FormatFeatureFlags flags, params GAL.Format[] formats) + public bool OptimalFormatsSupport(FormatFeatureFlags flags, params Format[] formats) { - foreach (GAL.Format format in formats) + foreach (Format format in formats) { if (!OptimalFormatSupports(flags, format)) { @@ -51,7 +52,7 @@ namespace Ryujinx.Graphics.Vulkan return true; } - public bool BufferFormatSupports(FormatFeatureFlags flags, GAL.Format format) + public bool BufferFormatSupports(FormatFeatureFlags flags, Format format) { var formatFeatureFlags = _bufferTable[(int)format]; @@ -72,7 +73,7 @@ namespace Ryujinx.Graphics.Vulkan return (fp.BufferFeatures & flags) == flags; } - public bool OptimalFormatSupports(FormatFeatureFlags flags, GAL.Format format) + public bool OptimalFormatSupports(FormatFeatureFlags flags, Format format) { var formatFeatureFlags = _optimalTable[(int)format]; @@ -86,7 +87,7 @@ namespace Ryujinx.Graphics.Vulkan return (formatFeatureFlags & flags) == flags; } - public VkFormat ConvertToVkFormat(GAL.Format srcFormat) + public VkFormat ConvertToVkFormat(Format srcFormat) { var format = FormatTable.GetFormat(srcFormat); @@ -115,7 +116,7 @@ namespace Ryujinx.Graphics.Vulkan { format = VkFormat.D32SfloatS8Uint; } - else if (srcFormat == GAL.Format.R4G4B4A4Unorm) + else if (srcFormat == Format.R4G4B4A4Unorm) { format = VkFormat.R4G4B4A4UnormPack16; } @@ -128,7 +129,7 @@ namespace Ryujinx.Graphics.Vulkan return format; } - public VkFormat ConvertToVertexVkFormat(GAL.Format srcFormat) + public VkFormat ConvertToVertexVkFormat(Format srcFormat) { var format = FormatTable.GetFormat(srcFormat); @@ -138,13 +139,13 @@ namespace Ryujinx.Graphics.Vulkan // The format is not supported. Can we convert it to an alternative format? switch (srcFormat) { - case GAL.Format.R16G16B16Float: + case Format.R16G16B16Float: format = VkFormat.R16G16B16A16Sfloat; break; - case GAL.Format.R16G16B16Sint: + case Format.R16G16B16Sint: format = VkFormat.R16G16B16A16Sint; break; - case GAL.Format.R16G16B16Uint: + case Format.R16G16B16Uint: format = VkFormat.R16G16B16A16Uint; break; default: @@ -156,16 +157,16 @@ namespace Ryujinx.Graphics.Vulkan return format; } - public static bool IsD24S8(GAL.Format format) + public static bool IsD24S8(Format format) { - return format == GAL.Format.D24UnormS8Uint || format == GAL.Format.S8UintD24Unorm; + return format == Format.D24UnormS8Uint || format == Format.S8UintD24Unorm; } - private static bool IsRGB16IntFloat(GAL.Format format) + private static bool IsRGB16IntFloat(Format format) { - return format == GAL.Format.R16G16B16Float || - format == GAL.Format.R16G16B16Sint || - format == GAL.Format.R16G16B16Uint; + return format == Format.R16G16B16Float || + format == Format.R16G16B16Sint || + format == Format.R16G16B16Uint; } } } diff --git a/src/Ryujinx.Graphics.Vulkan/FormatTable.cs b/src/Ryujinx.Graphics.Vulkan/FormatTable.cs index 3d70f6f26..eacfa0dbf 100644 --- a/src/Ryujinx.Graphics.Vulkan/FormatTable.cs +++ b/src/Ryujinx.Graphics.Vulkan/FormatTable.cs @@ -12,6 +12,7 @@ namespace Ryujinx.Graphics.Vulkan { _table = new VkFormat[Enum.GetNames(typeof(Format)).Length]; +#pragma warning disable IDE0055 // Disable formatting Add(Format.R8Unorm, VkFormat.R8Unorm); Add(Format.R8Snorm, VkFormat.R8SNorm); Add(Format.R8Uint, VkFormat.R8Uint); @@ -157,6 +158,7 @@ namespace Ryujinx.Graphics.Vulkan Add(Format.A1B5G5R5Unorm, VkFormat.R5G5B5A1UnormPack16); Add(Format.B8G8R8A8Unorm, VkFormat.B8G8R8A8Unorm); Add(Format.B8G8R8A8Srgb, VkFormat.B8G8R8A8Srgb); +#pragma warning restore IDE0055 } private static void Add(Format format, VkFormat vkFormat) @@ -175,7 +177,7 @@ namespace Ryujinx.Graphics.Vulkan { Format.R8G8B8A8Srgb => Format.R8G8B8A8Unorm, Format.B8G8R8A8Srgb => Format.B8G8R8A8Unorm, - _ => format + _ => format, }; } @@ -280,121 +282,61 @@ namespace Ryujinx.Graphics.Vulkan public static VkFormat DropLastComponent(VkFormat format) { - switch (format) + return format switch { - case VkFormat.R8G8Unorm: - return VkFormat.R8Unorm; - case VkFormat.R8G8SNorm: - return VkFormat.R8SNorm; - case VkFormat.R8G8Uint: - return VkFormat.R8Uint; - case VkFormat.R8G8Sint: - return VkFormat.R8Sint; - case VkFormat.R8G8Uscaled: - return VkFormat.R8Uscaled; - case VkFormat.R8G8Sscaled: - return VkFormat.R8Sscaled; - - case VkFormat.R8G8B8Unorm: - return VkFormat.R8G8Unorm; - case VkFormat.R8G8B8SNorm: - return VkFormat.R8G8SNorm; - case VkFormat.R8G8B8Uint: - return VkFormat.R8G8Uint; - case VkFormat.R8G8B8Sint: - return VkFormat.R8G8Sint; - case VkFormat.R8G8B8Uscaled: - return VkFormat.R8G8Uscaled; - case VkFormat.R8G8B8Sscaled: - return VkFormat.R8G8Sscaled; - - case VkFormat.R8G8B8A8Unorm: - return VkFormat.R8G8B8Unorm; - case VkFormat.R8G8B8A8SNorm: - return VkFormat.R8G8B8SNorm; - case VkFormat.R8G8B8A8Uint: - return VkFormat.R8G8B8Uint; - case VkFormat.R8G8B8A8Sint: - return VkFormat.R8G8B8Sint; - case VkFormat.R8G8B8A8Srgb: - return VkFormat.R8G8B8Srgb; - case VkFormat.R8G8B8A8Uscaled: - return VkFormat.R8G8B8Uscaled; - case VkFormat.R8G8B8A8Sscaled: - return VkFormat.R8G8B8Sscaled; - case VkFormat.B8G8R8A8Unorm: - return VkFormat.B8G8R8Unorm; - case VkFormat.B8G8R8A8Srgb: - return VkFormat.B8G8R8Srgb; - - case VkFormat.R16G16Sfloat: - return VkFormat.R16Sfloat; - case VkFormat.R16G16Unorm: - return VkFormat.R16Unorm; - case VkFormat.R16G16SNorm: - return VkFormat.R16SNorm; - case VkFormat.R16G16Uint: - return VkFormat.R16Uint; - case VkFormat.R16G16Sint: - return VkFormat.R16Sint; - case VkFormat.R16G16Uscaled: - return VkFormat.R16Uscaled; - case VkFormat.R16G16Sscaled: - return VkFormat.R16Sscaled; - - case VkFormat.R16G16B16Sfloat: - return VkFormat.R16G16Sfloat; - case VkFormat.R16G16B16Unorm: - return VkFormat.R16G16Unorm; - case VkFormat.R16G16B16SNorm: - return VkFormat.R16G16SNorm; - case VkFormat.R16G16B16Uint: - return VkFormat.R16G16Uint; - case VkFormat.R16G16B16Sint: - return VkFormat.R16G16Sint; - case VkFormat.R16G16B16Uscaled: - return VkFormat.R16G16Uscaled; - case VkFormat.R16G16B16Sscaled: - return VkFormat.R16G16Sscaled; - - case VkFormat.R16G16B16A16Sfloat: - return VkFormat.R16G16B16Sfloat; - case VkFormat.R16G16B16A16Unorm: - return VkFormat.R16G16B16Unorm; - case VkFormat.R16G16B16A16SNorm: - return VkFormat.R16G16B16SNorm; - case VkFormat.R16G16B16A16Uint: - return VkFormat.R16G16B16Uint; - case VkFormat.R16G16B16A16Sint: - return VkFormat.R16G16B16Sint; - case VkFormat.R16G16B16A16Uscaled: - return VkFormat.R16G16B16Uscaled; - case VkFormat.R16G16B16A16Sscaled: - return VkFormat.R16G16B16Sscaled; - - case VkFormat.R32G32Sfloat: - return VkFormat.R32Sfloat; - case VkFormat.R32G32Uint: - return VkFormat.R32Uint; - case VkFormat.R32G32Sint: - return VkFormat.R32Sint; - - case VkFormat.R32G32B32Sfloat: - return VkFormat.R32G32Sfloat; - case VkFormat.R32G32B32Uint: - return VkFormat.R32G32Uint; - case VkFormat.R32G32B32Sint: - return VkFormat.R32G32Sint; - - case VkFormat.R32G32B32A32Sfloat: - return VkFormat.R32G32B32Sfloat; - case VkFormat.R32G32B32A32Uint: - return VkFormat.R32G32B32Uint; - case VkFormat.R32G32B32A32Sint: - return VkFormat.R32G32B32Sint; - } - - return format; + VkFormat.R8G8Unorm => VkFormat.R8Unorm, + VkFormat.R8G8SNorm => VkFormat.R8SNorm, + VkFormat.R8G8Uint => VkFormat.R8Uint, + VkFormat.R8G8Sint => VkFormat.R8Sint, + VkFormat.R8G8Uscaled => VkFormat.R8Uscaled, + VkFormat.R8G8Sscaled => VkFormat.R8Sscaled, + VkFormat.R8G8B8Unorm => VkFormat.R8G8Unorm, + VkFormat.R8G8B8SNorm => VkFormat.R8G8SNorm, + VkFormat.R8G8B8Uint => VkFormat.R8G8Uint, + VkFormat.R8G8B8Sint => VkFormat.R8G8Sint, + VkFormat.R8G8B8Uscaled => VkFormat.R8G8Uscaled, + VkFormat.R8G8B8Sscaled => VkFormat.R8G8Sscaled, + VkFormat.R8G8B8A8Unorm => VkFormat.R8G8B8Unorm, + VkFormat.R8G8B8A8SNorm => VkFormat.R8G8B8SNorm, + VkFormat.R8G8B8A8Uint => VkFormat.R8G8B8Uint, + VkFormat.R8G8B8A8Sint => VkFormat.R8G8B8Sint, + VkFormat.R8G8B8A8Srgb => VkFormat.R8G8B8Srgb, + VkFormat.R8G8B8A8Uscaled => VkFormat.R8G8B8Uscaled, + VkFormat.R8G8B8A8Sscaled => VkFormat.R8G8B8Sscaled, + VkFormat.B8G8R8A8Unorm => VkFormat.B8G8R8Unorm, + VkFormat.B8G8R8A8Srgb => VkFormat.B8G8R8Srgb, + VkFormat.R16G16Sfloat => VkFormat.R16Sfloat, + VkFormat.R16G16Unorm => VkFormat.R16Unorm, + VkFormat.R16G16SNorm => VkFormat.R16SNorm, + VkFormat.R16G16Uint => VkFormat.R16Uint, + VkFormat.R16G16Sint => VkFormat.R16Sint, + VkFormat.R16G16Uscaled => VkFormat.R16Uscaled, + VkFormat.R16G16Sscaled => VkFormat.R16Sscaled, + VkFormat.R16G16B16Sfloat => VkFormat.R16G16Sfloat, + VkFormat.R16G16B16Unorm => VkFormat.R16G16Unorm, + VkFormat.R16G16B16SNorm => VkFormat.R16G16SNorm, + VkFormat.R16G16B16Uint => VkFormat.R16G16Uint, + VkFormat.R16G16B16Sint => VkFormat.R16G16Sint, + VkFormat.R16G16B16Uscaled => VkFormat.R16G16Uscaled, + VkFormat.R16G16B16Sscaled => VkFormat.R16G16Sscaled, + VkFormat.R16G16B16A16Sfloat => VkFormat.R16G16B16Sfloat, + VkFormat.R16G16B16A16Unorm => VkFormat.R16G16B16Unorm, + VkFormat.R16G16B16A16SNorm => VkFormat.R16G16B16SNorm, + VkFormat.R16G16B16A16Uint => VkFormat.R16G16B16Uint, + VkFormat.R16G16B16A16Sint => VkFormat.R16G16B16Sint, + VkFormat.R16G16B16A16Uscaled => VkFormat.R16G16B16Uscaled, + VkFormat.R16G16B16A16Sscaled => VkFormat.R16G16B16Sscaled, + VkFormat.R32G32Sfloat => VkFormat.R32Sfloat, + VkFormat.R32G32Uint => VkFormat.R32Uint, + VkFormat.R32G32Sint => VkFormat.R32Sint, + VkFormat.R32G32B32Sfloat => VkFormat.R32G32Sfloat, + VkFormat.R32G32B32Uint => VkFormat.R32G32Uint, + VkFormat.R32G32B32Sint => VkFormat.R32G32Sint, + VkFormat.R32G32B32A32Sfloat => VkFormat.R32G32B32Sfloat, + VkFormat.R32G32B32A32Uint => VkFormat.R32G32B32Uint, + VkFormat.R32G32B32A32Sint => VkFormat.R32G32B32Sint, + _ => format, + }; } } } diff --git a/src/Ryujinx.Graphics.Vulkan/FramebufferParams.cs b/src/Ryujinx.Graphics.Vulkan/FramebufferParams.cs index 0437a402c..7b40e96b2 100644 --- a/src/Ryujinx.Graphics.Vulkan/FramebufferParams.cs +++ b/src/Ryujinx.Graphics.Vulkan/FramebufferParams.cs @@ -12,7 +12,7 @@ namespace Ryujinx.Graphics.Vulkan private readonly Auto[] _attachments; private readonly TextureView[] _colors; private readonly TextureView _depthStencil; - private uint _validColorAttachments; + private readonly uint _validColorAttachments; public uint Width { get; } public uint Height { get; } @@ -24,7 +24,7 @@ namespace Ryujinx.Graphics.Vulkan public uint AttachmentIntegerFormatMask { get; } public int AttachmentsCount { get; } - public int MaxColorAttachmentIndex => AttachmentIndices.Length > 0 ? AttachmentIndices[AttachmentIndices.Length - 1] : -1; + public int MaxColorAttachmentIndex => AttachmentIndices.Length > 0 ? AttachmentIndices[^1] : -1; public bool HasDepthStencil { get; } public int ColorAttachmentsCount => AttachmentsCount - (HasDepthStencil ? 1 : 0); @@ -158,7 +158,8 @@ namespace Ryujinx.Graphics.Vulkan { return ComponentType.SignedInteger; } - else if (format.IsUint()) + + if (format.IsUint()) { return ComponentType.UnsignedInteger; } @@ -196,7 +197,7 @@ namespace Ryujinx.Graphics.Vulkan attachments[i] = _attachments[i].Get(cbs).Value; } - var framebufferCreateInfo = new FramebufferCreateInfo() + var framebufferCreateInfo = new FramebufferCreateInfo { SType = StructureType.FramebufferCreateInfo, RenderPass = renderPass.Get(cbs).Value, @@ -204,7 +205,7 @@ namespace Ryujinx.Graphics.Vulkan PAttachments = attachments, Width = Width, Height = Height, - Layers = Layers + Layers = Layers, }; api.CreateFramebuffer(_device, framebufferCreateInfo, null, out var framebuffer).ThrowOnError(); diff --git a/src/Ryujinx.Graphics.Vulkan/HardwareCapabilities.cs b/src/Ryujinx.Graphics.Vulkan/HardwareCapabilities.cs index 393bcf1a2..11d9c4fb4 100644 --- a/src/Ryujinx.Graphics.Vulkan/HardwareCapabilities.cs +++ b/src/Ryujinx.Graphics.Vulkan/HardwareCapabilities.cs @@ -11,7 +11,7 @@ namespace Ryujinx.Graphics.Vulkan NoTriangleFans = 1, NoPointMode = 1 << 1, No3DImageView = 1 << 2, - NoLodBias = 1 << 3 + NoLodBias = 1 << 3, } readonly struct HardwareCapabilities diff --git a/src/Ryujinx.Graphics.Vulkan/HashTableSlim.cs b/src/Ryujinx.Graphics.Vulkan/HashTableSlim.cs index e4ad39587..2efe81a60 100644 --- a/src/Ryujinx.Graphics.Vulkan/HashTableSlim.cs +++ b/src/Ryujinx.Graphics.Vulkan/HashTableSlim.cs @@ -8,7 +8,7 @@ namespace Ryujinx.Graphics.Vulkan bool Equals(ref T other); } - class HashTableSlim where K : IRefEquatable + class HashTableSlim where TKey : IRefEquatable { private const int TotalBuckets = 16; // Must be power of 2 private const int TotalBucketsMask = TotalBuckets - 1; @@ -16,13 +16,13 @@ namespace Ryujinx.Graphics.Vulkan private struct Entry { public int Hash; - public K Key; - public V Value; + public TKey Key; + public TValue Value; } private readonly Entry[][] _hashTable = new Entry[TotalBuckets][]; - public IEnumerable Keys + public IEnumerable Keys { get { @@ -39,7 +39,7 @@ namespace Ryujinx.Graphics.Vulkan } } - public IEnumerable Values + public IEnumerable Values { get { @@ -56,13 +56,13 @@ namespace Ryujinx.Graphics.Vulkan } } - public void Add(ref K key, V value) + public void Add(ref TKey key, TValue value) { - var entry = new Entry() + var entry = new Entry { Hash = key.GetHashCode(), Key = key, - Value = value + Value = value, }; int hashCode = key.GetHashCode(); @@ -79,14 +79,14 @@ namespace Ryujinx.Graphics.Vulkan } else { - _hashTable[bucketIndex] = new Entry[] + _hashTable[bucketIndex] = new[] { - entry + entry, }; } } - public bool TryGetValue(ref K key, out V value) + public bool TryGetValue(ref TKey key, out TValue value) { int hashCode = key.GetHashCode(); diff --git a/src/Ryujinx.Graphics.Vulkan/HelperShader.cs b/src/Ryujinx.Graphics.Vulkan/HelperShader.cs index 43214be4d..648afcd6a 100644 --- a/src/Ryujinx.Graphics.Vulkan/HelperShader.cs +++ b/src/Ryujinx.Graphics.Vulkan/HelperShader.cs @@ -6,6 +6,12 @@ using Silk.NET.Vulkan; using System; using System.Collections.Generic; using System.Numerics; +using CompareOp = Ryujinx.Graphics.GAL.CompareOp; +using Format = Ryujinx.Graphics.GAL.Format; +using PrimitiveTopology = Ryujinx.Graphics.GAL.PrimitiveTopology; +using SamplerCreateInfo = Ryujinx.Graphics.GAL.SamplerCreateInfo; +using StencilOp = Ryujinx.Graphics.GAL.StencilOp; +using Viewport = Ryujinx.Graphics.GAL.Viewport; using VkFormat = Silk.NET.Vulkan.Format; namespace Ryujinx.Graphics.Vulkan @@ -14,7 +20,7 @@ namespace Ryujinx.Graphics.Vulkan { Float, SignedInteger, - UnsignedInteger + UnsignedInteger, } class HelperShader : IDisposable @@ -52,8 +58,8 @@ namespace Ryujinx.Graphics.Vulkan _pipeline = new PipelineHelperShader(gd, device); _pipeline.Initialize(); - _samplerLinear = gd.CreateSampler(GAL.SamplerCreateInfo.Create(MinFilter.Linear, MagFilter.Linear)); - _samplerNearest = gd.CreateSampler(GAL.SamplerCreateInfo.Create(MinFilter.Nearest, MagFilter.Nearest)); + _samplerLinear = gd.CreateSampler(SamplerCreateInfo.Create(MinFilter.Linear, MagFilter.Linear)); + _samplerNearest = gd.CreateSampler(SamplerCreateInfo.Create(MinFilter.Nearest, MagFilter.Nearest)); var blitResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Vertex, ResourceType.UniformBuffer, 1) @@ -416,7 +422,7 @@ namespace Ryujinx.Graphics.Vulkan _pipeline.SetUniformBuffers(stackalloc[] { new BufferAssignment(1, new BufferRange(bufferHandle, 0, RegionBufferSize)) }); - Span viewports = stackalloc GAL.Viewport[1]; + Span viewports = stackalloc Viewport[1]; var rect = new Rectangle( MathF.Min(dstRegion.X1, dstRegion.X2), @@ -424,7 +430,7 @@ namespace Ryujinx.Graphics.Vulkan MathF.Abs(dstRegion.X2 - dstRegion.X1), MathF.Abs(dstRegion.Y2 - dstRegion.Y1)); - viewports[0] = new GAL.Viewport( + viewports[0] = new Viewport( rect, ViewportSwizzle.PositiveX, ViewportSwizzle.PositiveY, @@ -440,7 +446,7 @@ namespace Ryujinx.Graphics.Vulkan if (dstIsDepthOrStencil) { _pipeline.SetProgram(src.Info.Target.IsMultisample() ? _programDepthBlitMs : _programDepthBlit); - _pipeline.SetDepthTest(new DepthTestDescriptor(true, true, GAL.CompareOp.Always)); + _pipeline.SetDepthTest(new DepthTestDescriptor(true, true, CompareOp.Always)); } else if (src.Info.Target.IsMultisample()) { @@ -465,12 +471,12 @@ namespace Ryujinx.Graphics.Vulkan } _pipeline.SetViewports(viewports, false); - _pipeline.SetPrimitiveTopology(GAL.PrimitiveTopology.TriangleStrip); + _pipeline.SetPrimitiveTopology(PrimitiveTopology.TriangleStrip); _pipeline.Draw(4, 1, 0, 0); if (dstIsDepthOrStencil) { - _pipeline.SetDepthTest(new DepthTestDescriptor(false, false, GAL.CompareOp.Always)); + _pipeline.SetDepthTest(new DepthTestDescriptor(false, false, CompareOp.Always)); } _pipeline.Finish(gd, cbs); @@ -517,7 +523,7 @@ namespace Ryujinx.Graphics.Vulkan _pipeline.SetUniformBuffers(stackalloc[] { new BufferAssignment(1, new BufferRange(bufferHandle, 0, RegionBufferSize)) }); - Span viewports = stackalloc GAL.Viewport[1]; + Span viewports = stackalloc Viewport[1]; var rect = new Rectangle( MathF.Min(dstRegion.X1, dstRegion.X2), @@ -525,7 +531,7 @@ namespace Ryujinx.Graphics.Vulkan MathF.Abs(dstRegion.X2 - dstRegion.X1), MathF.Abs(dstRegion.Y2 - dstRegion.Y1)); - viewports[0] = new GAL.Viewport( + viewports[0] = new Viewport( rect, ViewportSwizzle.PositiveX, ViewportSwizzle.PositiveY, @@ -541,7 +547,7 @@ namespace Ryujinx.Graphics.Vulkan _pipeline.SetRenderTarget(dst, (uint)dstWidth, (uint)dstHeight, (uint)dstSamples, true, dstFormat); _pipeline.SetScissors(scissors); _pipeline.SetViewports(viewports, false); - _pipeline.SetPrimitiveTopology(GAL.PrimitiveTopology.TriangleStrip); + _pipeline.SetPrimitiveTopology(PrimitiveTopology.TriangleStrip); var aspectFlags = src.Info.Format.ConvertAspectFlags(); @@ -606,7 +612,7 @@ namespace Ryujinx.Graphics.Vulkan if (isDepth) { _pipeline.SetProgram(src.Info.Target.IsMultisample() ? _programDepthBlitMs : _programDepthBlit); - _pipeline.SetDepthTest(new DepthTestDescriptor(true, true, GAL.CompareOp.Always)); + _pipeline.SetDepthTest(new DepthTestDescriptor(true, true, CompareOp.Always)); } else { @@ -618,7 +624,7 @@ namespace Ryujinx.Graphics.Vulkan if (isDepth) { - _pipeline.SetDepthTest(new DepthTestDescriptor(false, false, GAL.CompareOp.Always)); + _pipeline.SetDepthTest(new DepthTestDescriptor(false, false, CompareOp.Always)); } else { @@ -630,17 +636,17 @@ namespace Ryujinx.Graphics.Vulkan { return new StencilTestDescriptor( enabled, - GAL.CompareOp.Always, - GAL.StencilOp.Replace, - GAL.StencilOp.Replace, - GAL.StencilOp.Replace, + CompareOp.Always, + StencilOp.Replace, + StencilOp.Replace, + StencilOp.Replace, 0, 0xff, 0xff, - GAL.CompareOp.Always, - GAL.StencilOp.Replace, - GAL.StencilOp.Replace, - GAL.StencilOp.Replace, + CompareOp.Always, + StencilOp.Replace, + StencilOp.Replace, + StencilOp.Replace, 0, 0xff, 0xff); @@ -667,13 +673,13 @@ namespace Ryujinx.Graphics.Vulkan var bufferHandle = gd.BufferManager.CreateWithHandle(gd, ClearColorBufferSize); - gd.BufferManager.SetData(bufferHandle, 0, clearColor); + gd.BufferManager.SetData(bufferHandle, 0, clearColor); _pipeline.SetUniformBuffers(stackalloc[] { new BufferAssignment(1, new BufferRange(bufferHandle, 0, ClearColorBufferSize)) }); - Span viewports = stackalloc GAL.Viewport[1]; + Span viewports = stackalloc Viewport[1]; - viewports[0] = new GAL.Viewport( + viewports[0] = new Viewport( new Rectangle(0, 0, dstWidth, dstHeight), ViewportSwizzle.PositiveX, ViewportSwizzle.PositiveY, @@ -703,10 +709,10 @@ namespace Ryujinx.Graphics.Vulkan _pipeline.SetProgram(program); _pipeline.SetRenderTarget(dst, (uint)dstWidth, (uint)dstHeight, false, dstFormat); - _pipeline.SetRenderTargetColorMasks(new uint[] { componentMask }); + _pipeline.SetRenderTargetColorMasks(new[] { componentMask }); _pipeline.SetViewports(viewports, false); _pipeline.SetScissors(scissors); - _pipeline.SetPrimitiveTopology(GAL.PrimitiveTopology.TriangleStrip); + _pipeline.SetPrimitiveTopology(PrimitiveTopology.TriangleStrip); _pipeline.Draw(4, 1, 0, 0); _pipeline.Finish(); @@ -748,7 +754,7 @@ namespace Ryujinx.Graphics.Vulkan pipeline.SetUniformBuffers(stackalloc[] { new BufferAssignment(1, new BufferRange(bufferHandle, 0, RegionBufferSize)) }); - Span viewports = stackalloc GAL.Viewport[1]; + Span viewports = stackalloc Viewport[1]; var rect = new Rectangle( MathF.Min(dstRegion.X1, dstRegion.X2), @@ -756,7 +762,7 @@ namespace Ryujinx.Graphics.Vulkan MathF.Abs(dstRegion.X2 - dstRegion.X1), MathF.Abs(dstRegion.Y2 - dstRegion.Y1)); - viewports[0] = new GAL.Viewport( + viewports[0] = new Viewport( rect, ViewportSwizzle.PositiveX, ViewportSwizzle.PositiveY, @@ -769,13 +775,13 @@ namespace Ryujinx.Graphics.Vulkan pipeline.SetProgram(_programColorBlit); pipeline.SetViewports(viewports, false); - pipeline.SetPrimitiveTopology(GAL.PrimitiveTopology.TriangleStrip); + pipeline.SetPrimitiveTopology(PrimitiveTopology.TriangleStrip); pipeline.Draw(4, 1, 0, 0); gd.BufferManager.Delete(bufferHandle); } - public unsafe void ConvertI8ToI16(VulkanRenderer gd, CommandBufferScoped cbs, BufferHolder src, BufferHolder dst, int srcOffset, int size) + public void ConvertI8ToI16(VulkanRenderer gd, CommandBufferScoped cbs, BufferHolder src, BufferHolder dst, int srcOffset, int size) { ChangeStride(gd, cbs, src, dst, srcOffset, size, 1, 2); } @@ -1093,11 +1099,11 @@ namespace Ryujinx.Graphics.Vulkan { // We can't use compute for this case because compute can't modify depth textures. - Span viewports = stackalloc GAL.Viewport[1]; + Span viewports = stackalloc Viewport[1]; var rect = new Rectangle(0, 0, dst.Width, dst.Height); - viewports[0] = new GAL.Viewport( + viewports[0] = new Viewport( rect, ViewportSwizzle.PositiveX, ViewportSwizzle.PositiveY, @@ -1112,7 +1118,7 @@ namespace Ryujinx.Graphics.Vulkan _pipeline.SetScissors(scissors); _pipeline.SetViewports(viewports, false); - _pipeline.SetPrimitiveTopology(GAL.PrimitiveTopology.TriangleStrip); + _pipeline.SetPrimitiveTopology(PrimitiveTopology.TriangleStrip); for (int z = 0; z < depth; z++) { @@ -1120,7 +1126,7 @@ namespace Ryujinx.Graphics.Vulkan var dstView = Create2DLayerView(dst, dstLayer + z, 0); _pipeline.SetRenderTarget( - ((TextureView)dstView).GetImageViewForAttachment(), + dstView.GetImageViewForAttachment(), (uint)dst.Width, (uint)dst.Height, true, @@ -1225,11 +1231,11 @@ namespace Ryujinx.Graphics.Vulkan _pipeline.SetCommandBuffer(cbs); - Span viewports = stackalloc GAL.Viewport[1]; + Span viewports = stackalloc Viewport[1]; var rect = new Rectangle(0, 0, dst.Width, dst.Height); - viewports[0] = new GAL.Viewport( + viewports[0] = new Viewport( rect, ViewportSwizzle.PositiveX, ViewportSwizzle.PositiveY, @@ -1245,7 +1251,7 @@ namespace Ryujinx.Graphics.Vulkan _pipeline.SetRenderTargetColorMasks(new uint[] { 0xf }); _pipeline.SetScissors(scissors); _pipeline.SetViewports(viewports, false); - _pipeline.SetPrimitiveTopology(GAL.PrimitiveTopology.TriangleStrip); + _pipeline.SetPrimitiveTopology(PrimitiveTopology.TriangleStrip); _pipeline.SetUniformBuffers(stackalloc[] { new BufferAssignment(0, new BufferRange(bufferHandle, 0, ParamsBufferSize)) }); @@ -1257,7 +1263,7 @@ namespace Ryujinx.Graphics.Vulkan var dstView = Create2DLayerView(dst, dstLayer + z, 0); _pipeline.SetRenderTarget( - ((TextureView)dstView).GetImageViewForAttachment(), + dstView.GetImageViewForAttachment(), (uint)dst.Width, (uint)dst.Height, (uint)samples, @@ -1291,7 +1297,7 @@ namespace Ryujinx.Graphics.Vulkan _pipeline.SetTextureAndSamplerIdentitySwizzle(ShaderStage.Fragment, 0, srcView, null); _pipeline.SetRenderTarget( - ((TextureView)dstView).GetView(format).GetImageViewForAttachment(), + dstView.GetView(format).GetImageViewForAttachment(), (uint)dst.Width, (uint)dst.Height, (uint)samples, @@ -1365,7 +1371,7 @@ namespace Ryujinx.Graphics.Vulkan if (isDepth) { _pipeline.SetProgram(fromMS ? _programDepthDrawToNonMs : _programDepthDrawToMs); - _pipeline.SetDepthTest(new DepthTestDescriptor(true, true, GAL.CompareOp.Always)); + _pipeline.SetDepthTest(new DepthTestDescriptor(true, true, CompareOp.Always)); } else { @@ -1377,7 +1383,7 @@ namespace Ryujinx.Graphics.Vulkan if (isDepth) { - _pipeline.SetDepthTest(new DepthTestDescriptor(false, false, GAL.CompareOp.Always)); + _pipeline.SetDepthTest(new DepthTestDescriptor(false, false, CompareOp.Always)); } else { @@ -1420,7 +1426,7 @@ namespace Ryujinx.Graphics.Vulkan return (samplesInXLog2, samplesInYLog2); } - private static TextureView Create2DLayerView(TextureView from, int layer, int level, GAL.Format? format = null) + private static TextureView Create2DLayerView(TextureView from, int layer, int level, Format? format = null) { if (from.Info.Target == Target.Texture2D && level == 0 && (format == null || format.Value == from.Info.Format)) { @@ -1431,7 +1437,7 @@ namespace Ryujinx.Graphics.Vulkan { Target.Texture1DArray => Target.Texture1D, Target.Texture2DMultisampleArray => Target.Texture2DMultisample, - _ => Target.Texture2D + _ => Target.Texture2D, }; var info = new TextureCreateInfo( @@ -1454,55 +1460,55 @@ namespace Ryujinx.Graphics.Vulkan return from.CreateViewImpl(info, layer, level); } - private static GAL.Format GetFormat(int bytesPerPixel) + private static Format GetFormat(int bytesPerPixel) { return bytesPerPixel switch { - 1 => GAL.Format.R8Uint, - 2 => GAL.Format.R16Uint, - 4 => GAL.Format.R32Uint, - 8 => GAL.Format.R32G32Uint, - 16 => GAL.Format.R32G32B32A32Uint, - _ => throw new ArgumentException($"Invalid bytes per pixel {bytesPerPixel}.") + 1 => Format.R8Uint, + 2 => Format.R16Uint, + 4 => Format.R32Uint, + 8 => Format.R32G32Uint, + 16 => Format.R32G32B32A32Uint, + _ => throw new ArgumentException($"Invalid bytes per pixel {bytesPerPixel}."), }; } - private static GAL.Format GetFormat(int componentSize, int componentsCount) + private static Format GetFormat(int componentSize, int componentsCount) { if (componentSize == 1) { return componentsCount switch { - 1 => GAL.Format.R8Uint, - 2 => GAL.Format.R8G8Uint, - 4 => GAL.Format.R8G8B8A8Uint, - _ => throw new ArgumentException($"Invalid components count {componentsCount}.") + 1 => Format.R8Uint, + 2 => Format.R8G8Uint, + 4 => Format.R8G8B8A8Uint, + _ => throw new ArgumentException($"Invalid components count {componentsCount}."), }; } - else if (componentSize == 2) + + if (componentSize == 2) { return componentsCount switch { - 1 => GAL.Format.R16Uint, - 2 => GAL.Format.R16G16Uint, - 4 => GAL.Format.R16G16B16A16Uint, - _ => throw new ArgumentException($"Invalid components count {componentsCount}.") + 1 => Format.R16Uint, + 2 => Format.R16G16Uint, + 4 => Format.R16G16B16A16Uint, + _ => throw new ArgumentException($"Invalid components count {componentsCount}."), }; } - else if (componentSize == 4) + + if (componentSize == 4) { return componentsCount switch { - 1 => GAL.Format.R32Uint, - 2 => GAL.Format.R32G32Uint, - 4 => GAL.Format.R32G32B32A32Uint, - _ => throw new ArgumentException($"Invalid components count {componentsCount}.") + 1 => Format.R32Uint, + 2 => Format.R32G32Uint, + 4 => Format.R32G32B32A32Uint, + _ => throw new ArgumentException($"Invalid components count {componentsCount}."), }; } - else - { - throw new ArgumentException($"Invalid component size {componentSize}."); - } + + throw new ArgumentException($"Invalid component size {componentSize}."); } public void ConvertIndexBufferIndirect( @@ -1524,7 +1530,7 @@ namespace Ryujinx.Graphics.Vulkan { // TODO: Support conversion with primitive restart enabled. - BufferRange drawCountBufferAligned = new BufferRange( + BufferRange drawCountBufferAligned = new( drawCountBuffer.Handle, drawCountBuffer.Offset & ~(UniformBufferAlignment - 1), UniformBufferAlignment); @@ -1562,7 +1568,7 @@ namespace Ryujinx.Graphics.Vulkan shaderParams[22] = indirectDataStride / 4; shaderParams[23] = srcIndirectBufferOffset / 4; - pattern.OffsetIndex.CopyTo(shaderParams.Slice(0, pattern.OffsetIndex.Length)); + pattern.OffsetIndex.CopyTo(shaderParams[..pattern.OffsetIndex.Length]); var patternBufferHandle = gd.BufferManager.CreateWithHandle(gd, ParamsBufferSize, out var patternBuffer); var patternBufferAuto = patternBuffer.GetBuffer(); diff --git a/src/Ryujinx.Graphics.Vulkan/HostMemoryAllocator.cs b/src/Ryujinx.Graphics.Vulkan/HostMemoryAllocator.cs index e62b2dbba..726cafc51 100644 --- a/src/Ryujinx.Graphics.Vulkan/HostMemoryAllocator.cs +++ b/src/Ryujinx.Graphics.Vulkan/HostMemoryAllocator.cs @@ -10,7 +10,7 @@ namespace Ryujinx.Graphics.Vulkan { internal class HostMemoryAllocator { - private struct HostMemoryAllocation + private readonly struct HostMemoryAllocation { public readonly Auto Allocation; public readonly IntPtr Pointer; @@ -33,8 +33,8 @@ namespace Ryujinx.Graphics.Vulkan private readonly Device _device; private readonly object _lock = new(); - private List _allocations; - private IntervalTree _allocationTree; + private readonly List _allocations; + private readonly IntervalTree _allocationTree; public HostMemoryAllocator(MemoryAllocator allocator, Vk api, ExtExternalMemoryHost hostMemoryApi, Device device) { @@ -100,19 +100,19 @@ namespace Ryujinx.Graphics.Vulkan return false; } - ImportMemoryHostPointerInfoEXT importInfo = new ImportMemoryHostPointerInfoEXT() + ImportMemoryHostPointerInfoEXT importInfo = new() { SType = StructureType.ImportMemoryHostPointerInfoExt, HandleType = ExternalMemoryHandleTypeFlags.HostAllocationBitExt, - PHostPointer = (void*)pageAlignedPointer + PHostPointer = (void*)pageAlignedPointer, }; - var memoryAllocateInfo = new MemoryAllocateInfo() + var memoryAllocateInfo = new MemoryAllocateInfo { SType = StructureType.MemoryAllocateInfo, AllocationSize = pageAlignedSize, MemoryTypeIndex = (uint)memoryTypeIndex, - PNext = &importInfo + PNext = &importInfo, }; Result result = _api.AllocateMemory(_device, memoryAllocateInfo, null, out var deviceMemory); diff --git a/src/Ryujinx.Graphics.Vulkan/IdList.cs b/src/Ryujinx.Graphics.Vulkan/IdList.cs index 9fba9fe99..598d68584 100644 --- a/src/Ryujinx.Graphics.Vulkan/IdList.cs +++ b/src/Ryujinx.Graphics.Vulkan/IdList.cs @@ -85,11 +85,9 @@ namespace Ryujinx.Graphics.Vulkan value = _list[id]; return value != null; } - else - { - value = null; - return false; - } + + value = null; + return false; } catch (ArgumentOutOfRangeException) { @@ -120,4 +118,4 @@ namespace Ryujinx.Graphics.Vulkan } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Vulkan/IndexBufferPattern.cs b/src/Ryujinx.Graphics.Vulkan/IndexBufferPattern.cs index 11f4ec333..9d34c8116 100644 --- a/src/Ryujinx.Graphics.Vulkan/IndexBufferPattern.cs +++ b/src/Ryujinx.Graphics.Vulkan/IndexBufferPattern.cs @@ -14,7 +14,7 @@ namespace Ryujinx.Graphics.Vulkan public int IndexStride { get; } public bool RepeatStart { get; } - private VulkanRenderer _gd; + private readonly VulkanRenderer _gd; private int _currentSize; private BufferHandle _repeatingBuffer; diff --git a/src/Ryujinx.Graphics.Vulkan/IndexBufferState.cs b/src/Ryujinx.Graphics.Vulkan/IndexBufferState.cs index 75b18456a..e81268e96 100644 --- a/src/Ryujinx.Graphics.Vulkan/IndexBufferState.cs +++ b/src/Ryujinx.Graphics.Vulkan/IndexBufferState.cs @@ -1,19 +1,20 @@ -using Silk.NET.Vulkan; +using Ryujinx.Graphics.GAL; +using IndexType = Silk.NET.Vulkan.IndexType; namespace Ryujinx.Graphics.Vulkan { internal struct IndexBufferState { - public static IndexBufferState Null => new IndexBufferState(GAL.BufferHandle.Null, 0, 0); + public static IndexBufferState Null => new(BufferHandle.Null, 0, 0); private readonly int _offset; private readonly int _size; private readonly IndexType _type; - private readonly GAL.BufferHandle _handle; + private readonly BufferHandle _handle; private Auto _buffer; - public IndexBufferState(GAL.BufferHandle handle, int offset, int size, IndexType type) + public IndexBufferState(BufferHandle handle, int offset, int size, IndexType type) { _handle = handle; _offset = offset; @@ -22,7 +23,7 @@ namespace Ryujinx.Graphics.Vulkan _buffer = null; } - public IndexBufferState(GAL.BufferHandle handle, int offset, int size) + public IndexBufferState(BufferHandle handle, int offset, int size) { _handle = handle; _offset = offset; @@ -97,8 +98,8 @@ namespace Ryujinx.Graphics.Vulkan public Auto BindConvertedIndexBufferIndirect( VulkanRenderer gd, CommandBufferScoped cbs, - GAL.BufferRange indirectBuffer, - GAL.BufferRange drawCountBuffer, + BufferRange indirectBuffer, + BufferRange drawCountBuffer, IndexBufferPattern pattern, bool hasDrawCount, int maxDrawCount, @@ -110,7 +111,7 @@ namespace Ryujinx.Graphics.Vulkan (var indexBufferAuto, var indirectBufferAuto) = gd.BufferManager.GetBufferTopologyConversionIndirect( gd, cbs, - new GAL.BufferRange(_handle, _offset, _size), + new BufferRange(_handle, _offset, _size), indirectBuffer, drawCountBuffer, pattern, @@ -132,7 +133,7 @@ namespace Ryujinx.Graphics.Vulkan return indirectBufferAuto; } - private int GetIndexSize() + private readonly int GetIndexSize() { return _type switch { @@ -142,7 +143,7 @@ namespace Ryujinx.Graphics.Vulkan }; } - public bool BoundEquals(Auto buffer) + public readonly bool BoundEquals(Auto buffer) { return _buffer == buffer; } diff --git a/src/Ryujinx.Graphics.Vulkan/MemoryAllocation.cs b/src/Ryujinx.Graphics.Vulkan/MemoryAllocation.cs index 3c98c417c..e2b6028ab 100644 --- a/src/Ryujinx.Graphics.Vulkan/MemoryAllocation.cs +++ b/src/Ryujinx.Graphics.Vulkan/MemoryAllocation.cs @@ -10,7 +10,7 @@ namespace Ryujinx.Graphics.Vulkan private readonly HostMemoryAllocator _hostMemory; public DeviceMemory Memory { get; } - public IntPtr HostPointer { get;} + public IntPtr HostPointer { get; } public ulong Offset { get; } public ulong Size { get; } diff --git a/src/Ryujinx.Graphics.Vulkan/MemoryAllocator.cs b/src/Ryujinx.Graphics.Vulkan/MemoryAllocator.cs index 462d8f052..ab7006270 100644 --- a/src/Ryujinx.Graphics.Vulkan/MemoryAllocator.cs +++ b/src/Ryujinx.Graphics.Vulkan/MemoryAllocator.cs @@ -6,7 +6,7 @@ namespace Ryujinx.Graphics.Vulkan { class MemoryAllocator : IDisposable { - private ulong MaxDeviceMemoryUsageEstimate = 16UL * 1024 * 1024 * 1024; + private const ulong MaxDeviceMemoryUsageEstimate = 16UL * 1024 * 1024 * 1024; private readonly Vk _api; private readonly VulkanPhysicalDevice _physicalDevice; @@ -20,7 +20,7 @@ namespace Ryujinx.Graphics.Vulkan _physicalDevice = physicalDevice; _device = device; _blockLists = new List(); - _blockAlignment = (int)Math.Min(int.MaxValue, MaxDeviceMemoryUsageEstimate / (ulong)_physicalDevice.PhysicalDeviceProperties.Limits.MaxMemoryAllocationCount); + _blockAlignment = (int)Math.Min(int.MaxValue, MaxDeviceMemoryUsageEstimate / _physicalDevice.PhysicalDeviceProperties.Limits.MaxMemoryAllocationCount); } public MemoryAllocation AllocateDeviceMemory( diff --git a/src/Ryujinx.Graphics.Vulkan/MemoryAllocatorBlockList.cs b/src/Ryujinx.Graphics.Vulkan/MemoryAllocatorBlockList.cs index e564cb264..bd57e778b 100644 --- a/src/Ryujinx.Graphics.Vulkan/MemoryAllocatorBlockList.cs +++ b/src/Ryujinx.Graphics.Vulkan/MemoryAllocatorBlockList.cs @@ -43,7 +43,7 @@ namespace Ryujinx.Graphics.Vulkan Size = size; _freeRanges = new List { - new Range(0, size) + new Range(0, size), }; } @@ -53,7 +53,7 @@ namespace Ryujinx.Graphics.Vulkan { var range = _freeRanges[i]; - ulong alignedOffset = BitUtils.AlignUp(range.Offset, alignment); + ulong alignedOffset = BitUtils.AlignUp(range.Offset, alignment); ulong sizeDelta = alignedOffset - range.Offset; ulong usableSize = range.Size - sizeDelta; @@ -198,13 +198,13 @@ namespace Ryujinx.Graphics.Vulkan } } - ulong blockAlignedSize = BitUtils.AlignUp(size, (ulong)_blockAlignment); + ulong blockAlignedSize = BitUtils.AlignUp(size, (ulong)_blockAlignment); - var memoryAllocateInfo = new MemoryAllocateInfo() + var memoryAllocateInfo = new MemoryAllocateInfo { SType = StructureType.MemoryAllocateInfo, AllocationSize = blockAlignedSize, - MemoryTypeIndex = (uint)MemoryTypeIndex + MemoryTypeIndex = (uint)MemoryTypeIndex, }; _api.AllocateMemory(_device, memoryAllocateInfo, null, out var deviceMemory).ThrowOnError(); @@ -213,12 +213,9 @@ namespace Ryujinx.Graphics.Vulkan if (map) { - unsafe - { - void* pointer = null; - _api.MapMemory(_device, deviceMemory, 0, blockAlignedSize, 0, ref pointer).ThrowOnError(); - hostPointer = (IntPtr)pointer; - } + void* pointer = null; + _api.MapMemory(_device, deviceMemory, 0, blockAlignedSize, 0, ref pointer).ThrowOnError(); + hostPointer = (IntPtr)pointer; } var newBlock = new Block(deviceMemory, hostPointer, blockAlignedSize); @@ -238,10 +235,10 @@ namespace Ryujinx.Graphics.Vulkan return IntPtr.Zero; } - return (IntPtr)((nuint)(nint)block.HostPointer + offset); + return (IntPtr)((nuint)block.HostPointer + offset); } - public unsafe void Free(Block block, ulong offset, ulong size) + public void Free(Block block, ulong offset, ulong size) { block.Free(offset, size); @@ -271,7 +268,7 @@ namespace Ryujinx.Graphics.Vulkan _blocks.Insert(index, block); } - public unsafe void Dispose() + public void Dispose() { for (int i = 0; i < _blocks.Count; i++) { diff --git a/src/Ryujinx.Graphics.Vulkan/MoltenVK/MVKConfiguration.cs b/src/Ryujinx.Graphics.Vulkan/MoltenVK/MVKConfiguration.cs index 414dbc628..bdf606e82 100644 --- a/src/Ryujinx.Graphics.Vulkan/MoltenVK/MVKConfiguration.cs +++ b/src/Ryujinx.Graphics.Vulkan/MoltenVK/MVKConfiguration.cs @@ -9,7 +9,7 @@ namespace Ryujinx.Graphics.Vulkan.MoltenVK Error = 1, Warning = 2, Info = 3, - Debug = 4 + Debug = 4, } enum MVKConfigTraceVulkanCalls @@ -17,14 +17,14 @@ namespace Ryujinx.Graphics.Vulkan.MoltenVK None = 0, Enter = 1, EnterExit = 2, - Duration = 3 + Duration = 3, } enum MVKConfigAutoGPUCaptureScope { None = 0, Device = 1, - Frame = 2 + Frame = 2, } [Flags] @@ -33,7 +33,7 @@ namespace Ryujinx.Graphics.Vulkan.MoltenVK All = 0x00000001, MoltenVK = 0x00000002, WSI = 0x00000004, - Portability = 0x00000008 + Portability = 0x00000008, } enum MVKVkSemaphoreSupportStyle @@ -42,7 +42,7 @@ namespace Ryujinx.Graphics.Vulkan.MoltenVK MVK_CONFIG_VK_SEMAPHORE_SUPPORT_STYLE_METAL_EVENTS_WHERE_SAFE = 1, MVK_CONFIG_VK_SEMAPHORE_SUPPORT_STYLE_METAL_EVENTS = 2, MVK_CONFIG_VK_SEMAPHORE_SUPPORT_STYLE_CALLBACK = 3, - MVK_CONFIG_VK_SEMAPHORE_SUPPORT_STYLE_MAX_ENUM = 0x7FFFFFFF + MVK_CONFIG_VK_SEMAPHORE_SUPPORT_STYLE_MAX_ENUM = 0x7FFFFFFF, } readonly struct Bool32 @@ -60,7 +60,7 @@ namespace Ryujinx.Graphics.Vulkan.MoltenVK } public static implicit operator bool(Bool32 val) => val.Value == 1; - public static implicit operator Bool32(bool val) => new Bool32(val); + public static implicit operator Bool32(bool val) => new(val); } [StructLayout(LayoutKind.Sequential)] diff --git a/src/Ryujinx.Graphics.Vulkan/MoltenVK/MVKInitialization.cs b/src/Ryujinx.Graphics.Vulkan/MoltenVK/MVKInitialization.cs index b5d88dde6..457240aa0 100644 --- a/src/Ryujinx.Graphics.Vulkan/MoltenVK/MVKInitialization.cs +++ b/src/Ryujinx.Graphics.Vulkan/MoltenVK/MVKInitialization.cs @@ -30,4 +30,4 @@ namespace Ryujinx.Graphics.Vulkan.MoltenVK vkSetMoltenVKConfigurationMVK(IntPtr.Zero, config, configSize); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Vulkan/MultiFenceHolder.cs b/src/Ryujinx.Graphics.Vulkan/MultiFenceHolder.cs index 13a4f4c14..d564f3e16 100644 --- a/src/Ryujinx.Graphics.Vulkan/MultiFenceHolder.cs +++ b/src/Ryujinx.Graphics.Vulkan/MultiFenceHolder.cs @@ -8,10 +8,10 @@ namespace Ryujinx.Graphics.Vulkan /// class MultiFenceHolder { - private static int BufferUsageTrackingGranularity = 4096; + private static readonly int _bufferUsageTrackingGranularity = 4096; private readonly FenceHolder[] _fences; - private BufferUsageBitmap _bufferUsageBitmap; + private readonly BufferUsageBitmap _bufferUsageBitmap; /// /// Creates a new instance of the multiple fence holder. @@ -28,7 +28,7 @@ namespace Ryujinx.Graphics.Vulkan public MultiFenceHolder(int size) { _fences = new FenceHolder[CommandBufferPool.MaxCommandBuffers]; - _bufferUsageBitmap = new BufferUsageBitmap(size, BufferUsageTrackingGranularity); + _bufferUsageBitmap = new BufferUsageBitmap(size, _bufferUsageTrackingGranularity); } /// @@ -189,11 +189,11 @@ namespace Ryujinx.Graphics.Vulkan if (hasTimeout) { - signaled = FenceHelper.AllSignaled(api, device, fences.Slice(0, fenceCount), timeout); + signaled = FenceHelper.AllSignaled(api, device, fences[..fenceCount], timeout); } else { - FenceHelper.WaitAllIndefinitely(api, device, fences.Slice(0, fenceCount)); + FenceHelper.WaitAllIndefinitely(api, device, fences[..fenceCount]); } for (int i = 0; i < fenceCount; i++) diff --git a/src/Ryujinx.Graphics.Vulkan/PersistentFlushBuffer.cs b/src/Ryujinx.Graphics.Vulkan/PersistentFlushBuffer.cs index fc98b68f7..80a24682b 100644 --- a/src/Ryujinx.Graphics.Vulkan/PersistentFlushBuffer.cs +++ b/src/Ryujinx.Graphics.Vulkan/PersistentFlushBuffer.cs @@ -1,10 +1,11 @@ -using System; +using Ryujinx.Graphics.GAL; +using System; namespace Ryujinx.Graphics.Vulkan { internal class PersistentFlushBuffer : IDisposable { - private VulkanRenderer _gd; + private readonly VulkanRenderer _gd; private BufferHolder _flushStorage; @@ -19,10 +20,7 @@ namespace Ryujinx.Graphics.Vulkan if (flushStorage == null || size > _flushStorage.Size) { - if (flushStorage != null) - { - flushStorage.Dispose(); - } + flushStorage?.Dispose(); flushStorage = _gd.BufferManager.Create(_gd, size); _flushStorage = flushStorage; @@ -59,7 +57,7 @@ namespace Ryujinx.Graphics.Vulkan public Span GetTextureData(CommandBufferPool cbp, TextureView view, int size) { - GAL.TextureCreateInfo info = view.Info; + TextureCreateInfo info = view.Info; var flushStorage = ResizeIfNeeded(size); diff --git a/src/Ryujinx.Graphics.Vulkan/PipelineBase.cs b/src/Ryujinx.Graphics.Vulkan/PipelineBase.cs index 1ee03536d..5ee926911 100644 --- a/src/Ryujinx.Graphics.Vulkan/PipelineBase.cs +++ b/src/Ryujinx.Graphics.Vulkan/PipelineBase.cs @@ -1,5 +1,4 @@ -using Ryujinx.Common; -using Ryujinx.Graphics.GAL; +using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.Shader; using Silk.NET.Vulkan; using System; @@ -7,6 +6,13 @@ using System.Linq; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using CompareOp = Ryujinx.Graphics.GAL.CompareOp; +using Format = Ryujinx.Graphics.GAL.Format; +using FrontFace = Ryujinx.Graphics.GAL.FrontFace; +using IndexType = Ryujinx.Graphics.GAL.IndexType; +using PolygonMode = Ryujinx.Graphics.GAL.PolygonMode; +using PrimitiveTopology = Ryujinx.Graphics.GAL.PrimitiveTopology; +using Viewport = Ryujinx.Graphics.GAL.Viewport; namespace Ryujinx.Graphics.Vulkan { @@ -28,7 +34,7 @@ namespace Ryujinx.Graphics.Vulkan protected PipelineDynamicState DynamicState; private PipelineState _newState; private bool _stateDirty; - private GAL.PrimitiveTopology _topology; + private PrimitiveTopology _topology; private ulong _currentPipelineHandle; @@ -44,7 +50,7 @@ namespace Ryujinx.Graphics.Vulkan private ShaderCollection _program; - private Vector4[] _renderScale = new Vector4[73]; + private readonly Vector4[] _renderScale = new Vector4[73]; private int _fragmentScaleCount; protected FramebufferParams FramebufferParams; @@ -78,7 +84,7 @@ namespace Ryujinx.Graphics.Vulkan private bool _tfEnabled; private bool _tfActive; - private PipelineColorBlendAttachmentState[] _storedBlend; + private readonly PipelineColorBlendAttachmentState[] _storedBlend; private ulong _drawCountSinceBarrier; public ulong DrawCount { get; private set; } @@ -91,9 +97,9 @@ namespace Ryujinx.Graphics.Vulkan AutoFlush = new AutoFlushCounter(gd); - var pipelineCacheCreateInfo = new PipelineCacheCreateInfo() + var pipelineCacheCreateInfo = new PipelineCacheCreateInfo { - SType = StructureType.PipelineCacheCreateInfo + SType = StructureType.PipelineCacheCreateInfo, }; gd.Api.CreatePipelineCache(device, pipelineCacheCreateInfo, null, out PipelineCache).ThrowOnError(); @@ -108,7 +114,7 @@ namespace Ryujinx.Graphics.Vulkan using var emptyVb = gd.BufferManager.Create(gd, EmptyVbSize); emptyVb.SetData(0, new byte[EmptyVbSize]); - _vertexBuffers[0] = new VertexBufferState(emptyVb.GetBuffer(), 0, 0, EmptyVbSize, 0); + _vertexBuffers[0] = new VertexBufferState(emptyVb.GetBuffer(), 0, 0, EmptyVbSize); _vertexBuffersDirty = ulong.MaxValue >> (64 - _vertexBuffers.Length); ClearScissor = new Rectangle(0, 0, 0xffff, 0xffff); @@ -146,11 +152,11 @@ namespace Ryujinx.Graphics.Vulkan } } - MemoryBarrier memoryBarrier = new MemoryBarrier() + MemoryBarrier memoryBarrier = new() { SType = StructureType.MemoryBarrier, SrcAccessMask = AccessFlags.MemoryReadBit | AccessFlags.MemoryWriteBit, - DstAccessMask = AccessFlags.MemoryReadBit | AccessFlags.MemoryWriteBit + DstAccessMask = AccessFlags.MemoryReadBit | AccessFlags.MemoryWriteBit, }; Gd.Api.CmdPipelineBarrier( @@ -168,11 +174,11 @@ namespace Ryujinx.Graphics.Vulkan public void ComputeBarrier() { - MemoryBarrier memoryBarrier = new MemoryBarrier() + MemoryBarrier memoryBarrier = new() { SType = StructureType.MemoryBarrier, SrcAccessMask = AccessFlags.MemoryReadBit | AccessFlags.MemoryWriteBit, - DstAccessMask = AccessFlags.MemoryReadBit | AccessFlags.MemoryWriteBit + DstAccessMask = AccessFlags.MemoryReadBit | AccessFlags.MemoryWriteBit, }; Gd.Api.CmdPipelineBarrier( @@ -188,7 +194,7 @@ namespace Ryujinx.Graphics.Vulkan ReadOnlySpan.Empty); } - public void BeginTransformFeedback(GAL.PrimitiveTopology topology) + public void BeginTransformFeedback(PrimitiveTopology topology) { _tfEnabled = true; } @@ -281,11 +287,11 @@ namespace Ryujinx.Graphics.Vulkan public unsafe void CommandBufferBarrier() { - MemoryBarrier memoryBarrier = new MemoryBarrier() + MemoryBarrier memoryBarrier = new() { SType = StructureType.MemoryBarrier, SrcAccessMask = BufferHolder.DefaultAccessFlags, - DstAccessMask = AccessFlags.IndirectCommandReadBit + DstAccessMask = AccessFlags.IndirectCommandReadBit, }; Gd.Api.CmdPipelineBarrier( @@ -374,10 +380,10 @@ namespace Ryujinx.Graphics.Vulkan IndexBufferPattern pattern = _topology switch { - GAL.PrimitiveTopology.Quads => QuadsToTrisPattern, - GAL.PrimitiveTopology.TriangleFan or - GAL.PrimitiveTopology.Polygon => TriFanToTrisPattern, - _ => throw new NotSupportedException($"Unsupported topology: {_topology}") + PrimitiveTopology.Quads => QuadsToTrisPattern, + PrimitiveTopology.TriangleFan or + PrimitiveTopology.Polygon => TriFanToTrisPattern, + _ => throw new NotSupportedException($"Unsupported topology: {_topology}"), }; BufferHandle handle = pattern.GetRepeatingBuffer(vertexCount, out int indexCount); @@ -406,10 +412,10 @@ namespace Ryujinx.Graphics.Vulkan { pattern = _topology switch { - GAL.PrimitiveTopology.Quads => QuadsToTrisPattern, - GAL.PrimitiveTopology.TriangleFan or - GAL.PrimitiveTopology.Polygon => TriFanToTrisPattern, - _ => throw new NotSupportedException($"Unsupported topology: {_topology}") + PrimitiveTopology.Quads => QuadsToTrisPattern, + PrimitiveTopology.TriangleFan or + PrimitiveTopology.Polygon => TriFanToTrisPattern, + _ => throw new NotSupportedException($"Unsupported topology: {_topology}"), }; } @@ -718,7 +724,7 @@ namespace Ryujinx.Graphics.Vulkan return CommandBuffer.Handle == cb.Handle; } - public void SetAlphaTest(bool enable, float reference, GAL.CompareOp op) + public void SetAlphaTest(bool enable, float reference, CompareOp op) { // This is currently handled using shader specialization, as Vulkan does not support alpha test. // In the future, we may want to use this to write the reference value into the support buffer, @@ -847,13 +853,13 @@ namespace Ryujinx.Graphics.Vulkan SignalStateChange(); } - public void SetFrontFace(GAL.FrontFace frontFace) + public void SetFrontFace(FrontFace frontFace) { _newState.FrontFace = frontFace.Convert(); SignalStateChange(); } - public void SetImage(int binding, ITexture image, GAL.Format imageFormat) + public void SetImage(int binding, ITexture image, Format imageFormat) { _descriptorSetUpdater.SetImage(binding, image, imageFormat); } @@ -863,7 +869,7 @@ namespace Ryujinx.Graphics.Vulkan _descriptorSetUpdater.SetImage(binding, image); } - public void SetIndexBuffer(BufferRange buffer, GAL.IndexType type) + public void SetIndexBuffer(BufferRange buffer, IndexType type) { if (buffer.Handle != BufferHandle.Null) { @@ -897,12 +903,7 @@ namespace Ryujinx.Graphics.Vulkan SignalStateChange(); } - public void SetOrigin(Origin origin) - { - // TODO. - } - - public unsafe void SetPatchParameters(int vertices, ReadOnlySpan defaultOuterLevel, ReadOnlySpan defaultInnerLevel) + public void SetPatchParameters(int vertices, ReadOnlySpan defaultOuterLevel, ReadOnlySpan defaultInnerLevel) { _newState.PatchControlPoints = (uint)vertices; SignalStateChange(); @@ -910,15 +911,17 @@ namespace Ryujinx.Graphics.Vulkan // TODO: Default levels (likely needs emulation on shaders?) } +#pragma warning disable CA1822 // Mark member as static public void SetPointParameters(float size, bool isProgramPointSize, bool enablePointSprite, Origin origin) { // TODO. } - public void SetPolygonMode(GAL.PolygonMode frontMode, GAL.PolygonMode backMode) + public void SetPolygonMode(PolygonMode frontMode, PolygonMode backMode) { // TODO. } +#pragma warning restore CA1822 public void SetPrimitiveRestart(bool enable, int index) { @@ -927,7 +930,7 @@ namespace Ryujinx.Graphics.Vulkan SignalStateChange(); } - public void SetPrimitiveTopology(GAL.PrimitiveTopology topology) + public void SetPrimitiveTopology(PrimitiveTopology topology) { _topology = topology; @@ -950,7 +953,7 @@ namespace Ryujinx.Graphics.Vulkan _newState.PipelineLayout = internalProgram.PipelineLayout; _newState.StagesCount = (uint)stages.Length; - stages.CopyTo(_newState.Stages.AsSpan().Slice(0, stages.Length)); + stages.CopyTo(_newState.Stages.AsSpan()[..stages.Length]); SignalStateChange(); @@ -1149,10 +1152,12 @@ namespace Ryujinx.Graphics.Vulkan _descriptorSetUpdater.SetUniformBuffers(CommandBuffer, buffers); } +#pragma warning disable CA1822 // Mark member as static public void SetUserClipDistance(int index, bool enableClip) { // TODO. } +#pragma warning restore CA1822 public void SetVertexAttribs(ReadOnlySpan vertexAttribs) { @@ -1298,7 +1303,7 @@ namespace Ryujinx.Graphics.Vulkan SignalStateChange(); } - public void SetViewports(ReadOnlySpan viewports, bool disableTransform) + public void SetViewports(ReadOnlySpan viewports, bool disableTransform) { int maxViewports = Gd.Capabilities.SupportsMultiView ? Constants.MaxViewports : 1; int count = Math.Min(maxViewports, viewports.Length); @@ -1332,7 +1337,7 @@ namespace Ryujinx.Graphics.Vulkan X = scale * 2f / viewports[0].Region.Width, Y = scale * 2f / viewports[0].Region.Height, Z = 1, - W = disableTransformF + W = disableTransformF, }); } @@ -1361,11 +1366,11 @@ namespace Ryujinx.Graphics.Vulkan public unsafe void TextureBarrier() { - MemoryBarrier memoryBarrier = new MemoryBarrier() + MemoryBarrier memoryBarrier = new() { SType = StructureType.MemoryBarrier, SrcAccessMask = AccessFlags.MemoryReadBit | AccessFlags.MemoryWriteBit, - DstAccessMask = AccessFlags.MemoryReadBit | AccessFlags.MemoryWriteBit + DstAccessMask = AccessFlags.MemoryReadBit | AccessFlags.MemoryWriteBit, }; Gd.Api.CmdPipelineBarrier( @@ -1433,7 +1438,7 @@ namespace Ryujinx.Graphics.Vulkan // Just try to remove duplicate attachments. // Save a copy of the array to rebind when mask changes. - void maskOut() + void MaskOut() { if (!_framebufferUsingColorWriteMask) { @@ -1467,12 +1472,12 @@ namespace Ryujinx.Graphics.Vulkan if (vkBlend.ColorWriteMask == 0) { colors[i] = null; - maskOut(); + MaskOut(); } else if (vkBlend2.ColorWriteMask == 0) { colors[j] = null; - maskOut(); + MaskOut(); } } } @@ -1505,9 +1510,9 @@ namespace Ryujinx.Graphics.Vulkan AttachmentDescription[] attachmentDescs = null; - var subpass = new SubpassDescription() + var subpass = new SubpassDescription { - PipelineBindPoint = PipelineBindPoint.Graphics + PipelineBindPoint = PipelineBindPoint.Graphics, }; AttachmentReference* attachmentReferences = stackalloc AttachmentReference[MaxAttachments]; @@ -1572,7 +1577,7 @@ namespace Ryujinx.Graphics.Vulkan fixed (AttachmentDescription* pAttachmentDescs = attachmentDescs) { - var renderPassCreateInfo = new RenderPassCreateInfo() + var renderPassCreateInfo = new RenderPassCreateInfo { SType = StructureType.RenderPassCreateInfo, PAttachments = pAttachmentDescs, @@ -1580,7 +1585,7 @@ namespace Ryujinx.Graphics.Vulkan PSubpasses = &subpass, SubpassCount = 1, PDependencies = &subpassDependency, - DependencyCount = 1 + DependencyCount = 1, }; Gd.Api.CreateRenderPass(Device, renderPassCreateInfo, null, out var renderPass).ThrowOnError(); @@ -1688,14 +1693,14 @@ namespace Ryujinx.Graphics.Vulkan var renderArea = new Rect2D(null, new Extent2D(FramebufferParams.Width, FramebufferParams.Height)); var clearValue = new ClearValue(); - var renderPassBeginInfo = new RenderPassBeginInfo() + var renderPassBeginInfo = new RenderPassBeginInfo { SType = StructureType.RenderPassBeginInfo, RenderPass = _renderPass.Get(Cbs).Value, Framebuffer = _framebuffer.Get(Cbs).Value, RenderArea = renderArea, PClearValues = &clearValue, - ClearValueCount = 1 + ClearValueCount = 1, }; Gd.Api.CmdBeginRenderPass(CommandBuffer, renderPassBeginInfo, SubpassContents.Inline); diff --git a/src/Ryujinx.Graphics.Vulkan/PipelineConverter.cs b/src/Ryujinx.Graphics.Vulkan/PipelineConverter.cs index a52b44622..7c1ddef8d 100644 --- a/src/Ryujinx.Graphics.Vulkan/PipelineConverter.cs +++ b/src/Ryujinx.Graphics.Vulkan/PipelineConverter.cs @@ -2,6 +2,8 @@ using Ryujinx.Graphics.GAL; using Silk.NET.Vulkan; using System; +using Format = Silk.NET.Vulkan.Format; +using PolygonMode = Silk.NET.Vulkan.PolygonMode; namespace Ryujinx.Graphics.Vulkan { @@ -16,15 +18,15 @@ namespace Ryujinx.Graphics.Vulkan AttachmentDescription[] attachmentDescs = null; - var subpass = new SubpassDescription() + var subpass = new SubpassDescription { - PipelineBindPoint = PipelineBindPoint.Graphics + PipelineBindPoint = PipelineBindPoint.Graphics, }; AttachmentReference* attachmentReferences = stackalloc AttachmentReference[MaxAttachments]; Span attachmentIndices = stackalloc int[MaxAttachments]; - Span attachmentFormats = stackalloc Silk.NET.Vulkan.Format[MaxAttachments]; + Span attachmentFormats = stackalloc Format[MaxAttachments]; int attachmentCount = 0; int colorCount = 0; @@ -106,7 +108,7 @@ namespace Ryujinx.Graphics.Vulkan fixed (AttachmentDescription* pAttachmentDescs = attachmentDescs) { - var renderPassCreateInfo = new RenderPassCreateInfo() + var renderPassCreateInfo = new RenderPassCreateInfo { SType = StructureType.RenderPassCreateInfo, PAttachments = pAttachmentDescs, @@ -114,7 +116,7 @@ namespace Ryujinx.Graphics.Vulkan PSubpasses = &subpass, SubpassCount = 1, PDependencies = &subpassDependency, - DependencyCount = 1 + DependencyCount = 1, }; gd.Api.CreateRenderPass(device, renderPassCreateInfo, null, out var renderPass).ThrowOnError(); @@ -151,7 +153,7 @@ namespace Ryujinx.Graphics.Vulkan public static PipelineState ToVulkanPipelineState(this ProgramPipelineState state, VulkanRenderer gd) { - PipelineState pipeline = new PipelineState(); + PipelineState pipeline = new(); pipeline.Initialize(); // It is assumed that Dynamic State is enabled when this conversion is used. @@ -178,7 +180,7 @@ namespace Ryujinx.Graphics.Vulkan pipeline.MaxDepthBounds = 0f; // Not implemented. pipeline.PatchControlPoints = state.PatchControlPoints; - pipeline.PolygonMode = Silk.NET.Vulkan.PolygonMode.Fill; // Not implemented. + pipeline.PolygonMode = PolygonMode.Fill; // Not implemented. pipeline.PrimitiveRestartEnable = state.PrimitiveRestartEnable; pipeline.RasterizerDiscardEnable = state.RasterizerDiscard; pipeline.SamplesCount = (uint)state.SamplesCount; diff --git a/src/Ryujinx.Graphics.Vulkan/PipelineDynamicState.cs b/src/Ryujinx.Graphics.Vulkan/PipelineDynamicState.cs index 42ea022a4..ff88e4cf4 100644 --- a/src/Ryujinx.Graphics.Vulkan/PipelineDynamicState.cs +++ b/src/Ryujinx.Graphics.Vulkan/PipelineDynamicState.cs @@ -32,7 +32,7 @@ namespace Ryujinx.Graphics.Vulkan Scissor = 1 << 2, Stencil = 1 << 3, Viewport = 1 << 4, - All = Blend | DepthBias | Scissor | Stencil | Viewport + All = Blend | DepthBias | Scissor | Stencil | Viewport, } private DirtyFlags _dirty; @@ -139,7 +139,7 @@ namespace Ryujinx.Graphics.Vulkan api.CmdSetBlendConstants(commandBuffer, _blendConstants.AsSpan()); } - private void RecordDepthBias(Vk api, CommandBuffer commandBuffer) + private readonly void RecordDepthBias(Vk api, CommandBuffer commandBuffer) { api.CmdSetDepthBias(commandBuffer, _depthBiasConstantFactor, _depthBiasClamp, _depthBiasSlopeFactor); } @@ -149,7 +149,7 @@ namespace Ryujinx.Graphics.Vulkan api.CmdSetScissor(commandBuffer, 0, (uint)ScissorsCount, _scissors.AsSpan()); } - private void RecordStencilMasks(Vk api, CommandBuffer commandBuffer) + private readonly void RecordStencilMasks(Vk api, CommandBuffer commandBuffer) { api.CmdSetStencilCompareMask(commandBuffer, StencilFaceFlags.FaceBackBit, _backCompareMask); api.CmdSetStencilWriteMask(commandBuffer, StencilFaceFlags.FaceBackBit, _backWriteMask); diff --git a/src/Ryujinx.Graphics.Vulkan/PipelineFull.cs b/src/Ryujinx.Graphics.Vulkan/PipelineFull.cs index 8026103e7..dfdac52fd 100644 --- a/src/Ryujinx.Graphics.Vulkan/PipelineFull.cs +++ b/src/Ryujinx.Graphics.Vulkan/PipelineFull.cs @@ -17,7 +17,7 @@ namespace Ryujinx.Graphics.Vulkan private ulong _byteWeight; - private List _backingSwaps; + private readonly List _backingSwaps; public PipelineFull(VulkanRenderer gd, Device device) : base(gd, device) { @@ -116,15 +116,15 @@ namespace Ryujinx.Graphics.Vulkan if (Gd.Capabilities.SupportsConditionalRendering) { - var buffer = evt.GetBuffer().Get(Cbs, 0, sizeof(long)).Value; - var flags = isEqual ? ConditionalRenderingFlagsEXT.InvertedBitExt : 0; + // var buffer = evt.GetBuffer().Get(Cbs, 0, sizeof(long)).Value; + // var flags = isEqual ? ConditionalRenderingFlagsEXT.InvertedBitExt : 0; - var conditionalRenderingBeginInfo = new ConditionalRenderingBeginInfoEXT() - { - SType = StructureType.ConditionalRenderingBeginInfoExt, - Buffer = buffer, - Flags = flags - }; + // var conditionalRenderingBeginInfo = new ConditionalRenderingBeginInfoEXT + // { + // SType = StructureType.ConditionalRenderingBeginInfoExt, + // Buffer = buffer, + // Flags = flags, + // }; // Gd.ConditionalRenderingApi.CmdBeginConditionalRendering(CommandBuffer, conditionalRenderingBeginInfo); } @@ -156,10 +156,7 @@ namespace Ryujinx.Graphics.Vulkan public CommandBufferScoped GetPreloadCommandBuffer() { - if (PreloadCbs == null) - { - PreloadCbs = Gd.CommandBufferPool.Rent(); - } + PreloadCbs ??= Gd.CommandBufferPool.Rent(); return PreloadCbs.Value; } @@ -192,7 +189,7 @@ namespace Ryujinx.Graphics.Vulkan { CommandBufferScoped? cbs = null; - _backingSwaps.RemoveAll((holder) => holder.TryBackingSwap(ref cbs)); + _backingSwaps.RemoveAll(holder => holder.TryBackingSwap(ref cbs)); cbs?.Dispose(); } diff --git a/src/Ryujinx.Graphics.Vulkan/PipelineLayoutCache.cs b/src/Ryujinx.Graphics.Vulkan/PipelineLayoutCache.cs index e7c435670..5d0cada96 100644 --- a/src/Ryujinx.Graphics.Vulkan/PipelineLayoutCache.cs +++ b/src/Ryujinx.Graphics.Vulkan/PipelineLayoutCache.cs @@ -21,7 +21,7 @@ namespace Ryujinx.Graphics.Vulkan public override int GetHashCode() { - HashCode hasher = new HashCode(); + HashCode hasher = new(); if (SetDescriptors != null) { @@ -83,10 +83,10 @@ namespace Ryujinx.Graphics.Vulkan { var key = new PlceKey(setDescriptors, usePushDescriptors); - return _plces.GetOrAdd(key, (newKey) => new PipelineLayoutCacheEntry(gd, device, setDescriptors, usePushDescriptors)); + return _plces.GetOrAdd(key, newKey => new PipelineLayoutCacheEntry(gd, device, setDescriptors, usePushDescriptors)); } - protected virtual unsafe void Dispose(bool disposing) + protected virtual void Dispose(bool disposing) { if (disposing) { diff --git a/src/Ryujinx.Graphics.Vulkan/PipelineLayoutFactory.cs b/src/Ryujinx.Graphics.Vulkan/PipelineLayoutFactory.cs index bcb2c1a50..ba93dfadb 100644 --- a/src/Ryujinx.Graphics.Vulkan/PipelineLayoutFactory.cs +++ b/src/Ryujinx.Graphics.Vulkan/PipelineLayoutFactory.cs @@ -45,23 +45,23 @@ namespace Ryujinx.Graphics.Vulkan stages = activeStages; } - layoutBindings[descIndex] = new DescriptorSetLayoutBinding() + layoutBindings[descIndex] = new DescriptorSetLayoutBinding { Binding = (uint)descriptor.Binding, DescriptorType = descriptor.Type.Convert(), DescriptorCount = (uint)descriptor.Count, - StageFlags = stages.Convert() + StageFlags = stages.Convert(), }; } fixed (DescriptorSetLayoutBinding* pLayoutBindings = layoutBindings) { - var descriptorSetLayoutCreateInfo = new DescriptorSetLayoutCreateInfo() + var descriptorSetLayoutCreateInfo = new DescriptorSetLayoutCreateInfo { SType = StructureType.DescriptorSetLayoutCreateInfo, PBindings = pLayoutBindings, BindingCount = (uint)layoutBindings.Length, - Flags = usePushDescriptors && setIndex == 0 ? DescriptorSetLayoutCreateFlags.PushDescriptorBitKhr : DescriptorSetLayoutCreateFlags.None + Flags = usePushDescriptors && setIndex == 0 ? DescriptorSetLayoutCreateFlags.PushDescriptorBitKhr : DescriptorSetLayoutCreateFlags.None, }; gd.Api.CreateDescriptorSetLayout(device, descriptorSetLayoutCreateInfo, null, out layouts[setIndex]).ThrowOnError(); @@ -72,11 +72,11 @@ namespace Ryujinx.Graphics.Vulkan fixed (DescriptorSetLayout* pLayouts = layouts) { - var pipelineLayoutCreateInfo = new PipelineLayoutCreateInfo() + var pipelineLayoutCreateInfo = new PipelineLayoutCreateInfo { SType = StructureType.PipelineLayoutCreateInfo, PSetLayouts = pLayouts, - SetLayoutCount = (uint)layouts.Length + SetLayoutCount = (uint)layouts.Length, }; gd.Api.CreatePipelineLayout(device, &pipelineLayoutCreateInfo, null, out layout).ThrowOnError(); diff --git a/src/Ryujinx.Graphics.Vulkan/PipelineState.cs b/src/Ryujinx.Graphics.Vulkan/PipelineState.cs index 7e803913f..cc9af5b6d 100644 --- a/src/Ryujinx.Graphics.Vulkan/PipelineState.cs +++ b/src/Ryujinx.Graphics.Vulkan/PipelineState.cs @@ -13,301 +13,301 @@ namespace Ryujinx.Graphics.Vulkan public float LineWidth { - get => BitConverter.Int32BitsToSingle((int)((Internal.Id0 >> 0) & 0xFFFFFFFF)); + readonly get => BitConverter.Int32BitsToSingle((int)((Internal.Id0 >> 0) & 0xFFFFFFFF)); set => Internal.Id0 = (Internal.Id0 & 0xFFFFFFFF00000000) | ((ulong)(uint)BitConverter.SingleToInt32Bits(value) << 0); } public float DepthBiasClamp { - get => BitConverter.Int32BitsToSingle((int)((Internal.Id0 >> 32) & 0xFFFFFFFF)); + readonly get => BitConverter.Int32BitsToSingle((int)((Internal.Id0 >> 32) & 0xFFFFFFFF)); set => Internal.Id0 = (Internal.Id0 & 0xFFFFFFFF) | ((ulong)(uint)BitConverter.SingleToInt32Bits(value) << 32); } public float DepthBiasConstantFactor { - get => BitConverter.Int32BitsToSingle((int)((Internal.Id1 >> 0) & 0xFFFFFFFF)); + readonly get => BitConverter.Int32BitsToSingle((int)((Internal.Id1 >> 0) & 0xFFFFFFFF)); set => Internal.Id1 = (Internal.Id1 & 0xFFFFFFFF00000000) | ((ulong)(uint)BitConverter.SingleToInt32Bits(value) << 0); } public float DepthBiasSlopeFactor { - get => BitConverter.Int32BitsToSingle((int)((Internal.Id1 >> 32) & 0xFFFFFFFF)); + readonly get => BitConverter.Int32BitsToSingle((int)((Internal.Id1 >> 32) & 0xFFFFFFFF)); set => Internal.Id1 = (Internal.Id1 & 0xFFFFFFFF) | ((ulong)(uint)BitConverter.SingleToInt32Bits(value) << 32); } public uint StencilFrontCompareMask { - get => (uint)((Internal.Id2 >> 0) & 0xFFFFFFFF); + readonly get => (uint)((Internal.Id2 >> 0) & 0xFFFFFFFF); set => Internal.Id2 = (Internal.Id2 & 0xFFFFFFFF00000000) | ((ulong)value << 0); } public uint StencilFrontWriteMask { - get => (uint)((Internal.Id2 >> 32) & 0xFFFFFFFF); + readonly get => (uint)((Internal.Id2 >> 32) & 0xFFFFFFFF); set => Internal.Id2 = (Internal.Id2 & 0xFFFFFFFF) | ((ulong)value << 32); } public uint StencilFrontReference { - get => (uint)((Internal.Id3 >> 0) & 0xFFFFFFFF); + readonly get => (uint)((Internal.Id3 >> 0) & 0xFFFFFFFF); set => Internal.Id3 = (Internal.Id3 & 0xFFFFFFFF00000000) | ((ulong)value << 0); } public uint StencilBackCompareMask { - get => (uint)((Internal.Id3 >> 32) & 0xFFFFFFFF); + readonly get => (uint)((Internal.Id3 >> 32) & 0xFFFFFFFF); set => Internal.Id3 = (Internal.Id3 & 0xFFFFFFFF) | ((ulong)value << 32); } public uint StencilBackWriteMask { - get => (uint)((Internal.Id4 >> 0) & 0xFFFFFFFF); + readonly get => (uint)((Internal.Id4 >> 0) & 0xFFFFFFFF); set => Internal.Id4 = (Internal.Id4 & 0xFFFFFFFF00000000) | ((ulong)value << 0); } public uint StencilBackReference { - get => (uint)((Internal.Id4 >> 32) & 0xFFFFFFFF); + readonly get => (uint)((Internal.Id4 >> 32) & 0xFFFFFFFF); set => Internal.Id4 = (Internal.Id4 & 0xFFFFFFFF) | ((ulong)value << 32); } public float MinDepthBounds { - get => BitConverter.Int32BitsToSingle((int)((Internal.Id5 >> 0) & 0xFFFFFFFF)); + readonly get => BitConverter.Int32BitsToSingle((int)((Internal.Id5 >> 0) & 0xFFFFFFFF)); set => Internal.Id5 = (Internal.Id5 & 0xFFFFFFFF00000000) | ((ulong)(uint)BitConverter.SingleToInt32Bits(value) << 0); } public float MaxDepthBounds { - get => BitConverter.Int32BitsToSingle((int)((Internal.Id5 >> 32) & 0xFFFFFFFF)); + readonly get => BitConverter.Int32BitsToSingle((int)((Internal.Id5 >> 32) & 0xFFFFFFFF)); set => Internal.Id5 = (Internal.Id5 & 0xFFFFFFFF) | ((ulong)(uint)BitConverter.SingleToInt32Bits(value) << 32); } public PolygonMode PolygonMode { - get => (PolygonMode)((Internal.Id6 >> 0) & 0x3FFFFFFF); + readonly get => (PolygonMode)((Internal.Id6 >> 0) & 0x3FFFFFFF); set => Internal.Id6 = (Internal.Id6 & 0xFFFFFFFFC0000000) | ((ulong)value << 0); } public uint StagesCount { - get => (byte)((Internal.Id6 >> 30) & 0xFF); + readonly get => (byte)((Internal.Id6 >> 30) & 0xFF); set => Internal.Id6 = (Internal.Id6 & 0xFFFFFFC03FFFFFFF) | ((ulong)value << 30); } public uint VertexAttributeDescriptionsCount { - get => (byte)((Internal.Id6 >> 38) & 0xFF); + readonly get => (byte)((Internal.Id6 >> 38) & 0xFF); set => Internal.Id6 = (Internal.Id6 & 0xFFFFC03FFFFFFFFF) | ((ulong)value << 38); } public uint VertexBindingDescriptionsCount { - get => (byte)((Internal.Id6 >> 46) & 0xFF); + readonly get => (byte)((Internal.Id6 >> 46) & 0xFF); set => Internal.Id6 = (Internal.Id6 & 0xFFC03FFFFFFFFFFF) | ((ulong)value << 46); } public uint ViewportsCount { - get => (byte)((Internal.Id6 >> 54) & 0xFF); + readonly get => (byte)((Internal.Id6 >> 54) & 0xFF); set => Internal.Id6 = (Internal.Id6 & 0xC03FFFFFFFFFFFFF) | ((ulong)value << 54); } public uint ScissorsCount { - get => (byte)((Internal.Id7 >> 0) & 0xFF); + readonly get => (byte)((Internal.Id7 >> 0) & 0xFF); set => Internal.Id7 = (Internal.Id7 & 0xFFFFFFFFFFFFFF00) | ((ulong)value << 0); } public uint ColorBlendAttachmentStateCount { - get => (byte)((Internal.Id7 >> 8) & 0xFF); + readonly get => (byte)((Internal.Id7 >> 8) & 0xFF); set => Internal.Id7 = (Internal.Id7 & 0xFFFFFFFFFFFF00FF) | ((ulong)value << 8); } public PrimitiveTopology Topology { - get => (PrimitiveTopology)((Internal.Id7 >> 16) & 0xF); + readonly get => (PrimitiveTopology)((Internal.Id7 >> 16) & 0xF); set => Internal.Id7 = (Internal.Id7 & 0xFFFFFFFFFFF0FFFF) | ((ulong)value << 16); } public LogicOp LogicOp { - get => (LogicOp)((Internal.Id7 >> 20) & 0xF); + readonly get => (LogicOp)((Internal.Id7 >> 20) & 0xF); set => Internal.Id7 = (Internal.Id7 & 0xFFFFFFFFFF0FFFFF) | ((ulong)value << 20); } public CompareOp DepthCompareOp { - get => (CompareOp)((Internal.Id7 >> 24) & 0x7); + readonly get => (CompareOp)((Internal.Id7 >> 24) & 0x7); set => Internal.Id7 = (Internal.Id7 & 0xFFFFFFFFF8FFFFFF) | ((ulong)value << 24); } public StencilOp StencilFrontFailOp { - get => (StencilOp)((Internal.Id7 >> 27) & 0x7); + readonly get => (StencilOp)((Internal.Id7 >> 27) & 0x7); set => Internal.Id7 = (Internal.Id7 & 0xFFFFFFFFC7FFFFFF) | ((ulong)value << 27); } public StencilOp StencilFrontPassOp { - get => (StencilOp)((Internal.Id7 >> 30) & 0x7); + readonly get => (StencilOp)((Internal.Id7 >> 30) & 0x7); set => Internal.Id7 = (Internal.Id7 & 0xFFFFFFFE3FFFFFFF) | ((ulong)value << 30); } public StencilOp StencilFrontDepthFailOp { - get => (StencilOp)((Internal.Id7 >> 33) & 0x7); + readonly get => (StencilOp)((Internal.Id7 >> 33) & 0x7); set => Internal.Id7 = (Internal.Id7 & 0xFFFFFFF1FFFFFFFF) | ((ulong)value << 33); } public CompareOp StencilFrontCompareOp { - get => (CompareOp)((Internal.Id7 >> 36) & 0x7); + readonly get => (CompareOp)((Internal.Id7 >> 36) & 0x7); set => Internal.Id7 = (Internal.Id7 & 0xFFFFFF8FFFFFFFFF) | ((ulong)value << 36); } public StencilOp StencilBackFailOp { - get => (StencilOp)((Internal.Id7 >> 39) & 0x7); + readonly get => (StencilOp)((Internal.Id7 >> 39) & 0x7); set => Internal.Id7 = (Internal.Id7 & 0xFFFFFC7FFFFFFFFF) | ((ulong)value << 39); } public StencilOp StencilBackPassOp { - get => (StencilOp)((Internal.Id7 >> 42) & 0x7); + readonly get => (StencilOp)((Internal.Id7 >> 42) & 0x7); set => Internal.Id7 = (Internal.Id7 & 0xFFFFE3FFFFFFFFFF) | ((ulong)value << 42); } public StencilOp StencilBackDepthFailOp { - get => (StencilOp)((Internal.Id7 >> 45) & 0x7); + readonly get => (StencilOp)((Internal.Id7 >> 45) & 0x7); set => Internal.Id7 = (Internal.Id7 & 0xFFFF1FFFFFFFFFFF) | ((ulong)value << 45); } public CompareOp StencilBackCompareOp { - get => (CompareOp)((Internal.Id7 >> 48) & 0x7); + readonly get => (CompareOp)((Internal.Id7 >> 48) & 0x7); set => Internal.Id7 = (Internal.Id7 & 0xFFF8FFFFFFFFFFFF) | ((ulong)value << 48); } public CullModeFlags CullMode { - get => (CullModeFlags)((Internal.Id7 >> 51) & 0x3); + readonly get => (CullModeFlags)((Internal.Id7 >> 51) & 0x3); set => Internal.Id7 = (Internal.Id7 & 0xFFE7FFFFFFFFFFFF) | ((ulong)value << 51); } public bool PrimitiveRestartEnable { - get => ((Internal.Id7 >> 53) & 0x1) != 0UL; + readonly get => ((Internal.Id7 >> 53) & 0x1) != 0UL; set => Internal.Id7 = (Internal.Id7 & 0xFFDFFFFFFFFFFFFF) | ((value ? 1UL : 0UL) << 53); } public bool DepthClampEnable { - get => ((Internal.Id7 >> 54) & 0x1) != 0UL; + readonly get => ((Internal.Id7 >> 54) & 0x1) != 0UL; set => Internal.Id7 = (Internal.Id7 & 0xFFBFFFFFFFFFFFFF) | ((value ? 1UL : 0UL) << 54); } public bool RasterizerDiscardEnable { - get => ((Internal.Id7 >> 55) & 0x1) != 0UL; + readonly get => ((Internal.Id7 >> 55) & 0x1) != 0UL; set => Internal.Id7 = (Internal.Id7 & 0xFF7FFFFFFFFFFFFF) | ((value ? 1UL : 0UL) << 55); } public FrontFace FrontFace { - get => (FrontFace)((Internal.Id7 >> 56) & 0x1); + readonly get => (FrontFace)((Internal.Id7 >> 56) & 0x1); set => Internal.Id7 = (Internal.Id7 & 0xFEFFFFFFFFFFFFFF) | ((ulong)value << 56); } public bool DepthBiasEnable { - get => ((Internal.Id7 >> 57) & 0x1) != 0UL; + readonly get => ((Internal.Id7 >> 57) & 0x1) != 0UL; set => Internal.Id7 = (Internal.Id7 & 0xFDFFFFFFFFFFFFFF) | ((value ? 1UL : 0UL) << 57); } public bool DepthTestEnable { - get => ((Internal.Id7 >> 58) & 0x1) != 0UL; + readonly get => ((Internal.Id7 >> 58) & 0x1) != 0UL; set => Internal.Id7 = (Internal.Id7 & 0xFBFFFFFFFFFFFFFF) | ((value ? 1UL : 0UL) << 58); } public bool DepthWriteEnable { - get => ((Internal.Id7 >> 59) & 0x1) != 0UL; + readonly get => ((Internal.Id7 >> 59) & 0x1) != 0UL; set => Internal.Id7 = (Internal.Id7 & 0xF7FFFFFFFFFFFFFF) | ((value ? 1UL : 0UL) << 59); } public bool DepthBoundsTestEnable { - get => ((Internal.Id7 >> 60) & 0x1) != 0UL; + readonly get => ((Internal.Id7 >> 60) & 0x1) != 0UL; set => Internal.Id7 = (Internal.Id7 & 0xEFFFFFFFFFFFFFFF) | ((value ? 1UL : 0UL) << 60); } public bool StencilTestEnable { - get => ((Internal.Id7 >> 61) & 0x1) != 0UL; + readonly get => ((Internal.Id7 >> 61) & 0x1) != 0UL; set => Internal.Id7 = (Internal.Id7 & 0xDFFFFFFFFFFFFFFF) | ((value ? 1UL : 0UL) << 61); } public bool LogicOpEnable { - get => ((Internal.Id7 >> 62) & 0x1) != 0UL; + readonly get => ((Internal.Id7 >> 62) & 0x1) != 0UL; set => Internal.Id7 = (Internal.Id7 & 0xBFFFFFFFFFFFFFFF) | ((value ? 1UL : 0UL) << 62); } public bool HasDepthStencil { - get => ((Internal.Id7 >> 63) & 0x1) != 0UL; + readonly get => ((Internal.Id7 >> 63) & 0x1) != 0UL; set => Internal.Id7 = (Internal.Id7 & 0x7FFFFFFFFFFFFFFF) | ((value ? 1UL : 0UL) << 63); } public uint PatchControlPoints { - get => (uint)((Internal.Id8 >> 0) & 0xFFFFFFFF); + readonly get => (uint)((Internal.Id8 >> 0) & 0xFFFFFFFF); set => Internal.Id8 = (Internal.Id8 & 0xFFFFFFFF00000000) | ((ulong)value << 0); } public uint SamplesCount { - get => (uint)((Internal.Id8 >> 32) & 0xFFFFFFFF); + readonly get => (uint)((Internal.Id8 >> 32) & 0xFFFFFFFF); set => Internal.Id8 = (Internal.Id8 & 0xFFFFFFFF) | ((ulong)value << 32); } public bool AlphaToCoverageEnable { - get => ((Internal.Id9 >> 0) & 0x1) != 0UL; + readonly get => ((Internal.Id9 >> 0) & 0x1) != 0UL; set => Internal.Id9 = (Internal.Id9 & 0xFFFFFFFFFFFFFFFE) | ((value ? 1UL : 0UL) << 0); } public bool AlphaToOneEnable { - get => ((Internal.Id9 >> 1) & 0x1) != 0UL; + readonly get => ((Internal.Id9 >> 1) & 0x1) != 0UL; set => Internal.Id9 = (Internal.Id9 & 0xFFFFFFFFFFFFFFFD) | ((value ? 1UL : 0UL) << 1); } public bool AdvancedBlendSrcPreMultiplied { - get => ((Internal.Id9 >> 2) & 0x1) != 0UL; + readonly get => ((Internal.Id9 >> 2) & 0x1) != 0UL; set => Internal.Id9 = (Internal.Id9 & 0xFFFFFFFFFFFFFFFB) | ((value ? 1UL : 0UL) << 2); } public bool AdvancedBlendDstPreMultiplied { - get => ((Internal.Id9 >> 3) & 0x1) != 0UL; + readonly get => ((Internal.Id9 >> 3) & 0x1) != 0UL; set => Internal.Id9 = (Internal.Id9 & 0xFFFFFFFFFFFFFFF7) | ((value ? 1UL : 0UL) << 3); } public BlendOverlapEXT AdvancedBlendOverlap { - get => (BlendOverlapEXT)((Internal.Id9 >> 4) & 0x3); + readonly get => (BlendOverlapEXT)((Internal.Id9 >> 4) & 0x3); set => Internal.Id9 = (Internal.Id9 & 0xFFFFFFFFFFFFFFCF) | ((ulong)value << 4); } public bool DepthMode { - get => ((Internal.Id9 >> 6) & 0x1) != 0UL; + readonly get => ((Internal.Id9 >> 6) & 0x1) != 0UL; set => Internal.Id9 = (Internal.Id9 & 0xFFFFFFFFFFFFFFBF) | ((value ? 1UL : 0UL) << 6); } @@ -325,10 +325,10 @@ namespace Ryujinx.Graphics.Vulkan for (int index = 0; index < Constants.MaxShaderStages; index++) { - StageRequiredSubgroupSizes[index] = new PipelineShaderStageRequiredSubgroupSizeCreateInfoEXT() + StageRequiredSubgroupSizes[index] = new PipelineShaderStageRequiredSubgroupSizeCreateInfoEXT { SType = StructureType.PipelineShaderStageRequiredSubgroupSizeCreateInfoExt, - RequiredSubgroupSize = RequiredSubgroupSize + RequiredSubgroupSize = RequiredSubgroupSize, }; } @@ -357,12 +357,12 @@ namespace Ryujinx.Graphics.Vulkan UpdateStageRequiredSubgroupSizes(gd, 1); } - var pipelineCreateInfo = new ComputePipelineCreateInfo() + var pipelineCreateInfo = new ComputePipelineCreateInfo { SType = StructureType.ComputePipelineCreateInfo, Stage = Stages[0], BasePipelineIndex = -1, - Layout = PipelineLayout + Layout = PipelineLayout, }; Pipeline pipelineHandle = default; @@ -431,7 +431,7 @@ namespace Ryujinx.Graphics.Vulkan VertexAttributeDescriptionCount = VertexAttributeDescriptionsCount, PVertexAttributeDescriptions = isMoltenVk ? pVertexAttributeDescriptions2 : pVertexAttributeDescriptions, VertexBindingDescriptionCount = VertexBindingDescriptionsCount, - PVertexBindingDescriptions = pVertexBindingDescriptions + PVertexBindingDescriptions = pVertexBindingDescriptions, }; bool primitiveRestartEnable = PrimitiveRestartEnable; @@ -453,20 +453,20 @@ namespace Ryujinx.Graphics.Vulkan primitiveRestartEnable &= topologySupportsRestart; - var inputAssemblyState = new PipelineInputAssemblyStateCreateInfo() + var inputAssemblyState = new PipelineInputAssemblyStateCreateInfo { SType = StructureType.PipelineInputAssemblyStateCreateInfo, PrimitiveRestartEnable = primitiveRestartEnable, - Topology = Topology + Topology = Topology, }; - var tessellationState = new PipelineTessellationStateCreateInfo() + var tessellationState = new PipelineTessellationStateCreateInfo { SType = StructureType.PipelineTessellationStateCreateInfo, - PatchControlPoints = PatchControlPoints + PatchControlPoints = PatchControlPoints, }; - var rasterizationState = new PipelineRasterizationStateCreateInfo() + var rasterizationState = new PipelineRasterizationStateCreateInfo { SType = StructureType.PipelineRasterizationStateCreateInfo, DepthClampEnable = DepthClampEnable, @@ -478,24 +478,24 @@ namespace Ryujinx.Graphics.Vulkan DepthBiasEnable = DepthBiasEnable, DepthBiasClamp = DepthBiasClamp, DepthBiasConstantFactor = DepthBiasConstantFactor, - DepthBiasSlopeFactor = DepthBiasSlopeFactor + DepthBiasSlopeFactor = DepthBiasSlopeFactor, }; - var viewportState = new PipelineViewportStateCreateInfo() + var viewportState = new PipelineViewportStateCreateInfo { SType = StructureType.PipelineViewportStateCreateInfo, ViewportCount = ViewportsCount, PViewports = pViewports, ScissorCount = ScissorsCount, - PScissors = pScissors + PScissors = pScissors, }; if (gd.Capabilities.SupportsDepthClipControl) { - var viewportDepthClipControlState = new PipelineViewportDepthClipControlCreateInfoEXT() + var viewportDepthClipControlState = new PipelineViewportDepthClipControlCreateInfoEXT { SType = StructureType.PipelineViewportDepthClipControlCreateInfoExt, - NegativeOneToOne = DepthMode + NegativeOneToOne = DepthMode, }; viewportState.PNext = &viewportDepthClipControlState; @@ -508,7 +508,7 @@ namespace Ryujinx.Graphics.Vulkan RasterizationSamples = TextureStorage.ConvertToSampleCountFlags(gd.Capabilities.SupportedSampleCounts, SamplesCount), MinSampleShading = 1, AlphaToCoverageEnable = AlphaToCoverageEnable, - AlphaToOneEnable = AlphaToOneEnable + AlphaToOneEnable = AlphaToOneEnable, }; var stencilFront = new StencilOpState( @@ -529,7 +529,7 @@ namespace Ryujinx.Graphics.Vulkan StencilBackWriteMask, StencilBackReference); - var depthStencilState = new PipelineDepthStencilStateCreateInfo() + var depthStencilState = new PipelineDepthStencilStateCreateInfo { SType = StructureType.PipelineDepthStencilStateCreateInfo, DepthTestEnable = DepthTestEnable, @@ -540,7 +540,7 @@ namespace Ryujinx.Graphics.Vulkan Front = stencilFront, Back = stencilBack, MinDepthBounds = MinDepthBounds, - MaxDepthBounds = MaxDepthBounds + MaxDepthBounds = MaxDepthBounds, }; uint blendEnables = 0; @@ -564,13 +564,13 @@ namespace Ryujinx.Graphics.Vulkan } } - var colorBlendState = new PipelineColorBlendStateCreateInfo() + var colorBlendState = new PipelineColorBlendStateCreateInfo { SType = StructureType.PipelineColorBlendStateCreateInfo, LogicOpEnable = LogicOpEnable, LogicOp = LogicOp, AttachmentCount = ColorBlendAttachmentStateCount, - PAttachments = pColorBlendAttachmentState + PAttachments = pColorBlendAttachmentState, }; PipelineColorBlendAdvancedStateCreateInfoEXT colorBlendAdvancedState; @@ -579,12 +579,12 @@ namespace Ryujinx.Graphics.Vulkan !AdvancedBlendDstPreMultiplied || AdvancedBlendOverlap != BlendOverlapEXT.UncorrelatedExt) { - colorBlendAdvancedState = new PipelineColorBlendAdvancedStateCreateInfoEXT() + colorBlendAdvancedState = new PipelineColorBlendAdvancedStateCreateInfoEXT { SType = StructureType.PipelineColorBlendAdvancedStateCreateInfoExt, SrcPremultiplied = AdvancedBlendSrcPreMultiplied, DstPremultiplied = AdvancedBlendDstPreMultiplied, - BlendOverlap = AdvancedBlendOverlap + BlendOverlap = AdvancedBlendOverlap, }; colorBlendState.PNext = &colorBlendAdvancedState; @@ -609,11 +609,11 @@ namespace Ryujinx.Graphics.Vulkan dynamicStates[8] = DynamicState.VertexInputBindingStrideExt; } - var pipelineDynamicStateCreateInfo = new PipelineDynamicStateCreateInfo() + var pipelineDynamicStateCreateInfo = new PipelineDynamicStateCreateInfo { SType = StructureType.PipelineDynamicStateCreateInfo, DynamicStateCount = (uint)dynamicStatesCount, - PDynamicStates = dynamicStates + PDynamicStates = dynamicStates, }; if (gd.Capabilities.SupportsSubgroupSizeControl) @@ -621,7 +621,7 @@ namespace Ryujinx.Graphics.Vulkan UpdateStageRequiredSubgroupSizes(gd, (int)StagesCount); } - var pipelineCreateInfo = new GraphicsPipelineCreateInfo() + var pipelineCreateInfo = new GraphicsPipelineCreateInfo { SType = StructureType.GraphicsPipelineCreateInfo, StageCount = StagesCount, @@ -637,7 +637,7 @@ namespace Ryujinx.Graphics.Vulkan PDynamicState = &pipelineDynamicStateCreateInfo, Layout = PipelineLayout, RenderPass = renderPass, - BasePipelineIndex = -1 + BasePipelineIndex = -1, }; gd.Api.CreateGraphicsPipelines(device, cache, 1, &pipelineCreateInfo, null, &pipelineHandle).ThrowOnError(); @@ -659,7 +659,7 @@ namespace Ryujinx.Graphics.Vulkan return pipeline; } - private unsafe void UpdateStageRequiredSubgroupSizes(VulkanRenderer gd, int count) + private readonly unsafe void UpdateStageRequiredSubgroupSizes(VulkanRenderer gd, int count) { for (int index = 0; index < count; index++) { @@ -728,7 +728,7 @@ namespace Ryujinx.Graphics.Vulkan return -1; } - public void Dispose() + public readonly void Dispose() { Stages.Dispose(); StageRequiredSubgroupSizes.Dispose(); diff --git a/src/Ryujinx.Graphics.Vulkan/PipelineUid.cs b/src/Ryujinx.Graphics.Vulkan/PipelineUid.cs index f404be744..460c27d8b 100644 --- a/src/Ryujinx.Graphics.Vulkan/PipelineUid.cs +++ b/src/Ryujinx.Graphics.Vulkan/PipelineUid.cs @@ -22,12 +22,10 @@ namespace Ryujinx.Graphics.Vulkan public ulong Id8; public ulong Id9; - private uint VertexAttributeDescriptionsCount => (byte)((Id6 >> 38) & 0xFF); - private uint VertexBindingDescriptionsCount => (byte)((Id6 >> 46) & 0xFF); - private uint ViewportsCount => (byte)((Id6 >> 54) & 0xFF); - private uint ScissorsCount => (byte)(Id7 & 0xFF); - private uint ColorBlendAttachmentStateCount => (byte)((Id7 >> 8) & 0xFF); - private bool HasDepthStencil => ((Id7 >> 63) & 0x1) != 0UL; + private readonly uint VertexAttributeDescriptionsCount => (byte)((Id6 >> 38) & 0xFF); + private readonly uint VertexBindingDescriptionsCount => (byte)((Id6 >> 46) & 0xFF); + private readonly uint ColorBlendAttachmentStateCount => (byte)((Id7 >> 8) & 0xFF); + private readonly bool HasDepthStencil => ((Id7 >> 63) & 0x1) != 0UL; public Array32 VertexAttributeDescriptions; public Array33 VertexBindingDescriptions; @@ -37,7 +35,7 @@ namespace Ryujinx.Graphics.Vulkan public Array9 AttachmentFormats; public uint AttachmentIntegerFormatMask; - public override bool Equals(object obj) + public readonly override bool Equals(object obj) { return obj is PipelineUid other && Equals(other); } @@ -76,7 +74,7 @@ namespace Ryujinx.Graphics.Vulkan private static bool SequenceEqual(ReadOnlySpan x, ReadOnlySpan y, uint count) where T : unmanaged { - return MemoryMarshal.Cast(x.Slice(0, (int)count)).SequenceEqual(MemoryMarshal.Cast(y.Slice(0, (int)count))); + return MemoryMarshal.Cast(x[..(int)count]).SequenceEqual(MemoryMarshal.Cast(y[..(int)count])); } public override int GetHashCode() diff --git a/src/Ryujinx.Graphics.Vulkan/Queries/BufferedQuery.cs b/src/Ryujinx.Graphics.Vulkan/Queries/BufferedQuery.cs index 861155a30..8d4fdc196 100644 --- a/src/Ryujinx.Graphics.Vulkan/Queries/BufferedQuery.cs +++ b/src/Ryujinx.Graphics.Vulkan/Queries/BufferedQuery.cs @@ -23,10 +23,10 @@ namespace Ryujinx.Graphics.Vulkan.Queries private readonly BufferHolder _buffer; private readonly IntPtr _bufferMap; private readonly CounterType _type; - private bool _result32Bit; - private bool _isSupported; + private readonly bool _result32Bit; + private readonly bool _isSupported; - private long _defaultValue; + private readonly long _defaultValue; private int? _resetSequence; public unsafe BufferedQuery(VulkanRenderer gd, Device device, PipelineFull pipeline, CounterType type, bool result32Bit) @@ -44,12 +44,12 @@ namespace Ryujinx.Graphics.Vulkan.Queries QueryPipelineStatisticFlags flags = type == CounterType.PrimitivesGenerated ? QueryPipelineStatisticFlags.GeometryShaderPrimitivesBit : 0; - var queryPoolCreateInfo = new QueryPoolCreateInfo() + var queryPoolCreateInfo = new QueryPoolCreateInfo { SType = StructureType.QueryPoolCreateInfo, QueryCount = 1, QueryType = GetQueryType(type), - PipelineStatistics = flags + PipelineStatistics = flags, }; gd.Api.CreateQueryPool(device, queryPoolCreateInfo, null, out _queryPool).ThrowOnError(); @@ -63,14 +63,14 @@ namespace Ryujinx.Graphics.Vulkan.Queries _buffer = buffer; } - private bool QueryTypeSupported(VulkanRenderer gd, CounterType type) + private static bool QueryTypeSupported(VulkanRenderer gd, CounterType type) { return type switch { CounterType.SamplesPassed => true, CounterType.PrimitivesGenerated => gd.Capabilities.SupportsPipelineStatisticsQuery, CounterType.TransformFeedbackPrimitivesWritten => gd.Capabilities.SupportsTransformFeedbackQueries, - _ => false + _ => false, }; } @@ -81,7 +81,7 @@ namespace Ryujinx.Graphics.Vulkan.Queries CounterType.SamplesPassed => QueryType.Occlusion, CounterType.PrimitivesGenerated => QueryType.PipelineStatistics, CounterType.TransformFeedbackPrimitivesWritten => QueryType.TransformFeedbackStreamExt, - _ => QueryType.Occlusion + _ => QueryType.Occlusion, }; } @@ -107,7 +107,7 @@ namespace Ryujinx.Graphics.Vulkan.Queries _resetSequence = null; } - public unsafe void End(bool withResult) + public void End(bool withResult) { if (_isSupported) { diff --git a/src/Ryujinx.Graphics.Vulkan/Queries/CounterQueue.cs b/src/Ryujinx.Graphics.Vulkan/Queries/CounterQueue.cs index 2fdddaeab..724588d57 100644 --- a/src/Ryujinx.Graphics.Vulkan/Queries/CounterQueue.cs +++ b/src/Ryujinx.Graphics.Vulkan/Queries/CounterQueue.cs @@ -18,7 +18,7 @@ namespace Ryujinx.Graphics.Vulkan.Queries public CounterType Type { get; } public bool Disposed { get; private set; } - private Queue _events = new Queue(); + private readonly Queue _events = new(); private CounterQueueEvent _current; private ulong _accumulatedCounter; @@ -26,12 +26,12 @@ namespace Ryujinx.Graphics.Vulkan.Queries private readonly object _lock = new(); - private Queue _queryPool; - private AutoResetEvent _queuedEvent = new AutoResetEvent(false); - private AutoResetEvent _wakeSignal = new AutoResetEvent(false); - private AutoResetEvent _eventConsumed = new AutoResetEvent(false); + private readonly Queue _queryPool; + private readonly AutoResetEvent _queuedEvent = new(false); + private readonly AutoResetEvent _wakeSignal = new(false); + private readonly AutoResetEvent _eventConsumed = new(false); - private Thread _consumerThread; + private readonly Thread _consumerThread; public int ResetSequence { get; private set; } @@ -116,10 +116,8 @@ namespace Ryujinx.Graphics.Vulkan.Queries BufferedQuery result = _queryPool.Dequeue(); return result; } - else - { - return new BufferedQuery(_gd, _device, _pipeline, Type, _gd.IsAmdWindows); - } + + return new BufferedQuery(_gd, _device, _pipeline, Type, _gd.IsAmdWindows); } } diff --git a/src/Ryujinx.Graphics.Vulkan/Queries/CounterQueueEvent.cs b/src/Ryujinx.Graphics.Vulkan/Queries/CounterQueueEvent.cs index 9d0a674b4..77d9a3557 100644 --- a/src/Ryujinx.Graphics.Vulkan/Queries/CounterQueueEvent.cs +++ b/src/Ryujinx.Graphics.Vulkan/Queries/CounterQueueEvent.cs @@ -16,10 +16,10 @@ namespace Ryujinx.Graphics.Vulkan.Queries public ulong DrawIndex { get; } - private CounterQueue _queue; - private BufferedQuery _counter; + private readonly CounterQueue _queue; + private readonly BufferedQuery _counter; - private bool _hostAccessReserved = false; + private bool _hostAccessReserved; private int _refCount = 1; // Starts with a reference from the counter queue. private readonly object _lock = new(); diff --git a/src/Ryujinx.Graphics.Vulkan/ResourceBindingSegment.cs b/src/Ryujinx.Graphics.Vulkan/ResourceBindingSegment.cs index feeba4744..9de46e614 100644 --- a/src/Ryujinx.Graphics.Vulkan/ResourceBindingSegment.cs +++ b/src/Ryujinx.Graphics.Vulkan/ResourceBindingSegment.cs @@ -19,4 +19,4 @@ namespace Ryujinx.Graphics.Vulkan Access = access; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Vulkan/ResourceLayoutBuilder.cs b/src/Ryujinx.Graphics.Vulkan/ResourceLayoutBuilder.cs index eac0d6c20..0b87d8000 100644 --- a/src/Ryujinx.Graphics.Vulkan/ResourceLayoutBuilder.cs +++ b/src/Ryujinx.Graphics.Vulkan/ResourceLayoutBuilder.cs @@ -31,7 +31,7 @@ namespace Ryujinx.Graphics.Vulkan ResourceType.StorageBuffer => PipelineBase.StorageSetIndex, ResourceType.TextureAndSampler or ResourceType.BufferTexture => PipelineBase.TextureSetIndex, ResourceType.Image or ResourceType.BufferImage => PipelineBase.ImageSetIndex, - _ => throw new ArgumentException($"Invalid resource type \"{type}\".") + _ => throw new ArgumentException($"Invalid resource type \"{type}\"."), }; ResourceAccess access = IsReadOnlyType(type) ? ResourceAccess.Read : ResourceAccess.ReadWrite; @@ -64,4 +64,4 @@ namespace Ryujinx.Graphics.Vulkan return new ResourceLayout(descriptors.AsReadOnly(), usages.AsReadOnly()); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Vulkan/SamplerHolder.cs b/src/Ryujinx.Graphics.Vulkan/SamplerHolder.cs index a95e4dba2..6e9f408f3 100644 --- a/src/Ryujinx.Graphics.Vulkan/SamplerHolder.cs +++ b/src/Ryujinx.Graphics.Vulkan/SamplerHolder.cs @@ -1,5 +1,6 @@ using Ryujinx.Graphics.GAL; using Silk.NET.Vulkan; +using SamplerCreateInfo = Ryujinx.Graphics.GAL.SamplerCreateInfo; namespace Ryujinx.Graphics.Vulkan { @@ -8,13 +9,13 @@ namespace Ryujinx.Graphics.Vulkan private readonly VulkanRenderer _gd; private readonly Auto _sampler; - public unsafe SamplerHolder(VulkanRenderer gd, Device device, GAL.SamplerCreateInfo info) + public unsafe SamplerHolder(VulkanRenderer gd, Device device, SamplerCreateInfo info) { _gd = gd; gd.Samplers.Add(this); - (Filter minFilter, SamplerMipmapMode mipFilter) = EnumConversion.Convert(info.MinFilter); + (Filter minFilter, SamplerMipmapMode mipFilter) = info.MinFilter.Convert(); float minLod = info.MinLod; float maxLod = info.MaxLod; @@ -27,7 +28,7 @@ namespace Ryujinx.Graphics.Vulkan var borderColor = GetConstrainedBorderColor(info.BorderColor, out var cantConstrain); - var samplerCreateInfo = new Silk.NET.Vulkan.SamplerCreateInfo() + var samplerCreateInfo = new Silk.NET.Vulkan.SamplerCreateInfo { SType = StructureType.SamplerCreateInfo, MagFilter = info.MagFilter.Convert(), @@ -44,7 +45,7 @@ namespace Ryujinx.Graphics.Vulkan MinLod = minLod, MaxLod = maxLod, BorderColor = borderColor, - UnnormalizedCoordinates = false // TODO: Use unnormalized coordinates. + UnnormalizedCoordinates = false, // TODO: Use unnormalized coordinates. }; SamplerCustomBorderColorCreateInfoEXT customBorderColor; @@ -57,10 +58,10 @@ namespace Ryujinx.Graphics.Vulkan info.BorderColor.Blue, info.BorderColor.Alpha); - customBorderColor = new SamplerCustomBorderColorCreateInfoEXT() + customBorderColor = new SamplerCustomBorderColorCreateInfoEXT { SType = StructureType.SamplerCustomBorderColorCreateInfoExt, - CustomBorderColor = color + CustomBorderColor = color, }; samplerCreateInfo.PNext = &customBorderColor; @@ -86,7 +87,8 @@ namespace Ryujinx.Graphics.Vulkan cantConstrain = false; return BorderColor.FloatOpaqueBlack; } - else if (a == 0f) + + if (a == 0f) { cantConstrain = false; return BorderColor.FloatTransparentBlack; diff --git a/src/Ryujinx.Graphics.Vulkan/SemaphoreHolder.cs b/src/Ryujinx.Graphics.Vulkan/SemaphoreHolder.cs index aa1b0eafe..2dd17c51c 100644 --- a/src/Ryujinx.Graphics.Vulkan/SemaphoreHolder.cs +++ b/src/Ryujinx.Graphics.Vulkan/SemaphoreHolder.cs @@ -11,16 +11,16 @@ namespace Ryujinx.Graphics.Vulkan private readonly Device _device; private VkSemaphore _semaphore; private int _referenceCount; - public bool _disposed; + private bool _disposed; public unsafe SemaphoreHolder(Vk api, Device device) { _api = api; _device = device; - var semaphoreCreateInfo = new SemaphoreCreateInfo() + var semaphoreCreateInfo = new SemaphoreCreateInfo { - SType = StructureType.SemaphoreCreateInfo + SType = StructureType.SemaphoreCreateInfo, }; api.CreateSemaphore(device, in semaphoreCreateInfo, null, out _semaphore).ThrowOnError(); diff --git a/src/Ryujinx.Graphics.Vulkan/Shader.cs b/src/Ryujinx.Graphics.Vulkan/Shader.cs index d853bb04c..2229785d8 100644 --- a/src/Ryujinx.Graphics.Vulkan/Shader.cs +++ b/src/Ryujinx.Graphics.Vulkan/Shader.cs @@ -13,7 +13,7 @@ namespace Ryujinx.Graphics.Vulkan { // The shaderc.net dependency's Options constructor and dispose are not thread safe. // Take this lock when using them. - private static object _shaderOptionsLock = new object(); + private static readonly object _shaderOptionsLock = new(); private static readonly IntPtr _ptrMainEntryPointName = Marshal.StringToHGlobalAnsi("main"); @@ -57,11 +57,11 @@ namespace Ryujinx.Graphics.Vulkan fixed (byte* pCode = spirv) { - var shaderModuleCreateInfo = new ShaderModuleCreateInfo() + var shaderModuleCreateInfo = new ShaderModuleCreateInfo { SType = StructureType.ShaderModuleCreateInfo, CodeSize = (uint)spirv.Length, - PCode = (uint*)pCode + PCode = (uint*)pCode, }; api.CreateShaderModule(device, shaderModuleCreateInfo, null, out _module).ThrowOnError(); @@ -80,12 +80,12 @@ namespace Ryujinx.Graphics.Vulkan options = new Options(false) { SourceLanguage = SourceLanguage.Glsl, - TargetSpirVVersion = new SpirVVersion(1, 5) + TargetSpirVVersion = new SpirVVersion(1, 5), }; } options.SetTargetEnvironment(TargetEnvironment.Vulkan, EnvironmentVersion.Vulkan_1_2); - Compiler compiler = new Compiler(options); + Compiler compiler = new(options); var scr = compiler.Compile(glsl, "Ryu", GetShaderCShaderStage(stage)); lock (_shaderOptionsLock) @@ -104,7 +104,7 @@ namespace Ryujinx.Graphics.Vulkan byte[] code = new byte[(scr.CodeLength + 3) & ~3]; - spirvBytes.CopyTo(code.AsSpan().Slice(0, (int)scr.CodeLength)); + spirvBytes.CopyTo(code.AsSpan()[..(int)scr.CodeLength]); return code; } @@ -134,12 +134,12 @@ namespace Ryujinx.Graphics.Vulkan public unsafe PipelineShaderStageCreateInfo GetInfo() { - return new PipelineShaderStageCreateInfo() + return new PipelineShaderStageCreateInfo { SType = StructureType.PipelineShaderStageCreateInfo, Stage = _stage, Module = _module, - PName = (byte*)_ptrMainEntryPointName + PName = (byte*)_ptrMainEntryPointName, }; } diff --git a/src/Ryujinx.Graphics.Vulkan/ShaderCollection.cs b/src/Ryujinx.Graphics.Vulkan/ShaderCollection.cs index 2a3f86579..1e56d1e89 100644 --- a/src/Ryujinx.Graphics.Vulkan/ShaderCollection.cs +++ b/src/Ryujinx.Graphics.Vulkan/ShaderCollection.cs @@ -47,13 +47,13 @@ namespace Ryujinx.Graphics.Vulkan private HashTableSlim> _graphicsPipelineCache; private HashTableSlim> _computePipelineCache; - private VulkanRenderer _gd; + private readonly VulkanRenderer _gd; private Device _device; private bool _initialized; private ProgramPipelineState _state; private DisposableRenderPass _dummyRenderPass; - private Task _compileTask; + private readonly Task _compileTask; private bool _firstBackgroundUse; public ShaderCollection( @@ -94,7 +94,7 @@ namespace Ryujinx.Graphics.Vulkan ShaderStageFlags.GeometryBit => 2, ShaderStageFlags.TessellationControlBit => 3, ShaderStageFlags.TessellationEvaluationBit => 4, - _ => 0 + _ => 0, }; if (shader.StageFlags == ShaderStageFlags.ComputeBit) @@ -143,7 +143,7 @@ namespace Ryujinx.Graphics.Vulkan for (int setIndex = 0; setIndex < sets.Count; setIndex++) { - List currentSegments = new List(); + List currentSegments = new(); ResourceDescriptor currentDescriptor = default; int currentCount = 0; @@ -197,7 +197,7 @@ namespace Ryujinx.Graphics.Vulkan for (int setIndex = 0; setIndex < setUsages.Count; setIndex++) { - List currentSegments = new List(); + List currentSegments = new(); ResourceUsage currentUsage = default; int currentCount = 0; @@ -319,7 +319,7 @@ namespace Ryujinx.Graphics.Vulkan return _infos; } - protected unsafe DisposableRenderPass CreateDummyRenderPass() + protected DisposableRenderPass CreateDummyRenderPass() { if (_dummyRenderPass.Value.Handle != 0) { @@ -331,7 +331,7 @@ namespace Ryujinx.Graphics.Vulkan public void CreateBackgroundComputePipeline() { - PipelineState pipeline = new PipelineState(); + PipelineState pipeline = new(); pipeline.Initialize(); pipeline.Stages[0] = _shaders[0].GetInfo(); @@ -484,7 +484,7 @@ namespace Ryujinx.Graphics.Vulkan return _plce.GetNewDescriptorSetCollection(gd, commandBufferIndex, setIndex, out isNew); } - protected virtual unsafe void Dispose(bool disposing) + protected virtual void Dispose(bool disposing) { if (disposing) { diff --git a/src/Ryujinx.Graphics.Vulkan/Shaders/ShaderBinaries.cs b/src/Ryujinx.Graphics.Vulkan/Shaders/ShaderBinaries.cs index 69d1fa3ce..f6ca2432f 100644 --- a/src/Ryujinx.Graphics.Vulkan/Shaders/ShaderBinaries.cs +++ b/src/Ryujinx.Graphics.Vulkan/Shaders/ShaderBinaries.cs @@ -2,8 +2,7 @@ namespace Ryujinx.Graphics.Vulkan.Shaders { static class ShaderBinaries { - public static readonly byte[] ChangeBufferStrideShaderSource = new byte[] - { + public static readonly byte[] ChangeBufferStrideShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x05, 0x01, 0x00, 0x0A, 0x00, 0x0D, 0x00, 0x8E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x60, 0x11, 0x00, 0x00, 0x0B, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x4C, 0x53, 0x4C, @@ -242,11 +241,10 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0x06, 0x00, 0x00, 0x00, 0x8B, 0x00, 0x00, 0x00, 0x8A, 0x00, 0x00, 0x00, 0x3C, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x03, 0x00, 0x56, 0x00, 0x00, 0x00, 0x8B, 0x00, 0x00, 0x00, 0xF9, 0x00, 0x02, 0x00, 0x57, 0x00, 0x00, 0x00, 0xF8, 0x00, 0x02, 0x00, 0x59, 0x00, 0x00, 0x00, 0xFD, 0x00, 0x01, 0x00, - 0x38, 0x00, 0x01, 0x00 + 0x38, 0x00, 0x01, 0x00, }; - public static readonly byte[] ColorBlitClearAlphaFragmentShaderSource = new byte[] - { + public static readonly byte[] ColorBlitClearAlphaFragmentShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0A, 0x00, 0x08, 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x4C, 0x53, 0x4C, 0x2E, 0x73, 0x74, 0x64, 0x2E, 0x34, 0x35, 0x30, @@ -290,8 +288,7 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0x09, 0x00, 0x00, 0x00, 0x1A, 0x00, 0x00, 0x00, 0xFD, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00, }; - public static readonly byte[] ColorBlitFragmentShaderSource = new byte[] - { + public static readonly byte[] ColorBlitFragmentShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0A, 0x00, 0x08, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x4C, 0x53, 0x4C, 0x2E, 0x73, 0x74, 0x64, 0x2E, 0x34, 0x35, 0x30, @@ -329,8 +326,7 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0xFD, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00, }; - public static readonly byte[] ColorBlitMsFragmentShaderSource = new byte[] - { + public static readonly byte[] ColorBlitMsFragmentShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0B, 0x00, 0x08, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x23, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x32, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x06, 0x00, @@ -384,8 +380,7 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0xFD, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00, }; - public static readonly byte[] ColorBlitVertexShaderSource = new byte[] - { + public static readonly byte[] ColorBlitVertexShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0A, 0x00, 0x08, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x4C, 0x53, 0x4C, 0x2E, 0x73, 0x74, 0x64, 0x2E, 0x34, 0x35, 0x30, @@ -486,8 +481,7 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0x3C, 0x00, 0x00, 0x00, 0xFD, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00, }; - public static readonly byte[] ColorClearFFragmentShaderSource = new byte[] - { + public static readonly byte[] ColorClearFFragmentShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0A, 0x00, 0x08, 0x00, 0x0D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x4C, 0x53, 0x4C, 0x2E, 0x73, 0x74, 0x64, 0x2E, 0x34, 0x35, 0x30, @@ -514,8 +508,7 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0x0C, 0x00, 0x00, 0x00, 0xFD, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00, }; - public static readonly byte[] ColorClearSIFragmentShaderSource = new byte[] - { + public static readonly byte[] ColorClearSIFragmentShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0A, 0x00, 0x08, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x4C, 0x53, 0x4C, 0x2E, 0x73, 0x74, 0x64, 0x2E, 0x34, 0x35, 0x30, @@ -545,8 +538,7 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0x0F, 0x00, 0x00, 0x00, 0xFD, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00, }; - public static readonly byte[] ColorClearUIFragmentShaderSource = new byte[] - { + public static readonly byte[] ColorClearUIFragmentShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0A, 0x00, 0x08, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x4C, 0x53, 0x4C, 0x2E, 0x73, 0x74, 0x64, 0x2E, 0x34, 0x35, 0x30, @@ -576,8 +568,7 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0x0F, 0x00, 0x00, 0x00, 0xFD, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00, }; - public static readonly byte[] ColorClearVertexShaderSource = new byte[] - { + public static readonly byte[] ColorClearVertexShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0A, 0x00, 0x08, 0x00, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x4C, 0x53, 0x4C, 0x2E, 0x73, 0x74, 0x64, 0x2E, 0x34, 0x35, 0x30, @@ -669,8 +660,7 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0x35, 0x00, 0x00, 0x00, 0x33, 0x00, 0x00, 0x00, 0xFD, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00, }; - public static readonly byte[] ColorCopyShorteningComputeShaderSource = new byte[] - { + public static readonly byte[] ColorCopyShorteningComputeShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x05, 0x01, 0x00, 0x0B, 0x00, 0x08, 0x00, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x32, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x38, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x06, 0x00, @@ -801,8 +791,7 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0xFD, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00, }; - public static readonly byte[] ColorCopyToNonMsComputeShaderSource = new byte[] - { + public static readonly byte[] ColorCopyToNonMsComputeShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0A, 0x00, 0x08, 0x00, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x32, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x38, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x06, 0x00, @@ -933,8 +922,7 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0x84, 0x00, 0x00, 0x00, 0xFD, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00, }; - public static readonly byte[] ColorCopyWideningComputeShaderSource = new byte[] - { + public static readonly byte[] ColorCopyWideningComputeShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x05, 0x01, 0x00, 0x0B, 0x00, 0x08, 0x00, 0x72, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x32, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x38, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x06, 0x00, @@ -1060,8 +1048,7 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0xF8, 0x00, 0x02, 0x00, 0x70, 0x00, 0x00, 0x00, 0xFD, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00, }; - public static readonly byte[] ColorDrawToMsVertexShaderSource = new byte[] - { + public static readonly byte[] ColorDrawToMsVertexShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0A, 0x00, 0x08, 0x00, 0x2E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x4C, 0x53, 0x4C, 0x2E, 0x73, 0x74, 0x64, 0x2E, 0x34, 0x35, 0x30, @@ -1133,8 +1120,7 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0x2D, 0x00, 0x00, 0x00, 0x2B, 0x00, 0x00, 0x00, 0xFD, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00, }; - public static readonly byte[] ColorDrawToMsFragmentShaderSource = new byte[] - { + public static readonly byte[] ColorDrawToMsFragmentShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0A, 0x00, 0x08, 0x00, 0x5E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x23, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x4C, 0x53, 0x4C, @@ -1236,8 +1222,7 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0x38, 0x00, 0x01, 0x00, }; - public static readonly byte[] ConvertD32S8ToD24S8ShaderSource = new byte[] - { + public static readonly byte[] ConvertD32S8ToD24S8ShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x05, 0x01, 0x00, 0x0A, 0x00, 0x0D, 0x00, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x4C, 0x53, 0x4C, 0x2E, 0x73, 0x74, 0x64, 0x2E, 0x34, 0x35, 0x30, @@ -1441,10 +1426,9 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0x3E, 0x00, 0x03, 0x00, 0x40, 0x00, 0x00, 0x00, 0x73, 0x00, 0x00, 0x00, 0xF9, 0x00, 0x02, 0x00, 0x41, 0x00, 0x00, 0x00, 0xF8, 0x00, 0x02, 0x00, 0x43, 0x00, 0x00, 0x00, 0xFD, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00 - }; +, }; - public static readonly byte[] ConvertIndexBufferShaderSource = new byte[] - { + public static readonly byte[] ConvertIndexBufferShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0A, 0x00, 0x08, 0x00, 0x91, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x61, 0x11, 0x00, 0x00, 0x0A, 0x00, 0x07, 0x00, 0x53, 0x50, 0x56, 0x5F, 0x4B, 0x48, 0x52, 0x5F, @@ -1638,8 +1622,7 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0x38, 0x00, 0x01, 0x00, }; - public static readonly byte[] ConvertIndirectDataShaderSource = new byte[] - { + public static readonly byte[] ConvertIndirectDataShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0A, 0x00, 0x08, 0x00, 0x3D, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x4C, 0x53, 0x4C, 0x2E, 0x73, 0x74, 0x64, 0x2E, 0x34, 0x35, 0x30, @@ -1981,8 +1964,7 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0xF8, 0x00, 0x02, 0x00, 0xE5, 0x00, 0x00, 0x00, 0xFD, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00, }; - public static readonly byte[] DepthBlitFragmentShaderSource = new byte[] - { + public static readonly byte[] DepthBlitFragmentShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0B, 0x00, 0x08, 0x00, 0x17, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x4C, 0x53, 0x4C, 0x2E, 0x73, 0x74, 0x64, 0x2E, 0x34, 0x35, 0x30, @@ -2023,8 +2005,7 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0xFD, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00, }; - public static readonly byte[] DepthBlitMsFragmentShaderSource = new byte[] - { + public static readonly byte[] DepthBlitMsFragmentShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0B, 0x00, 0x08, 0x00, 0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x23, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x32, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x06, 0x00, @@ -2081,8 +2062,7 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0xFD, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00, }; - public static readonly byte[] DepthDrawToMsFragmentShaderSource = new byte[] - { + public static readonly byte[] DepthDrawToMsFragmentShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0B, 0x00, 0x08, 0x00, 0x5E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x23, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x4C, 0x53, 0x4C, @@ -2185,8 +2165,7 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0x5D, 0x00, 0x00, 0x00, 0xFD, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00, }; - public static readonly byte[] DepthDrawToNonMsFragmentShaderSource = new byte[] - { + public static readonly byte[] DepthDrawToNonMsFragmentShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0B, 0x00, 0x08, 0x00, 0x6A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x4C, 0x53, 0x4C, 0x2E, 0x73, 0x74, 0x64, 0x2E, 0x34, 0x35, 0x30, @@ -2288,8 +2267,7 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0xFD, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00, }; - public static readonly byte[] StencilBlitFragmentShaderSource = new byte[] - { + public static readonly byte[] StencilBlitFragmentShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0B, 0x00, 0x08, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x95, 0x13, 0x00, 0x00, 0x0A, 0x00, 0x09, 0x00, 0x53, 0x50, 0x56, 0x5F, 0x45, 0x58, 0x54, 0x5F, @@ -2336,8 +2314,7 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0x08, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0xFD, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00, }; - public static readonly byte[] StencilBlitMsFragmentShaderSource = new byte[] - { + public static readonly byte[] StencilBlitMsFragmentShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0B, 0x00, 0x08, 0x00, 0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x23, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x32, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, @@ -2399,8 +2376,7 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0x08, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0xFD, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00, }; - public static readonly byte[] StencilDrawToMsFragmentShaderSource = new byte[] - { + public static readonly byte[] StencilDrawToMsFragmentShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0B, 0x00, 0x08, 0x00, 0x5E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x23, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x95, 0x13, 0x00, 0x00, 0x0A, 0x00, 0x09, 0x00, @@ -2509,8 +2485,7 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0x38, 0x00, 0x01, 0x00, }; - public static readonly byte[] StencilDrawToNonMsFragmentShaderSource = new byte[] - { + public static readonly byte[] StencilDrawToNonMsFragmentShaderSource = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0B, 0x00, 0x08, 0x00, 0x6A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x95, 0x13, 0x00, 0x00, 0x0A, 0x00, 0x09, 0x00, 0x53, 0x50, 0x56, 0x5F, 0x45, 0x58, 0x54, 0x5F, @@ -2617,4 +2592,4 @@ namespace Ryujinx.Graphics.Vulkan.Shaders 0x5F, 0x00, 0x00, 0x00, 0x69, 0x00, 0x00, 0x00, 0xFD, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00, }; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Vulkan/SpecInfo.cs b/src/Ryujinx.Graphics.Vulkan/SpecInfo.cs index 4d226f615..ecb2abfc6 100644 --- a/src/Ryujinx.Graphics.Vulkan/SpecInfo.cs +++ b/src/Ryujinx.Graphics.Vulkan/SpecInfo.cs @@ -1,7 +1,5 @@ using Silk.NET.Vulkan; using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; namespace Ryujinx.Graphics.Vulkan { @@ -13,7 +11,7 @@ namespace Ryujinx.Graphics.Vulkan Int64, Float16, Float32, - Float64 + Float64, } sealed class SpecDescription @@ -36,10 +34,10 @@ namespace Ryujinx.Graphics.Vulkan structSize += typeSize; } - Info = new SpecializationInfo() + Info = new SpecializationInfo { DataSize = structSize, - MapEntryCount = (uint)count + MapEntryCount = (uint)count, }; } @@ -54,10 +52,10 @@ namespace Ryujinx.Graphics.Vulkan structSize = Math.Max(structSize, map[i].Offset + (uint)map[i].Size); } - Info = new SpecializationInfo() + Info = new SpecializationInfo { DataSize = structSize, - MapEntryCount = (uint)map.Length + MapEntryCount = (uint)map.Length, }; } @@ -66,7 +64,7 @@ namespace Ryujinx.Graphics.Vulkan SpecConstType.Int16 or SpecConstType.Float16 => 2, SpecConstType.Bool32 or SpecConstType.Int32 or SpecConstType.Float32 => 4, SpecConstType.Int64 or SpecConstType.Float64 => 8, - _ => throw new ArgumentOutOfRangeException(nameof(type)) + _ => throw new ArgumentOutOfRangeException(nameof(type)), }; private SpecDescription() @@ -99,4 +97,4 @@ namespace Ryujinx.Graphics.Vulkan public override bool Equals(object obj) => obj is SpecData other && Equals(other); public bool Equals(ref SpecData other) => _data.AsSpan().SequenceEqual(other._data); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Vulkan/StagingBuffer.cs b/src/Ryujinx.Graphics.Vulkan/StagingBuffer.cs index 4e3c1deea..00fa6477d 100644 --- a/src/Ryujinx.Graphics.Vulkan/StagingBuffer.cs +++ b/src/Ryujinx.Graphics.Vulkan/StagingBuffer.cs @@ -37,7 +37,7 @@ namespace Ryujinx.Graphics.Vulkan _freeSize = BufferSize; } - public unsafe void PushData(CommandBufferPool cbp, CommandBufferScoped? cbs, Action endRenderPass, BufferHolder dst, int dstOffset, ReadOnlySpan data) + public void PushData(CommandBufferPool cbp, CommandBufferScoped? cbs, Action endRenderPass, BufferHolder dst, int dstOffset, ReadOnlySpan data) { bool isRender = cbs != null; CommandBufferScoped scoped = cbs ?? cbp.Rent(); @@ -72,10 +72,10 @@ namespace Ryujinx.Graphics.Vulkan int chunkSize = Math.Min(_freeSize, data.Length); - PushDataImpl(scoped, dst, dstOffset, data.Slice(0, chunkSize)); + PushDataImpl(scoped, dst, dstOffset, data[..chunkSize]); dstOffset += chunkSize; - data = data.Slice(chunkSize); + data = data[chunkSize..]; } if (!isRender) @@ -93,8 +93,8 @@ namespace Ryujinx.Graphics.Vulkan int capacity = BufferSize - offset; if (capacity < data.Length) { - _buffer.SetDataUnchecked(offset, data.Slice(0, capacity)); - _buffer.SetDataUnchecked(0, data.Slice(capacity)); + _buffer.SetDataUnchecked(offset, data[..capacity]); + _buffer.SetDataUnchecked(0, data[capacity..]); BufferHolder.Copy(_gd, cbs, srcBuffer, dstBuffer, offset, dstOffset, capacity); BufferHolder.Copy(_gd, cbs, srcBuffer, dstBuffer, 0, dstOffset + capacity, data.Length - capacity); @@ -113,7 +113,7 @@ namespace Ryujinx.Graphics.Vulkan _pendingCopies.Enqueue(new PendingCopy(cbs.GetFence(), data.Length)); } - public unsafe bool TryPushData(CommandBufferScoped cbs, Action endRenderPass, BufferHolder dst, int dstOffset, ReadOnlySpan data) + public bool TryPushData(CommandBufferScoped cbs, Action endRenderPass, BufferHolder dst, int dstOffset, ReadOnlySpan data) { if (data.Length > BufferSize) { diff --git a/src/Ryujinx.Graphics.Vulkan/SyncManager.cs b/src/Ryujinx.Graphics.Vulkan/SyncManager.cs index b3f6e8e5a..35e9ab971 100644 --- a/src/Ryujinx.Graphics.Vulkan/SyncManager.cs +++ b/src/Ryujinx.Graphics.Vulkan/SyncManager.cs @@ -21,13 +21,13 @@ namespace Ryujinx.Graphics.Vulkan } } - private ulong _firstHandle = 0; + private ulong _firstHandle; private readonly VulkanRenderer _gd; private readonly Device _device; - private List _handles; - private ulong FlushId; - private long WaitTicks; + private readonly List _handles; + private ulong _flushId; + private long _waitTicks; public SyncManager(VulkanRenderer gd, Device device) { @@ -38,13 +38,13 @@ namespace Ryujinx.Graphics.Vulkan public void RegisterFlush() { - FlushId++; + _flushId++; } public void Create(ulong id, bool strict) { - ulong flushId = FlushId; - MultiFenceHolder waitable = new MultiFenceHolder(); + ulong flushId = _flushId; + MultiFenceHolder waitable = new(); if (strict || _gd.InterruptAction == null) { _gd.FlushAllCommands(); @@ -58,11 +58,11 @@ namespace Ryujinx.Graphics.Vulkan _gd.CommandBufferPool.AddInUseWaitable(waitable); } - SyncHandle handle = new SyncHandle + SyncHandle handle = new() { ID = id, Waitable = waitable, - FlushId = flushId + FlushId = flushId, }; lock (_handles) @@ -132,11 +132,11 @@ namespace Ryujinx.Graphics.Vulkan long beforeTicks = Stopwatch.GetTimestamp(); - if (result.NeedsFlush(FlushId)) + if (result.NeedsFlush(_flushId)) { _gd.InterruptAction(() => { - if (result.NeedsFlush(FlushId)) + if (result.NeedsFlush(_flushId)) { _gd.FlushAllCommands(); } @@ -158,7 +158,7 @@ namespace Ryujinx.Graphics.Vulkan } else { - WaitTicks += Stopwatch.GetTimestamp() - beforeTicks; + _waitTicks += Stopwatch.GetTimestamp() - beforeTicks; result.Signalled = true; } } @@ -177,7 +177,10 @@ namespace Ryujinx.Graphics.Vulkan first = _handles.FirstOrDefault(); } - if (first == null || first.NeedsFlush(FlushId)) break; + if (first == null || first.NeedsFlush(_flushId)) + { + break; + } bool signaled = first.Waitable.WaitForFences(_gd.Api, _device, 0); if (signaled) @@ -192,7 +195,8 @@ namespace Ryujinx.Graphics.Vulkan first.Waitable = null; } } - } else + } + else { // This sync handle and any following have not been reached yet. break; @@ -202,8 +206,8 @@ namespace Ryujinx.Graphics.Vulkan public long GetAndResetWaitTicks() { - long result = WaitTicks; - WaitTicks = 0; + long result = _waitTicks; + _waitTicks = 0; return result; } diff --git a/src/Ryujinx.Graphics.Vulkan/TextureBuffer.cs b/src/Ryujinx.Graphics.Vulkan/TextureBuffer.cs index 66951153d..e7d24a007 100644 --- a/src/Ryujinx.Graphics.Vulkan/TextureBuffer.cs +++ b/src/Ryujinx.Graphics.Vulkan/TextureBuffer.cs @@ -3,6 +3,7 @@ using Ryujinx.Graphics.GAL; using Silk.NET.Vulkan; using System; using System.Collections.Generic; +using Format = Ryujinx.Graphics.GAL.Format; using VkFormat = Silk.NET.Vulkan.Format; namespace Ryujinx.Graphics.Vulkan @@ -15,7 +16,7 @@ namespace Ryujinx.Graphics.Vulkan private int _offset; private int _size; private Auto _bufferView; - private Dictionary> _selfManagedViews; + private Dictionary> _selfManagedViews; private int _bufferCount; @@ -131,15 +132,12 @@ namespace Ryujinx.Graphics.Vulkan public BufferView GetBufferView(CommandBufferScoped cbs) { - if (_bufferView == null) - { - _bufferView = _gd.BufferManager.CreateView(_bufferHandle, VkFormat, _offset, _size, ReleaseImpl); - } + _bufferView ??= _gd.BufferManager.CreateView(_bufferHandle, VkFormat, _offset, _size, ReleaseImpl); return _bufferView?.Get(cbs, _offset, _size).Value ?? default; } - public BufferView GetBufferView(CommandBufferScoped cbs, GAL.Format format) + public BufferView GetBufferView(CommandBufferScoped cbs, Format format) { var vkFormat = FormatTable.GetFormat(format); if (vkFormat == VkFormat) @@ -156,7 +154,7 @@ namespace Ryujinx.Graphics.Vulkan if (bufferView != null) { - (_selfManagedViews ??= new Dictionary>()).Add(format, bufferView); + (_selfManagedViews ??= new Dictionary>()).Add(format, bufferView); } return bufferView?.Get(cbs, _offset, _size).Value ?? default; diff --git a/src/Ryujinx.Graphics.Vulkan/TextureCopy.cs b/src/Ryujinx.Graphics.Vulkan/TextureCopy.cs index c7ce2d99f..717935fb4 100644 --- a/src/Ryujinx.Graphics.Vulkan/TextureCopy.cs +++ b/src/Ryujinx.Graphics.Vulkan/TextureCopy.cs @@ -80,12 +80,12 @@ namespace Ryujinx.Graphics.Vulkan (srcOffsets.Element0, srcOffsets.Element1) = ExtentsToOffset3D(srcRegion, srcInfo.Width, srcInfo.Height, level); (dstOffsets.Element0, dstOffsets.Element1) = ExtentsToOffset3D(dstRegion, dstInfo.Width, dstInfo.Height, level); - var region = new ImageBlit() + var region = new ImageBlit { SrcSubresource = srcSl, SrcOffsets = srcOffsets, DstSubresource = dstSl, - DstOffsets = dstOffsets + DstOffsets = dstOffsets, }; api.CmdBlitImage(commandBuffer, srcImage, ImageLayout.General, dstImage, ImageLayout.General, 1, region, filter); @@ -219,21 +219,18 @@ namespace Ryujinx.Graphics.Vulkan int dstZ; int dstLayer; - int dstDepth; int dstLayers; if (dstInfo.Target == Target.Texture3D) { dstZ = dstDepthOrLayer; dstLayer = 0; - dstDepth = depthOrLayers; dstLayers = 1; } else { dstZ = 0; dstLayer = dstDepthOrLayer; - dstDepth = 1; dstLayers = depthOrLayers; } @@ -366,20 +363,20 @@ namespace Ryujinx.Graphics.Vulkan var dsAttachmentReference = new AttachmentReference2(StructureType.AttachmentReference2, null, 0, ImageLayout.General); var dsResolveAttachmentReference = new AttachmentReference2(StructureType.AttachmentReference2, null, 1, ImageLayout.General); - var subpassDsResolve = new SubpassDescriptionDepthStencilResolve() + var subpassDsResolve = new SubpassDescriptionDepthStencilResolve { SType = StructureType.SubpassDescriptionDepthStencilResolve, PDepthStencilResolveAttachment = &dsResolveAttachmentReference, DepthResolveMode = ResolveModeFlags.SampleZeroBit, - StencilResolveMode = ResolveModeFlags.SampleZeroBit + StencilResolveMode = ResolveModeFlags.SampleZeroBit, }; - var subpass = new SubpassDescription2() + var subpass = new SubpassDescription2 { SType = StructureType.SubpassDescription2, PipelineBindPoint = PipelineBindPoint.Graphics, PDepthStencilAttachment = &dsAttachmentReference, - PNext = &subpassDsResolve + PNext = &subpassDsResolve, }; AttachmentDescription2[] attachmentDescs = new AttachmentDescription2[2]; @@ -414,7 +411,7 @@ namespace Ryujinx.Graphics.Vulkan fixed (AttachmentDescription2* pAttachmentDescs = attachmentDescs) { - var renderPassCreateInfo = new RenderPassCreateInfo2() + var renderPassCreateInfo = new RenderPassCreateInfo2 { SType = StructureType.RenderPassCreateInfo2, PAttachments = pAttachmentDescs, @@ -422,7 +419,7 @@ namespace Ryujinx.Graphics.Vulkan PSubpasses = &subpass, SubpassCount = 1, PDependencies = &subpassDependency, - DependencyCount = 1 + DependencyCount = 1, }; gd.Api.CreateRenderPass2(device, renderPassCreateInfo, null, out var renderPass).ThrowOnError(); @@ -437,7 +434,7 @@ namespace Ryujinx.Graphics.Vulkan attachments[0] = srcView.Get(cbs).Value; attachments[1] = dstView.Get(cbs).Value; - var framebufferCreateInfo = new FramebufferCreateInfo() + var framebufferCreateInfo = new FramebufferCreateInfo { SType = StructureType.FramebufferCreateInfo, RenderPass = rp.Get(cbs).Value, @@ -445,23 +442,23 @@ namespace Ryujinx.Graphics.Vulkan PAttachments = attachments, Width = (uint)src.Width, Height = (uint)src.Height, - Layers = (uint)src.Layers + Layers = (uint)src.Layers, }; gd.Api.CreateFramebuffer(device, framebufferCreateInfo, null, out var framebuffer).ThrowOnError(); - using var fb = new Auto(new DisposableFramebuffer(gd.Api, device, framebuffer), null, new[] { srcView, dstView }); + using var fb = new Auto(new DisposableFramebuffer(gd.Api, device, framebuffer), null, srcView, dstView); var renderArea = new Rect2D(null, new Extent2D((uint)src.Info.Width, (uint)src.Info.Height)); var clearValue = new ClearValue(); - var renderPassBeginInfo = new RenderPassBeginInfo() + var renderPassBeginInfo = new RenderPassBeginInfo { SType = StructureType.RenderPassBeginInfo, RenderPass = rp.Get(cbs).Value, Framebuffer = fb.Get(cbs).Value, RenderArea = renderArea, PClearValues = &clearValue, - ClearValueCount = 1 + ClearValueCount = 1, }; // The resolve operation happens at the end of the subpass, so let's just do a begin/end diff --git a/src/Ryujinx.Graphics.Vulkan/TextureStorage.cs b/src/Ryujinx.Graphics.Vulkan/TextureStorage.cs index 4edb6f2fe..2a51c132a 100644 --- a/src/Ryujinx.Graphics.Vulkan/TextureStorage.cs +++ b/src/Ryujinx.Graphics.Vulkan/TextureStorage.cs @@ -4,6 +4,7 @@ using Silk.NET.Vulkan; using System; using System.Collections.Generic; using System.Numerics; +using Format = Ryujinx.Graphics.GAL.Format; using VkBuffer = Silk.NET.Vulkan.Buffer; using VkFormat = Silk.NET.Vulkan.Format; @@ -42,7 +43,7 @@ namespace Ryujinx.Graphics.Vulkan private readonly Auto _allocationAuto; private Auto _foreignAllocationAuto; - private Dictionary _aliasedStorages; + private Dictionary _aliasedStorages; private AccessFlags _lastModificationAccess; private PipelineStageFlags _lastModificationStage; @@ -50,7 +51,7 @@ namespace Ryujinx.Graphics.Vulkan private PipelineStageFlags _lastReadStage; private int _viewsCount; - private ulong _size; + private readonly ulong _size; public VkFormat VkFormat { get; } public float ScaleFactor { get; } @@ -98,7 +99,7 @@ namespace Ryujinx.Graphics.Vulkan flags |= ImageCreateFlags.Create2DArrayCompatibleBit; } - var imageCreateInfo = new ImageCreateInfo() + var imageCreateInfo = new ImageCreateInfo { SType = StructureType.ImageCreateInfo, ImageType = type, @@ -111,7 +112,7 @@ namespace Ryujinx.Graphics.Vulkan Usage = usage, SharingMode = SharingMode.Exclusive, InitialLayout = ImageLayout.Undefined, - Flags = flags + Flags = flags, }; gd.Api.CreateImage(device, imageCreateInfo, null, out _image).ThrowOnError(); @@ -150,27 +151,27 @@ namespace Ryujinx.Graphics.Vulkan } } - public TextureStorage CreateAliasedColorForDepthStorageUnsafe(GAL.Format format) + public TextureStorage CreateAliasedColorForDepthStorageUnsafe(Format format) { var colorFormat = format switch { - GAL.Format.S8Uint => GAL.Format.R8Unorm, - GAL.Format.D16Unorm => GAL.Format.R16Unorm, - GAL.Format.S8UintD24Unorm => GAL.Format.R8G8B8A8Unorm, - GAL.Format.D32Float => GAL.Format.R32Float, - GAL.Format.D24UnormS8Uint => GAL.Format.R8G8B8A8Unorm, - GAL.Format.D32FloatS8Uint => GAL.Format.R32G32Float, - _ => throw new ArgumentException($"\"{format}\" is not a supported depth or stencil format.") + Format.S8Uint => Format.R8Unorm, + Format.D16Unorm => Format.R16Unorm, + Format.S8UintD24Unorm => Format.R8G8B8A8Unorm, + Format.D32Float => Format.R32Float, + Format.D24UnormS8Uint => Format.R8G8B8A8Unorm, + Format.D32FloatS8Uint => Format.R32G32Float, + _ => throw new ArgumentException($"\"{format}\" is not a supported depth or stencil format."), }; return CreateAliasedStorageUnsafe(colorFormat); } - public TextureStorage CreateAliasedStorageUnsafe(GAL.Format format) + public TextureStorage CreateAliasedStorageUnsafe(Format format) { if (_aliasedStorages == null || !_aliasedStorages.TryGetValue(format, out var storage)) { - _aliasedStorages ??= new Dictionary(); + _aliasedStorages ??= new Dictionary(); var info = NewCreateInfoWith(ref _info, format, _info.BytesPerPixel); @@ -182,14 +183,14 @@ namespace Ryujinx.Graphics.Vulkan return storage; } - public static TextureCreateInfo NewCreateInfoWith(ref TextureCreateInfo info, GAL.Format format, int bytesPerPixel) + public static TextureCreateInfo NewCreateInfoWith(ref TextureCreateInfo info, Format format, int bytesPerPixel) { return NewCreateInfoWith(ref info, format, bytesPerPixel, info.Width, info.Height); } public static TextureCreateInfo NewCreateInfoWith( ref TextureCreateInfo info, - GAL.Format format, + Format format, int bytesPerPixel, int width, int height) @@ -262,7 +263,7 @@ namespace Ryujinx.Graphics.Vulkan var subresourceRange = new ImageSubresourceRange(aspectFlags, 0, (uint)_info.Levels, 0, (uint)_info.GetLayers()); - var barrier = new ImageMemoryBarrier() + var barrier = new ImageMemoryBarrier { SType = StructureType.ImageMemoryBarrier, SrcAccessMask = 0, @@ -272,7 +273,7 @@ namespace Ryujinx.Graphics.Vulkan SrcQueueFamilyIndex = Vk.QueueFamilyIgnored, DstQueueFamilyIndex = Vk.QueueFamilyIgnored, Image = _imageAuto.Get(cbs).Value, - SubresourceRange = subresourceRange + SubresourceRange = subresourceRange, }; _gd.Api.CmdPipelineBarrier( @@ -293,7 +294,7 @@ namespace Ryujinx.Graphics.Vulkan } } - public static ImageUsageFlags GetImageUsage(GAL.Format format, Target target, bool supportsMsStorage) + public static ImageUsageFlags GetImageUsage(Format format, Target target, bool supportsMsStorage) { var usage = DefaultUsageFlags; diff --git a/src/Ryujinx.Graphics.Vulkan/TextureView.cs b/src/Ryujinx.Graphics.Vulkan/TextureView.cs index eb094b3e6..6151d5a9e 100644 --- a/src/Ryujinx.Graphics.Vulkan/TextureView.cs +++ b/src/Ryujinx.Graphics.Vulkan/TextureView.cs @@ -3,6 +3,7 @@ using Ryujinx.Graphics.GAL; using Silk.NET.Vulkan; using System; using System.Collections.Generic; +using Format = Ryujinx.Graphics.GAL.Format; using VkBuffer = Silk.NET.Vulkan.Buffer; using VkFormat = Silk.NET.Vulkan.Format; @@ -18,9 +19,9 @@ namespace Ryujinx.Graphics.Vulkan private readonly Auto _imageViewDraw; private readonly Auto _imageViewIdentity; private readonly Auto _imageView2dArray; - private Dictionary _selfManagedViews; + private Dictionary _selfManagedViews; - private TextureCreateInfo _info; + private readonly TextureCreateInfo _info; public TextureCreateInfo Info => _info; @@ -68,16 +69,13 @@ namespace Ryujinx.Graphics.Vulkan var swizzleB = info.SwizzleB.Convert(); var swizzleA = info.SwizzleA.Convert(); - if (info.Format == GAL.Format.R5G5B5A1Unorm || - info.Format == GAL.Format.R5G5B5X1Unorm || - info.Format == GAL.Format.R5G6B5Unorm) + if (info.Format == Format.R5G5B5A1Unorm || + info.Format == Format.R5G5B5X1Unorm || + info.Format == Format.R5G6B5Unorm) { - var temp = swizzleR; - - swizzleR = swizzleB; - swizzleB = temp; + (swizzleB, swizzleR) = (swizzleR, swizzleB); } - else if (VkFormat == VkFormat.R4G4B4A4UnormPack16 || info.Format == GAL.Format.A1B5G5R5Unorm) + else if (VkFormat == VkFormat.R4G4B4A4UnormPack16 || info.Format == Format.A1B5G5R5Unorm) { var tempB = swizzleB; var tempA = swizzleA; @@ -98,13 +96,13 @@ namespace Ryujinx.Graphics.Vulkan unsafe Auto CreateImageView(ComponentMapping cm, ImageSubresourceRange sr, ImageViewType viewType, ImageUsageFlags usageFlags) { - var usage = new ImageViewUsageCreateInfo() + var usage = new ImageViewUsageCreateInfo { SType = StructureType.ImageViewUsageCreateInfo, - Usage = usageFlags + Usage = usageFlags, }; - var imageCreateInfo = new ImageViewCreateInfo() + var imageCreateInfo = new ImageViewCreateInfo { SType = StructureType.ImageViewCreateInfo, Image = storage.GetImageForViewCreation(), @@ -112,7 +110,7 @@ namespace Ryujinx.Graphics.Vulkan Format = format, Components = cm, SubresourceRange = sr, - PNext = &usage + PNext = &usage, }; gd.Api.CreateImageView(device, imageCreateInfo, null, out var imageView).ThrowOnError(); @@ -354,8 +352,9 @@ namespace Ryujinx.Graphics.Vulkan return; } - else if (_gd.FormatCapabilities.OptimalFormatSupports(FormatFeatureFlags.BlitSrcBit, srcFormat) && - _gd.FormatCapabilities.OptimalFormatSupports(FormatFeatureFlags.BlitDstBit, dstFormat)) + + if (_gd.FormatCapabilities.OptimalFormatSupports(FormatFeatureFlags.BlitSrcBit, srcFormat) && + _gd.FormatCapabilities.OptimalFormatSupports(FormatFeatureFlags.BlitDstBit, dstFormat)) { TextureCopy.Blit( _gd.Api, @@ -444,7 +443,7 @@ namespace Ryujinx.Graphics.Vulkan int layers, int levels) { - ImageMemoryBarrier memoryBarrier = new ImageMemoryBarrier() + ImageMemoryBarrier memoryBarrier = new() { SType = StructureType.ImageMemoryBarrier, SrcAccessMask = srcAccessMask, @@ -454,7 +453,7 @@ namespace Ryujinx.Graphics.Vulkan Image = image, OldLayout = ImageLayout.General, NewLayout = ImageLayout.General, - SubresourceRange = new ImageSubresourceRange(aspectFlags, (uint)firstLevel, (uint)levels, (uint)firstLayer, (uint)layers) + SubresourceRange = new ImageSubresourceRange(aspectFlags, (uint)firstLevel, (uint)levels, (uint)firstLayer, (uint)layers), }; api.CmdPipelineBarrier( @@ -470,7 +469,7 @@ namespace Ryujinx.Graphics.Vulkan memoryBarrier); } - public TextureView GetView(GAL.Format format) + public TextureView GetView(Format format) { if (format == Info.Format) { @@ -499,7 +498,7 @@ namespace Ryujinx.Graphics.Vulkan Info.SwizzleB, Info.SwizzleA), 0, 0); - (_selfManagedViews ??= new Dictionary()).Add(format, view); + (_selfManagedViews ??= new Dictionary()).Add(format, view); return view; } @@ -543,10 +542,8 @@ namespace Ryujinx.Graphics.Vulkan return PinnedSpan.UnsafeFromSpan(GetData(_gd.CommandBufferPool, resources.GetFlushBuffer())); } - else - { - return PinnedSpan.UnsafeFromSpan(GetData(resources.GetPool(), resources.GetFlushBuffer())); - } + + return PinnedSpan.UnsafeFromSpan(GetData(resources.GetPool(), resources.GetFlushBuffer())); } public PinnedSpan GetData(int layer, int level) @@ -559,10 +556,8 @@ namespace Ryujinx.Graphics.Vulkan return PinnedSpan.UnsafeFromSpan(GetData(_gd.CommandBufferPool, resources.GetFlushBuffer(), layer, level)); } - else - { - return PinnedSpan.UnsafeFromSpan(GetData(resources.GetPool(), resources.GetFlushBuffer(), layer, level)); - } + + return PinnedSpan.UnsafeFromSpan(GetData(resources.GetPool(), resources.GetFlushBuffer(), layer, level)); } public void CopyTo(BufferRange range, int layer, int level, int stride) @@ -686,11 +681,11 @@ namespace Ryujinx.Graphics.Vulkan return length; } - private GAL.Format GetCompatibleGalFormat(GAL.Format format) + private Format GetCompatibleGalFormat(Format format) { if (NeedsD24S8Conversion()) { - return GAL.Format.D32FloatS8Uint; + return Format.D32FloatS8Uint; } return format; diff --git a/src/Ryujinx.Graphics.Vulkan/Vendor.cs b/src/Ryujinx.Graphics.Vulkan/Vendor.cs index 5e0290c0a..2d2f17b25 100644 --- a/src/Ryujinx.Graphics.Vulkan/Vendor.cs +++ b/src/Ryujinx.Graphics.Vulkan/Vendor.cs @@ -12,7 +12,7 @@ namespace Ryujinx.Graphics.Vulkan Broadcom, Qualcomm, Apple, - Unknown + Unknown, } static partial class VendorUtils @@ -32,7 +32,7 @@ namespace Ryujinx.Graphics.Vulkan 0x14E4 => Vendor.Broadcom, 0x8086 => Vendor.Intel, 0x5143 => Vendor.Qualcomm, - _ => Vendor.Unknown + _ => Vendor.Unknown, }; } @@ -55,7 +55,7 @@ namespace Ryujinx.Graphics.Vulkan 0x10004 => "Codeplay Software Ltd.", 0x10005 => "Mesa", 0x10006 => "PoCL", - _ => $"0x{id:X}" + _ => $"0x{id:X}", }; } } diff --git a/src/Ryujinx.Graphics.Vulkan/VertexBufferState.cs b/src/Ryujinx.Graphics.Vulkan/VertexBufferState.cs index 2118bfaeb..cbbd829ab 100644 --- a/src/Ryujinx.Graphics.Vulkan/VertexBufferState.cs +++ b/src/Ryujinx.Graphics.Vulkan/VertexBufferState.cs @@ -1,10 +1,10 @@ -using BufferHandle = Ryujinx.Graphics.GAL.BufferHandle; +using Ryujinx.Graphics.GAL; namespace Ryujinx.Graphics.Vulkan { internal struct VertexBufferState { - public static VertexBufferState Null => new VertexBufferState(null, 0, 0, 0); + public static VertexBufferState Null => new(null, 0, 0, 0); private readonly int _offset; private readonly int _size; @@ -74,17 +74,15 @@ namespace Ryujinx.Graphics.Vulkan return; } - else + + autoBuffer = gd.BufferManager.GetBuffer(cbs.CommandBuffer, _handle, false, out int size); + + // The original stride must be reapplied in case it was rewritten. + state.Internal.VertexBindingDescriptions[DescriptorIndex].Stride = (uint)_stride; + + if (_offset >= size) { - autoBuffer = gd.BufferManager.GetBuffer(cbs.CommandBuffer, _handle, false, out int size); - - // The original stride must be reapplied in case it was rewritten. - state.Internal.VertexBindingDescriptions[DescriptorIndex].Stride = (uint)_stride; - - if (_offset >= size) - { - autoBuffer = null; - } + autoBuffer = null; } } @@ -96,12 +94,12 @@ namespace Ryujinx.Graphics.Vulkan } } - public bool BoundEquals(Auto buffer) + public readonly bool BoundEquals(Auto buffer) { return _buffer == buffer; } - public bool Matches(Auto buffer, int descriptorIndex, int offset, int size, int stride = 0) + public readonly bool Matches(Auto buffer, int descriptorIndex, int offset, int size, int stride = 0) { return _buffer == buffer && DescriptorIndex == descriptorIndex && _offset == offset && _size == size && _stride == stride; } @@ -117,7 +115,7 @@ namespace Ryujinx.Graphics.Vulkan } } - public void Dispose() + public readonly void Dispose() { // Only dispose if this buffer is not refetched on each bind. diff --git a/src/Ryujinx.Graphics.Vulkan/VertexBufferUpdater.cs b/src/Ryujinx.Graphics.Vulkan/VertexBufferUpdater.cs index bceaeb8c9..8d6b0a055 100644 --- a/src/Ryujinx.Graphics.Vulkan/VertexBufferUpdater.cs +++ b/src/Ryujinx.Graphics.Vulkan/VertexBufferUpdater.cs @@ -1,21 +1,19 @@ -using Silk.NET.Vulkan; -using System; - +using System; using VkBuffer = Silk.NET.Vulkan.Buffer; namespace Ryujinx.Graphics.Vulkan { internal class VertexBufferUpdater : IDisposable { - private VulkanRenderer _gd; + private readonly VulkanRenderer _gd; private uint _baseBinding; private uint _count; - private NativeArray _buffers; - private NativeArray _offsets; - private NativeArray _sizes; - private NativeArray _strides; + private readonly NativeArray _buffers; + private readonly NativeArray _offsets; + private readonly NativeArray _sizes; + private readonly NativeArray _strides; public VertexBufferUpdater(VulkanRenderer gd) { diff --git a/src/Ryujinx.Graphics.Vulkan/VulkanDebugMessenger.cs b/src/Ryujinx.Graphics.Vulkan/VulkanDebugMessenger.cs index 7e39a251e..82e30f5be 100644 --- a/src/Ryujinx.Graphics.Vulkan/VulkanDebugMessenger.cs +++ b/src/Ryujinx.Graphics.Vulkan/VulkanDebugMessenger.cs @@ -10,8 +10,7 @@ namespace Ryujinx.Graphics.Vulkan { class VulkanDebugMessenger : IDisposable { - private static string[] _excludedMessages = new string[] - { + private static readonly string[] _excludedMessages = { // NOTE: Done on purpose right now. "UNASSIGNED-CoreValidation-Shader-OutputNotConsumed", // TODO: Figure out if fixable @@ -19,7 +18,7 @@ namespace Ryujinx.Graphics.Vulkan // TODO: Might be worth looking into making this happy to possibly optimize copies. "UNASSIGNED-CoreValidation-DrawState-InvalidImageLayout", // TODO: Fix this, it's causing too much noise right now. - "VUID-VkSubpassDependency-srcSubpass-00867" + "VUID-VkSubpassDependency-srcSubpass-00867", }; private readonly Vk _api; @@ -48,7 +47,7 @@ namespace Ryujinx.Graphics.Vulkan private Result TryInitialize(out DebugUtilsMessengerEXT? debugUtilsMessengerHandle) { debugUtilsMessengerHandle = null; - + if (_debugUtils != null && _logLevel != GraphicsDebugLevel.None) { var messageType = _logLevel switch @@ -59,7 +58,7 @@ namespace Ryujinx.Graphics.Vulkan GraphicsDebugLevel.All => DebugUtilsMessageTypeFlagsEXT.GeneralBitExt | DebugUtilsMessageTypeFlagsEXT.ValidationBitExt | DebugUtilsMessageTypeFlagsEXT.PerformanceBitExt, - _ => throw new ArgumentException($"Invalid log level \"{_logLevel}\".") + _ => throw new ArgumentException($"Invalid log level \"{_logLevel}\"."), }; var messageSeverity = _logLevel switch @@ -71,14 +70,14 @@ namespace Ryujinx.Graphics.Vulkan DebugUtilsMessageSeverityFlagsEXT.WarningBitExt | DebugUtilsMessageSeverityFlagsEXT.VerboseBitExt | DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt, - _ => throw new ArgumentException($"Invalid log level \"{_logLevel}\".") + _ => throw new ArgumentException($"Invalid log level \"{_logLevel}\"."), }; - var debugUtilsMessengerCreateInfo = new DebugUtilsMessengerCreateInfoEXT() + var debugUtilsMessengerCreateInfo = new DebugUtilsMessengerCreateInfoEXT { SType = StructureType.DebugUtilsMessengerCreateInfoExt, MessageType = messageType, - MessageSeverity = messageSeverity + MessageSeverity = messageSeverity, }; unsafe diff --git a/src/Ryujinx.Graphics.Vulkan/VulkanInitialization.cs b/src/Ryujinx.Graphics.Vulkan/VulkanInitialization.cs index 51a3b129a..b0a3ba37b 100644 --- a/src/Ryujinx.Graphics.Vulkan/VulkanInitialization.cs +++ b/src/Ryujinx.Graphics.Vulkan/VulkanInitialization.cs @@ -14,14 +14,13 @@ namespace Ryujinx.Graphics.Vulkan public unsafe static class VulkanInitialization { private const uint InvalidIndex = uint.MaxValue; - private static uint MinimalVulkanVersion = Vk.Version11.Value; - private static uint MinimalInstanceVulkanVersion = Vk.Version12.Value; - private static uint MaximumVulkanVersion = Vk.Version12.Value; + private static readonly uint _minimalVulkanVersion = Vk.Version11.Value; + private static readonly uint _minimalInstanceVulkanVersion = Vk.Version12.Value; + private static readonly uint _maximumVulkanVersion = Vk.Version12.Value; private const string AppName = "Ryujinx.Graphics.Vulkan"; private const int QueuesCount = 2; - private static readonly string[] _desirableExtensions = new string[] - { + private static readonly string[] _desirableExtensions = { ExtConditionalRendering.ExtensionName, ExtExtendedDynamicState.ExtensionName, ExtTransformFeedback.ExtensionName, @@ -42,12 +41,11 @@ namespace Ryujinx.Graphics.Vulkan "VK_NV_geometry_shader_passthrough", "VK_NV_viewport_array2", "VK_EXT_depth_clip_control", - "VK_KHR_portability_subset" // As per spec, we should enable this if present. + "VK_KHR_portability_subset", // As per spec, we should enable this if present. }; - private static readonly string[] _requiredExtensions = new string[] - { - KhrSwapchain.ExtensionName + private static readonly string[] _requiredExtensions = { + KhrSwapchain.ExtensionName, }; internal static VulkanInstance CreateInstance(Vk api, GraphicsDebugLevel logLevel, string[] requiredExtensions) @@ -89,7 +87,7 @@ namespace Ryujinx.Graphics.Vulkan ApplicationVersion = 1, PEngineName = (byte*)appName, EngineVersion = 1, - ApiVersion = MaximumVulkanVersion + ApiVersion = _maximumVulkanVersion, }; IntPtr* ppEnabledExtensions = stackalloc IntPtr[enabledExtensions.Length]; @@ -112,7 +110,7 @@ namespace Ryujinx.Graphics.Vulkan PpEnabledExtensionNames = (byte**)ppEnabledExtensions, PpEnabledLayerNames = (byte**)ppEnabledLayers, EnabledExtensionCount = (uint)enabledExtensions.Length, - EnabledLayerCount = (uint)enabledLayers.Count + EnabledLayerCount = (uint)enabledLayers.Count, }; Result result = VulkanInstance.Create(api, ref instanceCreateInfo, out var instance); @@ -169,7 +167,7 @@ namespace Ryujinx.Graphics.Vulkan ApplicationVersion = 1, PEngineName = (byte*)appName, EngineVersion = 1, - ApiVersion = MaximumVulkanVersion + ApiVersion = _maximumVulkanVersion, }; var instanceCreateInfo = new InstanceCreateInfo @@ -179,7 +177,7 @@ namespace Ryujinx.Graphics.Vulkan PpEnabledExtensionNames = null, PpEnabledLayerNames = null, EnabledExtensionCount = 0, - EnabledLayerCount = 0 + EnabledLayerCount = 0, }; Result result = VulkanInstance.Create(api, ref instanceCreateInfo, out var rawInstance); @@ -192,18 +190,18 @@ namespace Ryujinx.Graphics.Vulkan // We currently assume that the instance is compatible with Vulkan 1.2 // TODO: Remove this once we relax our initialization codepaths. - if (instance.InstanceVersion < MinimalInstanceVulkanVersion) + if (instance.InstanceVersion < _minimalInstanceVulkanVersion) { return Array.Empty(); } instance.EnumeratePhysicalDevices(out VulkanPhysicalDevice[] physicalDevices).ThrowOnError(); - List deviceInfos = new List(); + List deviceInfos = new(); foreach (VulkanPhysicalDevice physicalDevice in physicalDevices) { - if (physicalDevice.PhysicalDeviceProperties.ApiVersion < MinimalVulkanVersion) + if (physicalDevice.PhysicalDeviceProperties.ApiVersion < _minimalVulkanVersion) { continue; } @@ -278,33 +276,33 @@ namespace Ryujinx.Graphics.Vulkan queuePriorities[i] = 1f; } - var queueCreateInfo = new DeviceQueueCreateInfo() + var queueCreateInfo = new DeviceQueueCreateInfo { SType = StructureType.DeviceQueueCreateInfo, QueueFamilyIndex = queueFamilyIndex, QueueCount = queueCount, - PQueuePriorities = queuePriorities + PQueuePriorities = queuePriorities, }; bool useRobustBufferAccess = VendorUtils.FromId(physicalDevice.PhysicalDeviceProperties.VendorID) == Vendor.Nvidia; - PhysicalDeviceFeatures2 features2 = new PhysicalDeviceFeatures2() + PhysicalDeviceFeatures2 features2 = new() { - SType = StructureType.PhysicalDeviceFeatures2 + SType = StructureType.PhysicalDeviceFeatures2, }; - PhysicalDeviceVulkan11Features supportedFeaturesVk11 = new PhysicalDeviceVulkan11Features() + PhysicalDeviceVulkan11Features supportedFeaturesVk11 = new() { SType = StructureType.PhysicalDeviceVulkan11Features, - PNext = features2.PNext + PNext = features2.PNext, }; features2.PNext = &supportedFeaturesVk11; - PhysicalDeviceCustomBorderColorFeaturesEXT supportedFeaturesCustomBorderColor = new PhysicalDeviceCustomBorderColorFeaturesEXT() + PhysicalDeviceCustomBorderColorFeaturesEXT supportedFeaturesCustomBorderColor = new() { SType = StructureType.PhysicalDeviceCustomBorderColorFeaturesExt, - PNext = features2.PNext + PNext = features2.PNext, }; if (physicalDevice.IsDeviceExtensionPresent("VK_EXT_custom_border_color")) @@ -312,10 +310,10 @@ namespace Ryujinx.Graphics.Vulkan features2.PNext = &supportedFeaturesCustomBorderColor; } - PhysicalDevicePrimitiveTopologyListRestartFeaturesEXT supportedFeaturesPrimitiveTopologyListRestart = new PhysicalDevicePrimitiveTopologyListRestartFeaturesEXT() + PhysicalDevicePrimitiveTopologyListRestartFeaturesEXT supportedFeaturesPrimitiveTopologyListRestart = new() { SType = StructureType.PhysicalDevicePrimitiveTopologyListRestartFeaturesExt, - PNext = features2.PNext + PNext = features2.PNext, }; if (physicalDevice.IsDeviceExtensionPresent("VK_EXT_primitive_topology_list_restart")) @@ -323,10 +321,10 @@ namespace Ryujinx.Graphics.Vulkan features2.PNext = &supportedFeaturesPrimitiveTopologyListRestart; } - PhysicalDeviceTransformFeedbackFeaturesEXT supportedFeaturesTransformFeedback = new PhysicalDeviceTransformFeedbackFeaturesEXT() + PhysicalDeviceTransformFeedbackFeaturesEXT supportedFeaturesTransformFeedback = new() { SType = StructureType.PhysicalDeviceTransformFeedbackFeaturesExt, - PNext = features2.PNext + PNext = features2.PNext, }; if (physicalDevice.IsDeviceExtensionPresent(ExtTransformFeedback.ExtensionName)) @@ -334,9 +332,9 @@ namespace Ryujinx.Graphics.Vulkan features2.PNext = &supportedFeaturesTransformFeedback; } - PhysicalDeviceRobustness2FeaturesEXT supportedFeaturesRobustness2 = new PhysicalDeviceRobustness2FeaturesEXT() + PhysicalDeviceRobustness2FeaturesEXT supportedFeaturesRobustness2 = new() { - SType = StructureType.PhysicalDeviceRobustness2FeaturesExt + SType = StructureType.PhysicalDeviceRobustness2FeaturesExt, }; if (physicalDevice.IsDeviceExtensionPresent("VK_EXT_robustness2")) @@ -346,10 +344,10 @@ namespace Ryujinx.Graphics.Vulkan features2.PNext = &supportedFeaturesRobustness2; } - PhysicalDeviceDepthClipControlFeaturesEXT supportedFeaturesDepthClipControl = new PhysicalDeviceDepthClipControlFeaturesEXT() + PhysicalDeviceDepthClipControlFeaturesEXT supportedFeaturesDepthClipControl = new() { SType = StructureType.PhysicalDeviceDepthClipControlFeaturesExt, - PNext = features2.PNext + PNext = features2.PNext, }; if (physicalDevice.IsDeviceExtensionPresent("VK_EXT_depth_clip_control")) @@ -361,7 +359,7 @@ namespace Ryujinx.Graphics.Vulkan var supportedFeatures = features2.Features; - var features = new PhysicalDeviceFeatures() + var features = new PhysicalDeviceFeatures { DepthBiasClamp = supportedFeatures.DepthBiasClamp, DepthClamp = supportedFeatures.DepthClamp, @@ -383,7 +381,7 @@ namespace Ryujinx.Graphics.Vulkan // ShaderStorageImageWriteWithoutFormat = true, TessellationShader = supportedFeatures.TessellationShader, VertexPipelineStoresAndAtomics = supportedFeatures.VertexPipelineStoresAndAtomics, - RobustBufferAccess = useRobustBufferAccess + RobustBufferAccess = useRobustBufferAccess, }; void* pExtendedFeatures = null; @@ -392,11 +390,11 @@ namespace Ryujinx.Graphics.Vulkan if (physicalDevice.IsDeviceExtensionPresent(ExtTransformFeedback.ExtensionName)) { - featuresTransformFeedback = new PhysicalDeviceTransformFeedbackFeaturesEXT() + featuresTransformFeedback = new PhysicalDeviceTransformFeedbackFeaturesEXT { SType = StructureType.PhysicalDeviceTransformFeedbackFeaturesExt, PNext = pExtendedFeatures, - TransformFeedback = supportedFeaturesTransformFeedback.TransformFeedback + TransformFeedback = supportedFeaturesTransformFeedback.TransformFeedback, }; pExtendedFeatures = &featuresTransformFeedback; @@ -406,12 +404,12 @@ namespace Ryujinx.Graphics.Vulkan if (physicalDevice.IsDeviceExtensionPresent("VK_EXT_primitive_topology_list_restart")) { - featuresPrimitiveTopologyListRestart = new PhysicalDevicePrimitiveTopologyListRestartFeaturesEXT() + featuresPrimitiveTopologyListRestart = new PhysicalDevicePrimitiveTopologyListRestartFeaturesEXT { SType = StructureType.PhysicalDevicePrimitiveTopologyListRestartFeaturesExt, PNext = pExtendedFeatures, PrimitiveTopologyListRestart = supportedFeaturesPrimitiveTopologyListRestart.PrimitiveTopologyListRestart, - PrimitiveTopologyPatchListRestart = supportedFeaturesPrimitiveTopologyListRestart.PrimitiveTopologyPatchListRestart + PrimitiveTopologyPatchListRestart = supportedFeaturesPrimitiveTopologyListRestart.PrimitiveTopologyPatchListRestart, }; pExtendedFeatures = &featuresPrimitiveTopologyListRestart; @@ -421,41 +419,41 @@ namespace Ryujinx.Graphics.Vulkan if (physicalDevice.IsDeviceExtensionPresent("VK_EXT_robustness2")) { - featuresRobustness2 = new PhysicalDeviceRobustness2FeaturesEXT() + featuresRobustness2 = new PhysicalDeviceRobustness2FeaturesEXT { SType = StructureType.PhysicalDeviceRobustness2FeaturesExt, PNext = pExtendedFeatures, - NullDescriptor = supportedFeaturesRobustness2.NullDescriptor + NullDescriptor = supportedFeaturesRobustness2.NullDescriptor, }; pExtendedFeatures = &featuresRobustness2; } - var featuresExtendedDynamicState = new PhysicalDeviceExtendedDynamicStateFeaturesEXT() + var featuresExtendedDynamicState = new PhysicalDeviceExtendedDynamicStateFeaturesEXT { SType = StructureType.PhysicalDeviceExtendedDynamicStateFeaturesExt, PNext = pExtendedFeatures, - ExtendedDynamicState = physicalDevice.IsDeviceExtensionPresent(ExtExtendedDynamicState.ExtensionName) + ExtendedDynamicState = physicalDevice.IsDeviceExtensionPresent(ExtExtendedDynamicState.ExtensionName), }; pExtendedFeatures = &featuresExtendedDynamicState; - var featuresVk11 = new PhysicalDeviceVulkan11Features() + var featuresVk11 = new PhysicalDeviceVulkan11Features { SType = StructureType.PhysicalDeviceVulkan11Features, PNext = pExtendedFeatures, - ShaderDrawParameters = supportedFeaturesVk11.ShaderDrawParameters + ShaderDrawParameters = supportedFeaturesVk11.ShaderDrawParameters, }; pExtendedFeatures = &featuresVk11; - var featuresVk12 = new PhysicalDeviceVulkan12Features() + var featuresVk12 = new PhysicalDeviceVulkan12Features { SType = StructureType.PhysicalDeviceVulkan12Features, PNext = pExtendedFeatures, DescriptorIndexing = physicalDevice.IsDeviceExtensionPresent("VK_EXT_descriptor_indexing"), DrawIndirectCount = physicalDevice.IsDeviceExtensionPresent(KhrDrawIndirectCount.ExtensionName), - UniformBufferStandardLayout = physicalDevice.IsDeviceExtensionPresent("VK_KHR_uniform_buffer_standard_layout") + UniformBufferStandardLayout = physicalDevice.IsDeviceExtensionPresent("VK_KHR_uniform_buffer_standard_layout"), }; pExtendedFeatures = &featuresVk12; @@ -464,11 +462,11 @@ namespace Ryujinx.Graphics.Vulkan if (physicalDevice.IsDeviceExtensionPresent("VK_EXT_index_type_uint8")) { - featuresIndexU8 = new PhysicalDeviceIndexTypeUint8FeaturesEXT() + featuresIndexU8 = new PhysicalDeviceIndexTypeUint8FeaturesEXT { SType = StructureType.PhysicalDeviceIndexTypeUint8FeaturesExt, PNext = pExtendedFeatures, - IndexTypeUint8 = true + IndexTypeUint8 = true, }; pExtendedFeatures = &featuresIndexU8; @@ -478,11 +476,11 @@ namespace Ryujinx.Graphics.Vulkan if (physicalDevice.IsDeviceExtensionPresent("VK_EXT_fragment_shader_interlock")) { - featuresFragmentShaderInterlock = new PhysicalDeviceFragmentShaderInterlockFeaturesEXT() + featuresFragmentShaderInterlock = new PhysicalDeviceFragmentShaderInterlockFeaturesEXT { SType = StructureType.PhysicalDeviceFragmentShaderInterlockFeaturesExt, PNext = pExtendedFeatures, - FragmentShaderPixelInterlock = true + FragmentShaderPixelInterlock = true, }; pExtendedFeatures = &featuresFragmentShaderInterlock; @@ -492,11 +490,11 @@ namespace Ryujinx.Graphics.Vulkan if (physicalDevice.IsDeviceExtensionPresent("VK_EXT_subgroup_size_control")) { - featuresSubgroupSizeControl = new PhysicalDeviceSubgroupSizeControlFeaturesEXT() + featuresSubgroupSizeControl = new PhysicalDeviceSubgroupSizeControlFeaturesEXT { SType = StructureType.PhysicalDeviceSubgroupSizeControlFeaturesExt, PNext = pExtendedFeatures, - SubgroupSizeControl = true + SubgroupSizeControl = true, }; pExtendedFeatures = &featuresSubgroupSizeControl; @@ -508,7 +506,7 @@ namespace Ryujinx.Graphics.Vulkan supportedFeaturesCustomBorderColor.CustomBorderColors && supportedFeaturesCustomBorderColor.CustomBorderColorWithoutFormat) { - featuresCustomBorderColor = new PhysicalDeviceCustomBorderColorFeaturesEXT() + featuresCustomBorderColor = new PhysicalDeviceCustomBorderColorFeaturesEXT { SType = StructureType.PhysicalDeviceCustomBorderColorFeaturesExt, PNext = pExtendedFeatures, @@ -524,11 +522,11 @@ namespace Ryujinx.Graphics.Vulkan if (physicalDevice.IsDeviceExtensionPresent("VK_EXT_depth_clip_control") && supportedFeaturesDepthClipControl.DepthClipControl) { - featuresDepthClipControl = new PhysicalDeviceDepthClipControlFeaturesEXT() + featuresDepthClipControl = new PhysicalDeviceDepthClipControlFeaturesEXT { SType = StructureType.PhysicalDeviceDepthClipControlFeaturesExt, PNext = pExtendedFeatures, - DepthClipControl = true + DepthClipControl = true, }; pExtendedFeatures = &featuresDepthClipControl; @@ -543,7 +541,7 @@ namespace Ryujinx.Graphics.Vulkan ppEnabledExtensions[i] = Marshal.StringToHGlobalAnsi(enabledExtensions[i]); } - var deviceCreateInfo = new DeviceCreateInfo() + var deviceCreateInfo = new DeviceCreateInfo { SType = StructureType.DeviceCreateInfo, PNext = pExtendedFeatures, @@ -551,7 +549,7 @@ namespace Ryujinx.Graphics.Vulkan PQueueCreateInfos = &queueCreateInfo, PpEnabledExtensionNames = (byte**)ppEnabledExtensions, EnabledExtensionCount = (uint)enabledExtensions.Length, - PEnabledFeatures = &features + PEnabledFeatures = &features, }; api.CreateDevice(physicalDevice.PhysicalDevice, in deviceCreateInfo, null, out var device).ThrowOnError(); diff --git a/src/Ryujinx.Graphics.Vulkan/VulkanRenderer.cs b/src/Ryujinx.Graphics.Vulkan/VulkanRenderer.cs index 8c1787d69..8f0c73061 100644 --- a/src/Ryujinx.Graphics.Vulkan/VulkanRenderer.cs +++ b/src/Ryujinx.Graphics.Vulkan/VulkanRenderer.cs @@ -11,6 +11,9 @@ using Silk.NET.Vulkan.Extensions.KHR; using System; using System.Collections.Generic; using System.Runtime.InteropServices; +using Format = Ryujinx.Graphics.GAL.Format; +using PrimitiveTopology = Ryujinx.Graphics.GAL.PrimitiveTopology; +using SamplerCreateInfo = Ryujinx.Graphics.GAL.SamplerCreateInfo; namespace Ryujinx.Graphics.Vulkan { @@ -143,14 +146,14 @@ namespace Ryujinx.Graphics.Vulkan BackgroundQueueLock = new object(); } - PhysicalDeviceProperties2 properties2 = new PhysicalDeviceProperties2() + PhysicalDeviceProperties2 properties2 = new() { - SType = StructureType.PhysicalDeviceProperties2 + SType = StructureType.PhysicalDeviceProperties2, }; - PhysicalDeviceBlendOperationAdvancedPropertiesEXT propertiesBlendOperationAdvanced = new PhysicalDeviceBlendOperationAdvancedPropertiesEXT() + PhysicalDeviceBlendOperationAdvancedPropertiesEXT propertiesBlendOperationAdvanced = new() { - SType = StructureType.PhysicalDeviceBlendOperationAdvancedPropertiesExt + SType = StructureType.PhysicalDeviceBlendOperationAdvancedPropertiesExt, }; bool supportsBlendOperationAdvanced = _physicalDevice.IsDeviceExtensionPresent("VK_EXT_blend_operation_advanced"); @@ -161,9 +164,9 @@ namespace Ryujinx.Graphics.Vulkan properties2.PNext = &propertiesBlendOperationAdvanced; } - PhysicalDeviceSubgroupSizeControlPropertiesEXT propertiesSubgroupSizeControl = new PhysicalDeviceSubgroupSizeControlPropertiesEXT() + PhysicalDeviceSubgroupSizeControlPropertiesEXT propertiesSubgroupSizeControl = new() { - SType = StructureType.PhysicalDeviceSubgroupSizeControlPropertiesExt + SType = StructureType.PhysicalDeviceSubgroupSizeControlPropertiesExt, }; bool supportsSubgroupSizeControl = _physicalDevice.IsDeviceExtensionPresent("VK_EXT_subgroup_size_control"); @@ -175,9 +178,9 @@ namespace Ryujinx.Graphics.Vulkan bool supportsTransformFeedback = _physicalDevice.IsDeviceExtensionPresent(ExtTransformFeedback.ExtensionName); - PhysicalDeviceTransformFeedbackPropertiesEXT propertiesTransformFeedback = new PhysicalDeviceTransformFeedbackPropertiesEXT() + PhysicalDeviceTransformFeedbackPropertiesEXT propertiesTransformFeedback = new() { - SType = StructureType.PhysicalDeviceTransformFeedbackPropertiesExt + SType = StructureType.PhysicalDeviceTransformFeedbackPropertiesExt, }; if (supportsTransformFeedback) @@ -186,44 +189,44 @@ namespace Ryujinx.Graphics.Vulkan properties2.PNext = &propertiesTransformFeedback; } - PhysicalDevicePortabilitySubsetPropertiesKHR propertiesPortabilitySubset = new PhysicalDevicePortabilitySubsetPropertiesKHR() + PhysicalDevicePortabilitySubsetPropertiesKHR propertiesPortabilitySubset = new() { - SType = StructureType.PhysicalDevicePortabilitySubsetPropertiesKhr + SType = StructureType.PhysicalDevicePortabilitySubsetPropertiesKhr, }; - PhysicalDeviceFeatures2 features2 = new PhysicalDeviceFeatures2() + PhysicalDeviceFeatures2 features2 = new() { - SType = StructureType.PhysicalDeviceFeatures2 + SType = StructureType.PhysicalDeviceFeatures2, }; - PhysicalDevicePrimitiveTopologyListRestartFeaturesEXT featuresPrimitiveTopologyListRestart = new PhysicalDevicePrimitiveTopologyListRestartFeaturesEXT() + PhysicalDevicePrimitiveTopologyListRestartFeaturesEXT featuresPrimitiveTopologyListRestart = new() { - SType = StructureType.PhysicalDevicePrimitiveTopologyListRestartFeaturesExt + SType = StructureType.PhysicalDevicePrimitiveTopologyListRestartFeaturesExt, }; - PhysicalDeviceRobustness2FeaturesEXT featuresRobustness2 = new PhysicalDeviceRobustness2FeaturesEXT() + PhysicalDeviceRobustness2FeaturesEXT featuresRobustness2 = new() { - SType = StructureType.PhysicalDeviceRobustness2FeaturesExt + SType = StructureType.PhysicalDeviceRobustness2FeaturesExt, }; - PhysicalDeviceShaderFloat16Int8FeaturesKHR featuresShaderInt8 = new PhysicalDeviceShaderFloat16Int8FeaturesKHR() + PhysicalDeviceShaderFloat16Int8FeaturesKHR featuresShaderInt8 = new() { - SType = StructureType.PhysicalDeviceShaderFloat16Int8Features + SType = StructureType.PhysicalDeviceShaderFloat16Int8Features, }; - PhysicalDeviceCustomBorderColorFeaturesEXT featuresCustomBorderColor = new PhysicalDeviceCustomBorderColorFeaturesEXT() + PhysicalDeviceCustomBorderColorFeaturesEXT featuresCustomBorderColor = new() { - SType = StructureType.PhysicalDeviceCustomBorderColorFeaturesExt + SType = StructureType.PhysicalDeviceCustomBorderColorFeaturesExt, }; - PhysicalDeviceDepthClipControlFeaturesEXT featuresDepthClipControl = new PhysicalDeviceDepthClipControlFeaturesEXT() + PhysicalDeviceDepthClipControlFeaturesEXT featuresDepthClipControl = new() { - SType = StructureType.PhysicalDeviceDepthClipControlFeaturesExt + SType = StructureType.PhysicalDeviceDepthClipControlFeaturesExt, }; - PhysicalDevicePortabilitySubsetFeaturesKHR featuresPortabilitySubset = new PhysicalDevicePortabilitySubsetFeaturesKHR() + PhysicalDevicePortabilitySubsetFeaturesKHR featuresPortabilitySubset = new() { - SType = StructureType.PhysicalDevicePortabilitySubsetFeaturesKhr + SType = StructureType.PhysicalDevicePortabilitySubsetFeaturesKhr, }; if (_physicalDevice.IsDeviceExtensionPresent("VK_EXT_primitive_topology_list_restart")) @@ -359,7 +362,7 @@ namespace Ryujinx.Graphics.Vulkan _counters = new Counters(this, _device, _pipeline); } - private unsafe void SetupContext(GraphicsDebugLevel logLevel) + private void SetupContext(GraphicsDebugLevel logLevel) { _instance = VulkanInitialization.CreateInstance(Api, logLevel, _getRequiredExtensions()); _debugMessenger = new VulkanDebugMessenger(Api, _instance.Instance, logLevel); @@ -415,10 +418,8 @@ namespace Ryujinx.Graphics.Vulkan { return new ShaderCollection(this, _device, sources, info.ResourceLayout, info.State ?? default, info.FromCache); } - else - { - return new ShaderCollection(this, _device, sources, info.ResourceLayout); - } + + return new ShaderCollection(this, _device, sources, info.ResourceLayout); } internal ShaderCollection CreateProgramWithMinimalLayout(ShaderSource[] sources, ResourceLayout resourceLayout, SpecDescription[] specDescription = null) @@ -426,7 +427,7 @@ namespace Ryujinx.Graphics.Vulkan return new ShaderCollection(this, _device, sources, resourceLayout, specDescription, isMinimal: true); } - public ISampler CreateSampler(GAL.SamplerCreateInfo info) + public ISampler CreateSampler(SamplerCreateInfo info) { return new SamplerHolder(this, _device, info); } @@ -483,83 +484,83 @@ namespace Ryujinx.Graphics.Vulkan FormatFeatureFlags.TransferDstBit; bool supportsBc123CompressionFormat = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags, - GAL.Format.Bc1RgbaSrgb, - GAL.Format.Bc1RgbaUnorm, - GAL.Format.Bc2Srgb, - GAL.Format.Bc2Unorm, - GAL.Format.Bc3Srgb, - GAL.Format.Bc3Unorm); + Format.Bc1RgbaSrgb, + Format.Bc1RgbaUnorm, + Format.Bc2Srgb, + Format.Bc2Unorm, + Format.Bc3Srgb, + Format.Bc3Unorm); bool supportsBc45CompressionFormat = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags, - GAL.Format.Bc4Snorm, - GAL.Format.Bc4Unorm, - GAL.Format.Bc5Snorm, - GAL.Format.Bc5Unorm); + Format.Bc4Snorm, + Format.Bc4Unorm, + Format.Bc5Snorm, + Format.Bc5Unorm); bool supportsBc67CompressionFormat = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags, - GAL.Format.Bc6HSfloat, - GAL.Format.Bc6HUfloat, - GAL.Format.Bc7Srgb, - GAL.Format.Bc7Unorm); + Format.Bc6HSfloat, + Format.Bc6HUfloat, + Format.Bc7Srgb, + Format.Bc7Unorm); bool supportsEtc2CompressionFormat = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags, - GAL.Format.Etc2RgbaSrgb, - GAL.Format.Etc2RgbaUnorm, - GAL.Format.Etc2RgbPtaSrgb, - GAL.Format.Etc2RgbPtaUnorm, - GAL.Format.Etc2RgbSrgb, - GAL.Format.Etc2RgbUnorm); + Format.Etc2RgbaSrgb, + Format.Etc2RgbaUnorm, + Format.Etc2RgbPtaSrgb, + Format.Etc2RgbPtaUnorm, + Format.Etc2RgbSrgb, + Format.Etc2RgbUnorm); bool supports5BitComponentFormat = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags, - GAL.Format.R5G6B5Unorm, - GAL.Format.R5G5B5A1Unorm, - GAL.Format.R5G5B5X1Unorm, - GAL.Format.B5G6R5Unorm, - GAL.Format.B5G5R5A1Unorm, - GAL.Format.A1B5G5R5Unorm); + Format.R5G6B5Unorm, + Format.R5G5B5A1Unorm, + Format.R5G5B5X1Unorm, + Format.B5G6R5Unorm, + Format.B5G5R5A1Unorm, + Format.A1B5G5R5Unorm); bool supportsR4G4B4A4Format = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags, - GAL.Format.R4G4B4A4Unorm); + Format.R4G4B4A4Unorm); bool supportsAstcFormats = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags, - GAL.Format.Astc4x4Unorm, - GAL.Format.Astc5x4Unorm, - GAL.Format.Astc5x5Unorm, - GAL.Format.Astc6x5Unorm, - GAL.Format.Astc6x6Unorm, - GAL.Format.Astc8x5Unorm, - GAL.Format.Astc8x6Unorm, - GAL.Format.Astc8x8Unorm, - GAL.Format.Astc10x5Unorm, - GAL.Format.Astc10x6Unorm, - GAL.Format.Astc10x8Unorm, - GAL.Format.Astc10x10Unorm, - GAL.Format.Astc12x10Unorm, - GAL.Format.Astc12x12Unorm, - GAL.Format.Astc4x4Srgb, - GAL.Format.Astc5x4Srgb, - GAL.Format.Astc5x5Srgb, - GAL.Format.Astc6x5Srgb, - GAL.Format.Astc6x6Srgb, - GAL.Format.Astc8x5Srgb, - GAL.Format.Astc8x6Srgb, - GAL.Format.Astc8x8Srgb, - GAL.Format.Astc10x5Srgb, - GAL.Format.Astc10x6Srgb, - GAL.Format.Astc10x8Srgb, - GAL.Format.Astc10x10Srgb, - GAL.Format.Astc12x10Srgb, - GAL.Format.Astc12x12Srgb); + Format.Astc4x4Unorm, + Format.Astc5x4Unorm, + Format.Astc5x5Unorm, + Format.Astc6x5Unorm, + Format.Astc6x6Unorm, + Format.Astc8x5Unorm, + Format.Astc8x6Unorm, + Format.Astc8x8Unorm, + Format.Astc10x5Unorm, + Format.Astc10x6Unorm, + Format.Astc10x8Unorm, + Format.Astc10x10Unorm, + Format.Astc12x10Unorm, + Format.Astc12x12Unorm, + Format.Astc4x4Srgb, + Format.Astc5x4Srgb, + Format.Astc5x5Srgb, + Format.Astc6x5Srgb, + Format.Astc6x6Srgb, + Format.Astc8x5Srgb, + Format.Astc8x6Srgb, + Format.Astc8x8Srgb, + Format.Astc10x5Srgb, + Format.Astc10x6Srgb, + Format.Astc10x8Srgb, + Format.Astc10x10Srgb, + Format.Astc12x10Srgb, + Format.Astc12x12Srgb); - PhysicalDeviceVulkan12Features featuresVk12 = new PhysicalDeviceVulkan12Features() + PhysicalDeviceVulkan12Features featuresVk12 = new() { - SType = StructureType.PhysicalDeviceVulkan12Features + SType = StructureType.PhysicalDeviceVulkan12Features, }; - PhysicalDeviceFeatures2 features2 = new PhysicalDeviceFeatures2() + PhysicalDeviceFeatures2 features2 = new() { SType = StructureType.PhysicalDeviceFeatures2, - PNext = &featuresVk12 + PNext = &featuresVk12, }; Api.GetPhysicalDeviceFeatures2(_physicalDevice.PhysicalDevice, &features2); @@ -665,10 +666,8 @@ namespace Ryujinx.Graphics.Vulkan { return $"{(driverVersionRaw >> 22) & 0x3FF}.{(driverVersionRaw >> 14) & 0xFF}.{(driverVersionRaw >> 6) & 0xFF}.{driverVersionRaw & 0x3F}"; } - else - { - return ParseStandardVulkanVersion(driverVersionRaw); - } + + return ParseStandardVulkanVersion(driverVersionRaw); } private unsafe void PrintGpuInformation() @@ -696,24 +695,24 @@ namespace Ryujinx.Graphics.Vulkan Logger.Notice.Print(LogClass.Gpu, $"{GpuVendor} {GpuRenderer} ({GpuVersion})"); } - internal GAL.PrimitiveTopology TopologyRemap(GAL.PrimitiveTopology topology) + internal PrimitiveTopology TopologyRemap(PrimitiveTopology topology) { return topology switch { - GAL.PrimitiveTopology.Quads => GAL.PrimitiveTopology.Triangles, - GAL.PrimitiveTopology.QuadStrip => GAL.PrimitiveTopology.TriangleStrip, - GAL.PrimitiveTopology.TriangleFan => Capabilities.PortabilitySubset.HasFlag(PortabilitySubsetFlags.NoTriangleFans) ? GAL.PrimitiveTopology.Triangles : topology, - _ => topology + PrimitiveTopology.Quads => PrimitiveTopology.Triangles, + PrimitiveTopology.QuadStrip => PrimitiveTopology.TriangleStrip, + PrimitiveTopology.TriangleFan => Capabilities.PortabilitySubset.HasFlag(PortabilitySubsetFlags.NoTriangleFans) ? PrimitiveTopology.Triangles : topology, + _ => topology, }; } - internal bool TopologyUnsupported(GAL.PrimitiveTopology topology) + internal bool TopologyUnsupported(PrimitiveTopology topology) { return topology switch { - GAL.PrimitiveTopology.Quads => true, - GAL.PrimitiveTopology.TriangleFan => Capabilities.PortabilitySubset.HasFlag(PortabilitySubsetFlags.NoTriangleFans), - _ => false + PrimitiveTopology.Quads => true, + PrimitiveTopology.TriangleFan => Capabilities.PortabilitySubset.HasFlag(PortabilitySubsetFlags.NoTriangleFans), + _ => false, }; } @@ -873,4 +872,4 @@ namespace Ryujinx.Graphics.Vulkan HostMemoryAllocator.TryImport(BufferManager.HostImportedBufferMemoryRequirements, BufferManager.DefaultBufferMemoryFlags, address, size); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Graphics.Vulkan/Window.cs b/src/Ryujinx.Graphics.Vulkan/Window.cs index 075d1b303..0a41e98df 100644 --- a/src/Ryujinx.Graphics.Vulkan/Window.cs +++ b/src/Ryujinx.Graphics.Vulkan/Window.cs @@ -48,9 +48,9 @@ namespace Ryujinx.Graphics.Vulkan CreateSwapchain(); - var semaphoreCreateInfo = new SemaphoreCreateInfo() + var semaphoreCreateInfo = new SemaphoreCreateInfo { - SType = StructureType.SemaphoreCreateInfo + SType = StructureType.SemaphoreCreateInfo, }; gd.Api.CreateSemaphore(device, semaphoreCreateInfo, null, out _imageAvailableSemaphore).ThrowOnError(); @@ -116,7 +116,7 @@ namespace Ryujinx.Graphics.Vulkan var oldSwapchain = _swapchain; - var swapchainCreateInfo = new SwapchainCreateInfoKHR() + var swapchainCreateInfo = new SwapchainCreateInfoKHR { SType = StructureType.SwapchainCreateInfoKhr, Surface = _surface, @@ -130,7 +130,7 @@ namespace Ryujinx.Graphics.Vulkan PreTransform = capabilities.CurrentTransform, CompositeAlpha = ChooseCompositeAlpha(capabilities.SupportedCompositeAlpha), PresentMode = ChooseSwapPresentMode(presentModes, _vsyncEnabled), - Clipped = true + Clipped = true, }; _gd.SwapchainApi.CreateSwapchain(_device, swapchainCreateInfo, null, out _swapchain).ThrowOnError(); @@ -164,14 +164,14 @@ namespace Ryujinx.Graphics.Vulkan var subresourceRange = new ImageSubresourceRange(aspectFlags, 0, 1, 0, 1); - var imageCreateInfo = new ImageViewCreateInfo() + var imageCreateInfo = new ImageViewCreateInfo { SType = StructureType.ImageViewCreateInfo, Image = swapchainImage, ViewType = ImageViewType.Type2D, Format = format, Components = componentMapping, - SubresourceRange = subresourceRange + SubresourceRange = subresourceRange, }; _gd.Api.CreateImageView(_device, imageCreateInfo, null, out var imageView).ThrowOnError(); @@ -234,13 +234,11 @@ namespace Ryujinx.Graphics.Vulkan { return capabilities.CurrentExtent; } - else - { - uint width = Math.Max(capabilities.MinImageExtent.Width, Math.Min(capabilities.MaxImageExtent.Width, SurfaceWidth)); - uint height = Math.Max(capabilities.MinImageExtent.Height, Math.Min(capabilities.MaxImageExtent.Height, SurfaceHeight)); - return new Extent2D(width, height); - } + uint width = Math.Max(capabilities.MinImageExtent.Width, Math.Min(capabilities.MaxImageExtent.Width, SurfaceWidth)); + uint height = Math.Max(capabilities.MinImageExtent.Height, Math.Min(capabilities.MaxImageExtent.Height, SurfaceHeight)); + + return new Extent2D(width, height); } public unsafe override void Present(ITexture texture, ImageCrop crop, Action swapBuffersCallback) @@ -350,10 +348,10 @@ namespace Ryujinx.Graphics.Vulkan float ratioX = crop.IsStretched ? 1.0f : MathF.Min(1.0f, _height * crop.AspectRatioX / (_width * crop.AspectRatioY)); float ratioY = crop.IsStretched ? 1.0f : MathF.Min(1.0f, _width * crop.AspectRatioY / (_height * crop.AspectRatioX)); - int dstWidth = (int)(_width * ratioX); + int dstWidth = (int)(_width * ratioX); int dstHeight = (int)(_height * ratioY); - int dstPaddingX = (_width - dstWidth) / 2; + int dstPaddingX = (_width - dstWidth) / 2; int dstPaddingY = (_height - dstHeight) / 2; int dstX0 = crop.FlipX ? _width - dstPaddingX : dstPaddingX; @@ -413,7 +411,7 @@ namespace Ryujinx.Graphics.Vulkan Result result; - var presentInfo = new PresentInfoKHR() + var presentInfo = new PresentInfoKHR { SType = StructureType.PresentInfoKhr, WaitSemaphoreCount = 1, @@ -421,7 +419,7 @@ namespace Ryujinx.Graphics.Vulkan SwapchainCount = 1, PSwapchains = &swapchain, PImageIndices = &nextImage, - PResults = &result + PResults = &result, }; lock (_gd.QueueLock) @@ -529,7 +527,7 @@ namespace Ryujinx.Graphics.Vulkan { var subresourceRange = new ImageSubresourceRange(ImageAspectFlags.ColorBit, 0, 1, 0, 1); - var barrier = new ImageMemoryBarrier() + var barrier = new ImageMemoryBarrier { SType = StructureType.ImageMemoryBarrier, SrcAccessMask = srcAccess, @@ -539,7 +537,7 @@ namespace Ryujinx.Graphics.Vulkan SrcQueueFamilyIndex = Vk.QueueFamilyIgnored, DstQueueFamilyIndex = Vk.QueueFamilyIgnored, Image = image, - SubresourceRange = subresourceRange + SubresourceRange = subresourceRange, }; _gd.Api.CmdPipelineBarrier( diff --git a/src/Ryujinx.Graphics.Vulkan/WindowBase.cs b/src/Ryujinx.Graphics.Vulkan/WindowBase.cs index 0a365e8fb..146cf6607 100644 --- a/src/Ryujinx.Graphics.Vulkan/WindowBase.cs +++ b/src/Ryujinx.Graphics.Vulkan/WindowBase.cs @@ -3,7 +3,7 @@ using System; namespace Ryujinx.Graphics.Vulkan { - internal abstract class WindowBase: IWindow + internal abstract class WindowBase : IWindow { public bool ScreenCaptureRequested { get; set; } @@ -15,4 +15,4 @@ namespace Ryujinx.Graphics.Vulkan public abstract void SetScalingFilter(ScalingFilter scalerType); public abstract void SetScalingFilterLevel(float scale); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.HLE/HOS/Services/Audio/AudioInManager.cs b/src/Ryujinx.HLE/HOS/Services/Audio/AudioInManager.cs index 2d342206b..36b0ed282 100644 --- a/src/Ryujinx.HLE/HOS/Services/Audio/AudioInManager.cs +++ b/src/Ryujinx.HLE/HOS/Services/Audio/AudioInManager.cs @@ -1,7 +1,6 @@ using Ryujinx.Audio.Common; using Ryujinx.Audio.Input; using Ryujinx.HLE.HOS.Services.Audio.AudioIn; - using AudioInManagerImpl = Ryujinx.Audio.Input.AudioInputManager; namespace Ryujinx.HLE.HOS.Services.Audio diff --git a/src/Ryujinx.HLE/HOS/Services/Audio/AudioOutManager.cs b/src/Ryujinx.HLE/HOS/Services/Audio/AudioOutManager.cs index 7b2891963..e95de0575 100644 --- a/src/Ryujinx.HLE/HOS/Services/Audio/AudioOutManager.cs +++ b/src/Ryujinx.HLE/HOS/Services/Audio/AudioOutManager.cs @@ -1,7 +1,6 @@ using Ryujinx.Audio.Common; using Ryujinx.Audio.Output; using Ryujinx.HLE.HOS.Services.Audio.AudioOut; - using AudioOutManagerImpl = Ryujinx.Audio.Output.AudioOutputManager; namespace Ryujinx.HLE.HOS.Services.Audio diff --git a/src/Ryujinx.Horizon/Bcat/BcatIpcServer.cs b/src/Ryujinx.Horizon/Bcat/BcatIpcServer.cs index 4a5378af2..f39929ddc 100644 --- a/src/Ryujinx.Horizon/Bcat/BcatIpcServer.cs +++ b/src/Ryujinx.Horizon/Bcat/BcatIpcServer.cs @@ -1,5 +1,4 @@ -using Ryujinx.Horizon.Bcat.Ipc; -using Ryujinx.Horizon.Bcat.Types; +using Ryujinx.Horizon.Bcat.Types; using Ryujinx.Horizon.Sdk.Sf.Hipc; using Ryujinx.Horizon.Sdk.Sm; @@ -8,7 +7,7 @@ namespace Ryujinx.Horizon.Bcat internal class BcatIpcServer { private const int BcatMaxSessionsCount = 8; - private const int BcatTotalMaxSessionsCount = BcatMaxSessionsCount * 4; + private const int BcatTotalMaxSessionsCount = BcatMaxSessionsCount * 4; private const int PointerBufferSize = 0x400; private const int MaxDomains = 64; @@ -29,10 +28,12 @@ namespace Ryujinx.Horizon.Bcat _serverManager = new BcatServerManager(allocator, _sm, MaxPortsCount, _bcatManagerOptions, BcatTotalMaxSessionsCount); +#pragma warning disable IDE0055 // Disable formatting _serverManager.RegisterServer((int)BcatPortIndex.Admin, ServiceName.Encode("bcat:a"), BcatMaxSessionsCount); _serverManager.RegisterServer((int)BcatPortIndex.Manager, ServiceName.Encode("bcat:m"), BcatMaxSessionsCount); _serverManager.RegisterServer((int)BcatPortIndex.User, ServiceName.Encode("bcat:u"), BcatMaxSessionsCount); _serverManager.RegisterServer((int)BcatPortIndex.System, ServiceName.Encode("bcat:s"), BcatMaxSessionsCount); +#pragma warning restore IDE0055 } public void ServiceRequests() diff --git a/src/Ryujinx.Horizon/Bcat/BcatMain.cs b/src/Ryujinx.Horizon/Bcat/BcatMain.cs index d4166fb18..f347e2166 100644 --- a/src/Ryujinx.Horizon/Bcat/BcatMain.cs +++ b/src/Ryujinx.Horizon/Bcat/BcatMain.cs @@ -1,11 +1,4 @@ -using Ryujinx.Horizon.LogManager; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Ryujinx.Horizon.Bcat +namespace Ryujinx.Horizon.Bcat { internal class BcatMain : IService { diff --git a/src/Ryujinx.Horizon/Bcat/BcatServerManager.cs b/src/Ryujinx.Horizon/Bcat/BcatServerManager.cs index f02eafd9d..0431bd9a9 100644 --- a/src/Ryujinx.Horizon/Bcat/BcatServerManager.cs +++ b/src/Ryujinx.Horizon/Bcat/BcatServerManager.cs @@ -17,12 +17,12 @@ namespace Ryujinx.Horizon.Bcat { return (BcatPortIndex)portIndex switch { - BcatPortIndex.Admin => AcceptImpl(server, new ServiceCreator("bcat:a", BcatServicePermissionLevel.Admin)), + BcatPortIndex.Admin => AcceptImpl(server, new ServiceCreator("bcat:a", BcatServicePermissionLevel.Admin)), BcatPortIndex.Manager => AcceptImpl(server, new ServiceCreator("bcat:m", BcatServicePermissionLevel.Manager)), - BcatPortIndex.User => AcceptImpl(server, new ServiceCreator("bcat:u", BcatServicePermissionLevel.User)), - BcatPortIndex.System => AcceptImpl(server, new ServiceCreator("bcat:s", BcatServicePermissionLevel.System)), - _ => throw new ArgumentOutOfRangeException(nameof(portIndex)), + BcatPortIndex.User => AcceptImpl(server, new ServiceCreator("bcat:u", BcatServicePermissionLevel.User)), + BcatPortIndex.System => AcceptImpl(server, new ServiceCreator("bcat:s", BcatServicePermissionLevel.System)), + _ => throw new ArgumentOutOfRangeException(nameof(portIndex)), }; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/BcatService.cs b/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/BcatService.cs index e82f597e9..9ea2dc11c 100644 --- a/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/BcatService.cs +++ b/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/BcatService.cs @@ -7,12 +7,7 @@ namespace Ryujinx.Horizon.Bcat.Ipc { partial class BcatService : IBcatService { - private readonly BcatServicePermissionLevel _permissionLevel; - - public BcatService(BcatServicePermissionLevel permissionLevel) - { - _permissionLevel = permissionLevel; - } + public BcatService(BcatServicePermissionLevel permissionLevel) { } [CmifCommand(10100)] public Result RequestSyncDeliveryCache(out IDeliveryCacheProgressService deliveryCacheProgressService) diff --git a/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/DeliveryCacheDirectoryService.cs b/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/DeliveryCacheDirectoryService.cs index dd13eefb4..c8b38c28f 100644 --- a/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/DeliveryCacheDirectoryService.cs +++ b/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/DeliveryCacheDirectoryService.cs @@ -26,7 +26,7 @@ namespace Ryujinx.Horizon.Bcat.Ipc } [CmifCommand(1)] - public Result Read(out int entriesRead, [Buffer(Sdk.Sf.Hipc.HipcBufferFlags.Out | HipcBufferFlags.MapAlias)] Span entriesBuffer) + public Result Read(out int entriesRead, [Buffer(HipcBufferFlags.Out | HipcBufferFlags.MapAlias)] Span entriesBuffer) { return _libHacService.Get.Read(out entriesRead, entriesBuffer).ToHorizonResult(); } diff --git a/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/DeliveryCacheFileService.cs b/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/DeliveryCacheFileService.cs index d23f5f41f..a26c3258f 100644 --- a/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/DeliveryCacheFileService.cs +++ b/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/DeliveryCacheFileService.cs @@ -28,7 +28,7 @@ namespace Ryujinx.Horizon.Bcat.Ipc [CmifCommand(1)] public Result Read(long offset, out long bytesRead, [Buffer(HipcBufferFlags.Out | HipcBufferFlags.MapAlias)] Span data) { - return _libHacService.Get.Read(out bytesRead, offset, data).ToHorizonResult(); + return _libHacService.Get.Read(out bytesRead, offset, data).ToHorizonResult(); } [CmifCommand(2)] diff --git a/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/DeliveryCacheProgressService.cs b/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/DeliveryCacheProgressService.cs index 91aa26867..578c18f43 100644 --- a/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/DeliveryCacheProgressService.cs +++ b/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/DeliveryCacheProgressService.cs @@ -39,7 +39,7 @@ namespace Ryujinx.Horizon.Bcat.Ipc deliveryCacheProgressImpl = new DeliveryCacheProgressImpl { State = DeliveryCacheProgressImpl.Status.Done, - Result = 0 + Result = 0, }; Logger.Stub?.PrintStub(LogClass.ServiceBcat); diff --git a/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/Types/DeliveryCacheProgressImpl.cs b/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/Types/DeliveryCacheProgressImpl.cs index 10e0b54fe..9e5274a61 100644 --- a/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/Types/DeliveryCacheProgressImpl.cs +++ b/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/Types/DeliveryCacheProgressImpl.cs @@ -8,11 +8,11 @@ namespace Ryujinx.Horizon.Bcat.Ipc.Types public enum Status { // TODO: determine other values - Done = 9 + Done = 9, } public Status State; - public uint Result; + public uint Result; // TODO: reverse the rest of the structure } } diff --git a/src/Ryujinx.Horizon/Bcat/Types/BcatPortIndex.cs b/src/Ryujinx.Horizon/Bcat/Types/BcatPortIndex.cs index e448dfdcd..958517892 100644 --- a/src/Ryujinx.Horizon/Bcat/Types/BcatPortIndex.cs +++ b/src/Ryujinx.Horizon/Bcat/Types/BcatPortIndex.cs @@ -5,6 +5,6 @@ Admin, Manager, User, - System + System, } } diff --git a/src/Ryujinx.Horizon/Bcat/Types/BcatServicePermissionLevel.cs b/src/Ryujinx.Horizon/Bcat/Types/BcatServicePermissionLevel.cs index 54d7461a7..6bf4b4cc0 100644 --- a/src/Ryujinx.Horizon/Bcat/Types/BcatServicePermissionLevel.cs +++ b/src/Ryujinx.Horizon/Bcat/Types/BcatServicePermissionLevel.cs @@ -2,9 +2,9 @@ { enum BcatServicePermissionLevel { - Admin = -1, - User = 1, - System = 2, - Manager = 6 + Admin = -1, + User = 1, + System = 2, + Manager = 6, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/HeapAllocator.cs b/src/Ryujinx.Horizon/HeapAllocator.cs index 40ff14d09..fc125387e 100644 --- a/src/Ryujinx.Horizon/HeapAllocator.cs +++ b/src/Ryujinx.Horizon/HeapAllocator.cs @@ -9,15 +9,15 @@ namespace Ryujinx.Horizon { private const ulong InvalidAddress = ulong.MaxValue; - private struct Range : IComparable + private readonly struct Range : IComparable { public ulong Offset { get; } - public ulong Size { get; } + public ulong Size { get; } public Range(ulong offset, ulong size) { Offset = offset; - Size = size; + Size = size; } public int CompareTo(Range other) @@ -31,7 +31,7 @@ namespace Ryujinx.Horizon public HeapAllocator() { - _freeRanges = new List(); + _freeRanges = new List(); _currentHeapSize = 0; } @@ -70,8 +70,8 @@ namespace Ryujinx.Horizon var range = _freeRanges[i]; ulong alignedOffset = BitUtils.AlignUp(range.Offset, alignment); - ulong sizeDelta = alignedOffset - range.Offset; - ulong usableSize = range.Size - sizeDelta; + ulong sizeDelta = alignedOffset - range.Offset; + ulong usableSize = range.Size - sizeDelta; if (sizeDelta < range.Size && usableSize >= size) { @@ -82,7 +82,7 @@ namespace Ryujinx.Horizon InsertFreeRange(range.Offset, sizeDelta); } - ulong endOffset = range.Offset + range.Size; + ulong endOffset = range.Offset + range.Size; ulong remainingSize = endOffset - (alignedOffset + size); if (remainingSize != 0) { @@ -140,4 +140,4 @@ namespace Ryujinx.Horizon _freeRanges.Insert(index, range); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/HorizonOptions.cs b/src/Ryujinx.Horizon/HorizonOptions.cs index 1ec56bfa7..75cc29b72 100644 --- a/src/Ryujinx.Horizon/HorizonOptions.cs +++ b/src/Ryujinx.Horizon/HorizonOptions.cs @@ -2,18 +2,18 @@ using LibHac; namespace Ryujinx.Horizon { - public struct HorizonOptions + public readonly struct HorizonOptions { - public bool IgnoreMissingServices { get; } + public bool IgnoreMissingServices { get; } public bool ThrowOnInvalidCommandIds { get; } public HorizonClient BcatClient { get; } public HorizonOptions(bool ignoreMissingServices, HorizonClient bcatClient) { - IgnoreMissingServices = ignoreMissingServices; + IgnoreMissingServices = ignoreMissingServices; ThrowOnInvalidCommandIds = true; - BcatClient = bcatClient; + BcatClient = bcatClient; } } } diff --git a/src/Ryujinx.Horizon/HorizonStatic.cs b/src/Ryujinx.Horizon/HorizonStatic.cs index e372df699..1e483cd44 100644 --- a/src/Ryujinx.Horizon/HorizonStatic.cs +++ b/src/Ryujinx.Horizon/HorizonStatic.cs @@ -21,24 +21,24 @@ namespace Ryujinx.Horizon [ThreadStatic] private static int _threadHandle; - public static HorizonOptions Options => _options; - public static ISyscallApi Syscall => _syscall; - public static IVirtualMemoryManager AddressSpace => _addressSpace; - public static IThreadContext ThreadContext => _threadContext; - public static int CurrentThreadHandle => _threadHandle; + public static HorizonOptions Options => _options; + public static ISyscallApi Syscall => _syscall; + public static IVirtualMemoryManager AddressSpace => _addressSpace; + public static IThreadContext ThreadContext => _threadContext; + public static int CurrentThreadHandle => _threadHandle; public static void Register( - HorizonOptions options, - ISyscallApi syscallApi, + HorizonOptions options, + ISyscallApi syscallApi, IVirtualMemoryManager addressSpace, - IThreadContext threadContext, - int threadHandle) + IThreadContext threadContext, + int threadHandle) { - _options = options; - _syscall = syscallApi; - _addressSpace = addressSpace; + _options = options; + _syscall = syscallApi; + _addressSpace = addressSpace; _threadContext = threadContext; - _threadHandle = threadHandle; + _threadHandle = threadHandle; } } } diff --git a/src/Ryujinx.Horizon/LogManager/Ipc/LmLogger.cs b/src/Ryujinx.Horizon/LogManager/Ipc/LmLogger.cs index 88dddef5e..b6460a4bc 100644 --- a/src/Ryujinx.Horizon/LogManager/Ipc/LmLogger.cs +++ b/src/Ryujinx.Horizon/LogManager/Ipc/LmLogger.cs @@ -95,74 +95,52 @@ namespace Ryujinx.Horizon.LogManager.Ipc LogDataChunkKey key = (LogDataChunkKey)type; - if (key == LogDataChunkKey.Start) + switch (key) { - reader.Skip(size); - - continue; - } - else if (key == LogDataChunkKey.Stop) - { - break; - } - else if (key == LogDataChunkKey.Line) - { - if (!reader.TryRead(out _logPacket.Line)) - { + case LogDataChunkKey.Start: + reader.Skip(size); + continue; + case LogDataChunkKey.Stop: + break; + case LogDataChunkKey.Line when !reader.TryRead(out _logPacket.Line): + case LogDataChunkKey.DropCount when !reader.TryRead(out _logPacket.DropCount): + case LogDataChunkKey.Time when !reader.TryRead(out _logPacket.Time): return true; - } - } - else if (key == LogDataChunkKey.DropCount) - { - if (!reader.TryRead(out _logPacket.DropCount)) - { - return true; - } - } - else if (key == LogDataChunkKey.Time) - { - if (!reader.TryRead(out _logPacket.Time)) - { - return true; - } - } - else if (key == LogDataChunkKey.Message) - { - string text = Encoding.UTF8.GetString(reader.GetSpanSafe(size)).TrimEnd(); - - if (isHeadPacket && isTailPacket) - { - _logPacket.Message = text; - } - else - { - _logPacket.Message += text; - - if (_logPacket.Message.Length >= MessageLengthLimit) + case LogDataChunkKey.Message: { - isTailPacket = true; + string text = Encoding.UTF8.GetString(reader.GetSpanSafe(size)).TrimEnd(); + + if (isHeadPacket && isTailPacket) + { + _logPacket.Message = text; + } + else + { + _logPacket.Message += text; + + if (_logPacket.Message.Length >= MessageLengthLimit) + { + isTailPacket = true; + } + } + + break; } - } - } - else if (key == LogDataChunkKey.Filename) - { - _logPacket.Filename = Encoding.UTF8.GetString(reader.GetSpanSafe(size)).TrimEnd(); - } - else if (key == LogDataChunkKey.Function) - { - _logPacket.Function = Encoding.UTF8.GetString(reader.GetSpanSafe(size)).TrimEnd(); - } - else if (key == LogDataChunkKey.Module) - { - _logPacket.Module = Encoding.UTF8.GetString(reader.GetSpanSafe(size)).TrimEnd(); - } - else if (key == LogDataChunkKey.Thread) - { - _logPacket.Thread = Encoding.UTF8.GetString(reader.GetSpanSafe(size)).TrimEnd(); - } - else if (key == LogDataChunkKey.ProgramName) - { - _logPacket.ProgramName = Encoding.UTF8.GetString(reader.GetSpanSafe(size)).TrimEnd(); + case LogDataChunkKey.Filename: + _logPacket.Filename = Encoding.UTF8.GetString(reader.GetSpanSafe(size)).TrimEnd(); + break; + case LogDataChunkKey.Function: + _logPacket.Function = Encoding.UTF8.GetString(reader.GetSpanSafe(size)).TrimEnd(); + break; + case LogDataChunkKey.Module: + _logPacket.Module = Encoding.UTF8.GetString(reader.GetSpanSafe(size)).TrimEnd(); + break; + case LogDataChunkKey.Thread: + _logPacket.Thread = Encoding.UTF8.GetString(reader.GetSpanSafe(size)).TrimEnd(); + break; + case LogDataChunkKey.ProgramName: + _logPacket.ProgramName = Encoding.UTF8.GetString(reader.GetSpanSafe(size)).TrimEnd(); + break; } } @@ -177,7 +155,7 @@ namespace Ryujinx.Horizon.LogManager.Ipc do { - if (!reader.TryRead(out encoded)) + if (!reader.TryRead(out encoded)) { return false; } @@ -190,4 +168,4 @@ namespace Ryujinx.Horizon.LogManager.Ipc return true; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/LogManager/Ipc/LogService.cs b/src/Ryujinx.Horizon/LogManager/Ipc/LogService.cs index 6899739e3..9ac9c27e6 100644 --- a/src/Ryujinx.Horizon/LogManager/Ipc/LogService.cs +++ b/src/Ryujinx.Horizon/LogManager/Ipc/LogService.cs @@ -17,4 +17,4 @@ namespace Ryujinx.Horizon.LogManager.Ipc return Result.Success; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/LogManager/LmIpcServer.cs b/src/Ryujinx.Horizon/LogManager/LmIpcServer.cs index 71b844a2b..d1a405b87 100644 --- a/src/Ryujinx.Horizon/LogManager/LmIpcServer.cs +++ b/src/Ryujinx.Horizon/LogManager/LmIpcServer.cs @@ -9,13 +9,13 @@ namespace Ryujinx.Horizon.LogManager private const int LogMaxSessionsCount = 42; private const int PointerBufferSize = 0x400; - private const int MaxDomains = 31; - private const int MaxDomainObjects = 61; - private const int MaxPortsCount = 1; + private const int MaxDomains = 31; + private const int MaxDomainObjects = 61; + private const int MaxPortsCount = 1; private static readonly ManagerOptions _logManagerOptions = new(PointerBufferSize, MaxDomains, MaxDomainObjects, false); - private SmApi _sm; + private SmApi _sm; private ServerManager _serverManager; public void Initialize() @@ -40,4 +40,4 @@ namespace Ryujinx.Horizon.LogManager _serverManager.Dispose(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/LogManager/LmMain.cs b/src/Ryujinx.Horizon/LogManager/LmMain.cs index bbe96d4c9..c229de597 100644 --- a/src/Ryujinx.Horizon/LogManager/LmMain.cs +++ b/src/Ryujinx.Horizon/LogManager/LmMain.cs @@ -14,4 +14,4 @@ ipcServer.Shutdown(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/LogManager/Types/LogPacket.cs b/src/Ryujinx.Horizon/LogManager/Types/LogPacket.cs index dbff5e3e2..57a389be9 100644 --- a/src/Ryujinx.Horizon/LogManager/Types/LogPacket.cs +++ b/src/Ryujinx.Horizon/LogManager/Types/LogPacket.cs @@ -5,15 +5,15 @@ namespace Ryujinx.Horizon.LogManager.Types { struct LogPacket { - public string Message; - public int Line; - public string Filename; - public string Function; - public string Module; - public string Thread; - public long DropCount; - public long Time; - public string ProgramName; + public string Message; + public int Line; + public string Filename; + public string Function; + public string Module; + public string Thread; + public long DropCount; + public long Time; + public string ProgramName; public LogSeverity Severity; public override string ToString() @@ -35,12 +35,12 @@ namespace Ryujinx.Horizon.LogManager.Types { builder.AppendLine($" ProgramName: {ProgramName}"); } - + if (!string.IsNullOrEmpty(Module)) { builder.AppendLine($" Module: {Module}"); } - + if (!string.IsNullOrEmpty(Thread)) { builder.AppendLine($" Thread: {Thread}"); @@ -69,4 +69,4 @@ namespace Ryujinx.Horizon.LogManager.Types return builder.ToString(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Prepo/Ipc/PrepoService.cs b/src/Ryujinx.Horizon/Prepo/Ipc/PrepoService.cs index e157fa562..f424b17e2 100644 --- a/src/Ryujinx.Horizon/Prepo/Ipc/PrepoService.cs +++ b/src/Ryujinx.Horizon/Prepo/Ipc/PrepoService.cs @@ -10,6 +10,7 @@ using Ryujinx.Horizon.Sdk.Sf; using Ryujinx.Horizon.Sdk.Sf.Hipc; using System; using System.Text; +using ApplicationId = Ryujinx.Horizon.Sdk.Ncm.ApplicationId; namespace Ryujinx.Horizon.Prepo.Ipc { @@ -18,14 +19,14 @@ namespace Ryujinx.Horizon.Prepo.Ipc enum PlayReportKind { Normal, - System + System, } private readonly PrepoServicePermissionLevel _permissionLevel; private ulong _systemSessionId; - private bool _immediateTransmissionEnabled = false; - private bool _userAgreementCheckEnabled = true; + private bool _immediateTransmissionEnabled; + private bool _userAgreementCheckEnabled = true; public PrepoService(PrepoServicePermissionLevel permissionLevel) { @@ -107,7 +108,7 @@ namespace Ryujinx.Horizon.Prepo.Ipc } [CmifCommand(20100)] - public Result SaveSystemReport([Buffer(HipcBufferFlags.In | HipcBufferFlags.Pointer)] ReadOnlySpan gameRoomBuffer, Sdk.Ncm.ApplicationId applicationId, [Buffer(HipcBufferFlags.In | HipcBufferFlags.MapAlias)] ReadOnlySpan reportBuffer) + public Result SaveSystemReport([Buffer(HipcBufferFlags.In | HipcBufferFlags.Pointer)] ReadOnlySpan gameRoomBuffer, ApplicationId applicationId, [Buffer(HipcBufferFlags.In | HipcBufferFlags.MapAlias)] ReadOnlySpan reportBuffer) { if ((_permissionLevel & PrepoServicePermissionLevel.System) != 0) { @@ -118,7 +119,7 @@ namespace Ryujinx.Horizon.Prepo.Ipc } [CmifCommand(20101)] - public Result SaveSystemReportWithUser(Uid userId, [Buffer(HipcBufferFlags.In | HipcBufferFlags.Pointer)] ReadOnlySpan gameRoomBuffer, Sdk.Ncm.ApplicationId applicationId, [Buffer(HipcBufferFlags.In | HipcBufferFlags.MapAlias)] ReadOnlySpan reportBuffer) + public Result SaveSystemReportWithUser(Uid userId, [Buffer(HipcBufferFlags.In | HipcBufferFlags.Pointer)] ReadOnlySpan gameRoomBuffer, ApplicationId applicationId, [Buffer(HipcBufferFlags.In | HipcBufferFlags.MapAlias)] ReadOnlySpan reportBuffer) { if ((_permissionLevel & PrepoServicePermissionLevel.System) != 0) { @@ -164,7 +165,7 @@ namespace Ryujinx.Horizon.Prepo.Ipc return PrepoResult.PermissionDenied; } - private static Result ProcessPlayReport(PlayReportKind playReportKind, ReadOnlySpan gameRoomBuffer, ReadOnlySpan reportBuffer, ulong pid, Uid userId, bool withUserId = false, Sdk.Ncm.ApplicationId applicationId = default) + private static Result ProcessPlayReport(PlayReportKind playReportKind, ReadOnlySpan gameRoomBuffer, ReadOnlySpan reportBuffer, ulong pid, Uid userId, bool withUserId = false, ApplicationId applicationId = default) { if (withUserId) { @@ -191,7 +192,7 @@ namespace Ryujinx.Horizon.Prepo.Ipc return PrepoResult.InvalidBufferSize; } - StringBuilder builder = new(); + StringBuilder builder = new(); MessagePackObject deserializedReport = MessagePackSerializer.UnpackMessagePackObject(reportBuffer.ToArray()); builder.AppendLine(); @@ -222,4 +223,4 @@ namespace Ryujinx.Horizon.Prepo.Ipc return Result.Success; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Prepo/PrepoIpcServer.cs b/src/Ryujinx.Horizon/Prepo/PrepoIpcServer.cs index b80399eaa..9c185520d 100644 --- a/src/Ryujinx.Horizon/Prepo/PrepoIpcServer.cs +++ b/src/Ryujinx.Horizon/Prepo/PrepoIpcServer.cs @@ -6,13 +6,13 @@ namespace Ryujinx.Horizon.Prepo { class PrepoIpcServer { - private const int PrepoMaxSessionsCount = 12; + private const int PrepoMaxSessionsCount = 12; private const int PrepoTotalMaxSessionsCount = PrepoMaxSessionsCount * 6; private const int PointerBufferSize = 0x80; - private const int MaxDomains = 64; - private const int MaxDomainObjects = 16; - private const int MaxPortsCount = 6; + private const int MaxDomains = 64; + private const int MaxDomainObjects = 16; + private const int MaxPortsCount = 6; private static readonly ManagerOptions _prepoManagerOptions = new(PointerBufferSize, MaxDomains, MaxDomainObjects, false); @@ -28,12 +28,14 @@ namespace Ryujinx.Horizon.Prepo _serverManager = new PrepoServerManager(allocator, _sm, MaxPortsCount, _prepoManagerOptions, PrepoTotalMaxSessionsCount); +#pragma warning disable IDE0055 // Disable formatting _serverManager.RegisterServer((int)PrepoPortIndex.Admin, ServiceName.Encode("prepo:a"), PrepoMaxSessionsCount); // 1.0.0-5.1.0 _serverManager.RegisterServer((int)PrepoPortIndex.Admin2, ServiceName.Encode("prepo:a2"), PrepoMaxSessionsCount); // 6.0.0+ _serverManager.RegisterServer((int)PrepoPortIndex.Manager, ServiceName.Encode("prepo:m"), PrepoMaxSessionsCount); _serverManager.RegisterServer((int)PrepoPortIndex.User, ServiceName.Encode("prepo:u"), PrepoMaxSessionsCount); _serverManager.RegisterServer((int)PrepoPortIndex.System, ServiceName.Encode("prepo:s"), PrepoMaxSessionsCount); _serverManager.RegisterServer((int)PrepoPortIndex.Debug, ServiceName.Encode("prepo:d"), PrepoMaxSessionsCount); // 1.0.0 +#pragma warning restore IDE0055 } public void ServiceRequests() @@ -46,4 +48,4 @@ namespace Ryujinx.Horizon.Prepo _serverManager.Dispose(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Prepo/PrepoMain.cs b/src/Ryujinx.Horizon/Prepo/PrepoMain.cs index 5ff0f53d9..c311d619f 100644 --- a/src/Ryujinx.Horizon/Prepo/PrepoMain.cs +++ b/src/Ryujinx.Horizon/Prepo/PrepoMain.cs @@ -14,4 +14,4 @@ ipcServer.Shutdown(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Prepo/PrepoResult.cs b/src/Ryujinx.Horizon/Prepo/PrepoResult.cs index 12255e3d8..4c6bc7a45 100644 --- a/src/Ryujinx.Horizon/Prepo/PrepoResult.cs +++ b/src/Ryujinx.Horizon/Prepo/PrepoResult.cs @@ -6,10 +6,12 @@ namespace Ryujinx.Horizon.Prepo { private const int ModuleId = 129; +#pragma warning disable IDE0055 // Disable formatting public static Result InvalidArgument => new(ModuleId, 1); public static Result InvalidState => new(ModuleId, 5); public static Result InvalidBufferSize => new(ModuleId, 9); public static Result PermissionDenied => new(ModuleId, 90); public static Result InvalidPid => new(ModuleId, 101); +#pragma warning restore IDE0055 } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Prepo/PrepoServerManager.cs b/src/Ryujinx.Horizon/Prepo/PrepoServerManager.cs index 55e4ff7db..a79360953 100644 --- a/src/Ryujinx.Horizon/Prepo/PrepoServerManager.cs +++ b/src/Ryujinx.Horizon/Prepo/PrepoServerManager.cs @@ -17,6 +17,7 @@ namespace Ryujinx.Horizon.Prepo { return (PrepoPortIndex)portIndex switch { +#pragma warning disable IDE0055 // Disable formatting PrepoPortIndex.Admin => AcceptImpl(server, new PrepoService(PrepoServicePermissionLevel.Admin)), PrepoPortIndex.Admin2 => AcceptImpl(server, new PrepoService(PrepoServicePermissionLevel.Admin)), PrepoPortIndex.Manager => AcceptImpl(server, new PrepoService(PrepoServicePermissionLevel.Manager)), @@ -24,7 +25,8 @@ namespace Ryujinx.Horizon.Prepo PrepoPortIndex.System => AcceptImpl(server, new PrepoService(PrepoServicePermissionLevel.System)), PrepoPortIndex.Debug => AcceptImpl(server, new PrepoService(PrepoServicePermissionLevel.Debug)), _ => throw new ArgumentOutOfRangeException(nameof(portIndex)), +#pragma warning restore IDE0055 }; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Prepo/Types/PrepoPortIndex.cs b/src/Ryujinx.Horizon/Prepo/Types/PrepoPortIndex.cs index f4d6b8773..31c5b02d0 100644 --- a/src/Ryujinx.Horizon/Prepo/Types/PrepoPortIndex.cs +++ b/src/Ryujinx.Horizon/Prepo/Types/PrepoPortIndex.cs @@ -7,6 +7,6 @@ Manager, User, System, - Debug + Debug, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Prepo/Types/PrepoServicePermissionLevel.cs b/src/Ryujinx.Horizon/Prepo/Types/PrepoServicePermissionLevel.cs index 8214f4b9a..759c5018d 100644 --- a/src/Ryujinx.Horizon/Prepo/Types/PrepoServicePermissionLevel.cs +++ b/src/Ryujinx.Horizon/Prepo/Types/PrepoServicePermissionLevel.cs @@ -2,10 +2,10 @@ { enum PrepoServicePermissionLevel { - Admin = -1, - User = 1, - System = 2, + Admin = -1, + User = 1, + System = 2, Manager = 6, - Debug = unchecked((int)0x80000006) + Debug = unchecked((int)0x80000006), } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Account/Uid.cs b/src/Ryujinx.Horizon/Sdk/Account/Uid.cs index 5aad0463f..0175d393c 100644 --- a/src/Ryujinx.Horizon/Sdk/Account/Uid.cs +++ b/src/Ryujinx.Horizon/Sdk/Account/Uid.cs @@ -17,14 +17,14 @@ namespace Ryujinx.Horizon.Sdk.Account public Uid(long low, long high) { - Low = low; + Low = low; High = high; } public Uid(byte[] bytes) { High = BitConverter.ToInt64(bytes, 0); - Low = BitConverter.ToInt64(bytes, 8); + Low = BitConverter.ToInt64(bytes, 8); } public Uid(string hex) @@ -34,7 +34,7 @@ namespace Ryujinx.Horizon.Sdk.Account throw new ArgumentException("Invalid Hex value!", nameof(hex)); } - Low = Convert.ToInt64(hex[16..], 16); + Low = Convert.ToInt64(hex[16..], 16); High = Convert.ToInt64(hex[..16], 16); } @@ -59,4 +59,4 @@ namespace Ryujinx.Horizon.Sdk.Account return new UInt128((ulong)High, (ulong)Low); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Bcat/IServiceCreator.cs b/src/Ryujinx.Horizon/Sdk/Bcat/IServiceCreator.cs index edc525900..04f25259f 100644 --- a/src/Ryujinx.Horizon/Sdk/Bcat/IServiceCreator.cs +++ b/src/Ryujinx.Horizon/Sdk/Bcat/IServiceCreator.cs @@ -1,4 +1,5 @@ using Ryujinx.Horizon.Common; +using Ryujinx.Horizon.Sdk.Ncm; using Ryujinx.Horizon.Sdk.Sf; namespace Ryujinx.Horizon.Sdk.Bcat @@ -7,6 +8,6 @@ namespace Ryujinx.Horizon.Sdk.Bcat { Result CreateBcatService(out IBcatService service, ulong pid); Result CreateDeliveryCacheStorageService(out IDeliveryCacheStorageService service, ulong pid); - Result CreateDeliveryCacheStorageServiceWithApplicationId(out IDeliveryCacheStorageService service, Ncm.ApplicationId applicationId); + Result CreateDeliveryCacheStorageServiceWithApplicationId(out IDeliveryCacheStorageService service, ApplicationId applicationId); } } diff --git a/src/Ryujinx.Horizon/Sdk/Diag/LogSeverity.cs b/src/Ryujinx.Horizon/Sdk/Diag/LogSeverity.cs index 72acf7896..ecac00bb3 100644 --- a/src/Ryujinx.Horizon/Sdk/Diag/LogSeverity.cs +++ b/src/Ryujinx.Horizon/Sdk/Diag/LogSeverity.cs @@ -6,6 +6,6 @@ namespace Ryujinx.Horizon.Sdk.Diag Info = 1, Warn = 2, Error = 3, - Fatal = 4 + Fatal = 4, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Lm/ILmLogger.cs b/src/Ryujinx.Horizon/Sdk/Lm/ILmLogger.cs index bb5770cbc..42165aab3 100644 --- a/src/Ryujinx.Horizon/Sdk/Lm/ILmLogger.cs +++ b/src/Ryujinx.Horizon/Sdk/Lm/ILmLogger.cs @@ -9,4 +9,4 @@ namespace Ryujinx.Horizon.Sdk.Lm Result Log(Span message); Result SetDestination(LogDestination destination); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Lm/ILogService.cs b/src/Ryujinx.Horizon/Sdk/Lm/ILogService.cs index ad6c8455a..b66b91267 100644 --- a/src/Ryujinx.Horizon/Sdk/Lm/ILogService.cs +++ b/src/Ryujinx.Horizon/Sdk/Lm/ILogService.cs @@ -8,4 +8,4 @@ namespace Ryujinx.Horizon.Sdk.Lm { Result OpenLogger(out LmLogger logger, ulong pid); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Lm/LogDataChunkKey.cs b/src/Ryujinx.Horizon/Sdk/Lm/LogDataChunkKey.cs index 90756ece2..6905db0ce 100644 --- a/src/Ryujinx.Horizon/Sdk/Lm/LogDataChunkKey.cs +++ b/src/Ryujinx.Horizon/Sdk/Lm/LogDataChunkKey.cs @@ -14,6 +14,6 @@ namespace Ryujinx.Horizon.Sdk.Lm Time = 9, ProgramName = 10, - Count + Count, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Lm/LogDestination.cs b/src/Ryujinx.Horizon/Sdk/Lm/LogDestination.cs index 8b08548d6..d9078629a 100644 --- a/src/Ryujinx.Horizon/Sdk/Lm/LogDestination.cs +++ b/src/Ryujinx.Horizon/Sdk/Lm/LogDestination.cs @@ -9,6 +9,6 @@ namespace Ryujinx.Horizon.Sdk.Lm Uart = 1 << 1, UartIfSleep = 1 << 2, - All = 0xffff + All = 0xffff, } } diff --git a/src/Ryujinx.Horizon/Sdk/Lm/LogPacketFlags.cs b/src/Ryujinx.Horizon/Sdk/Lm/LogPacketFlags.cs index 75d9f40b9..e7d5d664f 100644 --- a/src/Ryujinx.Horizon/Sdk/Lm/LogPacketFlags.cs +++ b/src/Ryujinx.Horizon/Sdk/Lm/LogPacketFlags.cs @@ -7,6 +7,6 @@ namespace Ryujinx.Horizon.Sdk.Lm { IsHead = 1 << 0, IsTail = 1 << 1, - IsLittleEndian = 1 << 2 + IsLittleEndian = 1 << 2, } } diff --git a/src/Ryujinx.Horizon/Sdk/Ncm/ApplicationId.cs b/src/Ryujinx.Horizon/Sdk/Ncm/ApplicationId.cs index 37b4cbfbc..652589e1a 100644 --- a/src/Ryujinx.Horizon/Sdk/Ncm/ApplicationId.cs +++ b/src/Ryujinx.Horizon/Sdk/Ncm/ApplicationId.cs @@ -49,4 +49,4 @@ return $"0x{Id:x}"; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/OsTypes/EventClearMode.cs b/src/Ryujinx.Horizon/Sdk/OsTypes/EventClearMode.cs index b500e6b3c..b82518d79 100644 --- a/src/Ryujinx.Horizon/Sdk/OsTypes/EventClearMode.cs +++ b/src/Ryujinx.Horizon/Sdk/OsTypes/EventClearMode.cs @@ -3,6 +3,6 @@ enum EventClearMode { ManualClear, - AutoClear + AutoClear, } } diff --git a/src/Ryujinx.Horizon/Sdk/OsTypes/Impl/MultiWaitImpl.cs b/src/Ryujinx.Horizon/Sdk/OsTypes/Impl/MultiWaitImpl.cs index 04bc8d1db..ad57152cb 100644 --- a/src/Ryujinx.Horizon/Sdk/OsTypes/Impl/MultiWaitImpl.cs +++ b/src/Ryujinx.Horizon/Sdk/OsTypes/Impl/MultiWaitImpl.cs @@ -7,9 +7,9 @@ namespace Ryujinx.Horizon.Sdk.OsTypes.Impl { class MultiWaitImpl { - private const int WaitTimedOut = -1; + private const int WaitTimedOut = -1; private const int WaitCancelled = -2; - private const int WaitInvalid = -3; + private const int WaitInvalid = -3; private readonly List _multiWaits; @@ -63,10 +63,7 @@ namespace Ryujinx.Horizon.Sdk.OsTypes.Impl } } - if (result == null) - { - result = WaitAnyHandleImpl(infinite, timeout); - } + result ??= WaitAnyHandleImpl(infinite, timeout); UnlinkHoldersFromObjectsList(); _waitingThreadHandle = 0; @@ -98,7 +95,7 @@ namespace Ryujinx.Horizon.Sdk.OsTypes.Impl } else { - index = WaitSynchronization(objectHandles.Slice(0, count), minTimeout); + index = WaitSynchronization(objectHandles[..count], minTimeout); DebugUtil.Assert(index != WaitInvalid); } @@ -200,10 +197,8 @@ namespace Ryujinx.Horizon.Sdk.OsTypes.Impl { return WaitCancelled; } - else - { - result.AbortOnFailure(); - } + + result.AbortOnFailure(); return index; } diff --git a/src/Ryujinx.Horizon/Sdk/OsTypes/InitializationState.cs b/src/Ryujinx.Horizon/Sdk/OsTypes/InitializationState.cs index 45ffd2587..3d5bb8108 100644 --- a/src/Ryujinx.Horizon/Sdk/OsTypes/InitializationState.cs +++ b/src/Ryujinx.Horizon/Sdk/OsTypes/InitializationState.cs @@ -3,6 +3,6 @@ namespace Ryujinx.Horizon.Sdk.OsTypes enum InitializationState : byte { NotInitialized, - Initialized + Initialized, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/OsTypes/MultiWaitHolderOfEvent.cs b/src/Ryujinx.Horizon/Sdk/OsTypes/MultiWaitHolderOfEvent.cs index 37ac22f0b..f5597847a 100644 --- a/src/Ryujinx.Horizon/Sdk/OsTypes/MultiWaitHolderOfEvent.cs +++ b/src/Ryujinx.Horizon/Sdk/OsTypes/MultiWaitHolderOfEvent.cs @@ -4,7 +4,7 @@ namespace Ryujinx.Horizon.Sdk.OsTypes { class MultiWaitHolderOfEvent : MultiWaitHolder { - private Event _event; + private readonly Event _event; private LinkedListNode _node; public override TriBool Signaled diff --git a/src/Ryujinx.Horizon/Sdk/OsTypes/MultiWaitHolderOfHandle.cs b/src/Ryujinx.Horizon/Sdk/OsTypes/MultiWaitHolderOfHandle.cs index 6fc5c75b9..e5839a480 100644 --- a/src/Ryujinx.Horizon/Sdk/OsTypes/MultiWaitHolderOfHandle.cs +++ b/src/Ryujinx.Horizon/Sdk/OsTypes/MultiWaitHolderOfHandle.cs @@ -2,7 +2,7 @@ { class MultiWaitHolderOfHandle : MultiWaitHolder { - private int _handle; + private readonly int _handle; public override int Handle => _handle; diff --git a/src/Ryujinx.Horizon/Sdk/OsTypes/OsEvent.cs b/src/Ryujinx.Horizon/Sdk/OsTypes/OsEvent.cs index cc7e84836..eac5e7c43 100644 --- a/src/Ryujinx.Horizon/Sdk/OsTypes/OsEvent.cs +++ b/src/Ryujinx.Horizon/Sdk/OsTypes/OsEvent.cs @@ -15,7 +15,7 @@ namespace Ryujinx.Horizon.Sdk.OsTypes InitiallySignaled = signaled, ClearMode = clearMode, State = InitializationState.Initialized, - Lock = new object() + Lock = new object(), }; } diff --git a/src/Ryujinx.Horizon/Sdk/OsTypes/OsResult.cs b/src/Ryujinx.Horizon/Sdk/OsTypes/OsResult.cs index 86dcd1fad..302922f12 100644 --- a/src/Ryujinx.Horizon/Sdk/OsTypes/OsResult.cs +++ b/src/Ryujinx.Horizon/Sdk/OsTypes/OsResult.cs @@ -6,6 +6,6 @@ namespace Ryujinx.Horizon.Sdk.OsTypes { private const int ModuleId = 3; - public static Result OutOfResource => new Result(ModuleId, 9); + public static Result OutOfResource => new(ModuleId, 9); } } diff --git a/src/Ryujinx.Horizon/Sdk/OsTypes/SystemEventType.cs b/src/Ryujinx.Horizon/Sdk/OsTypes/SystemEventType.cs index 338493d23..dee0fa43a 100644 --- a/src/Ryujinx.Horizon/Sdk/OsTypes/SystemEventType.cs +++ b/src/Ryujinx.Horizon/Sdk/OsTypes/SystemEventType.cs @@ -6,12 +6,12 @@ { NotInitialized, InitializedAsEvent, - InitializedAsInterProcess + InitializedAsInterProcess, } public InterProcessEventType InterProcessEvent; public InitializationState State; - public bool NotInitialized => State == InitializationState.NotInitialized; + public readonly bool NotInitialized => State == InitializationState.NotInitialized; } } diff --git a/src/Ryujinx.Horizon/Sdk/OsTypes/TriBool.cs b/src/Ryujinx.Horizon/Sdk/OsTypes/TriBool.cs index 7debd9e27..868d10258 100644 --- a/src/Ryujinx.Horizon/Sdk/OsTypes/TriBool.cs +++ b/src/Ryujinx.Horizon/Sdk/OsTypes/TriBool.cs @@ -4,6 +4,6 @@ { False, True, - Undefined + Undefined, } } diff --git a/src/Ryujinx.Horizon/Sdk/Prepo/IPrepoService.cs b/src/Ryujinx.Horizon/Sdk/Prepo/IPrepoService.cs index 042cb4007..3f2628205 100644 --- a/src/Ryujinx.Horizon/Sdk/Prepo/IPrepoService.cs +++ b/src/Ryujinx.Horizon/Sdk/Prepo/IPrepoService.cs @@ -2,6 +2,7 @@ using Ryujinx.Horizon.Sdk.Account; using Ryujinx.Horizon.Sdk.Sf; using System; +using ApplicationId = Ryujinx.Horizon.Sdk.Ncm.ApplicationId; namespace Ryujinx.Horizon.Sdk.Prepo { @@ -12,9 +13,9 @@ namespace Ryujinx.Horizon.Sdk.Prepo Result RequestImmediateTransmission(); Result GetTransmissionStatus(out int status); Result GetSystemSessionId(out ulong systemSessionId); - Result SaveSystemReport(ReadOnlySpan gameRoomBuffer, Ncm.ApplicationId applicationId, ReadOnlySpan reportBuffer); - Result SaveSystemReportWithUser(Uid userId, ReadOnlySpan gameRoomBuffer, Ncm.ApplicationId applicationId, ReadOnlySpan reportBuffer); + Result SaveSystemReport(ReadOnlySpan gameRoomBuffer, ApplicationId applicationId, ReadOnlySpan reportBuffer); + Result SaveSystemReportWithUser(Uid userId, ReadOnlySpan gameRoomBuffer, ApplicationId applicationId, ReadOnlySpan reportBuffer); Result IsUserAgreementCheckEnabled(out bool enabled); Result SetUserAgreementCheckEnabled(bool enabled); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/ServiceUtil.cs b/src/Ryujinx.Horizon/Sdk/ServiceUtil.cs index fe6fcce15..ccd6c93a6 100644 --- a/src/Ryujinx.Horizon/Sdk/ServiceUtil.cs +++ b/src/Ryujinx.Horizon/Sdk/ServiceUtil.cs @@ -10,15 +10,15 @@ namespace Ryujinx.Horizon.Sdk public static Result SendRequest(out CmifResponse response, int sessionHandle, uint requestId, bool sendPid, scoped ReadOnlySpan data) { ulong tlsAddress = HorizonStatic.ThreadContext.TlsAddress; - int tlsSize = Api.TlsMessageBufferSize; + int tlsSize = Api.TlsMessageBufferSize; using (var tlsRegion = HorizonStatic.AddressSpace.GetWritableRegion(tlsAddress, tlsSize)) { - CmifRequest request = CmifMessage.CreateRequest(tlsRegion.Memory.Span, new CmifRequestFormat() + CmifRequest request = CmifMessage.CreateRequest(tlsRegion.Memory.Span, new CmifRequestFormat { - DataSize = data.Length, + DataSize = data.Length, RequestId = requestId, - SendPid = sendPid + SendPid = sendPid, }); data.CopyTo(request.Data); @@ -36,4 +36,4 @@ namespace Ryujinx.Horizon.Sdk return CmifMessage.ParseResponse(out response, HorizonStatic.AddressSpace.GetWritableRegion(tlsAddress, tlsSize).Memory.Span, false, 0); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifDomainInHeader.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifDomainInHeader.cs index beaff613f..882115013 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifDomainInHeader.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifDomainInHeader.cs @@ -3,10 +3,10 @@ struct CmifDomainInHeader { public CmifDomainRequestType Type; - public byte ObjectsCount; - public ushort DataSize; - public int ObjectId; - public uint Padding; - public uint Token; + public byte ObjectsCount; + public ushort DataSize; + public int ObjectId; + public uint Padding; + public uint Token; } } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifDomainOutHeader.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifDomainOutHeader.cs index 2086d24c1..89766a421 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifDomainOutHeader.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifDomainOutHeader.cs @@ -2,7 +2,7 @@ { struct CmifDomainOutHeader { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public uint ObjectsCount; public uint Padding; public uint Padding2; diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifDomainRequestType.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifDomainRequestType.cs index 1a02e0825..4e52ff936 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifDomainRequestType.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifDomainRequestType.cs @@ -2,8 +2,8 @@ { enum CmifDomainRequestType : byte { - Invalid = 0, + Invalid = 0, SendMessage = 1, - Close = 2 + Close = 2, } } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifMessage.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifMessage.cs index 0d23d33bb..f0b6f0c36 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifMessage.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifMessage.cs @@ -8,7 +8,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif { static class CmifMessage { - public const uint CmifInHeaderMagic = 0x49434653; // SFCI + public const uint CmifInHeaderMagic = 0x49434653; // SFCI public const uint CmifOutHeaderMagic = 0x4f434653; // SFCO public static CmifRequest CreateRequest(Span output, CmifRequestFormat format) @@ -21,10 +21,10 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif } totalSize += Unsafe.SizeOf() + format.DataSize; - totalSize = (totalSize + 1) & ~1; + totalSize = (totalSize + 1) & ~1; int outPointerSizeTableOffset = totalSize; - int outPointerSizeTableSize = format.OutAutoBuffersCount + format.OutPointersCount; + int outPointerSizeTableSize = format.OutAutoBuffersCount + format.OutPointersCount; totalSize += sizeof(ushort) * outPointerSizeTableSize; @@ -32,19 +32,19 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif CmifRequest request = new() { - Hipc = HipcMessage.WriteMessage(output, new HipcMetadata() + Hipc = HipcMessage.WriteMessage(output, new HipcMetadata { - Type = format.Context != 0 ? (int)CommandType.RequestWithContext : (int)CommandType.Request, - SendStaticsCount = format.InAutoBuffersCount + format.InPointersCount, - SendBuffersCount = format.InAutoBuffersCount + format.InBuffersCount, - ReceiveBuffersCount = format.OutAutoBuffersCount + format.OutBuffersCount, + Type = format.Context != 0 ? (int)CommandType.RequestWithContext : (int)CommandType.Request, + SendStaticsCount = format.InAutoBuffersCount + format.InPointersCount, + SendBuffersCount = format.InAutoBuffersCount + format.InBuffersCount, + ReceiveBuffersCount = format.OutAutoBuffersCount + format.OutBuffersCount, ExchangeBuffersCount = format.InOutBuffersCount, - DataWordsCount = rawDataSizeInWords, - ReceiveStaticsCount = outPointerSizeTableSize + format.OutFixedPointersCount, - SendPid = format.SendPid, - CopyHandlesCount = format.HandlesCount, - MoveHandlesCount = 0 - }) + DataWordsCount = rawDataSizeInWords, + ReceiveStaticsCount = outPointerSizeTableSize + format.OutFixedPointersCount, + SendPid = format.SendPid, + CopyHandlesCount = format.HandlesCount, + MoveHandlesCount = 0, + }), }; Span data = request.Hipc.DataWords; @@ -55,14 +55,14 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif int payloadSize = Unsafe.SizeOf() + format.DataSize; - domainHeader = new CmifDomainInHeader() + domainHeader = new CmifDomainInHeader { - Type = CmifDomainRequestType.SendMessage, + Type = CmifDomainRequestType.SendMessage, ObjectsCount = (byte)format.ObjectsCount, - DataSize = (ushort)payloadSize, - ObjectId = format.ObjectId, - Padding = 0, - Token = format.Context + DataSize = (ushort)payloadSize, + ObjectId = format.ObjectId, + Padding = 0, + Token = format.Context, }; data = data[(Unsafe.SizeOf() / sizeof(uint))..]; @@ -72,12 +72,12 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif ref CmifInHeader header = ref MemoryMarshal.Cast(data)[0]; - header = new CmifInHeader() + header = new CmifInHeader { - Magic = CmifInHeaderMagic, - Version = format.Context != 0 ? 1u : 0u, + Magic = CmifInHeaderMagic, + Version = format.Context != 0 ? 1u : 0u, CommandId = format.RequestId, - Token = format.ObjectId != 0 ? 0u : format.Context + Token = format.ObjectId != 0 ? 0u : format.Context, }; request.Data = MemoryMarshal.Cast(data)[Unsafe.SizeOf()..]; @@ -86,7 +86,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif Span outPointerTable = MemoryMarshal.Cast(request.Hipc.DataWords)[(outPointerSizeTableOffset - paddingSizeBefore)..]; - request.OutPointerSizes = MemoryMarshal.Cast(outPointerTable); + request.OutPointerSizes = MemoryMarshal.Cast(outPointerTable); request.ServerPointerSize = format.ServerPointerSize; return request; @@ -96,12 +96,12 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif { HipcMessage responseMessage = new(input); - Span data = MemoryMarshal.Cast(responseMessage.Data.DataWords); + Span data = MemoryMarshal.Cast(responseMessage.Data.DataWords); Span objects = Span.Empty; if (isDomain) { - data = data[Unsafe.SizeOf()..]; + data = data[Unsafe.SizeOf()..]; objects = MemoryMarshal.Cast(data[(Unsafe.SizeOf() + size)..]); } @@ -121,15 +121,15 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif return header.Result; } - response = new CmifResponse() + response = new CmifResponse { - Data = data[Unsafe.SizeOf()..], - Objects = objects, + Data = data[Unsafe.SizeOf()..], + Objects = objects, CopyHandles = responseMessage.Data.CopyHandles, - MoveHandles = responseMessage.Data.MoveHandles + MoveHandles = responseMessage.Data.MoveHandles, }; return Result.Success; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifOutHeader.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifOutHeader.cs index 00b9d2bda..ae32e78d6 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifOutHeader.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifOutHeader.cs @@ -4,11 +4,11 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif { struct CmifOutHeader { -#pragma warning disable CS0649 - public uint Magic; - public uint Version; +#pragma warning disable CS0649 // Field is never assigned to + public uint Magic; + public uint Version; public Result Result; - public uint Token; + public uint Token; #pragma warning restore CS0649 } } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifRequest.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifRequest.cs index e44a84ec1..80772ad33 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifRequest.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifRequest.cs @@ -6,9 +6,9 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif ref struct CmifRequest { public HipcMessageData Hipc; - public Span Data; - public Span OutPointerSizes; - public Span Objects; - public int ServerPointerSize; + public Span Data; + public Span OutPointerSizes; + public Span Objects; + public int ServerPointerSize; } } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifRequestFormat.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifRequestFormat.cs index 592f11f42..c32646e30 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifRequestFormat.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifRequestFormat.cs @@ -2,22 +2,22 @@ { struct CmifRequestFormat { -#pragma warning disable CS0649 - public int ObjectId; +#pragma warning disable CS0649 // Field is never assigned to + public int ObjectId; public uint RequestId; public uint Context; - public int DataSize; - public int ServerPointerSize; - public int InAutoBuffersCount; - public int OutAutoBuffersCount; - public int InBuffersCount; - public int OutBuffersCount; - public int InOutBuffersCount; - public int InPointersCount; - public int OutPointersCount; - public int OutFixedPointersCount; - public int ObjectsCount; - public int HandlesCount; + public int DataSize; + public int ServerPointerSize; + public int InAutoBuffersCount; + public int OutAutoBuffersCount; + public int InBuffersCount; + public int OutBuffersCount; + public int InOutBuffersCount; + public int InPointersCount; + public int OutPointersCount; + public int OutFixedPointersCount; + public int ObjectsCount; + public int HandlesCount; public bool SendPid; #pragma warning restore CS0649 } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifResponse.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifResponse.cs index 2ff31eb67..d1d8dc9c5 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifResponse.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CmifResponse.cs @@ -6,7 +6,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif { public ReadOnlySpan Data; public ReadOnlySpan Objects; - public ReadOnlySpan CopyHandles; - public ReadOnlySpan MoveHandles; + public ReadOnlySpan CopyHandles; + public ReadOnlySpan MoveHandles; } } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CommandType.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CommandType.cs index 82c0648b6..4f6c50fc9 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CommandType.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/CommandType.cs @@ -2,13 +2,13 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif { enum CommandType { - Invalid = 0, - LegacyRequest = 1, - Close = 2, - LegacyControl = 3, - Request = 4, - Control = 5, + Invalid = 0, + LegacyRequest = 1, + Close = 2, + LegacyControl = 3, + Request = 4, + Control = 5, RequestWithContext = 6, - ControlWithContext = 7 + ControlWithContext = 7, } } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/DomainServiceObjectDispatchTable.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/DomainServiceObjectDispatchTable.cs index b0b4498d9..ccfacd908 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/DomainServiceObjectDispatchTable.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/DomainServiceObjectDispatchTable.cs @@ -12,7 +12,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif return ProcessMessageImpl(ref context, ((DomainServiceObject)context.ServiceObject).GetServerDomain(), inRawData); } - private Result ProcessMessageImpl(ref ServiceDispatchContext context, ServerDomainBase domain, ReadOnlySpan inRawData) + private static Result ProcessMessageImpl(ref ServiceDispatchContext context, ServerDomainBase domain, ReadOnlySpan inRawData) { if (inRawData.Length < Unsafe.SizeOf()) { diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/DomainServiceObjectProcessor.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/DomainServiceObjectProcessor.cs index 796b8a789..20ac5f101 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/DomainServiceObjectProcessor.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/DomainServiceObjectProcessor.cs @@ -19,7 +19,6 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif private int InObjectsCount => _inObjectIds.Length; private int OutObjectsCount => _implMetadata.OutObjectsCount; - private int ImplOutHeadersSize => _implMetadata.OutHeadersSize; private int ImplOutDataTotalSize => _implMetadata.OutDataSize + _implMetadata.OutHeadersSize; public DomainServiceObjectProcessor(ServerDomainBase domain, int[] inObjectIds) diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/HandlesToClose.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/HandlesToClose.cs index 0f3b259af..3c37e8b2e 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/HandlesToClose.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/HandlesToClose.cs @@ -17,7 +17,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif public int this[int index] { - get + readonly get { return index switch { @@ -29,22 +29,39 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif 5 => _handle5, 6 => _handle6, 7 => _handle7, - _ => throw new IndexOutOfRangeException() + _ => throw new IndexOutOfRangeException(), }; } set { switch (index) { - case 0: _handle0 = value; break; - case 1: _handle1 = value; break; - case 2: _handle2 = value; break; - case 3: _handle3 = value; break; - case 4: _handle4 = value; break; - case 5: _handle5 = value; break; - case 6: _handle6 = value; break; - case 7: _handle7 = value; break; - default: throw new IndexOutOfRangeException(); + case 0: + _handle0 = value; + break; + case 1: + _handle1 = value; + break; + case 2: + _handle2 = value; + break; + case 3: + _handle3 = value; + break; + case 4: + _handle4 = value; + break; + case 5: + _handle5 = value; + break; + case 6: + _handle6 = value; + break; + case 7: + _handle7 = value; + break; + default: + throw new IndexOutOfRangeException(); } } } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/PointerAndSize.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/PointerAndSize.cs index ad0e18244..23780c7c9 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/PointerAndSize.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/PointerAndSize.cs @@ -1,6 +1,6 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif { - struct PointerAndSize + readonly struct PointerAndSize { public static PointerAndSize Empty => new(0UL, 0UL); @@ -11,7 +11,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif public PointerAndSize(ulong address, ulong size) { Address = address; - Size = size; + Size = size; } } } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ScopedInlineContextChange.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ScopedInlineContextChange.cs index eabe544f4..0126d1f60 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ScopedInlineContextChange.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ScopedInlineContextChange.cs @@ -2,7 +2,7 @@ using System; namespace Ryujinx.Horizon.Sdk.Sf.Cmif { - struct ScopedInlineContextChange : IDisposable + readonly struct ScopedInlineContextChange : IDisposable { private readonly int _previousContext; diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServerDomainManager.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServerDomainManager.cs index f789b6c0c..f0222991d 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServerDomainManager.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServerDomainManager.cs @@ -211,7 +211,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif private readonly EntryManager _entryManager; private readonly object _entryOwnerLock; private readonly HashSet _domains; - private int _maxDomains; + private readonly int _maxDomains; public ServerDomainManager(int entryCount, int maxDomains) { diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServerMessageRuntimeMetadata.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServerMessageRuntimeMetadata.cs index 6a92e8d55..206676020 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServerMessageRuntimeMetadata.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServerMessageRuntimeMetadata.cs @@ -1,30 +1,30 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif { - struct ServerMessageRuntimeMetadata + readonly struct ServerMessageRuntimeMetadata { - public ushort InDataSize { get; } - public ushort OutDataSize { get; } - public byte InHeadersSize { get; } - public byte OutHeadersSize { get; } - public byte InObjectsCount { get; } - public byte OutObjectsCount { get; } + public ushort InDataSize { get; } + public ushort OutDataSize { get; } + public byte InHeadersSize { get; } + public byte OutHeadersSize { get; } + public byte InObjectsCount { get; } + public byte OutObjectsCount { get; } public int UnfixedOutPointerSizeOffset => InDataSize + InHeadersSize + 0x10; public ServerMessageRuntimeMetadata( ushort inDataSize, ushort outDataSize, - byte inHeadersSize, - byte outHeadersSize, - byte inObjectsCount, - byte outObjectsCount) + byte inHeadersSize, + byte outHeadersSize, + byte inObjectsCount, + byte outObjectsCount) { - InDataSize = inDataSize; - OutDataSize = outDataSize; - InHeadersSize = inHeadersSize; - OutHeadersSize = outHeadersSize; - InObjectsCount = inObjectsCount; + InDataSize = inDataSize; + OutDataSize = outDataSize; + InHeadersSize = inHeadersSize; + OutHeadersSize = outHeadersSize; + InObjectsCount = inObjectsCount; OutObjectsCount = outObjectsCount; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServiceDispatchContext.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServiceDispatchContext.cs index 31be810d3..3339a1a60 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServiceDispatchContext.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServiceDispatchContext.cs @@ -5,14 +5,14 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif { ref struct ServiceDispatchContext { - public IServiceObject ServiceObject; - public ServerSessionManager Manager; - public ServerSession Session; + public IServiceObject ServiceObject; + public ServerSessionManager Manager; + public ServerSession Session; public ServerMessageProcessor Processor; - public HandlesToClose HandlesToClose; - public PointerAndSize PointerBuffer; - public ReadOnlySpan InMessageBuffer; - public Span OutMessageBuffer; - public HipcMessage Request; + public HandlesToClose HandlesToClose; + public PointerAndSize PointerBuffer; + public ReadOnlySpan InMessageBuffer; + public Span OutMessageBuffer; + public HipcMessage Request; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServiceDispatchMeta.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServiceDispatchMeta.cs index 7fbd8eb84..286e94148 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServiceDispatchMeta.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServiceDispatchMeta.cs @@ -1,6 +1,6 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif { - struct ServiceDispatchMeta + readonly struct ServiceDispatchMeta { public ServiceDispatchTableBase DispatchTable { get; } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServiceDispatchTable.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServiceDispatchTable.cs index 21b342dff..145c17839 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServiceDispatchTable.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServiceDispatchTable.cs @@ -12,7 +12,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif public ServiceDispatchTable(string objectName, IReadOnlyDictionary entries) { _objectName = objectName; - _entries = entries; + _entries = entries; } public override Result ProcessMessage(ref ServiceDispatchContext context, ReadOnlySpan inRawData) @@ -30,4 +30,4 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif return new ServiceDispatchTable(instance.GetType().Name, instance.GetCommandHandlers()); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServiceDispatchTableBase.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServiceDispatchTableBase.cs index 816000675..a127bfcd5 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServiceDispatchTableBase.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServiceDispatchTableBase.cs @@ -14,7 +14,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif public abstract Result ProcessMessage(ref ServiceDispatchContext context, ReadOnlySpan inRawData); - protected Result ProcessMessageImpl(ref ServiceDispatchContext context, ReadOnlySpan inRawData, IReadOnlyDictionary entries, string objectName) + protected static Result ProcessMessageImpl(ref ServiceDispatchContext context, ReadOnlySpan inRawData, IReadOnlyDictionary entries, string objectName) { if (inRawData.Length < Unsafe.SizeOf()) { @@ -44,7 +44,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif // If ignore missing services is enabled, just pretend that everything is fine. PrepareForStubReply(ref context, out Span outRawData); CommandHandler.GetCmifOutHeaderPointer(ref outHeader, ref outRawData); - outHeader[0] = new CmifOutHeader() { Magic = CmifMessage.CmifOutHeaderMagic, Result = Result.Success }; + outHeader[0] = new CmifOutHeader { Magic = CmifMessage.CmifOutHeaderMagic, Result = Result.Success }; Logger.Warning?.Print(LogClass.Service, $"Missing service {objectName} (command ID: {commandId}) ignored"); @@ -80,7 +80,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif return commandResult; } - outHeader[0] = new CmifOutHeader() { Magic = CmifMessage.CmifOutHeaderMagic, Result = commandResult }; + outHeader[0] = new CmifOutHeader { Magic = CmifMessage.CmifOutHeaderMagic, Result = commandResult }; return Result.Success; } @@ -91,4 +91,4 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif outRawData = MemoryMarshal.Cast(response.DataWords); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Sf/CommandArg.cs b/src/Ryujinx.Horizon/Sdk/Sf/CommandArg.cs index 47aedde96..f6b54403f 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/CommandArg.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/CommandArg.cs @@ -15,42 +15,42 @@ namespace Ryujinx.Horizon.Sdk.Sf OutCopyHandle, OutMoveHandle, OutObject, - ProcessId + ProcessId, } - struct CommandArg + readonly struct CommandArg { - public CommandArgType Type { get; } - public HipcBufferFlags BufferFlags { get; } - public ushort BufferFixedSize { get; } - public int ArgSize { get; } - public int ArgAlignment { get; } + public CommandArgType Type { get; } + public HipcBufferFlags BufferFlags { get; } + public ushort BufferFixedSize { get; } + public int ArgSize { get; } + public int ArgAlignment { get; } public CommandArg(CommandArgType type) { - Type = type; - BufferFlags = default; + Type = type; + BufferFlags = default; BufferFixedSize = 0; - ArgSize = 0; - ArgAlignment = 0; + ArgSize = 0; + ArgAlignment = 0; } public CommandArg(CommandArgType type, int argSize, int argAlignment) { - Type = type; - BufferFlags = default; + Type = type; + BufferFlags = default; BufferFixedSize = 0; - ArgSize = argSize; - ArgAlignment = argAlignment; + ArgSize = argSize; + ArgAlignment = argAlignment; } public CommandArg(HipcBufferFlags flags, ushort fixedSize = 0) { - Type = CommandArgType.Buffer; - BufferFlags = flags; + Type = CommandArgType.Buffer; + BufferFlags = flags; BufferFixedSize = fixedSize; - ArgSize = 0; - ArgAlignment = 0; + ArgSize = 0; + ArgAlignment = 0; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Sf/CommandArgAttributes.cs b/src/Ryujinx.Horizon/Sdk/Sf/CommandArgAttributes.cs index 294c7d58d..5b7c302f2 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/CommandArgAttributes.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/CommandArgAttributes.cs @@ -6,8 +6,8 @@ namespace Ryujinx.Horizon.Sdk.Sf [AttributeUsage(AttributeTargets.Parameter)] class BufferAttribute : Attribute { - public HipcBufferFlags Flags { get; } - public ushort FixedSize { get; } + public HipcBufferFlags Flags { get; } + public ushort FixedSize { get; } public BufferAttribute(HipcBufferFlags flags) { @@ -16,7 +16,7 @@ namespace Ryujinx.Horizon.Sdk.Sf public BufferAttribute(HipcBufferFlags flags, ushort fixedSize) { - Flags = flags | HipcBufferFlags.FixedSize; + Flags = flags | HipcBufferFlags.FixedSize; FixedSize = fixedSize; } } @@ -35,4 +35,4 @@ namespace Ryujinx.Horizon.Sdk.Sf class MoveHandleAttribute : Attribute { } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Sf/CommandHandler.cs b/src/Ryujinx.Horizon/Sdk/Sf/CommandHandler.cs index 081ce3be5..fb88eaaa0 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/CommandHandler.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/CommandHandler.cs @@ -9,20 +9,20 @@ namespace Ryujinx.Horizon.Sdk.Sf class CommandHandler { public delegate Result MethodInvoke( - ref ServiceDispatchContext context, - HipcCommandProcessor processor, + ref ServiceDispatchContext context, + HipcCommandProcessor processor, ServerMessageRuntimeMetadata runtimeMetadata, - ReadOnlySpan inRawData, - ref Span outHeader); + ReadOnlySpan inRawData, + ref Span outHeader); - private readonly MethodInvoke _invoke; + private readonly MethodInvoke _invoke; private readonly HipcCommandProcessor _processor; public string MethodName => _invoke.Method.Name; public CommandHandler(MethodInvoke invoke, params CommandArg[] args) { - _invoke = invoke; + _invoke = invoke; _processor = new HipcCommandProcessor(args); } @@ -37,16 +37,16 @@ namespace Ryujinx.Horizon.Sdk.Sf context.Processor.SetImplementationProcessor(_processor); } - var runtimeMetadata = context.Processor.GetRuntimeMetadata(); - Result result = context.Processor.PrepareForProcess(ref context, runtimeMetadata); + var runtimeMetadata = context.Processor.GetRuntimeMetadata(); + Result result = context.Processor.PrepareForProcess(ref context, runtimeMetadata); return result.IsFailure ? result : _invoke(ref context, _processor, runtimeMetadata, inRawData, ref outHeader); } public static void GetCmifOutHeaderPointer(ref Span outHeader, ref Span outRawData) { - outHeader = MemoryMarshal.Cast(outRawData)[..1]; + outHeader = MemoryMarshal.Cast(outRawData)[..1]; outRawData = outRawData[Unsafe.SizeOf()..]; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Sf/CommandSerialization.cs b/src/Ryujinx.Horizon/Sdk/Sf/CommandSerialization.cs index 4205d3c16..a14892a8d 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/CommandSerialization.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/CommandSerialization.cs @@ -66,4 +66,4 @@ namespace Ryujinx.Horizon.Sdk.Sf response.MoveHandles[index] = value; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/Api.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/Api.cs index 33c42825f..530f81bd1 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/Api.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/Api.cs @@ -41,10 +41,8 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc { return HorizonStatic.Syscall.ReplyAndReceive(out _, handles, 0, -1L); } - else - { - throw new NotImplementedException(); - } + + throw new NotImplementedException(); } public static Result Reply(int sessionHandle, ReadOnlySpan messageBuffer) @@ -64,10 +62,8 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc { return HorizonStatic.Syscall.ReplyAndReceive(out _, ReadOnlySpan.Empty, sessionHandle, 0); } - else - { - throw new NotImplementedException(); - } + + throw new NotImplementedException(); } public static Result CreateSession(out int serverHandle, out int clientHandle) @@ -82,4 +78,4 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc return result; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/Header.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/Header.cs index cdb50b578..04abf6937 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/Header.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/Header.cs @@ -10,55 +10,55 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc public CommandType Type { - get => (CommandType)_word0.Extract(0, 16); + readonly get => (CommandType)_word0.Extract(0, 16); set => _word0 = _word0.Insert(0, 16, (uint)value); } public int SendStaticsCount { - get => (int)_word0.Extract(16, 4); + readonly get => (int)_word0.Extract(16, 4); set => _word0 = _word0.Insert(16, 4, (uint)value); } public int SendBuffersCount { - get => (int)_word0.Extract(20, 4); + readonly get => (int)_word0.Extract(20, 4); set => _word0 = _word0.Insert(20, 4, (uint)value); } public int ReceiveBuffersCount { - get => (int)_word0.Extract(24, 4); + readonly get => (int)_word0.Extract(24, 4); set => _word0 = _word0.Insert(24, 4, (uint)value); } public int ExchangeBuffersCount { - get => (int)_word0.Extract(28, 4); + readonly get => (int)_word0.Extract(28, 4); set => _word0 = _word0.Insert(28, 4, (uint)value); } public int DataWordsCount { - get => (int)_word1.Extract(0, 10); + readonly get => (int)_word1.Extract(0, 10); set => _word1 = _word1.Insert(0, 10, (uint)value); } public int ReceiveStaticMode { - get => (int)_word1.Extract(10, 4); + readonly get => (int)_word1.Extract(10, 4); set => _word1 = _word1.Insert(10, 4, (uint)value); } public int ReceiveListOffset { - get => (int)_word1.Extract(20, 11); + readonly get => (int)_word1.Extract(20, 11); set => _word1 = _word1.Insert(20, 11, (uint)value); } public bool HasSpecialHeader { - get => _word1.Extract(31); + readonly get => _word1.Extract(31); set => _word1 = _word1.Insert(31, value); } } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcBufferDescriptor.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcBufferDescriptor.cs index 7778d5bca..bef772e67 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcBufferDescriptor.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcBufferDescriptor.cs @@ -1,11 +1,11 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc { - struct HipcBufferDescriptor + readonly struct HipcBufferDescriptor { -#pragma warning disable CS0649 - private uint _sizeLow; - private uint _addressLow; - private uint _word2; +#pragma warning disable CS0649 // Field is never assigned to + private readonly uint _sizeLow; + private readonly uint _addressLow; + private readonly uint _word2; #pragma warning restore CS0649 public ulong Address => _addressLow | (((ulong)_word2 << 4) & 0xf00000000UL) | (((ulong)_word2 << 34) & 0x7000000000UL); diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcBufferFlags.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcBufferFlags.cs index 269ab4fe5..b1523d61d 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcBufferFlags.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcBufferFlags.cs @@ -5,13 +5,13 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc [Flags] enum HipcBufferFlags : byte { - In = 1 << 0, - Out = 1 << 1, - MapAlias = 1 << 2, - Pointer = 1 << 3, - FixedSize = 1 << 4, - AutoSelect = 1 << 5, + In = 1 << 0, + Out = 1 << 1, + MapAlias = 1 << 2, + Pointer = 1 << 3, + FixedSize = 1 << 4, + AutoSelect = 1 << 5, MapTransferAllowsNonSecure = 1 << 6, - MapTransferAllowsNonDevice = 1 << 7 + MapTransferAllowsNonDevice = 1 << 7, } } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcBufferMode.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcBufferMode.cs index b1e67253c..bc2d5336c 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcBufferMode.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcBufferMode.cs @@ -2,9 +2,9 @@ { enum HipcBufferMode { - Normal = 0, + Normal = 0, NonSecure = 1, - Invalid = 2, - NonDevice = 3 + Invalid = 2, + NonDevice = 3, } } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcManager.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcManager.cs index 7541e2941..f72d8e81d 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcManager.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcManager.cs @@ -112,4 +112,4 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc return Result.Success; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcMessage.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcMessage.cs index 6500d6cf7..82cf6e75f 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcMessage.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcMessage.cs @@ -10,9 +10,9 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc { public const int AutoReceiveStatic = byte.MaxValue; - public HipcMetadata Meta; + public HipcMetadata Meta; public HipcMessageData Data; - public ulong Pid; + public ulong Pid; public HipcMessage(Span data) { @@ -22,8 +22,8 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc data = data[Unsafe.SizeOf
()..]; - int receiveStaticsCount = 0; - ulong pid = 0; + int receiveStaticsCount = 0; + ulong pid = 0; if (header.ReceiveStaticMode != 0) { @@ -42,75 +42,75 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc if (header.HasSpecialHeader) { specialHeader = MemoryMarshal.Cast(data)[0]; - data = data[Unsafe.SizeOf()..]; + data = data[Unsafe.SizeOf()..]; if (specialHeader.SendPid) { - pid = MemoryMarshal.Cast(data)[0]; + pid = MemoryMarshal.Cast(data)[0]; data = data[sizeof(ulong)..]; } } - Meta = new HipcMetadata() + Meta = new HipcMetadata { - Type = (int)header.Type, - SendStaticsCount = header.SendStaticsCount, - SendBuffersCount = header.SendBuffersCount, - ReceiveBuffersCount = header.ReceiveBuffersCount, + Type = (int)header.Type, + SendStaticsCount = header.SendStaticsCount, + SendBuffersCount = header.SendBuffersCount, + ReceiveBuffersCount = header.ReceiveBuffersCount, ExchangeBuffersCount = header.ExchangeBuffersCount, - DataWordsCount = header.DataWordsCount, - ReceiveStaticsCount = receiveStaticsCount, - SendPid = specialHeader.SendPid, - CopyHandlesCount = specialHeader.CopyHandlesCount, - MoveHandlesCount = specialHeader.MoveHandlesCount + DataWordsCount = header.DataWordsCount, + ReceiveStaticsCount = receiveStaticsCount, + SendPid = specialHeader.SendPid, + CopyHandlesCount = specialHeader.CopyHandlesCount, + MoveHandlesCount = specialHeader.MoveHandlesCount, }; Data = CreateMessageData(Meta, data, initialLength); - Pid = pid; + Pid = pid; } public static HipcMessageData WriteResponse( Span destination, - int sendStaticCount, - int dataWordsCount, - int copyHandlesCount, - int moveHandlesCount) + int sendStaticCount, + int dataWordsCount, + int copyHandlesCount, + int moveHandlesCount) { - return WriteMessage(destination, new HipcMetadata() + return WriteMessage(destination, new HipcMetadata { SendStaticsCount = sendStaticCount, - DataWordsCount = dataWordsCount, + DataWordsCount = dataWordsCount, CopyHandlesCount = copyHandlesCount, - MoveHandlesCount = moveHandlesCount + MoveHandlesCount = moveHandlesCount, }); } public static HipcMessageData WriteMessage(Span destination, HipcMetadata meta) { - int initialLength = destination.Length; + int initialLength = destination.Length; bool hasSpecialHeader = meta.SendPid || meta.CopyHandlesCount != 0 || meta.MoveHandlesCount != 0; - MemoryMarshal.Cast(destination)[0] = new Header() + MemoryMarshal.Cast(destination)[0] = new Header { - Type = (CommandType)meta.Type, - SendStaticsCount = meta.SendStaticsCount, - SendBuffersCount = meta.SendBuffersCount, - ReceiveBuffersCount = meta.ReceiveBuffersCount, + Type = (CommandType)meta.Type, + SendStaticsCount = meta.SendStaticsCount, + SendBuffersCount = meta.SendBuffersCount, + ReceiveBuffersCount = meta.ReceiveBuffersCount, ExchangeBuffersCount = meta.ExchangeBuffersCount, - DataWordsCount = meta.DataWordsCount, - ReceiveStaticMode = meta.ReceiveStaticsCount != 0 ? (meta.ReceiveStaticsCount != AutoReceiveStatic ? meta.ReceiveStaticsCount + 2 : 2) : 0, - HasSpecialHeader = hasSpecialHeader + DataWordsCount = meta.DataWordsCount, + ReceiveStaticMode = meta.ReceiveStaticsCount != 0 ? (meta.ReceiveStaticsCount != AutoReceiveStatic ? meta.ReceiveStaticsCount + 2 : 2) : 0, + HasSpecialHeader = hasSpecialHeader, }; destination = destination[Unsafe.SizeOf
()..]; if (hasSpecialHeader) { - MemoryMarshal.Cast(destination)[0] = new SpecialHeader() + MemoryMarshal.Cast(destination)[0] = new SpecialHeader { - SendPid = meta.SendPid, + SendPid = meta.SendPid, CopyHandlesCount = meta.CopyHandlesCount, - MoveHandlesCount = meta.MoveHandlesCount + MoveHandlesCount = meta.MoveHandlesCount, }; destination = destination[Unsafe.SizeOf()..]; @@ -184,9 +184,9 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc if (meta.DataWordsCount != 0) { - int dataOffset = initialLength - data.Length; + int dataOffset = initialLength - data.Length; int dataOffsetAligned = BitUtils.AlignUp(dataOffset, 0x10); - int padding = (dataOffsetAligned - dataOffset) / sizeof(uint); + int padding = (dataOffsetAligned - dataOffset) / sizeof(uint); dataWords = MemoryMarshal.Cast(data)[padding..meta.DataWordsCount]; @@ -202,16 +202,16 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc receiveList = MemoryMarshal.Cast(data)[..receiveListSize]; } - return new HipcMessageData() + return new HipcMessageData { - SendStatics = sendStatics, - SendBuffers = sendBuffers, - ReceiveBuffers = receiveBuffers, + SendStatics = sendStatics, + SendBuffers = sendBuffers, + ReceiveBuffers = receiveBuffers, ExchangeBuffers = exchangeBuffers, - DataWords = dataWords, - ReceiveList = receiveList, - CopyHandles = copyHandles, - MoveHandles = moveHandles + DataWords = dataWords, + ReceiveList = receiveList, + CopyHandles = copyHandles, + MoveHandles = moveHandles, }; } } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcMessageData.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcMessageData.cs index 154b8f079..c83c422ca 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcMessageData.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcMessageData.cs @@ -8,9 +8,9 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc public Span SendBuffers; public Span ReceiveBuffers; public Span ExchangeBuffers; - public Span DataWords; + public Span DataWords; public Span ReceiveList; - public Span CopyHandles; - public Span MoveHandles; + public Span CopyHandles; + public Span MoveHandles; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcMetadata.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcMetadata.cs index 10abc4006..fe13137a6 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcMetadata.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcMetadata.cs @@ -2,15 +2,15 @@ { struct HipcMetadata { - public int Type; - public int SendStaticsCount; - public int SendBuffersCount; - public int ReceiveBuffersCount; - public int ExchangeBuffersCount; - public int DataWordsCount; - public int ReceiveStaticsCount; + public int Type; + public int SendStaticsCount; + public int SendBuffersCount; + public int ReceiveBuffersCount; + public int ExchangeBuffersCount; + public int DataWordsCount; + public int ReceiveStaticsCount; public bool SendPid; - public int CopyHandlesCount; - public int MoveHandlesCount; + public int CopyHandlesCount; + public int MoveHandlesCount; } } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcReceiveListEntry.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcReceiveListEntry.cs index 56cf16fb0..955428b84 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcReceiveListEntry.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcReceiveListEntry.cs @@ -1,14 +1,16 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc { - struct HipcReceiveListEntry + readonly struct HipcReceiveListEntry { - private uint _addressLow; - private uint _word1; +#pragma warning disable IDE0052 // Remove unread private member + private readonly uint _addressLow; + private readonly uint _word1; +#pragma warning restore IDE0052 public HipcReceiveListEntry(ulong address, ulong size) { _addressLow = (uint)address; - _word1 = (ushort)(address >> 32) | (uint)(size << 16); + _word1 = (ushort)(address >> 32) | (uint)(size << 16); } } } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcResult.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcResult.cs index 3b483be81..faf5dc410 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcResult.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcResult.cs @@ -6,6 +6,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc { public const int ModuleId = 11; +#pragma warning disable IDE0055 // Disable formatting public static Result OutOfSessionMemory => new(ModuleId, 102); public static Result OutOfSessions => new(ModuleId, 131); public static Result PointerBufferTooSmall => new(ModuleId, 141); @@ -15,5 +16,6 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc public static Result InvalidCmifRequest => new(ModuleId, 420); public static Result TargetNotDomain => new(ModuleId, 491); public static Result DomainObjectNotFound => new(ModuleId, 492); + #pragma warning restore IDE0055 } } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcStaticDescriptor.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcStaticDescriptor.cs index 103820a6b..43e7afb9d 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcStaticDescriptor.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcStaticDescriptor.cs @@ -1,12 +1,12 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc { - struct HipcStaticDescriptor + readonly struct HipcStaticDescriptor { private readonly ulong _data; - public ulong Address => ((((_data >> 2) & 0x70) | ((_data >> 12) & 0xf)) << 32) | (_data >> 32); - public ushort Size => (ushort)(_data >> 16); - public int ReceiveIndex => (int)(_data & 0xf); + public ulong Address => ((((_data >> 2) & 0x70) | ((_data >> 12) & 0xf)) << 32) | (_data >> 32); + public ushort Size => (ushort)(_data >> 16); + public int ReceiveIndex => (int)(_data & 0xf); public HipcStaticDescriptor(ulong address, ushort size, int receiveIndex) { @@ -19,4 +19,4 @@ _data = data; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ManagerOptions.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ManagerOptions.cs index b99d63c5e..e747490e6 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ManagerOptions.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ManagerOptions.cs @@ -1,20 +1,20 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc { - struct ManagerOptions + readonly struct ManagerOptions { public static ManagerOptions Default => new(0, 0, 0, false); - public int PointerBufferSize { get; } - public int MaxDomains { get; } - public int MaxDomainObjects { get; } + public int PointerBufferSize { get; } + public int MaxDomains { get; } + public int MaxDomainObjects { get; } public bool CanDeferInvokeRequest { get; } public ManagerOptions(int pointerBufferSize, int maxDomains, int maxDomainObjects, bool canDeferInvokeRequest) { - PointerBufferSize = pointerBufferSize; - MaxDomains = maxDomains; - MaxDomainObjects = maxDomainObjects; + PointerBufferSize = pointerBufferSize; + MaxDomains = maxDomains; + MaxDomainObjects = maxDomainObjects; CanDeferInvokeRequest = canDeferInvokeRequest; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ReceiveResult.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ReceiveResult.cs index 7c380a011..efe99f3f9 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ReceiveResult.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ReceiveResult.cs @@ -4,6 +4,6 @@ { Success, Closed, - NeedsRetry + NeedsRetry, } } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/Server.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/Server.cs index bbbab8985..923f2d52d 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/Server.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/Server.cs @@ -6,22 +6,22 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc { class Server : MultiWaitHolderOfHandle { - public int PortIndex { get; } - public int PortHandle { get; } - public ServiceName Name { get; } - public bool Managed { get; } + public int PortIndex { get; } + public int PortHandle { get; } + public ServiceName Name { get; } + public bool Managed { get; } public ServiceObjectHolder StaticObject { get; } public Server( - int portIndex, - int portHandle, - ServiceName name, - bool managed, + int portIndex, + int portHandle, + ServiceName name, + bool managed, ServiceObjectHolder staticHoder) : base(portHandle) { PortHandle = portHandle; - Name = name; - Managed = managed; + Name = name; + Managed = managed; if (staticHoder != null) { diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerManager.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerManager.cs index 2ca9ceea2..9ac2a337e 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerManager.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerManager.cs @@ -14,8 +14,8 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc private readonly bool _canDeferInvokeRequest; private readonly int _maxSessions; - private ulong _pointerBuffersBaseAddress; - private ulong _savedMessagesBaseAddress; + private readonly ulong _pointerBuffersBaseAddress; + private readonly ulong _savedMessagesBaseAddress; private readonly object _resourceLock; private readonly ulong[] _sessionAllocationBitmap; @@ -35,7 +35,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc if (options.CanDeferInvokeRequest) { - _savedMessagesBaseAddress = allocator.Allocate((ulong)maxSessions * (ulong)Api.TlsMessageBufferSize); + _savedMessagesBaseAddress = allocator.Allocate((ulong)maxSessions * Api.TlsMessageBufferSize); } } @@ -45,7 +45,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc _servers = new HashSet(); } - private PointerAndSize GetObjectBySessionIndex(ServerSession session, ulong baseAddress, ulong size) + private static PointerAndSize GetObjectBySessionIndex(ServerSession session, ulong baseAddress, ulong size) { return new PointerAndSize(baseAddress + (ulong)session.SessionIndex * size, size); } @@ -61,7 +61,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc return null; } - for (int i = 0; i <_sessionAllocationBitmap.Length; i++) + for (int i = 0; i < _sessionAllocationBitmap.Length; i++) { ref ulong mask = ref _sessionAllocationBitmap[i]; @@ -145,10 +145,8 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc { return GetObjectBySessionIndex(session, _pointerBuffersBaseAddress, (ulong)_pointerBufferSize); } - else - { - return PointerAndSize.Empty; - } + + return PointerAndSize.Empty; } protected override PointerAndSize GetSessionSavedMessageBuffer(ServerSession session) @@ -157,10 +155,8 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc { return GetObjectBySessionIndex(session, _savedMessagesBaseAddress, Api.TlsMessageBufferSize); } - else - { - return PointerAndSize.Empty; - } + + return PointerAndSize.Empty; } protected virtual void Dispose(bool disposing) diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerManagerBase.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerManagerBase.cs index c36cdda26..764078408 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerManagerBase.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerManagerBase.cs @@ -10,7 +10,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc { private readonly SmApi _sm; - private bool _canDeferInvokeRequest; + private readonly bool _canDeferInvokeRequest; private readonly MultiWait _multiWait; private readonly MultiWait _waitList; @@ -26,8 +26,8 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc private enum UserDataTag { - Server = 1, - Session = 2 + Server = 1, + Session = 2, } public ServerManagerBase(SmApi sm, ManagerOptions options) : base(options.MaxDomainObjects, options.MaxDomains) @@ -36,13 +36,13 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc _canDeferInvokeRequest = options.CanDeferInvokeRequest; _multiWait = new MultiWait(); - _waitList = new MultiWait(); + _waitList = new MultiWait(); _multiWaitSelectionLock = new object(); - _waitListLock = new object(); + _waitListLock = new object(); _requestStopEvent = new Event(EventClearMode.ManualClear); - _notifyEvent = new Event(EventClearMode.ManualClear); + _notifyEvent = new Event(EventClearMode.ManualClear); _requestStopEventHolder = new MultiWaitHolderOfEvent(_requestStopEvent); _multiWait.LinkMultiWaitHolder(_requestStopEventHolder); @@ -113,7 +113,9 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc public void ServiceRequests() { - while (WaitAndProcessRequestsImpl()); + while (WaitAndProcessRequestsImpl()) + { + } } public void WaitAndProcessRequests() @@ -183,7 +185,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc protected override void RegisterSessionToWaitList(ServerSession session) { session.HasReceived = false; - session.UserData = UserDataTag.Session; + session.UserData = UserDataTag.Session; RegisterToWaitList(session); } @@ -209,9 +211,9 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc { return (UserDataTag)holder.UserData switch { - UserDataTag.Server => ProcessForServer(holder), + UserDataTag.Server => ProcessForServer(holder), UserDataTag.Session => ProcessForSession(holder), - _ => throw new NotImplementedException(((UserDataTag)holder.UserData).ToString()) + _ => throw new NotImplementedException(((UserDataTag)holder.UserData).ToString()), }; } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerSession.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerSession.cs index a17300823..eb98fefd0 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerSession.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerSession.cs @@ -6,18 +6,18 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc class ServerSession : MultiWaitHolderOfHandle { public ServiceObjectHolder ServiceObjectHolder { get; set; } - public PointerAndSize PointerBuffer { get; set; } - public PointerAndSize SavedMessage { get; set; } - public int SessionIndex { get; } - public int SessionHandle { get; } - public bool IsClosed { get; set; } - public bool HasReceived { get; set; } + public PointerAndSize PointerBuffer { get; set; } + public PointerAndSize SavedMessage { get; set; } + public int SessionIndex { get; } + public int SessionHandle { get; } + public bool IsClosed { get; set; } + public bool HasReceived { get; set; } public ServerSession(int index, int handle, ServiceObjectHolder obj) : base(handle) { ServiceObjectHolder = obj; - SessionIndex = index; - SessionHandle = handle; + SessionIndex = index; + SessionHandle = handle; } } } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerSessionManager.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerSessionManager.cs index 6d3950813..bd5a48444 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerSessionManager.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerSessionManager.cs @@ -75,7 +75,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc } session.PointerBuffer = GetSessionPointerBuffer(session); - session.SavedMessage = GetSessionSavedMessageBuffer(session); + session.SavedMessage = GetSessionSavedMessageBuffer(session); RegisterSessionToWaitList(session); @@ -110,10 +110,10 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc } protected virtual Server AllocateServer( - int portIndex, - int portHandle, - ServiceName name, - bool managed, + int portIndex, + int portHandle, + ServiceName name, + bool managed, ServiceObjectHolder staticHoder) { throw new NotSupportedException(); @@ -161,29 +161,25 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc return Result.Success; } - else + + Result result = ProcessRequestImpl(session, message, message); + + if (result.IsSuccess) { - Result result = ProcessRequestImpl(session, message, message); + RegisterSessionToWaitList(session); - if (result.IsSuccess) - { - RegisterSessionToWaitList(session); - - return Result.Success; - } - else if (SfResult.RequestContextChanged(result)) - { - return result; - } - else - { - Logger.Warning?.Print(LogClass.KernelIpc, $"Request processing returned error {result}"); - - CloseSessionImpl(session); - - return Result.Success; - } + return Result.Success; } + else if (SfResult.RequestContextChanged(result)) + { + return result; + } + + Logger.Warning?.Print(LogClass.KernelIpc, $"Request processing returned error {result}"); + + CloseSessionImpl(session); + + return Result.Success; } private Result ProcessRequestImpl(ServerSession session, Span inMessage, Span outMessage) @@ -192,18 +188,13 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc using var _ = new ScopedInlineContextChange(GetInlineContext(commandType, inMessage)); - switch (commandType) + return commandType switch { - case CommandType.Request: - case CommandType.RequestWithContext: - return DispatchRequest(session.ServiceObjectHolder, session, inMessage, outMessage); - case CommandType.Control: - case CommandType.ControlWithContext: - return DispatchManagerRequest(session, inMessage, outMessage); - default: - return HipcResult.UnknownCommandType; + CommandType.Request or CommandType.RequestWithContext => DispatchRequest(session.ServiceObjectHolder, session, inMessage, outMessage), + CommandType.Control or CommandType.ControlWithContext => DispatchManagerRequest(session, inMessage, outMessage), + _ => HipcResult.UnknownCommandType, + }; } - } private static int GetInlineContext(CommandType commandType, ReadOnlySpan inMessage) { @@ -221,12 +212,12 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc return 0; } - protected Result ReceiveRequest(ServerSession session, Span message) + protected static Result ReceiveRequest(ServerSession session, Span message) { return ReceiveRequestImpl(session, message); } - private Result ReceiveRequestImpl(ServerSession session, Span message) + private static Result ReceiveRequestImpl(ServerSession session, Span message) { PointerAndSize pointerBuffer = session.PointerBuffer; @@ -234,19 +225,19 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc { if (pointerBuffer.Address != 0) { - HipcMessageData messageData = HipcMessage.WriteMessage(message, new HipcMetadata() + HipcMessageData messageData = HipcMessage.WriteMessage(message, new HipcMetadata { - Type = (int)CommandType.Invalid, - ReceiveStaticsCount = HipcMessage.AutoReceiveStatic + Type = (int)CommandType.Invalid, + ReceiveStaticsCount = HipcMessage.AutoReceiveStatic, }); messageData.ReceiveList[0] = new HipcReceiveListEntry(pointerBuffer.Address, pointerBuffer.Size); } else { - MemoryMarshal.Cast(message)[0] = new Header() + MemoryMarshal.Cast(message)[0] = new Header { - Type = CommandType.Invalid + Type = CommandType.Invalid, }; } @@ -276,9 +267,9 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc protected virtual Result DispatchRequest( ServiceObjectHolder objectHolder, - ServerSession session, - Span inMessage, - Span outMessage) + ServerSession session, + Span inMessage, + Span outMessage) { HipcMessage request; @@ -291,16 +282,16 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc return HipcResult.InvalidRequestSize; } - var dispatchCtx = new ServiceDispatchContext() + var dispatchCtx = new ServiceDispatchContext { - ServiceObject = objectHolder.ServiceObject, - Manager = this, - Session = session, - HandlesToClose = new HandlesToClose(), - PointerBuffer = session.PointerBuffer, - InMessageBuffer = inMessage, + ServiceObject = objectHolder.ServiceObject, + Manager = this, + Session = session, + HandlesToClose = new HandlesToClose(), + PointerBuffer = session.PointerBuffer, + InMessageBuffer = inMessage, OutMessageBuffer = outMessage, - Request = request + Request = request, }; ReadOnlySpan inRawData = MemoryMarshal.Cast(dispatchCtx.Request.Data.DataWords); @@ -337,4 +328,4 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc return this; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/SpecialHeader.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/SpecialHeader.cs index 8b747626d..b6304b7b6 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/SpecialHeader.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/SpecialHeader.cs @@ -8,19 +8,19 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc public bool SendPid { - get => _word.Extract(0); + readonly get => _word.Extract(0); set => _word = _word.Insert(0, value); } public int CopyHandlesCount { - get => (int)_word.Extract(1, 4); + readonly get => (int)_word.Extract(1, 4); set => _word = _word.Insert(1, 4, (uint)value); } public int MoveHandlesCount { - get => (int)_word.Extract(5, 4); + readonly get => (int)_word.Extract(5, 4); set => _word = _word.Insert(5, 4, (uint)value); } } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/HipcCommandProcessor.cs b/src/Ryujinx.Horizon/Sdk/Sf/HipcCommandProcessor.cs index a0578d48f..08b1d89b9 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/HipcCommandProcessor.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/HipcCommandProcessor.cs @@ -134,9 +134,9 @@ namespace Ryujinx.Horizon.Sdk.Sf ulong pointerBufferTail = context.PointerBuffer.Address; ulong pointerBufferHead = pointerBufferTail + context.PointerBuffer.Size; - int sendMapAliasIndex = 0; - int recvMapAliasIndex = 0; - int sendPointerIndex = 0; + int sendMapAliasIndex = 0; + int recvMapAliasIndex = 0; + int sendPointerIndex = 0; int unfixedRecvPointerIndex = 0; for (int i = 0; i < _args.Length; i++) @@ -186,8 +186,8 @@ namespace Ryujinx.Horizon.Sdk.Sf if (flags.HasFlag(HipcBufferFlags.In)) { var descriptor = context.Request.Data.SendStatics[sendPointerIndex++]; - ulong address = descriptor.Address; - ulong size = descriptor.Size; + ulong address = descriptor.Address; + ulong size = descriptor.Size; _bufferRanges[i] = new PointerAndSize(address, size); @@ -206,14 +206,14 @@ namespace Ryujinx.Horizon.Sdk.Sf } else { - var data = MemoryMarshal.Cast(context.Request.Data.DataWords); + var data = MemoryMarshal.Cast(context.Request.Data.DataWords); var recvPointerSizes = MemoryMarshal.Cast(data[runtimeMetadata.UnfixedOutPointerSizeOffset..]); size = recvPointerSizes[unfixedRecvPointerIndex++]; } pointerBufferHead = BitUtils.AlignDown(pointerBufferHead - size, 0x10UL); - _bufferRanges[i] = new PointerAndSize(pointerBufferHead, size); + _bufferRanges[i] = new PointerAndSize(pointerBufferHead, size); } } } @@ -305,13 +305,13 @@ namespace Ryujinx.Horizon.Sdk.Sf { ref var meta = ref context.Request.Meta; bool requestValid = true; - requestValid &= meta.SendPid == _hasInProcessIdHolder; - requestValid &= meta.SendStaticsCount == _inPointerBuffersCount; - requestValid &= meta.SendBuffersCount == _inMapAliasBuffersCount; - requestValid &= meta.ReceiveBuffersCount == _outMapAliasBuffersCount; + requestValid &= meta.SendPid == _hasInProcessIdHolder; + requestValid &= meta.SendStaticsCount == _inPointerBuffersCount; + requestValid &= meta.SendBuffersCount == _inMapAliasBuffersCount; + requestValid &= meta.ReceiveBuffersCount == _outMapAliasBuffersCount; requestValid &= meta.ExchangeBuffersCount == 0; - requestValid &= meta.CopyHandlesCount == _inCopyHandlesCount; - requestValid &= meta.MoveHandlesCount == _inMoveHandlesCount; + requestValid &= meta.CopyHandlesCount == _inCopyHandlesCount; + requestValid &= meta.MoveHandlesCount == _inMoveHandlesCount; int rawSizeInBytes = meta.DataWordsCount * sizeof(uint); int commandRawSize = BitUtils.AlignUp(runtimeMetadata.UnfixedOutPointerSizeOffset + (OutUnfixedSizePointerBuffersCount * sizeof(ushort)), sizeof(uint)); @@ -345,7 +345,7 @@ namespace Ryujinx.Horizon.Sdk.Sf continue; } - int index = inObjectIndex++; + int index = inObjectIndex++; var inObject = inObjects[index]; objects[index] = inObject?.ServiceObject; @@ -386,7 +386,9 @@ namespace Ryujinx.Horizon.Sdk.Sf outRawData = MemoryMarshal.Cast(response.DataWords); } +#pragma warning disable CA1822 // Mark member as static public void SetOutObjects(ref ServiceDispatchContext context, HipcMessageData response, Span objects) +#pragma warning restore CA1822 { if (objects.Length == 0) { @@ -411,7 +413,7 @@ namespace Ryujinx.Horizon.Sdk.Sf } } - private void SetOutObjectImpl(int index, HipcMessageData response, ServerSessionManager manager, ServiceObjectHolder obj) + private static void SetOutObjectImpl(int index, HipcMessageData response, ServerSessionManager manager, ServiceObjectHolder obj) { if (obj == null) { @@ -425,4 +427,4 @@ namespace Ryujinx.Horizon.Sdk.Sf response.MoveHandles[index] = clientHandle; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Sf/RawDataOffsetCalculator.cs b/src/Ryujinx.Horizon/Sdk/Sf/RawDataOffsetCalculator.cs index 10e4f9094..0172c1151 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/RawDataOffsetCalculator.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/RawDataOffsetCalculator.cs @@ -12,15 +12,15 @@ namespace Ryujinx.Horizon.Sdk.Sf { int argsCount = args.Length; - int[] sizes = new int[argsCount]; + int[] sizes = new int[argsCount]; int[] aligns = new int[argsCount]; - int[] map = new int[argsCount]; + int[] map = new int[argsCount]; for (int i = 0; i < argsCount; i++) { - sizes[i] = args[i].ArgSize; + sizes[i] = args[i].ArgSize; aligns[i] = args[i].ArgAlignment; - map[i] = i; + map[i] = i; } for (int i = 1; i < argsCount; i++) @@ -35,9 +35,9 @@ namespace Ryujinx.Horizon.Sdk.Sf foreach (int i in map) { - offset = BitUtils.AlignUp(offset, aligns[i]); + offset = BitUtils.AlignUp(offset, aligns[i]); offsets[i] = offset; - offset += sizes[i]; + offset += sizes[i]; } offsets[argsCount] = offset; @@ -46,4 +46,4 @@ namespace Ryujinx.Horizon.Sdk.Sf return offsets; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Sf/SfResult.cs b/src/Ryujinx.Horizon/Sdk/Sf/SfResult.cs index 72502d17e..029e17af0 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/SfResult.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/SfResult.cs @@ -6,6 +6,7 @@ namespace Ryujinx.Horizon.Sdk.Sf { public const int ModuleId = 10; +#pragma warning disable IDE0055 // Disable formatting public static Result NotSupported => new(ModuleId, 1); public static Result InvalidHeaderSize => new(ModuleId, 202); public static Result InvalidInHeader => new(ModuleId, 211); @@ -23,5 +24,6 @@ namespace Ryujinx.Horizon.Sdk.Sf public static bool RequestContextChanged(Result result) => result.InRange(800, 899); public static bool Invalidated(Result result) => result.InRange(801, 809); public static bool RequestDeferred(Result result) => result.InRange(811, 819); +#pragma warning restore IDE0055 } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Sm/IManagerService.cs b/src/Ryujinx.Horizon/Sdk/Sm/IManagerService.cs index 644285834..2343c7d6f 100644 --- a/src/Ryujinx.Horizon/Sdk/Sm/IManagerService.cs +++ b/src/Ryujinx.Horizon/Sdk/Sm/IManagerService.cs @@ -5,4 +5,4 @@ namespace Ryujinx.Horizon.Sdk.Sm interface IManagerService : IServiceObject { } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Sm/IUserService.cs b/src/Ryujinx.Horizon/Sdk/Sm/IUserService.cs index ad9bc9d7b..8605cdd1b 100644 --- a/src/Ryujinx.Horizon/Sdk/Sm/IUserService.cs +++ b/src/Ryujinx.Horizon/Sdk/Sm/IUserService.cs @@ -10,4 +10,4 @@ namespace Ryujinx.Horizon.Sdk.Sm Result RegisterService(out int handle, ServiceName name, int maxSessions, bool isLight); Result UnregisterService(ServiceName name); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sdk/Sm/ServiceName.cs b/src/Ryujinx.Horizon/Sdk/Sm/ServiceName.cs index 9b7fae3f5..f90d39c22 100644 --- a/src/Ryujinx.Horizon/Sdk/Sm/ServiceName.cs +++ b/src/Ryujinx.Horizon/Sdk/Sm/ServiceName.cs @@ -4,13 +4,13 @@ using System.Runtime.InteropServices; namespace Ryujinx.Horizon.Sdk.Sm { [StructLayout(LayoutKind.Sequential, Pack = 1)] - struct ServiceName + readonly struct ServiceName { - public static ServiceName Invalid { get; } = new ServiceName(0); + public static ServiceName Invalid { get; } = new(0); public bool IsValid => Packed != 0; - public int Length => sizeof(ulong); + public const int Length = sizeof(ulong); public ulong Packed { get; } diff --git a/src/Ryujinx.Horizon/Sdk/Sm/SmApi.cs b/src/Ryujinx.Horizon/Sdk/Sm/SmApi.cs index 533e68d9c..3e5635bf1 100644 --- a/src/Ryujinx.Horizon/Sdk/Sm/SmApi.cs +++ b/src/Ryujinx.Horizon/Sdk/Sm/SmApi.cs @@ -110,4 +110,4 @@ namespace Ryujinx.Horizon.Sdk.Sm return ServiceUtil.SendRequest(out _, _portHandle, 4, sendPid: true, data); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/ServiceEntry.cs b/src/Ryujinx.Horizon/ServiceEntry.cs index 06152d9ff..edf76fcd8 100644 --- a/src/Ryujinx.Horizon/ServiceEntry.cs +++ b/src/Ryujinx.Horizon/ServiceEntry.cs @@ -4,17 +4,17 @@ using System; namespace Ryujinx.Horizon { - public struct ServiceEntry + public readonly struct ServiceEntry { private readonly Action _entrypoint; - private readonly ServiceTable _serviceTable; - private readonly HorizonOptions _options; + private readonly ServiceTable _serviceTable; + private readonly HorizonOptions _options; internal ServiceEntry(Action entrypoint, ServiceTable serviceTable, HorizonOptions options) { - _entrypoint = entrypoint; + _entrypoint = entrypoint; _serviceTable = serviceTable; - _options = options; + _options = options; } public void Start(ISyscallApi syscallApi, IVirtualMemoryManager addressSpace, IThreadContext threadContext) @@ -24,4 +24,4 @@ namespace Ryujinx.Horizon _entrypoint(_serviceTable); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/ServiceTable.cs b/src/Ryujinx.Horizon/ServiceTable.cs index d97457d92..d47f91bf9 100644 --- a/src/Ryujinx.Horizon/ServiceTable.cs +++ b/src/Ryujinx.Horizon/ServiceTable.cs @@ -57,4 +57,4 @@ namespace Ryujinx.Horizon Dispose(true); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sm/Impl/ServiceInfo.cs b/src/Ryujinx.Horizon/Sm/Impl/ServiceInfo.cs index 50c18a2c9..fed420aa8 100644 --- a/src/Ryujinx.Horizon/Sm/Impl/ServiceInfo.cs +++ b/src/Ryujinx.Horizon/Sm/Impl/ServiceInfo.cs @@ -5,16 +5,16 @@ namespace Ryujinx.Horizon.Sm.Impl struct ServiceInfo { public ServiceName Name; - public ulong OwnerProcessId; - public int PortHandle; + public ulong OwnerProcessId; + public int PortHandle; public void Free() { HorizonStatic.Syscall.CloseHandle(PortHandle); - Name = ServiceName.Invalid; + Name = ServiceName.Invalid; OwnerProcessId = 0L; - PortHandle = 0; + PortHandle = 0; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sm/Impl/ServiceManager.cs b/src/Ryujinx.Horizon/Sm/Impl/ServiceManager.cs index d1f94267c..929474aa7 100644 --- a/src/Ryujinx.Horizon/Sm/Impl/ServiceManager.cs +++ b/src/Ryujinx.Horizon/Sm/Impl/ServiceManager.cs @@ -40,7 +40,7 @@ namespace Ryujinx.Horizon.Sm.Impl return result == KernelResult.SessionCountExceeded ? SmResult.OutOfSessions : result; } - private Result GetServiceImpl(out int handle, ref ServiceInfo serviceInfo) + private static Result GetServiceImpl(out int handle, ref ServiceInfo serviceInfo) { return HorizonStatic.Syscall.ConnectToPort(out handle, serviceInfo.PortHandle); } @@ -96,8 +96,8 @@ namespace Ryujinx.Horizon.Sm.Impl return result; } - freeService.PortHandle = clientPort; - freeService.Name = name; + freeService.PortHandle = clientPort; + freeService.Name = name; freeService.OwnerProcessId = processId; return Result.Success; @@ -140,7 +140,7 @@ namespace Ryujinx.Horizon.Sm.Impl int nameLength = 1; - for (; nameLength < name.Length; nameLength++) + for (; nameLength < ServiceName.Length; nameLength++) { if (name[nameLength] == 0) { @@ -148,7 +148,7 @@ namespace Ryujinx.Horizon.Sm.Impl } } - while (nameLength < name.Length) + while (nameLength < ServiceName.Length) { if (name[nameLength++] != 0) { @@ -182,4 +182,4 @@ namespace Ryujinx.Horizon.Sm.Impl return -1; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sm/Ipc/UserService.cs b/src/Ryujinx.Horizon/Sm/Ipc/UserService.cs index d093913a9..868a15e6f 100644 --- a/src/Ryujinx.Horizon/Sm/Ipc/UserService.cs +++ b/src/Ryujinx.Horizon/Sm/Ipc/UserService.cs @@ -10,7 +10,7 @@ namespace Ryujinx.Horizon.Sm.Ipc private readonly ServiceManager _serviceManager; private ulong _clientProcessId; - private bool _initialized; + private bool _initialized; public UserService(ServiceManager serviceManager) { @@ -21,7 +21,7 @@ namespace Ryujinx.Horizon.Sm.Ipc public Result Initialize([ClientProcessId] ulong clientProcessId) { _clientProcessId = clientProcessId; - _initialized = true; + _initialized = true; return Result.Success; } @@ -63,4 +63,4 @@ namespace Ryujinx.Horizon.Sm.Ipc return _serviceManager.UnregisterService(_clientProcessId, name); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sm/SmMain.cs b/src/Ryujinx.Horizon/Sm/SmMain.cs index f0b4d3300..7303847ab 100644 --- a/src/Ryujinx.Horizon/Sm/SmMain.cs +++ b/src/Ryujinx.Horizon/Sm/SmMain.cs @@ -1,6 +1,4 @@ -using Ryujinx.Horizon.Prepo; -using Ryujinx.Horizon.Prepo.Types; -using Ryujinx.Horizon.Sdk.Sf.Hipc; +using Ryujinx.Horizon.Sdk.Sf.Hipc; using Ryujinx.Horizon.Sdk.Sm; using Ryujinx.Horizon.Sm.Impl; using Ryujinx.Horizon.Sm.Types; @@ -9,8 +7,8 @@ namespace Ryujinx.Horizon.Sm { public class SmMain { - private const int SmMaxSessionsCount = 64; - private const int SmmMaxSessionsCount = 1; + private const int SmMaxSessionsCount = 64; + private const int SmmMaxSessionsCount = 1; private const int SmTotalMaxSessionsCount = SmMaxSessionsCount + SmmMaxSessionsCount; private const int MaxPortsCount = 2; @@ -31,4 +29,4 @@ namespace Ryujinx.Horizon.Sm _serverManager.ServiceRequests(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sm/SmResult.cs b/src/Ryujinx.Horizon/Sm/SmResult.cs index 2d503a4f8..75f47ca93 100644 --- a/src/Ryujinx.Horizon/Sm/SmResult.cs +++ b/src/Ryujinx.Horizon/Sm/SmResult.cs @@ -6,6 +6,7 @@ namespace Ryujinx.Horizon.Sm { private const int ModuleId = 21; +#pragma warning disable IDE0055 // Disable formatting public static Result OutOfProcess => new(ModuleId, 1); public static Result InvalidClient => new(ModuleId, 2); public static Result OutOfSessions => new(ModuleId, 3); @@ -15,5 +16,6 @@ namespace Ryujinx.Horizon.Sm public static Result NotRegistered => new(ModuleId, 7); public static Result NotAllowed => new(ModuleId, 8); public static Result TooLargeAccessControl => new(ModuleId, 9); +#pragma warning restore IDE0055 } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sm/SmServerManager.cs b/src/Ryujinx.Horizon/Sm/SmServerManager.cs index dc8dc5b67..c04123455 100644 --- a/src/Ryujinx.Horizon/Sm/SmServerManager.cs +++ b/src/Ryujinx.Horizon/Sm/SmServerManager.cs @@ -21,10 +21,10 @@ namespace Ryujinx.Horizon.Sm { return (SmPortIndex)portIndex switch { - SmPortIndex.User => AcceptImpl(server, new UserService(_serviceManager)), + SmPortIndex.User => AcceptImpl(server, new UserService(_serviceManager)), SmPortIndex.Manager => AcceptImpl(server, new ManagerService()), - _ => throw new ArgumentOutOfRangeException(nameof(portIndex)), + _ => throw new ArgumentOutOfRangeException(nameof(portIndex)), }; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Horizon/Sm/Types/SmPortIndex.cs b/src/Ryujinx.Horizon/Sm/Types/SmPortIndex.cs index 5325558b8..a29778566 100644 --- a/src/Ryujinx.Horizon/Sm/Types/SmPortIndex.cs +++ b/src/Ryujinx.Horizon/Sm/Types/SmPortIndex.cs @@ -3,6 +3,6 @@ enum SmPortIndex { User, - Manager + Manager, } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Input/GTK3/GTK3Keyboard.cs b/src/Ryujinx/Input/GTK3/GTK3Keyboard.cs index ca3ff32f4..16bef39b4 100644 --- a/src/Ryujinx/Input/GTK3/GTK3Keyboard.cs +++ b/src/Ryujinx/Input/GTK3/GTK3Keyboard.cs @@ -25,7 +25,7 @@ namespace Ryujinx.Input.GTK3 private readonly GTK3KeyboardDriver _driver; private StandardKeyboardInputConfig _configuration; - private List _buttonsUserMapping; + private readonly List _buttonsUserMapping; public GTK3Keyboard(GTK3KeyboardDriver driver, string id, string name) { @@ -48,6 +48,7 @@ namespace Ryujinx.Input.GTK3 public void Dispose() { // No operations + GC.SuppressFinalize(this); } public KeyboardStateSnapshot GetKeyboardStateSnapshot() @@ -87,7 +88,7 @@ namespace Ryujinx.Input.GTK3 stickX -= 1; } - OpenTK.Mathematics.Vector2 stick = new OpenTK.Mathematics.Vector2(stickX, stickY); + OpenTK.Mathematics.Vector2 stick = new(stickX, stickY); stick.NormalizeFast(); diff --git a/src/Ryujinx/Input/GTK3/GTK3KeyboardDriver.cs b/src/Ryujinx/Input/GTK3/GTK3KeyboardDriver.cs index 10c092fe7..ae249c273 100644 --- a/src/Ryujinx/Input/GTK3/GTK3KeyboardDriver.cs +++ b/src/Ryujinx/Input/GTK3/GTK3KeyboardDriver.cs @@ -9,7 +9,7 @@ namespace Ryujinx.Input.GTK3 public class GTK3KeyboardDriver : IGamepadDriver { private readonly Widget _widget; - private HashSet _pressedKeys; + private readonly HashSet _pressedKeys; public GTK3KeyboardDriver(Widget widget) { @@ -28,13 +28,13 @@ namespace Ryujinx.Input.GTK3 public event Action OnGamepadConnected { - add { } + add { } remove { } } public event Action OnGamepadDisconnected { - add { } + add { } remove { } } @@ -49,6 +49,7 @@ namespace Ryujinx.Input.GTK3 public void Dispose() { + GC.SuppressFinalize(this); Dispose(true); } diff --git a/src/Ryujinx/Input/GTK3/GTK3Mouse.cs b/src/Ryujinx/Input/GTK3/GTK3Mouse.cs index 836c2bf44..0ab817ecb 100644 --- a/src/Ryujinx/Input/GTK3/GTK3Mouse.cs +++ b/src/Ryujinx/Input/GTK3/GTK3Mouse.cs @@ -83,7 +83,8 @@ namespace Ryujinx.Input.GTK3 public void Dispose() { + GC.SuppressFinalize(this); _driver = null; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Input/GTK3/GTK3MouseDriver.cs b/src/Ryujinx/Input/GTK3/GTK3MouseDriver.cs index df37e4f4a..5962bcb25 100644 --- a/src/Ryujinx/Input/GTK3/GTK3MouseDriver.cs +++ b/src/Ryujinx/Input/GTK3/GTK3MouseDriver.cs @@ -12,18 +12,18 @@ namespace Ryujinx.Input.GTK3 private bool _isDisposed; public bool[] PressedButtons { get; } - + public Vector2 CurrentPosition { get; private set; } - public Vector2 Scroll{ get; private set; } + public Vector2 Scroll { get; private set; } public GTK3MouseDriver(Widget parent) { _widget = parent; - _widget.MotionNotifyEvent += Parent_MotionNotifyEvent; - _widget.ButtonPressEvent += Parent_ButtonPressEvent; + _widget.MotionNotifyEvent += Parent_MotionNotifyEvent; + _widget.ButtonPressEvent += Parent_ButtonPressEvent; _widget.ButtonReleaseEvent += Parent_ButtonReleaseEvent; - _widget.ScrollEvent += Parent_ScrollEvent; + _widget.ScrollEvent += Parent_ScrollEvent; PressedButtons = new bool[(int)MouseButton.Count]; } @@ -58,7 +58,7 @@ namespace Ryujinx.Input.GTK3 public bool IsButtonPressed(MouseButton button) { - return PressedButtons[(int) button]; + return PressedButtons[(int)button]; } public Size GetClientSize() @@ -67,21 +67,21 @@ namespace Ryujinx.Input.GTK3 } public string DriverName => "GTK3"; - + public event Action OnGamepadConnected { - add { } + add { } remove { } } public event Action OnGamepadDisconnected { - add { } + add { } remove { } } - public ReadOnlySpan GamepadsIds => new[] {"0"}; - + public ReadOnlySpan GamepadsIds => new[] { "0" }; + public IGamepad GetGamepad(string id) { return new GTK3Mouse(this); @@ -94,6 +94,8 @@ namespace Ryujinx.Input.GTK3 return; } + GC.SuppressFinalize(this); + _isDisposed = true; _widget.MotionNotifyEvent -= Parent_MotionNotifyEvent; @@ -103,4 +105,4 @@ namespace Ryujinx.Input.GTK3 _widget = null; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Modules/Updater/UpdateDialog.cs b/src/Ryujinx/Modules/Updater/UpdateDialog.cs index e0a257fd6..695634374 100644 --- a/src/Ryujinx/Modules/Updater/UpdateDialog.cs +++ b/src/Ryujinx/Modules/Updater/UpdateDialog.cs @@ -12,17 +12,17 @@ namespace Ryujinx.Modules { public class UpdateDialog : Gtk.Window { -#pragma warning disable CS0649, IDE0044 - [Builder.Object] public Label MainText; - [Builder.Object] public Label SecondaryText; +#pragma warning disable CS0649, IDE0044 // Field is never assigned to, Add readonly modifier + [Builder.Object] public Label MainText; + [Builder.Object] public Label SecondaryText; [Builder.Object] public LevelBar ProgressBar; - [Builder.Object] public Button YesButton; - [Builder.Object] public Button NoButton; + [Builder.Object] public Button YesButton; + [Builder.Object] public Button NoButton; #pragma warning restore CS0649, IDE0044 private readonly MainWindow _mainWindow; - private readonly string _buildUrl; - private bool _restartQuery; + private readonly string _buildUrl; + private bool _restartQuery; public UpdateDialog(MainWindow mainWindow, Version newVersion, string buildUrl) : this(new Builder("Ryujinx.Modules.Updater.UpdateDialog.glade"), mainWindow, newVersion, buildUrl) { } @@ -31,16 +31,16 @@ namespace Ryujinx.Modules builder.Autoconnect(this); _mainWindow = mainWindow; - _buildUrl = buildUrl; + _buildUrl = buildUrl; Icon = new Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Logo_Ryujinx.png"); - MainText.Text = "Do you want to update Ryujinx to the latest version?"; + MainText.Text = "Do you want to update Ryujinx to the latest version?"; SecondaryText.Text = $"{Program.Version} -> {newVersion}"; ProgressBar.Hide(); YesButton.Clicked += YesButton_Clicked; - NoButton.Clicked += NoButton_Clicked; + NoButton.Clicked += NoButton_Clicked; } private void YesButton_Clicked(object sender, EventArgs args) @@ -52,7 +52,7 @@ namespace Ryujinx.Modules ProcessStartInfo processStart = new(ryuName) { UseShellExecute = true, - WorkingDirectory = ReleaseInformation.GetBaseApplicationDirectory() + WorkingDirectory = ReleaseInformation.GetBaseApplicationDirectory(), }; foreach (string argument in CommandLineState.Arguments) @@ -74,7 +74,7 @@ namespace Ryujinx.Modules ProgressBar.Show(); SecondaryText.Text = ""; - _restartQuery = true; + _restartQuery = true; Updater.UpdateRyujinx(this, _buildUrl); } @@ -85,10 +85,10 @@ namespace Ryujinx.Modules Updater.Running = false; _mainWindow.Window.Functions = WMFunction.All; - _mainWindow.ExitMenuItem.Sensitive = true; + _mainWindow.ExitMenuItem.Sensitive = true; _mainWindow.UpdateMenuItem.Sensitive = true; Dispose(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Modules/Updater/Updater.cs b/src/Ryujinx/Modules/Updater/Updater.cs index 344edf9e5..f8ce4c0b9 100644 --- a/src/Ryujinx/Modules/Updater/Updater.cs +++ b/src/Ryujinx/Modules/Updater/Updater.cs @@ -24,28 +24,28 @@ namespace Ryujinx.Modules { public static class Updater { - private const string GitHubApiURL = "https://api.github.com"; + private const string GitHubApiUrl = "https://api.github.com"; private const int ConnectionCount = 4; internal static bool Running; - private static readonly string HomeDir = AppDomain.CurrentDomain.BaseDirectory; - private static readonly string UpdateDir = Path.Combine(Path.GetTempPath(), "Ryujinx", "update"); - private static readonly string UpdatePublishDir = Path.Combine(UpdateDir, "publish"); + private static readonly string _homeDir = AppDomain.CurrentDomain.BaseDirectory; + private static readonly string _updateDir = Path.Combine(Path.GetTempPath(), "Ryujinx", "update"); + private static readonly string _updatePublishDir = Path.Combine(_updateDir, "publish"); private static string _buildVer; private static string _platformExt; private static string _buildUrl; - private static long _buildSize; + private static long _buildSize; - private static readonly GithubReleasesJsonSerializerContext SerializerContext = new(JsonHelper.GetDefaultSerializerOptions()); + private static readonly GithubReleasesJsonSerializerContext _serializerContext = new(JsonHelper.GetDefaultSerializerOptions()); // On Windows, GtkSharp.Dependencies adds these extra dirs that must be cleaned during updates. - private static readonly string[] WindowsDependencyDirs = new string[] { "bin", "etc", "lib", "share" }; + private static readonly string[] _windowsDependencyDirs = { "bin", "etc", "lib", "share" }; private static HttpClient ConstructHttpClient() { - HttpClient result = new HttpClient(); + HttpClient result = new(); // Required by GitHub to interact with APIs. result.DefaultRequestHeaders.Add("User-Agent", "Ryujinx-Updater/1.0.0"); @@ -55,7 +55,10 @@ namespace Ryujinx.Modules public static async Task BeginParse(MainWindow mainWindow, bool showVersionUpToDate) { - if (Running) return; + if (Running) + { + return; + } Running = true; mainWindow.UpdateMenuItem.Sensitive = false; @@ -65,17 +68,17 @@ namespace Ryujinx.Modules // Detect current platform if (OperatingSystem.IsMacOS()) { - _platformExt = "osx_x64.zip"; + _platformExt = "osx_x64.zip"; artifactIndex = 1; } else if (OperatingSystem.IsWindows()) { - _platformExt = "win_x64.zip"; + _platformExt = "win_x64.zip"; artifactIndex = 2; } else if (OperatingSystem.IsLinux()) { - _platformExt = "linux_x64.tar.gz"; + _platformExt = "linux_x64.tar.gz"; artifactIndex = 0; } @@ -105,11 +108,11 @@ namespace Ryujinx.Modules try { using HttpClient jsonClient = ConstructHttpClient(); - string buildInfoURL = $"{GitHubApiURL}/repos/{ReleaseInformation.ReleaseChannelOwner}/{ReleaseInformation.ReleaseChannelRepo}/releases/latest"; + string buildInfoUrl = $"{GitHubApiUrl}/repos/{ReleaseInformation.ReleaseChannelOwner}/{ReleaseInformation.ReleaseChannelRepo}/releases/latest"; // Fetch latest build information - string fetchedJson = await jsonClient.GetStringAsync(buildInfoURL); - var fetched = JsonHelper.Deserialize(fetchedJson, SerializerContext.GithubReleasesJsonResponse); + string fetchedJson = await jsonClient.GetStringAsync(buildInfoUrl); + var fetched = JsonHelper.Deserialize(fetchedJson, _serializerContext.GithubReleasesJsonResponse); _buildVer = fetched.Name; foreach (var asset in fetched.Assets) @@ -176,45 +179,43 @@ namespace Ryujinx.Modules } // Fetch build size information to learn chunk sizes. - using (HttpClient buildSizeClient = ConstructHttpClient()) + using HttpClient buildSizeClient = ConstructHttpClient(); + try { - try - { - buildSizeClient.DefaultRequestHeaders.Add("Range", "bytes=0-0"); + buildSizeClient.DefaultRequestHeaders.Add("Range", "bytes=0-0"); - HttpResponseMessage message = await buildSizeClient.GetAsync(new Uri(_buildUrl), HttpCompletionOption.ResponseHeadersRead); + HttpResponseMessage message = await buildSizeClient.GetAsync(new Uri(_buildUrl), HttpCompletionOption.ResponseHeadersRead); - _buildSize = message.Content.Headers.ContentRange.Length.Value; - } - catch (Exception ex) - { - Logger.Warning?.Print(LogClass.Application, ex.Message); - Logger.Warning?.Print(LogClass.Application, "Couldn't determine build size for update, using single-threaded updater"); + _buildSize = message.Content.Headers.ContentRange.Length.Value; + } + catch (Exception ex) + { + Logger.Warning?.Print(LogClass.Application, ex.Message); + Logger.Warning?.Print(LogClass.Application, "Couldn't determine build size for update, using single-threaded updater"); - _buildSize = -1; - } + _buildSize = -1; } // Show a message asking the user if they want to update - UpdateDialog updateDialog = new UpdateDialog(mainWindow, newVersion, _buildUrl); + UpdateDialog updateDialog = new(mainWindow, newVersion, _buildUrl); updateDialog.Show(); } public static void UpdateRyujinx(UpdateDialog updateDialog, string downloadUrl) { // Empty update dir, although it shouldn't ever have anything inside it - if (Directory.Exists(UpdateDir)) + if (Directory.Exists(_updateDir)) { - Directory.Delete(UpdateDir, true); + Directory.Delete(_updateDir, true); } - Directory.CreateDirectory(UpdateDir); + Directory.CreateDirectory(_updateDir); - string updateFile = Path.Combine(UpdateDir, "update.bin"); + string updateFile = Path.Combine(_updateDir, "update.bin"); // Download the update .zip - updateDialog.MainText.Text = "Downloading Update..."; - updateDialog.ProgressBar.Value = 0; + updateDialog.MainText.Text = "Downloading Update..."; + updateDialog.ProgressBar.Value = 0; updateDialog.ProgressBar.MaxValue = 100; if (_buildSize >= 0) @@ -237,8 +238,8 @@ namespace Ryujinx.Modules int totalProgressPercentage = 0; int[] progressPercentage = new int[ConnectionCount]; - List list = new List(ConnectionCount); - List webClients = new List(ConnectionCount); + List list = new(ConnectionCount); + List webClients = new(ConnectionCount); for (int i = 0; i < ConnectionCount; i++) { @@ -249,7 +250,7 @@ namespace Ryujinx.Modules { #pragma warning disable SYSLIB0014 // TODO: WebClient is obsolete and need to be replaced with a more complex logic using HttpClient. - using WebClient client = new WebClient(); + using WebClient client = new(); #pragma warning restore SYSLIB0014 webClients.Add(client); @@ -337,35 +338,32 @@ namespace Ryujinx.Modules private static void DoUpdateWithSingleThreadWorker(UpdateDialog updateDialog, string downloadUrl, string updateFile) { - using HttpClient client = new HttpClient(); + using HttpClient client = new(); // We do not want to timeout while downloading client.Timeout = TimeSpan.FromDays(1); - using (HttpResponseMessage response = client.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead).Result) - using (Stream remoteFileStream = response.Content.ReadAsStreamAsync().Result) + using HttpResponseMessage response = client.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead).Result; + using Stream remoteFileStream = response.Content.ReadAsStreamAsync().Result; + using Stream updateFileStream = File.Open(updateFile, FileMode.Create); + + long totalBytes = response.Content.Headers.ContentLength.Value; + long byteWritten = 0; + + byte[] buffer = new byte[32 * 1024]; + + while (true) { - using (Stream updateFileStream = File.Open(updateFile, FileMode.Create)) + int readSize = remoteFileStream.Read(buffer); + + if (readSize == 0) { - long totalBytes = response.Content.Headers.ContentLength.Value; - long byteWritten = 0; - - byte[] buffer = new byte[32 * 1024]; - - while (true) - { - int readSize = remoteFileStream.Read(buffer); - - if (readSize == 0) - { - break; - } - - byteWritten += readSize; - - updateDialog.ProgressBar.Value = ((double)byteWritten / totalBytes) * 100; - updateFileStream.Write(buffer, 0, readSize); - } + break; } + + byteWritten += readSize; + + updateDialog.ProgressBar.Value = ((double)byteWritten / totalBytes) * 100; + updateFileStream.Write(buffer, 0, readSize); } InstallUpdate(updateDialog, updateFile); @@ -373,9 +371,9 @@ namespace Ryujinx.Modules private static void DoUpdateWithSingleThread(UpdateDialog updateDialog, string downloadUrl, string updateFile) { - Thread worker = new Thread(() => DoUpdateWithSingleThreadWorker(updateDialog, downloadUrl, updateFile)) + Thread worker = new(() => DoUpdateWithSingleThreadWorker(updateDialog, downloadUrl, updateFile)) { - Name = "Updater.SingleThreadWorker" + Name = "Updater.SingleThreadWorker", }; worker.Start(); } @@ -383,14 +381,14 @@ namespace Ryujinx.Modules private static async void InstallUpdate(UpdateDialog updateDialog, string updateFile) { // Extract Update - updateDialog.MainText.Text = "Extracting Update..."; + updateDialog.MainText.Text = "Extracting Update..."; updateDialog.ProgressBar.Value = 0; if (OperatingSystem.IsLinux()) { - using Stream inStream = File.OpenRead(updateFile); - using Stream gzipStream = new GZipInputStream(inStream); - using TarInputStream tarStream = new TarInputStream(gzipStream, Encoding.ASCII); + using Stream inStream = File.OpenRead(updateFile); + using Stream gzipStream = new GZipInputStream(inStream); + using TarInputStream tarStream = new(gzipStream, Encoding.ASCII); updateDialog.ProgressBar.MaxValue = inStream.Length; await Task.Run(() => @@ -401,16 +399,17 @@ namespace Ryujinx.Modules { while ((tarEntry = tarStream.GetNextEntry()) != null) { - if (tarEntry.IsDirectory) continue; + if (tarEntry.IsDirectory) + { + continue; + } - string outPath = Path.Combine(UpdateDir, tarEntry.Name); + string outPath = Path.Combine(_updateDir, tarEntry.Name); Directory.CreateDirectory(Path.GetDirectoryName(outPath)); - using (FileStream outStream = File.OpenWrite(outPath)) - { - tarStream.CopyEntryContents(outStream); - } + using FileStream outStream = File.OpenWrite(outPath); + tarStream.CopyEntryContents(outStream); File.SetUnixFileMode(outPath, (UnixFileMode)tarEntry.TarHeader.Mode); File.SetLastWriteTime(outPath, DateTime.SpecifyKind(tarEntry.ModTime, DateTimeKind.Utc)); @@ -429,25 +428,26 @@ namespace Ryujinx.Modules } else { - using Stream inStream = File.OpenRead(updateFile); - using ZipFile zipFile = new ZipFile(inStream); + using Stream inStream = File.OpenRead(updateFile); + using ZipFile zipFile = new(inStream); updateDialog.ProgressBar.MaxValue = zipFile.Count; await Task.Run(() => { foreach (ZipEntry zipEntry in zipFile) { - if (zipEntry.IsDirectory) continue; + if (zipEntry.IsDirectory) + { + continue; + } - string outPath = Path.Combine(UpdateDir, zipEntry.Name); + string outPath = Path.Combine(_updateDir, zipEntry.Name); Directory.CreateDirectory(Path.GetDirectoryName(outPath)); - using (Stream zipStream = zipFile.GetInputStream(zipEntry)) - using (FileStream outStream = File.OpenWrite(outPath)) - { - zipStream.CopyTo(outStream); - } + using Stream zipStream = zipFile.GetInputStream(zipEntry); + using FileStream outStream = File.OpenWrite(outPath); + zipStream.CopyTo(outStream); File.SetLastWriteTime(outPath, DateTime.SpecifyKind(zipEntry.DateTime, DateTimeKind.Utc)); @@ -464,8 +464,8 @@ namespace Ryujinx.Modules List allFiles = EnumerateFilesToDelete().ToList(); - updateDialog.MainText.Text = "Renaming Old Files..."; - updateDialog.ProgressBar.Value = 0; + updateDialog.MainText.Text = "Renaming Old Files..."; + updateDialog.ProgressBar.Value = 0; updateDialog.ProgressBar.MaxValue = allFiles.Count; // Replace old files @@ -490,19 +490,19 @@ namespace Ryujinx.Modules Application.Invoke(delegate { - updateDialog.MainText.Text = "Adding New Files..."; - updateDialog.ProgressBar.Value = 0; - updateDialog.ProgressBar.MaxValue = Directory.GetFiles(UpdatePublishDir, "*", SearchOption.AllDirectories).Length; + updateDialog.MainText.Text = "Adding New Files..."; + updateDialog.ProgressBar.Value = 0; + updateDialog.ProgressBar.MaxValue = Directory.GetFiles(_updatePublishDir, "*", SearchOption.AllDirectories).Length; }); - MoveAllFilesOver(UpdatePublishDir, HomeDir, updateDialog); + MoveAllFilesOver(_updatePublishDir, _homeDir, updateDialog); }); - Directory.Delete(UpdateDir, true); + Directory.Delete(_updateDir, true); - updateDialog.MainText.Text = "Update Complete!"; + updateDialog.MainText.Text = "Update Complete!"; updateDialog.SecondaryText.Text = "Do you want to restart Ryujinx now?"; - updateDialog.Modal = true; + updateDialog.Modal = true; updateDialog.ProgressBar.Hide(); updateDialog.YesButton.Show(); @@ -563,15 +563,15 @@ namespace Ryujinx.Modules // NOTE: This method should always reflect the latest build layout. private static IEnumerable EnumerateFilesToDelete() { - var files = Directory.EnumerateFiles(HomeDir); // All files directly in base dir. + var files = Directory.EnumerateFiles(_homeDir); // All files directly in base dir. // Determine and exclude user files only when the updater is running, not when cleaning old files if (Running) { // Compare the loose files in base directory against the loose files from the incoming update, and store foreign ones in a user list. - var oldFiles = Directory.EnumerateFiles(HomeDir, "*", SearchOption.TopDirectoryOnly).Select(Path.GetFileName); - var newFiles = Directory.EnumerateFiles(UpdatePublishDir, "*", SearchOption.TopDirectoryOnly).Select(Path.GetFileName); - var userFiles = oldFiles.Except(newFiles).Select(filename => Path.Combine(HomeDir, filename)); + var oldFiles = Directory.EnumerateFiles(_homeDir, "*", SearchOption.TopDirectoryOnly).Select(Path.GetFileName); + var newFiles = Directory.EnumerateFiles(_updatePublishDir, "*", SearchOption.TopDirectoryOnly).Select(Path.GetFileName); + var userFiles = oldFiles.Except(newFiles).Select(filename => Path.Combine(_homeDir, filename)); // Remove user files from the paths in files. files = files.Except(userFiles); @@ -579,9 +579,9 @@ namespace Ryujinx.Modules if (OperatingSystem.IsWindows()) { - foreach (string dir in WindowsDependencyDirs) + foreach (string dir in _windowsDependencyDirs) { - string dirPath = Path.Combine(HomeDir, dir); + string dirPath = Path.Combine(_homeDir, dir); if (Directory.Exists(dirPath)) { files = files.Concat(Directory.EnumerateFiles(dirPath, "*", SearchOption.AllDirectories)); @@ -628,4 +628,4 @@ namespace Ryujinx.Modules } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Program.cs b/src/Ryujinx/Program.cs index 96024548f..50151d733 100644 --- a/src/Ryujinx/Program.cs +++ b/src/Ryujinx/Program.cs @@ -43,10 +43,7 @@ namespace Ryujinx [LibraryImport("libc", SetLastError = true)] private static partial int setenv([MarshalAs(UnmanagedType.LPStr)] string name, [MarshalAs(UnmanagedType.LPStr)] string value, int overwrite); - [LibraryImport("libc")] - private static partial IntPtr getenv([MarshalAs(UnmanagedType.LPStr)] string name); - - private const uint MB_ICONWARNING = 0x30; + private const uint MbIconWarning = 0x30; static Program() { @@ -78,16 +75,16 @@ namespace Ryujinx if (OperatingSystem.IsWindows() && !OperatingSystem.IsWindowsVersionAtLeast(10, 0, 17134)) { - MessageBoxA(IntPtr.Zero, "You are running an outdated version of Windows.\n\nStarting on June 1st 2022, Ryujinx will only support Windows 10 1803 and newer.\n", $"Ryujinx {Version}", MB_ICONWARNING); + MessageBoxA(IntPtr.Zero, "You are running an outdated version of Windows.\n\nStarting on June 1st 2022, Ryujinx will only support Windows 10 1803 and newer.\n", $"Ryujinx {Version}", MbIconWarning); } // Parse arguments CommandLineState.ParseArguments(args); // Hook unhandled exception and process exit events. - GLib.ExceptionManager.UnhandledException += (GLib.UnhandledExceptionArgs e) => ProcessUnhandledException(e.ExceptionObject as Exception, e.IsTerminating); + GLib.ExceptionManager.UnhandledException += (GLib.UnhandledExceptionArgs e) => ProcessUnhandledException(e.ExceptionObject as Exception, e.IsTerminating); AppDomain.CurrentDomain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) => ProcessUnhandledException(e.ExceptionObject as Exception, e.IsTerminating); - AppDomain.CurrentDomain.ProcessExit += (object sender, EventArgs e) => Exit(); + AppDomain.CurrentDomain.ProcessExit += (object sender, EventArgs e) => Exit(); // Make process DPI aware for proper window sizing on high-res screens. ForceDpiAware.Windows(); @@ -102,7 +99,11 @@ namespace Ryujinx // This ends up causing race condition and abort of XCB when a context is created by SPB (even if SPB do call XInitThreads). if (OperatingSystem.IsLinux()) { - XInitThreads(); + if (XInitThreads() == 0) + { + throw new NotSupportedException("Failed to initialize multi-threading support."); + } + Environment.SetEnvironmentVariable("GDK_BACKEND", "x11"); setenv("GDK_BACKEND", "x11", 1); } @@ -121,7 +122,7 @@ namespace Ryujinx resourcesDataDir = baseDirectory; } - void SetEnvironmentVariableNoCaching(string key, string value) + static void SetEnvironmentVariableNoCaching(string key, string value) { int res = setenv(key, value, 1); Debug.Assert(res != -1); @@ -163,11 +164,11 @@ namespace Ryujinx // Sets ImageSharp Jpeg Encoder Quality. SixLabors.ImageSharp.Configuration.Default.ImageFormatsManager.SetEncoder(JpegFormat.Instance, new JpegEncoder() { - Quality = 100 + Quality = 100, }); - string localConfigurationPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.json"); - string appDataConfigurationPath = Path.Combine(AppDataManager.BaseDirPath, "Config.json"); + string localConfigurationPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.json"); + string appDataConfigurationPath = Path.Combine(AppDataManager.BaseDirPath, "Config.json"); // Now load the configuration as the other subsystems are now registered ConfigurationPath = File.Exists(localConfigurationPath) @@ -232,7 +233,7 @@ namespace Ryujinx "never" => HideCursorMode.Never, "onidle" => HideCursorMode.OnIdle, "always" => HideCursorMode.Always, - _ => ConfigurationState.Instance.HideCursor.Value + _ => ConfigurationState.Instance.HideCursor.Value, }; } @@ -261,7 +262,7 @@ namespace Ryujinx } // Show the main window UI. - MainWindow mainWindow = new MainWindow(); + MainWindow mainWindow = new(); mainWindow.Show(); if (OperatingSystem.IsLinux()) @@ -278,7 +279,7 @@ namespace Ryujinx { { 0, "Yes, until the next restart" }, { 1, "Yes, permanently" }, - { 2, "No" } + { 2, "No" }, }; ResponseType response = GtkDialog.CreateCustomDialog( @@ -347,7 +348,7 @@ namespace Ryujinx var buttonTexts = new Dictionary() { { 0, "Yes (Vulkan)" }, - { 1, "No (OpenGL)" } + { 1, "No (OpenGL)" }, }; ResponseType response = GtkDialog.CreateCustomDialog( @@ -416,4 +417,4 @@ namespace Ryujinx Logger.Shutdown(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Ui/Applet/ErrorAppletDialog.cs b/src/Ryujinx/Ui/Applet/ErrorAppletDialog.cs index d4cc7cccb..cd3530f34 100644 --- a/src/Ryujinx/Ui/Applet/ErrorAppletDialog.cs +++ b/src/Ryujinx/Ui/Applet/ErrorAppletDialog.cs @@ -24,8 +24,8 @@ namespace Ryujinx.Ui.Applet { AddButton("OK", 0); } - + ShowAll(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Ui/Applet/GtkDynamicTextInputHandler.cs b/src/Ryujinx/Ui/Applet/GtkDynamicTextInputHandler.cs index 79df3cc77..3a3da4650 100644 --- a/src/Ryujinx/Ui/Applet/GtkDynamicTextInputHandler.cs +++ b/src/Ryujinx/Ui/Applet/GtkDynamicTextInputHandler.cs @@ -11,15 +11,15 @@ namespace Ryujinx.Ui.Applet ///
internal class GtkDynamicTextInputHandler : IDynamicTextInputHandler { - private readonly Window _parent; - private readonly OffscreenWindow _inputToTextWindow = new OffscreenWindow(); - private readonly RawInputToTextEntry _inputToTextEntry = new RawInputToTextEntry(); + private readonly Window _parent; + private readonly OffscreenWindow _inputToTextWindow = new(); + private readonly RawInputToTextEntry _inputToTextEntry = new(); private bool _canProcessInput; public event DynamicTextChangedHandler TextChangedEvent; - public event KeyPressedHandler KeyPressedEvent; - public event KeyReleasedHandler KeyReleasedEvent; + public event KeyPressedHandler KeyPressedEvent; + public event KeyReleasedHandler KeyReleasedEvent; public bool TextProcessingEnabled { @@ -37,7 +37,7 @@ namespace Ryujinx.Ui.Applet public GtkDynamicTextInputHandler(Window parent) { _parent = parent; - _parent.KeyPressEvent += HandleKeyPressEvent; + _parent.KeyPressEvent += HandleKeyPressEvent; _parent.KeyReleaseEvent += HandleKeyReleaseEvent; _inputToTextWindow.Add(_inputToTextEntry); @@ -101,8 +101,8 @@ namespace Ryujinx.Ui.Applet public void Dispose() { - _parent.KeyPressEvent -= HandleKeyPressEvent; + _parent.KeyPressEvent -= HandleKeyPressEvent; _parent.KeyReleaseEvent -= HandleKeyReleaseEvent; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Ui/Applet/GtkHostUiHandler.cs b/src/Ryujinx/Ui/Applet/GtkHostUiHandler.cs index b7577b85d..241e5e6cf 100644 --- a/src/Ryujinx/Ui/Applet/GtkHostUiHandler.cs +++ b/src/Ryujinx/Ui/Applet/GtkHostUiHandler.cs @@ -5,7 +5,6 @@ using Ryujinx.HLE.Ui; using Ryujinx.Ui.Widgets; using System; using System.Threading; -using Action = System.Action; namespace Ryujinx.Ui.Applet { @@ -37,7 +36,7 @@ namespace Ryujinx.Ui.Applet public bool DisplayMessageDialog(string title, string message) { - ManualResetEvent dialogCloseEvent = new ManualResetEvent(false); + ManualResetEvent dialogCloseEvent = new(false); bool okPressed = false; @@ -49,9 +48,9 @@ namespace Ryujinx.Ui.Applet { msgDialog = new MessageDialog(_parent, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Ok, null) { - Title = title, - Text = message, - UseMarkup = true + Title = title, + Text = message, + UseMarkup = true, }; msgDialog.SetDefaultSize(400, 0); @@ -84,10 +83,10 @@ namespace Ryujinx.Ui.Applet public bool DisplayInputDialog(SoftwareKeyboardUiArgs args, out string userText) { - ManualResetEvent dialogCloseEvent = new ManualResetEvent(false); + ManualResetEvent dialogCloseEvent = new(false); - bool okPressed = false; - bool error = false; + bool okPressed = false; + bool error = false; string inputText = args.InitialText ?? ""; Application.Invoke(delegate @@ -96,14 +95,14 @@ namespace Ryujinx.Ui.Applet { var swkbdDialog = new SwkbdAppletDialog(_parent) { - Title = "Software Keyboard", - Text = args.HeaderText, - SecondaryText = args.SubtitleText + Title = "Software Keyboard", + Text = args.HeaderText, + SecondaryText = args.SubtitleText, }; - swkbdDialog.InputEntry.Text = inputText; + swkbdDialog.InputEntry.Text = inputText; swkbdDialog.InputEntry.PlaceholderText = args.GuideText; - swkbdDialog.OkButton.Label = args.SubmitText; + swkbdDialog.OkButton.Label = args.SubmitText; swkbdDialog.SetInputLengthValidation(args.StringLengthMin, args.StringLengthMax); swkbdDialog.SetInputValidation(args.KeyboardMode); @@ -143,7 +142,7 @@ namespace Ryujinx.Ui.Applet public bool DisplayErrorAppletDialog(string title, string message, string[] buttons) { - ManualResetEvent dialogCloseEvent = new ManualResetEvent(false); + ManualResetEvent dialogCloseEvent = new(false); bool showDetails = false; @@ -151,12 +150,12 @@ namespace Ryujinx.Ui.Applet { try { - ErrorAppletDialog msgDialog = new ErrorAppletDialog(_parent, DialogFlags.DestroyWithParent, MessageType.Error, buttons) + ErrorAppletDialog msgDialog = new(_parent, DialogFlags.DestroyWithParent, MessageType.Error, buttons) { - Title = title, - Text = message, - UseMarkup = true, - WindowPosition = WindowPosition.CenterAlways + Title = title, + Text = message, + UseMarkup = true, + WindowPosition = WindowPosition.CenterAlways, }; msgDialog.SetDefaultSize(400, 0); @@ -193,22 +192,9 @@ namespace Ryujinx.Ui.Applet return showDetails; } - private void SynchronousGtkInvoke(Action action) - { - var waitHandle = new ManualResetEventSlim(); - - Application.Invoke(delegate - { - action(); - waitHandle.Set(); - }); - - waitHandle.Wait(); - } - public IDynamicTextInputHandler CreateDynamicTextInputHandler() { return new GtkDynamicTextInputHandler(_parent); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Ui/Applet/GtkHostUiTheme.cs b/src/Ryujinx/Ui/Applet/GtkHostUiTheme.cs index f25da47c4..df8103325 100644 --- a/src/Ryujinx/Ui/Applet/GtkHostUiTheme.cs +++ b/src/Ryujinx/Ui/Applet/GtkHostUiTheme.cs @@ -6,7 +6,7 @@ namespace Ryujinx.Ui.Applet { internal class GtkHostUiTheme : IHostUiTheme { - private const int RenderSurfaceWidth = 32; + private const int RenderSurfaceWidth = 32; private const int RenderSurfaceHeight = 32; public string FontFamily { get; private set; } @@ -19,7 +19,7 @@ namespace Ryujinx.Ui.Applet public GtkHostUiTheme(Window parent) { - Entry entry = new Entry(); + Entry entry = new(); entry.SetStateFlags(StateFlags.Selected, true); // Get the font and some colors directly from GTK. @@ -30,10 +30,10 @@ namespace Ryujinx.Ui.Applet var defaultForegroundColor = entry.StyleContext.GetColor(StateFlags.Normal); var selectedForegroundColor = entry.StyleContext.GetColor(StateFlags.Selected); - DefaultForegroundColor = new ThemeColor((float) defaultForegroundColor.Alpha, (float) defaultForegroundColor.Red, (float) defaultForegroundColor.Green, (float) defaultForegroundColor.Blue); + DefaultForegroundColor = new ThemeColor((float)defaultForegroundColor.Alpha, (float)defaultForegroundColor.Red, (float)defaultForegroundColor.Green, (float)defaultForegroundColor.Blue); SelectionForegroundColor = new ThemeColor((float)selectedForegroundColor.Alpha, (float)selectedForegroundColor.Red, (float)selectedForegroundColor.Green, (float)selectedForegroundColor.Blue); - ListBoxRow row = new ListBoxRow(); + ListBoxRow row = new(); row.SetStateFlags(StateFlags.Selected, true); // Request the main thread to render some UI elements to an image to get an approximation for the color. @@ -67,7 +67,7 @@ namespace Ryujinx.Ui.Applet SelectionBackgroundColor = DefaultBorderColor; } - private ThemeColor ToThemeColor(byte[] data) + private static ThemeColor ToThemeColor(byte[] data) { Debug.Assert(data.Length == 4 * RenderSurfaceWidth * RenderSurfaceHeight); @@ -87,4 +87,4 @@ namespace Ryujinx.Ui.Applet return new ThemeColor(a, r, g, b); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Ui/Applet/SwkbdAppletDialog.cs b/src/Ryujinx/Ui/Applet/SwkbdAppletDialog.cs index 13d30f6c0..1ed08250f 100644 --- a/src/Ryujinx/Ui/Applet/SwkbdAppletDialog.cs +++ b/src/Ryujinx/Ui/Applet/SwkbdAppletDialog.cs @@ -9,7 +9,9 @@ namespace Ryujinx.Ui.Applet { private int _inputMin; private int _inputMax; +#pragma warning disable IDE0052 // Remove unread private member private KeyboardMode _mode; +#pragma warning restore IDE0052 private string _validationInfoText = ""; @@ -18,8 +20,8 @@ namespace Ryujinx.Ui.Applet private readonly Label _validationInfo; - public Entry InputEntry { get; } - public Button OkButton { get; } + public Entry InputEntry { get; } + public Button OkButton { get; } public Button CancelButton { get; } public SwkbdAppletDialog(Window parent) : base(parent, DialogFlags.Modal | DialogFlags.DestroyWithParent, MessageType.Question, ButtonsType.None, null) @@ -28,22 +30,22 @@ namespace Ryujinx.Ui.Applet _validationInfo = new Label() { - Visible = false + Visible = false, }; InputEntry = new Entry() { - Visible = true + Visible = true, }; InputEntry.Activated += OnInputActivated; - InputEntry.Changed += OnInputChanged; + InputEntry.Changed += OnInputChanged; - OkButton = (Button)AddButton("OK", ResponseType.Ok); + OkButton = (Button)AddButton("OK", ResponseType.Ok); CancelButton = (Button)AddButton("Cancel", ResponseType.Cancel); ((Box)MessageArea).PackEnd(_validationInfo, true, true, 0); - ((Box)MessageArea).PackEnd(InputEntry, true, true, 4); + ((Box)MessageArea).PackEnd(InputEntry, true, true, 4); } private void ApplyValidationInfo() @@ -122,4 +124,4 @@ namespace Ryujinx.Ui.Applet OkButton.Sensitive = _checkLength(InputEntry.Text.Length) && _checkInput(InputEntry.Text); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Ui/Helper/MetalHelper.cs b/src/Ryujinx/Ui/Helper/MetalHelper.cs index c2d4893e8..a7af2aed2 100644 --- a/src/Ryujinx/Ui/Helper/MetalHelper.cs +++ b/src/Ryujinx/Ui/Helper/MetalHelper.cs @@ -12,7 +12,7 @@ namespace Ryujinx.Ui.Helper { private const string LibObjCImport = "/usr/lib/libobjc.A.dylib"; - private struct Selector + private readonly struct Selector { public readonly IntPtr NativePtr; @@ -29,7 +29,7 @@ namespace Ryujinx.Ui.Helper NativePtr = sel_registerName(data); } - public static implicit operator Selector(string value) => new Selector(value); + public static implicit operator Selector(string value) => new(value); } private static unsafe IntPtr GetClass(string value) @@ -45,27 +45,27 @@ namespace Ryujinx.Ui.Helper return objc_getClass(data); } - private struct NSPoint + private struct NsPoint { public double X; public double Y; - public NSPoint(double x, double y) + public NsPoint(double x, double y) { X = x; Y = y; } } - private struct NSRect + private struct NsRect { - public NSPoint Pos; - public NSPoint Size; + public NsPoint Pos; + public NsPoint Size; - public NSRect(double x, double y, double width, double height) + public NsRect(double x, double y, double width, double height) { - Pos = new NSPoint(x, y); - Size = new NSPoint(width, height); + Pos = new NsPoint(x, y); + Size = new NsPoint(width, height); } } @@ -81,7 +81,7 @@ namespace Ryujinx.Ui.Helper // Create a child NSView to render into. IntPtr nsViewClass = GetClass("NSView"); IntPtr child = IntPtr_objc_msgSend(nsViewClass, "alloc"); - objc_msgSend(child, "init", new NSRect()); + objc_msgSend(child, "init", new NsRect()); // Add it as a child. objc_msgSend(nsView, "addSubview:", child); @@ -92,11 +92,12 @@ namespace Ryujinx.Ui.Helper objc_msgSend(metalLayer, "setContentsScale:", (double)display.GetMonitorAtWindow(window).ScaleFactor); // Set the frame position/location. - updateBounds = (Window window) => { + updateBounds = (Window window) => + { window.GetPosition(out int x, out int y); int width = window.Width; int height = window.Height; - objc_msgSend(child, "setFrame:", new NSRect(x, y, width, height)); + objc_msgSend(child, "setFrame:", new NsRect(x, y, width, height)); }; updateBounds(window); @@ -120,7 +121,7 @@ namespace Ryujinx.Ui.Helper private static partial void objc_msgSend(IntPtr receiver, Selector selector, IntPtr value); [LibraryImport(LibObjCImport)] - private static partial void objc_msgSend(IntPtr receiver, Selector selector, NSRect point); + private static partial void objc_msgSend(IntPtr receiver, Selector selector, NsRect point); [LibraryImport(LibObjCImport)] private static partial void objc_msgSend(IntPtr receiver, Selector selector, double value); @@ -131,4 +132,4 @@ namespace Ryujinx.Ui.Helper [LibraryImport("libgdk-3.0.dylib")] private static partial IntPtr gdk_quartz_window_get_nsview(IntPtr gdkWindow); } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Ui/Helper/ThemeHelper.cs b/src/Ryujinx/Ui/Helper/ThemeHelper.cs index 448afcc96..5289ebc5f 100644 --- a/src/Ryujinx/Ui/Helper/ThemeHelper.cs +++ b/src/Ryujinx/Ui/Helper/ThemeHelper.cs @@ -16,7 +16,7 @@ namespace Ryujinx.Ui.Helper if (File.Exists(ConfigurationState.Instance.Ui.CustomThemePath) && (Path.GetExtension(ConfigurationState.Instance.Ui.CustomThemePath) == ".css")) { - CssProvider cssProvider = new CssProvider(); + CssProvider cssProvider = new(); cssProvider.LoadFromPath(ConfigurationState.Instance.Ui.CustomThemePath); @@ -26,10 +26,10 @@ namespace Ryujinx.Ui.Helper { Logger.Warning?.Print(LogClass.Application, $"The \"custom_theme_path\" section in \"Config.json\" contains an invalid path: \"{ConfigurationState.Instance.Ui.CustomThemePath}\"."); - ConfigurationState.Instance.Ui.CustomThemePath.Value = ""; + ConfigurationState.Instance.Ui.CustomThemePath.Value = ""; ConfigurationState.Instance.Ui.EnableCustomTheme.Value = false; ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath); } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Ui/MainWindow.cs b/src/Ryujinx/Ui/MainWindow.cs index 628bcff4f..7625e9e6f 100644 --- a/src/Ryujinx/Ui/MainWindow.cs +++ b/src/Ryujinx/Ui/MainWindow.cs @@ -18,8 +18,6 @@ using Ryujinx.Common.SystemInterop; using Ryujinx.Cpu; using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.GAL.Multithreading; -using Ryujinx.Graphics.OpenGL; -using Ryujinx.Graphics.Vulkan; using Ryujinx.HLE.FileSystem; using Ryujinx.HLE.HOS; using Ryujinx.HLE.HOS.Services.Account.Acc; @@ -51,9 +49,9 @@ namespace Ryujinx.Ui { public class MainWindow : Window { - private readonly VirtualFileSystem _virtualFileSystem; - private readonly ContentManager _contentManager; - private readonly AccountManager _accountManager; + private readonly VirtualFileSystem _virtualFileSystem; + private readonly ContentManager _contentManager; + private readonly AccountManager _accountManager; private readonly LibHacHorizonManager _libHacHorizonManager; private UserChannelPersistence _userChannelPersistence; @@ -63,9 +61,9 @@ namespace Ryujinx.Ui private WindowsMultimediaTimerResolution _windowsMultimediaTimerResolution; private readonly ApplicationLibrary _applicationLibrary; - private readonly GtkHostUiHandler _uiHandler; - private readonly AutoResetEvent _deviceExitStatus; - private readonly ListStore _tableStore; + private readonly GtkHostUiHandler _uiHandler; + private readonly AutoResetEvent _deviceExitStatus; + private readonly ListStore _tableStore; private bool _updatingGameTable; private bool _gameLoaded; @@ -74,76 +72,76 @@ namespace Ryujinx.Ui private string _currentEmulatedGamePath = null; private string _lastScannedAmiiboId = ""; - private bool _lastScannedAmiiboShowAll = false; + private bool _lastScannedAmiiboShowAll = false; public RendererWidgetBase RendererWidget; public InputManager InputManager; public bool IsFocused; -#pragma warning disable CS0169, CS0649, IDE0044 +#pragma warning disable CS0169, CS0649, IDE0044, IDE0051 // Field is never assigned to, Add readonly modifier, Remove unused private member [GUI] public MenuItem ExitMenuItem; [GUI] public MenuItem UpdateMenuItem; - [GUI] MenuBar _menuBar; - [GUI] Box _footerBox; - [GUI] Box _statusBar; - [GUI] MenuItem _optionMenu; - [GUI] MenuItem _manageUserProfiles; - [GUI] MenuItem _fileMenu; - [GUI] MenuItem _loadApplicationFile; - [GUI] MenuItem _loadApplicationFolder; - [GUI] MenuItem _appletMenu; - [GUI] MenuItem _actionMenu; - [GUI] MenuItem _pauseEmulation; - [GUI] MenuItem _resumeEmulation; - [GUI] MenuItem _stopEmulation; - [GUI] MenuItem _simulateWakeUpMessage; - [GUI] MenuItem _scanAmiibo; - [GUI] MenuItem _takeScreenshot; - [GUI] MenuItem _hideUi; - [GUI] MenuItem _fullScreen; - [GUI] CheckMenuItem _startFullScreen; - [GUI] CheckMenuItem _showConsole; - [GUI] CheckMenuItem _favToggle; - [GUI] MenuItem _firmwareInstallDirectory; - [GUI] MenuItem _firmwareInstallFile; - [GUI] MenuItem _fileTypesSubMenu; - [GUI] Label _fifoStatus; - [GUI] CheckMenuItem _iconToggle; - [GUI] CheckMenuItem _developerToggle; - [GUI] CheckMenuItem _appToggle; - [GUI] CheckMenuItem _timePlayedToggle; - [GUI] CheckMenuItem _versionToggle; - [GUI] CheckMenuItem _lastPlayedToggle; - [GUI] CheckMenuItem _fileExtToggle; - [GUI] CheckMenuItem _pathToggle; - [GUI] CheckMenuItem _fileSizeToggle; - [GUI] CheckMenuItem _nspShown; - [GUI] CheckMenuItem _pfs0Shown; - [GUI] CheckMenuItem _xciShown; - [GUI] CheckMenuItem _ncaShown; - [GUI] CheckMenuItem _nroShown; - [GUI] CheckMenuItem _nsoShown; - [GUI] Label _gpuBackend; - [GUI] Label _dockedMode; - [GUI] Label _aspectRatio; - [GUI] Label _gameStatus; - [GUI] TreeView _gameTable; - [GUI] TreeSelection _gameTableSelection; - [GUI] ScrolledWindow _gameTableWindow; - [GUI] Label _gpuName; - [GUI] Label _progressLabel; - [GUI] Label _firmwareVersionLabel; + [GUI] MenuBar _menuBar; + [GUI] Box _footerBox; + [GUI] Box _statusBar; + [GUI] MenuItem _optionMenu; + [GUI] MenuItem _manageUserProfiles; + [GUI] MenuItem _fileMenu; + [GUI] MenuItem _loadApplicationFile; + [GUI] MenuItem _loadApplicationFolder; + [GUI] MenuItem _appletMenu; + [GUI] MenuItem _actionMenu; + [GUI] MenuItem _pauseEmulation; + [GUI] MenuItem _resumeEmulation; + [GUI] MenuItem _stopEmulation; + [GUI] MenuItem _simulateWakeUpMessage; + [GUI] MenuItem _scanAmiibo; + [GUI] MenuItem _takeScreenshot; + [GUI] MenuItem _hideUi; + [GUI] MenuItem _fullScreen; + [GUI] CheckMenuItem _startFullScreen; + [GUI] CheckMenuItem _showConsole; + [GUI] CheckMenuItem _favToggle; + [GUI] MenuItem _firmwareInstallDirectory; + [GUI] MenuItem _firmwareInstallFile; + [GUI] MenuItem _fileTypesSubMenu; + [GUI] Label _fifoStatus; + [GUI] CheckMenuItem _iconToggle; + [GUI] CheckMenuItem _developerToggle; + [GUI] CheckMenuItem _appToggle; + [GUI] CheckMenuItem _timePlayedToggle; + [GUI] CheckMenuItem _versionToggle; + [GUI] CheckMenuItem _lastPlayedToggle; + [GUI] CheckMenuItem _fileExtToggle; + [GUI] CheckMenuItem _pathToggle; + [GUI] CheckMenuItem _fileSizeToggle; + [GUI] CheckMenuItem _nspShown; + [GUI] CheckMenuItem _pfs0Shown; + [GUI] CheckMenuItem _xciShown; + [GUI] CheckMenuItem _ncaShown; + [GUI] CheckMenuItem _nroShown; + [GUI] CheckMenuItem _nsoShown; + [GUI] Label _gpuBackend; + [GUI] Label _dockedMode; + [GUI] Label _aspectRatio; + [GUI] Label _gameStatus; + [GUI] TreeView _gameTable; + [GUI] TreeSelection _gameTableSelection; + [GUI] ScrolledWindow _gameTableWindow; + [GUI] Label _gpuName; + [GUI] Label _progressLabel; + [GUI] Label _firmwareVersionLabel; [GUI] Gtk.ProgressBar _progressBar; - [GUI] Box _viewBox; - [GUI] Label _vSyncStatus; - [GUI] Label _volumeStatus; - [GUI] Box _listStatusBox; - [GUI] Label _loadingStatusLabel; + [GUI] Box _viewBox; + [GUI] Label _vSyncStatus; + [GUI] Label _volumeStatus; + [GUI] Box _listStatusBox; + [GUI] Label _loadingStatusLabel; [GUI] Gtk.ProgressBar _loadingStatusBar; -#pragma warning restore CS0649, IDE0044, CS0169 +#pragma warning restore CS0649, IDE0044, CS0169, IDE0051 public MainWindow() : this(new Builder("Ryujinx.Ui.MainWindow.glade")) { } @@ -156,14 +154,14 @@ namespace Ryujinx.Ui SetWindowSizePosition(); - Icon = new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Logo_Ryujinx.png"); + Icon = new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Logo_Ryujinx.png"); Title = $"Ryujinx {Program.Version}"; // Hide emulation context status bar. _statusBar.Hide(); // Instantiate HLE objects. - _virtualFileSystem = VirtualFileSystem.CreateInstance(); + _virtualFileSystem = VirtualFileSystem.CreateInstance(); _libHacHorizonManager = new LibHacHorizonManager(); _libHacHorizonManager.InitializeFsServer(_virtualFileSystem); @@ -178,36 +176,36 @@ namespace Ryujinx.Ui // Consider removing this at some point in the future when we don't need to worry about old saves. VirtualFileSystem.FixExtraData(_libHacHorizonManager.RyujinxClient); - _contentManager = new ContentManager(_virtualFileSystem); - _accountManager = new AccountManager(_libHacHorizonManager.RyujinxClient, CommandLineState.Profile); + _contentManager = new ContentManager(_virtualFileSystem); + _accountManager = new AccountManager(_libHacHorizonManager.RyujinxClient, CommandLineState.Profile); _userChannelPersistence = new UserChannelPersistence(); // Instantiate GUI objects. _applicationLibrary = new ApplicationLibrary(_virtualFileSystem); - _uiHandler = new GtkHostUiHandler(this); - _deviceExitStatus = new AutoResetEvent(false); + _uiHandler = new GtkHostUiHandler(this); + _deviceExitStatus = new AutoResetEvent(false); WindowStateEvent += WindowStateEvent_Changed; - DeleteEvent += Window_Close; - FocusInEvent += MainWindow_FocusInEvent; - FocusOutEvent += MainWindow_FocusOutEvent; + DeleteEvent += Window_Close; + FocusInEvent += MainWindow_FocusInEvent; + FocusOutEvent += MainWindow_FocusOutEvent; - _applicationLibrary.ApplicationAdded += Application_Added; + _applicationLibrary.ApplicationAdded += Application_Added; _applicationLibrary.ApplicationCountUpdated += ApplicationCount_Updated; - _fileMenu.StateChanged += FileMenu_StateChanged; + _fileMenu.StateChanged += FileMenu_StateChanged; _actionMenu.StateChanged += ActionMenu_StateChanged; _optionMenu.StateChanged += OptionMenu_StateChanged; _gameTable.ButtonReleaseEvent += Row_Clicked; - _fullScreen.Activated += FullScreen_Toggled; + _fullScreen.Activated += FullScreen_Toggled; RendererWidgetBase.StatusUpdatedEvent += Update_StatusBar; ConfigurationState.Instance.System.IgnoreMissingServices.Event += UpdateIgnoreMissingServicesState; - ConfigurationState.Instance.Graphics.AspectRatio.Event += UpdateAspectRatioState; - ConfigurationState.Instance.System.EnableDockedMode.Event += UpdateDockedModeState; - ConfigurationState.Instance.System.AudioVolume.Event += UpdateAudioVolumeState; + ConfigurationState.Instance.Graphics.AspectRatio.Event += UpdateAspectRatioState; + ConfigurationState.Instance.System.EnableDockedMode.Event += UpdateDockedModeState; + ConfigurationState.Instance.System.AudioVolume.Event += UpdateAudioVolumeState; if (ConfigurationState.Instance.Ui.StartFullscreen) { @@ -221,43 +219,73 @@ namespace Ryujinx.Ui _pauseEmulation.Sensitive = false; _resumeEmulation.Sensitive = false; - _nspShown.Active = ConfigurationState.Instance.Ui.ShownFileTypes.NSP.Value; + _nspShown.Active = ConfigurationState.Instance.Ui.ShownFileTypes.NSP.Value; _pfs0Shown.Active = ConfigurationState.Instance.Ui.ShownFileTypes.PFS0.Value; - _xciShown.Active = ConfigurationState.Instance.Ui.ShownFileTypes.XCI.Value; - _ncaShown.Active = ConfigurationState.Instance.Ui.ShownFileTypes.NCA.Value; - _nroShown.Active = ConfigurationState.Instance.Ui.ShownFileTypes.NRO.Value; - _nsoShown.Active = ConfigurationState.Instance.Ui.ShownFileTypes.NSO.Value; + _xciShown.Active = ConfigurationState.Instance.Ui.ShownFileTypes.XCI.Value; + _ncaShown.Active = ConfigurationState.Instance.Ui.ShownFileTypes.NCA.Value; + _nroShown.Active = ConfigurationState.Instance.Ui.ShownFileTypes.NRO.Value; + _nsoShown.Active = ConfigurationState.Instance.Ui.ShownFileTypes.NSO.Value; - _nspShown.Toggled += NSP_Shown_Toggled; + _nspShown.Toggled += NSP_Shown_Toggled; _pfs0Shown.Toggled += PFS0_Shown_Toggled; - _xciShown.Toggled += XCI_Shown_Toggled; - _ncaShown.Toggled += NCA_Shown_Toggled; - _nroShown.Toggled += NRO_Shown_Toggled; - _nsoShown.Toggled += NSO_Shown_Toggled; + _xciShown.Toggled += XCI_Shown_Toggled; + _ncaShown.Toggled += NCA_Shown_Toggled; + _nroShown.Toggled += NRO_Shown_Toggled; + _nsoShown.Toggled += NSO_Shown_Toggled; _fileTypesSubMenu.Visible = FileAssociationHelper.IsTypeAssociationSupported; - if (ConfigurationState.Instance.Ui.GuiColumns.FavColumn) _favToggle.Active = true; - if (ConfigurationState.Instance.Ui.GuiColumns.IconColumn) _iconToggle.Active = true; - if (ConfigurationState.Instance.Ui.GuiColumns.AppColumn) _appToggle.Active = true; - if (ConfigurationState.Instance.Ui.GuiColumns.DevColumn) _developerToggle.Active = true; - if (ConfigurationState.Instance.Ui.GuiColumns.VersionColumn) _versionToggle.Active = true; - if (ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn) _timePlayedToggle.Active = true; - if (ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn) _lastPlayedToggle.Active = true; - if (ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn) _fileExtToggle.Active = true; - if (ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn) _fileSizeToggle.Active = true; - if (ConfigurationState.Instance.Ui.GuiColumns.PathColumn) _pathToggle.Active = true; + if (ConfigurationState.Instance.Ui.GuiColumns.FavColumn) + { + _favToggle.Active = true; + } + if (ConfigurationState.Instance.Ui.GuiColumns.IconColumn) + { + _iconToggle.Active = true; + } + if (ConfigurationState.Instance.Ui.GuiColumns.AppColumn) + { + _appToggle.Active = true; + } + if (ConfigurationState.Instance.Ui.GuiColumns.DevColumn) + { + _developerToggle.Active = true; + } + if (ConfigurationState.Instance.Ui.GuiColumns.VersionColumn) + { + _versionToggle.Active = true; + } + if (ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn) + { + _timePlayedToggle.Active = true; + } + if (ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn) + { + _lastPlayedToggle.Active = true; + } + if (ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn) + { + _fileExtToggle.Active = true; + } + if (ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn) + { + _fileSizeToggle.Active = true; + } + if (ConfigurationState.Instance.Ui.GuiColumns.PathColumn) + { + _pathToggle.Active = true; + } - _favToggle.Toggled += Fav_Toggled; - _iconToggle.Toggled += Icon_Toggled; - _appToggle.Toggled += App_Toggled; - _developerToggle.Toggled += Developer_Toggled; - _versionToggle.Toggled += Version_Toggled; + _favToggle.Toggled += Fav_Toggled; + _iconToggle.Toggled += Icon_Toggled; + _appToggle.Toggled += App_Toggled; + _developerToggle.Toggled += Developer_Toggled; + _versionToggle.Toggled += Version_Toggled; _timePlayedToggle.Toggled += TimePlayed_Toggled; _lastPlayedToggle.Toggled += LastPlayed_Toggled; - _fileExtToggle.Toggled += FileExt_Toggled; - _fileSizeToggle.Toggled += FileSize_Toggled; - _pathToggle.Toggled += Path_Toggled; + _fileExtToggle.Toggled += FileExt_Toggled; + _fileSizeToggle.Toggled += FileSize_Toggled; + _pathToggle.Toggled += Path_Toggled; _gameTable.Model = _tableStore = new ListStore( typeof(bool), @@ -276,7 +304,7 @@ namespace Ryujinx.Ui _tableStore.SetSortFunc(6, SortHelper.LastPlayedSort); _tableStore.SetSortFunc(8, SortHelper.FileSizeSort); - int columnId = ConfigurationState.Instance.Ui.ColumnSort.SortColumnId; + int columnId = ConfigurationState.Instance.Ui.ColumnSort.SortColumnId; bool ascending = ConfigurationState.Instance.Ui.ColumnSort.SortAscending; _tableStore.SetSortColumnId(columnId, ascending ? SortType.Ascending : SortType.Descending); @@ -321,10 +349,7 @@ namespace Ryujinx.Ui private void UpdateDockedModeState(object sender, ReactiveEventArgs e) { - if (_emulationContext != null) - { - _emulationContext.System.ChangeDockedModeState(e.NewValue); - } + _emulationContext?.System.ChangeDockedModeState(e.NewValue); } private void UpdateAudioVolumeState(object sender, ReactiveEventArgs e) @@ -354,19 +379,49 @@ namespace Ryujinx.Ui _gameTable.RemoveColumn(column); } - CellRendererToggle favToggle = new CellRendererToggle(); + CellRendererToggle favToggle = new(); favToggle.Toggled += FavToggle_Toggled; - if (ConfigurationState.Instance.Ui.GuiColumns.FavColumn) _gameTable.AppendColumn("Fav", favToggle, "active", 0); - if (ConfigurationState.Instance.Ui.GuiColumns.IconColumn) _gameTable.AppendColumn("Icon", new CellRendererPixbuf(), "pixbuf", 1); - if (ConfigurationState.Instance.Ui.GuiColumns.AppColumn) _gameTable.AppendColumn("Application", new CellRendererText(), "text", 2); - if (ConfigurationState.Instance.Ui.GuiColumns.DevColumn) _gameTable.AppendColumn("Developer", new CellRendererText(), "text", 3); - if (ConfigurationState.Instance.Ui.GuiColumns.VersionColumn) _gameTable.AppendColumn("Version", new CellRendererText(), "text", 4); - if (ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn) _gameTable.AppendColumn("Time Played", new CellRendererText(), "text", 5); - if (ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn) _gameTable.AppendColumn("Last Played", new CellRendererText(), "text", 6); - if (ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn) _gameTable.AppendColumn("File Ext", new CellRendererText(), "text", 7); - if (ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn) _gameTable.AppendColumn("File Size", new CellRendererText(), "text", 8); - if (ConfigurationState.Instance.Ui.GuiColumns.PathColumn) _gameTable.AppendColumn("Path", new CellRendererText(), "text", 9); + if (ConfigurationState.Instance.Ui.GuiColumns.FavColumn) + { + _gameTable.AppendColumn("Fav", favToggle, "active", 0); + } + if (ConfigurationState.Instance.Ui.GuiColumns.IconColumn) + { + _gameTable.AppendColumn("Icon", new CellRendererPixbuf(), "pixbuf", 1); + } + if (ConfigurationState.Instance.Ui.GuiColumns.AppColumn) + { + _gameTable.AppendColumn("Application", new CellRendererText(), "text", 2); + } + if (ConfigurationState.Instance.Ui.GuiColumns.DevColumn) + { + _gameTable.AppendColumn("Developer", new CellRendererText(), "text", 3); + } + if (ConfigurationState.Instance.Ui.GuiColumns.VersionColumn) + { + _gameTable.AppendColumn("Version", new CellRendererText(), "text", 4); + } + if (ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn) + { + _gameTable.AppendColumn("Time Played", new CellRendererText(), "text", 5); + } + if (ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn) + { + _gameTable.AppendColumn("Last Played", new CellRendererText(), "text", 6); + } + if (ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn) + { + _gameTable.AppendColumn("File Ext", new CellRendererText(), "text", 7); + } + if (ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn) + { + _gameTable.AppendColumn("File Size", new CellRendererText(), "text", 8); + } + if (ConfigurationState.Instance.Ui.GuiColumns.PathColumn) + { + _gameTable.AppendColumn("Path", new CellRendererText(), "text", 9); + } foreach (TreeViewColumn column in _gameTable.Columns) { @@ -426,11 +481,11 @@ namespace Ryujinx.Ui if (ConfigurationState.Instance.Graphics.GraphicsBackend == GraphicsBackend.Vulkan) { string preferredGpu = ConfigurationState.Instance.Graphics.PreferredGpu.Value; - renderer = new VulkanRenderer(Vk.GetApi(), CreateVulkanSurface, VulkanHelper.GetRequiredInstanceExtensions, preferredGpu); + renderer = new Graphics.Vulkan.VulkanRenderer(Vk.GetApi(), CreateVulkanSurface, VulkanHelper.GetRequiredInstanceExtensions, preferredGpu); } else { - renderer = new OpenGLRenderer(); + renderer = new Graphics.OpenGL.OpenGLRenderer(); } BackendThreading threadingMode = ConfigurationState.Instance.Graphics.BackendThreading; @@ -570,38 +625,38 @@ namespace Ryujinx.Ui IntegrityCheckLevel fsIntegrityCheckLevel = ConfigurationState.Instance.System.EnableFsIntegrityChecks ? IntegrityCheckLevel.ErrorOnInvalid : IntegrityCheckLevel.None; - HLE.HLEConfiguration configuration = new HLE.HLEConfiguration(_virtualFileSystem, - _libHacHorizonManager, - _contentManager, - _accountManager, - _userChannelPersistence, - renderer, - deviceDriver, - memoryConfiguration, - _uiHandler, - (SystemLanguage)ConfigurationState.Instance.System.Language.Value, - (RegionCode)ConfigurationState.Instance.System.Region.Value, - ConfigurationState.Instance.Graphics.EnableVsync, - ConfigurationState.Instance.System.EnableDockedMode, - ConfigurationState.Instance.System.EnablePtc, - ConfigurationState.Instance.System.EnableInternetAccess, - fsIntegrityCheckLevel, - ConfigurationState.Instance.System.FsGlobalAccessLogMode, - ConfigurationState.Instance.System.SystemTimeOffset, - ConfigurationState.Instance.System.TimeZone, - ConfigurationState.Instance.System.MemoryManagerMode, - ConfigurationState.Instance.System.IgnoreMissingServices, - ConfigurationState.Instance.Graphics.AspectRatio, - ConfigurationState.Instance.System.AudioVolume, - ConfigurationState.Instance.System.UseHypervisor, - ConfigurationState.Instance.Multiplayer.LanInterfaceId.Value); + HLE.HLEConfiguration configuration = new(_virtualFileSystem, + _libHacHorizonManager, + _contentManager, + _accountManager, + _userChannelPersistence, + renderer, + deviceDriver, + memoryConfiguration, + _uiHandler, + (SystemLanguage)ConfigurationState.Instance.System.Language.Value, + (RegionCode)ConfigurationState.Instance.System.Region.Value, + ConfigurationState.Instance.Graphics.EnableVsync, + ConfigurationState.Instance.System.EnableDockedMode, + ConfigurationState.Instance.System.EnablePtc, + ConfigurationState.Instance.System.EnableInternetAccess, + fsIntegrityCheckLevel, + ConfigurationState.Instance.System.FsGlobalAccessLogMode, + ConfigurationState.Instance.System.SystemTimeOffset, + ConfigurationState.Instance.System.TimeZone, + ConfigurationState.Instance.System.MemoryManagerMode, + ConfigurationState.Instance.System.IgnoreMissingServices, + ConfigurationState.Instance.Graphics.AspectRatio, + ConfigurationState.Instance.System.AudioVolume, + ConfigurationState.Instance.System.UseHypervisor, + ConfigurationState.Instance.Multiplayer.LanInterfaceId.Value); _emulationContext = new HLE.Switch(configuration); } private SurfaceKHR CreateVulkanSurface(Instance instance, Vk vk) { - return new SurfaceKHR((ulong)((VKRenderer)RendererWidget).CreateWindowSurface(instance.Handle)); + return new SurfaceKHR((ulong)((VulkanRenderer)RendererWidget).CreateWindowSurface(instance.Handle)); } private void SetupProgressUiHandlers() @@ -655,14 +710,16 @@ namespace Ryujinx.Ui _tableStore.Clear(); - Thread applicationLibraryThread = new Thread(() => + Thread applicationLibraryThread = new(() => { _applicationLibrary.LoadApplications(ConfigurationState.Instance.Ui.GameDirs, ConfigurationState.Instance.System.Language); _updatingGameTable = false; - }); - applicationLibraryThread.Name = "GUI.ApplicationLibraryThread"; - applicationLibraryThread.IsBackground = true; + }) + { + Name = "GUI.ApplicationLibraryThread", + IsBackground = true, + }; applicationLibraryThread.Start(); } @@ -671,11 +728,11 @@ namespace Ryujinx.Ui { if (ConfigurationState.Instance.Logger.EnableTrace.Value) { - MessageDialog debugWarningDialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, null) + MessageDialog debugWarningDialog = new(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, null) { - Title = "Ryujinx - Warning", - Text = "You have trace logging enabled, which is designed to be used by developers only.", - SecondaryText = "For optimal performance, it's recommended to disable trace logging. Would you like to disable trace logging now?" + Title = "Ryujinx - Warning", + Text = "You have trace logging enabled, which is designed to be used by developers only.", + SecondaryText = "For optimal performance, it's recommended to disable trace logging. Would you like to disable trace logging now?", }; if (debugWarningDialog.Run() == (int)ResponseType.Yes) @@ -689,11 +746,11 @@ namespace Ryujinx.Ui if (!string.IsNullOrWhiteSpace(ConfigurationState.Instance.Graphics.ShadersDumpPath.Value)) { - MessageDialog shadersDumpWarningDialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, null) + MessageDialog shadersDumpWarningDialog = new(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, null) { - Title = "Ryujinx - Warning", - Text = "You have shader dumping enabled, which is designed to be used by developers only.", - SecondaryText = "For optimal performance, it's recommended to disable shader dumping. Would you like to disable shader dumping now?" + Title = "Ryujinx - Warning", + Text = "You have shader dumping enabled, which is designed to be used by developers only.", + SecondaryText = "For optimal performance, it's recommended to disable shader dumping. Would you like to disable shader dumping now?", }; if (shadersDumpWarningDialog.Run() == (int)ResponseType.Yes) @@ -857,18 +914,18 @@ namespace Ryujinx.Ui Thread windowThread = new(CreateGameWindow) { - Name = "GUI.WindowThread" + Name = "GUI.WindowThread", }; windowThread.Start(); - _gameLoaded = true; + _gameLoaded = true; _actionMenu.Sensitive = true; UpdateMenuItem.Sensitive = false; _lastScannedAmiiboId = ""; - _firmwareInstallFile.Sensitive = false; + _firmwareInstallFile.Sensitive = false; _firmwareInstallDirectory.Sensitive = false; DiscordIntegrationModule.SwitchToPlayingState(_emulationContext.Processes.ActiveApplication.ProgramIdText, @@ -885,11 +942,11 @@ namespace Ryujinx.Ui { if (ConfigurationState.Instance.Graphics.GraphicsBackend == GraphicsBackend.Vulkan) { - return new VKRenderer(InputManager, ConfigurationState.Instance.Logger.GraphicsDebugLevel); + return new VulkanRenderer(InputManager, ConfigurationState.Instance.Logger.GraphicsDebugLevel); } else { - return new GlRenderer(InputManager, ConfigurationState.Instance.Logger.GraphicsDebugLevel); + return new OpenGLRenderer(InputManager, ConfigurationState.Instance.Logger.GraphicsDebugLevel); } } @@ -1030,20 +1087,20 @@ namespace Ryujinx.Ui } } - public void UpdateGraphicsConfig() + public static void UpdateGraphicsConfig() { - int resScale = ConfigurationState.Instance.Graphics.ResScale; + int resScale = ConfigurationState.Instance.Graphics.ResScale; float resScaleCustom = ConfigurationState.Instance.Graphics.ResScaleCustom; - Graphics.Gpu.GraphicsConfig.ResScale = (resScale == -1) ? resScaleCustom : resScale; - Graphics.Gpu.GraphicsConfig.MaxAnisotropy = ConfigurationState.Instance.Graphics.MaxAnisotropy; - Graphics.Gpu.GraphicsConfig.ShadersDumpPath = ConfigurationState.Instance.Graphics.ShadersDumpPath; - Graphics.Gpu.GraphicsConfig.EnableShaderCache = ConfigurationState.Instance.Graphics.EnableShaderCache; + Graphics.Gpu.GraphicsConfig.ResScale = (resScale == -1) ? resScaleCustom : resScale; + Graphics.Gpu.GraphicsConfig.MaxAnisotropy = ConfigurationState.Instance.Graphics.MaxAnisotropy; + Graphics.Gpu.GraphicsConfig.ShadersDumpPath = ConfigurationState.Instance.Graphics.ShadersDumpPath; + Graphics.Gpu.GraphicsConfig.EnableShaderCache = ConfigurationState.Instance.Graphics.EnableShaderCache; Graphics.Gpu.GraphicsConfig.EnableTextureRecompression = ConfigurationState.Instance.Graphics.EnableTextureRecompression; - Graphics.Gpu.GraphicsConfig.EnableMacroHLE = ConfigurationState.Instance.Graphics.EnableMacroHLE; + Graphics.Gpu.GraphicsConfig.EnableMacroHLE = ConfigurationState.Instance.Graphics.EnableMacroHLE; } - public void SaveConfig() + public static void SaveConfig() { ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath); } @@ -1105,7 +1162,7 @@ namespace Ryujinx.Ui Application.Invoke(delegate { _progressLabel.Text = $"{args.NumAppsLoaded}/{args.NumAppsFound} Games Loaded"; - float barValue = 0; + float barValue = 0; if (args.NumAppsFound != 0) { @@ -1126,12 +1183,12 @@ namespace Ryujinx.Ui { Application.Invoke(delegate { - _gameStatus.Text = args.GameStatus; - _fifoStatus.Text = args.FifoStatus; - _gpuName.Text = args.GpuName; - _dockedMode.Text = args.DockedMode; - _aspectRatio.Text = args.AspectRatio; - _gpuBackend.Text = args.GpuBackend; + _gameStatus.Text = args.GameStatus; + _fifoStatus.Text = args.FifoStatus; + _gpuName.Text = args.GpuName; + _dockedMode.Text = args.DockedMode; + _aspectRatio.Text = args.AspectRatio; + _gpuBackend.Text = args.GpuBackend; _volumeStatus.Text = GetVolumeLabelText(args.Volume); if (args.VSyncEnabled) @@ -1151,8 +1208,8 @@ namespace Ryujinx.Ui { _tableStore.GetIter(out TreeIter treeIter, new TreePath(args.Path)); - string titleId = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[1].ToLower(); - bool newToggleValue = !(bool)_tableStore.GetValue(treeIter, 0); + string titleId = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[1].ToLower(); + bool newToggleValue = !(bool)_tableStore.GetValue(treeIter, 0); _tableStore.SetValue(treeIter, 0, newToggleValue); @@ -1166,7 +1223,7 @@ namespace Ryujinx.Ui { TreeViewColumn column = (TreeViewColumn)sender; - ConfigurationState.Instance.Ui.ColumnSort.SortColumnId.Value = column.SortColumnId; + ConfigurationState.Instance.Ui.ColumnSort.SortColumnId.Value = column.SortColumnId; ConfigurationState.Instance.Ui.ColumnSort.SortAscending.Value = column.SortOrder == SortType.Ascending; SaveConfig(); @@ -1193,7 +1250,7 @@ namespace Ryujinx.Ui ConfigurationState.Instance.System.EnableDockedMode.Value = !ConfigurationState.Instance.System.EnableDockedMode.Value; } - private string GetVolumeLabelText(float volume) + private static string GetVolumeLabelText(float volume) { string icon = volume == 0 ? "🔇" : "🔊"; @@ -1237,8 +1294,8 @@ namespace Ryujinx.Ui } string titleFilePath = _tableStore.GetValue(treeIter, 9).ToString(); - string titleName = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[0]; - string titleId = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[1].ToLower(); + string titleName = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[0]; + string titleId = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[1].ToLower(); BlitStruct controlData = (BlitStruct)_tableStore.GetValue(treeIter, 10); @@ -1247,43 +1304,41 @@ namespace Ryujinx.Ui private void Load_Application_File(object sender, EventArgs args) { - using (FileChooserNative fileChooser = new FileChooserNative("Choose the file to open", this, FileChooserAction.Open, "Open", "Cancel")) + using FileChooserNative fileChooser = new("Choose the file to open", this, FileChooserAction.Open, "Open", "Cancel"); + + FileFilter filter = new() { - FileFilter filter = new FileFilter() - { - Name = "Switch Executables" - }; - filter.AddPattern("*.xci"); - filter.AddPattern("*.nsp"); - filter.AddPattern("*.pfs0"); - filter.AddPattern("*.nca"); - filter.AddPattern("*.nro"); - filter.AddPattern("*.nso"); + Name = "Switch Executables", + }; + filter.AddPattern("*.xci"); + filter.AddPattern("*.nsp"); + filter.AddPattern("*.pfs0"); + filter.AddPattern("*.nca"); + filter.AddPattern("*.nro"); + filter.AddPattern("*.nso"); - fileChooser.AddFilter(filter); + fileChooser.AddFilter(filter); - if (fileChooser.Run() == (int)ResponseType.Accept) - { - RunApplication(fileChooser.Filename); - } + if (fileChooser.Run() == (int)ResponseType.Accept) + { + RunApplication(fileChooser.Filename); } } private void Load_Application_Folder(object sender, EventArgs args) { - using (FileChooserNative fileChooser = new FileChooserNative("Choose the folder to open", this, FileChooserAction.SelectFolder, "Open", "Cancel")) + using FileChooserNative fileChooser = new("Choose the folder to open", this, FileChooserAction.SelectFolder, "Open", "Cancel"); + + if (fileChooser.Run() == (int)ResponseType.Accept) { - if (fileChooser.Run() == (int)ResponseType.Accept) - { - RunApplication(fileChooser.Filename); - } + RunApplication(fileChooser.Filename); } } private void FileMenu_StateChanged(object o, StateChangedArgs args) { - _appletMenu.Sensitive = _emulationContext == null && _contentManager.GetCurrentFirmwareVersion() != null && _contentManager.GetCurrentFirmwareVersion().Major > 3; - _loadApplicationFile.Sensitive = _emulationContext == null; + _appletMenu.Sensitive = _emulationContext == null && _contentManager.GetCurrentFirmwareVersion() != null && _contentManager.GetCurrentFirmwareVersion().Major > 3; + _loadApplicationFile.Sensitive = _emulationContext == null; _loadApplicationFolder.Sensitive = _emulationContext == null; } @@ -1332,7 +1387,7 @@ namespace Ryujinx.Ui private void SetWindowSizePosition() { - DefaultWidth = ConfigurationState.Instance.Ui.WindowStartup.WindowSizeWidth; + DefaultWidth = ConfigurationState.Instance.Ui.WindowStartup.WindowSizeWidth; DefaultHeight = ConfigurationState.Instance.Ui.WindowStartup.WindowSizeHeight; Move(ConfigurationState.Instance.Ui.WindowStartup.WindowPositionX, ConfigurationState.Instance.Ui.WindowStartup.WindowPositionY); @@ -1399,11 +1454,11 @@ namespace Ryujinx.Ui private void Installer_File_Pressed(object o, EventArgs args) { - FileChooserNative fileChooser = new FileChooserNative("Choose the firmware file to open", this, FileChooserAction.Open, "Open", "Cancel"); + FileChooserNative fileChooser = new("Choose the firmware file to open", this, FileChooserAction.Open, "Open", "Cancel"); - FileFilter filter = new FileFilter + FileFilter filter = new() { - Name = "Switch Firmware Files" + Name = "Switch Firmware Files", }; filter.AddPattern("*.zip"); filter.AddPattern("*.xci"); @@ -1415,7 +1470,7 @@ namespace Ryujinx.Ui private void Installer_Directory_Pressed(object o, EventArgs args) { - FileChooserNative directoryChooser = new FileChooserNative("Choose the firmware directory to open", this, FileChooserAction.SelectFolder, "Open", "Cancel"); + FileChooserNative directoryChooser = new("Choose the firmware directory to open", this, FileChooserAction.SelectFolder, "Open", "Cancel"); HandleInstallerDialog(directoryChooser); } @@ -1460,7 +1515,7 @@ namespace Ryujinx.Ui { Logger.Info?.Print(LogClass.Application, $"Installing firmware {firmwareVersion.VersionString}"); - Thread thread = new Thread(() => + Thread thread = new(() => { Application.Invoke(delegate { @@ -1483,7 +1538,7 @@ namespace Ryujinx.Ui // Purge Applet Cache. - DirectoryInfo miiEditorCacheFolder = new DirectoryInfo(System.IO.Path.Combine(AppDataManager.GamesDirPath, "0100000000001009", "cache")); + DirectoryInfo miiEditorCacheFolder = new(System.IO.Path.Combine(AppDataManager.GamesDirPath, "0100000000001009", "cache")); if (miiEditorCacheFolder.Exists) { @@ -1504,9 +1559,10 @@ namespace Ryujinx.Ui { RefreshFirmwareLabel(); } - }); - - thread.Name = "GUI.FirmwareInstallerThread"; + }) + { + Name = "GUI.FirmwareInstallerThread", + }; thread.Start(); } } @@ -1571,7 +1627,7 @@ namespace Ryujinx.Ui else { // otherwise, clear state. - _userChannelPersistence = new UserChannelPersistence(); + _userChannelPersistence = new UserChannelPersistence(); _currentEmulatedGamePath = null; _actionMenu.Sensitive = false; _firmwareInstallFile.Sensitive = true; @@ -1616,7 +1672,7 @@ namespace Ryujinx.Ui private void Settings_Pressed(object sender, EventArgs args) { - SettingsWindow settingsWindow = new SettingsWindow(this, _virtualFileSystem, _contentManager); + SettingsWindow settingsWindow = new(this, _virtualFileSystem, _contentManager); settingsWindow.SetSizeRequest((int)(settingsWindow.DefaultWidth * Program.WindowScaleFactor), (int)(settingsWindow.DefaultHeight * Program.WindowScaleFactor)); settingsWindow.Show(); @@ -1648,7 +1704,7 @@ namespace Ryujinx.Ui private void ManageUserProfiles_Pressed(object sender, EventArgs args) { - UserProfilesManagerWindow userProfilesManagerWindow = new UserProfilesManagerWindow(_accountManager, _contentManager, _virtualFileSystem); + UserProfilesManagerWindow userProfilesManagerWindow = new(_accountManager, _contentManager, _virtualFileSystem); userProfilesManagerWindow.SetSizeRequest((int)(userProfilesManagerWindow.DefaultWidth * Program.WindowScaleFactor), (int)(userProfilesManagerWindow.DefaultHeight * Program.WindowScaleFactor)); userProfilesManagerWindow.Show(); @@ -1656,15 +1712,12 @@ namespace Ryujinx.Ui private void Simulate_WakeUp_Message_Pressed(object sender, EventArgs args) { - if (_emulationContext != null) - { - _emulationContext.System.SimulateWakeUpMessage(); - } + _emulationContext?.System.SimulateWakeUpMessage(); } private void ActionMenu_StateChanged(object o, StateChangedArgs args) { - _scanAmiibo.Sensitive = _emulationContext != null && _emulationContext.System.SearchingForAmiibo(out int _); + _scanAmiibo.Sensitive = _emulationContext != null && _emulationContext.System.SearchingForAmiibo(out int _); _takeScreenshot.Sensitive = _emulationContext != null; } @@ -1672,12 +1725,12 @@ namespace Ryujinx.Ui { if (_emulationContext.System.SearchingForAmiibo(out int deviceId)) { - AmiiboWindow amiiboWindow = new AmiiboWindow + AmiiboWindow amiiboWindow = new() { LastScannedAmiiboShowAll = _lastScannedAmiiboShowAll, - LastScannedAmiiboId = _lastScannedAmiiboId, - DeviceId = deviceId, - TitleId = _emulationContext.Processes.ActiveApplication.ProgramIdText.ToUpper() + LastScannedAmiiboId = _lastScannedAmiiboId, + DeviceId = deviceId, + TitleId = _emulationContext.Processes.ActiveApplication.ProgramIdText.ToUpper(), }; amiiboWindow.DeleteEvent += AmiiboWindow_DeleteEvent; @@ -1702,7 +1755,7 @@ namespace Ryujinx.Ui { if (((AmiiboWindow)sender).AmiiboId != "" && ((AmiiboWindow)sender).Response == ResponseType.Ok) { - _lastScannedAmiiboId = ((AmiiboWindow)sender).AmiiboId; + _lastScannedAmiiboId = ((AmiiboWindow)sender).AmiiboId; _lastScannedAmiiboShowAll = ((AmiiboWindow)sender).LastScannedAmiiboShowAll; _emulationContext.System.ScanAmiibo(((AmiiboWindow)sender).DeviceId, ((AmiiboWindow)sender).AmiiboId, ((AmiiboWindow)sender).UseRandomUuid); @@ -1722,7 +1775,7 @@ namespace Ryujinx.Ui private void About_Pressed(object sender, EventArgs args) { - AboutWindow aboutWindow = new AboutWindow(); + AboutWindow aboutWindow = new(); aboutWindow.SetSizeRequest((int)(aboutWindow.DefaultWidth * Program.WindowScaleFactor), (int)(aboutWindow.DefaultHeight * Program.WindowScaleFactor)); aboutWindow.Show(); @@ -1824,7 +1877,7 @@ namespace Ryujinx.Ui UpdateGameTable(); } - private void XCI_Shown_Toggled (object sender, EventArgs args) + private void XCI_Shown_Toggled(object sender, EventArgs args) { ConfigurationState.Instance.Ui.ShownFileTypes.XCI.Value = _xciShown.Active; @@ -1832,7 +1885,7 @@ namespace Ryujinx.Ui UpdateGameTable(); } - private void NCA_Shown_Toggled (object sender, EventArgs args) + private void NCA_Shown_Toggled(object sender, EventArgs args) { ConfigurationState.Instance.Ui.ShownFileTypes.NCA.Value = _ncaShown.Active; @@ -1840,7 +1893,7 @@ namespace Ryujinx.Ui UpdateGameTable(); } - private void NRO_Shown_Toggled (object sender, EventArgs args) + private void NRO_Shown_Toggled(object sender, EventArgs args) { ConfigurationState.Instance.Ui.ShownFileTypes.NRO.Value = _nroShown.Active; @@ -1848,7 +1901,7 @@ namespace Ryujinx.Ui UpdateGameTable(); } - private void NSO_Shown_Toggled (object sender, EventArgs args) + private void NSO_Shown_Toggled(object sender, EventArgs args) { ConfigurationState.Instance.Ui.ShownFileTypes.NSO.Value = _nsoShown.Active; diff --git a/src/Ryujinx/Ui/GLRenderer.cs b/src/Ryujinx/Ui/OpenGLRenderer.cs similarity index 91% rename from src/Ryujinx/Ui/GLRenderer.cs rename to src/Ryujinx/Ui/OpenGLRenderer.cs index c56996910..2ca791fe8 100644 --- a/src/Ryujinx/Ui/GLRenderer.cs +++ b/src/Ryujinx/Ui/OpenGLRenderer.cs @@ -1,7 +1,6 @@ using OpenTK.Graphics.OpenGL; using Ryujinx.Common.Configuration; using Ryujinx.Common.Logging; -using Ryujinx.Graphics.OpenGL; using Ryujinx.Input.HLE; using SPB.Graphics; using SPB.Graphics.Exceptions; @@ -15,16 +14,16 @@ using System.Runtime.InteropServices; namespace Ryujinx.Ui { - public partial class GlRenderer : RendererWidgetBase + public partial class OpenGLRenderer : RendererWidgetBase { - private GraphicsDebugLevel _glLogLevel; + private readonly GraphicsDebugLevel _glLogLevel; private bool _initializedOpenGL; private OpenGLContextBase _openGLContext; private SwappableNativeWindowBase _nativeWindow; - public GlRenderer(InputManager inputManager, GraphicsDebugLevel glLogLevel) : base(inputManager, glLogLevel) + public OpenGLRenderer(InputManager inputManager, GraphicsDebugLevel glLogLevel) : base(inputManager, glLogLevel) { _glLogLevel = glLogLevel; } @@ -93,7 +92,7 @@ namespace Ryujinx.Ui public override void InitializeRenderer() { // First take exclusivity on the OpenGL context. - ((OpenGLRenderer)Renderer).InitializeBackgroundContext(SPBOpenGLContext.CreateBackgroundContext(_openGLContext)); + ((Graphics.OpenGL.OpenGLRenderer)Renderer).InitializeBackgroundContext(SPBOpenGLContext.CreateBackgroundContext(_openGLContext)); _openGLContext.MakeCurrent(_nativeWindow); @@ -140,4 +139,4 @@ namespace Ryujinx.Ui _openGLContext?.Dispose(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Ui/OpenToolkitBindingsContext.cs b/src/Ryujinx/Ui/OpenToolkitBindingsContext.cs index ec4111fa3..b35673ebb 100644 --- a/src/Ryujinx/Ui/OpenToolkitBindingsContext.cs +++ b/src/Ryujinx/Ui/OpenToolkitBindingsContext.cs @@ -5,7 +5,7 @@ namespace Ryujinx.Ui { public class OpenToolkitBindingsContext : OpenTK.IBindingsContext { - private IBindingsContext _bindingContext; + private readonly IBindingsContext _bindingContext; public OpenToolkitBindingsContext(IBindingsContext bindingsContext) { diff --git a/src/Ryujinx/Ui/RendererWidgetBase.cs b/src/Ryujinx/Ui/RendererWidgetBase.cs index 87ff7f6c0..0ee344434 100644 --- a/src/Ryujinx/Ui/RendererWidgetBase.cs +++ b/src/Ryujinx/Ui/RendererWidgetBase.cs @@ -21,14 +21,13 @@ using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; +using Image = SixLabors.ImageSharp.Image; +using Key = Ryujinx.Input.Key; +using ScalingFilter = Ryujinx.Graphics.GAL.ScalingFilter; +using Switch = Ryujinx.HLE.Switch; namespace Ryujinx.Ui { - using Image = SixLabors.ImageSharp.Image; - using Key = Input.Key; - using ScalingFilter = Graphics.GAL.ScalingFilter; - using Switch = HLE.Switch; - public abstract class RendererWidgetBase : DrawingArea { private const int SwitchPanelWidth = 1280; @@ -71,12 +70,12 @@ namespace Ryujinx.Ui // Hide Cursor const int CursorHideIdleTime = 5; // seconds - private static readonly Cursor _invisibleCursor = new Cursor(Display.Default, CursorType.BlankCursor); + private static readonly Cursor _invisibleCursor = new(Display.Default, CursorType.BlankCursor); private long _lastCursorMoveTime; private HideCursorMode _hideCursorMode; - private InputManager _inputManager; - private IKeyboard _keyboardInterface; - private GraphicsDebugLevel _glLogLevel; + private readonly InputManager _inputManager; + private readonly IKeyboard _keyboardInterface; + private readonly GraphicsDebugLevel _glLogLevel; private string _gpuBackendName; private string _gpuVendorName; private bool _isMouseInClient; @@ -165,7 +164,7 @@ namespace Ryujinx.Ui Window.Cursor = _invisibleCursor; break; default: - throw new ArgumentOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(state)); } }); } @@ -379,12 +378,12 @@ namespace Ryujinx.Ui { lock (this) { - var currentTime = DateTime.Now; - string filename = $"ryujinx_capture_{currentTime.Year}-{currentTime.Month:D2}-{currentTime.Day:D2}_{currentTime.Hour:D2}-{currentTime.Minute:D2}-{currentTime.Second:D2}.png"; - string directory = AppDataManager.Mode switch + var currentTime = DateTime.Now; + string filename = $"ryujinx_capture_{currentTime.Year}-{currentTime.Month:D2}-{currentTime.Day:D2}_{currentTime.Hour:D2}-{currentTime.Minute:D2}-{currentTime.Second:D2}.png"; + string directory = AppDataManager.Mode switch { AppDataManager.LaunchMode.Portable or AppDataManager.LaunchMode.Custom => System.IO.Path.Combine(AppDataManager.BaseDirPath, "screenshots"), - _ => System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "Ryujinx") + _ => System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "Ryujinx"), }; string path = System.IO.Path.Combine(directory, filename); @@ -415,7 +414,7 @@ namespace Ryujinx.Ui image.SaveAsPng(path, new PngEncoder() { - ColorType = PngColorType.Rgb + ColorType = PngColorType.Rgb, }); image.Dispose(); @@ -524,30 +523,30 @@ namespace Ryujinx.Ui { parent.Present(); - var activeProcess = Device.Processes.ActiveApplication; + var activeProcess = Device.Processes.ActiveApplication; - string titleNameSection = string.IsNullOrWhiteSpace(activeProcess.Name) ? string.Empty : $" {activeProcess.Name}"; + string titleNameSection = string.IsNullOrWhiteSpace(activeProcess.Name) ? string.Empty : $" {activeProcess.Name}"; string titleVersionSection = string.IsNullOrWhiteSpace(activeProcess.DisplayVersion) ? string.Empty : $" v{activeProcess.DisplayVersion}"; - string titleIdSection = $" ({activeProcess.ProgramIdText.ToUpper()})"; - string titleArchSection = activeProcess.Is64Bit ? " (64-bit)" : " (32-bit)"; + string titleIdSection = $" ({activeProcess.ProgramIdText.ToUpper()})"; + string titleArchSection = activeProcess.Is64Bit ? " (64-bit)" : " (32-bit)"; parent.Title = $"Ryujinx {Program.Version} -{titleNameSection}{titleVersionSection}{titleIdSection}{titleArchSection}"; }); - Thread renderLoopThread = new Thread(Render) + Thread renderLoopThread = new(Render) { - Name = "GUI.RenderLoop" + Name = "GUI.RenderLoop", }; renderLoopThread.Start(); - Thread nvStutterWorkaround = null; + Thread nvidiaStutterWorkaround = null; if (Renderer is Graphics.OpenGL.OpenGLRenderer) { - nvStutterWorkaround = new Thread(NVStutterWorkaround) + nvidiaStutterWorkaround = new Thread(NvidiaStutterWorkaround) { - Name = "GUI.NVStutterWorkaround" + Name = "GUI.NvidiaStutterWorkaround", }; - nvStutterWorkaround.Start(); + nvidiaStutterWorkaround.Start(); } MainLoop(); @@ -556,7 +555,7 @@ namespace Ryujinx.Ui // We only need to wait for all commands submitted during the main gpu loop to be processed. _gpuDoneEvent.WaitOne(); _gpuDoneEvent.Dispose(); - nvStutterWorkaround?.Join(); + nvidiaStutterWorkaround?.Join(); Exit(); } @@ -584,7 +583,7 @@ namespace Ryujinx.Ui } } - private void NVStutterWorkaround() + private void NvidiaStutterWorkaround() { while (_isActive) { @@ -752,7 +751,7 @@ namespace Ryujinx.Ui ResScaleUp = 1 << 5, ResScaleDown = 1 << 6, VolumeUp = 1 << 7, - VolumeDown = 1 << 8 + VolumeDown = 1 << 8, } private KeyboardHotkeyState GetHotkeyState() @@ -807,4 +806,4 @@ namespace Ryujinx.Ui return state; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Ui/SPBOpenGLContext.cs b/src/Ryujinx/Ui/SPBOpenGLContext.cs index 97644269b..b6195a9c6 100644 --- a/src/Ryujinx/Ui/SPBOpenGLContext.cs +++ b/src/Ryujinx/Ui/SPBOpenGLContext.cs @@ -9,8 +9,8 @@ namespace Ryujinx.Ui { class SPBOpenGLContext : IOpenGLContext { - private OpenGLContextBase _context; - private NativeWindowBase _window; + private readonly OpenGLContextBase _context; + private readonly NativeWindowBase _window; private SPBOpenGLContext(OpenGLContextBase context, NativeWindowBase window) { diff --git a/src/Ryujinx/Ui/StatusUpdatedEventArgs.cs b/src/Ryujinx/Ui/StatusUpdatedEventArgs.cs index 046597b07..949390caa 100644 --- a/src/Ryujinx/Ui/StatusUpdatedEventArgs.cs +++ b/src/Ryujinx/Ui/StatusUpdatedEventArgs.cs @@ -4,8 +4,8 @@ namespace Ryujinx.Ui { public class StatusUpdatedEventArgs : EventArgs { - public bool VSyncEnabled; - public float Volume; + public bool VSyncEnabled; + public float Volume; public string DockedMode; public string AspectRatio; public string GameStatus; @@ -16,13 +16,13 @@ namespace Ryujinx.Ui public StatusUpdatedEventArgs(bool vSyncEnabled, float volume, string gpuBackend, string dockedMode, string aspectRatio, string gameStatus, string fifoStatus, string gpuName) { VSyncEnabled = vSyncEnabled; - Volume = volume; - GpuBackend = gpuBackend; - DockedMode = dockedMode; - AspectRatio = aspectRatio; - GameStatus = gameStatus; - FifoStatus = fifoStatus; - GpuName = gpuName; + Volume = volume; + GpuBackend = gpuBackend; + DockedMode = dockedMode; + AspectRatio = aspectRatio; + GameStatus = gameStatus; + FifoStatus = fifoStatus; + GpuName = gpuName; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Ui/VKRenderer.cs b/src/Ryujinx/Ui/VulkanRenderer.cs similarity index 93% rename from src/Ryujinx/Ui/VKRenderer.cs rename to src/Ryujinx/Ui/VulkanRenderer.cs index d2106c58f..ecb3fa243 100644 --- a/src/Ryujinx/Ui/VKRenderer.cs +++ b/src/Ryujinx/Ui/VulkanRenderer.cs @@ -12,12 +12,12 @@ using System.Runtime.InteropServices; namespace Ryujinx.Ui { - public partial class VKRenderer : RendererWidgetBase + public partial class VulkanRenderer : RendererWidgetBase { public NativeWindowBase NativeWindow { get; private set; } private UpdateBoundsCallbackDelegate _updateBoundsCallback; - public VKRenderer(InputManager inputManager, GraphicsDebugLevel glLogLevel) : base(inputManager, glLogLevel) { } + public VulkanRenderer(InputManager inputManager, GraphicsDebugLevel glLogLevel) : base(inputManager, glLogLevel) { } private NativeWindowBase RetrieveNativeWindow() { diff --git a/src/Ryujinx/Ui/Widgets/GameTableContextMenu.Designer.cs b/src/Ryujinx/Ui/Widgets/GameTableContextMenu.Designer.cs index 5a0563d93..0f7b4f22b 100644 --- a/src/Ryujinx/Ui/Widgets/GameTableContextMenu.Designer.cs +++ b/src/Ryujinx/Ui/Widgets/GameTableContextMenu.Designer.cs @@ -12,12 +12,12 @@ namespace Ryujinx.Ui.Widgets private MenuItem _manageCheatMenuItem; private MenuItem _openTitleModDirMenuItem; private MenuItem _openTitleSdModDirMenuItem; - private Menu _extractSubMenu; + private Menu _extractSubMenu; private MenuItem _extractMenuItem; private MenuItem _extractRomFsMenuItem; private MenuItem _extractExeFsMenuItem; private MenuItem _extractLogoMenuItem; - private Menu _manageSubMenu; + private Menu _manageSubMenu; private MenuItem _manageCacheMenuItem; private MenuItem _purgePtcCacheMenuItem; private MenuItem _purgeShaderCacheMenuItem; @@ -31,7 +31,7 @@ namespace Ryujinx.Ui.Widgets // _openSaveUserDirMenuItem = new MenuItem("Open User Save Directory") { - TooltipText = "Open the directory which contains Application's User Saves." + TooltipText = "Open the directory which contains Application's User Saves.", }; _openSaveUserDirMenuItem.Activated += OpenSaveUserDir_Clicked; @@ -40,7 +40,7 @@ namespace Ryujinx.Ui.Widgets // _openSaveDeviceDirMenuItem = new MenuItem("Open Device Save Directory") { - TooltipText = "Open the directory which contains Application's Device Saves." + TooltipText = "Open the directory which contains Application's Device Saves.", }; _openSaveDeviceDirMenuItem.Activated += OpenSaveDeviceDir_Clicked; @@ -49,7 +49,7 @@ namespace Ryujinx.Ui.Widgets // _openSaveBcatDirMenuItem = new MenuItem("Open BCAT Save Directory") { - TooltipText = "Open the directory which contains Application's BCAT Saves." + TooltipText = "Open the directory which contains Application's BCAT Saves.", }; _openSaveBcatDirMenuItem.Activated += OpenSaveBcatDir_Clicked; @@ -58,7 +58,7 @@ namespace Ryujinx.Ui.Widgets // _manageTitleUpdatesMenuItem = new MenuItem("Manage Title Updates") { - TooltipText = "Open the Title Update management window" + TooltipText = "Open the Title Update management window", }; _manageTitleUpdatesMenuItem.Activated += ManageTitleUpdates_Clicked; @@ -67,7 +67,7 @@ namespace Ryujinx.Ui.Widgets // _manageDlcMenuItem = new MenuItem("Manage DLC") { - TooltipText = "Open the DLC management window" + TooltipText = "Open the DLC management window", }; _manageDlcMenuItem.Activated += ManageDlc_Clicked; @@ -76,7 +76,7 @@ namespace Ryujinx.Ui.Widgets // _manageCheatMenuItem = new MenuItem("Manage Cheats") { - TooltipText = "Open the Cheat management window" + TooltipText = "Open the Cheat management window", }; _manageCheatMenuItem.Activated += ManageCheats_Clicked; @@ -85,7 +85,7 @@ namespace Ryujinx.Ui.Widgets // _openTitleModDirMenuItem = new MenuItem("Open Mods Directory") { - TooltipText = "Open the directory which contains Application's Mods." + TooltipText = "Open the directory which contains Application's Mods.", }; _openTitleModDirMenuItem.Activated += OpenTitleModDir_Clicked; @@ -94,7 +94,7 @@ namespace Ryujinx.Ui.Widgets // _openTitleSdModDirMenuItem = new MenuItem("Open Atmosphere Mods Directory") { - TooltipText = "Open the alternative SD card atmosphere directory which contains the Application's Mods." + TooltipText = "Open the alternative SD card atmosphere directory which contains the Application's Mods.", }; _openTitleSdModDirMenuItem.Activated += OpenTitleSdModDir_Clicked; @@ -116,7 +116,7 @@ namespace Ryujinx.Ui.Widgets // _extractRomFsMenuItem = new MenuItem("RomFS") { - TooltipText = "Extract the RomFS section from Application's current config (including updates)." + TooltipText = "Extract the RomFS section from Application's current config (including updates).", }; _extractRomFsMenuItem.Activated += ExtractRomFs_Clicked; @@ -125,7 +125,7 @@ namespace Ryujinx.Ui.Widgets // _extractExeFsMenuItem = new MenuItem("ExeFS") { - TooltipText = "Extract the ExeFS section from Application's current config (including updates)." + TooltipText = "Extract the ExeFS section from Application's current config (including updates).", }; _extractExeFsMenuItem.Activated += ExtractExeFs_Clicked; @@ -134,7 +134,7 @@ namespace Ryujinx.Ui.Widgets // _extractLogoMenuItem = new MenuItem("Logo") { - TooltipText = "Extract the Logo section from Application's current config (including updates)." + TooltipText = "Extract the Logo section from Application's current config (including updates).", }; _extractLogoMenuItem.Activated += ExtractLogo_Clicked; @@ -148,7 +148,7 @@ namespace Ryujinx.Ui.Widgets // _manageCacheMenuItem = new MenuItem("Cache Management") { - Submenu = _manageSubMenu + Submenu = _manageSubMenu, }; // @@ -156,7 +156,7 @@ namespace Ryujinx.Ui.Widgets // _purgePtcCacheMenuItem = new MenuItem("Queue PPTC Rebuild") { - TooltipText = "Trigger PPTC to rebuild at boot time on the next game launch." + TooltipText = "Trigger PPTC to rebuild at boot time on the next game launch.", }; _purgePtcCacheMenuItem.Activated += PurgePtcCache_Clicked; @@ -165,7 +165,7 @@ namespace Ryujinx.Ui.Widgets // _purgeShaderCacheMenuItem = new MenuItem("Purge Shader Cache") { - TooltipText = "Delete the Application's shader cache." + TooltipText = "Delete the Application's shader cache.", }; _purgeShaderCacheMenuItem.Activated += PurgeShaderCache_Clicked; @@ -174,7 +174,7 @@ namespace Ryujinx.Ui.Widgets // _openPtcDirMenuItem = new MenuItem("Open PPTC Directory") { - TooltipText = "Open the directory which contains the Application's PPTC cache." + TooltipText = "Open the directory which contains the Application's PPTC cache.", }; _openPtcDirMenuItem.Activated += OpenPtcDir_Clicked; @@ -183,7 +183,7 @@ namespace Ryujinx.Ui.Widgets // _openShaderCacheDirMenuItem = new MenuItem("Open Shader Cache Directory") { - TooltipText = "Open the directory which contains the Application's shader cache." + TooltipText = "Open the directory which contains the Application's shader cache.", }; _openShaderCacheDirMenuItem.Activated += OpenShaderCacheDir_Clicked; @@ -217,4 +217,4 @@ namespace Ryujinx.Ui.Widgets ShowAll(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Ui/Widgets/GameTableContextMenu.cs b/src/Ryujinx/Ui/Widgets/GameTableContextMenu.cs index 6279891e6..8170b9317 100644 --- a/src/Ryujinx/Ui/Widgets/GameTableContextMenu.cs +++ b/src/Ryujinx/Ui/Widgets/GameTableContextMenu.cs @@ -31,19 +31,19 @@ namespace Ryujinx.Ui.Widgets { public partial class GameTableContextMenu : Menu { - private readonly MainWindow _parent; - private readonly VirtualFileSystem _virtualFileSystem; - private readonly AccountManager _accountManager; - private readonly HorizonClient _horizonClient; + private readonly MainWindow _parent; + private readonly VirtualFileSystem _virtualFileSystem; + private readonly AccountManager _accountManager; + private readonly HorizonClient _horizonClient; private readonly BlitStruct _controlData; private readonly string _titleFilePath; private readonly string _titleName; private readonly string _titleIdText; - private readonly ulong _titleId; + private readonly ulong _titleId; private MessageDialog _dialog; - private bool _cancel; + private bool _cancel; public GameTableContextMenu(MainWindow parent, VirtualFileSystem virtualFileSystem, AccountManager accountManager, HorizonClient horizonClient, string titleFilePath, string titleName, string titleId, BlitStruct controlData) { @@ -52,12 +52,12 @@ namespace Ryujinx.Ui.Widgets InitializeComponent(); _virtualFileSystem = virtualFileSystem; - _accountManager = accountManager; - _horizonClient = horizonClient; - _titleFilePath = titleFilePath; - _titleName = titleName; - _titleIdText = titleId; - _controlData = controlData; + _accountManager = accountManager; + _horizonClient = horizonClient; + _titleFilePath = titleFilePath; + _titleName = titleName; + _titleIdText = titleId; + _controlData = controlData; if (!ulong.TryParse(_titleIdText, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out _titleId)) { @@ -66,16 +66,16 @@ namespace Ryujinx.Ui.Widgets return; } - _openSaveUserDirMenuItem.Sensitive = !Utilities.IsZeros(controlData.ByteSpan) && controlData.Value.UserAccountSaveDataSize > 0; - _openSaveDeviceDirMenuItem.Sensitive = !Utilities.IsZeros(controlData.ByteSpan) && controlData.Value.DeviceSaveDataSize > 0; - _openSaveBcatDirMenuItem.Sensitive = !Utilities.IsZeros(controlData.ByteSpan) && controlData.Value.BcatDeliveryCacheStorageSize > 0; + _openSaveUserDirMenuItem.Sensitive = !Utilities.IsZeros(controlData.ByteSpan) && controlData.Value.UserAccountSaveDataSize > 0; + _openSaveDeviceDirMenuItem.Sensitive = !Utilities.IsZeros(controlData.ByteSpan) && controlData.Value.DeviceSaveDataSize > 0; + _openSaveBcatDirMenuItem.Sensitive = !Utilities.IsZeros(controlData.ByteSpan) && controlData.Value.BcatDeliveryCacheStorageSize > 0; string fileExt = System.IO.Path.GetExtension(_titleFilePath).ToLower(); - bool hasNca = fileExt == ".nca" || fileExt == ".nsp" || fileExt == ".pfs0" || fileExt == ".xci"; + bool hasNca = fileExt == ".nca" || fileExt == ".nsp" || fileExt == ".pfs0" || fileExt == ".xci"; _extractRomFsMenuItem.Sensitive = hasNca; _extractExeFsMenuItem.Sensitive = hasNca; - _extractLogoMenuItem.Sensitive = hasNca; + _extractLogoMenuItem.Sensitive = hasNca; PopupAtPointer(null); } @@ -99,13 +99,13 @@ namespace Ryujinx.Ui.Widgets control = ref new BlitStruct(1).Value; // The set sizes don't actually matter as long as they're non-zero because we use directory savedata. - control.UserAccountSaveDataSize = 0x4000; + control.UserAccountSaveDataSize = 0x4000; control.UserAccountSaveDataJournalSize = 0x4000; Logger.Warning?.Print(LogClass.Application, "No control file was found for this game. Using a dummy one instead. This may cause inaccuracies in some games."); } - Uid user = new Uid((ulong)_accountManager.LastOpenedUser.UserId.High, (ulong)_accountManager.LastOpenedUser.UserId.Low); + Uid user = new((ulong)_accountManager.LastOpenedUser.UserId.High, (ulong)_accountManager.LastOpenedUser.UserId.Low); result = _horizonClient.Fs.EnsureApplicationSaveData(out _, new LibHac.Ncm.ApplicationId(titleId), in control, in user); @@ -148,7 +148,7 @@ namespace Ryujinx.Ui.Widgets } string committedPath = System.IO.Path.Combine(saveRootPath, "0"); - string workingPath = System.IO.Path.Combine(saveRootPath, "1"); + string workingPath = System.IO.Path.Combine(saveRootPath, "1"); // If the committed directory exists, that path will be loaded the next time the savedata is mounted if (Directory.Exists(committedPath)) @@ -170,25 +170,25 @@ namespace Ryujinx.Ui.Widgets private void ExtractSection(NcaSectionType ncaSectionType, int programIndex = 0) { - FileChooserNative fileChooser = new FileChooserNative("Choose the folder to extract into", _parent, FileChooserAction.SelectFolder, "Extract", "Cancel"); + FileChooserNative fileChooser = new("Choose the folder to extract into", _parent, FileChooserAction.SelectFolder, "Extract", "Cancel"); - ResponseType response = (ResponseType)fileChooser.Run(); - string destination = fileChooser.Filename; + ResponseType response = (ResponseType)fileChooser.Run(); + string destination = fileChooser.Filename; fileChooser.Dispose(); if (response == ResponseType.Accept) { - Thread extractorThread = new Thread(() => + Thread extractorThread = new(() => { Gtk.Application.Invoke(delegate { _dialog = new MessageDialog(null, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Cancel, null) { - Title = "Ryujinx - NCA Section Extractor", - Icon = new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Logo_Ryujinx.png"), - SecondaryText = $"Extracting {ncaSectionType} section from {System.IO.Path.GetFileName(_titleFilePath)}...", - WindowPosition = WindowPosition.Center + Title = "Ryujinx - NCA Section Extractor", + Icon = new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Logo_Ryujinx.png"), + SecondaryText = $"Extracting {ncaSectionType} section from {System.IO.Path.GetFileName(_titleFilePath)}...", + WindowPosition = WindowPosition.Center, }; int dialogResponse = _dialog.Run(); @@ -199,139 +199,140 @@ namespace Ryujinx.Ui.Widgets } }); - using (FileStream file = new FileStream(_titleFilePath, FileMode.Open, FileAccess.Read)) + using FileStream file = new(_titleFilePath, FileMode.Open, FileAccess.Read); + + Nca mainNca = null; + Nca patchNca = null; + + if ((System.IO.Path.GetExtension(_titleFilePath).ToLower() == ".nsp") || + (System.IO.Path.GetExtension(_titleFilePath).ToLower() == ".pfs0") || + (System.IO.Path.GetExtension(_titleFilePath).ToLower() == ".xci")) { - Nca mainNca = null; - Nca patchNca = null; + PartitionFileSystem pfs; - if ((System.IO.Path.GetExtension(_titleFilePath).ToLower() == ".nsp") || - (System.IO.Path.GetExtension(_titleFilePath).ToLower() == ".pfs0") || - (System.IO.Path.GetExtension(_titleFilePath).ToLower() == ".xci")) + if (System.IO.Path.GetExtension(_titleFilePath) == ".xci") { - PartitionFileSystem pfs; + Xci xci = new(_virtualFileSystem.KeySet, file.AsStorage()); - if (System.IO.Path.GetExtension(_titleFilePath) == ".xci") + pfs = xci.OpenPartition(XciPartitionType.Secure); + } + else + { + pfs = new PartitionFileSystem(file.AsStorage()); + } + + foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca")) + { + using var ncaFile = new UniqueRef(); + + pfs.OpenFile(ref ncaFile.Ref, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); + + Nca nca = new(_virtualFileSystem.KeySet, ncaFile.Release().AsStorage()); + + if (nca.Header.ContentType == NcaContentType.Program) { - Xci xci = new Xci(_virtualFileSystem.KeySet, file.AsStorage()); + int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program); - pfs = xci.OpenPartition(XciPartitionType.Secure); - } - else - { - pfs = new PartitionFileSystem(file.AsStorage()); - } - - foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca")) - { - using var ncaFile = new UniqueRef(); - - pfs.OpenFile(ref ncaFile.Ref, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); - - Nca nca = new Nca(_virtualFileSystem.KeySet, ncaFile.Release().AsStorage()); - - if (nca.Header.ContentType == NcaContentType.Program) + if (nca.SectionExists(NcaSectionType.Data) && nca.Header.GetFsHeader(dataIndex).IsPatchSection()) { - int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program); - - if (nca.SectionExists(NcaSectionType.Data) && nca.Header.GetFsHeader(dataIndex).IsPatchSection()) - { - patchNca = nca; - } - else - { - mainNca = nca; - } + patchNca = nca; + } + else + { + mainNca = nca; } } } - else if (System.IO.Path.GetExtension(_titleFilePath).ToLower() == ".nca") - { - mainNca = new Nca(_virtualFileSystem.KeySet, file.AsStorage()); - } + } + else if (System.IO.Path.GetExtension(_titleFilePath).ToLower() == ".nca") + { + mainNca = new Nca(_virtualFileSystem.KeySet, file.AsStorage()); + } - if (mainNca == null) - { - Logger.Error?.Print(LogClass.Application, "Extraction failure. The main NCA is not present in the selected file."); + if (mainNca == null) + { + Logger.Error?.Print(LogClass.Application, "Extraction failure. The main NCA is not present in the selected file."); - Gtk.Application.Invoke(delegate + Gtk.Application.Invoke(delegate { GtkDialog.CreateErrorDialog("Extraction failure. The main NCA is not present in the selected file."); }); - return; - } + return; + } - (Nca updatePatchNca, _) = ApplicationLibrary.GetGameUpdateData(_virtualFileSystem, mainNca.Header.TitleId.ToString("x16"), programIndex, out _); + (Nca updatePatchNca, _) = ApplicationLibrary.GetGameUpdateData(_virtualFileSystem, mainNca.Header.TitleId.ToString("x16"), programIndex, out _); - if (updatePatchNca != null) - { - patchNca = updatePatchNca; - } + if (updatePatchNca != null) + { + patchNca = updatePatchNca; + } - int index = Nca.GetSectionIndexFromType(ncaSectionType, mainNca.Header.ContentType); + int index = Nca.GetSectionIndexFromType(ncaSectionType, mainNca.Header.ContentType); - bool sectionExistsInPatch = false; - if (patchNca != null) - { - sectionExistsInPatch = patchNca.CanOpenSection(index); - } + bool sectionExistsInPatch = false; - IFileSystem ncaFileSystem = sectionExistsInPatch ? mainNca.OpenFileSystemWithPatch(patchNca, index, IntegrityCheckLevel.ErrorOnInvalid) + if (patchNca != null) + { + sectionExistsInPatch = patchNca.CanOpenSection(index); + } + + IFileSystem ncaFileSystem = sectionExistsInPatch ? mainNca.OpenFileSystemWithPatch(patchNca, index, IntegrityCheckLevel.ErrorOnInvalid) : mainNca.OpenFileSystem(index, IntegrityCheckLevel.ErrorOnInvalid); - FileSystemClient fsClient = _horizonClient.Fs; + FileSystemClient fsClient = _horizonClient.Fs; - string source = DateTime.Now.ToFileTime().ToString()[10..]; - string output = DateTime.Now.ToFileTime().ToString()[10..]; + string source = DateTime.Now.ToFileTime().ToString()[10..]; + string output = DateTime.Now.ToFileTime().ToString()[10..]; - using var uniqueSourceFs = new UniqueRef(ncaFileSystem); - using var uniqueOutputFs = new UniqueRef(new LocalFileSystem(destination)); + using var uniqueSourceFs = new UniqueRef(ncaFileSystem); + using var uniqueOutputFs = new UniqueRef(new LocalFileSystem(destination)); - fsClient.Register(source.ToU8Span(), ref uniqueSourceFs.Ref); - fsClient.Register(output.ToU8Span(), ref uniqueOutputFs.Ref); + fsClient.Register(source.ToU8Span(), ref uniqueSourceFs.Ref); + fsClient.Register(output.ToU8Span(), ref uniqueOutputFs.Ref); - (Result? resultCode, bool canceled) = CopyDirectory(fsClient, $"{source}:/", $"{output}:/"); + (Result? resultCode, bool canceled) = CopyDirectory(fsClient, $"{source}:/", $"{output}:/"); - if (!canceled) + if (!canceled) + { + if (resultCode.Value.IsFailure()) { - if (resultCode.Value.IsFailure()) - { - Logger.Error?.Print(LogClass.Application, $"LibHac returned error code: {resultCode.Value.ErrorCode}"); + Logger.Error?.Print(LogClass.Application, $"LibHac returned error code: {resultCode.Value.ErrorCode}"); - Gtk.Application.Invoke(delegate + Gtk.Application.Invoke(delegate { _dialog?.Dispose(); GtkDialog.CreateErrorDialog("Extraction failed. Read the log file for further information."); }); - } - else if (resultCode.Value.IsSuccess()) - { - Gtk.Application.Invoke(delegate + } + else if (resultCode.Value.IsSuccess()) + { + Gtk.Application.Invoke(delegate { _dialog?.Dispose(); - MessageDialog dialog = new MessageDialog(null, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Ok, null) + MessageDialog dialog = new(null, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Ok, null) { - Title = "Ryujinx - NCA Section Extractor", - Icon = new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Logo_Ryujinx.png"), - SecondaryText = "Extraction completed successfully.", - WindowPosition = WindowPosition.Center + Title = "Ryujinx - NCA Section Extractor", + Icon = new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Logo_Ryujinx.png"), + SecondaryText = "Extraction completed successfully.", + WindowPosition = WindowPosition.Center, }; dialog.Run(); dialog.Dispose(); }); - } } - - fsClient.Unmount(source.ToU8Span()); - fsClient.Unmount(output.ToU8Span()); } - }); - extractorThread.Name = "GUI.NcaSectionExtractorThread"; - extractorThread.IsBackground = true; + fsClient.Unmount(source.ToU8Span()); + fsClient.Unmount(output.ToU8Span()); + }) + { + Name = "GUI.NcaSectionExtractorThread", + IsBackground = true, + }; extractorThread.Start(); } } @@ -339,7 +340,10 @@ namespace Ryujinx.Ui.Widgets private (Result? result, bool canceled) CopyDirectory(FileSystemClient fs, string sourcePath, string destPath) { Result rc = fs.OpenDirectory(out DirectoryHandle sourceHandle, sourcePath.ToU8Span(), OpenDirectoryMode.All); - if (rc.IsFailure()) return (rc, false); + if (rc.IsFailure()) + { + return (rc, false); + } using (sourceHandle) { @@ -369,7 +373,10 @@ namespace Ryujinx.Ui.Widgets fs.CreateOrOverwriteFile(subDstPath, entry.Size); rc = CopyFile(fs, subSrcPath, subDstPath); - if (rc.IsFailure()) return (rc, false); + if (rc.IsFailure()) + { + return (rc, false); + } } } } @@ -377,22 +384,31 @@ namespace Ryujinx.Ui.Widgets return (Result.Success, false); } - public Result CopyFile(FileSystemClient fs, string sourcePath, string destPath) + public static Result CopyFile(FileSystemClient fs, string sourcePath, string destPath) { Result rc = fs.OpenFile(out FileHandle sourceHandle, sourcePath.ToU8Span(), OpenMode.Read); - if (rc.IsFailure()) return rc; + if (rc.IsFailure()) + { + return rc; + } using (sourceHandle) { rc = fs.OpenFile(out FileHandle destHandle, destPath.ToU8Span(), OpenMode.Write | OpenMode.AllowAppend); - if (rc.IsFailure()) return rc; + if (rc.IsFailure()) + { + return rc; + } using (destHandle) { const int MaxBufferSize = 1024 * 1024; rc = fs.GetFileSize(out long fileSize, sourceHandle); - if (rc.IsFailure()) return rc; + if (rc.IsFailure()) + { + return rc; + } int bufferSize = (int)Math.Min(MaxBufferSize, fileSize); @@ -405,10 +421,16 @@ namespace Ryujinx.Ui.Widgets Span buf = buffer.AsSpan(0, toRead); rc = fs.ReadFile(out long _, sourceHandle, offset, buf); - if (rc.IsFailure()) return rc; + if (rc.IsFailure()) + { + return rc; + } rc = fs.WriteFile(destHandle, offset, buf, WriteOption.None); - if (rc.IsFailure()) return rc; + if (rc.IsFailure()) + { + return rc; + } } } finally @@ -417,7 +439,10 @@ namespace Ryujinx.Ui.Widgets } rc = fs.FlushFile(destHandle); - if (rc.IsFailure()) return rc; + if (rc.IsFailure()) + { + return rc; + } } } @@ -466,7 +491,7 @@ namespace Ryujinx.Ui.Widgets private void OpenTitleModDir_Clicked(object sender, EventArgs args) { - string modsBasePath = ModLoader.GetModsBasePath(); + string modsBasePath = ModLoader.GetModsBasePath(); string titleModsPath = ModLoader.GetTitleDir(modsBasePath, _titleIdText); OpenHelper.OpenFolder(titleModsPath); @@ -474,8 +499,8 @@ namespace Ryujinx.Ui.Widgets private void OpenTitleSdModDir_Clicked(object sender, EventArgs args) { - string sdModsBasePath = ModLoader.GetSdModsBasePath(); - string titleModsPath = ModLoader.GetTitleDir(sdModsBasePath, _titleIdText); + string sdModsBasePath = ModLoader.GetSdModsBasePath(); + string titleModsPath = ModLoader.GetTitleDir(sdModsBasePath, _titleIdText); OpenHelper.OpenFolder(titleModsPath); } @@ -497,9 +522,9 @@ namespace Ryujinx.Ui.Widgets private void OpenPtcDir_Clicked(object sender, EventArgs args) { - string ptcDir = System.IO.Path.Combine(AppDataManager.GamesDirPath, _titleIdText, "cache", "cpu"); + string ptcDir = System.IO.Path.Combine(AppDataManager.GamesDirPath, _titleIdText, "cache", "cpu"); - string mainPath = System.IO.Path.Combine(ptcDir, "0"); + string mainPath = System.IO.Path.Combine(ptcDir, "0"); string backupPath = System.IO.Path.Combine(ptcDir, "1"); if (!Directory.Exists(ptcDir)) @@ -526,12 +551,12 @@ namespace Ryujinx.Ui.Widgets private void PurgePtcCache_Clicked(object sender, EventArgs args) { - DirectoryInfo mainDir = new DirectoryInfo(System.IO.Path.Combine(AppDataManager.GamesDirPath, _titleIdText, "cache", "cpu", "0")); - DirectoryInfo backupDir = new DirectoryInfo(System.IO.Path.Combine(AppDataManager.GamesDirPath, _titleIdText, "cache", "cpu", "1")); + DirectoryInfo mainDir = new(System.IO.Path.Combine(AppDataManager.GamesDirPath, _titleIdText, "cache", "cpu", "0")); + DirectoryInfo backupDir = new(System.IO.Path.Combine(AppDataManager.GamesDirPath, _titleIdText, "cache", "cpu", "1")); MessageDialog warningDialog = GtkDialog.CreateConfirmationDialog("Warning", $"You are about to queue a PPTC rebuild on the next boot of:\n\n{_titleName}\n\nAre you sure you want to proceed?"); - List cacheFiles = new List(); + List cacheFiles = new(); if (mainDir.Exists) { @@ -551,7 +576,7 @@ namespace Ryujinx.Ui.Widgets { file.Delete(); } - catch(Exception e) + catch (Exception e) { GtkDialog.CreateErrorDialog($"Error purging PPTC cache {file.Name}: {e}"); } @@ -563,12 +588,12 @@ namespace Ryujinx.Ui.Widgets private void PurgeShaderCache_Clicked(object sender, EventArgs args) { - DirectoryInfo shaderCacheDir = new DirectoryInfo(System.IO.Path.Combine(AppDataManager.GamesDirPath, _titleIdText, "cache", "shader")); + DirectoryInfo shaderCacheDir = new(System.IO.Path.Combine(AppDataManager.GamesDirPath, _titleIdText, "cache", "shader")); using MessageDialog warningDialog = GtkDialog.CreateConfirmationDialog("Warning", $"You are about to delete the shader cache for :\n\n{_titleName}\n\nAre you sure you want to proceed?"); - List oldCacheDirectories = new List(); - List newCacheFiles = new List(); + List oldCacheDirectories = new(); + List newCacheFiles = new(); if (shaderCacheDir.Exists) { diff --git a/src/Ryujinx/Ui/Widgets/GtkDialog.cs b/src/Ryujinx/Ui/Widgets/GtkDialog.cs index d2cab2196..51e777fa1 100644 --- a/src/Ryujinx/Ui/Widgets/GtkDialog.cs +++ b/src/Ryujinx/Ui/Widgets/GtkDialog.cs @@ -10,14 +10,14 @@ namespace Ryujinx.Ui.Widgets { private static bool _isChoiceDialogOpen; - private GtkDialog(string title, string mainText, string secondaryText, MessageType messageType = MessageType.Other, ButtonsType buttonsType = ButtonsType.Ok) + private GtkDialog(string title, string mainText, string secondaryText, MessageType messageType = MessageType.Other, ButtonsType buttonsType = ButtonsType.Ok) : base(null, DialogFlags.Modal, messageType, buttonsType, null) { - Title = title; - Icon = new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Logo_Ryujinx.png"); - Text = mainText; - SecondaryText = secondaryText; - WindowPosition = WindowPosition.Center; + Title = title; + Icon = new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Logo_Ryujinx.png"); + Text = mainText; + SecondaryText = secondaryText; + WindowPosition = WindowPosition.Center; SecondaryUseMarkup = true; Response += GtkDialog_Response; @@ -80,7 +80,7 @@ namespace Ryujinx.Ui.Widgets internal static ResponseType CreateCustomDialog(string title, string mainText, string secondaryText, Dictionary buttons, MessageType messageType = MessageType.Other) { - GtkDialog gtkDialog = new GtkDialog(title, mainText, secondaryText, messageType, ButtonsType.None); + GtkDialog gtkDialog = new(title, mainText, secondaryText, messageType, ButtonsType.None); foreach (var button in buttons) { @@ -92,9 +92,9 @@ namespace Ryujinx.Ui.Widgets internal static string CreateInputDialog(Window parent, string title, string mainText, uint inputMax) { - GtkInputDialog gtkDialog = new GtkInputDialog(parent, title, mainText, inputMax); - ResponseType response = (ResponseType)gtkDialog.Run(); - string responseText = gtkDialog.InputEntry.Text.TrimEnd(); + GtkInputDialog gtkDialog = new(parent, title, mainText, inputMax); + ResponseType response = (ResponseType)gtkDialog.Run(); + string responseText = gtkDialog.InputEntry.Text.TrimEnd(); gtkDialog.Dispose(); diff --git a/src/Ryujinx/Ui/Widgets/GtkInputDialog.cs b/src/Ryujinx/Ui/Widgets/GtkInputDialog.cs index 21b349373..e4fb5aa17 100644 --- a/src/Ryujinx/Ui/Widgets/GtkInputDialog.cs +++ b/src/Ryujinx/Ui/Widgets/GtkInputDialog.cs @@ -12,26 +12,26 @@ namespace Ryujinx.Ui.Widgets Title = title; - Label mainTextLabel = new Label + Label mainTextLabel = new() { - Text = mainText + Text = mainText, }; InputEntry = new Entry { - MaxLength = (int)inputMax + MaxLength = (int)inputMax, }; - Label inputMaxTextLabel = new Label + Label inputMaxTextLabel = new() { - Text = $"(Max length: {inputMax})" + Text = $"(Max length: {inputMax})", }; - ((Box)MessageArea).PackStart(mainTextLabel, true, true, 0); - ((Box)MessageArea).PackStart(InputEntry, true, true, 5); + ((Box)MessageArea).PackStart(mainTextLabel, true, true, 0); + ((Box)MessageArea).PackStart(InputEntry, true, true, 5); ((Box)MessageArea).PackStart(inputMaxTextLabel, true, true, 0); ShowAll(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Ui/Widgets/ProfileDialog.cs b/src/Ryujinx/Ui/Widgets/ProfileDialog.cs index 242e8bd7d..0731b37a1 100644 --- a/src/Ryujinx/Ui/Widgets/ProfileDialog.cs +++ b/src/Ryujinx/Ui/Widgets/ProfileDialog.cs @@ -10,7 +10,7 @@ namespace Ryujinx.Ui.Widgets { public string FileName { get; private set; } -#pragma warning disable CS0649, IDE0044 +#pragma warning disable CS0649, IDE0044 // Field is never assigned to, Add readonly modifier [GUI] Entry _profileEntry; [GUI] Label _errorMessage; #pragma warning restore CS0649, IDE0044 @@ -54,4 +54,4 @@ namespace Ryujinx.Ui.Widgets Respond(ResponseType.Cancel); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Ui/Widgets/UserErrorDialog.cs b/src/Ryujinx/Ui/Widgets/UserErrorDialog.cs index fc3938d42..b2dea8355 100644 --- a/src/Ryujinx/Ui/Widgets/UserErrorDialog.cs +++ b/src/Ryujinx/Ui/Widgets/UserErrorDialog.cs @@ -6,9 +6,9 @@ namespace Ryujinx.Ui.Widgets { internal class UserErrorDialog : MessageDialog { - private const string SetupGuideUrl = "https://github.com/Ryujinx/Ryujinx/wiki/Ryujinx-Setup-&-Configuration-Guide"; - private const int OkResponseId = 0; - private const int SetupGuideResponseId = 1; + private const string SetupGuideUrl = "https://github.com/Ryujinx/Ryujinx/wiki/Ryujinx-Setup-&-Configuration-Guide"; + private const int OkResponseId = 0; + private const int SetupGuideResponseId = 1; private readonly UserError _userError; @@ -16,7 +16,7 @@ namespace Ryujinx.Ui.Widgets { _userError = error; - WindowPosition = WindowPosition.Center; + WindowPosition = WindowPosition.Center; SecondaryUseMarkup = true; Response += UserErrorDialog_Response; @@ -36,8 +36,8 @@ namespace Ryujinx.Ui.Widgets SecondaryUseMarkup = true; - Title = $"Ryujinx error ({errorCode})"; - Text = $"{errorCode}: {GetErrorTitle(error)}"; + Title = $"Ryujinx error ({errorCode})"; + Text = $"{errorCode}: {GetErrorTitle(error)}"; SecondaryText = GetErrorDescription(error); if (isInSetupGuide) @@ -46,34 +46,34 @@ namespace Ryujinx.Ui.Widgets } } - private string GetErrorCode(UserError error) + private static string GetErrorCode(UserError error) { return $"RYU-{(uint)error:X4}"; } - private string GetErrorTitle(UserError error) + private static string GetErrorTitle(UserError error) { return error switch { - UserError.NoKeys => "Keys not found", - UserError.NoFirmware => "Firmware not found", + UserError.NoKeys => "Keys not found", + UserError.NoFirmware => "Firmware not found", UserError.FirmwareParsingFailed => "Firmware parsing error", - UserError.ApplicationNotFound => "Application not found", - UserError.Unknown => "Unknown error", - _ => "Undefined error", + UserError.ApplicationNotFound => "Application not found", + UserError.Unknown => "Unknown error", + _ => "Undefined error", }; } - private string GetErrorDescription(UserError error) + private static string GetErrorDescription(UserError error) { return error switch { - UserError.NoKeys => "Ryujinx was unable to find your 'prod.keys' file", - UserError.NoFirmware => "Ryujinx was unable to find any firmwares installed", + UserError.NoKeys => "Ryujinx was unable to find your 'prod.keys' file", + UserError.NoFirmware => "Ryujinx was unable to find any firmwares installed", UserError.FirmwareParsingFailed => "Ryujinx was unable to parse the provided firmware. This is usually caused by outdated keys.", - UserError.ApplicationNotFound => "Ryujinx couldn't find a valid application at the given path.", - UserError.Unknown => "An unknown error occured!", - _ => "An undefined error occured! This shouldn't happen, please contact a dev!", + UserError.ApplicationNotFound => "Ryujinx couldn't find a valid application at the given path.", + UserError.Unknown => "An unknown error occured!", + _ => "An undefined error occured! This shouldn't happen, please contact a dev!", }; } @@ -82,9 +82,9 @@ namespace Ryujinx.Ui.Widgets return error switch { UserError.NoKeys or - UserError.NoFirmware or + UserError.NoFirmware or UserError.FirmwareParsingFailed => true, - _ => false, + _ => false, }; } @@ -97,9 +97,9 @@ namespace Ryujinx.Ui.Widgets return error switch { - UserError.NoKeys => SetupGuideUrl + "#initial-setup---placement-of-prodkeys", + UserError.NoKeys => SetupGuideUrl + "#initial-setup---placement-of-prodkeys", UserError.NoFirmware => SetupGuideUrl + "#initial-setup-continued---installation-of-firmware", - _ => SetupGuideUrl, + _ => SetupGuideUrl, }; } @@ -120,4 +120,4 @@ namespace Ryujinx.Ui.Widgets new UserErrorDialog(error).Run(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Ui/Windows/AboutWindow.Designer.cs b/src/Ryujinx/Ui/Windows/AboutWindow.Designer.cs index 3edc002d7..345026334 100644 --- a/src/Ryujinx/Ui/Windows/AboutWindow.Designer.cs +++ b/src/Ryujinx/Ui/Windows/AboutWindow.Designer.cs @@ -7,65 +7,63 @@ namespace Ryujinx.Ui.Windows { public partial class AboutWindow : Window { - private Box _mainBox; - private Box _leftBox; - private Box _logoBox; - private Image _ryujinxLogo; - private Box _logoTextBox; - private Label _ryujinxLabel; - private Label _ryujinxPhoneticLabel; - private EventBox _ryujinxLink; - private Label _ryujinxLinkLabel; - private Label _versionLabel; - private Label _disclaimerLabel; - private EventBox _amiiboApiLink; - private Label _amiiboApiLinkLabel; - private Box _socialBox; - private EventBox _patreonEventBox; - private Box _patreonBox; - private Image _patreonLogo; - private Label _patreonLabel; - private EventBox _githubEventBox; - private Box _githubBox; - private Image _githubLogo; - private Label _githubLabel; - private Box _discordBox; - private EventBox _discordEventBox; - private Image _discordLogo; - private Label _discordLabel; - private EventBox _twitterEventBox; - private Box _twitterBox; - private Image _twitterLogo; - private Label _twitterLabel; - private Separator _separator; - private Box _rightBox; - private Label _aboutLabel; - private Label _aboutDescriptionLabel; - private Label _createdByLabel; - private TextView _createdByText; - private EventBox _contributorsEventBox; - private Label _contributorsLinkLabel; - private Label _patreonNamesLabel; + private Box _mainBox; + private Box _leftBox; + private Box _logoBox; + private Image _ryujinxLogo; + private Box _logoTextBox; + private Label _ryujinxLabel; + private Label _ryujinxPhoneticLabel; + private EventBox _ryujinxLink; + private Label _ryujinxLinkLabel; + private Label _versionLabel; + private Label _disclaimerLabel; + private EventBox _amiiboApiLink; + private Label _amiiboApiLinkLabel; + private Box _socialBox; + private EventBox _patreonEventBox; + private Box _patreonBox; + private Image _patreonLogo; + private Label _patreonLabel; + private EventBox _githubEventBox; + private Box _githubBox; + private Image _githubLogo; + private Label _githubLabel; + private Box _discordBox; + private EventBox _discordEventBox; + private Image _discordLogo; + private Label _discordLabel; + private EventBox _twitterEventBox; + private Box _twitterBox; + private Image _twitterLogo; + private Label _twitterLabel; + private Separator _separator; + private Box _rightBox; + private Label _aboutLabel; + private Label _aboutDescriptionLabel; + private Label _createdByLabel; + private TextView _createdByText; + private EventBox _contributorsEventBox; + private Label _contributorsLinkLabel; + private Label _patreonNamesLabel; private ScrolledWindow _patreonNamesScrolled; - private TextView _patreonNamesText; - private EventBox _changelogEventBox; - private Label _changelogLinkLabel; + private TextView _patreonNamesText; + private EventBox _changelogEventBox; + private Label _changelogLinkLabel; private void InitializeComponent() { -#pragma warning disable CS0612 - // // AboutWindow // - CanFocus = false; - Resizable = false; - Modal = true; + CanFocus = false; + Resizable = false; + Modal = true; WindowPosition = WindowPosition.Center; - DefaultWidth = 800; - DefaultHeight = 450; - TypeHint = Gdk.WindowTypeHint.Dialog; + DefaultWidth = 800; + DefaultHeight = 450; + TypeHint = Gdk.WindowTypeHint.Dialog; // // _mainBox @@ -77,9 +75,9 @@ namespace Ryujinx.Ui.Windows // _leftBox = new Box(Orientation.Vertical, 0) { - Margin = 15, - MarginLeft = 30, - MarginRight = 0 + Margin = 15, + MarginStart = 30, + MarginEnd = 0, }; // @@ -92,8 +90,8 @@ namespace Ryujinx.Ui.Windows // _ryujinxLogo = new Image(new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Logo_Ryujinx.png", 100, 100)) { - Margin = 10, - MarginLeft = 15 + Margin = 10, + MarginStart = 15, }; // @@ -106,9 +104,9 @@ namespace Ryujinx.Ui.Windows // _ryujinxLabel = new Label("Ryujinx") { - MarginTop = 15, - Justify = Justification.Center, - Attributes = new AttrList() + MarginTop = 15, + Justify = Justification.Center, + Attributes = new AttrList(), }; _ryujinxLabel.Attributes.Insert(new Pango.AttrScale(2.7f)); @@ -117,7 +115,7 @@ namespace Ryujinx.Ui.Windows // _ryujinxPhoneticLabel = new Label("(REE-YOU-JINX)") { - Justify = Justification.Center + Justify = Justification.Center, }; // @@ -135,8 +133,8 @@ namespace Ryujinx.Ui.Windows _ryujinxLinkLabel = new Label("www.ryujinx.org") { TooltipText = "Click to open the Ryujinx website in your default browser.", - Justify = Justification.Center, - Attributes = new AttrList() + Justify = Justification.Center, + Attributes = new AttrList(), }; _ryujinxLinkLabel.Attributes.Insert(new Pango.AttrUnderline(Underline.Single)); @@ -145,9 +143,9 @@ namespace Ryujinx.Ui.Windows // _versionLabel = new Label(Program.Version) { - Expand = true, + Expand = true, Justify = Justification.Center, - Margin = 5 + Margin = 5, }; // @@ -163,7 +161,7 @@ namespace Ryujinx.Ui.Windows { TooltipText = "Click to open the changelog for this version in your default browser.", Justify = Justification.Center, - Attributes = new AttrList() + Attributes = new AttrList(), }; _changelogLinkLabel.Attributes.Insert(new Pango.AttrUnderline(Underline.Single)); @@ -172,10 +170,10 @@ namespace Ryujinx.Ui.Windows // _disclaimerLabel = new Label("Ryujinx is not affiliated with Nintendo™,\nor any of its partners, in any way.") { - Expand = true, - Justify = Justification.Center, - Margin = 5, - Attributes = new AttrList() + Expand = true, + Justify = Justification.Center, + Margin = 5, + Attributes = new AttrList(), }; _disclaimerLabel.Attributes.Insert(new Pango.AttrScale(0.8f)); @@ -184,7 +182,7 @@ namespace Ryujinx.Ui.Windows // _amiiboApiLink = new EventBox() { - Margin = 5 + Margin = 5, }; _amiiboApiLink.ButtonPressEvent += AmiiboApiButton_Pressed; @@ -194,8 +192,8 @@ namespace Ryujinx.Ui.Windows _amiiboApiLinkLabel = new Label("AmiiboAPI (www.amiiboapi.com) is used\nin our Amiibo emulation.") { TooltipText = "Click to open the AmiiboAPI website in your default browser.", - Justify = Justification.Center, - Attributes = new AttrList() + Justify = Justification.Center, + Attributes = new AttrList(), }; _amiiboApiLinkLabel.Attributes.Insert(new Pango.AttrScale(0.9f)); @@ -204,8 +202,8 @@ namespace Ryujinx.Ui.Windows // _socialBox = new Box(Orientation.Horizontal, 0) { - Margin = 25, - MarginBottom = 10 + Margin = 25, + MarginBottom = 10, }; // @@ -213,7 +211,7 @@ namespace Ryujinx.Ui.Windows // _patreonEventBox = new EventBox() { - TooltipText = "Click to open the Ryujinx Patreon page in your default browser." + TooltipText = "Click to open the Ryujinx Patreon page in your default browser.", }; _patreonEventBox.ButtonPressEvent += PatreonButton_Pressed; @@ -227,7 +225,7 @@ namespace Ryujinx.Ui.Windows // _patreonLogo = new Image(new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Logo_Patreon_Light.png", 30, 30)) { - Margin = 10 + Margin = 10, }; // @@ -235,7 +233,7 @@ namespace Ryujinx.Ui.Windows // _patreonLabel = new Label("Patreon") { - Justify = Justification.Center + Justify = Justification.Center, }; // @@ -243,7 +241,7 @@ namespace Ryujinx.Ui.Windows // _githubEventBox = new EventBox() { - TooltipText = "Click to open the Ryujinx GitHub page in your default browser." + TooltipText = "Click to open the Ryujinx GitHub page in your default browser.", }; _githubEventBox.ButtonPressEvent += GitHubButton_Pressed; @@ -257,7 +255,7 @@ namespace Ryujinx.Ui.Windows // _githubLogo = new Image(new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Logo_GitHub_Light.png", 30, 30)) { - Margin = 10 + Margin = 10, }; // @@ -265,7 +263,7 @@ namespace Ryujinx.Ui.Windows // _githubLabel = new Label("GitHub") { - Justify = Justification.Center + Justify = Justification.Center, }; // @@ -278,7 +276,7 @@ namespace Ryujinx.Ui.Windows // _discordEventBox = new EventBox() { - TooltipText = "Click to open an invite to the Ryujinx Discord server in your default browser." + TooltipText = "Click to open an invite to the Ryujinx Discord server in your default browser.", }; _discordEventBox.ButtonPressEvent += DiscordButton_Pressed; @@ -287,7 +285,7 @@ namespace Ryujinx.Ui.Windows // _discordLogo = new Image(new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Logo_Discord_Light.png", 30, 30)) { - Margin = 10 + Margin = 10, }; // @@ -295,7 +293,7 @@ namespace Ryujinx.Ui.Windows // _discordLabel = new Label("Discord") { - Justify = Justification.Center + Justify = Justification.Center, }; // @@ -303,7 +301,7 @@ namespace Ryujinx.Ui.Windows // _twitterEventBox = new EventBox() { - TooltipText = "Click to open the Ryujinx Twitter page in your default browser." + TooltipText = "Click to open the Ryujinx Twitter page in your default browser.", }; _twitterEventBox.ButtonPressEvent += TwitterButton_Pressed; @@ -317,7 +315,7 @@ namespace Ryujinx.Ui.Windows // _twitterLogo = new Image(new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Logo_Twitter_Light.png", 30, 30)) { - Margin = 10 + Margin = 10, }; // @@ -325,7 +323,7 @@ namespace Ryujinx.Ui.Windows // _twitterLabel = new Label("Twitter") { - Justify = Justification.Center + Justify = Justification.Center, }; // @@ -333,7 +331,7 @@ namespace Ryujinx.Ui.Windows // _separator = new Separator(Orientation.Vertical) { - Margin = 15 + Margin = 15, }; // @@ -341,8 +339,8 @@ namespace Ryujinx.Ui.Windows // _rightBox = new Box(Orientation.Vertical, 0) { - Margin = 15, - MarginTop = 40 + Margin = 15, + MarginTop = 40, }; // @@ -350,8 +348,8 @@ namespace Ryujinx.Ui.Windows // _aboutLabel = new Label("About :") { - Halign = Align.Start, - Attributes = new AttrList() + Halign = Align.Start, + Attributes = new AttrList(), }; _aboutLabel.Attributes.Insert(new Pango.AttrWeight(Weight.Bold)); _aboutLabel.Attributes.Insert(new Pango.AttrUnderline(Underline.Single)); @@ -365,7 +363,7 @@ namespace Ryujinx.Ui.Windows "Developers interested in contributing can find out more on our GitHub or Discord.") { Margin = 15, - Halign = Align.Start + Halign = Align.Start, }; // @@ -373,8 +371,8 @@ namespace Ryujinx.Ui.Windows // _createdByLabel = new Label("Maintained by :") { - Halign = Align.Start, - Attributes = new AttrList() + Halign = Align.Start, + Attributes = new AttrList(), }; _createdByLabel.Attributes.Insert(new Pango.AttrWeight(Weight.Bold)); _createdByLabel.Attributes.Insert(new Pango.AttrUnderline(Underline.Single)); @@ -384,11 +382,11 @@ namespace Ryujinx.Ui.Windows // _createdByText = new TextView() { - WrapMode = Gtk.WrapMode.Word, - Editable = false, + WrapMode = Gtk.WrapMode.Word, + Editable = false, CursorVisible = false, - Margin = 15, - MarginRight = 30 + Margin = 15, + MarginEnd = 30, }; _createdByText.Buffer.Text = "gdkchan, Ac_K, Thog, rip in peri peri, LDj3SNuD, emmaus, Thealexbarney, Xpl0itR, GoffyDude, »jD« and more..."; @@ -404,9 +402,9 @@ namespace Ryujinx.Ui.Windows _contributorsLinkLabel = new Label("See All Contributors...") { TooltipText = "Click to open the Contributors page in your default browser.", - MarginRight = 30, - Halign = Align.End, - Attributes = new AttrList() + MarginEnd = 30, + Halign = Align.End, + Attributes = new AttrList(), }; _contributorsLinkLabel.Attributes.Insert(new Pango.AttrUnderline(Underline.Single)); @@ -415,8 +413,8 @@ namespace Ryujinx.Ui.Windows // _patreonNamesLabel = new Label("Supported on Patreon by :") { - Halign = Align.Start, - Attributes = new AttrList() + Halign = Align.Start, + Attributes = new AttrList(), }; _patreonNamesLabel.Attributes.Insert(new Pango.AttrWeight(Weight.Bold)); _patreonNamesLabel.Attributes.Insert(new Pango.AttrUnderline(Underline.Single)); @@ -426,10 +424,10 @@ namespace Ryujinx.Ui.Windows // _patreonNamesScrolled = new ScrolledWindow() { - Margin = 15, - MarginRight = 30, - Expand = true, - ShadowType = ShadowType.In + Margin = 15, + MarginEnd = 30, + Expand = true, + ShadowType = ShadowType.In, }; _patreonNamesScrolled.SetPolicy(PolicyType.Never, PolicyType.Automatic); @@ -438,13 +436,11 @@ namespace Ryujinx.Ui.Windows // _patreonNamesText = new TextView() { - WrapMode = Gtk.WrapMode.Word + WrapMode = Gtk.WrapMode.Word, }; _patreonNamesText.Buffer.Text = "Loading..."; _patreonNamesText.SetProperty("editable", new GLib.Value(false)); -#pragma warning restore CS0612 - ShowComponent(); } @@ -512,4 +508,4 @@ namespace Ryujinx.Ui.Windows ShowAll(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Ui/Windows/AboutWindow.cs b/src/Ryujinx/Ui/Windows/AboutWindow.cs index 15bfa500d..9e11905db 100644 --- a/src/Ryujinx/Ui/Windows/AboutWindow.cs +++ b/src/Ryujinx/Ui/Windows/AboutWindow.cs @@ -25,7 +25,7 @@ namespace Ryujinx.Ui.Windows _patreonNamesText.Buffer.Text = "Connection Error."; } - HttpClient httpClient = new HttpClient(); + HttpClient httpClient = new(); try { @@ -82,4 +82,4 @@ namespace Ryujinx.Ui.Windows OpenHelper.OpenUrl("https://github.com/Ryujinx/Ryujinx/wiki/Changelog#ryujinx-changelog"); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Ui/Windows/AmiiboWindow.Designer.cs b/src/Ryujinx/Ui/Windows/AmiiboWindow.Designer.cs index 3480c6e8a..cb27c34cb 100644 --- a/src/Ryujinx/Ui/Windows/AmiiboWindow.Designer.cs +++ b/src/Ryujinx/Ui/Windows/AmiiboWindow.Designer.cs @@ -4,37 +4,35 @@ namespace Ryujinx.Ui.Windows { public partial class AmiiboWindow : Window { - private Box _mainBox; - private ButtonBox _buttonBox; - private Button _scanButton; - private Button _cancelButton; - private CheckButton _randomUuidCheckBox; - private Box _amiiboBox; - private Box _amiiboHeadBox; - private Box _amiiboSeriesBox; - private Label _amiiboSeriesLabel; + private Box _mainBox; + private ButtonBox _buttonBox; + private Button _scanButton; + private Button _cancelButton; + private CheckButton _randomUuidCheckBox; + private Box _amiiboBox; + private Box _amiiboHeadBox; + private Box _amiiboSeriesBox; + private Label _amiiboSeriesLabel; private ComboBoxText _amiiboSeriesComboBox; - private Box _amiiboCharsBox; - private Label _amiiboCharsLabel; + private Box _amiiboCharsBox; + private Label _amiiboCharsLabel; private ComboBoxText _amiiboCharsComboBox; - private CheckButton _showAllCheckBox; - private Image _amiiboImage; - private Label _gameUsageLabel; + private CheckButton _showAllCheckBox; + private Image _amiiboImage; + private Label _gameUsageLabel; private void InitializeComponent() { -#pragma warning disable CS0612 - // // AmiiboWindow // - CanFocus = false; - Resizable = false; - Modal = true; + CanFocus = false; + Resizable = false; + Modal = true; WindowPosition = WindowPosition.Center; - DefaultWidth = 600; - DefaultHeight = 470; - TypeHint = Gdk.WindowTypeHint.Dialog; + DefaultWidth = 600; + DefaultHeight = 470; + TypeHint = Gdk.WindowTypeHint.Dialog; // // _mainBox @@ -46,8 +44,8 @@ namespace Ryujinx.Ui.Windows // _buttonBox = new ButtonBox(Orientation.Horizontal) { - Margin = 20, - LayoutStyle = ButtonBoxStyle.End + Margin = 20, + LayoutStyle = ButtonBoxStyle.End, }; // @@ -55,10 +53,10 @@ namespace Ryujinx.Ui.Windows // _scanButton = new Button() { - Label = "Scan It!", - CanFocus = true, + Label = "Scan It!", + CanFocus = true, ReceivesDefault = true, - MarginLeft = 10 + MarginStart = 10, }; _scanButton.Clicked += ScanButton_Pressed; @@ -67,8 +65,8 @@ namespace Ryujinx.Ui.Windows // _randomUuidCheckBox = new CheckButton() { - Label = "Hack: Use Random Tag Uuid", - TooltipText = "This allows multiple scans of a single Amiibo.\n(used in The Legend of Zelda: Breath of the Wild)" + Label = "Hack: Use Random Tag Uuid", + TooltipText = "This allows multiple scans of a single Amiibo.\n(used in The Legend of Zelda: Breath of the Wild)", }; // @@ -76,10 +74,10 @@ namespace Ryujinx.Ui.Windows // _cancelButton = new Button() { - Label = "Cancel", - CanFocus = true, + Label = "Cancel", + CanFocus = true, ReceivesDefault = true, - MarginLeft = 10 + MarginStart = 10, }; _cancelButton.Clicked += CancelButton_Pressed; @@ -94,7 +92,7 @@ namespace Ryujinx.Ui.Windows _amiiboHeadBox = new Box(Orientation.Horizontal, 0) { Margin = 20, - Hexpand = true + Hexpand = true, }; // @@ -102,7 +100,7 @@ namespace Ryujinx.Ui.Windows // _amiiboSeriesBox = new Box(Orientation.Horizontal, 0) { - Hexpand = true + Hexpand = true, }; // @@ -120,7 +118,7 @@ namespace Ryujinx.Ui.Windows // _amiiboCharsBox = new Box(Orientation.Horizontal, 0) { - Hexpand = true + Hexpand = true, }; // @@ -138,7 +136,7 @@ namespace Ryujinx.Ui.Windows // _showAllCheckBox = new CheckButton() { - Label = "Show All Amiibo" + Label = "Show All Amiibo", }; // @@ -147,7 +145,7 @@ namespace Ryujinx.Ui.Windows _amiiboImage = new Image() { HeightRequest = 350, - WidthRequest = 350 + WidthRequest = 350, }; // @@ -155,11 +153,9 @@ namespace Ryujinx.Ui.Windows // _gameUsageLabel = new Label("") { - MarginTop = 20 + MarginTop = 20, }; -#pragma warning restore CS0612 - ShowComponent(); } @@ -191,4 +187,4 @@ namespace Ryujinx.Ui.Windows ShowAll(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Ui/Windows/AmiiboWindow.cs b/src/Ryujinx/Ui/Windows/AmiiboWindow.cs index 5bf69d5af..4bbaaaaa4 100644 --- a/src/Ryujinx/Ui/Windows/AmiiboWindow.cs +++ b/src/Ryujinx/Ui/Windows/AmiiboWindow.cs @@ -14,21 +14,19 @@ using System.Net.Http; using System.Reflection; using System.Text; using System.Threading.Tasks; -using AmiiboApi = Ryujinx.Ui.Common.Models.Amiibo.AmiiboApi; -using AmiiboJsonSerializerContext = Ryujinx.Ui.Common.Models.Amiibo.AmiiboJsonSerializerContext; namespace Ryujinx.Ui.Windows { public partial class AmiiboWindow : Window { - private const string DEFAULT_JSON = "{ \"amiibo\": [] }"; + private const string DefaultJson = "{ \"amiibo\": [] }"; public string AmiiboId { get; private set; } - public int DeviceId { get; set; } - public string TitleId { get; set; } - public string LastScannedAmiiboId { get; set; } - public bool LastScannedAmiiboShowAll { get; set; } + public int DeviceId { get; set; } + public string TitleId { get; set; } + public string LastScannedAmiiboId { get; set; } + public bool LastScannedAmiiboShowAll { get; set; } public ResponseType Response { get; private set; } @@ -41,13 +39,13 @@ namespace Ryujinx.Ui.Windows } private readonly HttpClient _httpClient; - private readonly string _amiiboJsonPath; + private readonly string _amiiboJsonPath; private readonly byte[] _amiiboLogoBytes; private List _amiiboList; - private static readonly AmiiboJsonSerializerContext SerializerContext = new(JsonHelper.GetDefaultSerializerOptions()); + private static readonly AmiiboJsonSerializerContext _serializerContext = new(JsonHelper.GetDefaultSerializerOptions()); public AmiiboWindow() : base($"Ryujinx {Program.Version} - Amiibo") { @@ -57,18 +55,18 @@ namespace Ryujinx.Ui.Windows _httpClient = new HttpClient() { - Timeout = TimeSpan.FromSeconds(30) + Timeout = TimeSpan.FromSeconds(30), }; Directory.CreateDirectory(System.IO.Path.Join(AppDataManager.BaseDirPath, "system", "amiibo")); _amiiboJsonPath = System.IO.Path.Join(AppDataManager.BaseDirPath, "system", "amiibo", "Amiibo.json"); - _amiiboList = new List(); + _amiiboList = new List(); - _amiiboLogoBytes = EmbeddedResources.Read("Ryujinx.Ui.Common/Resources/Logo_Amiibo.png"); + _amiiboLogoBytes = EmbeddedResources.Read("Ryujinx.Ui.Common/Resources/Logo_Amiibo.png"); _amiiboImage.Pixbuf = new Gdk.Pixbuf(_amiiboLogoBytes); - _scanButton.Sensitive = false; + _scanButton.Sensitive = false; _randomUuidCheckBox.Sensitive = false; _ = LoadContentAsync(); @@ -76,13 +74,13 @@ namespace Ryujinx.Ui.Windows private async Task LoadContentAsync() { - string amiiboJsonString = DEFAULT_JSON; + string amiiboJsonString = DefaultJson; if (File.Exists(_amiiboJsonPath)) { amiiboJsonString = await File.ReadAllTextAsync(_amiiboJsonPath); - if (await NeedsUpdate(JsonHelper.Deserialize(amiiboJsonString, SerializerContext.AmiiboJson).LastUpdated)) + if (await NeedsUpdate(JsonHelper.Deserialize(amiiboJsonString, _serializerContext.AmiiboJson).LastUpdated)) { amiiboJsonString = await DownloadAmiiboJson(); } @@ -103,7 +101,7 @@ namespace Ryujinx.Ui.Windows } } - _amiiboList = JsonHelper.Deserialize(amiiboJsonString, SerializerContext.AmiiboJson).Amiibo; + _amiiboList = JsonHelper.Deserialize(amiiboJsonString, _serializerContext.AmiiboJson).Amiibo; _amiiboList = _amiiboList.OrderBy(amiibo => amiibo.AmiiboSeries).ToList(); if (LastScannedAmiiboShowAll) @@ -118,7 +116,7 @@ namespace Ryujinx.Ui.Windows private void ParseAmiiboData() { - List comboxItemList = new List(); + List comboxItemList = new(); for (int i = 0; i < _amiiboList.Count; i++) { @@ -149,7 +147,7 @@ namespace Ryujinx.Ui.Windows } _amiiboSeriesComboBox.Changed += SeriesComboBox_Changed; - _amiiboCharsComboBox.Changed += CharacterComboBox_Changed; + _amiiboCharsComboBox.Changed += CharacterComboBox_Changed; if (LastScannedAmiiboId != "") { @@ -219,7 +217,7 @@ namespace Ryujinx.Ui.Windows Close(); } - return DEFAULT_JSON; + return DefaultJson; } private async Task UpdateAmiiboPreview(string imageUrl) @@ -228,14 +226,14 @@ namespace Ryujinx.Ui.Windows if (response.IsSuccessStatusCode) { - byte[] amiiboPreviewBytes = await response.Content.ReadAsByteArrayAsync(); - Gdk.Pixbuf amiiboPreview = new Gdk.Pixbuf(amiiboPreviewBytes); + byte[] amiiboPreviewBytes = await response.Content.ReadAsByteArrayAsync(); + Gdk.Pixbuf amiiboPreview = new(amiiboPreviewBytes); - float ratio = Math.Min((float)_amiiboImage.AllocatedWidth / amiiboPreview.Width, + float ratio = Math.Min((float)_amiiboImage.AllocatedWidth / amiiboPreview.Width, (float)_amiiboImage.AllocatedHeight / amiiboPreview.Height); int resizeHeight = (int)(amiiboPreview.Height * ratio); - int resizeWidth = (int)(amiiboPreview.Width * ratio); + int resizeWidth = (int)(amiiboPreview.Width * ratio); _amiiboImage.Pixbuf = amiiboPreview.ScaleSimple(resizeWidth, resizeHeight, Gdk.InterpType.Bilinear); } @@ -245,7 +243,7 @@ namespace Ryujinx.Ui.Windows } } - private void ShowInfoDialog() + private static void ShowInfoDialog() { GtkDialog.CreateInfoDialog($"Amiibo API", "Unable to connect to Amiibo API server. The service may be down or you may need to verify your internet connection is online."); } @@ -261,7 +259,7 @@ namespace Ryujinx.Ui.Windows List amiiboSortedList = _amiiboList.Where(amiibo => amiibo.AmiiboSeries == _amiiboSeriesComboBox.ActiveId).OrderBy(amiibo => amiibo.Name).ToList(); - List comboxItemList = new List(); + List comboxItemList = new(); for (int i = 0; i < amiiboSortedList.Count; i++) { @@ -295,7 +293,7 @@ namespace Ryujinx.Ui.Windows _amiiboCharsComboBox.Active = 0; - _scanButton.Sensitive = true; + _scanButton.Sensitive = true; _randomUuidCheckBox.Sensitive = true; } @@ -346,12 +344,12 @@ namespace Ryujinx.Ui.Windows _amiiboImage.Pixbuf = new Gdk.Pixbuf(_amiiboLogoBytes); _amiiboSeriesComboBox.Changed -= SeriesComboBox_Changed; - _amiiboCharsComboBox.Changed -= CharacterComboBox_Changed; + _amiiboCharsComboBox.Changed -= CharacterComboBox_Changed; _amiiboSeriesComboBox.RemoveAll(); _amiiboCharsComboBox.RemoveAll(); - _scanButton.Sensitive = false; + _scanButton.Sensitive = false; _randomUuidCheckBox.Sensitive = false; new Task(() => ParseAmiiboData()).Start(); @@ -368,8 +366,8 @@ namespace Ryujinx.Ui.Windows private void CancelButton_Pressed(object sender, EventArgs args) { - AmiiboId = ""; - LastScannedAmiiboId = ""; + AmiiboId = ""; + LastScannedAmiiboId = ""; LastScannedAmiiboShowAll = false; Response = ResponseType.Cancel; @@ -384,4 +382,4 @@ namespace Ryujinx.Ui.Windows base.Dispose(disposing); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Ui/Windows/AvatarWindow.cs b/src/Ryujinx/Ui/Windows/AvatarWindow.cs index 0cda890f5..3940f17d6 100644 --- a/src/Ryujinx/Ui/Windows/AvatarWindow.cs +++ b/src/Ryujinx/Ui/Windows/AvatarWindow.cs @@ -18,7 +18,6 @@ using System.Buffers.Binary; using System.Collections.Generic; using System.IO; using System.Reflection; - using Image = SixLabors.ImageSharp.Image; namespace Ryujinx.Ui.Windows @@ -26,23 +25,23 @@ namespace Ryujinx.Ui.Windows public class AvatarWindow : Window { public byte[] SelectedProfileImage; - public bool NewUser; + public bool NewUser; - private static Dictionary _avatarDict = new Dictionary(); + private static readonly Dictionary _avatarDict = new(); - private ListStore _listStore; - private IconView _iconView; - private Button _setBackgroungColorButton; - private Gdk.RGBA _backgroundColor; + private readonly ListStore _listStore; + private readonly IconView _iconView; + private readonly Button _setBackgroungColorButton; + private Gdk.RGBA _backgroundColor; public AvatarWindow() : base($"Ryujinx {Program.Version} - Manage Accounts - Avatar") { Icon = new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Logo_Ryujinx.png"); - CanFocus = false; + CanFocus = false; Resizable = false; - Modal = true; - TypeHint = Gdk.WindowTypeHint.Dialog; + Modal = true; + TypeHint = Gdk.WindowTypeHint.Dialog; SetDefaultSize(740, 400); SetPosition(WindowPosition.Center); @@ -50,54 +49,56 @@ namespace Ryujinx.Ui.Windows Box vbox = new(Orientation.Vertical, 0); Add(vbox); - ScrolledWindow scrolledWindow = new ScrolledWindow + ScrolledWindow scrolledWindow = new() { - ShadowType = ShadowType.EtchedIn + ShadowType = ShadowType.EtchedIn, }; scrolledWindow.SetPolicy(PolicyType.Automatic, PolicyType.Automatic); Box hbox = new(Orientation.Horizontal, 0); - Button chooseButton = new Button() + Button chooseButton = new() { - Label = "Choose", - CanFocus = true, - ReceivesDefault = true + Label = "Choose", + CanFocus = true, + ReceivesDefault = true, }; chooseButton.Clicked += ChooseButton_Pressed; _setBackgroungColorButton = new Button() { - Label = "Set Background Color", - CanFocus = true + Label = "Set Background Color", + CanFocus = true, }; _setBackgroungColorButton.Clicked += SetBackgroungColorButton_Pressed; - _backgroundColor.Red = 1; + _backgroundColor.Red = 1; _backgroundColor.Green = 1; - _backgroundColor.Blue = 1; + _backgroundColor.Blue = 1; _backgroundColor.Alpha = 1; - Button closeButton = new Button() + Button closeButton = new() { - Label = "Close", - CanFocus = true + Label = "Close", + CanFocus = true, }; closeButton.Clicked += CloseButton_Pressed; - vbox.PackStart(scrolledWindow, true, true, 0); - hbox.PackStart(chooseButton, true, true, 0); - hbox.PackStart(_setBackgroungColorButton, true, true, 0); - hbox.PackStart(closeButton, true, true, 0); - vbox.PackStart(hbox, false, false, 0); + vbox.PackStart(scrolledWindow, true, true, 0); + hbox.PackStart(chooseButton, true, true, 0); + hbox.PackStart(_setBackgroungColorButton, true, true, 0); + hbox.PackStart(closeButton, true, true, 0); + vbox.PackStart(hbox, false, false, 0); _listStore = new ListStore(typeof(string), typeof(Gdk.Pixbuf)); _listStore.SetSortColumnId(0, SortType.Ascending); - _iconView = new IconView(_listStore); - _iconView.ItemWidth = 64; - _iconView.ItemPadding = 10; - _iconView.PixbufColumn = 1; + _iconView = new IconView(_listStore) + { + ItemWidth = 64, + ItemPadding = 10, + PixbufColumn = 1, + }; _iconView.SelectionChanged += IconView_SelectionChanged; @@ -118,39 +119,36 @@ namespace Ryujinx.Ui.Windows } string contentPath = contentManager.GetInstalledContentPath(0x010000000000080A, StorageId.BuiltInSystem, NcaContentType.Data); - string avatarPath = virtualFileSystem.SwitchPathToSystemPath(contentPath); + string avatarPath = virtualFileSystem.SwitchPathToSystemPath(contentPath); if (!string.IsNullOrWhiteSpace(avatarPath)) { - using (IStorage ncaFileStream = new LocalStorage(avatarPath, FileAccess.Read, FileMode.Open)) + using IStorage ncaFileStream = new LocalStorage(avatarPath, FileAccess.Read, FileMode.Open); + + Nca nca = new(virtualFileSystem.KeySet, ncaFileStream); + IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid); + + foreach (var item in romfs.EnumerateEntries()) { - Nca nca = new Nca(virtualFileSystem.KeySet, ncaFileStream); - IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid); + // TODO: Parse DatabaseInfo.bin and table.bin files for more accuracy. - foreach (var item in romfs.EnumerateEntries()) + if (item.Type == DirectoryEntryType.File && item.FullPath.Contains("chara") && item.FullPath.Contains("szs")) { - // TODO: Parse DatabaseInfo.bin and table.bin files for more accuracy. + using var file = new UniqueRef(); - if (item.Type == DirectoryEntryType.File && item.FullPath.Contains("chara") && item.FullPath.Contains("szs")) - { - using var file = new UniqueRef(); + romfs.OpenFile(ref file.Ref, ("/" + item.FullPath).ToU8Span(), OpenMode.Read).ThrowIfFailure(); - romfs.OpenFile(ref file.Ref, ("/" + item.FullPath).ToU8Span(), OpenMode.Read).ThrowIfFailure(); + using MemoryStream stream = MemoryStreamManager.Shared.GetStream(); + using MemoryStream streamPng = MemoryStreamManager.Shared.GetStream(); + file.Get.AsStream().CopyTo(stream); - using (MemoryStream stream = MemoryStreamManager.Shared.GetStream()) - using (MemoryStream streamPng = MemoryStreamManager.Shared.GetStream()) - { - file.Get.AsStream().CopyTo(stream); + stream.Position = 0; - stream.Position = 0; + Image avatarImage = Image.LoadPixelData(DecompressYaz0(stream), 256, 256); - Image avatarImage = Image.LoadPixelData(DecompressYaz0(stream), 256, 256); + avatarImage.SaveAsPng(streamPng); - avatarImage.SaveAsPng(streamPng); - - _avatarDict.Add(item.FullPath, streamPng.ToArray()); - } - } + _avatarDict.Add(item.FullPath, streamPng.ToArray()); } } } @@ -165,23 +163,24 @@ namespace Ryujinx.Ui.Windows _listStore.AppendValues(avatar.Key, new Gdk.Pixbuf(ProcessImage(avatar.Value), 96, 96)); } - _iconView.SelectPath(new TreePath(new int[] { 0 })); + _iconView.SelectPath(new TreePath(new[] { 0 })); } private byte[] ProcessImage(byte[] data) { - using (MemoryStream streamJpg = MemoryStreamManager.Shared.GetStream()) - { - Image avatarImage = Image.Load(data, new PngDecoder()); + using MemoryStream streamJpg = MemoryStreamManager.Shared.GetStream(); - avatarImage.Mutate(x => x.BackgroundColor(new Rgba32((byte)(_backgroundColor.Red * 255), - (byte)(_backgroundColor.Green * 255), - (byte)(_backgroundColor.Blue * 255), - (byte)(_backgroundColor.Alpha * 255)))); - avatarImage.SaveAsJpeg(streamJpg); + Image avatarImage = Image.Load(data, new PngDecoder()); - return streamJpg.ToArray(); - } + avatarImage.Mutate(x => x.BackgroundColor(new Rgba32( + (byte)(_backgroundColor.Red * 255), + (byte)(_backgroundColor.Green * 255), + (byte)(_backgroundColor.Blue * 255), + (byte)(_backgroundColor.Alpha * 255) + ))); + avatarImage.SaveAsJpeg(streamJpg); + + return streamJpg.ToArray(); } private void CloseButton_Pressed(object sender, EventArgs e) @@ -203,20 +202,19 @@ namespace Ryujinx.Ui.Windows private void SetBackgroungColorButton_Pressed(object sender, EventArgs e) { - using (ColorChooserDialog colorChooserDialog = new ColorChooserDialog("Set Background Color", this)) + using ColorChooserDialog colorChooserDialog = new("Set Background Color", this); + + colorChooserDialog.UseAlpha = false; + colorChooserDialog.Rgba = _backgroundColor; + + if (colorChooserDialog.Run() == (int)ResponseType.Ok) { - colorChooserDialog.UseAlpha = false; - colorChooserDialog.Rgba = _backgroundColor; - - if (colorChooserDialog.Run() == (int)ResponseType.Ok) - { - _backgroundColor = colorChooserDialog.Rgba; + _backgroundColor = colorChooserDialog.Rgba; - ProcessAvatars(); - } - - colorChooserDialog.Hide(); + ProcessAvatars(); } + + colorChooserDialog.Hide(); } private void ChooseButton_Pressed(object sender, EventArgs e) @@ -226,69 +224,68 @@ namespace Ryujinx.Ui.Windows private static byte[] DecompressYaz0(Stream stream) { - using (BinaryReader reader = new BinaryReader(stream)) + using BinaryReader reader = new(stream); + + reader.ReadInt32(); // Magic + + uint decodedLength = BinaryPrimitives.ReverseEndianness(reader.ReadUInt32()); + + reader.ReadInt64(); // Padding + + byte[] input = new byte[stream.Length - stream.Position]; + stream.Read(input, 0, input.Length); + + long inputOffset = 0; + + byte[] output = new byte[decodedLength]; + long outputOffset = 0; + + ushort mask = 0; + byte header = 0; + + while (outputOffset < decodedLength) { - reader.ReadInt32(); // Magic - - uint decodedLength = BinaryPrimitives.ReverseEndianness(reader.ReadUInt32()); - - reader.ReadInt64(); // Padding - - byte[] input = new byte[stream.Length - stream.Position]; - stream.Read(input, 0, input.Length); - - long inputOffset = 0; - - byte[] output = new byte[decodedLength]; - long outputOffset = 0; - - ushort mask = 0; - byte header = 0; - - while (outputOffset < decodedLength) + if ((mask >>= 1) == 0) { - if ((mask >>= 1) == 0) + header = input[inputOffset++]; + mask = 0x80; + } + + if ((header & mask) > 0) + { + if (outputOffset == output.Length) { - header = input[inputOffset++]; - mask = 0x80; + break; } - if ((header & mask) > 0) - { - if (outputOffset == output.Length) - { - break; - } + output[outputOffset++] = input[inputOffset++]; + } + else + { + byte byte1 = input[inputOffset++]; + byte byte2 = input[inputOffset++]; - output[outputOffset++] = input[inputOffset++]; + int dist = ((byte1 & 0xF) << 8) | byte2; + int position = (int)outputOffset - (dist + 1); + + int length = byte1 >> 4; + if (length == 0) + { + length = input[inputOffset++] + 0x12; } else { - byte byte1 = input[inputOffset++]; - byte byte2 = input[inputOffset++]; + length += 2; + } - int dist = ((byte1 & 0xF) << 8) | byte2; - int position = (int)outputOffset - (dist + 1); - - int length = byte1 >> 4; - if (length == 0) - { - length = input[inputOffset++] + 0x12; - } - else - { - length += 2; - } - - while (length-- > 0) - { - output[outputOffset++] = output[position++]; - } + while (length-- > 0) + { + output[outputOffset++] = output[position++]; } } - - return output; } + + return output; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Ui/Windows/CheatWindow.cs b/src/Ryujinx/Ui/Windows/CheatWindow.cs index 32df2c0c2..1eca732b2 100644 --- a/src/Ryujinx/Ui/Windows/CheatWindow.cs +++ b/src/Ryujinx/Ui/Windows/CheatWindow.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; - using GUI = Gtk.Builder.ObjectAttribute; namespace Ryujinx.Ui.Windows @@ -16,11 +15,11 @@ namespace Ryujinx.Ui.Windows private readonly string _enabledCheatsPath; private readonly bool _noCheatsFound; -#pragma warning disable CS0649, IDE0044 - [GUI] Label _baseTitleInfoLabel; +#pragma warning disable CS0649, IDE0044 // Field is never assigned to, Add readonly modifier + [GUI] Label _baseTitleInfoLabel; [GUI] TextView _buildIdTextView; [GUI] TreeView _cheatTreeView; - [GUI] Button _saveButton; + [GUI] Button _saveButton; #pragma warning restore CS0649, IDE0044 public CheatWindow(VirtualFileSystem virtualFileSystem, ulong titleId, string titleName, string titlePath) : this(new Builder("Ryujinx.Ui.Windows.CheatWindow.glade"), virtualFileSystem, titleId, titleName, titlePath) { } @@ -31,14 +30,14 @@ namespace Ryujinx.Ui.Windows _baseTitleInfoLabel.Text = $"Cheats Available for {titleName} [{titleId:X16}]"; _buildIdTextView.Buffer.Text = $"BuildId: {ApplicationData.GetApplicationBuildId(virtualFileSystem, titlePath)}"; - string modsBasePath = ModLoader.GetModsBasePath(); + string modsBasePath = ModLoader.GetModsBasePath(); string titleModsPath = ModLoader.GetTitleDir(modsBasePath, titleId.ToString("X16")); _enabledCheatsPath = System.IO.Path.Combine(titleModsPath, "cheats", "enabled.txt"); _cheatTreeView.Model = new TreeStore(typeof(bool), typeof(string), typeof(string), typeof(string)); - CellRendererToggle enableToggle = new CellRendererToggle(); + CellRendererToggle enableToggle = new(); enableToggle.Toggled += (sender, args) => { _cheatTreeView.Model.GetIter(out TreeIter treeIter, new TreePath(args.Path)); @@ -62,7 +61,7 @@ namespace Ryujinx.Ui.Windows var buildIdColumn = _cheatTreeView.AppendColumn("Build Id", new CellRendererText(), "text", 3); buildIdColumn.Visible = false; - string[] enabled = { }; + string[] enabled = Array.Empty(); if (File.Exists(_enabledCheatsPath)) { @@ -90,7 +89,7 @@ namespace Ryujinx.Ui.Windows parentIter = ((TreeStore)_cheatTreeView.Model).AppendValues(false, buildId, parentPath, ""); } - string cleanName = cheat.Name.Substring(1, cheat.Name.Length - 8); + string cleanName = cheat.Name[1..^7]; ((TreeStore)_cheatTreeView.Model).AppendValues(parentIter, enabled.Contains($"{buildId}-{cheat.Name}"), cleanName, "", buildId); cheatAdded++; @@ -116,7 +115,7 @@ namespace Ryujinx.Ui.Windows return; } - List enabledCheats = new List(); + List enabledCheats = new(); if (_cheatTreeView.Model.GetIterFirst(out TreeIter parentIter)) { diff --git a/src/Ryujinx/Ui/Windows/ControllerWindow.cs b/src/Ryujinx/Ui/Windows/ControllerWindow.cs index 9b4befd85..ebf22ab60 100644 --- a/src/Ryujinx/Ui/Windows/ControllerWindow.cs +++ b/src/Ryujinx/Ui/Windows/ControllerWindow.cs @@ -31,47 +31,47 @@ namespace Ryujinx.Ui.Windows private bool _isWaitingForInput; -#pragma warning disable CS0649, IDE0044 - [GUI] Adjustment _controllerStrongRumble; - [GUI] Adjustment _controllerWeakRumble; - [GUI] Adjustment _controllerDeadzoneLeft; - [GUI] Adjustment _controllerDeadzoneRight; - [GUI] Adjustment _controllerRangeLeft; - [GUI] Adjustment _controllerRangeRight; - [GUI] Adjustment _controllerTriggerThreshold; - [GUI] Adjustment _slotNumber; - [GUI] Adjustment _altSlotNumber; - [GUI] Adjustment _sensitivity; - [GUI] Adjustment _gyroDeadzone; - [GUI] CheckButton _enableMotion; - [GUI] CheckButton _enableCemuHook; - [GUI] CheckButton _mirrorInput; - [GUI] Entry _dsuServerHost; - [GUI] Entry _dsuServerPort; +#pragma warning disable CS0649, IDE0044 // Field is never assigned to, Add readonly modifier + [GUI] Adjustment _controllerStrongRumble; + [GUI] Adjustment _controllerWeakRumble; + [GUI] Adjustment _controllerDeadzoneLeft; + [GUI] Adjustment _controllerDeadzoneRight; + [GUI] Adjustment _controllerRangeLeft; + [GUI] Adjustment _controllerRangeRight; + [GUI] Adjustment _controllerTriggerThreshold; + [GUI] Adjustment _slotNumber; + [GUI] Adjustment _altSlotNumber; + [GUI] Adjustment _sensitivity; + [GUI] Adjustment _gyroDeadzone; + [GUI] CheckButton _enableMotion; + [GUI] CheckButton _enableCemuHook; + [GUI] CheckButton _mirrorInput; + [GUI] Entry _dsuServerHost; + [GUI] Entry _dsuServerPort; [GUI] ComboBoxText _inputDevice; [GUI] ComboBoxText _profile; - [GUI] Box _settingsBox; - [GUI] Box _motionAltBox; - [GUI] Box _motionBox; - [GUI] Box _dsuServerHostBox; - [GUI] Box _dsuServerPortBox; - [GUI] Box _motionControllerSlot; - [GUI] Grid _leftStickKeyboard; - [GUI] Grid _leftStickController; - [GUI] Box _deadZoneLeftBox; - [GUI] Box _rangeLeftBox; - [GUI] Grid _rightStickKeyboard; - [GUI] Grid _rightStickController; - [GUI] Box _deadZoneRightBox; - [GUI] Box _rangeRightBox; - [GUI] Grid _leftSideTriggerBox; - [GUI] Grid _rightSideTriggerBox; - [GUI] Box _triggerThresholdBox; + [GUI] Box _settingsBox; + [GUI] Box _motionAltBox; + [GUI] Box _motionBox; + [GUI] Box _dsuServerHostBox; + [GUI] Box _dsuServerPortBox; + [GUI] Box _motionControllerSlot; + [GUI] Grid _leftStickKeyboard; + [GUI] Grid _leftStickController; + [GUI] Box _deadZoneLeftBox; + [GUI] Box _rangeLeftBox; + [GUI] Grid _rightStickKeyboard; + [GUI] Grid _rightStickController; + [GUI] Box _deadZoneRightBox; + [GUI] Box _rangeRightBox; + [GUI] Grid _leftSideTriggerBox; + [GUI] Grid _rightSideTriggerBox; + [GUI] Box _triggerThresholdBox; [GUI] ComboBoxText _controllerType; [GUI] ToggleButton _lStick; - [GUI] CheckButton _invertLStickX; - [GUI] CheckButton _invertLStickY; - [GUI] CheckButton _rotateL90CW; + [GUI] CheckButton _invertLStickX; + [GUI] CheckButton _invertLStickY; + [GUI] CheckButton _rotateL90CW; [GUI] ToggleButton _lStickUp; [GUI] ToggleButton _lStickDown; [GUI] ToggleButton _lStickLeft; @@ -85,9 +85,9 @@ namespace Ryujinx.Ui.Windows [GUI] ToggleButton _l; [GUI] ToggleButton _zL; [GUI] ToggleButton _rStick; - [GUI] CheckButton _invertRStickX; - [GUI] CheckButton _invertRStickY; - [GUI] CheckButton _rotateR90CW; + [GUI] CheckButton _invertRStickX; + [GUI] CheckButton _invertRStickY; + [GUI] CheckButton _rotateR90CW; [GUI] ToggleButton _rStickUp; [GUI] ToggleButton _rStickDown; [GUI] ToggleButton _rStickLeft; @@ -104,18 +104,18 @@ namespace Ryujinx.Ui.Windows [GUI] ToggleButton _lSr; [GUI] ToggleButton _rSl; [GUI] ToggleButton _rSr; - [GUI] Image _controllerImage; - [GUI] CheckButton _enableRumble; - [GUI] Box _rumbleBox; + [GUI] Image _controllerImage; + [GUI] CheckButton _enableRumble; + [GUI] Box _rumbleBox; #pragma warning restore CS0649, IDE0044 - private MainWindow _mainWindow; - private IGamepadDriver _gtk3KeyboardDriver; + private readonly MainWindow _mainWindow; + private readonly IGamepadDriver _gtk3KeyboardDriver; private IGamepad _selectedGamepad; private bool _mousePressed; private bool _middleMousePressed; - private static readonly InputConfigJsonSerializerContext SerializerContext = new(JsonHelper.GetDefaultSerializerOptions()); + private static readonly InputConfigJsonSerializerContext _serializerContext = new(JsonHelper.GetDefaultSerializerOptions()); public ControllerWindow(MainWindow mainWindow, PlayerIndex controllerId) : this(mainWindow, new Builder("Ryujinx.Ui.Windows.ControllerWindow.glade"), controllerId) { } @@ -152,36 +152,36 @@ namespace Ryujinx.Ui.Windows _controllerType.Active = 0; // Set initial value to first in list. // Bind Events. - _lStick.Clicked += ButtonForStick_Pressed; - _lStickUp.Clicked += Button_Pressed; - _lStickDown.Clicked += Button_Pressed; - _lStickLeft.Clicked += Button_Pressed; - _lStickRight.Clicked += Button_Pressed; - _lStickButton.Clicked += Button_Pressed; - _dpadUp.Clicked += Button_Pressed; - _dpadDown.Clicked += Button_Pressed; - _dpadLeft.Clicked += Button_Pressed; - _dpadRight.Clicked += Button_Pressed; - _minus.Clicked += Button_Pressed; - _l.Clicked += Button_Pressed; - _zL.Clicked += Button_Pressed; - _lSl.Clicked += Button_Pressed; - _lSr.Clicked += Button_Pressed; - _rStick.Clicked += ButtonForStick_Pressed; - _rStickUp.Clicked += Button_Pressed; - _rStickDown.Clicked += Button_Pressed; - _rStickLeft.Clicked += Button_Pressed; - _rStickRight.Clicked += Button_Pressed; - _rStickButton.Clicked += Button_Pressed; - _a.Clicked += Button_Pressed; - _b.Clicked += Button_Pressed; - _x.Clicked += Button_Pressed; - _y.Clicked += Button_Pressed; - _plus.Clicked += Button_Pressed; - _r.Clicked += Button_Pressed; - _zR.Clicked += Button_Pressed; - _rSl.Clicked += Button_Pressed; - _rSr.Clicked += Button_Pressed; + _lStick.Clicked += ButtonForStick_Pressed; + _lStickUp.Clicked += Button_Pressed; + _lStickDown.Clicked += Button_Pressed; + _lStickLeft.Clicked += Button_Pressed; + _lStickRight.Clicked += Button_Pressed; + _lStickButton.Clicked += Button_Pressed; + _dpadUp.Clicked += Button_Pressed; + _dpadDown.Clicked += Button_Pressed; + _dpadLeft.Clicked += Button_Pressed; + _dpadRight.Clicked += Button_Pressed; + _minus.Clicked += Button_Pressed; + _l.Clicked += Button_Pressed; + _zL.Clicked += Button_Pressed; + _lSl.Clicked += Button_Pressed; + _lSr.Clicked += Button_Pressed; + _rStick.Clicked += ButtonForStick_Pressed; + _rStickUp.Clicked += Button_Pressed; + _rStickDown.Clicked += Button_Pressed; + _rStickLeft.Clicked += Button_Pressed; + _rStickRight.Clicked += Button_Pressed; + _rStickButton.Clicked += Button_Pressed; + _a.Clicked += Button_Pressed; + _b.Clicked += Button_Pressed; + _x.Clicked += Button_Pressed; + _y.Clicked += Button_Pressed; + _plus.Clicked += Button_Pressed; + _r.Clicked += Button_Pressed; + _zR.Clicked += Button_Pressed; + _rSl.Clicked += Button_Pressed; + _rSr.Clicked += Button_Pressed; _enableCemuHook.Clicked += CemuHookCheckButtonPressed; // Setup current values. @@ -197,10 +197,7 @@ namespace Ryujinx.Ui.Windows mainWindow.InputManager.GamepadDriver.OnGamepadConnected += HandleOnGamepadConnected; mainWindow.InputManager.GamepadDriver.OnGamepadDisconnected += HandleOnGamepadDisconnected; - if (_mainWindow.RendererWidget != null) - { - _mainWindow.RendererWidget.NpadManager.BlockInputUpdates(); - } + _mainWindow.RendererWidget?.NpadManager.BlockInputUpdates(); } private void CemuHookCheckButtonPressed(object sender, EventArgs e) @@ -229,10 +226,7 @@ namespace Ryujinx.Ui.Windows _mainWindow.InputManager.GamepadDriver.OnGamepadConnected -= HandleOnGamepadConnected; _mainWindow.InputManager.GamepadDriver.OnGamepadDisconnected -= HandleOnGamepadDisconnected; - if (_mainWindow.RendererWidget != null) - { - _mainWindow.RendererWidget.NpadManager.UnblockInputUpdates(); - } + _mainWindow.RendererWidget?.NpadManager.UnblockInputUpdates(); _selectedGamepad?.Dispose(); @@ -384,62 +378,62 @@ namespace Ryujinx.Ui.Windows _controllerImage.Pixbuf = _controllerType.ActiveId switch { "ProController" => new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Controller_ProCon.svg", 400, 400), - "JoyconLeft" => new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Controller_JoyConLeft.svg", 400, 500), - "JoyconRight" => new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Controller_JoyConRight.svg", 400, 500), - _ => new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Controller_JoyConPair.svg", 400, 500), + "JoyconLeft" => new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Controller_JoyConLeft.svg", 400, 500), + "JoyconRight" => new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Controller_JoyConRight.svg", 400, 500), + _ => new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Controller_JoyConPair.svg", 400, 500), }; } } private void ClearValues() { - _lStick.Label = "Unbound"; - _lStickUp.Label = "Unbound"; - _lStickDown.Label = "Unbound"; - _lStickLeft.Label = "Unbound"; - _lStickRight.Label = "Unbound"; - _lStickButton.Label = "Unbound"; - _dpadUp.Label = "Unbound"; - _dpadDown.Label = "Unbound"; - _dpadLeft.Label = "Unbound"; - _dpadRight.Label = "Unbound"; - _minus.Label = "Unbound"; - _l.Label = "Unbound"; - _zL.Label = "Unbound"; - _lSl.Label = "Unbound"; - _lSr.Label = "Unbound"; - _rStick.Label = "Unbound"; - _rStickUp.Label = "Unbound"; - _rStickDown.Label = "Unbound"; - _rStickLeft.Label = "Unbound"; - _rStickRight.Label = "Unbound"; - _rStickButton.Label = "Unbound"; - _a.Label = "Unbound"; - _b.Label = "Unbound"; - _x.Label = "Unbound"; - _y.Label = "Unbound"; - _plus.Label = "Unbound"; - _r.Label = "Unbound"; - _zR.Label = "Unbound"; - _rSl.Label = "Unbound"; - _rSr.Label = "Unbound"; - _controllerStrongRumble.Value = 1; - _controllerWeakRumble.Value = 1; - _controllerDeadzoneLeft.Value = 0; - _controllerDeadzoneRight.Value = 0; - _controllerRangeLeft.Value = 1; - _controllerRangeRight.Value = 1; + _lStick.Label = "Unbound"; + _lStickUp.Label = "Unbound"; + _lStickDown.Label = "Unbound"; + _lStickLeft.Label = "Unbound"; + _lStickRight.Label = "Unbound"; + _lStickButton.Label = "Unbound"; + _dpadUp.Label = "Unbound"; + _dpadDown.Label = "Unbound"; + _dpadLeft.Label = "Unbound"; + _dpadRight.Label = "Unbound"; + _minus.Label = "Unbound"; + _l.Label = "Unbound"; + _zL.Label = "Unbound"; + _lSl.Label = "Unbound"; + _lSr.Label = "Unbound"; + _rStick.Label = "Unbound"; + _rStickUp.Label = "Unbound"; + _rStickDown.Label = "Unbound"; + _rStickLeft.Label = "Unbound"; + _rStickRight.Label = "Unbound"; + _rStickButton.Label = "Unbound"; + _a.Label = "Unbound"; + _b.Label = "Unbound"; + _x.Label = "Unbound"; + _y.Label = "Unbound"; + _plus.Label = "Unbound"; + _r.Label = "Unbound"; + _zR.Label = "Unbound"; + _rSl.Label = "Unbound"; + _rSr.Label = "Unbound"; + _controllerStrongRumble.Value = 1; + _controllerWeakRumble.Value = 1; + _controllerDeadzoneLeft.Value = 0; + _controllerDeadzoneRight.Value = 0; + _controllerRangeLeft.Value = 1; + _controllerRangeRight.Value = 1; _controllerTriggerThreshold.Value = 0; - _mirrorInput.Active = false; - _enableMotion.Active = false; - _enableCemuHook.Active = false; - _slotNumber.Value = 0; - _altSlotNumber.Value = 0; - _sensitivity.Value = 100; - _gyroDeadzone.Value = 1; - _dsuServerHost.Buffer.Text = ""; - _dsuServerPort.Buffer.Text = ""; - _enableRumble.Active = false; + _mirrorInput.Active = false; + _enableMotion.Active = false; + _enableCemuHook.Active = false; + _slotNumber.Value = 0; + _altSlotNumber.Value = 0; + _sensitivity.Value = 100; + _gyroDeadzone.Value = 1; + _dsuServerHost.Buffer.Text = ""; + _dsuServerPort.Buffer.Text = ""; + _enableRumble.Active = false; } private void SetValues(InputConfig config) @@ -454,34 +448,34 @@ namespace Ryujinx.Ui.Windows : ControllerType.ProController.ToString()); } - _lStickUp.Label = keyboardConfig.LeftJoyconStick.StickUp.ToString(); - _lStickDown.Label = keyboardConfig.LeftJoyconStick.StickDown.ToString(); - _lStickLeft.Label = keyboardConfig.LeftJoyconStick.StickLeft.ToString(); - _lStickRight.Label = keyboardConfig.LeftJoyconStick.StickRight.ToString(); - _lStickButton.Label = keyboardConfig.LeftJoyconStick.StickButton.ToString(); - _dpadUp.Label = keyboardConfig.LeftJoycon.DpadUp.ToString(); - _dpadDown.Label = keyboardConfig.LeftJoycon.DpadDown.ToString(); - _dpadLeft.Label = keyboardConfig.LeftJoycon.DpadLeft.ToString(); - _dpadRight.Label = keyboardConfig.LeftJoycon.DpadRight.ToString(); - _minus.Label = keyboardConfig.LeftJoycon.ButtonMinus.ToString(); - _l.Label = keyboardConfig.LeftJoycon.ButtonL.ToString(); - _zL.Label = keyboardConfig.LeftJoycon.ButtonZl.ToString(); - _lSl.Label = keyboardConfig.LeftJoycon.ButtonSl.ToString(); - _lSr.Label = keyboardConfig.LeftJoycon.ButtonSr.ToString(); - _rStickUp.Label = keyboardConfig.RightJoyconStick.StickUp.ToString(); - _rStickDown.Label = keyboardConfig.RightJoyconStick.StickDown.ToString(); - _rStickLeft.Label = keyboardConfig.RightJoyconStick.StickLeft.ToString(); - _rStickRight.Label = keyboardConfig.RightJoyconStick.StickRight.ToString(); - _rStickButton.Label = keyboardConfig.RightJoyconStick.StickButton.ToString(); - _a.Label = keyboardConfig.RightJoycon.ButtonA.ToString(); - _b.Label = keyboardConfig.RightJoycon.ButtonB.ToString(); - _x.Label = keyboardConfig.RightJoycon.ButtonX.ToString(); - _y.Label = keyboardConfig.RightJoycon.ButtonY.ToString(); - _plus.Label = keyboardConfig.RightJoycon.ButtonPlus.ToString(); - _r.Label = keyboardConfig.RightJoycon.ButtonR.ToString(); - _zR.Label = keyboardConfig.RightJoycon.ButtonZr.ToString(); - _rSl.Label = keyboardConfig.RightJoycon.ButtonSl.ToString(); - _rSr.Label = keyboardConfig.RightJoycon.ButtonSr.ToString(); + _lStickUp.Label = keyboardConfig.LeftJoyconStick.StickUp.ToString(); + _lStickDown.Label = keyboardConfig.LeftJoyconStick.StickDown.ToString(); + _lStickLeft.Label = keyboardConfig.LeftJoyconStick.StickLeft.ToString(); + _lStickRight.Label = keyboardConfig.LeftJoyconStick.StickRight.ToString(); + _lStickButton.Label = keyboardConfig.LeftJoyconStick.StickButton.ToString(); + _dpadUp.Label = keyboardConfig.LeftJoycon.DpadUp.ToString(); + _dpadDown.Label = keyboardConfig.LeftJoycon.DpadDown.ToString(); + _dpadLeft.Label = keyboardConfig.LeftJoycon.DpadLeft.ToString(); + _dpadRight.Label = keyboardConfig.LeftJoycon.DpadRight.ToString(); + _minus.Label = keyboardConfig.LeftJoycon.ButtonMinus.ToString(); + _l.Label = keyboardConfig.LeftJoycon.ButtonL.ToString(); + _zL.Label = keyboardConfig.LeftJoycon.ButtonZl.ToString(); + _lSl.Label = keyboardConfig.LeftJoycon.ButtonSl.ToString(); + _lSr.Label = keyboardConfig.LeftJoycon.ButtonSr.ToString(); + _rStickUp.Label = keyboardConfig.RightJoyconStick.StickUp.ToString(); + _rStickDown.Label = keyboardConfig.RightJoyconStick.StickDown.ToString(); + _rStickLeft.Label = keyboardConfig.RightJoyconStick.StickLeft.ToString(); + _rStickRight.Label = keyboardConfig.RightJoyconStick.StickRight.ToString(); + _rStickButton.Label = keyboardConfig.RightJoyconStick.StickButton.ToString(); + _a.Label = keyboardConfig.RightJoycon.ButtonA.ToString(); + _b.Label = keyboardConfig.RightJoycon.ButtonB.ToString(); + _x.Label = keyboardConfig.RightJoycon.ButtonX.ToString(); + _y.Label = keyboardConfig.RightJoycon.ButtonY.ToString(); + _plus.Label = keyboardConfig.RightJoycon.ButtonPlus.ToString(); + _r.Label = keyboardConfig.RightJoycon.ButtonR.ToString(); + _zR.Label = keyboardConfig.RightJoycon.ButtonZr.ToString(); + _rSl.Label = keyboardConfig.RightJoycon.ButtonSl.ToString(); + _rSr.Label = keyboardConfig.RightJoycon.ButtonSr.ToString(); break; case StandardControllerInputConfig controllerConfig: @@ -492,63 +486,63 @@ namespace Ryujinx.Ui.Windows : ControllerType.ProController.ToString()); } - _lStick.Label = controllerConfig.LeftJoyconStick.Joystick.ToString(); - _invertLStickX.Active = controllerConfig.LeftJoyconStick.InvertStickX; - _invertLStickY.Active = controllerConfig.LeftJoyconStick.InvertStickY; - _rotateL90CW.Active = controllerConfig.LeftJoyconStick.Rotate90CW; - _lStickButton.Label = controllerConfig.LeftJoyconStick.StickButton.ToString(); - _dpadUp.Label = controllerConfig.LeftJoycon.DpadUp.ToString(); - _dpadDown.Label = controllerConfig.LeftJoycon.DpadDown.ToString(); - _dpadLeft.Label = controllerConfig.LeftJoycon.DpadLeft.ToString(); - _dpadRight.Label = controllerConfig.LeftJoycon.DpadRight.ToString(); - _minus.Label = controllerConfig.LeftJoycon.ButtonMinus.ToString(); - _l.Label = controllerConfig.LeftJoycon.ButtonL.ToString(); - _zL.Label = controllerConfig.LeftJoycon.ButtonZl.ToString(); - _lSl.Label = controllerConfig.LeftJoycon.ButtonSl.ToString(); - _lSr.Label = controllerConfig.LeftJoycon.ButtonSr.ToString(); - _rStick.Label = controllerConfig.RightJoyconStick.Joystick.ToString(); - _invertRStickX.Active = controllerConfig.RightJoyconStick.InvertStickX; - _invertRStickY.Active = controllerConfig.RightJoyconStick.InvertStickY; - _rotateR90CW.Active = controllerConfig.RightJoyconStick.Rotate90CW; - _rStickButton.Label = controllerConfig.RightJoyconStick.StickButton.ToString(); - _a.Label = controllerConfig.RightJoycon.ButtonA.ToString(); - _b.Label = controllerConfig.RightJoycon.ButtonB.ToString(); - _x.Label = controllerConfig.RightJoycon.ButtonX.ToString(); - _y.Label = controllerConfig.RightJoycon.ButtonY.ToString(); - _plus.Label = controllerConfig.RightJoycon.ButtonPlus.ToString(); - _r.Label = controllerConfig.RightJoycon.ButtonR.ToString(); - _zR.Label = controllerConfig.RightJoycon.ButtonZr.ToString(); - _rSl.Label = controllerConfig.RightJoycon.ButtonSl.ToString(); - _rSr.Label = controllerConfig.RightJoycon.ButtonSr.ToString(); - _controllerStrongRumble.Value = controllerConfig.Rumble.StrongRumble; - _controllerWeakRumble.Value = controllerConfig.Rumble.WeakRumble; - _enableRumble.Active = controllerConfig.Rumble.EnableRumble; - _controllerDeadzoneLeft.Value = controllerConfig.DeadzoneLeft; - _controllerDeadzoneRight.Value = controllerConfig.DeadzoneRight; - _controllerRangeLeft.Value = controllerConfig.RangeLeft; - _controllerRangeRight.Value = controllerConfig.RangeRight; + _lStick.Label = controllerConfig.LeftJoyconStick.Joystick.ToString(); + _invertLStickX.Active = controllerConfig.LeftJoyconStick.InvertStickX; + _invertLStickY.Active = controllerConfig.LeftJoyconStick.InvertStickY; + _rotateL90CW.Active = controllerConfig.LeftJoyconStick.Rotate90CW; + _lStickButton.Label = controllerConfig.LeftJoyconStick.StickButton.ToString(); + _dpadUp.Label = controllerConfig.LeftJoycon.DpadUp.ToString(); + _dpadDown.Label = controllerConfig.LeftJoycon.DpadDown.ToString(); + _dpadLeft.Label = controllerConfig.LeftJoycon.DpadLeft.ToString(); + _dpadRight.Label = controllerConfig.LeftJoycon.DpadRight.ToString(); + _minus.Label = controllerConfig.LeftJoycon.ButtonMinus.ToString(); + _l.Label = controllerConfig.LeftJoycon.ButtonL.ToString(); + _zL.Label = controllerConfig.LeftJoycon.ButtonZl.ToString(); + _lSl.Label = controllerConfig.LeftJoycon.ButtonSl.ToString(); + _lSr.Label = controllerConfig.LeftJoycon.ButtonSr.ToString(); + _rStick.Label = controllerConfig.RightJoyconStick.Joystick.ToString(); + _invertRStickX.Active = controllerConfig.RightJoyconStick.InvertStickX; + _invertRStickY.Active = controllerConfig.RightJoyconStick.InvertStickY; + _rotateR90CW.Active = controllerConfig.RightJoyconStick.Rotate90CW; + _rStickButton.Label = controllerConfig.RightJoyconStick.StickButton.ToString(); + _a.Label = controllerConfig.RightJoycon.ButtonA.ToString(); + _b.Label = controllerConfig.RightJoycon.ButtonB.ToString(); + _x.Label = controllerConfig.RightJoycon.ButtonX.ToString(); + _y.Label = controllerConfig.RightJoycon.ButtonY.ToString(); + _plus.Label = controllerConfig.RightJoycon.ButtonPlus.ToString(); + _r.Label = controllerConfig.RightJoycon.ButtonR.ToString(); + _zR.Label = controllerConfig.RightJoycon.ButtonZr.ToString(); + _rSl.Label = controllerConfig.RightJoycon.ButtonSl.ToString(); + _rSr.Label = controllerConfig.RightJoycon.ButtonSr.ToString(); + _controllerStrongRumble.Value = controllerConfig.Rumble.StrongRumble; + _controllerWeakRumble.Value = controllerConfig.Rumble.WeakRumble; + _enableRumble.Active = controllerConfig.Rumble.EnableRumble; + _controllerDeadzoneLeft.Value = controllerConfig.DeadzoneLeft; + _controllerDeadzoneRight.Value = controllerConfig.DeadzoneRight; + _controllerRangeLeft.Value = controllerConfig.RangeLeft; + _controllerRangeRight.Value = controllerConfig.RangeRight; _controllerTriggerThreshold.Value = controllerConfig.TriggerThreshold; - _sensitivity.Value = controllerConfig.Motion.Sensitivity; - _gyroDeadzone.Value = controllerConfig.Motion.GyroDeadzone; - _enableMotion.Active = controllerConfig.Motion.EnableMotion; - _enableCemuHook.Active = controllerConfig.Motion.MotionBackend == MotionInputBackendType.CemuHook; + _sensitivity.Value = controllerConfig.Motion.Sensitivity; + _gyroDeadzone.Value = controllerConfig.Motion.GyroDeadzone; + _enableMotion.Active = controllerConfig.Motion.EnableMotion; + _enableCemuHook.Active = controllerConfig.Motion.MotionBackend == MotionInputBackendType.CemuHook; // If both stick ranges are 0 (usually indicative of an outdated profile load) then both sticks will be set to 1.0. if (_controllerRangeLeft.Value <= 0.0 && _controllerRangeRight.Value <= 0.0) { - _controllerRangeLeft.Value = 1.0; + _controllerRangeLeft.Value = 1.0; _controllerRangeRight.Value = 1.0; - + Logger.Info?.Print(LogClass.Application, $"{config.PlayerIndex} stick range reset. Save the profile now to update your configuration"); } if (controllerConfig.Motion is CemuHookMotionConfigController cemuHookMotionConfig) { - _slotNumber.Value = cemuHookMotionConfig.Slot; - _altSlotNumber.Value = cemuHookMotionConfig.AltSlot; - _mirrorInput.Active = cemuHookMotionConfig.MirrorInput; - _dsuServerHost.Buffer.Text = cemuHookMotionConfig.DsuServerHost; - _dsuServerPort.Buffer.Text = cemuHookMotionConfig.DsuServerPort.ToString(); + _slotNumber.Value = cemuHookMotionConfig.Slot; + _altSlotNumber.Value = cemuHookMotionConfig.AltSlot; + _mirrorInput.Active = cemuHookMotionConfig.MirrorInput; + _dsuServerHost.Buffer.Text = cemuHookMotionConfig.DsuServerHost; + _dsuServerPort.Buffer.Text = cemuHookMotionConfig.DsuServerPort.ToString(); } break; @@ -559,6 +553,7 @@ namespace Ryujinx.Ui.Windows { if (_inputDevice.ActiveId.StartsWith("keyboard")) { +#pragma warning disable CA1806, IDE0055 // Disable formatting Enum.TryParse(_lStickUp.Label, out Key lStickUp); Enum.TryParse(_lStickDown.Label, out Key lStickDown); Enum.TryParse(_lStickLeft.Label, out Key lStickLeft); @@ -588,60 +583,62 @@ namespace Ryujinx.Ui.Windows Enum.TryParse(_zR.Label, out Key rButtonZr); Enum.TryParse(_rSl.Label, out Key rButtonSl); Enum.TryParse(_rSr.Label, out Key rButtonSr); +#pragma warning restore CA1806, IDE0055 return new StandardKeyboardInputConfig { - Backend = InputBackendType.WindowKeyboard, - Version = InputConfig.CurrentVersion, - Id = _inputDevice.ActiveId.Split("/")[1], - ControllerType = Enum.Parse(_controllerType.ActiveId), - PlayerIndex = _playerIndex, - LeftJoycon = new LeftJoyconCommonConfig + Backend = InputBackendType.WindowKeyboard, + Version = InputConfig.CurrentVersion, + Id = _inputDevice.ActiveId.Split("/")[1], + ControllerType = Enum.Parse(_controllerType.ActiveId), + PlayerIndex = _playerIndex, + LeftJoycon = new LeftJoyconCommonConfig { - ButtonMinus = lButtonMinus, - ButtonL = lButtonL, - ButtonZl = lButtonZl, - ButtonSl = lButtonSl, - ButtonSr = lButtonSr, - DpadUp = lDPadUp, - DpadDown = lDPadDown, - DpadLeft = lDPadLeft, - DpadRight = lDPadRight + ButtonMinus = lButtonMinus, + ButtonL = lButtonL, + ButtonZl = lButtonZl, + ButtonSl = lButtonSl, + ButtonSr = lButtonSr, + DpadUp = lDPadUp, + DpadDown = lDPadDown, + DpadLeft = lDPadLeft, + DpadRight = lDPadRight, }, LeftJoyconStick = new JoyconConfigKeyboardStick { - StickUp = lStickUp, - StickDown = lStickDown, - StickLeft = lStickLeft, - StickRight = lStickRight, - StickButton = lStickButton, + StickUp = lStickUp, + StickDown = lStickDown, + StickLeft = lStickLeft, + StickRight = lStickRight, + StickButton = lStickButton, }, - RightJoycon = new RightJoyconCommonConfig + RightJoycon = new RightJoyconCommonConfig { - ButtonA = rButtonA, - ButtonB = rButtonB, - ButtonX = rButtonX, - ButtonY = rButtonY, - ButtonPlus = rButtonPlus, - ButtonR = rButtonR, - ButtonZr = rButtonZr, - ButtonSl = rButtonSl, - ButtonSr = rButtonSr + ButtonA = rButtonA, + ButtonB = rButtonB, + ButtonX = rButtonX, + ButtonY = rButtonY, + ButtonPlus = rButtonPlus, + ButtonR = rButtonR, + ButtonZr = rButtonZr, + ButtonSl = rButtonSl, + ButtonSr = rButtonSr, }, RightJoyconStick = new JoyconConfigKeyboardStick { - StickUp = rStickUp, - StickDown = rStickDown, - StickLeft = rStickLeft, - StickRight = rStickRight, - StickButton = rStickButton, + StickUp = rStickUp, + StickDown = rStickDown, + StickLeft = rStickLeft, + StickRight = rStickRight, + StickButton = rStickButton, }, }; } - + if (_inputDevice.ActiveId.StartsWith("controller")) { - Enum.TryParse(_lStick.Label, out ConfigStickInputId lStick); +#pragma warning disable CA1806, IDE0055 // Disable formatting + Enum.TryParse(_lStick.Label, out ConfigStickInputId lStick); Enum.TryParse(_lStickButton.Label, out ConfigGamepadInputId lStickButton); Enum.TryParse(_minus.Label, out ConfigGamepadInputId lButtonMinus); Enum.TryParse(_l.Label, out ConfigGamepadInputId lButtonL); @@ -653,7 +650,7 @@ namespace Ryujinx.Ui.Windows Enum.TryParse(_dpadLeft.Label, out ConfigGamepadInputId lDPadLeft); Enum.TryParse(_dpadRight.Label, out ConfigGamepadInputId lDPadRight); - Enum.TryParse(_rStick.Label, out ConfigStickInputId rStick); + Enum.TryParse(_rStick.Label, out ConfigStickInputId rStick); Enum.TryParse(_rStickButton.Label, out ConfigGamepadInputId rStickButton); Enum.TryParse(_a.Label, out ConfigGamepadInputId rButtonA); Enum.TryParse(_b.Label, out ConfigGamepadInputId rButtonB); @@ -666,94 +663,95 @@ namespace Ryujinx.Ui.Windows Enum.TryParse(_rSr.Label, out ConfigGamepadInputId rButtonSr); int.TryParse(_dsuServerPort.Buffer.Text, out int port); +#pragma warning restore CA1806, IDE0055 MotionConfigController motionConfig; if (_enableCemuHook.Active) { - motionConfig = new CemuHookMotionConfigController + motionConfig = new CemuHookMotionConfigController { MotionBackend = MotionInputBackendType.CemuHook, - EnableMotion = _enableMotion.Active, - Sensitivity = (int)_sensitivity.Value, - GyroDeadzone = _gyroDeadzone.Value, - MirrorInput = _mirrorInput.Active, - Slot = (int)_slotNumber.Value, - AltSlot = (int)_altSlotNumber.Value, + EnableMotion = _enableMotion.Active, + Sensitivity = (int)_sensitivity.Value, + GyroDeadzone = _gyroDeadzone.Value, + MirrorInput = _mirrorInput.Active, + Slot = (int)_slotNumber.Value, + AltSlot = (int)_altSlotNumber.Value, DsuServerHost = _dsuServerHost.Buffer.Text, - DsuServerPort = port + DsuServerPort = port, }; } else { - motionConfig = new StandardMotionConfigController + motionConfig = new StandardMotionConfigController { MotionBackend = MotionInputBackendType.GamepadDriver, - EnableMotion = _enableMotion.Active, - Sensitivity = (int)_sensitivity.Value, - GyroDeadzone = _gyroDeadzone.Value, + EnableMotion = _enableMotion.Active, + Sensitivity = (int)_sensitivity.Value, + GyroDeadzone = _gyroDeadzone.Value, }; } return new StandardControllerInputConfig { - Backend = InputBackendType.GamepadSDL2, - Version = InputConfig.CurrentVersion, - Id = _inputDevice.ActiveId.Split("/")[1].Split(" ")[0], - ControllerType = Enum.Parse(_controllerType.ActiveId), - PlayerIndex = _playerIndex, - DeadzoneLeft = (float)_controllerDeadzoneLeft.Value, - DeadzoneRight = (float)_controllerDeadzoneRight.Value, - RangeLeft = (float)_controllerRangeLeft.Value, - RangeRight = (float)_controllerRangeRight.Value, + Backend = InputBackendType.GamepadSDL2, + Version = InputConfig.CurrentVersion, + Id = _inputDevice.ActiveId.Split("/")[1].Split(" ")[0], + ControllerType = Enum.Parse(_controllerType.ActiveId), + PlayerIndex = _playerIndex, + DeadzoneLeft = (float)_controllerDeadzoneLeft.Value, + DeadzoneRight = (float)_controllerDeadzoneRight.Value, + RangeLeft = (float)_controllerRangeLeft.Value, + RangeRight = (float)_controllerRangeRight.Value, TriggerThreshold = (float)_controllerTriggerThreshold.Value, - LeftJoycon = new LeftJoyconCommonConfig + LeftJoycon = new LeftJoyconCommonConfig { - ButtonMinus = lButtonMinus, - ButtonL = lButtonL, - ButtonZl = lButtonZl, - ButtonSl = lButtonSl, - ButtonSr = lButtonSr, - DpadUp = lDPadUp, - DpadDown = lDPadDown, - DpadLeft = lDPadLeft, - DpadRight = lDPadRight + ButtonMinus = lButtonMinus, + ButtonL = lButtonL, + ButtonZl = lButtonZl, + ButtonSl = lButtonSl, + ButtonSr = lButtonSr, + DpadUp = lDPadUp, + DpadDown = lDPadDown, + DpadLeft = lDPadLeft, + DpadRight = lDPadRight, }, LeftJoyconStick = new JoyconConfigControllerStick { InvertStickX = _invertLStickX.Active, - Joystick = lStick, + Joystick = lStick, InvertStickY = _invertLStickY.Active, - StickButton = lStickButton, - Rotate90CW = _rotateL90CW.Active, + StickButton = lStickButton, + Rotate90CW = _rotateL90CW.Active, }, - RightJoycon = new RightJoyconCommonConfig + RightJoycon = new RightJoyconCommonConfig { - ButtonA = rButtonA, - ButtonB = rButtonB, - ButtonX = rButtonX, - ButtonY = rButtonY, - ButtonPlus = rButtonPlus, - ButtonR = rButtonR, - ButtonZr = rButtonZr, - ButtonSl = rButtonSl, - ButtonSr = rButtonSr + ButtonA = rButtonA, + ButtonB = rButtonB, + ButtonX = rButtonX, + ButtonY = rButtonY, + ButtonPlus = rButtonPlus, + ButtonR = rButtonR, + ButtonZr = rButtonZr, + ButtonSl = rButtonSl, + ButtonSr = rButtonSr, }, RightJoyconStick = new JoyconConfigControllerStick { InvertStickX = _invertRStickX.Active, - Joystick = rStick, + Joystick = rStick, InvertStickY = _invertRStickY.Active, - StickButton = rStickButton, - Rotate90CW = _rotateR90CW.Active, + StickButton = rStickButton, + Rotate90CW = _rotateR90CW.Active, }, - Motion = motionConfig, - Rumble = new RumbleConfigController + Motion = motionConfig, + Rumble = new RumbleConfigController { StrongRumble = (float)_controllerStrongRumble.Value, - WeakRumble = (float)_controllerWeakRumble.Value, - EnableRumble = _enableRumble.Active - } + WeakRumble = (float)_controllerWeakRumble.Value, + EnableRumble = _enableRumble.Active, + }, }; } @@ -856,7 +854,7 @@ namespace Ryujinx.Ui.Windows { throw new Exception("Controller not supported"); } - + return assigner; } @@ -880,7 +878,7 @@ namespace Ryujinx.Ui.Windows // Open GTK3 keyboard for cancel operations IKeyboard keyboard = (IKeyboard)_gtk3KeyboardDriver.GetGamepad("0"); - Thread inputThread = new Thread(() => + Thread inputThread = new(() => { assigner.Initialize(); @@ -916,10 +914,11 @@ namespace Ryujinx.Ui.Windows button.Active = false; _isWaitingForInput = false; }); - }); - - inputThread.Name = "GUI.InputThread"; - inputThread.IsBackground = true; + }) + { + Name = "GUI.InputThread", + IsBackground = true, + }; inputThread.Start(); } @@ -950,7 +949,7 @@ namespace Ryujinx.Ui.Windows Directory.CreateDirectory(basePath); } - if (_inputDevice.ActiveId == null|| _inputDevice.ActiveId.Equals("disabled")) + if (_inputDevice.ActiveId == null || _inputDevice.ActiveId.Equals("disabled")) { _profile.Append("default", "None"); } @@ -971,10 +970,13 @@ namespace Ryujinx.Ui.Windows { ((ToggleButton)sender).SetStateFlags(StateFlags.Normal, true); - if (_inputDevice.ActiveId == "disabled" || _profile.ActiveId == null) return; + if (_inputDevice.ActiveId == "disabled" || _profile.ActiveId == null) + { + return; + } InputConfig config = null; - int pos = _profile.Active; + int pos = _profile.Active; if (_profile.ActiveId == "default") { @@ -982,53 +984,53 @@ namespace Ryujinx.Ui.Windows { config = new StandardKeyboardInputConfig { - Version = InputConfig.CurrentVersion, - Backend = InputBackendType.WindowKeyboard, - Id = null, - ControllerType = ControllerType.ProController, - LeftJoycon = new LeftJoyconCommonConfig + Version = InputConfig.CurrentVersion, + Backend = InputBackendType.WindowKeyboard, + Id = null, + ControllerType = ControllerType.ProController, + LeftJoycon = new LeftJoyconCommonConfig { - DpadUp = Key.Up, - DpadDown = Key.Down, - DpadLeft = Key.Left, - DpadRight = Key.Right, - ButtonMinus = Key.Minus, - ButtonL = Key.E, - ButtonZl = Key.Q, - ButtonSl = Key.Unbound, - ButtonSr = Key.Unbound + DpadUp = Key.Up, + DpadDown = Key.Down, + DpadLeft = Key.Left, + DpadRight = Key.Right, + ButtonMinus = Key.Minus, + ButtonL = Key.E, + ButtonZl = Key.Q, + ButtonSl = Key.Unbound, + ButtonSr = Key.Unbound, }, - LeftJoyconStick = new JoyconConfigKeyboardStick + LeftJoyconStick = new JoyconConfigKeyboardStick { - StickUp = Key.W, - StickDown = Key.S, - StickLeft = Key.A, - StickRight = Key.D, - StickButton = Key.F, + StickUp = Key.W, + StickDown = Key.S, + StickLeft = Key.A, + StickRight = Key.D, + StickButton = Key.F, }, - RightJoycon = new RightJoyconCommonConfig + RightJoycon = new RightJoyconCommonConfig { - ButtonA = Key.Z, - ButtonB = Key.X, - ButtonX = Key.C, - ButtonY = Key.V, - ButtonPlus = Key.Plus, - ButtonR = Key.U, - ButtonZr = Key.O, - ButtonSl = Key.Unbound, - ButtonSr = Key.Unbound + ButtonA = Key.Z, + ButtonB = Key.X, + ButtonX = Key.C, + ButtonY = Key.V, + ButtonPlus = Key.Plus, + ButtonR = Key.U, + ButtonZr = Key.O, + ButtonSl = Key.Unbound, + ButtonSr = Key.Unbound, }, RightJoyconStick = new JoyconConfigKeyboardStick { - StickUp = Key.I, - StickDown = Key.K, - StickLeft = Key.J, - StickRight = Key.L, - StickButton = Key.H, - } + StickUp = Key.I, + StickDown = Key.K, + StickLeft = Key.J, + StickRight = Key.L, + StickButton = Key.H, + }, }; } else if (_inputDevice.ActiveId.StartsWith("controller")) @@ -1037,72 +1039,72 @@ namespace Ryujinx.Ui.Windows config = new StandardControllerInputConfig { - Version = InputConfig.CurrentVersion, - Backend = InputBackendType.GamepadSDL2, - Id = null, - ControllerType = ControllerType.JoyconPair, - DeadzoneLeft = 0.1f, - DeadzoneRight = 0.1f, - RangeLeft = 1.0f, - RangeRight = 1.0f, + Version = InputConfig.CurrentVersion, + Backend = InputBackendType.GamepadSDL2, + Id = null, + ControllerType = ControllerType.JoyconPair, + DeadzoneLeft = 0.1f, + DeadzoneRight = 0.1f, + RangeLeft = 1.0f, + RangeRight = 1.0f, TriggerThreshold = 0.5f, LeftJoycon = new LeftJoyconCommonConfig { - DpadUp = ConfigGamepadInputId.DpadUp, - DpadDown = ConfigGamepadInputId.DpadDown, - DpadLeft = ConfigGamepadInputId.DpadLeft, - DpadRight = ConfigGamepadInputId.DpadRight, - ButtonMinus = ConfigGamepadInputId.Minus, - ButtonL = ConfigGamepadInputId.LeftShoulder, - ButtonZl = ConfigGamepadInputId.LeftTrigger, - ButtonSl = ConfigGamepadInputId.Unbound, - ButtonSr = ConfigGamepadInputId.Unbound, + DpadUp = ConfigGamepadInputId.DpadUp, + DpadDown = ConfigGamepadInputId.DpadDown, + DpadLeft = ConfigGamepadInputId.DpadLeft, + DpadRight = ConfigGamepadInputId.DpadRight, + ButtonMinus = ConfigGamepadInputId.Minus, + ButtonL = ConfigGamepadInputId.LeftShoulder, + ButtonZl = ConfigGamepadInputId.LeftTrigger, + ButtonSl = ConfigGamepadInputId.Unbound, + ButtonSr = ConfigGamepadInputId.Unbound, }, LeftJoyconStick = new JoyconConfigControllerStick { - Joystick = ConfigStickInputId.Left, - StickButton = ConfigGamepadInputId.LeftStick, + Joystick = ConfigStickInputId.Left, + StickButton = ConfigGamepadInputId.LeftStick, InvertStickX = false, InvertStickY = false, - Rotate90CW = false, + Rotate90CW = false, }, RightJoycon = new RightJoyconCommonConfig { - ButtonA = isNintendoStyle ? ConfigGamepadInputId.A : ConfigGamepadInputId.B, - ButtonB = isNintendoStyle ? ConfigGamepadInputId.B : ConfigGamepadInputId.A, - ButtonX = isNintendoStyle ? ConfigGamepadInputId.X : ConfigGamepadInputId.Y, - ButtonY = isNintendoStyle ? ConfigGamepadInputId.Y : ConfigGamepadInputId.X, - ButtonPlus = ConfigGamepadInputId.Plus, - ButtonR = ConfigGamepadInputId.RightShoulder, - ButtonZr = ConfigGamepadInputId.RightTrigger, - ButtonSl = ConfigGamepadInputId.Unbound, - ButtonSr = ConfigGamepadInputId.Unbound, + ButtonA = isNintendoStyle ? ConfigGamepadInputId.A : ConfigGamepadInputId.B, + ButtonB = isNintendoStyle ? ConfigGamepadInputId.B : ConfigGamepadInputId.A, + ButtonX = isNintendoStyle ? ConfigGamepadInputId.X : ConfigGamepadInputId.Y, + ButtonY = isNintendoStyle ? ConfigGamepadInputId.Y : ConfigGamepadInputId.X, + ButtonPlus = ConfigGamepadInputId.Plus, + ButtonR = ConfigGamepadInputId.RightShoulder, + ButtonZr = ConfigGamepadInputId.RightTrigger, + ButtonSl = ConfigGamepadInputId.Unbound, + ButtonSr = ConfigGamepadInputId.Unbound, }, RightJoyconStick = new JoyconConfigControllerStick { - Joystick = ConfigStickInputId.Right, - StickButton = ConfigGamepadInputId.RightStick, + Joystick = ConfigStickInputId.Right, + StickButton = ConfigGamepadInputId.RightStick, InvertStickX = false, InvertStickY = false, - Rotate90CW = false, + Rotate90CW = false, }, Motion = new StandardMotionConfigController { MotionBackend = MotionInputBackendType.GamepadDriver, EnableMotion = true, - Sensitivity = 100, + Sensitivity = 100, GyroDeadzone = 1, }, Rumble = new RumbleConfigController { StrongRumble = 1f, - WeakRumble = 1f, - EnableRumble = false - } + WeakRumble = 1f, + EnableRumble = false, + }, }; } } @@ -1122,7 +1124,7 @@ namespace Ryujinx.Ui.Windows try { - config = JsonHelper.DeserializeFromFile(path, SerializerContext.InputConfig); + config = JsonHelper.DeserializeFromFile(path, _serializerContext.InputConfig); } catch (JsonException) { } } @@ -1134,17 +1136,23 @@ namespace Ryujinx.Ui.Windows { ((ToggleButton)sender).SetStateFlags(StateFlags.Normal, true); - if (_inputDevice.ActiveId == "disabled") return; + if (_inputDevice.ActiveId == "disabled") + { + return; + } - InputConfig inputConfig = GetValues(); - ProfileDialog profileDialog = new ProfileDialog(); + InputConfig inputConfig = GetValues(); + ProfileDialog profileDialog = new(); - if (inputConfig == null) return; + if (inputConfig == null) + { + return; + } if (profileDialog.Run() == (int)ResponseType.Ok) { string path = System.IO.Path.Combine(GetProfileBasePath(), profileDialog.FileName); - string jsonString = JsonHelper.Serialize(inputConfig, SerializerContext.InputConfig); + string jsonString = JsonHelper.Serialize(inputConfig, _serializerContext.InputConfig); File.WriteAllText(path, jsonString); } @@ -1156,9 +1164,12 @@ namespace Ryujinx.Ui.Windows private void ProfileRemove_Activated(object sender, EventArgs args) { - ((ToggleButton) sender).SetStateFlags(StateFlags.Normal, true); + ((ToggleButton)sender).SetStateFlags(StateFlags.Normal, true); - if (_inputDevice.ActiveId == "disabled" || _profile.ActiveId == "default" || _profile.ActiveId == null) return; + if (_inputDevice.ActiveId == "disabled" || _profile.ActiveId == "default" || _profile.ActiveId == null) + { + return; + } MessageDialog confirmDialog = GtkDialog.CreateConfirmationDialog("Deleting Profile", "This action is irreversible, are you sure you want to continue?"); @@ -1200,10 +1211,7 @@ namespace Ryujinx.Ui.Windows } } - if (_mainWindow.RendererWidget != null) - { - _mainWindow.RendererWidget.NpadManager.ReloadConfiguration(newConfig, ConfigurationState.Instance.Hid.EnableKeyboard, ConfigurationState.Instance.Hid.EnableMouse); - } + _mainWindow.RendererWidget?.NpadManager.ReloadConfiguration(newConfig, ConfigurationState.Instance.Hid.EnableKeyboard, ConfigurationState.Instance.Hid.EnableMouse); // Atomically replace and signal input change. // NOTE: Do not modify InputConfig.Value directly as other code depends on the on-change event. diff --git a/src/Ryujinx/Ui/Windows/DlcWindow.cs b/src/Ryujinx/Ui/Windows/DlcWindow.cs index b22f15932..74aef00f4 100644 --- a/src/Ryujinx/Ui/Windows/DlcWindow.cs +++ b/src/Ryujinx/Ui/Windows/DlcWindow.cs @@ -19,16 +19,16 @@ namespace Ryujinx.Ui.Windows { public class DlcWindow : Window { - private readonly VirtualFileSystem _virtualFileSystem; - private readonly string _titleId; - private readonly string _dlcJsonPath; + private readonly VirtualFileSystem _virtualFileSystem; + private readonly string _titleId; + private readonly string _dlcJsonPath; private readonly List _dlcContainerList; - private static readonly DownloadableContentJsonSerializerContext SerializerContext = new(JsonHelper.GetDefaultSerializerOptions()); + private static readonly DownloadableContentJsonSerializerContext _serializerContext = new(JsonHelper.GetDefaultSerializerOptions()); -#pragma warning disable CS0649, IDE0044 - [GUI] Label _baseTitleInfoLabel; - [GUI] TreeView _dlcTreeView; +#pragma warning disable CS0649, IDE0044 // Field is never assigned to, Add readonly modifier + [GUI] Label _baseTitleInfoLabel; + [GUI] TreeView _dlcTreeView; [GUI] TreeSelection _dlcTreeSelection; #pragma warning restore CS0649, IDE0044 @@ -38,23 +38,23 @@ namespace Ryujinx.Ui.Windows { builder.Autoconnect(this); - _titleId = titleId; - _virtualFileSystem = virtualFileSystem; - _dlcJsonPath = System.IO.Path.Combine(AppDataManager.GamesDirPath, _titleId, "dlc.json"); + _titleId = titleId; + _virtualFileSystem = virtualFileSystem; + _dlcJsonPath = System.IO.Path.Combine(AppDataManager.GamesDirPath, _titleId, "dlc.json"); _baseTitleInfoLabel.Text = $"DLC Available for {titleName} [{titleId.ToUpper()}]"; try { - _dlcContainerList = JsonHelper.DeserializeFromFile(_dlcJsonPath, SerializerContext.ListDownloadableContentContainer); + _dlcContainerList = JsonHelper.DeserializeFromFile(_dlcJsonPath, _serializerContext.ListDownloadableContentContainer); } catch { _dlcContainerList = new List(); } - + _dlcTreeView.Model = new TreeStore(typeof(bool), typeof(string), typeof(string)); - CellRendererToggle enableToggle = new CellRendererToggle(); + CellRendererToggle enableToggle = new(); enableToggle.Toggled += (sender, args) => { _dlcTreeView.Model.GetIter(out TreeIter treeIter, new TreePath(args.Path)); @@ -71,9 +71,9 @@ namespace Ryujinx.Ui.Windows } }; - _dlcTreeView.AppendColumn("Enabled", enableToggle, "active", 0); - _dlcTreeView.AppendColumn("TitleId", new CellRendererText(), "text", 1); - _dlcTreeView.AppendColumn("Path", new CellRendererText(), "text", 2); + _dlcTreeView.AppendColumn("Enabled", enableToggle, "active", 0); + _dlcTreeView.AppendColumn("TitleId", new CellRendererText(), "text", 1); + _dlcTreeView.AppendColumn("Path", new CellRendererText(), "text", 2); foreach (DownloadableContentContainer dlcContainer in _dlcContainerList) { @@ -85,8 +85,11 @@ namespace Ryujinx.Ui.Windows // "enabled" box if all child NCAs are enabled. Usually fine since each nsp has only one nca. bool areAllContentPacksEnabled = dlcContainer.DownloadableContentNcaList.TrueForAll((nca) => nca.Enabled); TreeIter parentIter = ((TreeStore)_dlcTreeView.Model).AppendValues(areAllContentPacksEnabled, "", dlcContainer.ContainerPath); + using FileStream containerFile = File.OpenRead(dlcContainer.ContainerPath); - PartitionFileSystem pfs = new PartitionFileSystem(containerFile.AsStorage()); + + PartitionFileSystem pfs = new(containerFile.AsStorage()); + _virtualFileSystem.ImportTickets(pfs); foreach (DownloadableContentNca dlcNca in dlcContainer.DownloadableContentNcaList) @@ -126,14 +129,14 @@ namespace Ryujinx.Ui.Windows private void AddButton_Clicked(object sender, EventArgs args) { - FileChooserNative fileChooser = new FileChooserNative("Select DLC files", this, FileChooserAction.Open, "Add", "Cancel") + FileChooserNative fileChooser = new("Select DLC files", this, FileChooserAction.Open, "Add", "Cancel") { - SelectMultiple = true + SelectMultiple = true, }; - FileFilter filter = new FileFilter() + FileFilter filter = new() { - Name = "Switch Game DLCs" + Name = "Switch Game DLCs", }; filter.AddPattern("*.nsp"); @@ -148,44 +151,46 @@ namespace Ryujinx.Ui.Windows return; } - using (FileStream containerFile = File.OpenRead(containerPath)) + using FileStream containerFile = File.OpenRead(containerPath); + + PartitionFileSystem pfs = new(containerFile.AsStorage()); + bool containsDlc = false; + + _virtualFileSystem.ImportTickets(pfs); + + TreeIter? parentIter = null; + + foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca")) { - PartitionFileSystem pfs = new PartitionFileSystem(containerFile.AsStorage()); - bool containsDlc = false; + using var ncaFile = new UniqueRef(); - _virtualFileSystem.ImportTickets(pfs); + pfs.OpenFile(ref ncaFile.Ref, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); - TreeIter? parentIter = null; + Nca nca = TryCreateNca(ncaFile.Get.AsStorage(), containerPath); - foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca")) + if (nca == null) { - using var ncaFile = new UniqueRef(); + continue; + } - pfs.OpenFile(ref ncaFile.Ref, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); - - Nca nca = TryCreateNca(ncaFile.Get.AsStorage(), containerPath); - - if (nca == null) continue; - - if (nca.Header.ContentType == NcaContentType.PublicData) + if (nca.Header.ContentType == NcaContentType.PublicData) + { + if ((nca.Header.TitleId & 0xFFFFFFFFFFFFE000).ToString("x16") != _titleId) { - if ((nca.Header.TitleId & 0xFFFFFFFFFFFFE000).ToString("x16") != _titleId) - { - break; - } - - parentIter ??= ((TreeStore)_dlcTreeView.Model).AppendValues(true, "", containerPath); - - ((TreeStore)_dlcTreeView.Model).AppendValues(parentIter.Value, true, nca.Header.TitleId.ToString("X16"), fileEntry.FullPath); - containsDlc = true; + break; } - } - if (!containsDlc) - { - GtkDialog.CreateErrorDialog("The specified file does not contain DLC for the selected title!"); + parentIter ??= ((TreeStore)_dlcTreeView.Model).AppendValues(true, "", containerPath); + + ((TreeStore)_dlcTreeView.Model).AppendValues(parentIter.Value, true, nca.Header.TitleId.ToString("X16"), fileEntry.FullPath); + containsDlc = true; } } + + if (!containsDlc) + { + GtkDialog.CreateErrorDialog("The specified file does not contain DLC for the selected title!"); + } } } @@ -206,17 +211,17 @@ namespace Ryujinx.Ui.Windows } } } - + private void RemoveAllButton_Clicked(object sender, EventArgs args) { - List toRemove = new List(); + List toRemove = new(); if (_dlcTreeView.Model.GetIterFirst(out TreeIter iter)) { do { toRemove.Add(iter); - } + } while (_dlcTreeView.Model.IterNext(ref iter)); } @@ -237,19 +242,19 @@ namespace Ryujinx.Ui.Windows { if (_dlcTreeView.Model.IterChildren(out TreeIter childIter, parentIter)) { - DownloadableContentContainer dlcContainer = new DownloadableContentContainer + DownloadableContentContainer dlcContainer = new() { - ContainerPath = (string)_dlcTreeView.Model.GetValue(parentIter, 2), - DownloadableContentNcaList = new List() + ContainerPath = (string)_dlcTreeView.Model.GetValue(parentIter, 2), + DownloadableContentNcaList = new List(), }; do { dlcContainer.DownloadableContentNcaList.Add(new DownloadableContentNca { - Enabled = (bool)_dlcTreeView.Model.GetValue(childIter, 0), - TitleId = Convert.ToUInt64(_dlcTreeView.Model.GetValue(childIter, 1).ToString(), 16), - FullPath = (string)_dlcTreeView.Model.GetValue(childIter, 2) + Enabled = (bool)_dlcTreeView.Model.GetValue(childIter, 0), + TitleId = Convert.ToUInt64(_dlcTreeView.Model.GetValue(childIter, 1).ToString(), 16), + FullPath = (string)_dlcTreeView.Model.GetValue(childIter, 2), }); } while (_dlcTreeView.Model.IterNext(ref childIter)); @@ -260,7 +265,7 @@ namespace Ryujinx.Ui.Windows while (_dlcTreeView.Model.IterNext(ref parentIter)); } - JsonHelper.SerializeToFile(_dlcJsonPath, _dlcContainerList, SerializerContext.ListDownloadableContentContainer); + JsonHelper.SerializeToFile(_dlcJsonPath, _dlcContainerList, _serializerContext.ListDownloadableContentContainer); Dispose(); } diff --git a/src/Ryujinx/Ui/Windows/SettingsWindow.cs b/src/Ryujinx/Ui/Windows/SettingsWindow.cs index fbfbf527c..b9f1a90a3 100644 --- a/src/Ryujinx/Ui/Windows/SettingsWindow.cs +++ b/src/Ryujinx/Ui/Windows/SettingsWindow.cs @@ -6,14 +6,12 @@ using Ryujinx.Audio.Backends.SoundIo; using Ryujinx.Common.Configuration; using Ryujinx.Common.Configuration.Hid; using Ryujinx.Common.GraphicsDriver; -using Ryujinx.Graphics.Vulkan; using Ryujinx.HLE.FileSystem; using Ryujinx.HLE.HOS.Services.Time.TimeZone; using Ryujinx.Ui.Common.Configuration; using Ryujinx.Ui.Common.Configuration.System; using Ryujinx.Ui.Helper; using Ryujinx.Ui.Widgets; -using Silk.NET.Vulkan; using System; using System.Collections.Generic; using System.Globalization; @@ -27,95 +25,95 @@ namespace Ryujinx.Ui.Windows { public class SettingsWindow : Window { - private readonly MainWindow _parent; - private readonly ListStore _gameDirsBoxStore; - private readonly ListStore _audioBackendStore; + private readonly MainWindow _parent; + private readonly ListStore _gameDirsBoxStore; + private readonly ListStore _audioBackendStore; private readonly TimeZoneContentManager _timeZoneContentManager; - private readonly HashSet _validTzRegions; + private readonly HashSet _validTzRegions; - private long _systemTimeOffset; + private long _systemTimeOffset; private float _previousVolumeLevel; private bool _directoryChanged = false; -#pragma warning disable CS0649, IDE0044 - [GUI] CheckButton _traceLogToggle; - [GUI] CheckButton _errorLogToggle; - [GUI] CheckButton _warningLogToggle; - [GUI] CheckButton _infoLogToggle; - [GUI] CheckButton _stubLogToggle; - [GUI] CheckButton _debugLogToggle; - [GUI] CheckButton _fileLogToggle; - [GUI] CheckButton _guestLogToggle; - [GUI] CheckButton _fsAccessLogToggle; - [GUI] Adjustment _fsLogSpinAdjustment; - [GUI] ComboBoxText _graphicsDebugLevel; - [GUI] CheckButton _dockedModeToggle; - [GUI] CheckButton _discordToggle; - [GUI] CheckButton _checkUpdatesToggle; - [GUI] CheckButton _showConfirmExitToggle; - [GUI] RadioButton _hideCursorNever; - [GUI] RadioButton _hideCursorOnIdle; - [GUI] RadioButton _hideCursorAlways; - [GUI] CheckButton _vSyncToggle; - [GUI] CheckButton _shaderCacheToggle; - [GUI] CheckButton _textureRecompressionToggle; - [GUI] CheckButton _macroHLEToggle; - [GUI] CheckButton _ptcToggle; - [GUI] CheckButton _internetToggle; - [GUI] CheckButton _fsicToggle; - [GUI] RadioButton _mmSoftware; - [GUI] RadioButton _mmHost; - [GUI] RadioButton _mmHostUnsafe; - [GUI] CheckButton _expandRamToggle; - [GUI] CheckButton _ignoreToggle; - [GUI] CheckButton _directKeyboardAccess; - [GUI] CheckButton _directMouseAccess; - [GUI] ComboBoxText _systemLanguageSelect; - [GUI] ComboBoxText _systemRegionSelect; - [GUI] Entry _systemTimeZoneEntry; +#pragma warning disable CS0649, IDE0044 // Field is never assigned to, Add readonly modifier + [GUI] CheckButton _traceLogToggle; + [GUI] CheckButton _errorLogToggle; + [GUI] CheckButton _warningLogToggle; + [GUI] CheckButton _infoLogToggle; + [GUI] CheckButton _stubLogToggle; + [GUI] CheckButton _debugLogToggle; + [GUI] CheckButton _fileLogToggle; + [GUI] CheckButton _guestLogToggle; + [GUI] CheckButton _fsAccessLogToggle; + [GUI] Adjustment _fsLogSpinAdjustment; + [GUI] ComboBoxText _graphicsDebugLevel; + [GUI] CheckButton _dockedModeToggle; + [GUI] CheckButton _discordToggle; + [GUI] CheckButton _checkUpdatesToggle; + [GUI] CheckButton _showConfirmExitToggle; + [GUI] RadioButton _hideCursorNever; + [GUI] RadioButton _hideCursorOnIdle; + [GUI] RadioButton _hideCursorAlways; + [GUI] CheckButton _vSyncToggle; + [GUI] CheckButton _shaderCacheToggle; + [GUI] CheckButton _textureRecompressionToggle; + [GUI] CheckButton _macroHLEToggle; + [GUI] CheckButton _ptcToggle; + [GUI] CheckButton _internetToggle; + [GUI] CheckButton _fsicToggle; + [GUI] RadioButton _mmSoftware; + [GUI] RadioButton _mmHost; + [GUI] RadioButton _mmHostUnsafe; + [GUI] CheckButton _expandRamToggle; + [GUI] CheckButton _ignoreToggle; + [GUI] CheckButton _directKeyboardAccess; + [GUI] CheckButton _directMouseAccess; + [GUI] ComboBoxText _systemLanguageSelect; + [GUI] ComboBoxText _systemRegionSelect; + [GUI] Entry _systemTimeZoneEntry; [GUI] EntryCompletion _systemTimeZoneCompletion; - [GUI] Box _audioBackendBox; - [GUI] ComboBox _audioBackendSelect; - [GUI] Label _audioVolumeLabel; - [GUI] Scale _audioVolumeSlider; - [GUI] SpinButton _systemTimeYearSpin; - [GUI] SpinButton _systemTimeMonthSpin; - [GUI] SpinButton _systemTimeDaySpin; - [GUI] SpinButton _systemTimeHourSpin; - [GUI] SpinButton _systemTimeMinuteSpin; - [GUI] Adjustment _systemTimeYearSpinAdjustment; - [GUI] Adjustment _systemTimeMonthSpinAdjustment; - [GUI] Adjustment _systemTimeDaySpinAdjustment; - [GUI] Adjustment _systemTimeHourSpinAdjustment; - [GUI] Adjustment _systemTimeMinuteSpinAdjustment; - [GUI] ComboBoxText _multiLanSelect; - [GUI] CheckButton _custThemeToggle; - [GUI] Entry _custThemePath; - [GUI] ToggleButton _browseThemePath; - [GUI] Label _custThemePathLabel; - [GUI] TreeView _gameDirsBox; - [GUI] Entry _addGameDirBox; - [GUI] ComboBoxText _galThreading; - [GUI] Entry _graphicsShadersDumpPath; - [GUI] ComboBoxText _anisotropy; - [GUI] ComboBoxText _aspectRatio; - [GUI] ComboBoxText _antiAliasing; - [GUI] ComboBoxText _scalingFilter; - [GUI] ComboBoxText _graphicsBackend; - [GUI] ComboBoxText _preferredGpu; - [GUI] ComboBoxText _resScaleCombo; - [GUI] Entry _resScaleText; - [GUI] Adjustment _scalingFilterLevel; - [GUI] Scale _scalingFilterSlider; - [GUI] ToggleButton _configureController1; - [GUI] ToggleButton _configureController2; - [GUI] ToggleButton _configureController3; - [GUI] ToggleButton _configureController4; - [GUI] ToggleButton _configureController5; - [GUI] ToggleButton _configureController6; - [GUI] ToggleButton _configureController7; - [GUI] ToggleButton _configureController8; - [GUI] ToggleButton _configureControllerH; + [GUI] Box _audioBackendBox; + [GUI] ComboBox _audioBackendSelect; + [GUI] Label _audioVolumeLabel; + [GUI] Scale _audioVolumeSlider; + [GUI] SpinButton _systemTimeYearSpin; + [GUI] SpinButton _systemTimeMonthSpin; + [GUI] SpinButton _systemTimeDaySpin; + [GUI] SpinButton _systemTimeHourSpin; + [GUI] SpinButton _systemTimeMinuteSpin; + [GUI] Adjustment _systemTimeYearSpinAdjustment; + [GUI] Adjustment _systemTimeMonthSpinAdjustment; + [GUI] Adjustment _systemTimeDaySpinAdjustment; + [GUI] Adjustment _systemTimeHourSpinAdjustment; + [GUI] Adjustment _systemTimeMinuteSpinAdjustment; + [GUI] ComboBoxText _multiLanSelect; + [GUI] CheckButton _custThemeToggle; + [GUI] Entry _custThemePath; + [GUI] ToggleButton _browseThemePath; + [GUI] Label _custThemePathLabel; + [GUI] TreeView _gameDirsBox; + [GUI] Entry _addGameDirBox; + [GUI] ComboBoxText _galThreading; + [GUI] Entry _graphicsShadersDumpPath; + [GUI] ComboBoxText _anisotropy; + [GUI] ComboBoxText _aspectRatio; + [GUI] ComboBoxText _antiAliasing; + [GUI] ComboBoxText _scalingFilter; + [GUI] ComboBoxText _graphicsBackend; + [GUI] ComboBoxText _preferredGpu; + [GUI] ComboBoxText _resScaleCombo; + [GUI] Entry _resScaleText; + [GUI] Adjustment _scalingFilterLevel; + [GUI] Scale _scalingFilterSlider; + [GUI] ToggleButton _configureController1; + [GUI] ToggleButton _configureController2; + [GUI] ToggleButton _configureController3; + [GUI] ToggleButton _configureController4; + [GUI] ToggleButton _configureController5; + [GUI] ToggleButton _configureController6; + [GUI] ToggleButton _configureController7; + [GUI] ToggleButton _configureController8; + [GUI] ToggleButton _configureControllerH; #pragma warning restore CS0649, IDE0044 @@ -316,11 +314,11 @@ namespace Ryujinx.Ui.Windows } // Custom EntryCompletion Columns. If added to glade, need to override more signals - ListStore tzList = new ListStore(typeof(string), typeof(string), typeof(string)); + ListStore tzList = new(typeof(string), typeof(string), typeof(string)); _systemTimeZoneCompletion.Model = tzList; - CellRendererText offsetCol = new CellRendererText(); - CellRendererText abbrevCol = new CellRendererText(); + CellRendererText offsetCol = new(); + CellRendererText abbrevCol = new(); _systemTimeZoneCompletion.PackStart(offsetCol, false); _systemTimeZoneCompletion.AddAttribute(offsetCol, "text", 0); @@ -364,17 +362,17 @@ namespace Ryujinx.Ui.Windows PopulateNetworkInterfaces(); _multiLanSelect.SetActiveId(ConfigurationState.Instance.Multiplayer.LanInterfaceId.Value); - _custThemePath.Buffer.Text = ConfigurationState.Instance.Ui.CustomThemePath; - _resScaleText.Buffer.Text = ConfigurationState.Instance.Graphics.ResScaleCustom.Value.ToString(); - _scalingFilterLevel.Value = ConfigurationState.Instance.Graphics.ScalingFilterLevel.Value; - _resScaleText.Visible = _resScaleCombo.ActiveId == "-1"; - _scalingFilterSlider.Visible = _scalingFilter.ActiveId == "2"; + _custThemePath.Buffer.Text = ConfigurationState.Instance.Ui.CustomThemePath; + _resScaleText.Buffer.Text = ConfigurationState.Instance.Graphics.ResScaleCustom.Value.ToString(); + _scalingFilterLevel.Value = ConfigurationState.Instance.Graphics.ScalingFilterLevel.Value; + _resScaleText.Visible = _resScaleCombo.ActiveId == "-1"; + _scalingFilterSlider.Visible = _scalingFilter.ActiveId == "2"; _graphicsShadersDumpPath.Buffer.Text = ConfigurationState.Instance.Graphics.ShadersDumpPath; - _fsLogSpinAdjustment.Value = ConfigurationState.Instance.System.FsGlobalAccessLogMode; - _systemTimeOffset = ConfigurationState.Instance.System.SystemTimeOffset; + _fsLogSpinAdjustment.Value = ConfigurationState.Instance.System.FsGlobalAccessLogMode; + _systemTimeOffset = ConfigurationState.Instance.System.SystemTimeOffset; _gameDirsBox.AppendColumn("", new CellRendererText(), "text", 0); - _gameDirsBoxStore = new ListStore(typeof(string)); + _gameDirsBoxStore = new ListStore(typeof(string)); _gameDirsBox.Model = _gameDirsBoxStore; foreach (string gameDir in ConfigurationState.Instance.Ui.GameDirs.Value) @@ -384,9 +382,9 @@ namespace Ryujinx.Ui.Windows if (_custThemeToggle.Active == false) { - _custThemePath.Sensitive = false; + _custThemePath.Sensitive = false; _custThemePathLabel.Sensitive = false; - _browseThemePath.Sensitive = false; + _browseThemePath.Sensitive = false; } // Setup system time spinners @@ -394,10 +392,10 @@ namespace Ryujinx.Ui.Windows _audioBackendStore = new ListStore(typeof(string), typeof(AudioBackend)); - TreeIter openAlIter = _audioBackendStore.AppendValues("OpenAL", AudioBackend.OpenAl); + TreeIter openAlIter = _audioBackendStore.AppendValues("OpenAL", AudioBackend.OpenAl); TreeIter soundIoIter = _audioBackendStore.AppendValues("SoundIO", AudioBackend.SoundIo); - TreeIter sdl2Iter = _audioBackendStore.AppendValues("SDL2", AudioBackend.SDL2); - TreeIter dummyIter = _audioBackendStore.AppendValues("Dummy", AudioBackend.Dummy); + TreeIter sdl2Iter = _audioBackendStore.AppendValues("SDL2", AudioBackend.SDL2); + TreeIter dummyIter = _audioBackendStore.AppendValues("Dummy", AudioBackend.Dummy); _audioBackendSelect = ComboBox.NewWithModelAndEntry(_audioBackendStore); _audioBackendSelect.EntryTextColumn = 0; @@ -418,35 +416,35 @@ namespace Ryujinx.Ui.Windows _audioBackendSelect.SetActiveIter(dummyIter); break; default: - throw new ArgumentOutOfRangeException(); + throw new InvalidOperationException($"{nameof(ConfigurationState.Instance.System.AudioBackend)} contains an invalid value: {ConfigurationState.Instance.System.AudioBackend.Value}"); } _audioBackendBox.Add(_audioBackendSelect); _audioBackendSelect.Show(); - _previousVolumeLevel = ConfigurationState.Instance.System.AudioVolume; - _audioVolumeLabel = new Label("Volume: "); - _audioVolumeSlider = new Scale(Orientation.Horizontal, 0, 100, 1); - _audioVolumeLabel.MarginStart = 10; - _audioVolumeSlider.ValuePos = PositionType.Right; + _previousVolumeLevel = ConfigurationState.Instance.System.AudioVolume; + _audioVolumeLabel = new Label("Volume: "); + _audioVolumeSlider = new Scale(Orientation.Horizontal, 0, 100, 1); + _audioVolumeLabel.MarginStart = 10; + _audioVolumeSlider.ValuePos = PositionType.Right; _audioVolumeSlider.WidthRequest = 200; - _audioVolumeSlider.Value = _previousVolumeLevel * 100; + _audioVolumeSlider.Value = _previousVolumeLevel * 100; _audioVolumeSlider.ValueChanged += VolumeSlider_OnChange; _audioBackendBox.Add(_audioVolumeLabel); _audioBackendBox.Add(_audioVolumeSlider); _audioVolumeLabel.Show(); _audioVolumeSlider.Show(); - bool openAlIsSupported = false; + bool openAlIsSupported = false; bool soundIoIsSupported = false; - bool sdl2IsSupported = false; + bool sdl2IsSupported = false; Task.Run(() => { - openAlIsSupported = OpenALHardwareDeviceDriver.IsSupported; + openAlIsSupported = OpenALHardwareDeviceDriver.IsSupported; soundIoIsSupported = !OperatingSystem.IsMacOS() && SoundIoHardwareDeviceDriver.IsSupported; - sdl2IsSupported = SDL2HardwareDeviceDriver.IsSupported; + sdl2IsSupported = SDL2HardwareDeviceDriver.IsSupported; }); // This function runs whenever the dropdown is opened @@ -454,18 +452,18 @@ namespace Ryujinx.Ui.Windows { cell.Sensitive = ((AudioBackend)_audioBackendStore.GetValue(iter, 1)) switch { - AudioBackend.OpenAl => openAlIsSupported, + AudioBackend.OpenAl => openAlIsSupported, AudioBackend.SoundIo => soundIoIsSupported, - AudioBackend.SDL2 => sdl2IsSupported, - AudioBackend.Dummy => true, - _ => throw new ArgumentOutOfRangeException() + AudioBackend.SDL2 => sdl2IsSupported, + AudioBackend.Dummy => true, + _ => throw new InvalidOperationException($"{nameof(_audioBackendStore)} contains an invalid value for iteration {iter}: {_audioBackendStore.GetValue(iter, 1)}"), }; }); if (OperatingSystem.IsMacOS()) { var store = (_graphicsBackend.Model as ListStore); - store.GetIter(out TreeIter openglIter, new TreePath(new int[] {1})); + store.GetIter(out TreeIter openglIter, new TreePath(new[] { 1 })); store.Remove(ref openglIter); _graphicsBackend.Model = store; @@ -478,15 +476,15 @@ namespace Ryujinx.Ui.Windows if (Enum.Parse(_graphicsBackend.ActiveId) == GraphicsBackend.Vulkan) { - var devices = VulkanRenderer.GetPhysicalDevices(); + var devices = Graphics.Vulkan.VulkanRenderer.GetPhysicalDevices(); string preferredGpuIdFromConfig = ConfigurationState.Instance.Graphics.PreferredGpu.Value; string preferredGpuId = preferredGpuIdFromConfig; bool noGpuId = string.IsNullOrEmpty(preferredGpuIdFromConfig); foreach (var device in devices) { - string dGPU = device.IsDiscrete ? " (dGPU)" : ""; - _preferredGpu.Append(device.Id, $"{device.Name}{dGPU}"); + string dGpu = device.IsDiscrete ? " (dGPU)" : ""; + _preferredGpu.Append(device.Id, $"{device.Name}{dGpu}"); // If there's no GPU selected yet, we just pick the first GPU. // If there's a discrete GPU available, we always prefer that over the previous selection, @@ -521,33 +519,33 @@ namespace Ryujinx.Ui.Windows private void UpdateSystemTimeSpinners() { //Bind system time events - _systemTimeYearSpin.ValueChanged -= SystemTimeSpin_ValueChanged; - _systemTimeMonthSpin.ValueChanged -= SystemTimeSpin_ValueChanged; - _systemTimeDaySpin.ValueChanged -= SystemTimeSpin_ValueChanged; - _systemTimeHourSpin.ValueChanged -= SystemTimeSpin_ValueChanged; + _systemTimeYearSpin.ValueChanged -= SystemTimeSpin_ValueChanged; + _systemTimeMonthSpin.ValueChanged -= SystemTimeSpin_ValueChanged; + _systemTimeDaySpin.ValueChanged -= SystemTimeSpin_ValueChanged; + _systemTimeHourSpin.ValueChanged -= SystemTimeSpin_ValueChanged; _systemTimeMinuteSpin.ValueChanged -= SystemTimeSpin_ValueChanged; //Apply actual system time + SystemTimeOffset to system time spin buttons DateTime systemTime = DateTime.Now.AddSeconds(_systemTimeOffset); - _systemTimeYearSpinAdjustment.Value = systemTime.Year; - _systemTimeMonthSpinAdjustment.Value = systemTime.Month; - _systemTimeDaySpinAdjustment.Value = systemTime.Day; - _systemTimeHourSpinAdjustment.Value = systemTime.Hour; + _systemTimeYearSpinAdjustment.Value = systemTime.Year; + _systemTimeMonthSpinAdjustment.Value = systemTime.Month; + _systemTimeDaySpinAdjustment.Value = systemTime.Day; + _systemTimeHourSpinAdjustment.Value = systemTime.Hour; _systemTimeMinuteSpinAdjustment.Value = systemTime.Minute; //Format spin buttons text to include leading zeros - _systemTimeYearSpin.Text = systemTime.Year.ToString("0000"); - _systemTimeMonthSpin.Text = systemTime.Month.ToString("00"); - _systemTimeDaySpin.Text = systemTime.Day.ToString("00"); - _systemTimeHourSpin.Text = systemTime.Hour.ToString("00"); + _systemTimeYearSpin.Text = systemTime.Year.ToString("0000"); + _systemTimeMonthSpin.Text = systemTime.Month.ToString("00"); + _systemTimeDaySpin.Text = systemTime.Day.ToString("00"); + _systemTimeHourSpin.Text = systemTime.Hour.ToString("00"); _systemTimeMinuteSpin.Text = systemTime.Minute.ToString("00"); //Bind system time events - _systemTimeYearSpin.ValueChanged += SystemTimeSpin_ValueChanged; - _systemTimeMonthSpin.ValueChanged += SystemTimeSpin_ValueChanged; - _systemTimeDaySpin.ValueChanged += SystemTimeSpin_ValueChanged; - _systemTimeHourSpin.ValueChanged += SystemTimeSpin_ValueChanged; + _systemTimeYearSpin.ValueChanged += SystemTimeSpin_ValueChanged; + _systemTimeMonthSpin.ValueChanged += SystemTimeSpin_ValueChanged; + _systemTimeDaySpin.ValueChanged += SystemTimeSpin_ValueChanged; + _systemTimeHourSpin.ValueChanged += SystemTimeSpin_ValueChanged; _systemTimeMinuteSpin.ValueChanged += SystemTimeSpin_ValueChanged; } @@ -555,7 +553,7 @@ namespace Ryujinx.Ui.Windows { if (_directoryChanged) { - List gameDirs = new List(); + List gameDirs = new(); _gameDirsBoxStore.GetIterFirst(out TreeIter treeIter); @@ -611,52 +609,52 @@ namespace Ryujinx.Ui.Windows DriverUtilities.ToggleOGLThreading(backendThreading == BackendThreading.Off); } - ConfigurationState.Instance.Logger.EnableError.Value = _errorLogToggle.Active; - ConfigurationState.Instance.Logger.EnableTrace.Value = _traceLogToggle.Active; - ConfigurationState.Instance.Logger.EnableWarn.Value = _warningLogToggle.Active; - ConfigurationState.Instance.Logger.EnableInfo.Value = _infoLogToggle.Active; - ConfigurationState.Instance.Logger.EnableStub.Value = _stubLogToggle.Active; - ConfigurationState.Instance.Logger.EnableDebug.Value = _debugLogToggle.Active; - ConfigurationState.Instance.Logger.EnableGuest.Value = _guestLogToggle.Active; - ConfigurationState.Instance.Logger.EnableFsAccessLog.Value = _fsAccessLogToggle.Active; - ConfigurationState.Instance.Logger.EnableFileLog.Value = _fileLogToggle.Active; - ConfigurationState.Instance.Logger.GraphicsDebugLevel.Value = Enum.Parse(_graphicsDebugLevel.ActiveId); - ConfigurationState.Instance.System.EnableDockedMode.Value = _dockedModeToggle.Active; - ConfigurationState.Instance.EnableDiscordIntegration.Value = _discordToggle.Active; - ConfigurationState.Instance.CheckUpdatesOnStart.Value = _checkUpdatesToggle.Active; - ConfigurationState.Instance.ShowConfirmExit.Value = _showConfirmExitToggle.Active; - ConfigurationState.Instance.HideCursor.Value = hideCursor; - ConfigurationState.Instance.Graphics.EnableVsync.Value = _vSyncToggle.Active; - ConfigurationState.Instance.Graphics.EnableShaderCache.Value = _shaderCacheToggle.Active; + ConfigurationState.Instance.Logger.EnableError.Value = _errorLogToggle.Active; + ConfigurationState.Instance.Logger.EnableTrace.Value = _traceLogToggle.Active; + ConfigurationState.Instance.Logger.EnableWarn.Value = _warningLogToggle.Active; + ConfigurationState.Instance.Logger.EnableInfo.Value = _infoLogToggle.Active; + ConfigurationState.Instance.Logger.EnableStub.Value = _stubLogToggle.Active; + ConfigurationState.Instance.Logger.EnableDebug.Value = _debugLogToggle.Active; + ConfigurationState.Instance.Logger.EnableGuest.Value = _guestLogToggle.Active; + ConfigurationState.Instance.Logger.EnableFsAccessLog.Value = _fsAccessLogToggle.Active; + ConfigurationState.Instance.Logger.EnableFileLog.Value = _fileLogToggle.Active; + ConfigurationState.Instance.Logger.GraphicsDebugLevel.Value = Enum.Parse(_graphicsDebugLevel.ActiveId); + ConfigurationState.Instance.System.EnableDockedMode.Value = _dockedModeToggle.Active; + ConfigurationState.Instance.EnableDiscordIntegration.Value = _discordToggle.Active; + ConfigurationState.Instance.CheckUpdatesOnStart.Value = _checkUpdatesToggle.Active; + ConfigurationState.Instance.ShowConfirmExit.Value = _showConfirmExitToggle.Active; + ConfigurationState.Instance.HideCursor.Value = hideCursor; + ConfigurationState.Instance.Graphics.EnableVsync.Value = _vSyncToggle.Active; + ConfigurationState.Instance.Graphics.EnableShaderCache.Value = _shaderCacheToggle.Active; ConfigurationState.Instance.Graphics.EnableTextureRecompression.Value = _textureRecompressionToggle.Active; - ConfigurationState.Instance.Graphics.EnableMacroHLE.Value = _macroHLEToggle.Active; - ConfigurationState.Instance.System.EnablePtc.Value = _ptcToggle.Active; - ConfigurationState.Instance.System.EnableInternetAccess.Value = _internetToggle.Active; - ConfigurationState.Instance.System.EnableFsIntegrityChecks.Value = _fsicToggle.Active; - ConfigurationState.Instance.System.MemoryManagerMode.Value = memoryMode; - ConfigurationState.Instance.System.ExpandRam.Value = _expandRamToggle.Active; - ConfigurationState.Instance.System.IgnoreMissingServices.Value = _ignoreToggle.Active; - ConfigurationState.Instance.Hid.EnableKeyboard.Value = _directKeyboardAccess.Active; - ConfigurationState.Instance.Hid.EnableMouse.Value = _directMouseAccess.Active; - ConfigurationState.Instance.Ui.EnableCustomTheme.Value = _custThemeToggle.Active; - ConfigurationState.Instance.System.Language.Value = Enum.Parse(_systemLanguageSelect.ActiveId); - ConfigurationState.Instance.System.Region.Value = Enum.Parse(_systemRegionSelect.ActiveId); - ConfigurationState.Instance.System.SystemTimeOffset.Value = _systemTimeOffset; - ConfigurationState.Instance.Ui.CustomThemePath.Value = _custThemePath.Buffer.Text; - ConfigurationState.Instance.Graphics.ShadersDumpPath.Value = _graphicsShadersDumpPath.Buffer.Text; - ConfigurationState.Instance.System.FsGlobalAccessLogMode.Value = (int)_fsLogSpinAdjustment.Value; - ConfigurationState.Instance.Graphics.MaxAnisotropy.Value = float.Parse(_anisotropy.ActiveId, CultureInfo.InvariantCulture); - ConfigurationState.Instance.Graphics.AspectRatio.Value = Enum.Parse(_aspectRatio.ActiveId); - ConfigurationState.Instance.Graphics.BackendThreading.Value = backendThreading; - ConfigurationState.Instance.Graphics.GraphicsBackend.Value = Enum.Parse(_graphicsBackend.ActiveId); - ConfigurationState.Instance.Graphics.PreferredGpu.Value = _preferredGpu.ActiveId; - ConfigurationState.Instance.Graphics.ResScale.Value = int.Parse(_resScaleCombo.ActiveId); - ConfigurationState.Instance.Graphics.ResScaleCustom.Value = resScaleCustom; - ConfigurationState.Instance.System.AudioVolume.Value = (float)_audioVolumeSlider.Value / 100.0f; - ConfigurationState.Instance.Graphics.AntiAliasing.Value = Enum.Parse(_antiAliasing.ActiveId); - ConfigurationState.Instance.Graphics.ScalingFilter.Value = Enum.Parse(_scalingFilter.ActiveId); - ConfigurationState.Instance.Graphics.ScalingFilterLevel.Value = (int)_scalingFilterLevel.Value; - ConfigurationState.Instance.Multiplayer.LanInterfaceId.Value = _multiLanSelect.ActiveId; + ConfigurationState.Instance.Graphics.EnableMacroHLE.Value = _macroHLEToggle.Active; + ConfigurationState.Instance.System.EnablePtc.Value = _ptcToggle.Active; + ConfigurationState.Instance.System.EnableInternetAccess.Value = _internetToggle.Active; + ConfigurationState.Instance.System.EnableFsIntegrityChecks.Value = _fsicToggle.Active; + ConfigurationState.Instance.System.MemoryManagerMode.Value = memoryMode; + ConfigurationState.Instance.System.ExpandRam.Value = _expandRamToggle.Active; + ConfigurationState.Instance.System.IgnoreMissingServices.Value = _ignoreToggle.Active; + ConfigurationState.Instance.Hid.EnableKeyboard.Value = _directKeyboardAccess.Active; + ConfigurationState.Instance.Hid.EnableMouse.Value = _directMouseAccess.Active; + ConfigurationState.Instance.Ui.EnableCustomTheme.Value = _custThemeToggle.Active; + ConfigurationState.Instance.System.Language.Value = Enum.Parse(_systemLanguageSelect.ActiveId); + ConfigurationState.Instance.System.Region.Value = Enum.Parse(_systemRegionSelect.ActiveId); + ConfigurationState.Instance.System.SystemTimeOffset.Value = _systemTimeOffset; + ConfigurationState.Instance.Ui.CustomThemePath.Value = _custThemePath.Buffer.Text; + ConfigurationState.Instance.Graphics.ShadersDumpPath.Value = _graphicsShadersDumpPath.Buffer.Text; + ConfigurationState.Instance.System.FsGlobalAccessLogMode.Value = (int)_fsLogSpinAdjustment.Value; + ConfigurationState.Instance.Graphics.MaxAnisotropy.Value = float.Parse(_anisotropy.ActiveId, CultureInfo.InvariantCulture); + ConfigurationState.Instance.Graphics.AspectRatio.Value = Enum.Parse(_aspectRatio.ActiveId); + ConfigurationState.Instance.Graphics.BackendThreading.Value = backendThreading; + ConfigurationState.Instance.Graphics.GraphicsBackend.Value = Enum.Parse(_graphicsBackend.ActiveId); + ConfigurationState.Instance.Graphics.PreferredGpu.Value = _preferredGpu.ActiveId; + ConfigurationState.Instance.Graphics.ResScale.Value = int.Parse(_resScaleCombo.ActiveId); + ConfigurationState.Instance.Graphics.ResScaleCustom.Value = resScaleCustom; + ConfigurationState.Instance.System.AudioVolume.Value = (float)_audioVolumeSlider.Value / 100.0f; + ConfigurationState.Instance.Graphics.AntiAliasing.Value = Enum.Parse(_antiAliasing.ActiveId); + ConfigurationState.Instance.Graphics.ScalingFilter.Value = Enum.Parse(_scalingFilter.ActiveId); + ConfigurationState.Instance.Graphics.ScalingFilterLevel.Value = (int)_scalingFilterLevel.Value; + ConfigurationState.Instance.Multiplayer.LanInterfaceId.Value = _multiLanSelect.ActiveId; _previousVolumeLevel = ConfigurationState.Instance.System.AudioVolume.Value; @@ -666,7 +664,7 @@ namespace Ryujinx.Ui.Windows } ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath); - _parent.UpdateGraphicsConfig(); + MainWindow.UpdateGraphicsConfig(); ThemeHelper.ApplyTheme(); } @@ -692,10 +690,10 @@ namespace Ryujinx.Ui.Windows private void SystemTimeSpin_ValueChanged(object sender, EventArgs e) { - int year = _systemTimeYearSpin.ValueAsInt; - int month = _systemTimeMonthSpin.ValueAsInt; - int day = _systemTimeDaySpin.ValueAsInt; - int hour = _systemTimeHourSpin.ValueAsInt; + int year = _systemTimeYearSpin.ValueAsInt; + int month = _systemTimeMonthSpin.ValueAsInt; + int day = _systemTimeDaySpin.ValueAsInt; + int hour = _systemTimeHourSpin.ValueAsInt; int minute = _systemTimeMinuteSpin.ValueAsInt; if (!DateTime.TryParse(year + "-" + month + "-" + day + " " + hour + ":" + minute, out DateTime newTime)) @@ -725,9 +723,9 @@ namespace Ryujinx.Ui.Windows } else { - FileChooserNative fileChooser = new FileChooserNative("Choose the game directory to add to the list", this, FileChooserAction.SelectFolder, "Add", "Cancel") + FileChooserNative fileChooser = new("Choose the game directory to add to the list", this, FileChooserAction.SelectFolder, "Add", "Cancel") { - SelectMultiple = true + SelectMultiple = true, }; if (fileChooser.Run() == (int)ResponseType.Accept) @@ -779,18 +777,18 @@ namespace Ryujinx.Ui.Windows private void CustThemeToggle_Activated(object sender, EventArgs args) { - _custThemePath.Sensitive = _custThemeToggle.Active; + _custThemePath.Sensitive = _custThemeToggle.Active; _custThemePathLabel.Sensitive = _custThemeToggle.Active; - _browseThemePath.Sensitive = _custThemeToggle.Active; + _browseThemePath.Sensitive = _custThemeToggle.Active; } private void BrowseThemeDir_Pressed(object sender, EventArgs args) { - using (FileChooserNative fileChooser = new FileChooserNative("Choose the theme to load", this, FileChooserAction.Open, "Select", "Cancel")) + using (FileChooserNative fileChooser = new("Choose the theme to load", this, FileChooserAction.Open, "Select", "Cancel")) { - FileFilter filter = new FileFilter() + FileFilter filter = new() { - Name = "Theme Files" + Name = "Theme Files", }; filter.AddPattern("*.css"); @@ -809,7 +807,7 @@ namespace Ryujinx.Ui.Windows { ((ToggleButton)sender).SetStateFlags(StateFlags.Normal, true); - ControllerWindow controllerWindow = new ControllerWindow(_parent, playerIndex); + ControllerWindow controllerWindow = new(_parent, playerIndex); controllerWindow.SetSizeRequest((int)(controllerWindow.DefaultWidth * Program.WindowScaleFactor), (int)(controllerWindow.DefaultHeight * Program.WindowScaleFactor)); controllerWindow.Show(); diff --git a/src/Ryujinx/Ui/Windows/TitleUpdateWindow.cs b/src/Ryujinx/Ui/Windows/TitleUpdateWindow.cs index c40adc116..044f7e95a 100644 --- a/src/Ryujinx/Ui/Windows/TitleUpdateWindow.cs +++ b/src/Ryujinx/Ui/Windows/TitleUpdateWindow.cs @@ -9,33 +9,32 @@ using LibHac.Tools.FsSystem.NcaUtils; using Ryujinx.Common.Configuration; using Ryujinx.Common.Utilities; using Ryujinx.HLE.FileSystem; -using Ryujinx.HLE.HOS; using Ryujinx.Ui.App.Common; using Ryujinx.Ui.Widgets; using System; using System.Collections.Generic; using System.IO; using System.Linq; -using GUI = Gtk.Builder.ObjectAttribute; +using GUI = Gtk.Builder.ObjectAttribute; using SpanHelpers = LibHac.Common.SpanHelpers; namespace Ryujinx.Ui.Windows { public class TitleUpdateWindow : Window { - private readonly MainWindow _parent; + private readonly MainWindow _parent; private readonly VirtualFileSystem _virtualFileSystem; - private readonly string _titleId; - private readonly string _updateJsonPath; + private readonly string _titleId; + private readonly string _updateJsonPath; private TitleUpdateMetadata _titleUpdateWindowData; private readonly Dictionary _radioButtonToPathDictionary; - private static readonly TitleUpdateMetadataJsonSerializerContext SerializerContext = new(JsonHelper.GetDefaultSerializerOptions()); + private static readonly TitleUpdateMetadataJsonSerializerContext _serializerContext = new(JsonHelper.GetDefaultSerializerOptions()); -#pragma warning disable CS0649, IDE0044 - [GUI] Label _baseTitleInfoLabel; - [GUI] Box _availableUpdatesBox; +#pragma warning disable CS0649, IDE0044 // Field is never assigned to, Add readonly modifier + [GUI] Label _baseTitleInfoLabel; + [GUI] Box _availableUpdatesBox; [GUI] RadioButton _noUpdateRadioButton; #pragma warning restore CS0649, IDE0044 @@ -47,26 +46,26 @@ namespace Ryujinx.Ui.Windows builder.Autoconnect(this); - _titleId = titleId; - _virtualFileSystem = virtualFileSystem; - _updateJsonPath = System.IO.Path.Combine(AppDataManager.GamesDirPath, _titleId, "updates.json"); + _titleId = titleId; + _virtualFileSystem = virtualFileSystem; + _updateJsonPath = System.IO.Path.Combine(AppDataManager.GamesDirPath, _titleId, "updates.json"); _radioButtonToPathDictionary = new Dictionary(); try { - _titleUpdateWindowData = JsonHelper.DeserializeFromFile(_updateJsonPath, SerializerContext.TitleUpdateMetadata); + _titleUpdateWindowData = JsonHelper.DeserializeFromFile(_updateJsonPath, _serializerContext.TitleUpdateMetadata); } catch { _titleUpdateWindowData = new TitleUpdateMetadata { Selected = "", - Paths = new List() + Paths = new List(), }; } _baseTitleInfoLabel.Text = $"Updates Available for {titleName} [{titleId.ToUpper()}]"; - + foreach (string path in _titleUpdateWindowData.Paths) { AddUpdate(path); @@ -89,42 +88,41 @@ namespace Ryujinx.Ui.Windows { if (File.Exists(path)) { - using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read)) + using FileStream file = new(path, FileMode.Open, FileAccess.Read); + + PartitionFileSystem nsp = new(file.AsStorage()); + + try { - PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage()); + (Nca patchNca, Nca controlNca) = ApplicationLibrary.GetGameUpdateDataFromPartition(_virtualFileSystem, nsp, _titleId, 0); - try + if (controlNca != null && patchNca != null) { - (Nca patchNca, Nca controlNca) = ApplicationLibrary.GetGameUpdateDataFromPartition(_virtualFileSystem, nsp, _titleId, 0); + ApplicationControlProperty controlData = new(); - if (controlNca != null && patchNca != null) - { - ApplicationControlProperty controlData = new ApplicationControlProperty(); + using var nacpFile = new UniqueRef(); - using var nacpFile = new UniqueRef(); + controlNca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.None).OpenFile(ref nacpFile.Ref, "/control.nacp".ToU8Span(), OpenMode.Read).ThrowIfFailure(); + nacpFile.Get.Read(out _, 0, SpanHelpers.AsByteSpan(ref controlData), ReadOption.None).ThrowIfFailure(); - controlNca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.None).OpenFile(ref nacpFile.Ref, "/control.nacp".ToU8Span(), OpenMode.Read).ThrowIfFailure(); - nacpFile.Get.Read(out _, 0, SpanHelpers.AsByteSpan(ref controlData), ReadOption.None).ThrowIfFailure(); + RadioButton radioButton = new($"Version {controlData.DisplayVersionString.ToString()} - {path}"); + radioButton.JoinGroup(_noUpdateRadioButton); - RadioButton radioButton = new RadioButton($"Version {controlData.DisplayVersionString.ToString()} - {path}"); - radioButton.JoinGroup(_noUpdateRadioButton); + _availableUpdatesBox.Add(radioButton); + _radioButtonToPathDictionary.Add(radioButton, path); - _availableUpdatesBox.Add(radioButton); - _radioButtonToPathDictionary.Add(radioButton, path); - - radioButton.Show(); - radioButton.Active = true; - } - else - { - GtkDialog.CreateErrorDialog("The specified file does not contain an update for the selected title!"); - } + radioButton.Show(); + radioButton.Active = true; } - catch (Exception exception) + else { - GtkDialog.CreateErrorDialog($"{exception.Message}. Errored File: {path}"); + GtkDialog.CreateErrorDialog("The specified file does not contain an update for the selected title!"); } } + catch (Exception exception) + { + GtkDialog.CreateErrorDialog($"{exception.Message}. Errored File: {path}"); + } } } @@ -143,24 +141,23 @@ namespace Ryujinx.Ui.Windows private void AddButton_Clicked(object sender, EventArgs args) { - using (FileChooserNative fileChooser = new FileChooserNative("Select update files", this, FileChooserAction.Open, "Add", "Cancel")) + using FileChooserNative fileChooser = new("Select update files", this, FileChooserAction.Open, "Add", "Cancel"); + + fileChooser.SelectMultiple = true; + + FileFilter filter = new() { - fileChooser.SelectMultiple = true; + Name = "Switch Game Updates", + }; + filter.AddPattern("*.nsp"); - FileFilter filter = new FileFilter() + fileChooser.AddFilter(filter); + + if (fileChooser.Run() == (int)ResponseType.Accept) + { + foreach (string path in fileChooser.Filenames) { - Name = "Switch Game Updates" - }; - filter.AddPattern("*.nsp"); - - fileChooser.AddFilter(filter); - - if (fileChooser.Run() == (int)ResponseType.Accept) - { - foreach (string path in fileChooser.Filenames) - { - AddUpdate(path); - } + AddUpdate(path); } } } @@ -193,7 +190,7 @@ namespace Ryujinx.Ui.Windows } } - JsonHelper.SerializeToFile(_updateJsonPath, _titleUpdateWindowData, SerializerContext.TitleUpdateMetadata); + JsonHelper.SerializeToFile(_updateJsonPath, _titleUpdateWindowData, _serializerContext.TitleUpdateMetadata); _parent.UpdateGameTable(); @@ -205,4 +202,4 @@ namespace Ryujinx.Ui.Windows Dispose(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Ui/Windows/UserProfilesManagerWindow.Designer.cs b/src/Ryujinx/Ui/Windows/UserProfilesManagerWindow.Designer.cs index 7c9ae8baa..804bd3fb0 100644 --- a/src/Ryujinx/Ui/Windows/UserProfilesManagerWindow.Designer.cs +++ b/src/Ryujinx/Ui/Windows/UserProfilesManagerWindow.Designer.cs @@ -1,45 +1,43 @@ using Gtk; using Pango; +using System; namespace Ryujinx.Ui.Windows { public partial class UserProfilesManagerWindow : Window { - private Box _mainBox; - private Label _selectedLabel; - private Box _selectedUserBox; - private Image _selectedUserImage; - private VBox _selectedUserInfoBox; - private Entry _selectedUserNameEntry; - private Label _selectedUserIdLabel; - private VBox _selectedUserButtonsBox; - private Button _saveProfileNameButton; - private Button _changeProfileImageButton; - private Box _usersTreeViewBox; - private Label _availableUsersLabel; + private Box _mainBox; + private Label _selectedLabel; + private Box _selectedUserBox; + private Image _selectedUserImage; + private Box _selectedUserInfoBox; + private Entry _selectedUserNameEntry; + private Label _selectedUserIdLabel; + private Box _selectedUserButtonsBox; + private Button _saveProfileNameButton; + private Button _changeProfileImageButton; + private Box _usersTreeViewBox; + private Label _availableUsersLabel; private ScrolledWindow _usersTreeViewWindow; - private ListStore _tableStore; - private TreeView _usersTreeView; - private Box _bottomBox; - private Button _addButton; - private Button _deleteButton; - private Button _closeButton; + private ListStore _tableStore; + private TreeView _usersTreeView; + private Box _bottomBox; + private Button _addButton; + private Button _deleteButton; + private Button _closeButton; private void InitializeComponent() { - -#pragma warning disable CS0612 - // // UserProfilesManagerWindow // - CanFocus = false; - Resizable = false; - Modal = true; + CanFocus = false; + Resizable = false; + Modal = true; WindowPosition = WindowPosition.Center; - DefaultWidth = 620; - DefaultHeight = 548; - TypeHint = Gdk.WindowTypeHint.Dialog; + DefaultWidth = 620; + DefaultHeight = 548; + TypeHint = Gdk.WindowTypeHint.Dialog; // // _mainBox @@ -51,9 +49,9 @@ namespace Ryujinx.Ui.Windows // _selectedLabel = new Label("Selected User Profile:") { - Margin = 15, + Margin = 15, Attributes = new AttrList(), - Halign = Align.Start + Halign = Align.Start, }; _selectedLabel.Attributes.Insert(new Pango.AttrWeight(Weight.Bold)); @@ -67,7 +65,7 @@ namespace Ryujinx.Ui.Windows // _selectedUserBox = new Box(Orientation.Horizontal, 0) { - MarginLeft = 30 + MarginStart = 30, }; // @@ -78,15 +76,18 @@ namespace Ryujinx.Ui.Windows // // _selectedUserInfoBox // - _selectedUserInfoBox = new VBox(true, 0); + _selectedUserInfoBox = new Box(Orientation.Vertical, 0) + { + Homogeneous = true, + }; // // _selectedUserNameEntry // _selectedUserNameEntry = new Entry("") { - MarginLeft = 15, - MaxLength = (int)MaxProfileNameLength + MarginStart = 15, + MaxLength = (int)MaxProfileNameLength, }; _selectedUserNameEntry.KeyReleaseEvent += SelectedUserNameEntry_KeyReleaseEvent; @@ -95,16 +96,16 @@ namespace Ryujinx.Ui.Windows // _selectedUserIdLabel = new Label("") { - MarginTop = 15, - MarginLeft = 15 + MarginTop = 15, + MarginStart = 15, }; // // _selectedUserButtonsBox // - _selectedUserButtonsBox = new VBox() + _selectedUserButtonsBox = new Box(Orientation.Vertical, 0) { - MarginRight = 30 + MarginEnd = 30, }; // @@ -112,10 +113,10 @@ namespace Ryujinx.Ui.Windows // _saveProfileNameButton = new Button() { - Label = "Save Profile Name", - CanFocus = true, + Label = "Save Profile Name", + CanFocus = true, ReceivesDefault = true, - Sensitive = false + Sensitive = false, }; _saveProfileNameButton.Clicked += EditProfileNameButton_Pressed; @@ -124,10 +125,10 @@ namespace Ryujinx.Ui.Windows // _changeProfileImageButton = new Button() { - Label = "Change Profile Image", - CanFocus = true, + Label = "Change Profile Image", + CanFocus = true, ReceivesDefault = true, - MarginTop = 10 + MarginTop = 10, }; _changeProfileImageButton.Clicked += ChangeProfileImageButton_Pressed; @@ -136,9 +137,9 @@ namespace Ryujinx.Ui.Windows // _availableUsersLabel = new Label("Available User Profiles:") { - Margin = 15, + Margin = 15, Attributes = new AttrList(), - Halign = Align.Start + Halign = Align.Start, }; _availableUsersLabel.Attributes.Insert(new Pango.AttrWeight(Weight.Bold)); @@ -147,12 +148,12 @@ namespace Ryujinx.Ui.Windows // _usersTreeViewWindow = new ScrolledWindow() { - ShadowType = ShadowType.In, - CanFocus = true, - Expand = true, - MarginLeft = 30, - MarginRight = 30, - MarginBottom = 15 + ShadowType = ShadowType.In, + CanFocus = true, + Expand = true, + MarginStart = 30, + MarginEnd = 30, + MarginBottom = 15, }; // @@ -175,9 +176,9 @@ namespace Ryujinx.Ui.Windows // _bottomBox = new Box(Orientation.Horizontal, 0) { - MarginLeft = 30, - MarginRight = 30, - MarginBottom = 15 + MarginStart = 30, + MarginEnd = 30, + MarginBottom = 15, }; // @@ -185,10 +186,10 @@ namespace Ryujinx.Ui.Windows // _addButton = new Button() { - Label = "Add New Profile", - CanFocus = true, + Label = "Add New Profile", + CanFocus = true, ReceivesDefault = true, - HeightRequest = 35 + HeightRequest = 35, }; _addButton.Clicked += AddButton_Pressed; @@ -197,11 +198,11 @@ namespace Ryujinx.Ui.Windows // _deleteButton = new Button() { - Label = "Delete Selected Profile", - CanFocus = true, + Label = "Delete Selected Profile", + CanFocus = true, ReceivesDefault = true, - HeightRequest = 35, - MarginLeft = 10 + HeightRequest = 35, + MarginStart = 10, }; _deleteButton.Clicked += DeleteButton_Pressed; @@ -210,16 +211,14 @@ namespace Ryujinx.Ui.Windows // _closeButton = new Button() { - Label = "Close", - CanFocus = true, + Label = "Close", + CanFocus = true, ReceivesDefault = true, - HeightRequest = 35, - WidthRequest = 80 + HeightRequest = 35, + WidthRequest = 80, }; _closeButton.Clicked += CloseButton_Pressed; -#pragma warning restore CS0612 - ShowComponent(); } @@ -253,4 +252,4 @@ namespace Ryujinx.Ui.Windows ShowAll(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx/Ui/Windows/UserProfilesManagerWindow.cs b/src/Ryujinx/Ui/Windows/UserProfilesManagerWindow.cs index a08b5dd17..c2ca010c7 100644 --- a/src/Ryujinx/Ui/Windows/UserProfilesManagerWindow.cs +++ b/src/Ryujinx/Ui/Windows/UserProfilesManagerWindow.cs @@ -13,7 +13,6 @@ using System.Reflection; using System.Threading; using System.Threading.Tasks; using Image = SixLabors.ImageSharp.Image; -using UserId = Ryujinx.HLE.HOS.Services.Account.Acc.UserId; namespace Ryujinx.Ui.Windows { @@ -29,7 +28,7 @@ namespace Ryujinx.Ui.Windows private Gdk.RGBA _selectedColor; - private ManualResetEvent _avatarsPreloadingEvent = new ManualResetEvent(false); + private readonly ManualResetEvent _avatarsPreloadingEvent = new(false); public UserProfilesManagerWindow(AccountManager accountManager, ContentManager contentManager, VirtualFileSystem virtualFileSystem) : base($"Ryujinx {Program.Version} - Manage User Profiles") { @@ -37,24 +36,24 @@ namespace Ryujinx.Ui.Windows InitializeComponent(); - _selectedColor.Red = 0.212; + _selectedColor.Red = 0.212; _selectedColor.Green = 0.843; - _selectedColor.Blue = 0.718; + _selectedColor.Blue = 0.718; _selectedColor.Alpha = 1; _accountManager = accountManager; _contentManager = contentManager; - CellRendererToggle userSelectedToggle = new CellRendererToggle(); + CellRendererToggle userSelectedToggle = new(); userSelectedToggle.Toggled += UserSelectedToggle_Toggled; // NOTE: Uncomment following line when multiple selection of user profiles is supported. //_usersTreeView.AppendColumn("Selected", userSelectedToggle, "active", 0); _usersTreeView.AppendColumn("User Icon", new CellRendererPixbuf(), "pixbuf", 1); - _usersTreeView.AppendColumn("User Info", new CellRendererText(), "text", 2, "background-rgba", 3); + _usersTreeView.AppendColumn("User Info", new CellRendererText(), "text", 2, "background-rgba", 3); _tableStore.SetSortColumnId(0, SortType.Descending); - + RefreshList(); if (_contentManager.GetCurrentFirmwareVersion() != null) @@ -77,8 +76,8 @@ namespace Ryujinx.Ui.Windows if (userProfile.AccountState == AccountState.Open) { - _selectedUserImage.Pixbuf = new Gdk.Pixbuf(userProfile.Image, 96, 96); - _selectedUserIdLabel.Text = userProfile.UserId.ToString(); + _selectedUserImage.Pixbuf = new Gdk.Pixbuf(userProfile.Image, 96, 96); + _selectedUserIdLabel.Text = userProfile.UserId.ToString(); _selectedUserNameEntry.Text = userProfile.Name; _deleteButton.Sensitive = userProfile.UserId != AccountManager.DefaultUserId; @@ -111,7 +110,7 @@ namespace Ryujinx.Ui.Windows Gdk.Pixbuf userPicture = (Gdk.Pixbuf)_tableStore.GetValue(selectedIter, 1); string userName = _tableStore.GetValue(selectedIter, 2).ToString().Split("\n")[0]; - string userId = _tableStore.GetValue(selectedIter, 2).ToString().Split("\n")[1]; + string userId = _tableStore.GetValue(selectedIter, 2).ToString().Split("\n")[1]; // Unselect the first user. _usersTreeView.Model.GetIterFirst(out TreeIter firstIter); @@ -121,9 +120,9 @@ namespace Ryujinx.Ui.Windows // Set new informations. _tableStore.SetValue(selectedIter, 0, true); - _selectedUserImage.Pixbuf = userPicture; - _selectedUserNameEntry.Text = userName; - _selectedUserIdLabel.Text = userId; + _selectedUserImage.Pixbuf = userPicture; + _selectedUserNameEntry.Text = userName; + _selectedUserIdLabel.Text = userId; _saveProfileNameButton.Sensitive = false; // Open the selected one. @@ -178,29 +177,27 @@ namespace Ryujinx.Ui.Windows private void ProcessProfileImage(byte[] buffer) { - using (Image image = Image.Load(buffer)) - { - image.Mutate(x => x.Resize(256, 256)); + using Image image = Image.Load(buffer); - using (MemoryStream streamJpg = MemoryStreamManager.Shared.GetStream()) - { - image.SaveAsJpeg(streamJpg); + image.Mutate(x => x.Resize(256, 256)); - _bufferImageProfile = streamJpg.ToArray(); - } - } + using MemoryStream streamJpg = MemoryStreamManager.Shared.GetStream(); + + image.SaveAsJpeg(streamJpg); + + _bufferImageProfile = streamJpg.ToArray(); } private void ProfileImageFileChooser() { - FileChooserNative fileChooser = new FileChooserNative("Import Custom Profile Image", this, FileChooserAction.Open, "Import", "Cancel") + FileChooserNative fileChooser = new("Import Custom Profile Image", this, FileChooserAction.Open, "Import", "Cancel") { - SelectMultiple = false + SelectMultiple = false, }; - FileFilter filter = new FileFilter() + FileFilter filter = new() { - Name = "Custom Profile Images" + Name = "Custom Profile Images", }; filter.AddPattern("*.jpg"); filter.AddPattern("*.jpeg"); @@ -225,15 +222,15 @@ namespace Ryujinx.Ui.Windows } else { - Dictionary buttons = new Dictionary() + Dictionary buttons = new() { { 0, "Import Image File" }, - { 1, "Select Firmware Avatar" } + { 1, "Select Firmware Avatar" }, }; ResponseType responseDialog = GtkDialog.CreateCustomDialog("Profile Image Selection", "Choose a Profile Image", - "You may import a custom profile image, or select an avatar from the system firmware.", + "You may import a custom profile image, or select an avatar from the system firmware.", buttons, MessageType.Question); if (responseDialog == 0) @@ -242,9 +239,9 @@ namespace Ryujinx.Ui.Windows } else if (responseDialog == (ResponseType)1) { - AvatarWindow avatarWindow = new AvatarWindow() + AvatarWindow avatarWindow = new() { - NewUser = newUser + NewUser = newUser, }; avatarWindow.DeleteEvent += AvatarWindow_DeleteEvent; @@ -328,4 +325,4 @@ namespace Ryujinx.Ui.Windows Close(); } } -} \ No newline at end of file +}