From be3bd0bcb5ee8c3f15a0c09feaddfe64b1eb6cb9 Mon Sep 17 00:00:00 2001 From: Evan Husted Date: Sat, 25 Jan 2025 14:00:23 -0600 Subject: [PATCH 01/19] misc: chore: Use explicit types in the Avalonia project --- src/Ryujinx/AppHost.cs | 30 +++--- src/Ryujinx/Common/ApplicationHelper.cs | 20 ++-- src/Ryujinx/Common/LocaleManager.cs | 12 +-- .../Common/Models/XCITrimmerFileModel.cs | 2 +- src/Ryujinx/Headless/HeadlessRyujinx.Init.cs | 4 +- src/Ryujinx/Headless/HeadlessRyujinx.cs | 2 +- src/Ryujinx/Headless/Windows/WindowBase.cs | 6 +- src/Ryujinx/Input/AvaloniaKeyboardDriver.cs | 2 +- .../Input/AvaloniaKeyboardMappingHelper.cs | 6 +- src/Ryujinx/Program.cs | 2 +- src/Ryujinx/RyujinxApp.axaml.cs | 2 +- src/Ryujinx/UI/Applet/AvaHostUIHandler.cs | 2 +- .../Applet/AvaloniaDynamicTextInputHandler.cs | 4 +- .../UI/Applet/UserSelectorDialog.axaml.cs | 4 +- .../Controls/ApplicationContextMenu.axaml.cs | 14 +-- .../UI/Controls/ApplicationListView.axaml.cs | 5 +- .../UI/Controls/NavigationDialogHost.axaml.cs | 16 +-- .../UI/Helpers/AvaloniaListExtensions.cs | 6 +- src/Ryujinx/UI/Helpers/ContentDialogHelper.cs | 2 +- .../Helpers/Converters/GlyphValueConverter.cs | 2 +- .../Converters/TitleUpdateLabelConverter.cs | 2 +- src/Ryujinx/UI/Helpers/LoggerAdapter.cs | 6 +- src/Ryujinx/UI/Helpers/NotificationHelper.cs | 4 +- src/Ryujinx/UI/Models/CheatNode.cs | 2 +- .../UI/Models/Input/KeyboardInputConfig.cs | 2 +- src/Ryujinx/UI/Models/SaveModel.cs | 14 +-- src/Ryujinx/UI/Models/UserProfile.cs | 3 +- .../UI/Renderer/EmbeddedWindowOpenGL.cs | 4 +- src/Ryujinx/UI/ViewModels/BaseModel.cs | 2 +- .../DownloadableContentManagerViewModel.cs | 25 ++--- .../UI/ViewModels/Input/InputViewModel.cs | 22 ++--- .../UI/ViewModels/MainWindowViewModel.cs | 42 ++++---- .../UI/ViewModels/ModManagerViewModel.cs | 48 ++++----- .../UI/ViewModels/SettingsViewModel.cs | 5 +- .../UI/ViewModels/TitleUpdateViewModel.cs | 24 ++--- .../UserFirmwareAvatarSelectorViewModel.cs | 6 +- .../UI/ViewModels/UserSaveManagerViewModel.cs | 2 +- .../UI/ViewModels/XCITrimmerViewModel.cs | 21 ++-- .../Views/Input/ControllerInputView.axaml.cs | 7 +- src/Ryujinx/UI/Views/Input/InputView.axaml.cs | 2 +- .../UI/Views/Input/KeyboardInputView.axaml.cs | 3 +- .../UI/Views/Input/MotionInputView.axaml.cs | 5 +- .../UI/Views/Input/RumbleInputView.axaml.cs | 5 +- .../UI/Views/Main/MainMenuBarView.axaml.cs | 5 +- .../Settings/SettingsHotkeysView.axaml.cs | 7 +- .../UI/Views/User/UserEditorView.axaml.cs | 2 +- .../UserFirmwareAvatarSelectorView.axaml.cs | 12 +-- .../UserProfileImageSelectorView.axaml.cs | 12 +-- .../UI/Views/User/UserRecovererView.axaml.cs | 2 +- .../Views/User/UserSaveManagerView.axaml.cs | 14 +-- src/Ryujinx/UI/Windows/CheatWindow.axaml.cs | 9 +- .../DownloadableContentManagerWindow.axaml.cs | 4 +- src/Ryujinx/UI/Windows/IconColorPicker.cs | 28 +++--- src/Ryujinx/UI/Windows/MainWindow.axaml.cs | 15 +-- .../UI/Windows/ModManagerWindow.axaml.cs | 12 +-- .../UI/Windows/XCITrimmerWindow.axaml.cs | 4 +- src/Ryujinx/Updater.cs | 14 +-- .../Utilities/AppLibrary/ApplicationData.cs | 6 +- .../AppLibrary/ApplicationLibrary.cs | 98 +++++++++---------- .../Utilities/Compat/CompatibilityCsv.cs | 2 +- .../Configuration/ConfigurationState.Model.cs | 2 +- .../Utilities/Configuration/LoggerModule.cs | 4 +- .../Utilities/DownloadableContentsHelper.cs | 10 +- src/Ryujinx/Utilities/ShortcutHelper.cs | 26 ++--- .../Utilities/SystemInfo/LinuxSystemInfo.cs | 4 +- .../Utilities/SystemInfo/MacOSSystemInfo.cs | 4 +- .../Utilities/SystemInfo/WindowsSystemInfo.cs | 2 +- src/Ryujinx/Utilities/TitleUpdatesHelper.cs | 14 +-- src/Ryujinx/Utilities/ValueFormatUtils.cs | 4 +- 69 files changed, 367 insertions(+), 348 deletions(-) diff --git a/src/Ryujinx/AppHost.cs b/src/Ryujinx/AppHost.cs index 65c279fc4..27c2d5b7a 100644 --- a/src/Ryujinx/AppHost.cs +++ b/src/Ryujinx/AppHost.cs @@ -238,10 +238,10 @@ namespace Ryujinx.Ava _lastCursorMoveTime = Stopwatch.GetTimestamp(); } - var point = e.GetCurrentPoint(window).Position; - var bounds = RendererHost.EmbeddedWindow.Bounds; - var windowYOffset = bounds.Y + window.MenuBarHeight; - var windowYLimit = (int)window.Bounds.Height - window.StatusBarHeight - 1; + Point point = e.GetCurrentPoint(window).Position; + Rect bounds = RendererHost.EmbeddedWindow.Bounds; + double windowYOffset = bounds.Y + window.MenuBarHeight; + double windowYLimit = (int)window.Bounds.Height - window.StatusBarHeight - 1; if (!_viewModel.ShowMenuAndStatusBar) { @@ -265,10 +265,10 @@ namespace Ryujinx.Ava if (sender is MainWindow window) { - var point = e.GetCurrentPoint(window).Position; - var bounds = RendererHost.EmbeddedWindow.Bounds; - var windowYOffset = bounds.Y + window.MenuBarHeight; - var windowYLimit = (int)window.Bounds.Height - window.StatusBarHeight - 1; + Point point = e.GetCurrentPoint(window).Position; + Rect bounds = RendererHost.EmbeddedWindow.Bounds; + double windowYOffset = bounds.Y + window.MenuBarHeight; + double windowYLimit = (int)window.Bounds.Height - window.StatusBarHeight - 1; if (!_viewModel.ShowMenuAndStatusBar) { @@ -435,7 +435,7 @@ namespace Ryujinx.Ava return; } - var colorType = e.IsBgra ? SKColorType.Bgra8888 : SKColorType.Rgba8888; + SKColorType colorType = e.IsBgra ? SKColorType.Bgra8888 : SKColorType.Rgba8888; using SKBitmap bitmap = new(new SKImageInfo(e.Width, e.Height, colorType, SKAlphaType.Premul)); Marshal.Copy(e.Data, 0, bitmap.GetPixels(), e.Data.Length); @@ -448,7 +448,7 @@ namespace Ryujinx.Ava float scaleX = e.FlipX ? -1 : 1; float scaleY = e.FlipY ? -1 : 1; - var matrix = SKMatrix.CreateScale(scaleX, scaleY, bitmap.Width / 2f, bitmap.Height / 2f); + SKMatrix matrix = SKMatrix.CreateScale(scaleX, scaleY, bitmap.Width / 2f, bitmap.Height / 2f); canvas.SetMatrix(matrix); canvas.DrawBitmap(bitmap, SKPoint.Empty); @@ -467,8 +467,8 @@ namespace Ryujinx.Ava private static void SaveBitmapAsPng(SKBitmap bitmap, string path) { - using var data = bitmap.Encode(SKEncodedImageFormat.Png, 100); - using var stream = File.OpenWrite(path); + using SKData data = bitmap.Encode(SKEncodedImageFormat.Png, 100); + using FileStream stream = File.OpenWrite(path); data.SaveTo(stream); } @@ -923,7 +923,7 @@ namespace Ryujinx.Ava BackendThreading threadingMode = ConfigurationState.Instance.Graphics.BackendThreading; - var isGALThreaded = threadingMode == BackendThreading.On || (threadingMode == BackendThreading.Auto && renderer.PreferThreading); + bool isGALThreaded = threadingMode == BackendThreading.On || (threadingMode == BackendThreading.Auto && renderer.PreferThreading); if (isGALThreaded) { renderer = new ThreadedRenderer(renderer); @@ -932,7 +932,7 @@ namespace Ryujinx.Ava Logger.Info?.PrintMsg(LogClass.Gpu, $"Backend Threading ({threadingMode}): {isGALThreaded}"); // Initialize Configuration. - var memoryConfiguration = ConfigurationState.Instance.System.DramSize.Value; + MemoryConfiguration memoryConfiguration = ConfigurationState.Instance.System.DramSize.Value; Device = new Switch(new HLEConfiguration( VirtualFileSystem, @@ -970,7 +970,7 @@ namespace Ryujinx.Ava private static IHardwareDeviceDriver InitializeAudio() { - var availableBackends = new List + List availableBackends = new List { AudioBackend.SDL2, AudioBackend.SoundIo, diff --git a/src/Ryujinx/Common/ApplicationHelper.cs b/src/Ryujinx/Common/ApplicationHelper.cs index e5b4da728..1c839aaaa 100644 --- a/src/Ryujinx/Common/ApplicationHelper.cs +++ b/src/Ryujinx/Common/ApplicationHelper.cs @@ -144,7 +144,7 @@ namespace Ryujinx.Ava.Common public static void ExtractSection(string destination, NcaSectionType ncaSectionType, string titleFilePath, string titleName, int programIndex = 0) { - var cancellationToken = new CancellationTokenSource(); + CancellationTokenSource cancellationToken = new CancellationTokenSource(); UpdateWaitWindow waitingDialog = new( RyujinxApp.FormatTitle(LocaleKeys.DialogNcaExtractionTitle), @@ -171,14 +171,14 @@ namespace Ryujinx.Ava.Common } else { - var pfsTemp = new PartitionFileSystem(); + PartitionFileSystem pfsTemp = new PartitionFileSystem(); pfsTemp.Initialize(file.AsStorage()).ThrowIfFailure(); pfs = pfsTemp; } foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca")) { - using var ncaFile = new UniqueRef(); + using UniqueRef ncaFile = new UniqueRef(); pfs.OpenFile(ref ncaFile.Ref, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); @@ -244,8 +244,8 @@ namespace Ryujinx.Ava.Common 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 UniqueRef uniqueSourceFs = new UniqueRef(ncaFileSystem); + using UniqueRef uniqueOutputFs = new UniqueRef(new LocalFileSystem(destination)); fsClient.Register(source.ToU8Span(), ref uniqueSourceFs.Ref); fsClient.Register(output.ToU8Span(), ref uniqueOutputFs.Ref); @@ -299,7 +299,7 @@ namespace Ryujinx.Ava.Common public static void ExtractAoc(string destination, string updateFilePath, string updateName) { - var cancellationToken = new CancellationTokenSource(); + CancellationTokenSource cancellationToken = new CancellationTokenSource(); UpdateWaitWindow waitingDialog = new( RyujinxApp.FormatTitle(LocaleKeys.DialogNcaExtractionTitle), @@ -317,13 +317,13 @@ namespace Ryujinx.Ava.Common string extension = Path.GetExtension(updateFilePath).ToLower(); if (extension is ".nsp") { - var pfsTemp = new PartitionFileSystem(); + PartitionFileSystem pfsTemp = new PartitionFileSystem(); pfsTemp.Initialize(file.AsStorage()).ThrowIfFailure(); IFileSystem pfs = pfsTemp; foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca")) { - using var ncaFile = new UniqueRef(); + using UniqueRef ncaFile = new UniqueRef(); pfs.OpenFile(ref ncaFile.Ref, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); @@ -364,8 +364,8 @@ namespace Ryujinx.Ava.Common 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 UniqueRef uniqueSourceFs = new UniqueRef(ncaFileSystem); + using UniqueRef uniqueOutputFs = new UniqueRef(new LocalFileSystem(destination)); fsClient.Register(source.ToU8Span(), ref uniqueSourceFs.Ref); fsClient.Register(output.ToU8Span(), ref uniqueOutputFs.Ref); diff --git a/src/Ryujinx/Common/LocaleManager.cs b/src/Ryujinx/Common/LocaleManager.cs index 9422cf7fb..72c2e04c4 100644 --- a/src/Ryujinx/Common/LocaleManager.cs +++ b/src/Ryujinx/Common/LocaleManager.cs @@ -32,7 +32,7 @@ namespace Ryujinx.Ava.Common.Locale private void Load() { - var localeLanguageCode = !string.IsNullOrEmpty(ConfigurationState.Instance.UI.LanguageCode.Value) ? + string localeLanguageCode = !string.IsNullOrEmpty(ConfigurationState.Instance.UI.LanguageCode.Value) ? ConfigurationState.Instance.UI.LanguageCode.Value : CultureInfo.CurrentCulture.Name.Replace('-', '_'); LoadLanguage(localeLanguageCode); @@ -54,7 +54,7 @@ namespace Ryujinx.Ava.Common.Locale if (_localeStrings.TryGetValue(key, out string value)) { // Check if the localized string needs to be formatted. - if (_dynamicValues.TryGetValue(key, out var dynamicValue)) + if (_dynamicValues.TryGetValue(key, out object[] dynamicValue)) try { return string.Format(value, dynamicValue); @@ -99,7 +99,7 @@ namespace Ryujinx.Ava.Common.Locale public void LoadLanguage(string languageCode) { - var locale = LoadJsonLanguage(languageCode); + Dictionary locale = LoadJsonLanguage(languageCode); if (locale == null) { @@ -125,7 +125,7 @@ namespace Ryujinx.Ava.Common.Locale private static Dictionary LoadJsonLanguage(string languageCode) { - var localeStrings = new Dictionary(); + Dictionary localeStrings = new Dictionary(); _localeData ??= EmbeddedResources.ReadAllText("Ryujinx/Assets/locales.json") .Into(it => JsonHelper.Deserialize(it, LocalesJsonContext.Default.LocalesJson)); @@ -142,10 +142,10 @@ namespace Ryujinx.Ava.Common.Locale throw new Exception($"Locale key {{{locale.ID}}} has too many languages! Has {locale.Translations.Count} translations, expected {_localeData.Value.Languages.Count}!"); } - if (!Enum.TryParse(locale.ID, out var localeKey)) + if (!Enum.TryParse(locale.ID, out LocaleKeys localeKey)) continue; - var str = locale.Translations.TryGetValue(languageCode, out string val) && !string.IsNullOrEmpty(val) + string str = locale.Translations.TryGetValue(languageCode, out string val) && !string.IsNullOrEmpty(val) ? val : locale.Translations[DefaultLanguageCode]; diff --git a/src/Ryujinx/Common/Models/XCITrimmerFileModel.cs b/src/Ryujinx/Common/Models/XCITrimmerFileModel.cs index 526bf230c..7286178e7 100644 --- a/src/Ryujinx/Common/Models/XCITrimmerFileModel.cs +++ b/src/Ryujinx/Common/Models/XCITrimmerFileModel.cs @@ -16,7 +16,7 @@ namespace Ryujinx.Ava.Common.Models { public static XCITrimmerFileModel FromApplicationData(ApplicationData applicationData, XCIFileTrimmerLog logger) { - var trimmer = new XCIFileTrimmer(applicationData.Path, logger); + XCIFileTrimmer trimmer = new XCIFileTrimmer(applicationData.Path, logger); return new XCITrimmerFileModel( applicationData.Name, diff --git a/src/Ryujinx/Headless/HeadlessRyujinx.Init.cs b/src/Ryujinx/Headless/HeadlessRyujinx.Init.cs index 7d75ac7c1..7b29cd59c 100644 --- a/src/Ryujinx/Headless/HeadlessRyujinx.Init.cs +++ b/src/Ryujinx/Headless/HeadlessRyujinx.Init.cs @@ -291,9 +291,9 @@ namespace Ryujinx.Headless if (!string.IsNullOrEmpty(options.PreferredGPUVendor)) { string preferredGpuVendor = options.PreferredGPUVendor.ToLowerInvariant(); - var devices = VulkanRenderer.GetPhysicalDevices(api); + DeviceInfo[] devices = VulkanRenderer.GetPhysicalDevices(api); - foreach (var device in devices) + foreach (DeviceInfo device in devices) { if (device.Vendor.ToLowerInvariant() == preferredGpuVendor) { diff --git a/src/Ryujinx/Headless/HeadlessRyujinx.cs b/src/Ryujinx/Headless/HeadlessRyujinx.cs index 787aaca62..18efdceee 100644 --- a/src/Ryujinx/Headless/HeadlessRyujinx.cs +++ b/src/Ryujinx/Headless/HeadlessRyujinx.cs @@ -149,7 +149,7 @@ namespace Ryujinx.Headless AppDataManager.Initialize(option.BaseDataDir); - if (useLastUsedProfile && AccountSaveDataManager.GetLastUsedUser().TryGet(out var profile)) + if (useLastUsedProfile && AccountSaveDataManager.GetLastUsedUser().TryGet(out UserProfile profile)) option.UserProfile = profile.Name; // Check if keys exists. diff --git a/src/Ryujinx/Headless/Windows/WindowBase.cs b/src/Ryujinx/Headless/Windows/WindowBase.cs index 068c32062..8fd445199 100644 --- a/src/Ryujinx/Headless/Windows/WindowBase.cs +++ b/src/Ryujinx/Headless/Windows/WindowBase.cs @@ -1,4 +1,5 @@ using Humanizer; +using LibHac.Ns; using Ryujinx.Ava; using Ryujinx.Ava.UI.Models; using Ryujinx.Common; @@ -11,6 +12,7 @@ using Ryujinx.Graphics.OpenGL; using Ryujinx.HLE.HOS.Applets; using Ryujinx.HLE.HOS.Services.Account.Acc; using Ryujinx.HLE.HOS.Services.Am.AppletOE.ApplicationProxyService.ApplicationProxy.Types; +using Ryujinx.HLE.Loaders.Processes; using Ryujinx.HLE.UI; using Ryujinx.Input; using Ryujinx.Input.HLE; @@ -165,8 +167,8 @@ namespace Ryujinx.Headless private void InitializeWindow() { - var activeProcess = Device.Processes.ActiveApplication; - var nacp = activeProcess.ApplicationControlProperties; + ProcessResult activeProcess = Device.Processes.ActiveApplication; + ApplicationControlProperty nacp = activeProcess.ApplicationControlProperties; int desiredLanguage = (int)Device.System.State.DesiredTitleLanguage; string titleNameSection = string.IsNullOrWhiteSpace(nacp.Title[desiredLanguage].NameString.ToString()) ? string.Empty : $" - {nacp.Title[desiredLanguage].NameString.ToString()}"; diff --git a/src/Ryujinx/Input/AvaloniaKeyboardDriver.cs b/src/Ryujinx/Input/AvaloniaKeyboardDriver.cs index 214652265..581d1db8e 100644 --- a/src/Ryujinx/Input/AvaloniaKeyboardDriver.cs +++ b/src/Ryujinx/Input/AvaloniaKeyboardDriver.cs @@ -91,7 +91,7 @@ namespace Ryujinx.Ava.Input return false; } - AvaloniaKeyboardMappingHelper.TryGetAvaKey(key, out var nativeKey); + AvaloniaKeyboardMappingHelper.TryGetAvaKey(key, out AvaKey nativeKey); return _pressedKeys.Contains(nativeKey); } diff --git a/src/Ryujinx/Input/AvaloniaKeyboardMappingHelper.cs b/src/Ryujinx/Input/AvaloniaKeyboardMappingHelper.cs index 97ebd721d..c3e653e5d 100644 --- a/src/Ryujinx/Input/AvaloniaKeyboardMappingHelper.cs +++ b/src/Ryujinx/Input/AvaloniaKeyboardMappingHelper.cs @@ -150,14 +150,14 @@ namespace Ryujinx.Ava.Input static AvaloniaKeyboardMappingHelper() { - var inputKeys = Enum.GetValues(); + Key[] inputKeys = Enum.GetValues(); // NOTE: Avalonia.Input.Key is not contiguous and quite large, so use a dictionary instead of an array. _avaKeyMapping = new Dictionary(); - foreach (var key in inputKeys) + foreach (Key key in inputKeys) { - if (TryGetAvaKey(key, out var index)) + if (TryGetAvaKey(key, out AvaKey index)) { _avaKeyMapping[index] = key; } diff --git a/src/Ryujinx/Program.cs b/src/Ryujinx/Program.cs index f1c5a301b..e7a4fde56 100644 --- a/src/Ryujinx/Program.cs +++ b/src/Ryujinx/Program.cs @@ -262,7 +262,7 @@ namespace Ryujinx.Ava exceptions.Add(initialException); } - foreach (var e in exceptions) + foreach (Exception e in exceptions) { string message = $"Unhandled exception caught: {e}"; // ReSharper disable once ConstantConditionalAccessQualifier diff --git a/src/Ryujinx/RyujinxApp.axaml.cs b/src/Ryujinx/RyujinxApp.axaml.cs index d950af3a9..95bc92c3d 100644 --- a/src/Ryujinx/RyujinxApp.axaml.cs +++ b/src/Ryujinx/RyujinxApp.axaml.cs @@ -79,7 +79,7 @@ namespace Ryujinx.Ava { if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { - var result = await ContentDialogHelper.CreateConfirmationDialog( + UserResult result = await ContentDialogHelper.CreateConfirmationDialog( LocaleManager.Instance[LocaleKeys.DialogThemeRestartMessage], LocaleManager.Instance[LocaleKeys.DialogThemeRestartSubMessage], LocaleManager.Instance[LocaleKeys.InputDialogYes], diff --git a/src/Ryujinx/UI/Applet/AvaHostUIHandler.cs b/src/Ryujinx/UI/Applet/AvaHostUIHandler.cs index d2fad58ac..86e9adcd5 100644 --- a/src/Ryujinx/UI/Applet/AvaHostUIHandler.cs +++ b/src/Ryujinx/UI/Applet/AvaHostUIHandler.cs @@ -46,7 +46,7 @@ namespace Ryujinx.Ava.UI.Applet Dispatcher.UIThread.InvokeAsync(async () => { - var response = await ControllerAppletDialog.ShowControllerAppletDialog(_parent, args); + UserResult response = await ControllerAppletDialog.ShowControllerAppletDialog(_parent, args); if (response == UserResult.Ok) { okPressed = true; diff --git a/src/Ryujinx/UI/Applet/AvaloniaDynamicTextInputHandler.cs b/src/Ryujinx/UI/Applet/AvaloniaDynamicTextInputHandler.cs index 0cd3f18e5..397eab72c 100644 --- a/src/Ryujinx/UI/Applet/AvaloniaDynamicTextInputHandler.cs +++ b/src/Ryujinx/UI/Applet/AvaloniaDynamicTextInputHandler.cs @@ -65,7 +65,7 @@ namespace Ryujinx.Ava.UI.Applet private void AvaloniaDynamicTextInputHandler_KeyRelease(object sender, KeyEventArgs e) { - var key = (HidKey)AvaloniaKeyboardMappingHelper.ToInputKey(e.Key); + HidKey key = (HidKey)AvaloniaKeyboardMappingHelper.ToInputKey(e.Key); if (!(KeyReleasedEvent?.Invoke(key)).GetValueOrDefault(true)) { @@ -85,7 +85,7 @@ namespace Ryujinx.Ava.UI.Applet private void AvaloniaDynamicTextInputHandler_KeyPressed(object sender, KeyEventArgs e) { - var key = (HidKey)AvaloniaKeyboardMappingHelper.ToInputKey(e.Key); + HidKey key = (HidKey)AvaloniaKeyboardMappingHelper.ToInputKey(e.Key); if (!(KeyPressedEvent?.Invoke(key)).GetValueOrDefault(true)) { diff --git a/src/Ryujinx/UI/Applet/UserSelectorDialog.axaml.cs b/src/Ryujinx/UI/Applet/UserSelectorDialog.axaml.cs index 6e25588ec..4081de61e 100644 --- a/src/Ryujinx/UI/Applet/UserSelectorDialog.axaml.cs +++ b/src/Ryujinx/UI/Applet/UserSelectorDialog.axaml.cs @@ -60,11 +60,11 @@ namespace Ryujinx.Ava.UI.Applet ObservableCollection newProfiles = []; - foreach (var item in ViewModel.Profiles) + foreach (BaseModel item in ViewModel.Profiles) { if (item is UserProfile originalItem) { - var profile = new UserProfileSft(originalItem.UserId, originalItem.Name, originalItem.Image); + UserProfileSft profile = new UserProfileSft(originalItem.UserId, originalItem.Name, originalItem.Image); if (profile.UserId == ViewModel.SelectedUserId) { diff --git a/src/Ryujinx/UI/Controls/ApplicationContextMenu.axaml.cs b/src/Ryujinx/UI/Controls/ApplicationContextMenu.axaml.cs index de95be387..13a1d3bf3 100644 --- a/src/Ryujinx/UI/Controls/ApplicationContextMenu.axaml.cs +++ b/src/Ryujinx/UI/Controls/ApplicationContextMenu.axaml.cs @@ -76,7 +76,7 @@ namespace Ryujinx.Ava.UI.Controls private static void OpenSaveDirectory(MainWindowViewModel viewModel, SaveDataType saveDataType, UserId userId) { - var saveDataFilter = SaveDataFilter.Make(viewModel.SelectedApplication.Id, saveDataType, userId, saveDataId: default, index: default); + SaveDataFilter saveDataFilter = SaveDataFilter.Make(viewModel.SelectedApplication.Id, saveDataType, userId, saveDataId: default, index: default); ApplicationHelper.OpenSaveDir(in saveDataFilter, viewModel.SelectedApplication.Id, viewModel.SelectedApplication.ControlHolder, viewModel.SelectedApplication.Name); } @@ -305,7 +305,7 @@ namespace Ryujinx.Ava.UI.Controls if (sender is not MenuItem { DataContext: MainWindowViewModel { SelectedApplication: not null } viewModel }) return; - var result = await viewModel.StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions + IReadOnlyList result = await viewModel.StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions { Title = LocaleManager.Instance[LocaleKeys.FolderDialogExtractTitle], AllowMultiple = false, @@ -320,13 +320,13 @@ namespace Ryujinx.Ava.UI.Controls viewModel.SelectedApplication.Path, viewModel.SelectedApplication.Name); - var iconFile = await result[0].CreateFileAsync($"{viewModel.SelectedApplication.IdString}.png"); - await using var fileStream = await iconFile.OpenWriteAsync(); + IStorageFile iconFile = await result[0].CreateFileAsync($"{viewModel.SelectedApplication.IdString}.png"); + await using Stream fileStream = await iconFile.OpenWriteAsync(); - using var bitmap = SKBitmap.Decode(viewModel.SelectedApplication.Icon) + using SKBitmap bitmap = SKBitmap.Decode(viewModel.SelectedApplication.Icon) .Resize(new SKSizeI(512, 512), SKFilterQuality.High); - using var png = bitmap.Encode(SKEncodedImageFormat.Png, 100); + using SKData png = bitmap.Encode(SKEncodedImageFormat.Png, 100); png.SaveTo(fileStream); } @@ -350,7 +350,7 @@ namespace Ryujinx.Ava.UI.Controls public async void TrimXCI_Click(object sender, RoutedEventArgs args) { - var viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; + MainWindowViewModel viewModel = (sender as MenuItem)?.DataContext as MainWindowViewModel; if (viewModel?.SelectedApplication != null) { diff --git a/src/Ryujinx/UI/Controls/ApplicationListView.axaml.cs b/src/Ryujinx/UI/Controls/ApplicationListView.axaml.cs index 1f63f43c8..41919ebf5 100644 --- a/src/Ryujinx/UI/Controls/ApplicationListView.axaml.cs +++ b/src/Ryujinx/UI/Controls/ApplicationListView.axaml.cs @@ -1,6 +1,7 @@ using Avalonia.Controls; using Avalonia.Controls.Notifications; using Avalonia.Input; +using Avalonia.Input.Platform; using Avalonia.Interactivity; using FluentAvalonia.UI.Controls; using Ryujinx.Ava.UI.Helpers; @@ -38,10 +39,10 @@ namespace Ryujinx.Ava.UI.Controls if (sender is not Button { Content: TextBlock idText }) return; - if (!RyujinxApp.IsClipboardAvailable(out var clipboard)) + if (!RyujinxApp.IsClipboardAvailable(out IClipboard clipboard)) return; - var appData = mwvm.Applications.FirstOrDefault(it => it.IdString == idText.Text); + ApplicationData appData = mwvm.Applications.FirstOrDefault(it => it.IdString == idText.Text); if (appData is null) return; diff --git a/src/Ryujinx/UI/Controls/NavigationDialogHost.axaml.cs b/src/Ryujinx/UI/Controls/NavigationDialogHost.axaml.cs index 4d021655e..1c20aac74 100644 --- a/src/Ryujinx/UI/Controls/NavigationDialogHost.axaml.cs +++ b/src/Ryujinx/UI/Controls/NavigationDialogHost.axaml.cs @@ -106,9 +106,9 @@ namespace Ryujinx.Ava.UI.Controls .OrderBy(x => x.Name) .ForEach(profile => ViewModel.Profiles.Add(new UserProfile(profile, this))); - var saveDataFilter = SaveDataFilter.Make(programId: default, saveType: SaveDataType.Account, default, saveDataId: default, index: default); + SaveDataFilter saveDataFilter = SaveDataFilter.Make(programId: default, saveType: SaveDataType.Account, default, saveDataId: default, index: default); - using var saveDataIterator = new UniqueRef(); + using UniqueRef saveDataIterator = new UniqueRef(); HorizonClient.Fs.OpenSaveDataIterator(ref saveDataIterator.Ref, SaveDataSpaceId.User, in saveDataFilter).ThrowIfFailure(); @@ -127,8 +127,8 @@ namespace Ryujinx.Ava.UI.Controls for (int i = 0; i < readCount; i++) { - var save = saveDataInfo[i]; - var id = new UserId((long)save.UserId.Id.Low, (long)save.UserId.Id.High); + SaveDataInfo save = saveDataInfo[i]; + UserId id = new UserId((long)save.UserId.Id.Low, (long)save.UserId.Id.High); if (ViewModel.Profiles.Cast().FirstOrDefault(x => x.UserId == id) == null) { lostAccounts.Add(id); @@ -136,7 +136,7 @@ namespace Ryujinx.Ava.UI.Controls } } - foreach (var account in lostAccounts) + foreach (UserId account in lostAccounts) { ViewModel.LostProfiles.Add(new UserProfile(new HLE.HOS.Services.Account.Acc.UserProfile(account, string.Empty, null), this)); } @@ -146,12 +146,12 @@ namespace Ryujinx.Ava.UI.Controls public async void DeleteUser(UserProfile userProfile) { - var lastUserId = AccountManager.LastOpenedUser.UserId; + UserId lastUserId = AccountManager.LastOpenedUser.UserId; if (userProfile.UserId == lastUserId) { // If we are deleting the currently open profile, then we must open something else before deleting. - var profile = ViewModel.Profiles.Cast().FirstOrDefault(x => x.UserId != lastUserId); + UserProfile profile = ViewModel.Profiles.Cast().FirstOrDefault(x => x.UserId != lastUserId); if (profile == null) { @@ -165,7 +165,7 @@ namespace Ryujinx.Ava.UI.Controls AccountManager.OpenUser(profile.UserId); } - var result = await ContentDialogHelper.CreateConfirmationDialog( + UserResult result = await ContentDialogHelper.CreateConfirmationDialog( LocaleManager.Instance[LocaleKeys.DialogUserProfileDeletionConfirmMessage], string.Empty, LocaleManager.Instance[LocaleKeys.InputDialogYes], diff --git a/src/Ryujinx/UI/Helpers/AvaloniaListExtensions.cs b/src/Ryujinx/UI/Helpers/AvaloniaListExtensions.cs index b3bb53bd0..f4a5dc0c1 100644 --- a/src/Ryujinx/UI/Helpers/AvaloniaListExtensions.cs +++ b/src/Ryujinx/UI/Helpers/AvaloniaListExtensions.cs @@ -21,7 +21,7 @@ namespace Ryujinx.Ava.UI.Helpers /// public static bool ReplaceWith(this AvaloniaList list, T item, bool addIfNotFound = true) { - var index = list.IndexOf(item); + int index = list.IndexOf(item); if (index != -1) { @@ -45,9 +45,9 @@ namespace Ryujinx.Ava.UI.Helpers /// The items to use as matching records to search for in the `sourceList', if not found this item will be added instead public static void AddOrReplaceMatching(this AvaloniaList list, IList sourceList, IList matchingList) { - foreach (var match in matchingList) + foreach (T match in matchingList) { - var index = sourceList.IndexOf(match); + int index = sourceList.IndexOf(match); if (index != -1) { list.ReplaceWith(sourceList[index]); diff --git a/src/Ryujinx/UI/Helpers/ContentDialogHelper.cs b/src/Ryujinx/UI/Helpers/ContentDialogHelper.cs index 3f0f0f033..b5d085ba1 100644 --- a/src/Ryujinx/UI/Helpers/ContentDialogHelper.cs +++ b/src/Ryujinx/UI/Helpers/ContentDialogHelper.cs @@ -121,7 +121,7 @@ namespace Ryujinx.Ava.UI.Helpers startedDeferring = true; - var deferral = args.GetDeferral(); + Deferral deferral = args.GetDeferral(); sender.PrimaryButtonClick -= DeferClose; diff --git a/src/Ryujinx/UI/Helpers/Converters/GlyphValueConverter.cs b/src/Ryujinx/UI/Helpers/Converters/GlyphValueConverter.cs index 6196421c8..fe50aab58 100644 --- a/src/Ryujinx/UI/Helpers/Converters/GlyphValueConverter.cs +++ b/src/Ryujinx/UI/Helpers/Converters/GlyphValueConverter.cs @@ -23,7 +23,7 @@ namespace Ryujinx.Ava.UI.Helpers } public string this[string key] => - _glyphs.TryGetValue(Enum.Parse(key), out var val) + _glyphs.TryGetValue(Enum.Parse(key), out string val) ? val : string.Empty; diff --git a/src/Ryujinx/UI/Helpers/Converters/TitleUpdateLabelConverter.cs b/src/Ryujinx/UI/Helpers/Converters/TitleUpdateLabelConverter.cs index cbb6edff1..d462b9463 100644 --- a/src/Ryujinx/UI/Helpers/Converters/TitleUpdateLabelConverter.cs +++ b/src/Ryujinx/UI/Helpers/Converters/TitleUpdateLabelConverter.cs @@ -30,7 +30,7 @@ namespace Ryujinx.Ava.UI.Helpers return null; } - var key = isBundled ? LocaleKeys.TitleBundledUpdateVersionLabel : LocaleKeys.TitleUpdateVersionLabel; + LocaleKeys key = isBundled ? LocaleKeys.TitleBundledUpdateVersionLabel : LocaleKeys.TitleUpdateVersionLabel; return LocaleManager.Instance.UpdateAndGetDynamicValue(key, label); } diff --git a/src/Ryujinx/UI/Helpers/LoggerAdapter.cs b/src/Ryujinx/UI/Helpers/LoggerAdapter.cs index 2d26bd090..1dc1adcc5 100644 --- a/src/Ryujinx/UI/Helpers/LoggerAdapter.cs +++ b/src/Ryujinx/UI/Helpers/LoggerAdapter.cs @@ -50,8 +50,8 @@ namespace Ryujinx.Ava.UI.Helpers private static string Format(AvaLogLevel level, string area, string template, object source, object[] v) { - var result = new StringBuilder(); - var r = new CharacterReader(template.AsSpan()); + StringBuilder result = new StringBuilder(); + CharacterReader r = new CharacterReader(template.AsSpan()); int i = 0; result.Append('['); @@ -64,7 +64,7 @@ namespace Ryujinx.Ava.UI.Helpers while (!r.End) { - var c = r.Take(); + char c = r.Take(); if (c != '{') { diff --git a/src/Ryujinx/UI/Helpers/NotificationHelper.cs b/src/Ryujinx/UI/Helpers/NotificationHelper.cs index 74029a4b1..aa071a2a1 100644 --- a/src/Ryujinx/UI/Helpers/NotificationHelper.cs +++ b/src/Ryujinx/UI/Helpers/NotificationHelper.cs @@ -28,7 +28,7 @@ namespace Ryujinx.Ava.UI.Helpers Margin = new Thickness(0, 0, 15, 40), }; - var maybeAsyncWorkQueue = new Lazy>( + Lazy> maybeAsyncWorkQueue = new Lazy>( () => new AsyncWorkQueue(notification => { Dispatcher.UIThread.Post(() => @@ -57,7 +57,7 @@ namespace Ryujinx.Ava.UI.Helpers public static void Show(string title, string text, NotificationType type, bool waitingExit = false, Action onClick = null, Action onClose = null) { - var delay = waitingExit ? TimeSpan.FromMilliseconds(0) : TimeSpan.FromMilliseconds(NotificationDelayInMs); + TimeSpan delay = waitingExit ? TimeSpan.FromMilliseconds(0) : TimeSpan.FromMilliseconds(NotificationDelayInMs); _notifications.Add(new Notification(title, text, type, delay, onClick, onClose)); } diff --git a/src/Ryujinx/UI/Models/CheatNode.cs b/src/Ryujinx/UI/Models/CheatNode.cs index 8e9aee254..cce0f1d97 100644 --- a/src/Ryujinx/UI/Models/CheatNode.cs +++ b/src/Ryujinx/UI/Models/CheatNode.cs @@ -28,7 +28,7 @@ namespace Ryujinx.Ava.UI.Models } set { - foreach (var cheat in SubNodes) + foreach (CheatNode cheat in SubNodes) { cheat.IsEnabled = value; cheat.OnPropertyChanged(); diff --git a/src/Ryujinx/UI/Models/Input/KeyboardInputConfig.cs b/src/Ryujinx/UI/Models/Input/KeyboardInputConfig.cs index 66f1f62a2..bf3864b93 100644 --- a/src/Ryujinx/UI/Models/Input/KeyboardInputConfig.cs +++ b/src/Ryujinx/UI/Models/Input/KeyboardInputConfig.cs @@ -367,7 +367,7 @@ namespace Ryujinx.Ava.UI.Models.Input public InputConfig GetConfig() { - var config = new StandardKeyboardInputConfig + StandardKeyboardInputConfig config = new StandardKeyboardInputConfig { Id = Id, Backend = InputBackendType.WindowKeyboard, diff --git a/src/Ryujinx/UI/Models/SaveModel.cs b/src/Ryujinx/UI/Models/SaveModel.cs index 3dc009b2a..81be5ee93 100644 --- a/src/Ryujinx/UI/Models/SaveModel.cs +++ b/src/Ryujinx/UI/Models/SaveModel.cs @@ -48,7 +48,7 @@ namespace Ryujinx.Ava.UI.Models TitleId = info.ProgramId; UserId = info.UserId; - var appData = RyujinxApp.MainWindow.ViewModel.Applications.FirstOrDefault(x => x.IdString.EqualsIgnoreCase(TitleIdString)); + ApplicationData appData = RyujinxApp.MainWindow.ViewModel.Applications.FirstOrDefault(x => x.IdString.EqualsIgnoreCase(TitleIdString)); InGameList = appData != null; @@ -59,13 +59,13 @@ namespace Ryujinx.Ava.UI.Models } else { - var appMetadata = ApplicationLibrary.LoadAndSaveMetaData(TitleIdString); + ApplicationMetadata appMetadata = ApplicationLibrary.LoadAndSaveMetaData(TitleIdString); Title = appMetadata.Title ?? TitleIdString; } Task.Run(() => { - var saveRoot = Path.Combine(VirtualFileSystem.GetNandPath(), $"user/save/{info.SaveDataId:x16}"); + string saveRoot = Path.Combine(VirtualFileSystem.GetNandPath(), $"user/save/{info.SaveDataId:x16}"); long totalSize = GetDirectorySize(saveRoot); @@ -74,14 +74,14 @@ namespace Ryujinx.Ava.UI.Models long size = 0; if (Directory.Exists(path)) { - var directories = Directory.GetDirectories(path); - foreach (var directory in directories) + string[] directories = Directory.GetDirectories(path); + foreach (string directory in directories) { size += GetDirectorySize(directory); } - var files = Directory.GetFiles(path); - foreach (var file in files) + string[] files = Directory.GetFiles(path); + foreach (string file in files) { size += new FileInfo(file).Length; } diff --git a/src/Ryujinx/UI/Models/UserProfile.cs b/src/Ryujinx/UI/Models/UserProfile.cs index 7a9237fe1..7aa365e36 100644 --- a/src/Ryujinx/UI/Models/UserProfile.cs +++ b/src/Ryujinx/UI/Models/UserProfile.cs @@ -1,3 +1,4 @@ +using Avalonia; using Avalonia.Media; using Ryujinx.Ava.UI.Controls; using Ryujinx.Ava.UI.ViewModels; @@ -87,7 +88,7 @@ namespace Ryujinx.Ava.UI.Models private void UpdateBackground() { - var currentApplication = Avalonia.Application.Current; + Application currentApplication = Avalonia.Application.Current; currentApplication.Styles.TryGetResource("ControlFillColorSecondary", currentApplication.ActualThemeVariant, out object color); if (color is not null) diff --git a/src/Ryujinx/UI/Renderer/EmbeddedWindowOpenGL.cs b/src/Ryujinx/UI/Renderer/EmbeddedWindowOpenGL.cs index 4f59e2400..81a94d6c4 100644 --- a/src/Ryujinx/UI/Renderer/EmbeddedWindowOpenGL.cs +++ b/src/Ryujinx/UI/Renderer/EmbeddedWindowOpenGL.cs @@ -44,13 +44,13 @@ namespace Ryujinx.Ava.UI.Renderer throw new PlatformNotSupportedException(); } - var flags = OpenGLContextFlags.Compat; + OpenGLContextFlags flags = OpenGLContextFlags.Compat; if (ConfigurationState.Instance.Logger.GraphicsDebugLevel != GraphicsDebugLevel.None) { flags |= OpenGLContextFlags.Debug; } - var graphicsMode = Environment.OSVersion.Platform == PlatformID.Unix ? new FramebufferFormat(new ColorFormat(8, 8, 8, 0), 16, 0, ColorFormat.Zero, 0, 2, false) : FramebufferFormat.Default; + FramebufferFormat graphicsMode = Environment.OSVersion.Platform == PlatformID.Unix ? new FramebufferFormat(new ColorFormat(8, 8, 8, 0), 16, 0, ColorFormat.Zero, 0, 2, false) : FramebufferFormat.Default; Context = PlatformHelper.CreateOpenGLContext(graphicsMode, 3, 3, flags); diff --git a/src/Ryujinx/UI/ViewModels/BaseModel.cs b/src/Ryujinx/UI/ViewModels/BaseModel.cs index c0ccfcae1..94c5ddfdb 100644 --- a/src/Ryujinx/UI/ViewModels/BaseModel.cs +++ b/src/Ryujinx/UI/ViewModels/BaseModel.cs @@ -8,7 +8,7 @@ namespace Ryujinx.Ava.UI.ViewModels protected void OnPropertiesChanged(string firstPropertyName, params ReadOnlySpan propertyNames) { OnPropertyChanged(firstPropertyName); - foreach (var propertyName in propertyNames) + foreach (string propertyName in propertyNames) { OnPropertyChanged(propertyName); } diff --git a/src/Ryujinx/UI/ViewModels/DownloadableContentManagerViewModel.cs b/src/Ryujinx/UI/ViewModels/DownloadableContentManagerViewModel.cs index 52f97cf02..169aeb41d 100644 --- a/src/Ryujinx/UI/ViewModels/DownloadableContentManagerViewModel.cs +++ b/src/Ryujinx/UI/ViewModels/DownloadableContentManagerViewModel.cs @@ -11,6 +11,7 @@ using Ryujinx.Ava.UI.Helpers; using Ryujinx.Ava.Utilities.AppLibrary; using Ryujinx.HLE.FileSystem; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Threading.Tasks; @@ -71,7 +72,7 @@ namespace Ryujinx.Ava.UI.ViewModels private void LoadDownloadableContents() { - var dlcs = _applicationLibrary.DownloadableContents.Items + IEnumerable<(DownloadableContentModel Dlc, bool IsEnabled)> dlcs = _applicationLibrary.DownloadableContents.Items .Where(it => it.Dlc.TitleIdBase == _applicationData.IdBase); bool hasBundledContent = false; @@ -101,11 +102,11 @@ namespace Ryujinx.Ava.UI.ViewModels .ThenBy(it => it.TitleId) .AsObservableChangeSet() .Filter(Filter) - .Bind(out var view).AsObservableList(); + .Bind(out ReadOnlyObservableCollection view).AsObservableList(); // NOTE(jpr): this works around a bug where calling _views.Clear also clears SelectedDownloadableContents for // some reason. so we save the items here and add them back after - var items = SelectedDownloadableContents.ToArray(); + DownloadableContentModel[] items = SelectedDownloadableContents.ToArray(); Views.Clear(); Views.AddRange(view); @@ -130,7 +131,7 @@ namespace Ryujinx.Ava.UI.ViewModels public async void Add() { - var result = await _storageProvider.OpenFilePickerAsync(new FilePickerOpenOptions + IReadOnlyList result = await _storageProvider.OpenFilePickerAsync(new FilePickerOpenOptions { Title = LocaleManager.Instance[LocaleKeys.SelectDlcDialogTitle], AllowMultiple = true, @@ -145,10 +146,10 @@ namespace Ryujinx.Ava.UI.ViewModels }, }); - var totalDlcAdded = 0; - foreach (var file in result) + int totalDlcAdded = 0; + foreach (IStorageFile file in result) { - if (!AddDownloadableContent(file.Path.LocalPath, out var newDlcAdded)) + if (!AddDownloadableContent(file.Path.LocalPath, out int newDlcAdded)) { await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance[LocaleKeys.DialogDlcNoDlcErrorMessage]); } @@ -171,18 +172,18 @@ namespace Ryujinx.Ava.UI.ViewModels return false; } - if (!_applicationLibrary.TryGetDownloadableContentFromFile(path, out var dlcs) || dlcs.Count == 0) + if (!_applicationLibrary.TryGetDownloadableContentFromFile(path, out List dlcs) || dlcs.Count == 0) { return false; } - var dlcsForThisGame = dlcs.Where(it => it.TitleIdBase == _applicationData.IdBase).ToList(); + List dlcsForThisGame = dlcs.Where(it => it.TitleIdBase == _applicationData.IdBase).ToList(); if (dlcsForThisGame.Count == 0) { return false; } - foreach (var dlc in dlcsForThisGame) + foreach (DownloadableContentModel dlc in dlcsForThisGame) { if (!DownloadableContents.Contains(dlc)) { @@ -246,13 +247,13 @@ namespace Ryujinx.Ava.UI.ViewModels public void Save() { - var dlcs = DownloadableContents.Select(it => (it, SelectedDownloadableContents.Contains(it))).ToList(); + List<(DownloadableContentModel it, bool)> dlcs = DownloadableContents.Select(it => (it, SelectedDownloadableContents.Contains(it))).ToList(); _applicationLibrary.SaveDownloadableContentsForGame(_applicationData, dlcs); } private Task ShowNewDlcAddedDialog(int numAdded) { - var msg = string.Format(LocaleManager.Instance[LocaleKeys.DlcWindowDlcAddedMessage], numAdded); + string msg = string.Format(LocaleManager.Instance[LocaleKeys.DlcWindowDlcAddedMessage], numAdded); return Dispatcher.UIThread.InvokeAsync(async () => { await ContentDialogHelper.ShowTextDialog( diff --git a/src/Ryujinx/UI/ViewModels/Input/InputViewModel.cs b/src/Ryujinx/UI/ViewModels/Input/InputViewModel.cs index c59ec540c..cd0488f5f 100644 --- a/src/Ryujinx/UI/ViewModels/Input/InputViewModel.cs +++ b/src/Ryujinx/UI/ViewModels/Input/InputViewModel.cs @@ -215,7 +215,7 @@ namespace Ryujinx.Ava.UI.ViewModels.Input return; } - var selected = Devices[_device].Type; + DeviceType selected = Devices[_device].Type; if (selected != DeviceType.None) { @@ -299,7 +299,7 @@ namespace Ryujinx.Ava.UI.ViewModels.Input } else { - var type = DeviceType.None; + DeviceType type = DeviceType.None; if (Config is StandardKeyboardInputConfig) { @@ -311,7 +311,7 @@ namespace Ryujinx.Ava.UI.ViewModels.Input type = DeviceType.Controller; } - var item = Devices.FirstOrDefault(x => x.Type == type && x.Id == Config.Id); + (DeviceType Type, string Id, string Name) item = Devices.FirstOrDefault(x => x.Type == type && x.Id == Config.Id); if (item != default) { Device = Devices.ToList().FindIndex(x => x.Id == item.Id); @@ -331,7 +331,7 @@ namespace Ryujinx.Ava.UI.ViewModels.Input } string id = GetCurrentGamepadId(); - var type = Devices[Device].Type; + DeviceType type = Devices[Device].Type; if (type == DeviceType.None) { @@ -373,7 +373,7 @@ namespace Ryujinx.Ava.UI.ViewModels.Input return string.Empty; } - var device = Devices[Device]; + (DeviceType Type, string Id, string Name) device = Devices[Device]; if (device.Type == DeviceType.None) { @@ -485,7 +485,7 @@ namespace Ryujinx.Ava.UI.ViewModels.Input private string GetProfileBasePath() { string path = AppDataManager.ProfilesDirPath; - var type = Devices[Device == -1 ? 0 : Device].Type; + DeviceType type = Devices[Device == -1 ? 0 : Device].Type; if (type == DeviceType.Keyboard) { @@ -525,7 +525,7 @@ namespace Ryujinx.Ava.UI.ViewModels.Input public InputConfig LoadDefaultConfiguration() { - var activeDevice = Devices.FirstOrDefault(); + (DeviceType Type, string Id, string Name) activeDevice = Devices.FirstOrDefault(); if (Devices.Count > 0 && Device < Devices.Count && Device >= 0) { @@ -822,20 +822,20 @@ namespace Ryujinx.Ava.UI.ViewModels.Input } else { - var device = Devices[Device]; + (DeviceType Type, string Id, string Name) device = Devices[Device]; if (device.Type == DeviceType.Keyboard) { - var inputConfig = (ConfigViewModel as KeyboardInputViewModel).Config; + KeyboardInputConfig inputConfig = (ConfigViewModel as KeyboardInputViewModel).Config; inputConfig.Id = device.Id; } else { - var inputConfig = (ConfigViewModel as ControllerInputViewModel).Config; + GamepadInputConfig inputConfig = (ConfigViewModel as ControllerInputViewModel).Config; inputConfig.Id = device.Id.Split(" ")[0]; } - var config = !IsController + InputConfig config = !IsController ? (ConfigViewModel as KeyboardInputViewModel).Config.GetConfig() : (ConfigViewModel as ControllerInputViewModel).Config.GetConfig(); config.ControllerType = Controllers[_controller].Type; diff --git a/src/Ryujinx/UI/ViewModels/MainWindowViewModel.cs b/src/Ryujinx/UI/ViewModels/MainWindowViewModel.cs index 07cad41c5..1f938d313 100644 --- a/src/Ryujinx/UI/ViewModels/MainWindowViewModel.cs +++ b/src/Ryujinx/UI/ViewModels/MainWindowViewModel.cs @@ -1046,9 +1046,9 @@ namespace Ryujinx.Ava.UI.ViewModels private void PrepareLoadScreen() { using MemoryStream stream = new(SelectedIcon); - using var gameIconBmp = SKBitmap.Decode(stream); + using SKBitmap gameIconBmp = SKBitmap.Decode(stream); - var dominantColor = IconColorPicker.GetFilteredColor(gameIconBmp); + SKColor dominantColor = IconColorPicker.GetFilteredColor(gameIconBmp); const float ColorMultiple = 0.5f; @@ -1132,7 +1132,7 @@ namespace Ryujinx.Ava.UI.ViewModels private async Task LoadContentFromFolder(LocaleKeys localeMessageAddedKey, LocaleKeys localeMessageRemovedKey, LoadContentFromFolderDelegate onDirsSelected) { - var result = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions + IReadOnlyList result = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions { Title = LocaleManager.Instance[LocaleKeys.OpenFolderDialogTitle], AllowMultiple = true, @@ -1140,10 +1140,10 @@ namespace Ryujinx.Ava.UI.ViewModels if (result.Count > 0) { - var dirs = result.Select(it => it.Path.LocalPath).ToList(); - var numAdded = onDirsSelected(dirs, out int numRemoved); + List dirs = result.Select(it => it.Path.LocalPath).ToList(); + int numAdded = onDirsSelected(dirs, out int numRemoved); - var msg = String.Join("\r\n", new string[] { + string msg = String.Join("\r\n", new string[] { string.Format(LocaleManager.Instance[localeMessageRemovedKey], numRemoved), string.Format(LocaleManager.Instance[localeMessageAddedKey], numAdded) }); @@ -1180,17 +1180,17 @@ namespace Ryujinx.Ava.UI.ViewModels public void LoadConfigurableHotKeys() { - if (AvaloniaKeyboardMappingHelper.TryGetAvaKey((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ShowUI, out var showUiKey)) + if (AvaloniaKeyboardMappingHelper.TryGetAvaKey((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ShowUI, out Avalonia.Input.Key showUiKey)) { ShowUiKey = new KeyGesture(showUiKey); } - if (AvaloniaKeyboardMappingHelper.TryGetAvaKey((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Screenshot, out var screenshotKey)) + if (AvaloniaKeyboardMappingHelper.TryGetAvaKey((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Screenshot, out Avalonia.Input.Key screenshotKey)) { ScreenshotKey = new KeyGesture(screenshotKey); } - if (AvaloniaKeyboardMappingHelper.TryGetAvaKey((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Pause, out var pauseKey)) + if (AvaloniaKeyboardMappingHelper.TryGetAvaKey((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Pause, out Avalonia.Input.Key pauseKey)) { PauseKey = new KeyGesture(pauseKey); } @@ -1238,7 +1238,7 @@ namespace Ryujinx.Ava.UI.ViewModels public async Task InstallFirmwareFromFile() { - var result = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions + IReadOnlyList result = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions { AllowMultiple = false, FileTypeFilter = new List @@ -1272,7 +1272,7 @@ namespace Ryujinx.Ava.UI.ViewModels public async Task InstallFirmwareFromFolder() { - var result = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions + IReadOnlyList result = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions { AllowMultiple = false, }); @@ -1285,7 +1285,7 @@ namespace Ryujinx.Ava.UI.ViewModels public async Task InstallKeysFromFile() { - var result = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions + IReadOnlyList result = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions { AllowMultiple = false, FileTypeFilter = new List @@ -1319,7 +1319,7 @@ namespace Ryujinx.Ava.UI.ViewModels public async Task InstallKeysFromFolder() { - var result = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions + IReadOnlyList result = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions { AllowMultiple = false, }); @@ -1410,7 +1410,7 @@ namespace Ryujinx.Ava.UI.ViewModels public async Task OpenFile() { - var result = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions + IReadOnlyList result = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions { Title = LocaleManager.Instance[LocaleKeys.OpenFileDialogTitle], AllowMultiple = false, @@ -1501,7 +1501,7 @@ namespace Ryujinx.Ava.UI.ViewModels public async Task OpenFolder() { - var result = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions + IReadOnlyList result = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions { Title = LocaleManager.Instance[LocaleKeys.OpenFolderDialogTitle], AllowMultiple = false, @@ -1682,7 +1682,7 @@ namespace Ryujinx.Ava.UI.ViewModels { if (AppHost.Device.System.SearchingForAmiibo(out _) && IsGameRunning) { - var result = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions + IReadOnlyList result = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions { Title = LocaleManager.Instance[LocaleKeys.OpenFileDialogTitle], AllowMultiple = false, @@ -1802,16 +1802,16 @@ namespace Ryujinx.Ava.UI.ViewModels return; } - var trimmer = new XCIFileTrimmer(filename, new XCITrimmerLog.MainWindow(this)); + XCIFileTrimmer trimmer = new XCIFileTrimmer(filename, new XCITrimmerLog.MainWindow(this)); if (trimmer.CanBeTrimmed) { - var savings = (double)trimmer.DiskSpaceSavingsB / 1024.0 / 1024.0; - var currentFileSize = (double)trimmer.FileSizeB / 1024.0 / 1024.0; - var cartDataSize = (double)trimmer.DataSizeB / 1024.0 / 1024.0; + double savings = (double)trimmer.DiskSpaceSavingsB / 1024.0 / 1024.0; + double currentFileSize = (double)trimmer.FileSizeB / 1024.0 / 1024.0; + double cartDataSize = (double)trimmer.DataSizeB / 1024.0 / 1024.0; string secondaryText = LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.TrimXCIFileDialogSecondaryText, currentFileSize, cartDataSize, savings); - var result = await ContentDialogHelper.CreateConfirmationDialog( + UserResult result = await ContentDialogHelper.CreateConfirmationDialog( LocaleManager.Instance[LocaleKeys.TrimXCIFileDialogPrimaryText], secondaryText, LocaleManager.Instance[LocaleKeys.Continue], diff --git a/src/Ryujinx/UI/ViewModels/ModManagerViewModel.cs b/src/Ryujinx/UI/ViewModels/ModManagerViewModel.cs index ce40ce16c..7c465572d 100644 --- a/src/Ryujinx/UI/ViewModels/ModManagerViewModel.cs +++ b/src/Ryujinx/UI/ViewModels/ModManagerViewModel.cs @@ -12,6 +12,8 @@ using Ryujinx.Common.Logging; using Ryujinx.Common.Utilities; using Ryujinx.HLE.HOS; using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; using System.IO; using System.Linq; @@ -77,37 +79,37 @@ namespace Ryujinx.Ava.UI.ViewModels string[] modsBasePaths = [ModLoader.GetSdModsBasePath(), ModLoader.GetModsBasePath()]; - foreach (var path in modsBasePaths) + foreach (string path in modsBasePaths) { - var inSd = path == ModLoader.GetSdModsBasePath(); - var modCache = new ModLoader.ModCache(); + bool inSd = path == ModLoader.GetSdModsBasePath(); + ModLoader.ModCache modCache = new ModLoader.ModCache(); ModLoader.QueryContentsDir(modCache, new DirectoryInfo(Path.Combine(path, "contents")), applicationId); - foreach (var mod in modCache.RomfsDirs) + foreach (ModLoader.Mod mod in modCache.RomfsDirs) { - var modModel = new ModModel(mod.Path.Parent.FullName, mod.Name, mod.Enabled, inSd); + ModModel modModel = new ModModel(mod.Path.Parent.FullName, mod.Name, mod.Enabled, inSd); if (Mods.All(x => x.Path != mod.Path.Parent.FullName)) { Mods.Add(modModel); } } - foreach (var mod in modCache.RomfsContainers) + foreach (ModLoader.Mod mod in modCache.RomfsContainers) { Mods.Add(new ModModel(mod.Path.FullName, mod.Name, mod.Enabled, inSd)); } - foreach (var mod in modCache.ExefsDirs) + foreach (ModLoader.Mod mod in modCache.ExefsDirs) { - var modModel = new ModModel(mod.Path.Parent.FullName, mod.Name, mod.Enabled, inSd); + ModModel modModel = new ModModel(mod.Path.Parent.FullName, mod.Name, mod.Enabled, inSd); if (Mods.All(x => x.Path != mod.Path.Parent.FullName)) { Mods.Add(modModel); } } - foreach (var mod in modCache.ExefsContainers) + foreach (ModLoader.Mod mod in modCache.ExefsContainers) { Mods.Add(new ModModel(mod.Path.FullName, mod.Name, mod.Enabled, inSd)); } @@ -120,7 +122,7 @@ namespace Ryujinx.Ava.UI.ViewModels { Mods.AsObservableChangeSet() .Filter(Filter) - .Bind(out var view).AsObservableList(); + .Bind(out ReadOnlyObservableCollection view).AsObservableList(); #pragma warning disable MVVMTK0034 // Event to update is fired below _views.Clear(); @@ -163,10 +165,10 @@ namespace Ryujinx.Ava.UI.ViewModels public void Delete(ModModel model, bool removeFromList = true) { - var isSubdir = true; - var pathToDelete = model.Path; - var basePath = model.InSd ? ModLoader.GetSdModsBasePath() : ModLoader.GetModsBasePath(); - var modsDir = ModLoader.GetApplicationDir(basePath, _applicationId.ToString("x16")); + bool isSubdir = true; + string pathToDelete = model.Path; + string basePath = model.InSd ? ModLoader.GetSdModsBasePath() : ModLoader.GetModsBasePath(); + string modsDir = ModLoader.GetApplicationDir(basePath, _applicationId.ToString("x16")); if (new DirectoryInfo(model.Path).Parent?.FullName == modsDir) { @@ -175,9 +177,9 @@ namespace Ryujinx.Ava.UI.ViewModels if (isSubdir) { - var parentDir = String.Empty; + string parentDir = String.Empty; - foreach (var dir in Directory.GetDirectories(modsDir, "*", SearchOption.TopDirectoryOnly)) + foreach (string dir in Directory.GetDirectories(modsDir, "*", SearchOption.TopDirectoryOnly)) { if (Directory.GetDirectories(dir, "*", SearchOption.AllDirectories).Contains(model.Path)) { @@ -229,10 +231,10 @@ namespace Ryujinx.Ava.UI.ViewModels return; } - var destinationDir = ModLoader.GetApplicationDir(ModLoader.GetSdModsBasePath(), _applicationId.ToString("x16")); + string destinationDir = ModLoader.GetApplicationDir(ModLoader.GetSdModsBasePath(), _applicationId.ToString("x16")); // TODO: More robust checking for valid mod folders - var isDirectoryValid = true; + bool isDirectoryValid = true; if (directories.Length == 0) { @@ -248,7 +250,7 @@ namespace Ryujinx.Ava.UI.ViewModels return; } - foreach (var dir in directories) + foreach (string dir in directories) { string dirToCreate = dir.Replace(directory.Parent.ToString(), destinationDir); @@ -269,9 +271,9 @@ namespace Ryujinx.Ava.UI.ViewModels Directory.CreateDirectory(dirToCreate); } - var files = Directory.GetFiles(directory.ToString(), "*", SearchOption.AllDirectories); + string[] files = Directory.GetFiles(directory.ToString(), "*", SearchOption.AllDirectories); - foreach (var file in files) + foreach (string file in files) { File.Copy(file, file.Replace(directory.Parent.ToString(), destinationDir), true); } @@ -281,13 +283,13 @@ namespace Ryujinx.Ava.UI.ViewModels public async void Add() { - var result = await _storageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions + IReadOnlyList result = await _storageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions { Title = LocaleManager.Instance[LocaleKeys.SelectModDialogTitle], AllowMultiple = true, }); - foreach (var folder in result) + foreach (IStorageFolder folder in result) { AddMod(new DirectoryInfo(folder.Path.LocalPath)); } diff --git a/src/Ryujinx/UI/ViewModels/SettingsViewModel.cs b/src/Ryujinx/UI/ViewModels/SettingsViewModel.cs index b2311cfc7..b2f94d7b6 100644 --- a/src/Ryujinx/UI/ViewModels/SettingsViewModel.cs +++ b/src/Ryujinx/UI/ViewModels/SettingsViewModel.cs @@ -17,6 +17,7 @@ using Ryujinx.Common.Configuration; using Ryujinx.Common.Configuration.Multiplayer; using Ryujinx.Common.GraphicsDriver; using Ryujinx.Common.Logging; +using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.Vulkan; using Ryujinx.HLE; using Ryujinx.HLE.FileSystem; @@ -386,7 +387,7 @@ namespace Ryujinx.Ava.UI.ViewModels { AvailableGpus.Clear(); - var devices = VulkanRenderer.GetPhysicalDevices(); + DeviceInfo[] devices = VulkanRenderer.GetPhysicalDevices(); if (devices.Length == 0) { @@ -395,7 +396,7 @@ namespace Ryujinx.Ava.UI.ViewModels } else { - foreach (var device in devices) + foreach (DeviceInfo device in devices) { await Dispatcher.UIThread.InvokeAsync(() => { diff --git a/src/Ryujinx/UI/ViewModels/TitleUpdateViewModel.cs b/src/Ryujinx/UI/ViewModels/TitleUpdateViewModel.cs index 86d59d6b4..b01929291 100644 --- a/src/Ryujinx/UI/ViewModels/TitleUpdateViewModel.cs +++ b/src/Ryujinx/UI/ViewModels/TitleUpdateViewModel.cs @@ -41,7 +41,7 @@ namespace Ryujinx.Ava.UI.ViewModels private void LoadUpdates() { - var updates = ApplicationLibrary.TitleUpdates.Items + IEnumerable<(TitleUpdateModel TitleUpdate, bool IsSelected)> updates = ApplicationLibrary.TitleUpdates.Items .Where(it => it.TitleUpdate.TitleIdBase == ApplicationData.IdBase); bool hasBundledContent = false; @@ -64,11 +64,11 @@ namespace Ryujinx.Ava.UI.ViewModels public void SortUpdates() { - var sortedUpdates = TitleUpdates.OrderByDescending(update => update.Version); + IOrderedEnumerable sortedUpdates = TitleUpdates.OrderByDescending(update => update.Version); // NOTE(jpr): this works around a bug where calling Views.Clear also clears SelectedUpdate for // some reason. so we save the item here and restore it after - var selected = SelectedUpdate; + object selected = SelectedUpdate; Views.Clear(); Views.Add(new TitleUpdateViewModelNoUpdate()); @@ -96,18 +96,18 @@ namespace Ryujinx.Ava.UI.ViewModels return false; } - if (!ApplicationLibrary.TryGetTitleUpdatesFromFile(path, out var updates)) + if (!ApplicationLibrary.TryGetTitleUpdatesFromFile(path, out List updates)) { return false; } - var updatesForThisGame = updates.Where(it => it.TitleIdBase == ApplicationData.Id).ToList(); + List updatesForThisGame = updates.Where(it => it.TitleIdBase == ApplicationData.Id).ToList(); if (updatesForThisGame.Count == 0) { return false; } - foreach (var update in updatesForThisGame) + foreach (TitleUpdateModel update in updatesForThisGame) { if (!TitleUpdates.Contains(update)) { @@ -142,7 +142,7 @@ namespace Ryujinx.Ava.UI.ViewModels public async Task Add() { - var result = await _storageProvider.OpenFilePickerAsync(new FilePickerOpenOptions + IReadOnlyList result = await _storageProvider.OpenFilePickerAsync(new FilePickerOpenOptions { AllowMultiple = true, FileTypeFilter = new List @@ -156,10 +156,10 @@ namespace Ryujinx.Ava.UI.ViewModels }, }); - var totalUpdatesAdded = 0; - foreach (var file in result) + int totalUpdatesAdded = 0; + foreach (IStorageFile file in result) { - if (!AddUpdate(file.Path.LocalPath, out var newUpdatesAdded)) + if (!AddUpdate(file.Path.LocalPath, out int newUpdatesAdded)) { await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance[LocaleKeys.DialogUpdateAddUpdateErrorMessage]); } @@ -175,13 +175,13 @@ namespace Ryujinx.Ava.UI.ViewModels public void Save() { - var updates = TitleUpdates.Select(it => (it, it == SelectedUpdate as TitleUpdateModel)).ToList(); + List<(TitleUpdateModel it, bool)> updates = TitleUpdates.Select(it => (it, it == SelectedUpdate as TitleUpdateModel)).ToList(); ApplicationLibrary.SaveTitleUpdatesForGame(ApplicationData, updates); } private Task ShowNewUpdatesAddedDialog(int numAdded) { - var msg = string.Format(LocaleManager.Instance[LocaleKeys.UpdateWindowUpdateAddedMessage], numAdded); + string msg = string.Format(LocaleManager.Instance[LocaleKeys.UpdateWindowUpdateAddedMessage], numAdded); return Dispatcher.UIThread.InvokeAsync(async () => await ContentDialogHelper.ShowTextDialog( LocaleManager.Instance[LocaleKeys.DialogConfirmationTitle], diff --git a/src/Ryujinx/UI/ViewModels/UserFirmwareAvatarSelectorViewModel.cs b/src/Ryujinx/UI/ViewModels/UserFirmwareAvatarSelectorViewModel.cs index 29c81308b..d0b178e41 100644 --- a/src/Ryujinx/UI/ViewModels/UserFirmwareAvatarSelectorViewModel.cs +++ b/src/Ryujinx/UI/ViewModels/UserFirmwareAvatarSelectorViewModel.cs @@ -68,7 +68,7 @@ namespace Ryujinx.Ava.UI.ViewModels { Images.Clear(); - foreach (var image in _avatarStore) + foreach (KeyValuePair image in _avatarStore) { Images.Add(new ProfileImageModel(image.Key, image.Value)); } @@ -76,7 +76,7 @@ namespace Ryujinx.Ava.UI.ViewModels private void ChangeImageBackground() { - foreach (var image in Images) + foreach (ProfileImageModel image in Images) { image.BackgroundColor = new SolidColorBrush(BackgroundColor); } @@ -104,7 +104,7 @@ namespace Ryujinx.Ava.UI.ViewModels // TODO: Parse DatabaseInfo.bin and table.bin files for more accuracy. if (item.Type == DirectoryEntryType.File && item.FullPath.Contains("chara") && item.FullPath.Contains("szs")) { - using var file = new UniqueRef(); + using UniqueRef file = new UniqueRef(); romfs.OpenFile(ref file.Ref, ("/" + item.FullPath).ToU8Span(), OpenMode.Read).ThrowIfFailure(); diff --git a/src/Ryujinx/UI/ViewModels/UserSaveManagerViewModel.cs b/src/Ryujinx/UI/ViewModels/UserSaveManagerViewModel.cs index 187df0449..ac711089e 100644 --- a/src/Ryujinx/UI/ViewModels/UserSaveManagerViewModel.cs +++ b/src/Ryujinx/UI/ViewModels/UserSaveManagerViewModel.cs @@ -41,7 +41,7 @@ namespace Ryujinx.Ava.UI.ViewModels Saves.AsObservableChangeSet() .Filter(Filter) .Sort(GetComparer()) - .Bind(out var view).AsObservableList(); + .Bind(out ReadOnlyObservableCollection view).AsObservableList(); #pragma warning disable MVVMTK0034 _views.Clear(); diff --git a/src/Ryujinx/UI/ViewModels/XCITrimmerViewModel.cs b/src/Ryujinx/UI/ViewModels/XCITrimmerViewModel.cs index 64965cd96..60ddb2040 100644 --- a/src/Ryujinx/UI/ViewModels/XCITrimmerViewModel.cs +++ b/src/Ryujinx/UI/ViewModels/XCITrimmerViewModel.cs @@ -9,6 +9,7 @@ using Ryujinx.Ava.UI.Helpers; using Ryujinx.Ava.Utilities.AppLibrary; using Ryujinx.Common.Utilities; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Linq; using System.Threading; using static Ryujinx.Common.Utilities.XCIFileTrimmer; @@ -54,10 +55,10 @@ namespace Ryujinx.Ava.UI.ViewModels private void LoadXCIApplications() { - var apps = ApplicationLibrary.Applications.Items + IEnumerable apps = ApplicationLibrary.Applications.Items .Where(app => app.FileExtension == _FileExtXCI); - foreach (var xciApp in apps) + foreach (ApplicationData xciApp in apps) AddOrUpdateXCITrimmerFile(CreateXCITrimmerFile(xciApp.Path)); ApplicationsChanged(); @@ -67,7 +68,7 @@ namespace Ryujinx.Ava.UI.ViewModels string path, OperationOutcome operationOutcome = OperationOutcome.Undetermined) { - var xciApp = ApplicationLibrary.Applications.Items.First(app => app.FileExtension == _FileExtXCI && app.Path == path); + ApplicationData xciApp = ApplicationLibrary.Applications.Items.First(app => app.FileExtension == _FileExtXCI && app.Path == path); return XCITrimmerFileModel.FromApplicationData(xciApp, _logger) with { ProcessingOutcome = operationOutcome }; } @@ -156,17 +157,17 @@ namespace Ryujinx.Ava.UI.ViewModels _processingMode = processingMode; Processing = true; - var cancellationToken = _cancellationTokenSource.Token; + CancellationToken cancellationToken = _cancellationTokenSource.Token; Thread XCIFileTrimThread = new(() => { - var toProcess = Sort(SelectedXCIFiles + List toProcess = Sort(SelectedXCIFiles .Where(xci => (processingMode == ProcessingMode.Untrimming && xci.Untrimmable) || (processingMode == ProcessingMode.Trimming && xci.Trimmable) )).ToList(); - var viewsSaved = DisplayedXCIFiles.ToList(); + List viewsSaved = DisplayedXCIFiles.ToList(); Dispatcher.UIThread.Post(() => { @@ -177,19 +178,19 @@ namespace Ryujinx.Ava.UI.ViewModels try { - foreach (var xciApp in toProcess) + foreach (XCITrimmerFileModel xciApp in toProcess) { if (cancellationToken.IsCancellationRequested) break; - var trimmer = new XCIFileTrimmer(xciApp.Path, _logger); + XCIFileTrimmer trimmer = new XCIFileTrimmer(xciApp.Path, _logger); Dispatcher.UIThread.Post(() => { ProcessingApplication = xciApp; }); - var outcome = OperationOutcome.Undetermined; + OperationOutcome outcome = OperationOutcome.Undetermined; try { @@ -347,7 +348,7 @@ namespace Ryujinx.Ava.UI.ViewModels Sort(AllXCIFiles) .AsObservableChangeSet() .Filter(Filter) - .Bind(out var view).AsObservableList(); + .Bind(out ReadOnlyObservableCollection view).AsObservableList(); _displayedXCIFiles.Clear(); _displayedXCIFiles.AddRange(view); diff --git a/src/Ryujinx/UI/Views/Input/ControllerInputView.axaml.cs b/src/Ryujinx/UI/Views/Input/ControllerInputView.axaml.cs index 81483ce0e..4fdc84419 100644 --- a/src/Ryujinx/UI/Views/Input/ControllerInputView.axaml.cs +++ b/src/Ryujinx/UI/Views/Input/ControllerInputView.axaml.cs @@ -12,6 +12,7 @@ using Ryujinx.Common.Configuration.Hid.Controller; using Ryujinx.Input; using Ryujinx.Input.Assigner; using System.Linq; +using Button = Ryujinx.Input.Button; using StickInputId = Ryujinx.Common.Configuration.Hid.Controller.StickInputId; namespace Ryujinx.Ava.UI.Views.Input @@ -104,7 +105,7 @@ namespace Ryujinx.Ava.UI.Views.Input PointerPressed += MouseClick; - var viewModel = (DataContext as ControllerInputViewModel); + ControllerInputViewModel viewModel = (DataContext as ControllerInputViewModel); IKeyboard keyboard = (IKeyboard)viewModel.ParentModel.AvaloniaKeyboardDriver @@ -115,7 +116,7 @@ namespace Ryujinx.Ava.UI.Views.Input { if (e.ButtonValue.HasValue) { - var buttonValue = e.ButtonValue.Value; + Button buttonValue = e.ButtonValue.Value; viewModel.ParentModel.IsModified = true; switch (button.Name) @@ -223,7 +224,7 @@ namespace Ryujinx.Ava.UI.Views.Input { IButtonAssigner assigner; - var controllerInputViewModel = DataContext as ControllerInputViewModel; + ControllerInputViewModel controllerInputViewModel = DataContext as ControllerInputViewModel; assigner = new GamepadButtonAssigner( controllerInputViewModel.ParentModel.SelectedGamepad, diff --git a/src/Ryujinx/UI/Views/Input/InputView.axaml.cs b/src/Ryujinx/UI/Views/Input/InputView.axaml.cs index 3c9d4040f..b1061f70d 100644 --- a/src/Ryujinx/UI/Views/Input/InputView.axaml.cs +++ b/src/Ryujinx/UI/Views/Input/InputView.axaml.cs @@ -37,7 +37,7 @@ namespace Ryujinx.Ava.UI.Views.Input { _dialogOpen = true; - var result = await ContentDialogHelper.CreateDeniableConfirmationDialog( + UserResult result = await ContentDialogHelper.CreateDeniableConfirmationDialog( LocaleManager.Instance[LocaleKeys.DialogControllerSettingsModifiedConfirmMessage], LocaleManager.Instance[LocaleKeys.DialogControllerSettingsModifiedConfirmSubMessage], LocaleManager.Instance[LocaleKeys.InputDialogYes], diff --git a/src/Ryujinx/UI/Views/Input/KeyboardInputView.axaml.cs b/src/Ryujinx/UI/Views/Input/KeyboardInputView.axaml.cs index 090d0335c..99e424d4f 100644 --- a/src/Ryujinx/UI/Views/Input/KeyboardInputView.axaml.cs +++ b/src/Ryujinx/UI/Views/Input/KeyboardInputView.axaml.cs @@ -8,6 +8,7 @@ using Ryujinx.Ava.UI.Helpers; using Ryujinx.Ava.UI.ViewModels.Input; using Ryujinx.Input; using Ryujinx.Input.Assigner; +using Button = Ryujinx.Input.Button; using Key = Ryujinx.Common.Configuration.Hid.Key; namespace Ryujinx.Ava.UI.Views.Input @@ -71,7 +72,7 @@ namespace Ryujinx.Ava.UI.Views.Input { if (e.ButtonValue.HasValue) { - var buttonValue = e.ButtonValue.Value; + Button buttonValue = e.ButtonValue.Value; viewModel.ParentModel.IsModified = true; switch (button.Name) diff --git a/src/Ryujinx/UI/Views/Input/MotionInputView.axaml.cs b/src/Ryujinx/UI/Views/Input/MotionInputView.axaml.cs index ca4a4e1cf..36068821f 100644 --- a/src/Ryujinx/UI/Views/Input/MotionInputView.axaml.cs +++ b/src/Ryujinx/UI/Views/Input/MotionInputView.axaml.cs @@ -1,6 +1,7 @@ using Avalonia.Controls; using FluentAvalonia.UI.Controls; using Ryujinx.Ava.Common.Locale; +using Ryujinx.Ava.UI.Models.Input; using Ryujinx.Ava.UI.ViewModels.Input; using System.Threading.Tasks; @@ -17,7 +18,7 @@ namespace Ryujinx.Ava.UI.Views.Input public MotionInputView(ControllerInputViewModel viewModel) { - var config = viewModel.Config; + GamepadInputConfig config = viewModel.Config; _viewModel = new MotionInputViewModel { @@ -49,7 +50,7 @@ namespace Ryujinx.Ava.UI.Views.Input }; contentDialog.PrimaryButtonClick += (sender, args) => { - var config = viewModel.Config; + GamepadInputConfig config = viewModel.Config; config.Slot = content._viewModel.Slot; config.Sensitivity = content._viewModel.Sensitivity; config.GyroDeadzone = content._viewModel.GyroDeadzone; diff --git a/src/Ryujinx/UI/Views/Input/RumbleInputView.axaml.cs b/src/Ryujinx/UI/Views/Input/RumbleInputView.axaml.cs index 86a75e6eb..6a76ea59b 100644 --- a/src/Ryujinx/UI/Views/Input/RumbleInputView.axaml.cs +++ b/src/Ryujinx/UI/Views/Input/RumbleInputView.axaml.cs @@ -1,6 +1,7 @@ using Avalonia.Controls; using FluentAvalonia.UI.Controls; using Ryujinx.Ava.Common.Locale; +using Ryujinx.Ava.UI.Models.Input; using Ryujinx.Ava.UI.ViewModels.Input; using System.Threading.Tasks; @@ -17,7 +18,7 @@ namespace Ryujinx.Ava.UI.Views.Input public RumbleInputView(ControllerInputViewModel viewModel) { - var config = viewModel.Config; + GamepadInputConfig config = viewModel.Config; _viewModel = new RumbleInputViewModel { @@ -45,7 +46,7 @@ namespace Ryujinx.Ava.UI.Views.Input contentDialog.PrimaryButtonClick += (sender, args) => { - var config = viewModel.Config; + GamepadInputConfig config = viewModel.Config; config.StrongRumble = content._viewModel.StrongRumble; config.WeakRumble = content._viewModel.WeakRumble; }; diff --git a/src/Ryujinx/UI/Views/Main/MainMenuBarView.axaml.cs b/src/Ryujinx/UI/Views/Main/MainMenuBarView.axaml.cs index 9a63c022d..113c77e15 100644 --- a/src/Ryujinx/UI/Views/Main/MainMenuBarView.axaml.cs +++ b/src/Ryujinx/UI/Views/Main/MainMenuBarView.axaml.cs @@ -4,11 +4,14 @@ using Avalonia.Layout; using Avalonia.Threading; using CommunityToolkit.Mvvm.Input; using Gommon; +using LibHac.Common; +using LibHac.Ns; using Ryujinx.Ava.Common.Locale; using Ryujinx.Ava.UI.Helpers; using Ryujinx.Ava.UI.ViewModels; using Ryujinx.Ava.UI.Windows; using Ryujinx.Ava.Utilities; +using Ryujinx.Ava.Utilities.AppLibrary; using Ryujinx.Ava.Utilities.Compat; using Ryujinx.Ava.Utilities.Configuration; using Ryujinx.Common; @@ -142,7 +145,7 @@ namespace Ryujinx.Ava.UI.Views.Main public async Task OpenMiiApplet() { - if (!MiiApplet.CanStart(out var appData, out var nacpData)) + if (!MiiApplet.CanStart(out ApplicationData appData, out BlitStruct nacpData)) return; await ViewModel.LoadApplication(appData, ViewModel.IsFullScreen || ViewModel.StartGamesInFullscreen, nacpData); diff --git a/src/Ryujinx/UI/Views/Settings/SettingsHotkeysView.axaml.cs b/src/Ryujinx/UI/Views/Settings/SettingsHotkeysView.axaml.cs index 609f61633..d3d1537e0 100644 --- a/src/Ryujinx/UI/Views/Settings/SettingsHotkeysView.axaml.cs +++ b/src/Ryujinx/UI/Views/Settings/SettingsHotkeysView.axaml.cs @@ -8,6 +8,7 @@ using Ryujinx.Ava.UI.Helpers; using Ryujinx.Ava.UI.ViewModels; using Ryujinx.Input; using Ryujinx.Input.Assigner; +using Button = Ryujinx.Input.Button; using Key = Ryujinx.Common.Configuration.Hid.Key; namespace Ryujinx.Ava.UI.Views.Settings @@ -70,15 +71,15 @@ namespace Ryujinx.Ava.UI.Views.Settings PointerPressed += MouseClick; - var keyboard = (IKeyboard)_avaloniaKeyboardDriver.GetGamepad("0"); + IKeyboard keyboard = (IKeyboard)_avaloniaKeyboardDriver.GetGamepad("0"); IButtonAssigner assigner = new KeyboardKeyAssigner(keyboard); _currentAssigner.ButtonAssigned += (sender, e) => { if (e.ButtonValue.HasValue) { - var viewModel = (DataContext) as SettingsViewModel; - var buttonValue = e.ButtonValue.Value; + SettingsViewModel viewModel = (DataContext) as SettingsViewModel; + Button buttonValue = e.ButtonValue.Value; switch (button.Name) { diff --git a/src/Ryujinx/UI/Views/User/UserEditorView.axaml.cs b/src/Ryujinx/UI/Views/User/UserEditorView.axaml.cs index 588fa471e..695586a36 100644 --- a/src/Ryujinx/UI/Views/User/UserEditorView.axaml.cs +++ b/src/Ryujinx/UI/Views/User/UserEditorView.axaml.cs @@ -39,7 +39,7 @@ namespace Ryujinx.Ava.UI.Views.User switch (arg.NavigationMode) { case NavigationMode.New: - var (parent, profile, isNewUser) = ((NavigationDialogHost parent, UserProfile profile, bool isNewUser))arg.Parameter; + (NavigationDialogHost parent, UserProfile profile, bool isNewUser) = ((NavigationDialogHost parent, UserProfile profile, bool isNewUser))arg.Parameter; _isNewUser = isNewUser; _profile = profile; TempProfile = new TempProfile(_profile); diff --git a/src/Ryujinx/UI/Views/User/UserFirmwareAvatarSelectorView.axaml.cs b/src/Ryujinx/UI/Views/User/UserFirmwareAvatarSelectorView.axaml.cs index 064b5e908..206926755 100644 --- a/src/Ryujinx/UI/Views/User/UserFirmwareAvatarSelectorView.axaml.cs +++ b/src/Ryujinx/UI/Views/User/UserFirmwareAvatarSelectorView.axaml.cs @@ -66,11 +66,11 @@ namespace Ryujinx.Ava.UI.Views.User { if (ViewModel.SelectedImage != null) { - using var streamJpg = new MemoryStream(); - using var bitmap = SKBitmap.Decode(ViewModel.SelectedImage); - using var newBitmap = new SKBitmap(bitmap.Width, bitmap.Height); + using MemoryStream streamJpg = new MemoryStream(); + using SKBitmap bitmap = SKBitmap.Decode(ViewModel.SelectedImage); + using SKBitmap newBitmap = new SKBitmap(bitmap.Width, bitmap.Height); - using (var canvas = new SKCanvas(newBitmap)) + using (SKCanvas canvas = new SKCanvas(newBitmap)) { canvas.Clear(new SKColor( ViewModel.BackgroundColor.R, @@ -80,8 +80,8 @@ namespace Ryujinx.Ava.UI.Views.User canvas.DrawBitmap(bitmap, 0, 0); } - using (var image = SKImage.FromBitmap(newBitmap)) - using (var dataJpeg = image.Encode(SKEncodedImageFormat.Jpeg, 100)) + using (SKImage image = SKImage.FromBitmap(newBitmap)) + using (SKData dataJpeg = image.Encode(SKEncodedImageFormat.Jpeg, 100)) { dataJpeg.SaveTo(streamJpg); } diff --git a/src/Ryujinx/UI/Views/User/UserProfileImageSelectorView.axaml.cs b/src/Ryujinx/UI/Views/User/UserProfileImageSelectorView.axaml.cs index dba762972..73656e881 100644 --- a/src/Ryujinx/UI/Views/User/UserProfileImageSelectorView.axaml.cs +++ b/src/Ryujinx/UI/Views/User/UserProfileImageSelectorView.axaml.cs @@ -63,7 +63,7 @@ namespace Ryujinx.Ava.UI.Views.User private async void Import_OnClick(object sender, RoutedEventArgs e) { - var result = await ((Window)this.GetVisualRoot()!).StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions + IReadOnlyList result = await ((Window)this.GetVisualRoot()!).StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions { AllowMultiple = false, FileTypeFilter = new List @@ -99,16 +99,16 @@ namespace Ryujinx.Ava.UI.Views.User private static byte[] ProcessProfileImage(byte[] buffer) { - using var bitmap = SKBitmap.Decode(buffer); + using SKBitmap bitmap = SKBitmap.Decode(buffer); - var resizedBitmap = bitmap.Resize(new SKImageInfo(256, 256), SKFilterQuality.High); + SKBitmap resizedBitmap = bitmap.Resize(new SKImageInfo(256, 256), SKFilterQuality.High); - using var streamJpg = new MemoryStream(); + using MemoryStream streamJpg = new MemoryStream(); if (resizedBitmap != null) { - using var image = SKImage.FromBitmap(resizedBitmap); - using var dataJpeg = image.Encode(SKEncodedImageFormat.Jpeg, 100); + using SKImage image = SKImage.FromBitmap(resizedBitmap); + using SKData dataJpeg = image.Encode(SKEncodedImageFormat.Jpeg, 100); dataJpeg.SaveTo(streamJpg); } diff --git a/src/Ryujinx/UI/Views/User/UserRecovererView.axaml.cs b/src/Ryujinx/UI/Views/User/UserRecovererView.axaml.cs index 31934349d..98d7ceac9 100644 --- a/src/Ryujinx/UI/Views/User/UserRecovererView.axaml.cs +++ b/src/Ryujinx/UI/Views/User/UserRecovererView.axaml.cs @@ -27,7 +27,7 @@ namespace Ryujinx.Ava.UI.Views.User switch (arg.NavigationMode) { case NavigationMode.New: - var parent = (NavigationDialogHost)arg.Parameter; + NavigationDialogHost parent = (NavigationDialogHost)arg.Parameter; _parent = parent; diff --git a/src/Ryujinx/UI/Views/User/UserSaveManagerView.axaml.cs b/src/Ryujinx/UI/Views/User/UserSaveManagerView.axaml.cs index 69986c014..1d9cb10cf 100644 --- a/src/Ryujinx/UI/Views/User/UserSaveManagerView.axaml.cs +++ b/src/Ryujinx/UI/Views/User/UserSaveManagerView.axaml.cs @@ -48,7 +48,7 @@ namespace Ryujinx.Ava.UI.Views.User switch (arg.NavigationMode) { case NavigationMode.New: - var (parent, accountManager, client, virtualFileSystem) = ((NavigationDialogHost parent, AccountManager accountManager, HorizonClient client, VirtualFileSystem virtualFileSystem))arg.Parameter; + (NavigationDialogHost parent, AccountManager accountManager, HorizonClient client, VirtualFileSystem virtualFileSystem) = ((NavigationDialogHost parent, AccountManager accountManager, HorizonClient client, VirtualFileSystem virtualFileSystem))arg.Parameter; _accountManager = accountManager; _horizonClient = client; _virtualFileSystem = virtualFileSystem; @@ -67,15 +67,15 @@ namespace Ryujinx.Ava.UI.Views.User public void LoadSaves() { ViewModel.Saves.Clear(); - var saves = new ObservableCollection(); - var saveDataFilter = SaveDataFilter.Make( + ObservableCollection saves = new ObservableCollection(); + SaveDataFilter saveDataFilter = SaveDataFilter.Make( programId: default, saveType: SaveDataType.Account, new UserId((ulong)_accountManager.LastOpenedUser.UserId.High, (ulong)_accountManager.LastOpenedUser.UserId.Low), saveDataId: default, index: default); - using var saveDataIterator = new UniqueRef(); + using UniqueRef saveDataIterator = new UniqueRef(); _horizonClient.Fs.OpenSaveDataIterator(ref saveDataIterator.Ref, SaveDataSpaceId.User, in saveDataFilter).ThrowIfFailure(); @@ -92,10 +92,10 @@ namespace Ryujinx.Ava.UI.Views.User for (int i = 0; i < readCount; i++) { - var save = saveDataInfo[i]; + SaveDataInfo save = saveDataInfo[i]; if (save.ProgramId.Value != 0) { - var saveModel = new SaveModel(save); + SaveModel saveModel = new SaveModel(save); saves.Add(saveModel); } } @@ -130,7 +130,7 @@ namespace Ryujinx.Ava.UI.Views.User { if (button.DataContext is SaveModel saveModel) { - var result = await ContentDialogHelper.CreateConfirmationDialog(LocaleManager.Instance[LocaleKeys.DeleteUserSave], + UserResult result = await ContentDialogHelper.CreateConfirmationDialog(LocaleManager.Instance[LocaleKeys.DeleteUserSave], LocaleManager.Instance[LocaleKeys.IrreversibleActionNote], LocaleManager.Instance[LocaleKeys.InputDialogYes], LocaleManager.Instance[LocaleKeys.InputDialogNo], diff --git a/src/Ryujinx/UI/Windows/CheatWindow.axaml.cs b/src/Ryujinx/UI/Windows/CheatWindow.axaml.cs index c770a6f45..3ed27bfe7 100644 --- a/src/Ryujinx/UI/Windows/CheatWindow.axaml.cs +++ b/src/Ryujinx/UI/Windows/CheatWindow.axaml.cs @@ -6,6 +6,7 @@ using Ryujinx.Ava.Utilities.AppLibrary; using Ryujinx.Ava.Utilities.Configuration; using Ryujinx.HLE.FileSystem; using Ryujinx.HLE.HOS; +using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; @@ -58,7 +59,7 @@ namespace Ryujinx.Ava.UI.Windows int cheatAdded = 0; - var mods = new ModLoader.ModCache(); + ModLoader.ModCache mods = new ModLoader.ModCache(); ModLoader.QueryContentsDir(mods, new DirectoryInfo(Path.Combine(modsBasePath, "contents")), titleIdValue); @@ -67,7 +68,7 @@ namespace Ryujinx.Ava.UI.Windows CheatNode currentGroup = null; - foreach (var cheat in mods.Cheats) + foreach (ModLoader.Cheat cheat in mods.Cheats) { if (cheat.Path.FullName != currentCheatFile) { @@ -80,7 +81,7 @@ namespace Ryujinx.Ava.UI.Windows LoadedCheats.Add(currentGroup); } - var model = new CheatNode(cheat.Name, buildId, string.Empty, false, enabled.Contains($"{buildId}-{cheat.Name}")); + CheatNode model = new CheatNode(cheat.Name, buildId, string.Empty, false, enabled.Contains($"{buildId}-{cheat.Name}")); currentGroup?.SubNodes.Add(model); cheatAdded++; @@ -101,7 +102,7 @@ namespace Ryujinx.Ava.UI.Windows if (NoCheatsFound) return; - var enabledCheats = LoadedCheats.SelectMany(it => it.SubNodes) + IEnumerable enabledCheats = LoadedCheats.SelectMany(it => it.SubNodes) .Where(it => it.IsEnabled) .Select(it => it.BuildIdKey); diff --git a/src/Ryujinx/UI/Windows/DownloadableContentManagerWindow.axaml.cs b/src/Ryujinx/UI/Windows/DownloadableContentManagerWindow.axaml.cs index 3e8203e31..777b462b5 100644 --- a/src/Ryujinx/UI/Windows/DownloadableContentManagerWindow.axaml.cs +++ b/src/Ryujinx/UI/Windows/DownloadableContentManagerWindow.axaml.cs @@ -79,7 +79,7 @@ namespace Ryujinx.Ava.UI.Windows private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) { - foreach (var content in e.AddedItems) + foreach (object content in e.AddedItems) { if (content is DownloadableContentModel model) { @@ -87,7 +87,7 @@ namespace Ryujinx.Ava.UI.Windows } } - foreach (var content in e.RemovedItems) + foreach (object content in e.RemovedItems) { if (content is DownloadableContentModel model) { diff --git a/src/Ryujinx/UI/Windows/IconColorPicker.cs b/src/Ryujinx/UI/Windows/IconColorPicker.cs index bfa33eb43..78ad8562f 100644 --- a/src/Ryujinx/UI/Windows/IconColorPicker.cs +++ b/src/Ryujinx/UI/Windows/IconColorPicker.cs @@ -29,7 +29,7 @@ namespace Ryujinx.Ava.UI.Windows public static SKColor GetFilteredColor(SKBitmap image) { - var color = GetColor(image); + SKColor color = GetColor(image); // We don't want colors that are too dark. @@ -49,10 +49,10 @@ namespace Ryujinx.Ava.UI.Windows public static SKColor GetColor(SKBitmap image) { - var colors = new PaletteColor[TotalColors]; - var dominantColorBin = new Dictionary(); + PaletteColor[] colors = new PaletteColor[TotalColors]; + Dictionary dominantColorBin = new Dictionary(); - var buffer = GetBuffer(image); + SKColor[] buffer = GetBuffer(image); int i = 0; int maxHitCount = 0; @@ -70,7 +70,7 @@ namespace Ryujinx.Ava.UI.Windows byte cg = pixel.Green; byte cb = pixel.Blue; - var qck = GetQuantizedColorKey(cr, cg, cb); + int qck = GetQuantizedColorKey(cr, cg, cb); if (dominantColorBin.TryGetValue(qck, out int hitCount)) { @@ -95,7 +95,7 @@ namespace Ryujinx.Ava.UI.Windows for (i = 0; i < TotalColors; i++) { - var score = GetColorScore(dominantColorBin, maxHitCount, colors[i]); + int score = GetColorScore(dominantColorBin, maxHitCount, colors[i]); if (highScore < score) { @@ -109,7 +109,7 @@ namespace Ryujinx.Ava.UI.Windows public static SKColor[] GetBuffer(SKBitmap image) { - var pixels = new SKColor[image.Width * image.Height]; + SKColor[] pixels = new SKColor[image.Width * image.Height]; for (int y = 0; y < image.Height; y++) { @@ -124,17 +124,17 @@ namespace Ryujinx.Ava.UI.Windows private static int GetColorScore(Dictionary dominantColorBin, int maxHitCount, PaletteColor color) { - var hitCount = dominantColorBin[color.Qck]; - var balancedHitCount = BalanceHitCount(hitCount, maxHitCount); - var quantSat = (GetColorSaturation(color) >> SatQuantShift) << SatQuantShift; - var value = GetColorValue(color); + int hitCount = dominantColorBin[color.Qck]; + int balancedHitCount = BalanceHitCount(hitCount, maxHitCount); + int quantSat = (GetColorSaturation(color) >> SatQuantShift) << SatQuantShift; + int value = GetColorValue(color); // If the color is rarely used on the image, // then chances are that there's a better candidate, even if the saturation value // is high. By multiplying the saturation value with a weight, we can lower // it if the color is almost never used (hit count is low). - var satWeighted = quantSat; - var satWeight = balancedHitCount << 5; + int satWeighted = quantSat; + int satWeight = balancedHitCount << 5; if (satWeight < 0x100) { satWeighted = (satWeighted * satWeight) >> 8; @@ -142,7 +142,7 @@ namespace Ryujinx.Ava.UI.Windows // Compute score from saturation and dominance of the color. // We prefer more vivid colors over dominant ones, so give more weight to the saturation. - var score = ((satWeighted << 1) + balancedHitCount) * value; + int score = ((satWeighted << 1) + balancedHitCount) * value; return score; } diff --git a/src/Ryujinx/UI/Windows/MainWindow.axaml.cs b/src/Ryujinx/UI/Windows/MainWindow.axaml.cs index 0ee59325a..76002d1ab 100644 --- a/src/Ryujinx/UI/Windows/MainWindow.axaml.cs +++ b/src/Ryujinx/UI/Windows/MainWindow.axaml.cs @@ -8,6 +8,7 @@ using DynamicData; using FluentAvalonia.UI.Controls; using FluentAvalonia.UI.Windowing; using Gommon; +using LibHac.Ns; using LibHac.Tools.FsSystem; using Ryujinx.Ava.Common; using Ryujinx.Ava.Common.Locale; @@ -171,11 +172,11 @@ namespace Ryujinx.Ava.UI.Windows { Dispatcher.UIThread.Post(() => { - var ldnGameDataArray = e.LdnData.ToList(); + List ldnGameDataArray = e.LdnData.ToList(); ViewModel.LdnData.Clear(); - foreach (var application in ViewModel.Applications.Where(it => it.HasControlHolder)) + foreach (ApplicationData application in ViewModel.Applications.Where(it => it.HasControlHolder)) { - ref var controlHolder = ref application.ControlHolder.Value; + ref ApplicationControlProperty controlHolder = ref application.ControlHolder.Value; ViewModel.LdnData[application.IdString] = LdnGameData.GetArrayForApp( @@ -192,7 +193,7 @@ namespace Ryujinx.Ava.UI.Windows private void UpdateApplicationWithLdnData(ApplicationData application) { - if (application.HasControlHolder && ViewModel.LdnData.TryGetValue(application.IdString, out var ldnGameDatas)) + if (application.HasControlHolder && ViewModel.LdnData.TryGetValue(application.IdString, out LdnGameData.Array ldnGameDatas)) { application.PlayerCount = ldnGameDatas.PlayerCount; application.GameCount = ldnGameDatas.GameCount; @@ -690,12 +691,12 @@ namespace Ryujinx.Ava.UI.Windows ApplicationLibrary.LoadApplications(ConfigurationState.Instance.UI.GameDirs); - var autoloadDirs = ConfigurationState.Instance.UI.AutoloadDirs.Value; + List autoloadDirs = ConfigurationState.Instance.UI.AutoloadDirs.Value; autoloadDirs.ForEach(dir => Logger.Info?.Print(LogClass.Application, $"Auto loading DLC & updates from: {dir}")); if (autoloadDirs.Count > 0) { - var updatesLoaded = ApplicationLibrary.AutoLoadTitleUpdates(autoloadDirs, out int updatesRemoved); - var dlcLoaded = ApplicationLibrary.AutoLoadDownloadableContents(autoloadDirs, out int dlcRemoved); + int updatesLoaded = ApplicationLibrary.AutoLoadTitleUpdates(autoloadDirs, out int updatesRemoved); + int dlcLoaded = ApplicationLibrary.AutoLoadDownloadableContents(autoloadDirs, out int dlcRemoved); ShowNewContentAddedDialog(dlcLoaded, dlcRemoved, updatesLoaded, updatesRemoved); } diff --git a/src/Ryujinx/UI/Windows/ModManagerWindow.axaml.cs b/src/Ryujinx/UI/Windows/ModManagerWindow.axaml.cs index 449aab554..3d70917f0 100644 --- a/src/Ryujinx/UI/Windows/ModManagerWindow.axaml.cs +++ b/src/Ryujinx/UI/Windows/ModManagerWindow.axaml.cs @@ -66,7 +66,7 @@ namespace Ryujinx.Ava.UI.Windows { if (button.DataContext is ModModel model) { - var result = await ContentDialogHelper.CreateConfirmationDialog( + UserResult result = await ContentDialogHelper.CreateConfirmationDialog( LocaleManager.Instance[LocaleKeys.DialogWarning], LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogModManagerDeletionWarningMessage, model.Name), LocaleManager.Instance[LocaleKeys.InputDialogYes], @@ -83,7 +83,7 @@ namespace Ryujinx.Ava.UI.Windows private async void DeleteAll(object sender, RoutedEventArgs e) { - var result = await ContentDialogHelper.CreateConfirmationDialog( + UserResult result = await ContentDialogHelper.CreateConfirmationDialog( LocaleManager.Instance[LocaleKeys.DialogWarning], LocaleManager.Instance[LocaleKeys.DialogModManagerDeletionAllWarningMessage], LocaleManager.Instance[LocaleKeys.InputDialogYes], @@ -109,11 +109,11 @@ namespace Ryujinx.Ava.UI.Windows private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) { - foreach (var content in e.AddedItems) + foreach (object content in e.AddedItems) { if (content is ModModel model) { - var index = ViewModel.Mods.IndexOf(model); + int index = ViewModel.Mods.IndexOf(model); if (index != -1) { @@ -122,11 +122,11 @@ namespace Ryujinx.Ava.UI.Windows } } - foreach (var content in e.RemovedItems) + foreach (object content in e.RemovedItems) { if (content is ModModel model) { - var index = ViewModel.Mods.IndexOf(model); + int index = ViewModel.Mods.IndexOf(model); if (index != -1) { diff --git a/src/Ryujinx/UI/Windows/XCITrimmerWindow.axaml.cs b/src/Ryujinx/UI/Windows/XCITrimmerWindow.axaml.cs index 03ccc06a7..e02ff6279 100644 --- a/src/Ryujinx/UI/Windows/XCITrimmerWindow.axaml.cs +++ b/src/Ryujinx/UI/Windows/XCITrimmerWindow.axaml.cs @@ -81,7 +81,7 @@ namespace Ryujinx.Ava.UI.Windows private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) { - foreach (var content in e.AddedItems) + foreach (object content in e.AddedItems) { if (content is XCITrimmerFileModel applicationData) { @@ -89,7 +89,7 @@ namespace Ryujinx.Ava.UI.Windows } } - foreach (var content in e.RemovedItems) + foreach (object content in e.RemovedItems) { if (content is XCITrimmerFileModel applicationData) { diff --git a/src/Ryujinx/Updater.cs b/src/Ryujinx/Updater.cs index f878e1af5..230840a9a 100644 --- a/src/Ryujinx/Updater.cs +++ b/src/Ryujinx/Updater.cs @@ -71,7 +71,7 @@ namespace Ryujinx.Ava } else if (OperatingSystem.IsLinux()) { - var arch = RuntimeInformation.OSArchitecture == Architecture.Arm64 ? "arm64" : "x64"; + string arch = RuntimeInformation.OSArchitecture == Architecture.Arm64 ? "arm64" : "x64"; _platformExt = $"linux_{arch}.tar.gz"; } @@ -96,10 +96,10 @@ namespace Ryujinx.Ava using HttpClient jsonClient = ConstructHttpClient(); string fetchedJson = await jsonClient.GetStringAsync(LatestReleaseUrl); - var fetched = JsonHelper.Deserialize(fetchedJson, _serializerContext.GithubReleasesJsonResponse); + GithubReleasesJsonResponse fetched = JsonHelper.Deserialize(fetchedJson, _serializerContext.GithubReleasesJsonResponse); _buildVer = fetched.TagName; - foreach (var asset in fetched.Assets) + foreach (GithubReleaseAssetJsonResponse asset in fetched.Assets) { if (asset.Name.StartsWith("ryujinx") && asset.Name.EndsWith(_platformExt)) { @@ -711,15 +711,15 @@ namespace Ryujinx.Ava // 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. + IEnumerable 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 && !OperatingSystem.IsMacOS()) { // 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)); + IEnumerable oldFiles = Directory.EnumerateFiles(_homeDir, "*", SearchOption.TopDirectoryOnly).Select(Path.GetFileName); + IEnumerable newFiles = Directory.EnumerateFiles(_updatePublishDir, "*", SearchOption.TopDirectoryOnly).Select(Path.GetFileName); + IEnumerable userFiles = oldFiles.Except(newFiles).Select(filename => Path.Combine(_homeDir, filename)); // Remove user files from the paths in files. files = files.Except(userFiles); diff --git a/src/Ryujinx/Utilities/AppLibrary/ApplicationData.cs b/src/Ryujinx/Utilities/AppLibrary/ApplicationData.cs index a9610d7b2..5649addab 100644 --- a/src/Ryujinx/Utilities/AppLibrary/ApplicationData.cs +++ b/src/Ryujinx/Utilities/AppLibrary/ApplicationData.cs @@ -76,14 +76,14 @@ namespace Ryujinx.Ava.Utilities.AppLibrary } else { - var pfsTemp = new PartitionFileSystem(); + PartitionFileSystem pfsTemp = new PartitionFileSystem(); pfsTemp.Initialize(file.AsStorage()).ThrowIfFailure(); pfs = pfsTemp; } foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca")) { - using var ncaFile = new UniqueRef(); + using UniqueRef ncaFile = new UniqueRef(); pfs.OpenFile(ref ncaFile.Ref, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); @@ -158,7 +158,7 @@ namespace Ryujinx.Ava.Utilities.AppLibrary return string.Empty; } - using var nsoFile = new UniqueRef(); + using UniqueRef nsoFile = new UniqueRef(); codeFs.OpenFile(ref nsoFile.Ref, $"/{MainExeFs}".ToU8Span(), OpenMode.Read).ThrowIfFailure(); diff --git a/src/Ryujinx/Utilities/AppLibrary/ApplicationLibrary.cs b/src/Ryujinx/Utilities/AppLibrary/ApplicationLibrary.cs index d5a4ac83c..7a66fe44d 100644 --- a/src/Ryujinx/Utilities/AppLibrary/ApplicationLibrary.cs +++ b/src/Ryujinx/Utilities/AppLibrary/ApplicationLibrary.cs @@ -190,7 +190,7 @@ namespace Ryujinx.Ava.Utilities.AppLibrary /// An error occured while reading PFS data. private List GetApplicationsFromPfs(IFileSystem pfs, string filePath) { - var applications = new List(); + List applications = new List(); string extension = Path.GetExtension(filePath).ToLower(); foreach ((ulong titleId, ContentMetaData content) in pfs.GetContentData(ContentMetaType.Application, _virtualFileSystem, _checkLevel)) @@ -245,7 +245,7 @@ namespace Ryujinx.Ava.Utilities.AppLibrary continue; } - using var icon = new UniqueRef(); + using UniqueRef icon = new UniqueRef(); controlFs.OpenFile(ref icon.Ref, entry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); @@ -313,7 +313,7 @@ namespace Ryujinx.Ava.Utilities.AppLibrary case ".nsp": case ".pfs0": { - var pfs = new PartitionFileSystem(); + PartitionFileSystem pfs = new PartitionFileSystem(); pfs.Initialize(file.AsStorage()).ThrowIfFailure(); ApplicationData result = GetApplicationFromNsp(pfs, applicationPath); @@ -438,7 +438,7 @@ namespace Ryujinx.Ava.Utilities.AppLibrary return false; } - foreach (var data in applications) + foreach (ApplicationData data in applications) { // Only load metadata for applications with an ID if (data.Id != 0) @@ -501,7 +501,7 @@ namespace Ryujinx.Ava.Utilities.AppLibrary foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca")) { - using var ncaFile = new UniqueRef(); + using UniqueRef ncaFile = new UniqueRef(); pfs.OpenFile(ref ncaFile.Ref, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); @@ -588,8 +588,8 @@ namespace Ryujinx.Ava.Utilities.AppLibrary nacpFile.Get.Read(out _, 0, LibHac.Common.SpanHelpers.AsByteSpan(ref controlData), ReadOption.None).ThrowIfFailure(); - var displayVersion = controlData.DisplayVersionString.ToString(); - var update = new TitleUpdateModel(content.ApplicationId, content.Version.Version, + string displayVersion = controlData.DisplayVersionString.ToString(); + TitleUpdateModel update = new TitleUpdateModel(content.ApplicationId, content.Version.Version, displayVersion, filePath); titleUpdates.Add(update); @@ -685,11 +685,11 @@ namespace Ryujinx.Ava.Utilities.AppLibrary return; } - var fileInfo = new FileInfo(app); + FileInfo fileInfo = new FileInfo(app); try { - var fullPath = fileInfo.ResolveLinkTarget(true)?.FullName ?? fileInfo.FullName; + string fullPath = fileInfo.ResolveLinkTarget(true)?.FullName ?? fileInfo.FullName; applicationPaths.Add(fullPath); numApplicationsFound++; @@ -719,7 +719,7 @@ namespace Ryujinx.Ava.Utilities.AppLibrary { _applications.Edit(it => { - foreach (var application in applications) + foreach (ApplicationData application in applications) { it.AddOrUpdate(application); LoadDlcForApplication(application); @@ -840,7 +840,7 @@ namespace Ryujinx.Ava.Utilities.AppLibrary try { // Remove any downloadable content which can no longer be located on disk - var dlcToRemove = _downloadableContents.Items + List<(DownloadableContentModel Dlc, bool IsEnabled)> dlcToRemove = _downloadableContents.Items .Where(dlc => !File.Exists(dlc.Dlc.ContainerPath)) .ToList(); dlcToRemove.ForEach(dlc => @@ -882,11 +882,11 @@ namespace Ryujinx.Ava.Utilities.AppLibrary return newDlcLoaded; } - var fileInfo = new FileInfo(app); + FileInfo fileInfo = new FileInfo(app); try { - var fullPath = fileInfo.ResolveLinkTarget(true)?.FullName ?? fileInfo.FullName; + string fullPath = fileInfo.ResolveLinkTarget(true)?.FullName ?? fileInfo.FullName; dlcPaths.Add(fullPath); } @@ -904,7 +904,7 @@ namespace Ryujinx.Ava.Utilities.AppLibrary } } - var appIdLookup = Applications.Items.Select(it => it.IdBase).ToHashSet(); + HashSet appIdLookup = Applications.Items.Select(it => it.IdBase).ToHashSet(); foreach (string dlcPath in dlcPaths) { @@ -913,9 +913,9 @@ namespace Ryujinx.Ava.Utilities.AppLibrary return newDlcLoaded; } - if (TryGetDownloadableContentFromFile(dlcPath, out var foundDlcs)) + if (TryGetDownloadableContentFromFile(dlcPath, out List foundDlcs)) { - foreach (var dlc in foundDlcs.Where(it => appIdLookup.Contains(it.TitleIdBase))) + foreach (DownloadableContentModel dlc in foundDlcs.Where(it => appIdLookup.Contains(it.TitleIdBase))) { if (!_downloadableContents.Lookup(dlc).HasValue) { @@ -949,11 +949,11 @@ namespace Ryujinx.Ava.Utilities.AppLibrary try { - var titleIdsToSave = new HashSet(); - var titleIdsToRefresh = new HashSet(); + HashSet titleIdsToSave = new HashSet(); + HashSet titleIdsToRefresh = new HashSet(); // Remove any updates which can no longer be located on disk - var updatesToRemove = _titleUpdates.Items + List<(TitleUpdateModel TitleUpdate, bool IsSelected)> updatesToRemove = _titleUpdates.Items .Where(it => !File.Exists(it.TitleUpdate.Path)) .ToList(); @@ -998,11 +998,11 @@ namespace Ryujinx.Ava.Utilities.AppLibrary return numUpdatesLoaded; } - var fileInfo = new FileInfo(app); + FileInfo fileInfo = new FileInfo(app); try { - var fullPath = fileInfo.ResolveLinkTarget(true)?.FullName ?? fileInfo.FullName; + string fullPath = fileInfo.ResolveLinkTarget(true)?.FullName ?? fileInfo.FullName; updatePaths.Add(fullPath); } @@ -1020,7 +1020,7 @@ namespace Ryujinx.Ava.Utilities.AppLibrary } } - var appIdLookup = Applications.Items.Select(it => it.IdBase).ToHashSet(); + HashSet appIdLookup = Applications.Items.Select(it => it.IdBase).ToHashSet(); foreach (string updatePath in updatePaths) { @@ -1029,9 +1029,9 @@ namespace Ryujinx.Ava.Utilities.AppLibrary return numUpdatesLoaded; } - if (TryGetTitleUpdatesFromFile(updatePath, out var foundUpdates)) + if (TryGetTitleUpdatesFromFile(updatePath, out List foundUpdates)) { - foreach (var update in foundUpdates.Where(it => appIdLookup.Contains(it.TitleIdBase))) + foreach (TitleUpdateModel update in foundUpdates.Where(it => appIdLookup.Contains(it.TitleIdBase))) { if (!_titleUpdates.Lookup(update).HasValue) { @@ -1063,12 +1063,12 @@ namespace Ryujinx.Ava.Utilities.AppLibrary private bool AddAndAutoSelectUpdate(TitleUpdateModel update) { if (update == null) return false; - - var currentlySelected = TitleUpdates.Items.FirstOrOptional(it => + + DynamicData.Kernel.Optional<(TitleUpdateModel TitleUpdate, bool IsSelected)> currentlySelected = TitleUpdates.Items.FirstOrOptional(it => it.TitleUpdate.TitleIdBase == update.TitleIdBase && it.IsSelected); - var shouldSelect = !currentlySelected.HasValue || - currentlySelected.Value.TitleUpdate.Version < update.Version; + bool shouldSelect = !currentlySelected.HasValue || + currentlySelected.Value.TitleUpdate.Version < update.Version; _titleUpdates.AddOrUpdate((update, shouldSelect)); @@ -1170,7 +1170,7 @@ namespace Ryujinx.Ava.Utilities.AppLibrary } else { - var pfsTemp = new PartitionFileSystem(); + PartitionFileSystem pfsTemp = new PartitionFileSystem(); pfsTemp.Initialize(file.AsStorage()).ThrowIfFailure(); pfs = pfsTemp; @@ -1204,7 +1204,7 @@ namespace Ryujinx.Ava.Utilities.AppLibrary // Read the icon from the ControlFS and store it as a byte array try { - using var icon = new UniqueRef(); + using UniqueRef icon = new UniqueRef(); controlFs.OpenFile(ref icon.Ref, $"/icon_{desiredTitleLanguage}.dat".ToU8Span(), OpenMode.Read).ThrowIfFailure(); @@ -1222,7 +1222,7 @@ namespace Ryujinx.Ava.Utilities.AppLibrary continue; } - using var icon = new UniqueRef(); + using UniqueRef icon = new UniqueRef(); controlFs.OpenFile(ref icon.Ref, entry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); @@ -1330,7 +1330,7 @@ namespace Ryujinx.Ava.Utilities.AppLibrary if (string.IsNullOrWhiteSpace(data.Name)) { - foreach (ref readonly var controlTitle in controlData.Title.ItemsRo) + foreach (ref readonly ApplicationControlProperty.ApplicationTitle controlTitle in controlData.Title.ItemsRo) { if (!controlTitle.NameString.IsEmpty()) { @@ -1343,7 +1343,7 @@ namespace Ryujinx.Ava.Utilities.AppLibrary if (string.IsNullOrWhiteSpace(data.Developer)) { - foreach (ref readonly var controlTitle in controlData.Title.ItemsRo) + foreach (ref readonly ApplicationControlProperty.ApplicationTitle controlTitle in controlData.Title.ItemsRo) { if (!controlTitle.PublisherString.IsEmpty()) { @@ -1419,16 +1419,16 @@ namespace Ryujinx.Ava.Utilities.AppLibrary { _downloadableContents.Edit(it => { - var savedDlc = + List<(DownloadableContentModel, bool IsEnabled)> savedDlc = DownloadableContentsHelper.LoadDownloadableContentsJson(_virtualFileSystem, application.IdBase); it.AddOrUpdate(savedDlc); - if (TryGetDownloadableContentFromFile(application.Path, out var bundledDlc)) + if (TryGetDownloadableContentFromFile(application.Path, out List bundledDlc)) { - var savedDlcLookup = savedDlc.Select(dlc => dlc.Item1).ToHashSet(); + HashSet savedDlcLookup = savedDlc.Select(dlc => dlc.Item1).ToHashSet(); bool addedNewDlc = false; - foreach (var dlc in bundledDlc) + foreach (DownloadableContentModel dlc in bundledDlc) { if (!savedDlcLookup.Contains(dlc)) { @@ -1439,7 +1439,7 @@ namespace Ryujinx.Ava.Utilities.AppLibrary if (addedNewDlc) { - var gameDlcs = it.Items.Where(dlc => dlc.Dlc.TitleIdBase == application.IdBase).ToList(); + List<(DownloadableContentModel Dlc, bool IsEnabled)> gameDlcs = it.Items.Where(dlc => dlc.Dlc.TitleIdBase == application.IdBase).ToList(); DownloadableContentsHelper.SaveDownloadableContentsJson(application.IdBase, gameDlcs); } @@ -1451,22 +1451,22 @@ namespace Ryujinx.Ava.Utilities.AppLibrary // file itself private bool LoadTitleUpdatesForApplication(ApplicationData application) { - var modifiedVersion = false; + bool modifiedVersion = false; _titleUpdates.Edit(it => { - var savedUpdates = + List<(TitleUpdateModel Update, bool IsSelected)> savedUpdates = TitleUpdatesHelper.LoadTitleUpdatesJson(_virtualFileSystem, application.IdBase); it.AddOrUpdate(savedUpdates); - var selectedUpdate = savedUpdates.FirstOrOptional(update => update.IsSelected); + DynamicData.Kernel.Optional<(TitleUpdateModel Update, bool IsSelected)> selectedUpdate = savedUpdates.FirstOrOptional(update => update.IsSelected); - if (TryGetTitleUpdatesFromFile(application.Path, out var bundledUpdates)) + if (TryGetTitleUpdatesFromFile(application.Path, out List bundledUpdates)) { - var savedUpdateLookup = savedUpdates.Select(update => update.Update).ToHashSet(); + HashSet savedUpdateLookup = savedUpdates.Select(update => update.Update).ToHashSet(); bool updatesChanged = false; - foreach (var update in bundledUpdates.OrderByDescending(bundled => bundled.Version)) + foreach (TitleUpdateModel update in bundledUpdates.OrderByDescending(bundled => bundled.Version)) { if (!savedUpdateLookup.Contains(update)) { @@ -1488,7 +1488,7 @@ namespace Ryujinx.Ava.Utilities.AppLibrary if (updatesChanged) { - var gameUpdates = it.Items.Where(update => update.TitleUpdate.TitleIdBase == application.IdBase).ToList(); + List<(TitleUpdateModel TitleUpdate, bool IsSelected)> gameUpdates = it.Items.Where(update => update.TitleUpdate.TitleIdBase == application.IdBase).ToList(); TitleUpdatesHelper.SaveTitleUpdatesJson(application.IdBase, gameUpdates); } } @@ -1500,14 +1500,14 @@ namespace Ryujinx.Ava.Utilities.AppLibrary // Save the _currently tracked_ DLC state for the game private void SaveDownloadableContentsForGame(ulong titleIdBase) { - var dlcs = DownloadableContents.Items.Where(dlc => dlc.Dlc.TitleIdBase == titleIdBase).ToList(); + List<(DownloadableContentModel Dlc, bool IsEnabled)> dlcs = DownloadableContents.Items.Where(dlc => dlc.Dlc.TitleIdBase == titleIdBase).ToList(); DownloadableContentsHelper.SaveDownloadableContentsJson(titleIdBase, dlcs); } // Save the _currently tracked_ update state for the game private void SaveTitleUpdatesForGame(ulong titleIdBase) { - var updates = TitleUpdates.Items.Where(update => update.TitleUpdate.TitleIdBase == titleIdBase).ToList(); + List<(TitleUpdateModel TitleUpdate, bool IsSelected)> updates = TitleUpdates.Items.Where(update => update.TitleUpdate.TitleIdBase == titleIdBase).ToList(); TitleUpdatesHelper.SaveTitleUpdatesJson(titleIdBase, updates); } @@ -1515,7 +1515,7 @@ namespace Ryujinx.Ava.Utilities.AppLibrary // of its state private void RefreshApplicationInfo(ulong appIdBase) { - var application = _applications.Lookup(appIdBase); + DynamicData.Kernel.Optional application = _applications.Lookup(appIdBase); if (!application.HasValue) return; @@ -1523,7 +1523,7 @@ namespace Ryujinx.Ava.Utilities.AppLibrary if (!TryGetApplicationsFromFile(application.Value.Path, out List newApplications)) return; - var newApplication = newApplications.First(it => it.IdBase == appIdBase); + ApplicationData newApplication = newApplications.First(it => it.IdBase == appIdBase); _applications.AddOrUpdate(newApplication); } } diff --git a/src/Ryujinx/Utilities/Compat/CompatibilityCsv.cs b/src/Ryujinx/Utilities/Compat/CompatibilityCsv.cs index 7c8e6909c..af80c5a28 100644 --- a/src/Ryujinx/Utilities/Compat/CompatibilityCsv.cs +++ b/src/Ryujinx/Utilities/Compat/CompatibilityCsv.cs @@ -88,7 +88,7 @@ namespace Ryujinx.Ava.Utilities.Compat _ => null }; - if (DateTime.TryParse(ColStr(row[indices.LastUpdated]), out var dt)) + if (DateTime.TryParse(ColStr(row[indices.LastUpdated]), out DateTime dt)) LastUpdated = dt; return; diff --git a/src/Ryujinx/Utilities/Configuration/ConfigurationState.Model.cs b/src/Ryujinx/Utilities/Configuration/ConfigurationState.Model.cs index 0d08536d7..2d77c139d 100644 --- a/src/Ryujinx/Utilities/Configuration/ConfigurationState.Model.cs +++ b/src/Ryujinx/Utilities/Configuration/ConfigurationState.Model.cs @@ -661,7 +661,7 @@ namespace Ryujinx.Ava.Utilities.Configuration if (!ShowDirtyHacks) return; - var newHacks = EnabledHacks.Select(x => x.Hack) + string newHacks = EnabledHacks.Select(x => x.Hack) .JoinToString(", "); if (newHacks != _lastHackCollection) diff --git a/src/Ryujinx/Utilities/Configuration/LoggerModule.cs b/src/Ryujinx/Utilities/Configuration/LoggerModule.cs index 663ad607f..f6c1be082 100644 --- a/src/Ryujinx/Utilities/Configuration/LoggerModule.cs +++ b/src/Ryujinx/Utilities/Configuration/LoggerModule.cs @@ -31,12 +31,12 @@ namespace Ryujinx.Ava.Utilities.Configuration { bool noFilter = e.NewValue.Length == 0; - foreach (var logClass in Enum.GetValues()) + foreach (LogClass logClass in Enum.GetValues()) { Logger.SetEnable(logClass, noFilter); } - foreach (var logClass in e.NewValue) + foreach (LogClass logClass in e.NewValue) { Logger.SetEnable(logClass, true); } diff --git a/src/Ryujinx/Utilities/DownloadableContentsHelper.cs b/src/Ryujinx/Utilities/DownloadableContentsHelper.cs index b6d2420a3..b8af11527 100644 --- a/src/Ryujinx/Utilities/DownloadableContentsHelper.cs +++ b/src/Ryujinx/Utilities/DownloadableContentsHelper.cs @@ -22,7 +22,7 @@ namespace Ryujinx.Ava.Utilities public static List<(DownloadableContentModel, bool IsEnabled)> LoadDownloadableContentsJson(VirtualFileSystem vfs, ulong applicationIdBase) { - var downloadableContentJsonPath = PathToGameDLCJson(applicationIdBase); + string downloadableContentJsonPath = PathToGameDLCJson(applicationIdBase); if (!File.Exists(downloadableContentJsonPath)) { @@ -31,7 +31,7 @@ namespace Ryujinx.Ava.Utilities try { - var downloadableContentContainerList = JsonHelper.DeserializeFromFile(downloadableContentJsonPath, + List downloadableContentContainerList = JsonHelper.DeserializeFromFile(downloadableContentJsonPath, _serializerContext.ListDownloadableContentContainer); return LoadDownloadableContents(vfs, downloadableContentContainerList); } @@ -76,13 +76,13 @@ namespace Ryujinx.Ava.Utilities downloadableContentContainerList.Add(container); } - var downloadableContentJsonPath = PathToGameDLCJson(applicationIdBase); + string downloadableContentJsonPath = PathToGameDLCJson(applicationIdBase); JsonHelper.SerializeToFile(downloadableContentJsonPath, downloadableContentContainerList, _serializerContext.ListDownloadableContentContainer); } private static List<(DownloadableContentModel, bool IsEnabled)> LoadDownloadableContents(VirtualFileSystem vfs, List downloadableContentContainers) { - var result = new List<(DownloadableContentModel, bool IsEnabled)>(); + List<(DownloadableContentModel, bool IsEnabled)> result = new List<(DownloadableContentModel, bool IsEnabled)>(); foreach (DownloadableContentContainer downloadableContentContainer in downloadableContentContainers) { @@ -105,7 +105,7 @@ namespace Ryujinx.Ava.Utilities continue; } - var content = new DownloadableContentModel(nca.Header.TitleId, + DownloadableContentModel content = new DownloadableContentModel(nca.Header.TitleId, downloadableContentContainer.ContainerPath, downloadableContentNca.FullPath); diff --git a/src/Ryujinx/Utilities/ShortcutHelper.cs b/src/Ryujinx/Utilities/ShortcutHelper.cs index fed6a5c46..5a5f92773 100644 --- a/src/Ryujinx/Utilities/ShortcutHelper.cs +++ b/src/Ryujinx/Utilities/ShortcutHelper.cs @@ -18,11 +18,11 @@ namespace Ryujinx.Ava.Utilities iconPath += ".ico"; MemoryStream iconDataStream = new(iconData); - using var image = SKBitmap.Decode(iconDataStream); + using SKBitmap image = SKBitmap.Decode(iconDataStream); image.Resize(new SKImageInfo(128, 128), SKFilterQuality.High); SaveBitmapAsIcon(image, iconPath); - var shortcut = Shortcut.CreateShortcut(basePath, GetArgsString(applicationFilePath, applicationId), iconPath, 0); + Shortcut shortcut = Shortcut.CreateShortcut(basePath, GetArgsString(applicationFilePath, applicationId), iconPath, 0); shortcut.StringData.NameString = cleanedAppName; shortcut.WriteToFile(Path.Combine(desktopPath, cleanedAppName + ".lnk")); } @@ -31,12 +31,12 @@ namespace Ryujinx.Ava.Utilities private static void CreateShortcutLinux(string applicationFilePath, string applicationId, byte[] iconData, string iconPath, string desktopPath, string cleanedAppName) { string basePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Ryujinx.sh"); - var desktopFile = EmbeddedResources.ReadAllText("Ryujinx/Assets/ShortcutFiles/shortcut-template.desktop"); + string desktopFile = EmbeddedResources.ReadAllText("Ryujinx/Assets/ShortcutFiles/shortcut-template.desktop"); iconPath += ".png"; - var image = SKBitmap.Decode(iconData); - using var data = image.Encode(SKEncodedImageFormat.Png, 100); - using var file = File.OpenWrite(iconPath); + SKBitmap image = SKBitmap.Decode(iconData); + using SKData data = image.Encode(SKEncodedImageFormat.Png, 100); + using FileStream file = File.OpenWrite(iconPath); data.SaveTo(file); using StreamWriter outputFile = new(Path.Combine(desktopPath, cleanedAppName + ".desktop")); @@ -47,8 +47,8 @@ namespace Ryujinx.Ava.Utilities private static void CreateShortcutMacos(string appFilePath, string applicationId, byte[] iconData, string desktopPath, string cleanedAppName) { string basePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Ryujinx"); - var plistFile = EmbeddedResources.ReadAllText("Ryujinx/Assets/ShortcutFiles/shortcut-template.plist"); - var shortcutScript = EmbeddedResources.ReadAllText("Ryujinx/Assets/ShortcutFiles/shortcut-launch-script.sh"); + string plistFile = EmbeddedResources.ReadAllText("Ryujinx/Assets/ShortcutFiles/shortcut-template.plist"); + string shortcutScript = EmbeddedResources.ReadAllText("Ryujinx/Assets/ShortcutFiles/shortcut-launch-script.sh"); // Macos .App folder string contentFolderPath = Path.Combine("/Applications", cleanedAppName + ".app", "Contents"); string scriptFolderPath = Path.Combine(contentFolderPath, "MacOS"); @@ -77,9 +77,9 @@ namespace Ryujinx.Ava.Utilities } const string IconName = "icon.png"; - var image = SKBitmap.Decode(iconData); - using var data = image.Encode(SKEncodedImageFormat.Png, 100); - using var file = File.OpenWrite(Path.Combine(resourceFolderPath, IconName)); + SKBitmap image = SKBitmap.Decode(iconData); + using SKData data = image.Encode(SKEncodedImageFormat.Png, 100); + using FileStream file = File.OpenWrite(Path.Combine(resourceFolderPath, IconName)); data.SaveTo(file); // plist file @@ -124,7 +124,7 @@ namespace Ryujinx.Ava.Utilities private static string GetArgsString(string appFilePath, string applicationId) { // args are first defined as a list, for easier adjustments in the future - var argsList = new List(); + List argsList = new List(); if (!string.IsNullOrEmpty(CommandLineState.BaseDirPathArg)) { @@ -157,7 +157,7 @@ namespace Ryujinx.Ava.Utilities fs.Write(header); // Writing actual data - using var data = source.Encode(SKEncodedImageFormat.Png, 100); + using SKData data = source.Encode(SKEncodedImageFormat.Png, 100); data.SaveTo(fs); // Getting data length (file length minus header) long dataLength = fs.Length - header.Length; diff --git a/src/Ryujinx/Utilities/SystemInfo/LinuxSystemInfo.cs b/src/Ryujinx/Utilities/SystemInfo/LinuxSystemInfo.cs index 6ca38aa36..fa2f8bf71 100644 --- a/src/Ryujinx/Utilities/SystemInfo/LinuxSystemInfo.cs +++ b/src/Ryujinx/Utilities/SystemInfo/LinuxSystemInfo.cs @@ -16,7 +16,7 @@ namespace Ryujinx.Ava.Utilities.SystemInfo if (cpuName == null) { - var cpuDict = new Dictionary(StringComparer.Ordinal) + Dictionary cpuDict = new Dictionary(StringComparer.Ordinal) { ["model name"] = null, ["Processor"] = null, @@ -28,7 +28,7 @@ namespace Ryujinx.Ava.Utilities.SystemInfo cpuName = cpuDict["model name"] ?? cpuDict["Processor"] ?? cpuDict["Hardware"] ?? "Unknown"; } - var memDict = new Dictionary(StringComparer.Ordinal) + Dictionary memDict = new Dictionary(StringComparer.Ordinal) { ["MemTotal"] = null, ["MemAvailable"] = null, diff --git a/src/Ryujinx/Utilities/SystemInfo/MacOSSystemInfo.cs b/src/Ryujinx/Utilities/SystemInfo/MacOSSystemInfo.cs index 6b0beacf8..ab8102711 100644 --- a/src/Ryujinx/Utilities/SystemInfo/MacOSSystemInfo.cs +++ b/src/Ryujinx/Utilities/SystemInfo/MacOSSystemInfo.cs @@ -40,10 +40,10 @@ namespace Ryujinx.Ava.Utilities.SystemInfo static ulong GetVMInfoAvailableMemory() { - var port = mach_host_self(); + uint port = mach_host_self(); uint pageSize = 0; - var result = host_page_size(port, ref pageSize); + int result = host_page_size(port, ref pageSize); if (result != 0) { diff --git a/src/Ryujinx/Utilities/SystemInfo/WindowsSystemInfo.cs b/src/Ryujinx/Utilities/SystemInfo/WindowsSystemInfo.cs index 73845be11..c6e8894e2 100644 --- a/src/Ryujinx/Utilities/SystemInfo/WindowsSystemInfo.cs +++ b/src/Ryujinx/Utilities/SystemInfo/WindowsSystemInfo.cs @@ -34,7 +34,7 @@ namespace Ryujinx.Ava.Utilities.SystemInfo if (cpuObjs != null) { - foreach (var cpuObj in cpuObjs) + foreach (ManagementBaseObject cpuObj in cpuObjs) { return cpuObj["Name"].ToString().Trim(); } diff --git a/src/Ryujinx/Utilities/TitleUpdatesHelper.cs b/src/Ryujinx/Utilities/TitleUpdatesHelper.cs index 9fc9bbf6b..805d6a46a 100644 --- a/src/Ryujinx/Utilities/TitleUpdatesHelper.cs +++ b/src/Ryujinx/Utilities/TitleUpdatesHelper.cs @@ -30,7 +30,7 @@ namespace Ryujinx.Ava.Utilities public static List<(TitleUpdateModel Update, bool IsSelected)> LoadTitleUpdatesJson(VirtualFileSystem vfs, ulong applicationIdBase) { - var titleUpdatesJsonPath = PathToGameUpdatesJson(applicationIdBase); + string titleUpdatesJsonPath = PathToGameUpdatesJson(applicationIdBase); if (!File.Exists(titleUpdatesJsonPath)) { @@ -39,7 +39,7 @@ namespace Ryujinx.Ava.Utilities try { - var titleUpdateWindowData = JsonHelper.DeserializeFromFile(titleUpdatesJsonPath, _serializerContext.TitleUpdateMetadata); + TitleUpdateMetadata titleUpdateWindowData = JsonHelper.DeserializeFromFile(titleUpdatesJsonPath, _serializerContext.TitleUpdateMetadata); return LoadTitleUpdates(vfs, titleUpdateWindowData, applicationIdBase); } catch @@ -51,7 +51,7 @@ namespace Ryujinx.Ava.Utilities public static void SaveTitleUpdatesJson(ulong applicationIdBase, List<(TitleUpdateModel, bool IsSelected)> updates) { - var titleUpdateWindowData = new TitleUpdateMetadata + TitleUpdateMetadata titleUpdateWindowData = new TitleUpdateMetadata { Selected = string.Empty, Paths = [], @@ -73,13 +73,13 @@ namespace Ryujinx.Ava.Utilities } } - var titleUpdatesJsonPath = PathToGameUpdatesJson(applicationIdBase); + string titleUpdatesJsonPath = PathToGameUpdatesJson(applicationIdBase); JsonHelper.SerializeToFile(titleUpdatesJsonPath, titleUpdateWindowData, _serializerContext.TitleUpdateMetadata); } private static List<(TitleUpdateModel Update, bool IsSelected)> LoadTitleUpdates(VirtualFileSystem vfs, TitleUpdateMetadata titleUpdateMetadata, ulong applicationIdBase) { - var result = new List<(TitleUpdateModel, bool IsSelected)>(); + List<(TitleUpdateModel, bool IsSelected)> result = new List<(TitleUpdateModel, bool IsSelected)>(); IntegrityCheckLevel checkLevel = ConfigurationState.Instance.System.EnableFsIntegrityChecks ? IntegrityCheckLevel.ErrorOnInvalid @@ -115,8 +115,8 @@ namespace Ryujinx.Ava.Utilities nacpFile.Get.Read(out _, 0, SpanHelpers.AsByteSpan(ref controlData), ReadOption.None) .ThrowIfFailure(); - var displayVersion = controlData.DisplayVersionString.ToString(); - var update = new TitleUpdateModel(content.ApplicationId, content.Version.Version, + string displayVersion = controlData.DisplayVersionString.ToString(); + TitleUpdateModel update = new TitleUpdateModel(content.ApplicationId, content.Version.Version, displayVersion, path); result.Add((update, path == titleUpdateMetadata.Selected)); diff --git a/src/Ryujinx/Utilities/ValueFormatUtils.cs b/src/Ryujinx/Utilities/ValueFormatUtils.cs index f5cdb4125..e0a8b0457 100644 --- a/src/Ryujinx/Utilities/ValueFormatUtils.cs +++ b/src/Ryujinx/Utilities/ValueFormatUtils.cs @@ -139,10 +139,10 @@ namespace Ryujinx.Ava.Utilities // An input string can either look like "01:23:45" or "1d, 01:23:45" if the timespan represents a duration of more than a day. // Here, we split the input string to check if it's the former or the latter. - var valueSplit = timeSpanString.Split(", "); + string[] valueSplit = timeSpanString.Split(", "); if (valueSplit.Length > 1) { - var dayPart = valueSplit[0].Split("d")[0]; + string dayPart = valueSplit[0].Split("d")[0]; if (int.TryParse(dayPart, out int days)) { returnTimeSpan = returnTimeSpan.Add(TimeSpan.FromDays(days)); From e0567c5ce95fe228c3099b286955d71fefa656ee Mon Sep 17 00:00:00 2001 From: Evan Husted Date: Sat, 25 Jan 2025 14:01:13 -0600 Subject: [PATCH 02/19] misc: chore: Use explicit types in ARMeilleure project --- .../CodeGen/Arm64/Arm64Optimizer.cs | 4 +- src/ARMeilleure/CodeGen/Arm64/Assembler.cs | 2 +- .../CodeGen/Arm64/CodeGenContext.cs | 4 +- .../CodeGen/Arm64/CodeGenerator.cs | 4 +- src/ARMeilleure/CodeGen/Arm64/PreAllocator.cs | 2 +- .../RegisterAllocators/LinearScanAllocator.cs | 2 +- .../RegisterAllocators/LiveIntervalList.cs | 4 +- .../CodeGen/RegisterAllocators/UseList.cs | 4 +- src/ARMeilleure/CodeGen/X86/Assembler.cs | 15 ++++---- src/ARMeilleure/CodeGen/X86/CodeGenerator.cs | 4 +- .../CodeGen/X86/HardwareCapabilities.cs | 2 +- src/ARMeilleure/CodeGen/X86/PreAllocator.cs | 2 +- src/ARMeilleure/CodeGen/X86/X86Optimizer.cs | 4 +- src/ARMeilleure/Common/BitMap.cs | 6 +-- src/ARMeilleure/Common/EntryTable.cs | 8 ++-- .../Decoders/OpCode32SimdDupElem.cs | 2 +- .../Decoders/OpCode32SimdMovGpElem.cs | 2 +- src/ARMeilleure/Decoders/OpCodeAluImm.cs | 2 +- src/ARMeilleure/Decoders/OpCodeBfm.cs | 2 +- .../Decoders/Optimizations/TailCallRemover.cs | 2 +- src/ARMeilleure/Diagnostics/IRDumper.cs | 4 +- src/ARMeilleure/Instructions/InstEmitAlu32.cs | 4 +- .../Instructions/InstEmitFlowHelper.cs | 5 ++- .../Instructions/InstEmitMemoryEx32.cs | 4 +- .../Instructions/InstEmitSimdCmp32.cs | 2 +- .../Instructions/InstEmitSimdCvt32.cs | 8 ++-- .../Instructions/InstEmitSimdMemory32.cs | 2 +- src/ARMeilleure/Instructions/SoftFloat.cs | 4 +- .../IntermediateRepresentation/Operand.cs | 8 ++-- src/ARMeilleure/Signal/TestMethods.cs | 4 +- .../Translation/Cache/JitUnwindWindows.cs | 4 +- .../Translation/ControlFlowGraph.cs | 8 ++-- src/ARMeilleure/Translation/PTC/Ptc.cs | 19 +++++----- .../Translation/PTC/PtcProfiler.cs | 4 +- .../Translation/SsaConstruction.cs | 6 +-- src/ARMeilleure/Translation/Translator.cs | 14 +++---- .../Translation/TranslatorStubs.cs | 38 +++++++++---------- 37 files changed, 109 insertions(+), 106 deletions(-) diff --git a/src/ARMeilleure/CodeGen/Arm64/Arm64Optimizer.cs b/src/ARMeilleure/CodeGen/Arm64/Arm64Optimizer.cs index 00ffd1958..979b471ac 100644 --- a/src/ARMeilleure/CodeGen/Arm64/Arm64Optimizer.cs +++ b/src/ARMeilleure/CodeGen/Arm64/Arm64Optimizer.cs @@ -13,13 +13,13 @@ namespace ARMeilleure.CodeGen.Arm64 public static void RunPass(ControlFlowGraph cfg) { - var constants = new Dictionary(); + Dictionary constants = new Dictionary(); Operand GetConstantCopy(BasicBlock block, Operation operation, Operand source) { // If the constant has many uses, we also force a new constant mov to be added, in order // to avoid overflow of the counts field (that is limited to 16 bits). - if (!constants.TryGetValue(source.Value, out var constant) || constant.UsesCount > MaxConstantUses) + if (!constants.TryGetValue(source.Value, out Operand constant) || constant.UsesCount > MaxConstantUses) { constant = Local(source.Type); diff --git a/src/ARMeilleure/CodeGen/Arm64/Assembler.cs b/src/ARMeilleure/CodeGen/Arm64/Assembler.cs index 41684faf2..47902ddc8 100644 --- a/src/ARMeilleure/CodeGen/Arm64/Assembler.cs +++ b/src/ARMeilleure/CodeGen/Arm64/Assembler.cs @@ -123,7 +123,7 @@ namespace ARMeilleure.CodeGen.Arm64 public void Cset(Operand rd, ArmCondition condition) { - var zr = Factory.Register(ZrRegister, RegisterType.Integer, rd.Type); + Operand zr = Factory.Register(ZrRegister, RegisterType.Integer, rd.Type); Csinc(rd, zr, zr, (ArmCondition)((int)condition ^ 1)); } diff --git a/src/ARMeilleure/CodeGen/Arm64/CodeGenContext.cs b/src/ARMeilleure/CodeGen/Arm64/CodeGenContext.cs index 89b1e9e6b..ed271d24e 100644 --- a/src/ARMeilleure/CodeGen/Arm64/CodeGenContext.cs +++ b/src/ARMeilleure/CodeGen/Arm64/CodeGenContext.cs @@ -91,7 +91,7 @@ namespace ARMeilleure.CodeGen.Arm64 long target = _stream.Position; - if (_pendingBranches.TryGetValue(block, out var list)) + if (_pendingBranches.TryGetValue(block, out List<(ArmCondition Condition, long BranchPos)> list)) { foreach ((ArmCondition condition, long branchPos) in list) { @@ -119,7 +119,7 @@ namespace ARMeilleure.CodeGen.Arm64 } else { - if (!_pendingBranches.TryGetValue(target, out var list)) + if (!_pendingBranches.TryGetValue(target, out List<(ArmCondition Condition, long BranchPos)> list)) { list = new List<(ArmCondition, long)>(); _pendingBranches.Add(target, list); diff --git a/src/ARMeilleure/CodeGen/Arm64/CodeGenerator.cs b/src/ARMeilleure/CodeGen/Arm64/CodeGenerator.cs index 2df86671a..6c422a5bb 100644 --- a/src/ARMeilleure/CodeGen/Arm64/CodeGenerator.cs +++ b/src/ARMeilleure/CodeGen/Arm64/CodeGenerator.cs @@ -322,7 +322,7 @@ namespace ARMeilleure.CodeGen.Arm64 Debug.Assert(comp.Kind == OperandKind.Constant); - var cond = ((Comparison)comp.AsInt32()).ToArmCondition(); + ArmCondition cond = ((Comparison)comp.AsInt32()).ToArmCondition(); GenerateCompareCommon(context, operation); @@ -354,7 +354,7 @@ namespace ARMeilleure.CodeGen.Arm64 Debug.Assert(dest.Type == OperandType.I32); Debug.Assert(comp.Kind == OperandKind.Constant); - var cond = ((Comparison)comp.AsInt32()).ToArmCondition(); + ArmCondition cond = ((Comparison)comp.AsInt32()).ToArmCondition(); GenerateCompareCommon(context, operation); diff --git a/src/ARMeilleure/CodeGen/Arm64/PreAllocator.cs b/src/ARMeilleure/CodeGen/Arm64/PreAllocator.cs index f66bb66e6..e8193a9ab 100644 --- a/src/ARMeilleure/CodeGen/Arm64/PreAllocator.cs +++ b/src/ARMeilleure/CodeGen/Arm64/PreAllocator.cs @@ -847,7 +847,7 @@ namespace ARMeilleure.CodeGen.Arm64 Debug.Assert(comp.Kind == OperandKind.Constant); - var compType = (Comparison)comp.AsInt32(); + Comparison compType = (Comparison)comp.AsInt32(); return compType == Comparison.Equal || compType == Comparison.NotEqual; } diff --git a/src/ARMeilleure/CodeGen/RegisterAllocators/LinearScanAllocator.cs b/src/ARMeilleure/CodeGen/RegisterAllocators/LinearScanAllocator.cs index 16feeb914..fa0b8aa24 100644 --- a/src/ARMeilleure/CodeGen/RegisterAllocators/LinearScanAllocator.cs +++ b/src/ARMeilleure/CodeGen/RegisterAllocators/LinearScanAllocator.cs @@ -115,7 +115,7 @@ namespace ARMeilleure.CodeGen.RegisterAllocators { NumberLocals(cfg, regMasks.RegistersCount); - var context = new AllocationContext(stackAlloc, regMasks, _intervals.Count); + AllocationContext context = new AllocationContext(stackAlloc, regMasks, _intervals.Count); BuildIntervals(cfg, context); diff --git a/src/ARMeilleure/CodeGen/RegisterAllocators/LiveIntervalList.cs b/src/ARMeilleure/CodeGen/RegisterAllocators/LiveIntervalList.cs index 84b892f42..b31d8fa78 100644 --- a/src/ARMeilleure/CodeGen/RegisterAllocators/LiveIntervalList.cs +++ b/src/ARMeilleure/CodeGen/RegisterAllocators/LiveIntervalList.cs @@ -15,12 +15,12 @@ namespace ARMeilleure.CodeGen.RegisterAllocators { if (_count + 1 > _capacity) { - var oldSpan = Span; + Span oldSpan = Span; _capacity = Math.Max(4, _capacity * 2); _items = Allocators.References.Allocate((uint)_capacity); - var newSpan = Span; + Span newSpan = Span; oldSpan.CopyTo(newSpan); } diff --git a/src/ARMeilleure/CodeGen/RegisterAllocators/UseList.cs b/src/ARMeilleure/CodeGen/RegisterAllocators/UseList.cs index 806002f83..c78201785 100644 --- a/src/ARMeilleure/CodeGen/RegisterAllocators/UseList.cs +++ b/src/ARMeilleure/CodeGen/RegisterAllocators/UseList.cs @@ -16,12 +16,12 @@ namespace ARMeilleure.CodeGen.RegisterAllocators { if (Count + 1 > _capacity) { - var oldSpan = Span; + Span oldSpan = Span; _capacity = Math.Max(4, _capacity * 2); _items = Allocators.Default.Allocate((uint)_capacity); - var newSpan = Span; + Span newSpan = Span; oldSpan.CopyTo(newSpan); } diff --git a/src/ARMeilleure/CodeGen/X86/Assembler.cs b/src/ARMeilleure/CodeGen/X86/Assembler.cs index 96f4de049..74774a8cf 100644 --- a/src/ARMeilleure/CodeGen/X86/Assembler.cs +++ b/src/ARMeilleure/CodeGen/X86/Assembler.cs @@ -1,5 +1,6 @@ using ARMeilleure.CodeGen.Linking; using ARMeilleure.IntermediateRepresentation; +using Microsoft.IO; using Ryujinx.Common.Memory; using System; using System.Collections.Generic; @@ -1324,8 +1325,8 @@ namespace ARMeilleure.CodeGen.X86 public (byte[], RelocInfo) GetCode() { - var jumps = CollectionsMarshal.AsSpan(_jumps); - var relocs = CollectionsMarshal.AsSpan(_relocs); + Span jumps = CollectionsMarshal.AsSpan(_jumps); + Span relocs = CollectionsMarshal.AsSpan(_relocs); // Write jump relative offsets. bool modified; @@ -1410,13 +1411,13 @@ namespace ARMeilleure.CodeGen.X86 // Write the code, ignoring the dummy bytes after jumps, into a new stream. _stream.Seek(0, SeekOrigin.Begin); - using var codeStream = MemoryStreamManager.Shared.GetStream(); - var assembler = new Assembler(codeStream, HasRelocs); + using RecyclableMemoryStream codeStream = MemoryStreamManager.Shared.GetStream(); + Assembler assembler = new Assembler(codeStream, HasRelocs); bool hasRelocs = HasRelocs; int relocIndex = 0; int relocOffset = 0; - var relocEntries = hasRelocs + RelocEntry[] relocEntries = hasRelocs ? new RelocEntry[relocs.Length] : Array.Empty(); @@ -1469,8 +1470,8 @@ namespace ARMeilleure.CodeGen.X86 _stream.CopyTo(codeStream); - var code = codeStream.ToArray(); - var relocInfo = new RelocInfo(relocEntries); + byte[] code = codeStream.ToArray(); + RelocInfo relocInfo = new RelocInfo(relocEntries); return (code, relocInfo); } diff --git a/src/ARMeilleure/CodeGen/X86/CodeGenerator.cs b/src/ARMeilleure/CodeGen/X86/CodeGenerator.cs index 9e94a077f..ab8612133 100644 --- a/src/ARMeilleure/CodeGen/X86/CodeGenerator.cs +++ b/src/ARMeilleure/CodeGen/X86/CodeGenerator.cs @@ -623,7 +623,7 @@ namespace ARMeilleure.CodeGen.X86 Debug.Assert(comp.Kind == OperandKind.Constant); - var cond = ((Comparison)comp.AsInt32()).ToX86Condition(); + X86Condition cond = ((Comparison)comp.AsInt32()).ToX86Condition(); GenerateCompareCommon(context, operation); @@ -661,7 +661,7 @@ namespace ARMeilleure.CodeGen.X86 Debug.Assert(dest.Type == OperandType.I32); Debug.Assert(comp.Kind == OperandKind.Constant); - var cond = ((Comparison)comp.AsInt32()).ToX86Condition(); + X86Condition cond = ((Comparison)comp.AsInt32()).ToX86Condition(); GenerateCompareCommon(context, operation); diff --git a/src/ARMeilleure/CodeGen/X86/HardwareCapabilities.cs b/src/ARMeilleure/CodeGen/X86/HardwareCapabilities.cs index 4f6f1e87b..03a747071 100644 --- a/src/ARMeilleure/CodeGen/X86/HardwareCapabilities.cs +++ b/src/ARMeilleure/CodeGen/X86/HardwareCapabilities.cs @@ -53,7 +53,7 @@ namespace ARMeilleure.CodeGen.X86 memGetXcr0.Reprotect(0, (ulong)asmGetXcr0.Length, MemoryPermission.ReadAndExecute); - var fGetXcr0 = Marshal.GetDelegateForFunctionPointer(memGetXcr0.Pointer); + GetXcr0 fGetXcr0 = Marshal.GetDelegateForFunctionPointer(memGetXcr0.Pointer); return fGetXcr0(); } diff --git a/src/ARMeilleure/CodeGen/X86/PreAllocator.cs b/src/ARMeilleure/CodeGen/X86/PreAllocator.cs index 590c35c7b..ded3f866c 100644 --- a/src/ARMeilleure/CodeGen/X86/PreAllocator.cs +++ b/src/ARMeilleure/CodeGen/X86/PreAllocator.cs @@ -759,7 +759,7 @@ namespace ARMeilleure.CodeGen.X86 Debug.Assert(comp.Kind == OperandKind.Constant); - var compType = (Comparison)comp.AsInt32(); + Comparison compType = (Comparison)comp.AsInt32(); return compType == Comparison.Equal || compType == Comparison.NotEqual; } diff --git a/src/ARMeilleure/CodeGen/X86/X86Optimizer.cs b/src/ARMeilleure/CodeGen/X86/X86Optimizer.cs index 690ca5043..8fcc41bc4 100644 --- a/src/ARMeilleure/CodeGen/X86/X86Optimizer.cs +++ b/src/ARMeilleure/CodeGen/X86/X86Optimizer.cs @@ -13,13 +13,13 @@ namespace ARMeilleure.CodeGen.X86 public static void RunPass(ControlFlowGraph cfg) { - var constants = new Dictionary(); + Dictionary constants = new Dictionary(); Operand GetConstantCopy(BasicBlock block, Operation operation, Operand source) { // If the constant has many uses, we also force a new constant mov to be added, in order // to avoid overflow of the counts field (that is limited to 16 bits). - if (!constants.TryGetValue(source.Value, out var constant) || constant.UsesCount > MaxConstantUses) + if (!constants.TryGetValue(source.Value, out Operand constant) || constant.UsesCount > MaxConstantUses) { constant = Local(source.Type); diff --git a/src/ARMeilleure/Common/BitMap.cs b/src/ARMeilleure/Common/BitMap.cs index 94d47ea59..a7bc69238 100644 --- a/src/ARMeilleure/Common/BitMap.cs +++ b/src/ARMeilleure/Common/BitMap.cs @@ -129,13 +129,13 @@ namespace ARMeilleure.Common if (count > _count) { - var oldMask = _masks; - var oldSpan = new Span(_masks, _count); + long* oldMask = _masks; + Span oldSpan = new Span(_masks, _count); _masks = _allocator.Allocate((uint)count); _count = count; - var newSpan = new Span(_masks, _count); + Span newSpan = new Span(_masks, _count); oldSpan.CopyTo(newSpan); newSpan[oldSpan.Length..].Clear(); diff --git a/src/ARMeilleure/Common/EntryTable.cs b/src/ARMeilleure/Common/EntryTable.cs index e49a0989e..7b8c1e134 100644 --- a/src/ARMeilleure/Common/EntryTable.cs +++ b/src/ARMeilleure/Common/EntryTable.cs @@ -63,7 +63,7 @@ namespace ARMeilleure.Common } int index = _freeHint++; - var page = GetPage(index); + Span page = GetPage(index); _allocated.Set(index); @@ -111,7 +111,7 @@ namespace ARMeilleure.Common throw new ArgumentException("Entry at the specified index was not allocated", nameof(index)); } - var page = GetPage(index); + Span page = GetPage(index); return ref GetValue(page, index); } @@ -136,7 +136,7 @@ namespace ARMeilleure.Common /// Page for the specified private unsafe Span GetPage(int index) { - var pageIndex = (int)((uint)(index & ~(_pageCapacity - 1)) >> _pageLogCapacity); + int pageIndex = (int)((uint)(index & ~(_pageCapacity - 1)) >> _pageLogCapacity); if (!_pages.TryGetValue(pageIndex, out nint page)) { @@ -168,7 +168,7 @@ namespace ARMeilleure.Common { _allocated.Dispose(); - foreach (var page in _pages.Values) + foreach (IntPtr page in _pages.Values) { NativeAllocator.Instance.Free((void*)page); } diff --git a/src/ARMeilleure/Decoders/OpCode32SimdDupElem.cs b/src/ARMeilleure/Decoders/OpCode32SimdDupElem.cs index b6cdff088..fbb14056d 100644 --- a/src/ARMeilleure/Decoders/OpCode32SimdDupElem.cs +++ b/src/ARMeilleure/Decoders/OpCode32SimdDupElem.cs @@ -9,7 +9,7 @@ namespace ARMeilleure.Decoders public OpCode32SimdDupElem(InstDescriptor inst, ulong address, int opCode, bool isThumb) : base(inst, address, opCode, isThumb) { - var opc = (opCode >> 16) & 0xf; + int opc = (opCode >> 16) & 0xf; if ((opc & 0b1) == 1) { diff --git a/src/ARMeilleure/Decoders/OpCode32SimdMovGpElem.cs b/src/ARMeilleure/Decoders/OpCode32SimdMovGpElem.cs index f6fce7d99..3b9431da4 100644 --- a/src/ARMeilleure/Decoders/OpCode32SimdMovGpElem.cs +++ b/src/ARMeilleure/Decoders/OpCode32SimdMovGpElem.cs @@ -21,7 +21,7 @@ namespace ARMeilleure.Decoders Op = (opCode >> 20) & 0x1; U = ((opCode >> 23) & 1) != 0; - var opc = (((opCode >> 23) & 1) << 4) | (((opCode >> 21) & 0x3) << 2) | ((opCode >> 5) & 0x3); + int opc = (((opCode >> 23) & 1) << 4) | (((opCode >> 21) & 0x3) << 2) | ((opCode >> 5) & 0x3); if ((opc & 0b01000) == 0b01000) { diff --git a/src/ARMeilleure/Decoders/OpCodeAluImm.cs b/src/ARMeilleure/Decoders/OpCodeAluImm.cs index 0d2f7202f..41a12e474 100644 --- a/src/ARMeilleure/Decoders/OpCodeAluImm.cs +++ b/src/ARMeilleure/Decoders/OpCodeAluImm.cs @@ -20,7 +20,7 @@ namespace ARMeilleure.Decoders } else if (DataOp == DataOp.Logical) { - var bm = DecoderHelper.DecodeBitMask(opCode, true); + DecoderHelper.BitMask bm = DecoderHelper.DecodeBitMask(opCode, true); if (bm.IsUndefined) { diff --git a/src/ARMeilleure/Decoders/OpCodeBfm.cs b/src/ARMeilleure/Decoders/OpCodeBfm.cs index d51efade2..969c782f8 100644 --- a/src/ARMeilleure/Decoders/OpCodeBfm.cs +++ b/src/ARMeilleure/Decoders/OpCodeBfm.cs @@ -11,7 +11,7 @@ namespace ARMeilleure.Decoders public OpCodeBfm(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { - var bm = DecoderHelper.DecodeBitMask(opCode, false); + DecoderHelper.BitMask bm = DecoderHelper.DecodeBitMask(opCode, false); if (bm.IsUndefined) { diff --git a/src/ARMeilleure/Decoders/Optimizations/TailCallRemover.cs b/src/ARMeilleure/Decoders/Optimizations/TailCallRemover.cs index 9d988f0c9..361a7f0d0 100644 --- a/src/ARMeilleure/Decoders/Optimizations/TailCallRemover.cs +++ b/src/ARMeilleure/Decoders/Optimizations/TailCallRemover.cs @@ -69,7 +69,7 @@ namespace ARMeilleure.Decoders.Optimizations } } - var newBlocks = new List(blocks.Count); + List newBlocks = new List(blocks.Count); // Finally, rebuild decoded block list, ignoring blocks outside the contiguous range. for (int i = 0; i < blocks.Count; i++) diff --git a/src/ARMeilleure/Diagnostics/IRDumper.cs b/src/ARMeilleure/Diagnostics/IRDumper.cs index 16833d085..9d6a708b6 100644 --- a/src/ARMeilleure/Diagnostics/IRDumper.cs +++ b/src/ARMeilleure/Diagnostics/IRDumper.cs @@ -141,7 +141,7 @@ namespace ARMeilleure.Diagnostics break; case OperandKind.Memory: - var memOp = operand.GetMemory(); + MemoryOperand memOp = operand.GetMemory(); _builder.Append('['); @@ -285,7 +285,7 @@ namespace ARMeilleure.Diagnostics public static string GetDump(ControlFlowGraph cfg) { - var dumper = new IRDumper(1); + IRDumper dumper = new IRDumper(1); for (BasicBlock block = cfg.Blocks.First; block != null; block = block.ListNext) { diff --git a/src/ARMeilleure/Instructions/InstEmitAlu32.cs b/src/ARMeilleure/Instructions/InstEmitAlu32.cs index 8eabe093e..2e659fd5f 100644 --- a/src/ARMeilleure/Instructions/InstEmitAlu32.cs +++ b/src/ARMeilleure/Instructions/InstEmitAlu32.cs @@ -415,7 +415,7 @@ namespace ARMeilleure.Instructions { IOpCode32AluBf op = (IOpCode32AluBf)context.CurrOp; - var msb = op.Lsb + op.Msb; // For this instruction, the msb is actually a width. + int msb = op.Lsb + op.Msb; // For this instruction, the msb is actually a width. Operand n = GetIntA32(context, op.Rn); Operand res = context.ShiftRightSI(context.ShiftLeft(n, Const(31 - msb)), Const(31 - op.Msb)); @@ -547,7 +547,7 @@ namespace ARMeilleure.Instructions { IOpCode32AluBf op = (IOpCode32AluBf)context.CurrOp; - var msb = op.Lsb + op.Msb; // For this instruction, the msb is actually a width. + int msb = op.Lsb + op.Msb; // For this instruction, the msb is actually a width. Operand n = GetIntA32(context, op.Rn); Operand res = context.ShiftRightUI(context.ShiftLeft(n, Const(31 - msb)), Const(31 - op.Msb)); diff --git a/src/ARMeilleure/Instructions/InstEmitFlowHelper.cs b/src/ARMeilleure/Instructions/InstEmitFlowHelper.cs index a602ea49e..f67668da4 100644 --- a/src/ARMeilleure/Instructions/InstEmitFlowHelper.cs +++ b/src/ARMeilleure/Instructions/InstEmitFlowHelper.cs @@ -1,4 +1,5 @@ using ARMeilleure.CodeGen.Linking; +using ARMeilleure.Common; using ARMeilleure.Decoders; using ARMeilleure.IntermediateRepresentation; using ARMeilleure.State; @@ -193,7 +194,7 @@ namespace ARMeilleure.Instructions Operand hostAddress; - var table = context.FunctionTable; + IAddressTable table = context.FunctionTable; // If address is mapped onto the function table, we can skip the table walk. Otherwise we fallback // onto the dispatch stub. @@ -218,7 +219,7 @@ namespace ARMeilleure.Instructions for (int i = 0; i < table.Levels.Length; i++) { - var level = table.Levels[i]; + AddressTableLevel level = table.Levels[i]; int clearBits = 64 - (level.Index + level.Length); Operand index = context.ShiftLeft( diff --git a/src/ARMeilleure/Instructions/InstEmitMemoryEx32.cs b/src/ARMeilleure/Instructions/InstEmitMemoryEx32.cs index 150218827..ea9e33f26 100644 --- a/src/ARMeilleure/Instructions/InstEmitMemoryEx32.cs +++ b/src/ARMeilleure/Instructions/InstEmitMemoryEx32.cs @@ -143,8 +143,8 @@ namespace ARMeilleure.Instructions Operand address = context.Copy(GetIntA32(context, op.Rn)); - var exclusive = (accType & AccessType.Exclusive) != 0; - var ordered = (accType & AccessType.Ordered) != 0; + bool exclusive = (accType & AccessType.Exclusive) != 0; + bool ordered = (accType & AccessType.Ordered) != 0; if ((accType & AccessType.Load) != 0) { diff --git a/src/ARMeilleure/Instructions/InstEmitSimdCmp32.cs b/src/ARMeilleure/Instructions/InstEmitSimdCmp32.cs index 1d68bce6b..6ec2b58f9 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdCmp32.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdCmp32.cs @@ -229,7 +229,7 @@ namespace ARMeilleure.Instructions private static Operand ZerosOrOnes(ArmEmitterContext context, Operand fromBool, OperandType baseType) { - var ones = (baseType == OperandType.I64) ? Const(-1L) : Const(-1); + Operand ones = (baseType == OperandType.I64) ? Const(-1L) : Const(-1); return context.ConditionalSelect(fromBool, ones, Const(baseType, 0L)); } diff --git a/src/ARMeilleure/Instructions/InstEmitSimdCvt32.cs b/src/ARMeilleure/Instructions/InstEmitSimdCvt32.cs index 216726df9..d3fafc856 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdCvt32.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdCvt32.cs @@ -118,15 +118,15 @@ namespace ARMeilleure.Instructions { OpCode32SimdCvtFFixed op = (OpCode32SimdCvtFFixed)context.CurrOp; - var toFixed = op.Opc == 1; + bool toFixed = op.Opc == 1; int fracBits = op.Fbits; - var unsigned = op.U; + bool unsigned = op.U; if (toFixed) // F32 to S32 or U32 (fixed) { EmitVectorUnaryOpF32(context, (op1) => { - var scaledValue = context.Multiply(op1, ConstF(MathF.Pow(2f, fracBits))); + Operand scaledValue = context.Multiply(op1, ConstF(MathF.Pow(2f, fracBits))); MethodInfo info = unsigned ? typeof(SoftFallback).GetMethod(nameof(SoftFallback.SatF32ToU32)) : typeof(SoftFallback).GetMethod(nameof(SoftFallback.SatF32ToS32)); return context.Call(info, scaledValue); @@ -136,7 +136,7 @@ namespace ARMeilleure.Instructions { EmitVectorUnaryOpI32(context, (op1) => { - var floatValue = unsigned ? context.ConvertToFPUI(OperandType.FP32, op1) : context.ConvertToFP(OperandType.FP32, op1); + Operand floatValue = unsigned ? context.ConvertToFPUI(OperandType.FP32, op1) : context.ConvertToFP(OperandType.FP32, op1); return context.Multiply(floatValue, ConstF(1f / MathF.Pow(2f, fracBits))); }, !unsigned); diff --git a/src/ARMeilleure/Instructions/InstEmitSimdMemory32.cs b/src/ARMeilleure/Instructions/InstEmitSimdMemory32.cs index 35c6dd328..3808ef929 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdMemory32.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdMemory32.cs @@ -87,7 +87,7 @@ namespace ARMeilleure.Instructions { if (op.Replicate) { - var regs = (count > 1) ? 1 : op.Increment; + int regs = (count > 1) ? 1 : op.Increment; for (int reg = 0; reg < regs; reg++) { int dreg = reg + d; diff --git a/src/ARMeilleure/Instructions/SoftFloat.cs b/src/ARMeilleure/Instructions/SoftFloat.cs index 7895ca1dc..a2bb23be8 100644 --- a/src/ARMeilleure/Instructions/SoftFloat.cs +++ b/src/ARMeilleure/Instructions/SoftFloat.cs @@ -1538,7 +1538,7 @@ namespace ARMeilleure.Instructions } else if (MathF.Abs(value) < MathF.Pow(2f, -128)) { - var overflowToInf = fpcr.GetRoundingMode() switch + bool overflowToInf = fpcr.GetRoundingMode() switch { FPRoundingMode.ToNearest => true, FPRoundingMode.TowardsPlusInfinity => !sign, @@ -3073,7 +3073,7 @@ namespace ARMeilleure.Instructions } else if (Math.Abs(value) < Math.Pow(2d, -1024)) { - var overflowToInf = fpcr.GetRoundingMode() switch + bool overflowToInf = fpcr.GetRoundingMode() switch { FPRoundingMode.ToNearest => true, FPRoundingMode.TowardsPlusInfinity => !sign, diff --git a/src/ARMeilleure/IntermediateRepresentation/Operand.cs b/src/ARMeilleure/IntermediateRepresentation/Operand.cs index 89aefacb1..495a9d04a 100644 --- a/src/ARMeilleure/IntermediateRepresentation/Operand.cs +++ b/src/ARMeilleure/IntermediateRepresentation/Operand.cs @@ -304,7 +304,7 @@ namespace ARMeilleure.IntermediateRepresentation ushort newCount = checked((ushort)(count + 1)); ushort newCapacity = (ushort)Math.Min(capacity * 2, ushort.MaxValue); - var oldSpan = new Span(data, count); + Span oldSpan = new Span(data, count); capacity = newCapacity; data = Allocators.References.Allocate(capacity); @@ -338,7 +338,7 @@ namespace ARMeilleure.IntermediateRepresentation throw new OverflowException(); } - var oldSpan = new Span(data, (int)count); + Span oldSpan = new Span(data, (int)count); capacity = newCapacity; data = Allocators.References.Allocate(capacity); @@ -352,7 +352,7 @@ namespace ARMeilleure.IntermediateRepresentation private static void Remove(in T item, ref T* data, ref ushort count) where T : unmanaged { - var span = new Span(data, count); + Span span = new Span(data, count); for (int i = 0; i < span.Length; i++) { @@ -372,7 +372,7 @@ namespace ARMeilleure.IntermediateRepresentation private static void Remove(in T item, ref T* data, ref uint count) where T : unmanaged { - var span = new Span(data, (int)count); + Span span = new Span(data, (int)count); for (int i = 0; i < span.Length; i++) { diff --git a/src/ARMeilleure/Signal/TestMethods.cs b/src/ARMeilleure/Signal/TestMethods.cs index 9d11ab183..714bcc01b 100644 --- a/src/ARMeilleure/Signal/TestMethods.cs +++ b/src/ARMeilleure/Signal/TestMethods.cs @@ -22,7 +22,7 @@ namespace ARMeilleure.Signal { EmitterContext context = new(); - var result = WindowsPartialUnmapHandler.EmitRetryFromAccessViolation(context); + Operand result = WindowsPartialUnmapHandler.EmitRetryFromAccessViolation(context); context.Return(result); @@ -39,7 +39,7 @@ namespace ARMeilleure.Signal { EmitterContext context = new(); - var result = WindowsPartialUnmapHandler.EmitThreadLocalMapIntGetOrReserve(context, structPtr, context.LoadArgument(OperandType.I32, 0), context.LoadArgument(OperandType.I32, 1)); + Operand result = WindowsPartialUnmapHandler.EmitThreadLocalMapIntGetOrReserve(context, structPtr, context.LoadArgument(OperandType.I32, 0), context.LoadArgument(OperandType.I32, 1)); context.Return(result); diff --git a/src/ARMeilleure/Translation/Cache/JitUnwindWindows.cs b/src/ARMeilleure/Translation/Cache/JitUnwindWindows.cs index 642794188..01b2aa8ed 100644 --- a/src/ARMeilleure/Translation/Cache/JitUnwindWindows.cs +++ b/src/ARMeilleure/Translation/Cache/JitUnwindWindows.cs @@ -100,13 +100,13 @@ namespace ARMeilleure.Translation.Cache return null; // Not found. } - var unwindInfo = funcEntry.UnwindInfo; + CodeGen.Unwinding.UnwindInfo unwindInfo = funcEntry.UnwindInfo; int codeIndex = 0; for (int index = unwindInfo.PushEntries.Length - 1; index >= 0; index--) { - var entry = unwindInfo.PushEntries[index]; + UnwindPushEntry entry = unwindInfo.PushEntries[index]; switch (entry.PseudoOp) { diff --git a/src/ARMeilleure/Translation/ControlFlowGraph.cs b/src/ARMeilleure/Translation/ControlFlowGraph.cs index 45b092ec5..03ef6f461 100644 --- a/src/ARMeilleure/Translation/ControlFlowGraph.cs +++ b/src/ARMeilleure/Translation/ControlFlowGraph.cs @@ -47,8 +47,8 @@ namespace ARMeilleure.Translation { RemoveUnreachableBlocks(Blocks); - var visited = new HashSet(); - var blockStack = new Stack(); + HashSet visited = new HashSet(); + Stack blockStack = new Stack(); Array.Resize(ref _postOrderBlocks, Blocks.Count); Array.Resize(ref _postOrderMap, Blocks.Count); @@ -88,8 +88,8 @@ namespace ARMeilleure.Translation private void RemoveUnreachableBlocks(IntrusiveList blocks) { - var visited = new HashSet(); - var workQueue = new Queue(); + HashSet visited = new HashSet(); + Queue workQueue = new Queue(); visited.Add(Entry); workQueue.Enqueue(Entry); diff --git a/src/ARMeilleure/Translation/PTC/Ptc.cs b/src/ARMeilleure/Translation/PTC/Ptc.cs index 894e825cf..10f8f3043 100644 --- a/src/ARMeilleure/Translation/PTC/Ptc.cs +++ b/src/ARMeilleure/Translation/PTC/Ptc.cs @@ -9,6 +9,7 @@ using Ryujinx.Common.Logging; using Ryujinx.Common.Memory; using System; using System.Buffers.Binary; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; @@ -562,7 +563,7 @@ namespace ARMeilleure.Translation.PTC bool isEntryChanged = infoEntry.Hash != ComputeHash(translator.Memory, infoEntry.Address, infoEntry.GuestSize); - if (isEntryChanged || (!infoEntry.HighCq && Profiler.ProfiledFuncs.TryGetValue(infoEntry.Address, out var value) && value.HighCq)) + if (isEntryChanged || (!infoEntry.HighCq && Profiler.ProfiledFuncs.TryGetValue(infoEntry.Address, out PtcProfiler.FuncProfile value) && value.HighCq)) { infoEntry.Stubbed = true; infoEntry.CodeLength = 0; @@ -749,8 +750,8 @@ namespace ARMeilleure.Translation.PTC UnwindInfo unwindInfo, bool highCq) { - var cFunc = new CompiledFunction(code, unwindInfo, RelocInfo.Empty); - var gFunc = cFunc.MapWithPointer(out nint gFuncPointer); + CompiledFunction cFunc = new CompiledFunction(code, unwindInfo, RelocInfo.Empty); + GuestFunction gFunc = cFunc.MapWithPointer(out nint gFuncPointer); return new TranslatedFunction(gFunc, gFuncPointer, callCounter, guestSize, highCq); } @@ -787,7 +788,7 @@ namespace ARMeilleure.Translation.PTC public void MakeAndSaveTranslations(Translator translator) { - var profiledFuncsToTranslate = Profiler.GetProfiledFuncsToTranslate(translator.Functions); + ConcurrentQueue<(ulong address, PtcProfiler.FuncProfile funcProfile)> profiledFuncsToTranslate = Profiler.GetProfiledFuncsToTranslate(translator.Functions); _translateCount = 0; _translateTotalCount = profiledFuncsToTranslate.Count; @@ -831,7 +832,7 @@ namespace ARMeilleure.Translation.PTC void TranslateFuncs() { - while (profiledFuncsToTranslate.TryDequeue(out var item)) + while (profiledFuncsToTranslate.TryDequeue(out (ulong address, PtcProfiler.FuncProfile funcProfile) item)) { ulong address = item.address; @@ -866,11 +867,11 @@ namespace ARMeilleure.Translation.PTC Stopwatch sw = Stopwatch.StartNew(); - foreach (var thread in threads) + foreach (Thread thread in threads) { thread.Start(); } - foreach (var thread in threads) + foreach (Thread thread in threads) { thread.Join(); } @@ -944,7 +945,7 @@ namespace ARMeilleure.Translation.PTC WriteCode(code.AsSpan()); // WriteReloc. - using var relocInfoWriter = new BinaryWriter(_relocsStream, EncodingCache.UTF8NoBOM, true); + using BinaryWriter relocInfoWriter = new BinaryWriter(_relocsStream, EncodingCache.UTF8NoBOM, true); foreach (RelocEntry entry in relocInfo.Entries) { @@ -954,7 +955,7 @@ namespace ARMeilleure.Translation.PTC } // WriteUnwindInfo. - using var unwindInfoWriter = new BinaryWriter(_unwindInfosStream, EncodingCache.UTF8NoBOM, true); + using BinaryWriter unwindInfoWriter = new BinaryWriter(_unwindInfosStream, EncodingCache.UTF8NoBOM, true); unwindInfoWriter.Write(unwindInfo.PushEntries.Length); diff --git a/src/ARMeilleure/Translation/PTC/PtcProfiler.cs b/src/ARMeilleure/Translation/PTC/PtcProfiler.cs index bdb9abd05..250ef70bb 100644 --- a/src/ARMeilleure/Translation/PTC/PtcProfiler.cs +++ b/src/ARMeilleure/Translation/PTC/PtcProfiler.cs @@ -111,9 +111,9 @@ namespace ARMeilleure.Translation.PTC public ConcurrentQueue<(ulong address, FuncProfile funcProfile)> GetProfiledFuncsToTranslate(TranslatorCache funcs) { - var profiledFuncsToTranslate = new ConcurrentQueue<(ulong address, FuncProfile funcProfile)>(); + ConcurrentQueue<(ulong address, FuncProfile funcProfile)> profiledFuncsToTranslate = new ConcurrentQueue<(ulong address, FuncProfile funcProfile)>(); - foreach (var profiledFunc in ProfiledFuncs) + foreach (KeyValuePair profiledFunc in ProfiledFuncs) { if (!funcs.ContainsKey(profiledFunc.Key)) { diff --git a/src/ARMeilleure/Translation/SsaConstruction.cs b/src/ARMeilleure/Translation/SsaConstruction.cs index cddcfcd4f..3819340c6 100644 --- a/src/ARMeilleure/Translation/SsaConstruction.cs +++ b/src/ARMeilleure/Translation/SsaConstruction.cs @@ -44,10 +44,10 @@ namespace ARMeilleure.Translation public static void Construct(ControlFlowGraph cfg) { - var globalDefs = new DefMap[cfg.Blocks.Count]; - var localDefs = new Operand[cfg.LocalsCount + RegisterConsts.TotalCount]; + DefMap[] globalDefs = new DefMap[cfg.Blocks.Count]; + Operand[] localDefs = new Operand[cfg.LocalsCount + RegisterConsts.TotalCount]; - var dfPhiBlocks = new Queue(); + Queue dfPhiBlocks = new Queue(); for (BasicBlock block = cfg.Blocks.First; block != null; block = block.ListNext) { diff --git a/src/ARMeilleure/Translation/Translator.cs b/src/ARMeilleure/Translation/Translator.cs index 162368782..8e1a437db 100644 --- a/src/ARMeilleure/Translation/Translator.cs +++ b/src/ARMeilleure/Translation/Translator.cs @@ -222,7 +222,7 @@ namespace ARMeilleure.Translation internal TranslatedFunction Translate(ulong address, ExecutionMode mode, bool highCq, bool singleStep = false) { - var context = new ArmEmitterContext( + ArmEmitterContext context = new ArmEmitterContext( Memory, CountTable, FunctionTable, @@ -259,10 +259,10 @@ namespace ARMeilleure.Translation Logger.EndPass(PassName.RegisterUsage); - var retType = OperandType.I64; - var argTypes = new OperandType[] { OperandType.I64 }; + OperandType retType = OperandType.I64; + OperandType[] argTypes = new OperandType[] { OperandType.I64 }; - var options = highCq ? CompilerOptions.HighCq : CompilerOptions.None; + CompilerOptions options = highCq ? CompilerOptions.HighCq : CompilerOptions.None; if (context.HasPtc && !singleStep) { @@ -521,7 +521,7 @@ namespace ARMeilleure.Translation List functions = Functions.AsList(); - foreach (var func in functions) + foreach (TranslatedFunction func in functions) { JitCache.Unmap(func.FuncPointer); @@ -530,7 +530,7 @@ namespace ARMeilleure.Translation Functions.Clear(); - while (_oldFuncs.TryDequeue(out var kv)) + while (_oldFuncs.TryDequeue(out KeyValuePair kv)) { JitCache.Unmap(kv.Value.FuncPointer); @@ -551,7 +551,7 @@ namespace ARMeilleure.Translation { while (Queue.Count > 0 && Queue.TryDequeue(out RejitRequest request)) { - if (Functions.TryGetValue(request.Address, out var func) && func.CallCounter != null) + if (Functions.TryGetValue(request.Address, out TranslatedFunction func) && func.CallCounter != null) { Volatile.Write(ref func.CallCounter.Value, 0); } diff --git a/src/ARMeilleure/Translation/TranslatorStubs.cs b/src/ARMeilleure/Translation/TranslatorStubs.cs index bd9aed8d4..e48349963 100644 --- a/src/ARMeilleure/Translation/TranslatorStubs.cs +++ b/src/ARMeilleure/Translation/TranslatorStubs.cs @@ -142,7 +142,7 @@ namespace ARMeilleure.Translation /// Generated private nint GenerateDispatchStub() { - var context = new EmitterContext(); + EmitterContext context = new EmitterContext(); Operand lblFallback = Label(); Operand lblEnd = Label(); @@ -161,7 +161,7 @@ namespace ARMeilleure.Translation for (int i = 0; i < _functionTable.Levels.Length; i++) { - ref var level = ref _functionTable.Levels[i]; + ref AddressTableLevel level = ref _functionTable.Levels[i]; // level.Mask is not used directly because it is more often bigger than 32-bits, so it will not // be encoded as an immediate on x86's bitwise and operation. @@ -185,11 +185,11 @@ namespace ARMeilleure.Translation hostAddress = context.Call(typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetFunctionAddress)), guestAddress); context.Tailcall(hostAddress, nativeContext); - var cfg = context.GetControlFlowGraph(); - var retType = OperandType.I64; - var argTypes = new[] { OperandType.I64 }; + ControlFlowGraph cfg = context.GetControlFlowGraph(); + OperandType retType = OperandType.I64; + OperandType[] argTypes = new[] { OperandType.I64 }; - var func = Compiler.Compile(cfg, argTypes, retType, CompilerOptions.HighCq, RuntimeInformation.ProcessArchitecture).Map(); + GuestFunction func = Compiler.Compile(cfg, argTypes, retType, CompilerOptions.HighCq, RuntimeInformation.ProcessArchitecture).Map(); return Marshal.GetFunctionPointerForDelegate(func); } @@ -200,7 +200,7 @@ namespace ARMeilleure.Translation /// Generated private nint GenerateSlowDispatchStub() { - var context = new EmitterContext(); + EmitterContext context = new EmitterContext(); // Load the target guest address from the native context. Operand nativeContext = context.LoadArgument(OperandType.I64, 0); @@ -210,11 +210,11 @@ namespace ARMeilleure.Translation Operand hostAddress = context.Call(typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetFunctionAddress)), guestAddress); context.Tailcall(hostAddress, nativeContext); - var cfg = context.GetControlFlowGraph(); - var retType = OperandType.I64; - var argTypes = new[] { OperandType.I64 }; + ControlFlowGraph cfg = context.GetControlFlowGraph(); + OperandType retType = OperandType.I64; + OperandType[] argTypes = new[] { OperandType.I64 }; - var func = Compiler.Compile(cfg, argTypes, retType, CompilerOptions.HighCq, RuntimeInformation.ProcessArchitecture).Map(); + GuestFunction func = Compiler.Compile(cfg, argTypes, retType, CompilerOptions.HighCq, RuntimeInformation.ProcessArchitecture).Map(); return Marshal.GetFunctionPointerForDelegate(func); } @@ -251,7 +251,7 @@ namespace ARMeilleure.Translation /// function private DispatcherFunction GenerateDispatchLoop() { - var context = new EmitterContext(); + EmitterContext context = new EmitterContext(); Operand beginLbl = Label(); Operand endLbl = Label(); @@ -279,9 +279,9 @@ namespace ARMeilleure.Translation context.Return(); - var cfg = context.GetControlFlowGraph(); - var retType = OperandType.None; - var argTypes = new[] { OperandType.I64, OperandType.I64 }; + ControlFlowGraph cfg = context.GetControlFlowGraph(); + OperandType retType = OperandType.None; + OperandType[] argTypes = new[] { OperandType.I64, OperandType.I64 }; return Compiler.Compile(cfg, argTypes, retType, CompilerOptions.HighCq, RuntimeInformation.ProcessArchitecture).Map(); } @@ -292,7 +292,7 @@ namespace ARMeilleure.Translation /// function private WrapperFunction GenerateContextWrapper() { - var context = new EmitterContext(); + EmitterContext context = new EmitterContext(); Operand nativeContext = context.LoadArgument(OperandType.I64, 0); Operand guestMethod = context.LoadArgument(OperandType.I64, 1); @@ -303,9 +303,9 @@ namespace ARMeilleure.Translation context.Return(returnValue); - var cfg = context.GetControlFlowGraph(); - var retType = OperandType.I64; - var argTypes = new[] { OperandType.I64, OperandType.I64 }; + ControlFlowGraph cfg = context.GetControlFlowGraph(); + OperandType retType = OperandType.I64; + OperandType[] argTypes = new[] { OperandType.I64, OperandType.I64 }; return Compiler.Compile(cfg, argTypes, retType, CompilerOptions.HighCq, RuntimeInformation.ProcessArchitecture).Map(); } From 97188556d8ce508c097107a98ce29b6578a23783 Mon Sep 17 00:00:00 2001 From: Evan Husted Date: Sat, 25 Jan 2025 14:03:38 -0600 Subject: [PATCH 03/19] misc: chore: Use explicit types in audio projects --- src/Ryujinx.Audio.Backends.SDL2/SDL2HardwareDeviceDriver.cs | 2 +- .../Native/SoundIoOutStreamContext.cs | 6 +++--- src/Ryujinx.Audio/Renderer/Utils/FileHardwareDevice.cs | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Ryujinx.Audio.Backends.SDL2/SDL2HardwareDeviceDriver.cs b/src/Ryujinx.Audio.Backends.SDL2/SDL2HardwareDeviceDriver.cs index acd1582ec..2d04073d7 100644 --- a/src/Ryujinx.Audio.Backends.SDL2/SDL2HardwareDeviceDriver.cs +++ b/src/Ryujinx.Audio.Backends.SDL2/SDL2HardwareDeviceDriver.cs @@ -37,7 +37,7 @@ namespace Ryujinx.Audio.Backends.SDL2 SDL2Driver.Instance.Initialize(); - int res = SDL_GetDefaultAudioInfo(nint.Zero, out var spec, 0); + int res = SDL_GetDefaultAudioInfo(nint.Zero, out SDL_AudioSpec spec, 0); if (res != 0) { diff --git a/src/Ryujinx.Audio.Backends.SoundIo/Native/SoundIoOutStreamContext.cs b/src/Ryujinx.Audio.Backends.SoundIo/Native/SoundIoOutStreamContext.cs index b1823a074..072e49d8c 100644 --- a/src/Ryujinx.Audio.Backends.SoundIo/Native/SoundIoOutStreamContext.cs +++ b/src/Ryujinx.Audio.Backends.SoundIo/Native/SoundIoOutStreamContext.cs @@ -38,7 +38,7 @@ namespace Ryujinx.Audio.Backends.SoundIo.Native get => Marshal.PtrToStringAnsi(GetOutContext().Name); set { - var context = GetOutContext(); + SoundIoOutStream context = GetOutContext(); if (_nameStored != nint.Zero && context.Name == _nameStored) { @@ -129,8 +129,8 @@ namespace Ryujinx.Audio.Backends.SoundIo.Native unsafe { - var frameCountPtr = &nativeFrameCount; - var arenasPtr = &arenas; + int* frameCountPtr = &nativeFrameCount; + IntPtr* arenasPtr = &arenas; CheckError(soundio_outstream_begin_write(_context, (nint)arenasPtr, (nint)frameCountPtr)); frameCount = *frameCountPtr; diff --git a/src/Ryujinx.Audio/Renderer/Utils/FileHardwareDevice.cs b/src/Ryujinx.Audio/Renderer/Utils/FileHardwareDevice.cs index bc2313ccf..008a067f1 100644 --- a/src/Ryujinx.Audio/Renderer/Utils/FileHardwareDevice.cs +++ b/src/Ryujinx.Audio/Renderer/Utils/FileHardwareDevice.cs @@ -27,7 +27,7 @@ namespace Ryujinx.Audio.Renderer.Utils private void UpdateHeader() { - var writer = new BinaryWriter(_stream); + BinaryWriter writer = new(_stream); long currentPos = writer.Seek(0, SeekOrigin.Current); From a97fd4beb1a8cdb0eb7919ff781f3cb4f12adafe Mon Sep 17 00:00:00 2001 From: Evan Husted Date: Sat, 25 Jan 2025 14:04:12 -0600 Subject: [PATCH 04/19] misc: chore: Use explicit types in common project --- src/Ryujinx.Common/AsyncWorkQueue.cs | 2 +- src/Ryujinx.Common/Configuration/DirtyHack.cs | 4 +-- .../Extensions/SequenceReaderExtensions.cs | 7 ++-- .../Helpers/FileAssociationHelper.cs | 6 ++-- src/Ryujinx.Common/Helpers/LinuxHelper.cs | 2 +- src/Ryujinx.Common/Helpers/OpenHelper.cs | 4 +-- .../Formatters/DynamicObjectFormatter.cs | 4 +-- src/Ryujinx.Common/Logging/Logger.cs | 6 ++-- .../Logging/Targets/JsonLogTarget.cs | 2 +- .../Utilities/EmbeddedResources.cs | 36 +++++++++---------- .../Utilities/FileSystemUtils.cs | 4 +-- .../Utilities/MessagePackObjectFormatter.cs | 17 ++++----- src/Ryujinx.Common/Utilities/StreamUtils.cs | 3 +- .../Utilities/TypedStringEnumConverter.cs | 2 +- .../Utilities/XCIFileTrimmer.cs | 16 ++++----- 15 files changed, 59 insertions(+), 56 deletions(-) diff --git a/src/Ryujinx.Common/AsyncWorkQueue.cs b/src/Ryujinx.Common/AsyncWorkQueue.cs index abb5867b0..e3f91c891 100644 --- a/src/Ryujinx.Common/AsyncWorkQueue.cs +++ b/src/Ryujinx.Common/AsyncWorkQueue.cs @@ -34,7 +34,7 @@ namespace Ryujinx.Common { try { - foreach (var item in _queue.GetConsumingEnumerable(_cts.Token)) + foreach (T item in _queue.GetConsumingEnumerable(_cts.Token)) { _workerAction(item); } diff --git a/src/Ryujinx.Common/Configuration/DirtyHack.cs b/src/Ryujinx.Common/Configuration/DirtyHack.cs index 9ab9a26a5..6564f8567 100644 --- a/src/Ryujinx.Common/Configuration/DirtyHack.cs +++ b/src/Ryujinx.Common/Configuration/DirtyHack.cs @@ -23,7 +23,7 @@ namespace Ryujinx.Common.Configuration public static EnabledDirtyHack Unpack(ulong packedHack) { - var unpackedFields = packedHack.UnpackBitFields(PackedFormat); + uint[] unpackedFields = packedHack.UnpackBitFields(PackedFormat); if (unpackedFields is not [var hack, var value]) throw new Exception("The unpack operation on the integer resulted in an invalid unpacked result."); @@ -53,7 +53,7 @@ namespace Ryujinx.Common.Configuration public static implicit operator DirtyHacks(EnabledDirtyHack[] hacks) => new(hacks); public static implicit operator DirtyHacks(ulong[] packedHacks) => new(packedHacks); - public new int this[DirtyHack hack] => TryGetValue(hack, out var value) ? value : -1; + public new int this[DirtyHack hack] => TryGetValue(hack, out int value) ? value : -1; public bool IsEnabled(DirtyHack hack) => ContainsKey(hack); } diff --git a/src/Ryujinx.Common/Extensions/SequenceReaderExtensions.cs b/src/Ryujinx.Common/Extensions/SequenceReaderExtensions.cs index 79b5d743b..df2b82aa6 100644 --- a/src/Ryujinx.Common/Extensions/SequenceReaderExtensions.cs +++ b/src/Ryujinx.Common/Extensions/SequenceReaderExtensions.cs @@ -1,6 +1,7 @@ using System; using System.Buffers; using System.Diagnostics; +using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -16,15 +17,15 @@ namespace Ryujinx.Common.Extensions /// The path and name of the file to create and dump to public static void DumpToFile(this ref SequenceReader reader, string fileFullName) { - var initialConsumed = reader.Consumed; + long initialConsumed = reader.Consumed; reader.Rewind(initialConsumed); - using (var fileStream = System.IO.File.Create(fileFullName, 4096, System.IO.FileOptions.None)) + using (FileStream fileStream = System.IO.File.Create(fileFullName, 4096, System.IO.FileOptions.None)) { while (reader.End == false) { - var span = reader.CurrentSpan; + ReadOnlySpan span = reader.CurrentSpan; fileStream.Write(span); reader.Advance(span.Length); } diff --git a/src/Ryujinx.Common/Helpers/FileAssociationHelper.cs b/src/Ryujinx.Common/Helpers/FileAssociationHelper.cs index 476aee228..7ed5e869a 100644 --- a/src/Ryujinx.Common/Helpers/FileAssociationHelper.cs +++ b/src/Ryujinx.Common/Helpers/FileAssociationHelper.cs @@ -101,7 +101,7 @@ namespace Ryujinx.Common.Helper { RegistryKey key = Registry.CurrentUser.OpenSubKey(@$"Software\Classes\{ext}"); - var openCmd = key?.OpenSubKey(@"shell\open\command"); + RegistryKey openCmd = key?.OpenSubKey(@"shell\open\command"); if (openCmd is null) { @@ -143,7 +143,7 @@ namespace Ryujinx.Common.Helper } else { - using var key = Registry.CurrentUser.CreateSubKey(keyString); + using RegistryKey key = Registry.CurrentUser.CreateSubKey(keyString); if (key is null) { @@ -151,7 +151,7 @@ namespace Ryujinx.Common.Helper } Logger.Debug?.Print(LogClass.Application, $"Adding type association {ext}"); - using var openCmd = key.CreateSubKey(@"shell\open\command"); + using RegistryKey openCmd = key.CreateSubKey(@"shell\open\command"); openCmd.SetValue(string.Empty, $"\"{Environment.ProcessPath}\" \"%1\""); Logger.Debug?.Print(LogClass.Application, $"Added type association {ext}"); diff --git a/src/Ryujinx.Common/Helpers/LinuxHelper.cs b/src/Ryujinx.Common/Helpers/LinuxHelper.cs index 2adfd20f8..e342b2151 100644 --- a/src/Ryujinx.Common/Helpers/LinuxHelper.cs +++ b/src/Ryujinx.Common/Helpers/LinuxHelper.cs @@ -24,7 +24,7 @@ namespace Ryujinx.Common.Helper return null; } - foreach (var searchPath in pathVar.Split(":", StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) + foreach (string searchPath in pathVar.Split(":", StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) { string binaryPath = Path.Combine(searchPath, binary); diff --git a/src/Ryujinx.Common/Helpers/OpenHelper.cs b/src/Ryujinx.Common/Helpers/OpenHelper.cs index 6a54b69f3..402e6bcc1 100644 --- a/src/Ryujinx.Common/Helpers/OpenHelper.cs +++ b/src/Ryujinx.Common/Helpers/OpenHelper.cs @@ -60,7 +60,7 @@ namespace Ryujinx.Common.Helper { ObjectiveC.NSString nsStringPath = new(path); ObjectiveC.Object nsUrl = new("NSURL"); - var urlPtr = nsUrl.GetFromMessage("fileURLWithPath:", nsStringPath); + ObjectiveC.Object urlPtr = nsUrl.GetFromMessage("fileURLWithPath:", nsStringPath); ObjectiveC.Object nsArray = new("NSArray"); ObjectiveC.Object urlArray = nsArray.GetFromMessage("arrayWithObject:", urlPtr); @@ -99,7 +99,7 @@ namespace Ryujinx.Common.Helper { ObjectiveC.NSString nsStringPath = new(url); ObjectiveC.Object nsUrl = new("NSURL"); - var urlPtr = nsUrl.GetFromMessage("URLWithString:", nsStringPath); + ObjectiveC.Object urlPtr = nsUrl.GetFromMessage("URLWithString:", nsStringPath); ObjectiveC.Object nsWorkspace = new("NSWorkspace"); ObjectiveC.Object sharedWorkspace = nsWorkspace.GetFromMessage("sharedWorkspace"); diff --git a/src/Ryujinx.Common/Logging/Formatters/DynamicObjectFormatter.cs b/src/Ryujinx.Common/Logging/Formatters/DynamicObjectFormatter.cs index b1cc0eae3..a7b4da40f 100644 --- a/src/Ryujinx.Common/Logging/Formatters/DynamicObjectFormatter.cs +++ b/src/Ryujinx.Common/Logging/Formatters/DynamicObjectFormatter.cs @@ -41,7 +41,7 @@ namespace Ryujinx.Common.Logging.Formatters sb.Append('{'); - foreach (var prop in props) + foreach (PropertyInfo prop in props) { sb.Append(prop.Name); sb.Append(": "); @@ -52,7 +52,7 @@ namespace Ryujinx.Common.Logging.Formatters if (array is not null) { - foreach (var item in array) + foreach (object? item in array) { sb.Append(item); sb.Append(", "); diff --git a/src/Ryujinx.Common/Logging/Logger.cs b/src/Ryujinx.Common/Logging/Logger.cs index 6ea6b7ac3..0ac96c7d3 100644 --- a/src/Ryujinx.Common/Logging/Logger.cs +++ b/src/Ryujinx.Common/Logging/Logger.cs @@ -193,7 +193,7 @@ namespace Ryujinx.Common.Logging _stdErrAdapter.Dispose(); - foreach (var target in _logTargets) + foreach (ILogTarget target in _logTargets) { target.Dispose(); } @@ -203,9 +203,9 @@ namespace Ryujinx.Common.Logging public static IReadOnlyCollection GetEnabledLevels() { - var logs = new[] { Debug, Info, Warning, Error, Guest, AccessLog, Stub, Trace }; + Log?[] logs = new[] { Debug, Info, Warning, Error, Guest, AccessLog, Stub, Trace }; List levels = new(logs.Length); - foreach (var log in logs) + foreach (Log? log in logs) { if (log.HasValue) levels.Add(log.Value.Level); diff --git a/src/Ryujinx.Common/Logging/Targets/JsonLogTarget.cs b/src/Ryujinx.Common/Logging/Targets/JsonLogTarget.cs index c5bf23cdb..88b324a36 100644 --- a/src/Ryujinx.Common/Logging/Targets/JsonLogTarget.cs +++ b/src/Ryujinx.Common/Logging/Targets/JsonLogTarget.cs @@ -26,7 +26,7 @@ namespace Ryujinx.Common.Logging.Targets public void Log(object sender, LogEventArgs e) { - var logEventArgsJson = LogEventArgsJson.FromLogEventArgs(e); + LogEventArgsJson logEventArgsJson = LogEventArgsJson.FromLogEventArgs(e); JsonHelper.SerializeToStream(_stream, logEventArgsJson, LogEventJsonSerializerContext.Default.LogEventArgsJson); } diff --git a/src/Ryujinx.Common/Utilities/EmbeddedResources.cs b/src/Ryujinx.Common/Utilities/EmbeddedResources.cs index 7530c012a..107b4b584 100644 --- a/src/Ryujinx.Common/Utilities/EmbeddedResources.cs +++ b/src/Ryujinx.Common/Utilities/EmbeddedResources.cs @@ -19,21 +19,21 @@ namespace Ryujinx.Common public static byte[] Read(string filename) { - var (assembly, path) = ResolveManifestPath(filename); + (Assembly assembly, string path) = ResolveManifestPath(filename); return Read(assembly, path); } public static Task ReadAsync(string filename) { - var (assembly, path) = ResolveManifestPath(filename); + (Assembly assembly, string path) = ResolveManifestPath(filename); return ReadAsync(assembly, path); } public static byte[] Read(Assembly assembly, string filename) { - using var stream = GetStream(assembly, filename); + using Stream stream = GetStream(assembly, filename); if (stream == null) { return null; @@ -44,14 +44,14 @@ namespace Ryujinx.Common public static MemoryOwner ReadFileToRentedMemory(string filename) { - var (assembly, path) = ResolveManifestPath(filename); + (Assembly assembly, string path) = ResolveManifestPath(filename); return ReadFileToRentedMemory(assembly, path); } public static MemoryOwner ReadFileToRentedMemory(Assembly assembly, string filename) { - using var stream = GetStream(assembly, filename); + using Stream stream = GetStream(assembly, filename); return stream is null ? null @@ -60,7 +60,7 @@ namespace Ryujinx.Common public async static Task ReadAsync(Assembly assembly, string filename) { - using var stream = GetStream(assembly, filename); + using Stream stream = GetStream(assembly, filename); if (stream == null) { return null; @@ -71,55 +71,55 @@ namespace Ryujinx.Common public static string ReadAllText(string filename) { - var (assembly, path) = ResolveManifestPath(filename); + (Assembly assembly, string path) = ResolveManifestPath(filename); return ReadAllText(assembly, path); } public static Task ReadAllTextAsync(string filename) { - var (assembly, path) = ResolveManifestPath(filename); + (Assembly assembly, string path) = ResolveManifestPath(filename); return ReadAllTextAsync(assembly, path); } public static string ReadAllText(Assembly assembly, string filename) { - using var stream = GetStream(assembly, filename); + using Stream stream = GetStream(assembly, filename); if (stream == null) { return null; } - using var reader = new StreamReader(stream); + using StreamReader reader = new StreamReader(stream); return reader.ReadToEnd(); } public async static Task ReadAllTextAsync(Assembly assembly, string filename) { - using var stream = GetStream(assembly, filename); + using Stream stream = GetStream(assembly, filename); if (stream == null) { return null; } - using var reader = new StreamReader(stream); + using StreamReader reader = new StreamReader(stream); return await reader.ReadToEndAsync(); } public static Stream GetStream(string filename) { - var (assembly, path) = ResolveManifestPath(filename); + (Assembly assembly, string path) = ResolveManifestPath(filename); return GetStream(assembly, path); } public static Stream GetStream(Assembly assembly, string filename) { - var @namespace = assembly.GetName().Name; - var manifestUri = @namespace + "." + filename.Replace('/', '.'); + string @namespace = assembly.GetName().Name; + string manifestUri = @namespace + "." + filename.Replace('/', '.'); - var stream = assembly.GetManifestResourceStream(manifestUri); + Stream stream = assembly.GetManifestResourceStream(manifestUri); return stream; } @@ -133,11 +133,11 @@ namespace Ryujinx.Common private static (Assembly, string) ResolveManifestPath(string filename) { - var segments = filename.Split('/', 2, StringSplitOptions.RemoveEmptyEntries); + string[] segments = filename.Split('/', 2, StringSplitOptions.RemoveEmptyEntries); if (segments.Length >= 2) { - foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) + foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { if (assembly.GetName().Name == segments[0]) { diff --git a/src/Ryujinx.Common/Utilities/FileSystemUtils.cs b/src/Ryujinx.Common/Utilities/FileSystemUtils.cs index a57fa8a78..58bc80147 100644 --- a/src/Ryujinx.Common/Utilities/FileSystemUtils.cs +++ b/src/Ryujinx.Common/Utilities/FileSystemUtils.cs @@ -9,7 +9,7 @@ namespace Ryujinx.Common.Utilities public static void CopyDirectory(string sourceDir, string destinationDir, bool recursive) { // Get information about the source directory - var dir = new DirectoryInfo(sourceDir); + DirectoryInfo dir = new DirectoryInfo(sourceDir); // Check if the source directory exists if (!dir.Exists) @@ -49,7 +49,7 @@ namespace Ryujinx.Common.Utilities public static string SanitizeFileName(string fileName) { - var reservedChars = new HashSet(Path.GetInvalidFileNameChars()); + HashSet reservedChars = new HashSet(Path.GetInvalidFileNameChars()); return string.Concat(fileName.Select(c => reservedChars.Contains(c) ? '_' : c)); } } diff --git a/src/Ryujinx.Common/Utilities/MessagePackObjectFormatter.cs b/src/Ryujinx.Common/Utilities/MessagePackObjectFormatter.cs index 426cd46b7..6d5be656f 100644 --- a/src/Ryujinx.Common/Utilities/MessagePackObjectFormatter.cs +++ b/src/Ryujinx.Common/Utilities/MessagePackObjectFormatter.cs @@ -1,5 +1,6 @@ using MsgPack; using System; +using System.Collections.Generic; using System.Text; namespace Ryujinx.Common.Utilities @@ -18,7 +19,7 @@ namespace Ryujinx.Common.Utilities public static string Format(MessagePackObject obj) { - var builder = new IndentedStringBuilder(); + IndentedStringBuilder builder = new IndentedStringBuilder(); FormatMsgPackObj(obj, builder); @@ -41,7 +42,7 @@ namespace Ryujinx.Common.Utilities } else { - var literal = obj.ToObject(); + object literal = obj.ToObject(); if (literal is String) { @@ -88,7 +89,7 @@ namespace Ryujinx.Common.Utilities { builder.Append("[ "); - foreach (var b in arr) + foreach (byte b in arr) { builder.Append("0x"); builder.Append(ToHexChar(b >> 4)); @@ -111,7 +112,7 @@ namespace Ryujinx.Common.Utilities builder.Append("0x"); } - foreach (var b in arr) + foreach (byte b in arr) { builder.Append(ToHexChar(b >> 4)); builder.Append(ToHexChar(b & 0xF)); @@ -122,7 +123,7 @@ namespace Ryujinx.Common.Utilities private static void FormatMsgPackMap(MessagePackObject obj, IndentedStringBuilder builder) { - var map = obj.AsDictionary(); + MessagePackObjectDictionary map = obj.AsDictionary(); builder.Append('{'); @@ -130,7 +131,7 @@ namespace Ryujinx.Common.Utilities builder.IncreaseIndent() .AppendLine(); - foreach (var item in map) + foreach (KeyValuePair item in map) { FormatMsgPackObj(item.Key, builder); @@ -154,11 +155,11 @@ namespace Ryujinx.Common.Utilities private static void FormatMsgPackArray(MessagePackObject obj, IndentedStringBuilder builder) { - var arr = obj.AsList(); + IList arr = obj.AsList(); builder.Append("[ "); - foreach (var item in arr) + foreach (MessagePackObject item in arr) { FormatMsgPackObj(item, builder); diff --git a/src/Ryujinx.Common/Utilities/StreamUtils.cs b/src/Ryujinx.Common/Utilities/StreamUtils.cs index aeb6e0d52..60391a902 100644 --- a/src/Ryujinx.Common/Utilities/StreamUtils.cs +++ b/src/Ryujinx.Common/Utilities/StreamUtils.cs @@ -1,5 +1,6 @@ using Microsoft.IO; using Ryujinx.Common.Memory; +using System; using System.IO; using System.Threading; using System.Threading.Tasks; @@ -27,7 +28,7 @@ namespace Ryujinx.Common.Utilities MemoryOwner ownedMemory = MemoryOwner.Rent(checked((int)bytesExpected)); - var destSpan = ownedMemory.Span; + Span destSpan = ownedMemory.Span; int totalBytesRead = 0; diff --git a/src/Ryujinx.Common/Utilities/TypedStringEnumConverter.cs b/src/Ryujinx.Common/Utilities/TypedStringEnumConverter.cs index 9d3944c15..d7eb3d556 100644 --- a/src/Ryujinx.Common/Utilities/TypedStringEnumConverter.cs +++ b/src/Ryujinx.Common/Utilities/TypedStringEnumConverter.cs @@ -18,7 +18,7 @@ namespace Ryujinx.Common.Utilities { public override TEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - var enumValue = reader.GetString(); + string? enumValue = reader.GetString(); if (Enum.TryParse(enumValue, out TEnum value)) { diff --git a/src/Ryujinx.Common/Utilities/XCIFileTrimmer.cs b/src/Ryujinx.Common/Utilities/XCIFileTrimmer.cs index 050e78d1e..e92b5fe60 100644 --- a/src/Ryujinx.Common/Utilities/XCIFileTrimmer.cs +++ b/src/Ryujinx.Common/Utilities/XCIFileTrimmer.cs @@ -46,7 +46,7 @@ namespace Ryujinx.Common.Utilities { if (Path.GetExtension(filename).Equals(".XCI", StringComparison.InvariantCultureIgnoreCase)) { - var trimmer = new XCIFileTrimmer(filename, log); + XCIFileTrimmer trimmer = new XCIFileTrimmer(filename, log); return trimmer.CanBeTrimmed; } @@ -57,7 +57,7 @@ namespace Ryujinx.Common.Utilities { if (Path.GetExtension(filename).Equals(".XCI", StringComparison.InvariantCultureIgnoreCase)) { - var trimmer = new XCIFileTrimmer(filename, log); + XCIFileTrimmer trimmer = new XCIFileTrimmer(filename, log); return trimmer.CanBeUntrimmed; } @@ -201,7 +201,7 @@ namespace Ryujinx.Common.Utilities { long maxReads = readSizeB / XCIFileTrimmer.BufferSize; long read = 0; - var buffer = new byte[BufferSize]; + byte[] buffer = new byte[BufferSize]; while (true) { @@ -267,7 +267,7 @@ namespace Ryujinx.Common.Utilities try { - var info = new FileInfo(Filename); + FileInfo info = new FileInfo(Filename); if ((info.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { try @@ -288,7 +288,7 @@ namespace Ryujinx.Common.Utilities return OperationOutcome.FileSizeChanged; } - var outfileStream = new FileStream(_filename, FileMode.Open, FileAccess.Write, FileShare.Write); + FileStream outfileStream = new FileStream(_filename, FileMode.Open, FileAccess.Write, FileShare.Write); try { @@ -327,7 +327,7 @@ namespace Ryujinx.Common.Utilities { Log?.Write(LogType.Info, "Untrimming..."); - var info = new FileInfo(Filename); + FileInfo info = new FileInfo(Filename); if ((info.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { try @@ -348,7 +348,7 @@ namespace Ryujinx.Common.Utilities return OperationOutcome.FileSizeChanged; } - var outfileStream = new FileStream(_filename, FileMode.Append, FileAccess.Write, FileShare.Write); + FileStream outfileStream = new FileStream(_filename, FileMode.Append, FileAccess.Write, FileShare.Write); long bytesToWriteB = UntrimmedFileSizeB - FileSizeB; try @@ -393,7 +393,7 @@ namespace Ryujinx.Common.Utilities try { - var buffer = new byte[BufferSize]; + byte[] buffer = new byte[BufferSize]; Array.Fill(buffer, XCIFileTrimmer.PaddingByte); while (bytesLeftToWriteB > 0) From 5099548856181f839a7c3daee8c533d4fd2a9370 Mon Sep 17 00:00:00 2001 From: Evan Husted Date: Sat, 25 Jan 2025 14:04:43 -0600 Subject: [PATCH 05/19] misc: chore: Use explicit types in CPU project --- src/Ryujinx.Cpu/AddressTable.cs | 14 +++++++------- src/Ryujinx.Cpu/AppleHv/HvAddressSpace.cs | 2 +- src/Ryujinx.Cpu/AppleHv/HvMemoryBlockAllocator.cs | 2 +- src/Ryujinx.Cpu/AppleHv/HvMemoryManager.cs | 6 +++--- src/Ryujinx.Cpu/AppleHv/HvVcpu.cs | 2 +- src/Ryujinx.Cpu/AppleHv/HvVm.cs | 2 +- .../Jit/HostTracked/AddressSpacePartition.cs | 2 +- src/Ryujinx.Cpu/Jit/MemoryManager.cs | 6 +++--- src/Ryujinx.Cpu/Jit/MemoryManagerHostMapped.cs | 2 +- src/Ryujinx.Cpu/Jit/MemoryManagerHostTracked.cs | 4 ++-- .../Arm32/Target/Arm64/InstEmitFlow.cs | 2 +- .../Arm64/Target/Arm64/InstEmitSystem.cs | 2 +- src/Ryujinx.Cpu/LightningJit/Cache/NoWxCache.cs | 2 +- .../LightningJit/CodeGen/Arm64/Assembler.cs | 10 +++++----- src/Ryujinx.Cpu/LightningJit/Translator.cs | 4 ++-- src/Ryujinx.Cpu/LightningJit/TranslatorStubs.cs | 2 +- src/Ryujinx.Cpu/PrivateMemoryAllocator.cs | 14 +++++++------- src/Ryujinx.Cpu/Signal/NativeSignalHandler.cs | 2 +- 18 files changed, 40 insertions(+), 40 deletions(-) diff --git a/src/Ryujinx.Cpu/AddressTable.cs b/src/Ryujinx.Cpu/AddressTable.cs index 038a2009c..4015e0801 100644 --- a/src/Ryujinx.Cpu/AddressTable.cs +++ b/src/Ryujinx.Cpu/AddressTable.cs @@ -49,7 +49,7 @@ namespace ARMeilleure.Common public TableSparseBlock(ulong size, Action ensureMapped, PageInitDelegate pageInit) { - var block = new SparseMemoryBlock(size, pageInit, null); + SparseMemoryBlock block = new SparseMemoryBlock(size, pageInit, null); _trackingEvent = (ulong address, ulong size, bool write) => { @@ -146,7 +146,7 @@ namespace ARMeilleure.Common Levels = levels; Mask = 0; - foreach (var level in Levels) + foreach (AddressTableLevel level in Levels) { Mask |= level.Mask; } @@ -363,7 +363,7 @@ namespace ARMeilleure.Common /// The new sparse block that was added private TableSparseBlock ReserveNewSparseBlock() { - var block = new TableSparseBlock(_sparseBlockSize, EnsureMapped, InitLeafPage); + TableSparseBlock block = new TableSparseBlock(_sparseBlockSize, EnsureMapped, InitLeafPage); _sparseReserved.Add(block); _sparseReservedOffset = 0; @@ -381,7 +381,7 @@ namespace ARMeilleure.Common /// Allocated block private IntPtr Allocate(int length, T fill, bool leaf) where T : unmanaged { - var size = sizeof(T) * length; + int size = sizeof(T) * length; AddressTablePage page; @@ -413,10 +413,10 @@ namespace ARMeilleure.Common } else { - var address = (IntPtr)NativeAllocator.Instance.Allocate((uint)size); + IntPtr address = (IntPtr)NativeAllocator.Instance.Allocate((uint)size); page = new AddressTablePage(false, address); - var span = new Span((void*)page.Address, length); + Span span = new Span((void*)page.Address, length); span.Fill(fill); } @@ -445,7 +445,7 @@ namespace ARMeilleure.Common { if (!_disposed) { - foreach (var page in _pages) + foreach (AddressTablePage page in _pages) { if (!page.IsSparse) { diff --git a/src/Ryujinx.Cpu/AppleHv/HvAddressSpace.cs b/src/Ryujinx.Cpu/AppleHv/HvAddressSpace.cs index eb7c0ef08..662e50793 100644 --- a/src/Ryujinx.Cpu/AppleHv/HvAddressSpace.cs +++ b/src/Ryujinx.Cpu/AppleHv/HvAddressSpace.cs @@ -29,7 +29,7 @@ namespace Ryujinx.Cpu.AppleHv public HvAddressSpace(MemoryBlock backingMemory, ulong asSize) { - (_asBase, var ipaAllocator) = HvVm.CreateAddressSpace(backingMemory); + (_asBase, HvIpaAllocator ipaAllocator) = HvVm.CreateAddressSpace(backingMemory); _backingSize = backingMemory.Size; _userRange = new HvAddressSpaceRange(ipaAllocator); diff --git a/src/Ryujinx.Cpu/AppleHv/HvMemoryBlockAllocator.cs b/src/Ryujinx.Cpu/AppleHv/HvMemoryBlockAllocator.cs index 86936c592..779579e6a 100644 --- a/src/Ryujinx.Cpu/AppleHv/HvMemoryBlockAllocator.cs +++ b/src/Ryujinx.Cpu/AppleHv/HvMemoryBlockAllocator.cs @@ -45,7 +45,7 @@ namespace Ryujinx.Cpu.AppleHv public HvMemoryBlockAllocation Allocate(ulong size, ulong alignment) { - var allocation = Allocate(size, alignment, CreateBlock); + Allocation allocation = Allocate(size, alignment, CreateBlock); return new HvMemoryBlockAllocation(this, allocation.Block, allocation.Offset, allocation.Size); } diff --git a/src/Ryujinx.Cpu/AppleHv/HvMemoryManager.cs b/src/Ryujinx.Cpu/AppleHv/HvMemoryManager.cs index 74c39d6a8..28c78074d 100644 --- a/src/Ryujinx.Cpu/AppleHv/HvMemoryManager.cs +++ b/src/Ryujinx.Cpu/AppleHv/HvMemoryManager.cs @@ -233,13 +233,13 @@ namespace Ryujinx.Cpu.AppleHv yield break; } - var guestRegions = GetPhysicalRegionsImpl(va, size); + IEnumerable guestRegions = GetPhysicalRegionsImpl(va, size); if (guestRegions == null) { yield break; } - foreach (var guestRegion in guestRegions) + foreach (MemoryRange guestRegion in guestRegions) { nint pointer = _backingMemory.GetPointer(guestRegion.Address, guestRegion.Size); yield return new HostMemoryRange((nuint)(ulong)pointer, guestRegion.Size); @@ -254,7 +254,7 @@ namespace Ryujinx.Cpu.AppleHv yield break; } - foreach (var physicalRegion in GetPhysicalRegionsImpl(va, size)) + foreach (MemoryRange physicalRegion in GetPhysicalRegionsImpl(va, size)) { yield return physicalRegion; } diff --git a/src/Ryujinx.Cpu/AppleHv/HvVcpu.cs b/src/Ryujinx.Cpu/AppleHv/HvVcpu.cs index ee91c478b..c4eec31a6 100644 --- a/src/Ryujinx.Cpu/AppleHv/HvVcpu.cs +++ b/src/Ryujinx.Cpu/AppleHv/HvVcpu.cs @@ -41,7 +41,7 @@ namespace Ryujinx.Cpu.AppleHv { // Calculate our time delta in ticks based on the current clock frequency. - int result = TimeApi.mach_timebase_info(out var timeBaseInfo); + int result = TimeApi.mach_timebase_info(out MachTimebaseInfo timeBaseInfo); Debug.Assert(result == 0); diff --git a/src/Ryujinx.Cpu/AppleHv/HvVm.cs b/src/Ryujinx.Cpu/AppleHv/HvVm.cs index b4d45f36d..dc115f515 100644 --- a/src/Ryujinx.Cpu/AppleHv/HvVm.cs +++ b/src/Ryujinx.Cpu/AppleHv/HvVm.cs @@ -39,7 +39,7 @@ namespace Ryujinx.Cpu.AppleHv baseAddress = ipaAllocator.Allocate(block.Size, AsIpaAlignment); } - var rwx = HvMemoryFlags.Read | HvMemoryFlags.Write | HvMemoryFlags.Exec; + HvMemoryFlags rwx = HvMemoryFlags.Read | HvMemoryFlags.Write | HvMemoryFlags.Exec; HvApi.hv_vm_map((ulong)block.Pointer, baseAddress, block.Size, rwx).ThrowOnError(); diff --git a/src/Ryujinx.Cpu/Jit/HostTracked/AddressSpacePartition.cs b/src/Ryujinx.Cpu/Jit/HostTracked/AddressSpacePartition.cs index f9743a0a1..9ee2d58e6 100644 --- a/src/Ryujinx.Cpu/Jit/HostTracked/AddressSpacePartition.cs +++ b/src/Ryujinx.Cpu/Jit/HostTracked/AddressSpacePartition.cs @@ -127,7 +127,7 @@ namespace Ryujinx.Cpu.Jit.HostTracked Debug.Assert(leftSize > 0); Debug.Assert(rightSize > 0); - (var leftAllocation, PrivateAllocation) = PrivateAllocation.Split(leftSize); + (PrivateMemoryAllocation leftAllocation, PrivateAllocation) = PrivateAllocation.Split(leftSize); PrivateMapping left = new(Address, leftSize, leftAllocation); diff --git a/src/Ryujinx.Cpu/Jit/MemoryManager.cs b/src/Ryujinx.Cpu/Jit/MemoryManager.cs index 076fb6ad8..2635a2c7d 100644 --- a/src/Ryujinx.Cpu/Jit/MemoryManager.cs +++ b/src/Ryujinx.Cpu/Jit/MemoryManager.cs @@ -253,13 +253,13 @@ namespace Ryujinx.Cpu.Jit yield break; } - var guestRegions = GetPhysicalRegionsImpl(va, size); + IEnumerable guestRegions = GetPhysicalRegionsImpl(va, size); if (guestRegions == null) { yield break; } - foreach (var guestRegion in guestRegions) + foreach (MemoryRange guestRegion in guestRegions) { nint pointer = _backingMemory.GetPointer(guestRegion.Address, guestRegion.Size); yield return new HostMemoryRange((nuint)(ulong)pointer, guestRegion.Size); @@ -274,7 +274,7 @@ namespace Ryujinx.Cpu.Jit yield break; } - foreach (var physicalRegion in GetPhysicalRegionsImpl(va, size)) + foreach (MemoryRange physicalRegion in GetPhysicalRegionsImpl(va, size)) { yield return physicalRegion; } diff --git a/src/Ryujinx.Cpu/Jit/MemoryManagerHostMapped.cs b/src/Ryujinx.Cpu/Jit/MemoryManagerHostMapped.cs index 0fe8b344f..146805982 100644 --- a/src/Ryujinx.Cpu/Jit/MemoryManagerHostMapped.cs +++ b/src/Ryujinx.Cpu/Jit/MemoryManagerHostMapped.cs @@ -340,7 +340,7 @@ namespace Ryujinx.Cpu.Jit { int pages = GetPagesCount(va, (uint)size, out va); - var regions = new List(); + List regions = new List(); ulong regionStart = GetPhysicalAddressChecked(va); ulong regionSize = PageSize; diff --git a/src/Ryujinx.Cpu/Jit/MemoryManagerHostTracked.cs b/src/Ryujinx.Cpu/Jit/MemoryManagerHostTracked.cs index 499f991f2..d802f5046 100644 --- a/src/Ryujinx.Cpu/Jit/MemoryManagerHostTracked.cs +++ b/src/Ryujinx.Cpu/Jit/MemoryManagerHostTracked.cs @@ -240,7 +240,7 @@ namespace Ryujinx.Cpu.Jit if (TryGetVirtualContiguous(va, data.Length, out MemoryBlock memoryBlock, out ulong offset)) { - var target = memoryBlock.GetSpan(offset, data.Length); + Span target = memoryBlock.GetSpan(offset, data.Length); bool changed = !data.SequenceEqual(target); @@ -443,7 +443,7 @@ namespace Ryujinx.Cpu.Jit return null; } - var regions = new List(); + List regions = new List(); ulong endVa = va + size; try diff --git a/src/Ryujinx.Cpu/LightningJit/Arm32/Target/Arm64/InstEmitFlow.cs b/src/Ryujinx.Cpu/LightningJit/Arm32/Target/Arm64/InstEmitFlow.cs index 48bdbb573..6a8c2abdd 100644 --- a/src/Ryujinx.Cpu/LightningJit/Arm32/Target/Arm64/InstEmitFlow.cs +++ b/src/Ryujinx.Cpu/LightningJit/Arm32/Target/Arm64/InstEmitFlow.cs @@ -205,7 +205,7 @@ namespace Ryujinx.Cpu.LightningJit.Arm32.Target.Arm64 for (int i = 0; i < funcTable.Levels.Length; i++) { - var level = funcTable.Levels[i]; + AddressTableLevel level = funcTable.Levels[i]; asm.Ubfx(indexReg, guestAddress, level.Index, level.Length); asm.Lsl(indexReg, indexReg, Const(3)); diff --git a/src/Ryujinx.Cpu/LightningJit/Arm64/Target/Arm64/InstEmitSystem.cs b/src/Ryujinx.Cpu/LightningJit/Arm64/Target/Arm64/InstEmitSystem.cs index bf9338400..98939839c 100644 --- a/src/Ryujinx.Cpu/LightningJit/Arm64/Target/Arm64/InstEmitSystem.cs +++ b/src/Ryujinx.Cpu/LightningJit/Arm64/Target/Arm64/InstEmitSystem.cs @@ -370,7 +370,7 @@ namespace Ryujinx.Cpu.LightningJit.Arm64.Target.Arm64 for (int i = 0; i < funcTable.Levels.Length; i++) { - var level = funcTable.Levels[i]; + AddressTableLevel level = funcTable.Levels[i]; asm.Ubfx(indexReg, guestAddress, level.Index, level.Length); asm.Lsl(indexReg, indexReg, Const(3)); diff --git a/src/Ryujinx.Cpu/LightningJit/Cache/NoWxCache.cs b/src/Ryujinx.Cpu/LightningJit/Cache/NoWxCache.cs index e9a342aba..a743710e9 100644 --- a/src/Ryujinx.Cpu/LightningJit/Cache/NoWxCache.cs +++ b/src/Ryujinx.Cpu/LightningJit/Cache/NoWxCache.cs @@ -190,7 +190,7 @@ namespace Ryujinx.Cpu.LightningJit.Cache private bool TryGetThreadLocalFunction(ulong guestAddress, out nint funcPtr) { - if ((_threadLocalCache ??= new()).TryGetValue(guestAddress, out var entry)) + if ((_threadLocalCache ??= new()).TryGetValue(guestAddress, out ThreadLocalCacheEntry entry)) { if (entry.IncrementUseCount() >= MinCallsForPad) { diff --git a/src/Ryujinx.Cpu/LightningJit/CodeGen/Arm64/Assembler.cs b/src/Ryujinx.Cpu/LightningJit/CodeGen/Arm64/Assembler.cs index 28539707f..340ae43d1 100644 --- a/src/Ryujinx.Cpu/LightningJit/CodeGen/Arm64/Assembler.cs +++ b/src/Ryujinx.Cpu/LightningJit/CodeGen/Arm64/Assembler.cs @@ -41,7 +41,7 @@ namespace Ryujinx.Cpu.LightningJit.CodeGen.Arm64 { int targetIndex = _code.Count; - var state = _labels[label.AsInt32()]; + LabelState state = _labels[label.AsInt32()]; state.TargetIndex = targetIndex; state.HasTarget = true; @@ -68,7 +68,7 @@ namespace Ryujinx.Cpu.LightningJit.CodeGen.Arm64 { int branchIndex = _code.Count; - var state = _labels[label.AsInt32()]; + LabelState state = _labels[label.AsInt32()]; state.BranchIndex = branchIndex; state.HasBranch = true; @@ -94,7 +94,7 @@ namespace Ryujinx.Cpu.LightningJit.CodeGen.Arm64 { int branchIndex = _code.Count; - var state = _labels[label.AsInt32()]; + LabelState state = _labels[label.AsInt32()]; state.BranchIndex = branchIndex; state.HasBranch = true; @@ -113,7 +113,7 @@ namespace Ryujinx.Cpu.LightningJit.CodeGen.Arm64 { int branchIndex = _code.Count; - var state = _labels[label.AsInt32()]; + LabelState state = _labels[label.AsInt32()]; state.BranchIndex = branchIndex; state.HasBranch = true; @@ -342,7 +342,7 @@ namespace Ryujinx.Cpu.LightningJit.CodeGen.Arm64 public readonly void Cset(Operand rd, ArmCondition condition) { - var zr = new Operand(ZrRegister, RegisterType.Integer, rd.Type); + Operand zr = new Operand(ZrRegister, RegisterType.Integer, rd.Type); Csinc(rd, zr, zr, (ArmCondition)((int)condition ^ 1)); } diff --git a/src/Ryujinx.Cpu/LightningJit/Translator.cs b/src/Ryujinx.Cpu/LightningJit/Translator.cs index 4c4011f11..22a38ca99 100644 --- a/src/Ryujinx.Cpu/LightningJit/Translator.cs +++ b/src/Ryujinx.Cpu/LightningJit/Translator.cs @@ -163,14 +163,14 @@ namespace Ryujinx.Cpu.LightningJit { List functions = Functions.AsList(); - foreach (var func in functions) + foreach (TranslatedFunction func in functions) { JitCache.Unmap(func.FuncPointer); } Functions.Clear(); - while (_oldFuncs.TryDequeue(out var kv)) + while (_oldFuncs.TryDequeue(out KeyValuePair kv)) { JitCache.Unmap(kv.Value.FuncPointer); } diff --git a/src/Ryujinx.Cpu/LightningJit/TranslatorStubs.cs b/src/Ryujinx.Cpu/LightningJit/TranslatorStubs.cs index c5231e506..6ef653a37 100644 --- a/src/Ryujinx.Cpu/LightningJit/TranslatorStubs.cs +++ b/src/Ryujinx.Cpu/LightningJit/TranslatorStubs.cs @@ -174,7 +174,7 @@ namespace Ryujinx.Cpu.LightningJit for (int i = 0; i < _functionTable.Levels.Length; i++) { - ref var level = ref _functionTable.Levels[i]; + ref AddressTableLevel level = ref _functionTable.Levels[i]; asm.Mov(mask, level.Mask >> level.Index); asm.And(index, mask, guestAddress, ArmShiftType.Lsr, level.Index); diff --git a/src/Ryujinx.Cpu/PrivateMemoryAllocator.cs b/src/Ryujinx.Cpu/PrivateMemoryAllocator.cs index 8db74f1e9..99528b576 100644 --- a/src/Ryujinx.Cpu/PrivateMemoryAllocator.cs +++ b/src/Ryujinx.Cpu/PrivateMemoryAllocator.cs @@ -48,7 +48,7 @@ namespace Ryujinx.Cpu { for (int i = 0; i < _freeRanges.Count; i++) { - var range = _freeRanges[i]; + Range range = _freeRanges[i]; ulong alignedOffset = BitUtils.AlignUp(range.Offset, alignment); ulong sizeDelta = alignedOffset - range.Offset; @@ -84,7 +84,7 @@ namespace Ryujinx.Cpu private void InsertFreeRange(ulong offset, ulong size) { - var range = new Range(offset, size); + Range range = new Range(offset, size); int index = _freeRanges.BinarySearch(range); if (index < 0) { @@ -97,7 +97,7 @@ namespace Ryujinx.Cpu private void InsertFreeRangeComingled(ulong offset, ulong size) { ulong endOffset = offset + size; - var range = new Range(offset, size); + Range range = new Range(offset, size); int index = _freeRanges.BinarySearch(range); if (index < 0) { @@ -149,7 +149,7 @@ namespace Ryujinx.Cpu public PrivateMemoryAllocation Allocate(ulong size, ulong alignment) { - var allocation = Allocate(size, alignment, CreateBlock); + Allocation allocation = Allocate(size, alignment, CreateBlock); return new PrivateMemoryAllocation(this, allocation.Block, allocation.Offset, allocation.Size); } @@ -200,7 +200,7 @@ namespace Ryujinx.Cpu for (int i = 0; i < _blocks.Count; i++) { - var block = _blocks[i]; + T block = _blocks[i]; if (block.Size >= size) { @@ -214,8 +214,8 @@ namespace Ryujinx.Cpu ulong blockAlignedSize = BitUtils.AlignUp(size, _blockAlignment); - var memory = new MemoryBlock(blockAlignedSize, _allocationFlags); - var newBlock = createBlock(memory, blockAlignedSize); + MemoryBlock memory = new MemoryBlock(blockAlignedSize, _allocationFlags); + T newBlock = createBlock(memory, blockAlignedSize); InsertBlock(newBlock); diff --git a/src/Ryujinx.Cpu/Signal/NativeSignalHandler.cs b/src/Ryujinx.Cpu/Signal/NativeSignalHandler.cs index 75a6d3bf8..299adfbbd 100644 --- a/src/Ryujinx.Cpu/Signal/NativeSignalHandler.cs +++ b/src/Ryujinx.Cpu/Signal/NativeSignalHandler.cs @@ -98,7 +98,7 @@ namespace Ryujinx.Cpu.Signal _signalHandlerPtr = customSignalHandlerFactory(UnixSignalHandlerRegistration.GetSegfaultExceptionHandler().sa_handler, _signalHandlerPtr); } - var old = UnixSignalHandlerRegistration.RegisterExceptionHandler(_signalHandlerPtr); + UnixSignalHandlerRegistration.SigAction old = UnixSignalHandlerRegistration.RegisterExceptionHandler(_signalHandlerPtr); config.UnixOldSigaction = (nuint)(ulong)old.sa_handler; config.UnixOldSigaction3Arg = old.sa_flags & 4; From 1ae349efb15dbde21affcfa8f2648f38a87eb238 Mon Sep 17 00:00:00 2001 From: Evan Husted Date: Sat, 25 Jan 2025 14:05:44 -0600 Subject: [PATCH 06/19] misc: chore: Use explicit types in GPU, Device, and Host1x projects --- src/Ryujinx.Graphics.Device/DeviceState.cs | 15 ++-- .../Engine/Compute/ComputeClass.cs | 5 +- .../Engine/DeviceStateWithShadow.cs | 2 +- .../Engine/Dma/DmaClass.cs | 16 ++-- .../Engine/GPFifo/GPFifoProcessor.cs | 2 +- .../InlineToMemory/InlineToMemoryClass.cs | 11 +-- .../Engine/MME/MacroHLE.cs | 64 +++++++-------- .../Engine/MME/MacroHLETable.cs | 6 +- .../Engine/MME/MacroInterpreter.cs | 2 +- .../Engine/MME/MacroJitContext.cs | 2 +- .../Threed/Blender/AdvancedBlendFunctions.cs | 2 +- .../Threed/Blender/AdvancedBlendManager.cs | 2 +- .../Threed/ComputeDraw/VtgAsComputeContext.cs | 4 +- .../Threed/ComputeDraw/VtgAsComputeState.cs | 8 +- .../Engine/Threed/ConstantBufferUpdater.cs | 9 ++- .../Engine/Threed/DrawManager.cs | 16 ++-- .../Threed/SpecializationStateUpdater.cs | 2 +- .../Engine/Threed/StateUpdateTracker.cs | 15 ++-- .../Engine/Threed/StateUpdater.cs | 77 ++++++++++--------- .../Engine/Threed/ThreedClass.cs | 40 +++++----- .../Engine/Twod/TwodClass.cs | 21 ++--- src/Ryujinx.Graphics.Gpu/GpuChannel.cs | 6 +- src/Ryujinx.Graphics.Gpu/GpuContext.cs | 18 ++--- .../Image/AutoDeleteCache.cs | 12 +-- src/Ryujinx.Graphics.Gpu/Image/FormatTable.cs | 2 +- src/Ryujinx.Graphics.Gpu/Image/Texture.cs | 10 +-- .../Image/TextureCache.cs | 10 +-- .../Image/TextureGroup.cs | 44 +++++------ src/Ryujinx.Graphics.Gpu/Image/TexturePool.cs | 6 +- src/Ryujinx.Graphics.Gpu/Memory/Buffer.cs | 8 +- .../Memory/BufferBackingState.cs | 4 +- .../Memory/BufferCache.cs | 4 +- .../Memory/BufferManager.cs | 38 ++++----- .../Memory/BufferModifiedRangeList.cs | 10 +-- .../Memory/BufferUpdater.cs | 2 +- .../Memory/GpuRegionHandle.cs | 12 +-- .../Memory/MemoryManager.cs | 2 +- .../Memory/MultiRangeBuffer.cs | 4 +- .../Memory/PhysicalMemory.cs | 18 ++--- .../Memory/SupportBufferUpdater.cs | 2 +- .../Shader/CachedShaderBindings.cs | 4 +- .../Shader/ComputeShaderCacheHashTable.cs | 6 +- .../Shader/DiskCache/DiskCacheGuestStorage.cs | 14 ++-- .../Shader/DiskCache/DiskCacheHostStorage.cs | 44 +++++------ .../DiskCache/ParallelDiskCacheLoader.cs | 4 +- .../Shader/GpuAccessor.cs | 3 +- .../Shader/ShaderCache.cs | 22 +++--- .../Shader/ShaderCacheHashTable.cs | 8 +- .../Shader/ShaderInfoBuilder.cs | 4 +- .../Shader/ShaderSpecializationList.cs | 4 +- .../Shader/ShaderSpecializationState.cs | 34 ++++---- .../Synchronization/SynchronizationManager.cs | 2 +- src/Ryujinx.Graphics.Gpu/Window.cs | 3 +- src/Ryujinx.Graphics.Host1x/Devices.cs | 2 +- src/Ryujinx.Graphics.Host1x/Host1xDevice.cs | 2 +- 55 files changed, 350 insertions(+), 339 deletions(-) diff --git a/src/Ryujinx.Graphics.Device/DeviceState.cs b/src/Ryujinx.Graphics.Device/DeviceState.cs index 0dd4f5904..11d8e3ac2 100644 --- a/src/Ryujinx.Graphics.Device/DeviceState.cs +++ b/src/Ryujinx.Graphics.Device/DeviceState.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -32,15 +33,15 @@ namespace Ryujinx.Graphics.Device _debugLogCallback = debugLogCallback; } - var fields = typeof(TState).GetFields(); + FieldInfo[] fields = typeof(TState).GetFields(); int offset = 0; for (int fieldIndex = 0; fieldIndex < fields.Length; fieldIndex++) { - var field = fields[fieldIndex]; + FieldInfo field = fields[fieldIndex]; - var currentFieldOffset = (int)Marshal.OffsetOf(field.Name); - var nextFieldOffset = fieldIndex + 1 == fields.Length ? Unsafe.SizeOf() : (int)Marshal.OffsetOf(fields[fieldIndex + 1].Name); + int currentFieldOffset = (int)Marshal.OffsetOf(field.Name); + int nextFieldOffset = fieldIndex + 1 == fields.Length ? Unsafe.SizeOf() : (int)Marshal.OffsetOf(fields[fieldIndex + 1].Name); int sizeOfField = nextFieldOffset - currentFieldOffset; @@ -48,7 +49,7 @@ namespace Ryujinx.Graphics.Device { int index = (offset + i) / RegisterSize; - if (callbacks != null && callbacks.TryGetValue(field.Name, out var cb)) + if (callbacks != null && callbacks.TryGetValue(field.Name, out RwCallback cb)) { if (cb.Read != null) { @@ -81,7 +82,7 @@ namespace Ryujinx.Graphics.Device { uint alignedOffset = index * RegisterSize; - var readCallback = Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(_readCallbacks), (nint)index); + Func readCallback = Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(_readCallbacks), (nint)index); if (readCallback != null) { return readCallback(); @@ -119,7 +120,7 @@ namespace Ryujinx.Graphics.Device uint alignedOffset = index * RegisterSize; DebugWrite(alignedOffset, data); - ref var storage = ref GetRefIntAlignedUncheck(index); + ref int storage = ref GetRefIntAlignedUncheck(index); changed = storage != data; storage = data; diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Compute/ComputeClass.cs b/src/Ryujinx.Graphics.Gpu/Engine/Compute/ComputeClass.cs index cd8144724..0784fdca8 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Compute/ComputeClass.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Compute/ComputeClass.cs @@ -2,6 +2,7 @@ using Ryujinx.Graphics.Device; using Ryujinx.Graphics.Gpu.Engine.InlineToMemory; using Ryujinx.Graphics.Gpu.Engine.Threed; using Ryujinx.Graphics.Gpu.Engine.Types; +using Ryujinx.Graphics.Gpu.Memory; using Ryujinx.Graphics.Gpu.Shader; using Ryujinx.Graphics.Shader; using System; @@ -90,7 +91,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute /// Method call argument private void SendSignalingPcasB(int argument) { - var memoryManager = _channel.MemoryManager; + MemoryManager memoryManager = _channel.MemoryManager; // Since we're going to change the state, make sure any pending instanced draws are done. _3dEngine.PerformDeferredDraws(); @@ -100,7 +101,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Compute uint qmdAddress = _state.State.SendPcasA; - var qmd = _channel.MemoryManager.Read((ulong)qmdAddress << 8); + ComputeQmd qmd = _channel.MemoryManager.Read((ulong)qmdAddress << 8); ulong shaderGpuVa = ((ulong)_state.State.SetProgramRegionAAddressUpper << 32) | _state.State.SetProgramRegionB; diff --git a/src/Ryujinx.Graphics.Gpu/Engine/DeviceStateWithShadow.cs b/src/Ryujinx.Graphics.Gpu/Engine/DeviceStateWithShadow.cs index a2e5b1164..ccfba79a4 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/DeviceStateWithShadow.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/DeviceStateWithShadow.cs @@ -80,7 +80,7 @@ namespace Ryujinx.Graphics.Gpu.Engine [MethodImpl(MethodImplOptions.AggressiveInlining)] public void WriteWithRedundancyCheck(int offset, int value, out bool changed) { - var shadowRamControl = _state.State.SetMmeShadowRamControlMode; + SetMmeShadowRamControlMode shadowRamControl = _state.State.SetMmeShadowRamControlMode; if (shadowRamControl == SetMmeShadowRamControlMode.MethodPassthrough || offset < 0x200) { _state.WriteWithRedundancyCheck(offset, value, out changed); diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Dma/DmaClass.cs b/src/Ryujinx.Graphics.Gpu/Engine/Dma/DmaClass.cs index cdeae0040..4ee15dfef 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Dma/DmaClass.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Dma/DmaClass.cs @@ -190,7 +190,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Dma /// The LaunchDma call argument private void DmaCopy(int argument) { - var memoryManager = _channel.MemoryManager; + MemoryManager memoryManager = _channel.MemoryManager; CopyFlags copyFlags = (CopyFlags)argument; @@ -225,8 +225,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Dma int srcBpp = remap ? srcComponents * componentSize : 1; int dstBpp = remap ? dstComponents * componentSize : 1; - var dst = Unsafe.As(ref _state.State.SetDstBlockSize); - var src = Unsafe.As(ref _state.State.SetSrcBlockSize); + DmaTexture dst = Unsafe.As(ref _state.State.SetDstBlockSize); + DmaTexture src = Unsafe.As(ref _state.State.SetSrcBlockSize); int srcRegionX = 0, srcRegionY = 0, dstRegionX = 0, dstRegionY = 0; @@ -245,7 +245,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Dma int srcStride = (int)_state.State.PitchIn; int dstStride = (int)_state.State.PitchOut; - var srcCalculator = new OffsetCalculator( + OffsetCalculator srcCalculator = new OffsetCalculator( src.Width, src.Height, srcStride, @@ -254,7 +254,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Dma src.MemoryLayout.UnpackGobBlocksInZ(), srcBpp); - var dstCalculator = new OffsetCalculator( + OffsetCalculator dstCalculator = new OffsetCalculator( dst.Width, dst.Height, dstStride, @@ -293,7 +293,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Dma if (completeSource && completeDest && !srcLinear && isIdentityRemap) { - var source = memoryManager.Physical.TextureCache.FindTexture( + Image.Texture source = memoryManager.Physical.TextureCache.FindTexture( memoryManager, srcGpuVa, srcBpp, @@ -309,7 +309,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Dma { source.SynchronizeMemory(); - var target = memoryManager.Physical.TextureCache.FindOrCreateTexture( + Image.Texture target = memoryManager.Physical.TextureCache.FindOrCreateTexture( memoryManager, source.Info.FormatInfo, dstGpuVa, @@ -339,7 +339,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Dma if (completeSource && completeDest && !(dstLinear && !srcLinear) && isIdentityRemap) { - var target = memoryManager.Physical.TextureCache.FindTexture( + Image.Texture target = memoryManager.Physical.TextureCache.FindTexture( memoryManager, dstGpuVa, dstBpp, diff --git a/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPFifoProcessor.cs b/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPFifoProcessor.cs index 984a9cff8..c0f8ccf76 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPFifoProcessor.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/GPFifo/GPFifoProcessor.cs @@ -159,7 +159,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.GPFifo int availableCount = commandBuffer.Length - offset; int consumeCount = Math.Min(_state.MethodCount, availableCount); - var data = commandBuffer.Slice(offset, consumeCount); + ReadOnlySpan data = commandBuffer.Slice(offset, consumeCount); if (_state.SubChannel == 0) { diff --git a/src/Ryujinx.Graphics.Gpu/Engine/InlineToMemory/InlineToMemoryClass.cs b/src/Ryujinx.Graphics.Gpu/Engine/InlineToMemory/InlineToMemoryClass.cs index 78099f74a..aad97ad81 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/InlineToMemory/InlineToMemoryClass.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/InlineToMemory/InlineToMemoryClass.cs @@ -1,6 +1,7 @@ using Ryujinx.Common; using Ryujinx.Common.Memory; using Ryujinx.Graphics.Device; +using Ryujinx.Graphics.Gpu.Memory; using Ryujinx.Graphics.Texture; using System; using System.Collections.Generic; @@ -168,9 +169,9 @@ namespace Ryujinx.Graphics.Gpu.Engine.InlineToMemory /// private void FinishTransfer() { - var memoryManager = _channel.MemoryManager; + MemoryManager memoryManager = _channel.MemoryManager; - var data = MemoryMarshal.Cast(_buffer)[.._size]; + Span data = MemoryMarshal.Cast(_buffer)[.._size]; if (_isLinear && _lineCount == 1) { @@ -184,7 +185,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.InlineToMemory // Right now the copy code at the bottom assumes that it is used on both which might be incorrect. if (!_isLinear) { - var target = memoryManager.Physical.TextureCache.FindTexture( + Image.Texture target = memoryManager.Physical.TextureCache.FindTexture( memoryManager, _dstGpuVa, 1, @@ -199,7 +200,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.InlineToMemory if (target != null) { target.SynchronizeMemory(); - var dataCopy = MemoryOwner.RentCopy(data); + MemoryOwner dataCopy = MemoryOwner.RentCopy(data); target.SetData(dataCopy, 0, 0, new GAL.Rectangle(_dstX, _dstY, _lineLengthIn / target.Info.FormatInfo.BytesPerPixel, _lineCount)); target.SignalModified(); @@ -207,7 +208,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.InlineToMemory } } - var dstCalculator = new OffsetCalculator( + OffsetCalculator dstCalculator = new OffsetCalculator( _dstWidth, _dstHeight, _dstStride, diff --git a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLE.cs b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLE.cs index 475d1ee4e..f62a4c01a 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLE.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLE.cs @@ -285,12 +285,12 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME /// First argument of the call private void DrawArraysInstanced(IDeviceState state, int arg0) { - var topology = (PrimitiveTopology)arg0; + PrimitiveTopology topology = (PrimitiveTopology)arg0; - var count = FetchParam(); - var instanceCount = FetchParam(); - var firstVertex = FetchParam(); - var firstInstance = FetchParam(); + FifoWord count = FetchParam(); + FifoWord instanceCount = FetchParam(); + FifoWord firstVertex = FetchParam(); + FifoWord firstInstance = FetchParam(); if (ShouldSkipDraw(state, instanceCount.Word)) { @@ -314,13 +314,13 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME /// First argument of the call private void DrawElements(IDeviceState state, int arg0) { - var topology = (PrimitiveTopology)arg0; + PrimitiveTopology topology = (PrimitiveTopology)arg0; - var indexAddressHigh = FetchParam(); - var indexAddressLow = FetchParam(); - var indexType = FetchParam(); - var firstIndex = 0; - var indexCount = FetchParam(); + FifoWord indexAddressHigh = FetchParam(); + FifoWord indexAddressLow = FetchParam(); + FifoWord indexType = FetchParam(); + int firstIndex = 0; + FifoWord indexCount = FetchParam(); _processor.ThreedClass.UpdateIndexBuffer( (uint)indexAddressHigh.Word, @@ -344,13 +344,13 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME /// First argument of the call private void DrawElementsInstanced(IDeviceState state, int arg0) { - var topology = (PrimitiveTopology)arg0; + PrimitiveTopology topology = (PrimitiveTopology)arg0; - var count = FetchParam(); - var instanceCount = FetchParam(); - var firstIndex = FetchParam(); - var firstVertex = FetchParam(); - var firstInstance = FetchParam(); + FifoWord count = FetchParam(); + FifoWord instanceCount = FetchParam(); + FifoWord firstIndex = FetchParam(); + FifoWord firstVertex = FetchParam(); + FifoWord firstInstance = FetchParam(); if (ShouldSkipDraw(state, instanceCount.Word)) { @@ -374,17 +374,17 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME /// First argument of the call private void DrawElementsIndirect(IDeviceState state, int arg0) { - var topology = (PrimitiveTopology)arg0; + PrimitiveTopology topology = (PrimitiveTopology)arg0; - var count = FetchParam(); - var instanceCount = FetchParam(); - var firstIndex = FetchParam(); - var firstVertex = FetchParam(); - var firstInstance = FetchParam(); + FifoWord count = FetchParam(); + FifoWord instanceCount = FetchParam(); + FifoWord firstIndex = FetchParam(); + FifoWord firstVertex = FetchParam(); + FifoWord firstInstance = FetchParam(); ulong indirectBufferGpuVa = count.GpuVa; - var bufferCache = _processor.MemoryManager.Physical.BufferCache; + BufferCache bufferCache = _processor.MemoryManager.Physical.BufferCache; bool useBuffer = bufferCache.CheckModified(_processor.MemoryManager, indirectBufferGpuVa, IndirectIndexedDataEntrySize, out ulong indirectBufferAddress); @@ -432,7 +432,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME int startDraw = arg0; int endDraw = arg1; - var topology = (PrimitiveTopology)arg2; + PrimitiveTopology topology = (PrimitiveTopology)arg2; int paddingWords = arg3; int stride = paddingWords * 4 + 0x14; @@ -468,12 +468,12 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME for (int i = 0; i < maxDrawCount; i++) { - var count = FetchParam(); + FifoWord count = FetchParam(); #pragma warning disable IDE0059 // Remove unnecessary value assignment - var instanceCount = FetchParam(); - var firstIndex = FetchParam(); - var firstVertex = FetchParam(); - var firstInstance = FetchParam(); + FifoWord instanceCount = FetchParam(); + FifoWord firstIndex = FetchParam(); + FifoWord firstVertex = FetchParam(); + FifoWord firstInstance = FetchParam(); #pragma warning restore IDE0059 if (i == 0) @@ -492,7 +492,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME } } - var bufferCache = _processor.MemoryManager.Physical.BufferCache; + BufferCache bufferCache = _processor.MemoryManager.Physical.BufferCache; ulong indirectBufferSize = (ulong)maxDrawCount * (ulong)stride; @@ -526,7 +526,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME /// The call argument, or a 0 value with null address if the FIFO is empty private FifoWord FetchParam() { - if (!Fifo.TryDequeue(out var value)) + if (!Fifo.TryDequeue(out FifoWord value)) { Logger.Warning?.Print(LogClass.Gpu, "Macro attempted to fetch an inexistent argument."); diff --git a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLETable.cs b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLETable.cs index e3080228e..1df68a50f 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLETable.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroHLETable.cs @@ -90,13 +90,13 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME /// True if there is a implementation available and supported, false otherwise public static bool TryGetMacroHLEFunction(ReadOnlySpan code, Capabilities caps, out MacroHLEFunctionName name) { - var mc = MemoryMarshal.Cast(code); + ReadOnlySpan mc = MemoryMarshal.Cast(code); for (int i = 0; i < _table.Length; i++) { - ref var entry = ref _table[i]; + ref TableEntry entry = ref _table[i]; - var hash = Hash128.ComputeHash(mc[..entry.Length]); + Hash128 hash = Hash128.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 dd60688d6..707265184 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroInterpreter.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroInterpreter.cs @@ -369,7 +369,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME /// The call argument, or 0 if the FIFO is empty private int FetchParam() { - if (!Fifo.TryDequeue(out var value)) + if (!Fifo.TryDequeue(out FifoWord value)) { Logger.Warning?.Print(LogClass.Gpu, "Macro attempted to fetch an inexistent argument."); diff --git a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroJitContext.cs b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroJitContext.cs index 01bff8e89..174af9739 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroJitContext.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/MME/MacroJitContext.cs @@ -20,7 +20,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.MME /// The call argument, or 0 if the FIFO is empty public int FetchParam() { - if (!Fifo.TryDequeue(out var value)) + if (!Fifo.TryDequeue(out FifoWord value)) { Logger.Warning?.Print(LogClass.Gpu, "Macro attempted to fetch an inexistent argument."); diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendFunctions.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendFunctions.cs index 13e5d2a86..020db62be 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendFunctions.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendFunctions.cs @@ -221,7 +221,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.Blender sb.AppendLine($"private static Dictionary _entries = new()"); sb.AppendLine("{"); - foreach (var entry in Table) + foreach (AdvancedBlendUcode entry in Table) { Hash128 hash = Hash128.ComputeHash(MemoryMarshal.Cast(entry.Code)); diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendManager.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendManager.cs index ce3d2c236..18428eda9 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendManager.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/Blender/AdvancedBlendManager.cs @@ -66,7 +66,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.Blender descriptor = default; - if (!AdvancedBlendPreGenTable.Entries.TryGetValue(hash, out var entry)) + if (!AdvancedBlendPreGenTable.Entries.TryGetValue(hash, out AdvancedBlendEntry entry)) { return false; } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/ComputeDraw/VtgAsComputeContext.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/ComputeDraw/VtgAsComputeContext.cs index 34f2cfcad..15f1a4a33 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/ComputeDraw/VtgAsComputeContext.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/ComputeDraw/VtgAsComputeContext.cs @@ -65,7 +65,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.ComputeDraw { if (disposing) { - foreach (var texture in _cache.Values) + foreach (ITexture texture in _cache.Values) { texture.Release(); } @@ -603,7 +603,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.ComputeDraw DestroyIfNotNull(ref _geometryIndexDataBuffer.Handle); DestroyIfNotNull(ref _sequentialIndexBuffer); - foreach (var indexBuffer in _topologyRemapBuffers.Values) + foreach (IndexBuffer indexBuffer in _topologyRemapBuffers.Values) { _context.Renderer.DeleteBuffer(indexBuffer.Handle); } diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/ComputeDraw/VtgAsComputeState.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/ComputeDraw/VtgAsComputeState.cs index 2de324392..8a667b408 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/ComputeDraw/VtgAsComputeState.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/ComputeDraw/VtgAsComputeState.cs @@ -127,7 +127,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.ComputeDraw for (int index = 0; index < Constants.TotalVertexAttribs; index++) { - var vertexAttrib = _state.State.VertexAttribState[index]; + VertexAttribState vertexAttrib = _state.State.VertexAttribState[index]; if (!FormatTable.TryGetSingleComponentAttribFormat(vertexAttrib.UnpackFormat(), out Format format, out int componentsCount)) { @@ -153,7 +153,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.ComputeDraw int bufferIndex = vertexAttrib.UnpackBufferIndex(); GpuVa endAddress = _state.State.VertexBufferEndAddress[bufferIndex]; - var vertexBuffer = _state.State.VertexBufferState[bufferIndex]; + VertexBufferState vertexBuffer = _state.State.VertexBufferState[bufferIndex]; bool instanced = _state.State.VertexBufferInstanced[bufferIndex]; ulong address = vertexBuffer.Address.Pack(); @@ -351,7 +351,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.ComputeDraw /// Size of the buffer in bytes private readonly void SetBufferTexture(ResourceReservations reservations, int index, Format format, ulong address, ulong size) { - var memoryManager = _channel.MemoryManager; + MemoryManager memoryManager = _channel.MemoryManager; BufferRange range = memoryManager.Physical.BufferCache.GetBufferRange(memoryManager.GetPhysicalRegions(address, size), BufferStage.VertexBuffer); @@ -392,7 +392,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed.ComputeDraw indexOffset <<= shift; size <<= shift; - var memoryManager = _channel.MemoryManager; + MemoryManager memoryManager = _channel.MemoryManager; ulong misalign = address & ((ulong)_context.Capabilities.TextureBufferOffsetAlignment - 1); BufferRange range = memoryManager.Physical.BufferCache.GetBufferRange( diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/ConstantBufferUpdater.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/ConstantBufferUpdater.cs index 2095fcd7a..6fc49fc8d 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/ConstantBufferUpdater.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/ConstantBufferUpdater.cs @@ -1,3 +1,4 @@ +using Ryujinx.Graphics.Gpu.Memory; using System; using System.Runtime.InteropServices; @@ -92,7 +93,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed if (enable) { - var uniformBuffer = _state.State.UniformBufferState; + UniformBufferState uniformBuffer = _state.State.UniformBufferState; ulong address = uniformBuffer.Address.Pack(); @@ -111,7 +112,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed { if (_ubFollowUpAddress != 0) { - var memoryManager = _channel.MemoryManager; + MemoryManager memoryManager = _channel.MemoryManager; Span data = MemoryMarshal.Cast(_ubData.AsSpan(0, (int)(_ubByteCount / 4))); @@ -131,7 +132,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// New uniform buffer data word public void Update(int argument) { - var uniformBuffer = _state.State.UniformBufferState; + UniformBufferState uniformBuffer = _state.State.UniformBufferState; ulong address = uniformBuffer.Address.Pack() + (uint)uniformBuffer.Offset; @@ -157,7 +158,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Data to be written to the uniform buffer public void Update(ReadOnlySpan data) { - var uniformBuffer = _state.State.UniformBufferState; + UniformBufferState uniformBuffer = _state.State.UniformBufferState; ulong address = uniformBuffer.Address.Pack() + (uint)uniformBuffer.Offset; diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/DrawManager.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/DrawManager.cs index 56ef64c6e..2537b79b7 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/DrawManager.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/DrawManager.cs @@ -471,7 +471,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed int textureId = _state.State.DrawTextureTextureId; int samplerId = _state.State.DrawTextureSamplerId; - (var texture, var sampler) = _channel.TextureManager.GetGraphicsTextureAndSampler(textureId, samplerId); + (Image.Texture texture, Sampler sampler) = _channel.TextureManager.GetGraphicsTextureAndSampler(textureId, samplerId); srcX0 *= texture.ScaleFactor; srcY0 *= texture.ScaleFactor; @@ -684,8 +684,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed if (hasCount) { - var indirectBuffer = memory.BufferCache.GetBufferRange(indirectBufferRange, BufferStage.Indirect); - var parameterBuffer = memory.BufferCache.GetBufferRange(parameterBufferRange, BufferStage.Indirect); + BufferRange indirectBuffer = memory.BufferCache.GetBufferRange(indirectBufferRange, BufferStage.Indirect); + BufferRange parameterBuffer = memory.BufferCache.GetBufferRange(parameterBufferRange, BufferStage.Indirect); if (indexed) { @@ -698,7 +698,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed } else { - var indirectBuffer = memory.BufferCache.GetBufferRange(indirectBufferRange, BufferStage.Indirect); + BufferRange indirectBuffer = memory.BufferCache.GetBufferRange(indirectBufferRange, BufferStage.Indirect); if (indexed) { @@ -820,7 +820,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed // If there is a mismatch on the host clip region and the one explicitly defined by the guest // on the screen scissor state, then we need to force only one texture to be bound to avoid // host clipping. - var screenScissorState = _state.State.ScreenScissorState; + ScreenScissorState screenScissorState = _state.State.ScreenScissorState; bool clearAffectedByStencilMask = (_state.State.ClearFlags & 1) != 0; bool clearAffectedByScissor = (_state.State.ClearFlags & 0x100) != 0; @@ -833,7 +833,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed if (fullClear && clearAffectedByScissor && _state.State.ScissorState[0].Enable) { - ref var scissorState = ref _state.State.ScissorState[0]; + ref ScissorState scissorState = ref _state.State.ScissorState[0]; fullClear = scissorState.X1 == screenScissorState.X && scissorState.Y1 == screenScissorState.Y && @@ -894,7 +894,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed if (clearAffectedByScissor && _state.State.ScissorState[0].Enable) { - ref var scissorState = ref _state.State.ScissorState[0]; + ref ScissorState scissorState = ref _state.State.ScissorState[0]; scissorX = Math.Max(scissorX, scissorState.X1); scissorY = Math.Max(scissorY, scissorState.Y1); @@ -923,7 +923,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed if (componentMask != 0) { - var clearColor = _state.State.ClearColors; + ClearColors clearColor = _state.State.ClearColors; ColorF color = new(clearColor.Red, clearColor.Green, clearColor.Blue, clearColor.Alpha); diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/SpecializationStateUpdater.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/SpecializationStateUpdater.cs index dbd4efc8f..4eea80687 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/SpecializationStateUpdater.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/SpecializationStateUpdater.cs @@ -288,7 +288,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed { int rtIndex = rtControl.UnpackPermutationIndex(index); - var colorState = state[rtIndex]; + RtColorState colorState = state[rtIndex]; if (index < count && StateUpdater.IsRtEnabled(colorState)) { diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/StateUpdateTracker.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/StateUpdateTracker.cs index ea9fc9e31..4f9e57f76 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/StateUpdateTracker.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/StateUpdateTracker.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Numerics; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -58,13 +59,13 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed _registerToGroupMapping = new byte[BlockSize]; _callbacks = new Action[entries.Length]; - var fieldToDelegate = new Dictionary(); + Dictionary fieldToDelegate = new Dictionary(); for (int entryIndex = 0; entryIndex < entries.Length; entryIndex++) { - var entry = entries[entryIndex]; + StateUpdateCallbackEntry entry = entries[entryIndex]; - foreach (var fieldName in entry.FieldNames) + foreach (string fieldName in entry.FieldNames) { fieldToDelegate.Add(fieldName, entryIndex); } @@ -72,15 +73,15 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed _callbacks[entryIndex] = entry.Callback; } - var fields = typeof(TState).GetFields(); + FieldInfo[] fields = typeof(TState).GetFields(); int offset = 0; for (int fieldIndex = 0; fieldIndex < fields.Length; fieldIndex++) { - var field = fields[fieldIndex]; + FieldInfo field = fields[fieldIndex]; - var currentFieldOffset = (int)Marshal.OffsetOf(field.Name); - var nextFieldOffset = fieldIndex + 1 == fields.Length ? Unsafe.SizeOf() : (int)Marshal.OffsetOf(fields[fieldIndex + 1].Name); + int currentFieldOffset = (int)Marshal.OffsetOf(field.Name); + int nextFieldOffset = fieldIndex + 1 == fields.Length ? Unsafe.SizeOf() : (int)Marshal.OffsetOf(fields[fieldIndex + 1].Name); int sizeOfField = nextFieldOffset - currentFieldOffset; diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/StateUpdater.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/StateUpdater.cs index 1dc77b52d..d8e53124b 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/StateUpdater.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/StateUpdater.cs @@ -3,6 +3,7 @@ using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.Gpu.Engine.Threed.Blender; using Ryujinx.Graphics.Gpu.Engine.Types; using Ryujinx.Graphics.Gpu.Image; +using Ryujinx.Graphics.Gpu.Memory; using Ryujinx.Graphics.Gpu.Shader; using Ryujinx.Graphics.Shader; using Ryujinx.Graphics.Texture; @@ -463,8 +464,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// If this is not -1, it indicates that only the given indexed target will be used. public void UpdateRenderTargetState(RenderTargetUpdateFlags updateFlags, int singleUse = -1) { - var memoryManager = _channel.MemoryManager; - var rtControl = _state.State.RtControl; + MemoryManager memoryManager = _channel.MemoryManager; + RtControl rtControl = _state.State.RtControl; bool useControl = updateFlags.HasFlag(RenderTargetUpdateFlags.UseControl); bool layered = updateFlags.HasFlag(RenderTargetUpdateFlags.Layered); @@ -473,12 +474,12 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed int count = useControl ? rtControl.UnpackCount() : Constants.TotalRenderTargets; - var msaaMode = _state.State.RtMsaaMode; + TextureMsaaMode msaaMode = _state.State.RtMsaaMode; int samplesInX = msaaMode.SamplesInX(); int samplesInY = msaaMode.SamplesInY(); - var scissor = _state.State.ScreenScissorState; + ScreenScissorState scissor = _state.State.ScreenScissorState; Size sizeHint = new((scissor.X + scissor.Width) * samplesInX, (scissor.Y + scissor.Height) * samplesInY, 1); int clipRegionWidth = int.MaxValue; @@ -491,7 +492,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed { int rtIndex = useControl ? rtControl.UnpackPermutationIndex(index) : index; - var colorState = _state.State.RtColorState[rtIndex]; + RtColorState colorState = _state.State.RtColorState[rtIndex]; if (index >= count || !IsRtEnabled(colorState) || (singleColor && index != singleUse)) { @@ -541,8 +542,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed if (dsEnable && updateFlags.HasFlag(RenderTargetUpdateFlags.UpdateDepthStencil)) { - var dsState = _state.State.RtDepthStencilState; - var dsSize = _state.State.RtDepthStencilSize; + RtDepthStencilState dsState = _state.State.RtDepthStencilState; + Size3D dsSize = _state.State.RtDepthStencilSize; depthStencil = memoryManager.Physical.TextureCache.FindOrCreateTexture( memoryManager, @@ -643,7 +644,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed if (_state.State.YControl.HasFlag(YControl.NegateY)) { - ref var screenScissor = ref _state.State.ScreenScissorState; + ref ScreenScissorState screenScissor = ref _state.State.ScreenScissorState; y = screenScissor.Height - height - y; if (y < 0) @@ -721,8 +722,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// private void UpdateViewportTransform() { - var yControl = _state.State.YControl; - var face = _state.State.FaceState; + YControl yControl = _state.State.YControl; + FaceState face = _state.State.FaceState; bool disableTransform = _state.State.ViewportTransformEnable == 0; bool yNegate = yControl.HasFlag(YControl.NegateY); @@ -736,17 +737,17 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed { if (disableTransform) { - ref var scissor = ref _state.State.ScreenScissorState; + ref ScreenScissorState scissor = ref _state.State.ScreenScissorState; float rScale = _channel.TextureManager.RenderTargetScale; - var scissorRect = new Rectangle(0, 0, (scissor.X + scissor.Width) * rScale, (scissor.Y + scissor.Height) * rScale); + Rectangle scissorRect = new Rectangle(0, 0, (scissor.X + scissor.Width) * rScale, (scissor.Y + scissor.Height) * rScale); viewports[index] = new Viewport(scissorRect, ViewportSwizzle.PositiveX, ViewportSwizzle.PositiveY, ViewportSwizzle.PositiveZ, ViewportSwizzle.PositiveW, 0, 1); continue; } - ref var transform = ref _state.State.ViewportTransform[index]; - ref var extents = ref _state.State.ViewportExtents[index]; + ref ViewportTransform transform = ref _state.State.ViewportTransform[index]; + ref ViewportExtents extents = ref _state.State.ViewportExtents[index]; float scaleX = MathF.Abs(transform.ScaleX); float scaleY = transform.ScaleY; @@ -841,7 +842,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// private void UpdateDepthBiasState() { - var depthBias = _state.State.DepthBiasState; + DepthBiasState depthBias = _state.State.DepthBiasState; float factor = _state.State.DepthBiasFactor; float units = _state.State.DepthBiasUnits; @@ -862,9 +863,9 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// private void UpdateStencilTestState() { - var backMasks = _state.State.StencilBackMasks; - var test = _state.State.StencilTestState; - var backTest = _state.State.StencilBackTestState; + StencilBackMasks backMasks = _state.State.StencilBackMasks; + StencilTestState test = _state.State.StencilTestState; + StencilBackTestState backTest = _state.State.StencilBackTestState; CompareOp backFunc; StencilOp backSFail; @@ -934,10 +935,10 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// private void UpdateSamplerPoolState() { - var texturePool = _state.State.TexturePoolState; - var samplerPool = _state.State.SamplerPoolState; + PoolState texturePool = _state.State.TexturePoolState; + PoolState samplerPool = _state.State.SamplerPoolState; - var samplerIndex = _state.State.SamplerIndex; + SamplerIndex samplerIndex = _state.State.SamplerIndex; int maximumId = samplerIndex == SamplerIndex.ViaHeaderIndex ? texturePool.MaximumId @@ -951,7 +952,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// private void UpdateTexturePoolState() { - var texturePool = _state.State.TexturePoolState; + PoolState texturePool = _state.State.TexturePoolState; _channel.TextureManager.SetGraphicsTexturePool(texturePool.Address.Pack(), texturePool.MaximumId); _channel.TextureManager.SetGraphicsTextureBufferIndex((int)_state.State.TextureBufferIndex); @@ -971,7 +972,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed for (int index = 0; index < Constants.TotalVertexAttribs; index++) { - var vertexAttrib = _state.State.VertexAttribState[index]; + VertexAttribState vertexAttrib = _state.State.VertexAttribState[index]; int bufferIndex = vertexAttrib.UnpackBufferIndex(); @@ -1065,7 +1066,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// private void UpdateIndexBufferState() { - var indexBuffer = _state.State.IndexBufferState; + IndexBufferState indexBuffer = _state.State.IndexBufferState; if (_drawState.IndexCount == 0) { @@ -1109,7 +1110,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed for (int index = 0; index < Constants.TotalVertexBuffers; index++) { - var vertexBuffer = _state.State.VertexBufferState[index]; + VertexBufferState vertexBuffer = _state.State.VertexBufferState[index]; if (!vertexBuffer.UnpackEnable()) { @@ -1193,8 +1194,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// private void UpdateFaceState() { - var yControl = _state.State.YControl; - var face = _state.State.FaceState; + YControl yControl = _state.State.YControl; + FaceState face = _state.State.FaceState; _pipeline.CullEnable = face.CullEnable; _pipeline.CullMode = face.CullFace; @@ -1233,7 +1234,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed for (int index = 0; index < Constants.TotalRenderTargets; index++) { - var colorMask = _state.State.RtColorMask[rtColorMaskShared ? 0 : index]; + RtColorMask colorMask = _state.State.RtColorMask[rtColorMaskShared ? 0 : index]; uint componentMask; @@ -1256,7 +1257,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed { if (_state.State.BlendUcodeEnable != BlendUcodeEnable.Disabled) { - if (_context.Capabilities.SupportsBlendEquationAdvanced && _blendManager.TryGetAdvancedBlend(out var blendDescriptor)) + if (_context.Capabilities.SupportsBlendEquationAdvanced && _blendManager.TryGetAdvancedBlend(out AdvancedBlendDescriptor blendDescriptor)) { // Try to HLE it using advanced blend on the host if we can. _context.Renderer.Pipeline.SetBlendState(blendDescriptor); @@ -1278,9 +1279,9 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed for (int index = 0; index < Constants.TotalRenderTargets; index++) { bool enable = _state.State.BlendEnable[index]; - var blend = _state.State.BlendState[index]; + BlendState blend = _state.State.BlendState[index]; - var descriptor = new BlendDescriptor( + BlendDescriptor descriptor = new BlendDescriptor( enable, blendConstant, blend.ColorOp, @@ -1306,9 +1307,9 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed else { bool enable = _state.State.BlendEnable[0]; - var blend = _state.State.BlendStateCommon; + BlendStateCommon blend = _state.State.BlendStateCommon; - var descriptor = new BlendDescriptor( + BlendDescriptor descriptor = new BlendDescriptor( enable, blendConstant, blend.ColorOp, @@ -1409,7 +1410,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// private void UpdateShaderState() { - var shaderCache = _channel.MemoryManager.Physical.ShaderCache; + ShaderCache shaderCache = _channel.MemoryManager.Physical.ShaderCache; _vtgWritesRtLayer = false; @@ -1420,7 +1421,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed for (int index = 0; index < 6; index++) { - var shader = _state.State.ShaderState[index]; + ShaderState shader = _state.State.ShaderState[index]; if (!shader.UnpackEnable() && index != 1) { continue; @@ -1525,7 +1526,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// private void UpdateSupportBufferViewportSize() { - ref var transform = ref _state.State.ViewportTransform[0]; + ref ViewportTransform transform = ref _state.State.ViewportTransform[0]; float scaleX = MathF.Abs(transform.ScaleX); float scaleY = transform.ScaleY; @@ -1564,8 +1565,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Current depth mode private DepthMode GetDepthMode() { - ref var transform = ref _state.State.ViewportTransform[0]; - ref var extents = ref _state.State.ViewportExtents[0]; + ref ViewportTransform transform = ref _state.State.ViewportTransform[0]; + ref ViewportExtents extents = ref _state.State.ViewportExtents[0]; DepthMode depthMode; diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Threed/ThreedClass.cs b/src/Ryujinx.Graphics.Gpu/Engine/Threed/ThreedClass.cs index ab1d27a1c..618743018 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Threed/ThreedClass.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Threed/ThreedClass.cs @@ -82,8 +82,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed _i2mClass = new InlineToMemoryClass(context, channel, initializeState: false); - var spec = new SpecializationStateUpdater(context); - var drawState = new DrawState(); + SpecializationStateUpdater spec = new SpecializationStateUpdater(context); + DrawState drawState = new DrawState(); _drawManager = new DrawManager(context, channel, _state, drawState, spec); _blendManager = new AdvancedBlendManager(_state); @@ -253,8 +253,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed } else { - ref var lhsVec = ref Unsafe.As>(ref lhs); - ref var rhsVec = ref Unsafe.As>(ref rhs); + ref Vector128 lhsVec = ref Unsafe.As>(ref lhs); + ref Vector128 rhsVec = ref Unsafe.As>(ref rhs); return Vector128.EqualsAll(lhsVec, rhsVec) && Vector128.EqualsAll(Unsafe.Add(ref lhsVec, 1), Unsafe.Add(ref rhsVec, 1)); @@ -267,8 +267,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Blend enable public void UpdateBlendEnable(ref Array8 enable) { - var shadow = ShadowMode; - ref var state = ref _state.State.BlendEnable; + SetMmeShadowRamControlMode shadow = ShadowMode; + ref Array8 state = ref _state.State.BlendEnable; if (shadow.IsReplay()) { @@ -294,8 +294,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Color masks public void UpdateColorMasks(ref Array8 masks) { - var shadow = ShadowMode; - ref var state = ref _state.State.RtColorMask; + SetMmeShadowRamControlMode shadow = ShadowMode; + ref Array8 state = ref _state.State.RtColorMask; if (shadow.IsReplay()) { @@ -323,12 +323,12 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Type of the binding public void UpdateIndexBuffer(uint addrHigh, uint addrLow, IndexType type) { - var shadow = ShadowMode; - ref var state = ref _state.State.IndexBufferState; + SetMmeShadowRamControlMode shadow = ShadowMode; + ref IndexBufferState state = ref _state.State.IndexBufferState; if (shadow.IsReplay()) { - ref var shadowState = ref _state.ShadowState.IndexBufferState; + ref IndexBufferState shadowState = ref _state.ShadowState.IndexBufferState; addrHigh = shadowState.Address.High; addrLow = shadowState.Address.Low; type = shadowState.Type; @@ -345,7 +345,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed if (shadow.IsTrack()) { - ref var shadowState = ref _state.ShadowState.IndexBufferState; + ref IndexBufferState shadowState = ref _state.ShadowState.IndexBufferState; shadowState.Address.High = addrHigh; shadowState.Address.Low = addrLow; shadowState.Type = type; @@ -360,12 +360,12 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Low part of the address public void UpdateUniformBufferState(int size, uint addrHigh, uint addrLow) { - var shadow = ShadowMode; - ref var state = ref _state.State.UniformBufferState; + SetMmeShadowRamControlMode shadow = ShadowMode; + ref UniformBufferState state = ref _state.State.UniformBufferState; if (shadow.IsReplay()) { - ref var shadowState = ref _state.ShadowState.UniformBufferState; + ref UniformBufferState shadowState = ref _state.ShadowState.UniformBufferState; size = shadowState.Size; addrHigh = shadowState.Address.High; addrLow = shadowState.Address.Low; @@ -377,7 +377,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed if (shadow.IsTrack()) { - ref var shadowState = ref _state.ShadowState.UniformBufferState; + ref UniformBufferState shadowState = ref _state.ShadowState.UniformBufferState; shadowState.Size = size; shadowState.Address.High = addrHigh; shadowState.Address.Low = addrLow; @@ -391,8 +391,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Offset to update with public void SetShaderOffset(int index, uint offset) { - var shadow = ShadowMode; - ref var shaderState = ref _state.State.ShaderState[index]; + SetMmeShadowRamControlMode shadow = ShadowMode; + ref ShaderState shaderState = ref _state.State.ShaderState[index]; if (shadow.IsReplay()) { @@ -418,8 +418,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed /// Uniform buffer state public void UpdateUniformBufferState(UniformBufferState ubState) { - var shadow = ShadowMode; - ref var state = ref _state.State.UniformBufferState; + SetMmeShadowRamControlMode shadow = ShadowMode; + ref UniformBufferState state = ref _state.State.UniformBufferState; if (shadow.IsReplay()) { diff --git a/src/Ryujinx.Graphics.Gpu/Engine/Twod/TwodClass.cs b/src/Ryujinx.Graphics.Gpu/Engine/Twod/TwodClass.cs index 0dd9481df..60a558d56 100644 --- a/src/Ryujinx.Graphics.Gpu/Engine/Twod/TwodClass.cs +++ b/src/Ryujinx.Graphics.Gpu/Engine/Twod/TwodClass.cs @@ -3,6 +3,7 @@ using Ryujinx.Graphics.Device; using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.Gpu.Engine.Types; using Ryujinx.Graphics.Gpu.Image; +using Ryujinx.Graphics.Gpu.Memory; using Ryujinx.Graphics.Texture; using Ryujinx.Memory; using System; @@ -123,7 +124,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod /// Bytes per pixel private void UnscaledFullCopy(TwodTexture src, TwodTexture dst, int w, int h, int bpp) { - var srcCalculator = new OffsetCalculator( + OffsetCalculator srcCalculator = new OffsetCalculator( w, h, src.Stride, @@ -134,7 +135,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod (int _, int srcSize) = srcCalculator.GetRectangleRange(0, 0, w, h); - var memoryManager = _channel.MemoryManager; + MemoryManager memoryManager = _channel.MemoryManager; ulong srcGpuVa = src.Address.Pack(); ulong dstGpuVa = dst.Address.Pack(); @@ -228,10 +229,10 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod /// Method call argument private void PixelsFromMemorySrcY0Int(int argument) { - var memoryManager = _channel.MemoryManager; + MemoryManager memoryManager = _channel.MemoryManager; - var dstCopyTexture = Unsafe.As(ref _state.State.SetDstFormat); - var srcCopyTexture = Unsafe.As(ref _state.State.SetSrcFormat); + TwodTexture dstCopyTexture = Unsafe.As(ref _state.State.SetDstFormat); + TwodTexture srcCopyTexture = Unsafe.As(ref _state.State.SetSrcFormat); long srcX = ((long)_state.State.SetPixelsFromMemorySrcX0Int << 32) | (long)(ulong)_state.State.SetPixelsFromMemorySrcX0Frac; long srcY = ((long)_state.State.PixelsFromMemorySrcY0Int << 32) | (long)(ulong)_state.State.SetPixelsFromMemorySrcY0Frac; @@ -268,10 +269,10 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod // The source and destination textures should at least be as big as the region being requested. // The hints will only resize within alignment constraints, so out of bound copies won't resize in most cases. - var srcHint = new Size(srcX2, srcY2, 1); - var dstHint = new Size(dstX2, dstY2, 1); + Size srcHint = new Size(srcX2, srcY2, 1); + Size dstHint = new Size(dstX2, dstY2, 1); - var srcCopyTextureFormat = srcCopyTexture.Format.Convert(); + FormatInfo srcCopyTextureFormat = srcCopyTexture.Format.Convert(); int srcWidthAligned = srcCopyTexture.Stride / srcCopyTextureFormat.BytesPerPixel; @@ -304,7 +305,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod // are the same, as we can't blit between different depth formats. bool srcDepthAlias = srcCopyTexture.Format == dstCopyTexture.Format; - var srcTexture = memoryManager.Physical.TextureCache.FindOrCreateTexture( + Image.Texture srcTexture = memoryManager.Physical.TextureCache.FindOrCreateTexture( memoryManager, srcCopyTexture, offset, @@ -341,7 +342,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Twod dstCopyTextureFormat = dstCopyTexture.Format.Convert(); } - var dstTexture = memoryManager.Physical.TextureCache.FindOrCreateTexture( + Image.Texture dstTexture = memoryManager.Physical.TextureCache.FindOrCreateTexture( memoryManager, dstCopyTexture, 0, diff --git a/src/Ryujinx.Graphics.Gpu/GpuChannel.cs b/src/Ryujinx.Graphics.Gpu/GpuChannel.cs index 33618a15b..047cbcca6 100644 --- a/src/Ryujinx.Graphics.Gpu/GpuChannel.cs +++ b/src/Ryujinx.Graphics.Gpu/GpuChannel.cs @@ -57,7 +57,7 @@ namespace Ryujinx.Graphics.Gpu /// The new memory manager to be bound public void BindMemory(MemoryManager memoryManager) { - var oldMemoryManager = Interlocked.Exchange(ref _memoryManager, memoryManager ?? throw new ArgumentNullException(nameof(memoryManager))); + MemoryManager oldMemoryManager = Interlocked.Exchange(ref _memoryManager, memoryManager ?? throw new ArgumentNullException(nameof(memoryManager))); memoryManager.Physical.IncrementReferenceCount(); @@ -85,7 +85,7 @@ namespace Ryujinx.Graphics.Gpu { TextureManager.ReloadPools(); - var memoryManager = Volatile.Read(ref _memoryManager); + MemoryManager memoryManager = Volatile.Read(ref _memoryManager); memoryManager?.Physical.BufferCache.QueuePrune(); } @@ -138,7 +138,7 @@ namespace Ryujinx.Graphics.Gpu _processor.Dispose(); TextureManager.Dispose(); - var oldMemoryManager = Interlocked.Exchange(ref _memoryManager, null); + MemoryManager oldMemoryManager = Interlocked.Exchange(ref _memoryManager, null); if (oldMemoryManager != null) { oldMemoryManager.Physical.BufferCache.NotifyBuffersModified -= BufferManager.Rebind; diff --git a/src/Ryujinx.Graphics.Gpu/GpuContext.cs b/src/Ryujinx.Graphics.Gpu/GpuContext.cs index f7e8f1bf8..fa877cf8a 100644 --- a/src/Ryujinx.Graphics.Gpu/GpuContext.cs +++ b/src/Ryujinx.Graphics.Gpu/GpuContext.cs @@ -167,7 +167,7 @@ namespace Ryujinx.Graphics.Gpu /// Thrown when is invalid public MemoryManager CreateMemoryManager(ulong pid, ulong cpuMemorySize) { - if (!PhysicalMemoryRegistry.TryGetValue(pid, out var physicalMemory)) + if (!PhysicalMemoryRegistry.TryGetValue(pid, out PhysicalMemory physicalMemory)) { throw new ArgumentException("The PID is invalid or the process was not registered", nameof(pid)); } @@ -183,7 +183,7 @@ namespace Ryujinx.Graphics.Gpu /// Thrown when is invalid public DeviceMemoryManager CreateDeviceMemoryManager(ulong pid) { - if (!PhysicalMemoryRegistry.TryGetValue(pid, out var physicalMemory)) + if (!PhysicalMemoryRegistry.TryGetValue(pid, out PhysicalMemory physicalMemory)) { throw new ArgumentException("The PID is invalid or the process was not registered", nameof(pid)); } @@ -199,7 +199,7 @@ namespace Ryujinx.Graphics.Gpu /// Thrown if was already registered public void RegisterProcess(ulong pid, Cpu.IVirtualMemoryManagerTracked cpuMemory) { - var physicalMemory = new PhysicalMemory(this, cpuMemory); + PhysicalMemory physicalMemory = new PhysicalMemory(this, cpuMemory); if (!PhysicalMemoryRegistry.TryAdd(pid, physicalMemory)) { throw new ArgumentException("The PID was already registered", nameof(pid)); @@ -214,7 +214,7 @@ namespace Ryujinx.Graphics.Gpu /// ID of the process public void UnregisterProcess(ulong pid) { - if (PhysicalMemoryRegistry.TryRemove(pid, out var physicalMemory)) + if (PhysicalMemoryRegistry.TryRemove(pid, out PhysicalMemory physicalMemory)) { physicalMemory.ShaderCache.ShaderCacheStateChanged -= ShaderCacheStateUpdate; physicalMemory.Dispose(); @@ -289,7 +289,7 @@ namespace Ryujinx.Graphics.Gpu { HostInitalized.WaitOne(); - foreach (var physicalMemory in PhysicalMemoryRegistry.Values) + foreach (PhysicalMemory physicalMemory in PhysicalMemoryRegistry.Values) { physicalMemory.ShaderCache.Initialize(cancellationToken); } @@ -329,7 +329,7 @@ namespace Ryujinx.Graphics.Gpu /// public void ProcessShaderCacheQueue() { - foreach (var physicalMemory in PhysicalMemoryRegistry.Values) + foreach (PhysicalMemory physicalMemory in PhysicalMemoryRegistry.Values) { physicalMemory.ShaderCache.ProcessShaderCacheQueue(); } @@ -404,12 +404,12 @@ namespace Ryujinx.Graphics.Gpu if (force || _pendingSync || (syncpoint && SyncpointActions.Count > 0)) { - foreach (var action in SyncActions) + foreach (ISyncActionHandler action in SyncActions) { action.SyncPreAction(syncpoint); } - foreach (var action in SyncpointActions) + foreach (ISyncActionHandler action in SyncpointActions) { action.SyncPreAction(syncpoint); } @@ -450,7 +450,7 @@ namespace Ryujinx.Graphics.Gpu _gpuReadyEvent.Dispose(); // Has to be disposed before processing deferred actions, as it will produce some. - foreach (var physicalMemory in PhysicalMemoryRegistry.Values) + foreach (PhysicalMemory physicalMemory in PhysicalMemoryRegistry.Values) { physicalMemory.Dispose(); } diff --git a/src/Ryujinx.Graphics.Gpu/Image/AutoDeleteCache.cs b/src/Ryujinx.Graphics.Gpu/Image/AutoDeleteCache.cs index 74967b190..b1a416e23 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/AutoDeleteCache.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/AutoDeleteCache.cs @@ -80,7 +80,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// The amount of physical CPU Memory Avaiable on the device. public void Initialize(GpuContext context, ulong cpuMemorySize) { - var cpuMemorySizeGiB = cpuMemorySize / GiB; + ulong cpuMemorySizeGiB = cpuMemorySize / GiB; if (cpuMemorySizeGiB < 6 || context.Capabilities.MaximumGpuMemory == 0) { @@ -100,7 +100,7 @@ namespace Ryujinx.Graphics.Gpu.Image MaxTextureSizeCapacity = TextureSizeCapacity12GiB; } - var cacheMemory = (ulong)(context.Capabilities.MaximumGpuMemory * MemoryScaleFactor); + ulong cacheMemory = (ulong)(context.Capabilities.MaximumGpuMemory * MemoryScaleFactor); _maxCacheMemoryUsage = Math.Clamp(cacheMemory, MinTextureSizeCapacity, MaxTextureSizeCapacity); @@ -232,7 +232,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// The texture if found, null otherwise public Texture FindShortCache(in TextureDescriptor descriptor) { - if (_shortCacheLookup.Count > 0 && _shortCacheLookup.TryGetValue(descriptor, out var entry)) + if (_shortCacheLookup.Count > 0 && _shortCacheLookup.TryGetValue(descriptor, out ShortTextureCacheEntry entry)) { if (entry.InvalidatedSequence == entry.Texture.InvalidatedSequence) { @@ -277,7 +277,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Last used texture descriptor public void AddShortCache(Texture texture, ref TextureDescriptor descriptor) { - var entry = new ShortTextureCacheEntry(descriptor, texture); + ShortTextureCacheEntry entry = new ShortTextureCacheEntry(descriptor, texture); _shortCacheBuilder.Add(entry); _shortCacheLookup.Add(entry.Descriptor, entry); @@ -296,7 +296,7 @@ namespace Ryujinx.Graphics.Gpu.Image { if (texture.ShortCacheEntry != null) { - var entry = new ShortTextureCacheEntry(texture); + ShortTextureCacheEntry entry = new ShortTextureCacheEntry(texture); _shortCacheBuilder.Add(entry); @@ -314,7 +314,7 @@ namespace Ryujinx.Graphics.Gpu.Image { HashSet toRemove = _shortCache; - foreach (var entry in toRemove) + foreach (ShortTextureCacheEntry entry in toRemove) { entry.Texture.DecrementReferenceCount(); diff --git a/src/Ryujinx.Graphics.Gpu/Image/FormatTable.cs b/src/Ryujinx.Graphics.Gpu/Image/FormatTable.cs index da9e5c3a9..45e1971a8 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/FormatTable.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/FormatTable.cs @@ -704,7 +704,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// True if the format is valid, false otherwise public static bool TryGetSingleComponentAttribFormat(uint encoded, out Format format, out int componentsCount) { - bool result = _singleComponentAttribFormats.TryGetValue((VertexAttributeFormat)encoded, out var tuple); + bool result = _singleComponentAttribFormats.TryGetValue((VertexAttributeFormat)encoded, out (Format, int) tuple); format = tuple.Item1; componentsCount = tuple.Item2; diff --git a/src/Ryujinx.Graphics.Gpu/Image/Texture.cs b/src/Ryujinx.Graphics.Gpu/Image/Texture.cs index 7ee2e5cf0..51ce195f4 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/Texture.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/Texture.cs @@ -536,7 +536,7 @@ namespace Ryujinx.Graphics.Gpu.Image // All views must be recreated against the new storage. - foreach (var view in _views) + foreach (Texture view in _views) { Logger.Debug?.Print(LogClass.Gpu, $" Recreating view {Info.Width}x{Info.Height} {Info.FormatInfo.Format}."); view.ScaleFactor = scale; @@ -553,7 +553,7 @@ namespace Ryujinx.Graphics.Gpu.Image { ScaleMode = newScaleMode; - foreach (var view in _views) + foreach (Texture view in _views) { view.ScaleMode = newScaleMode; } @@ -899,7 +899,7 @@ namespace Ryujinx.Graphics.Gpu.Image { using (result) { - var converted = PixelConverter.ConvertR4G4ToR4G4B4A4(result.Span, width); + MemoryOwner converted = PixelConverter.ConvertR4G4ToR4G4B4A4(result.Span, width); if (_context.Capabilities.SupportsR4G4B4A4Format) { @@ -1650,7 +1650,7 @@ namespace Ryujinx.Graphics.Gpu.Image { lock (_poolOwners) { - foreach (var owner in _poolOwners) + foreach (TexturePoolOwner owner in _poolOwners) { owner.Pool.ForceRemove(this, owner.ID, deferred); } @@ -1680,7 +1680,7 @@ namespace Ryujinx.Graphics.Gpu.Image { ulong address = 0; - foreach (var owner in _poolOwners) + foreach (TexturePoolOwner owner in _poolOwners) { if (address == 0 || address == owner.GpuAddress) { diff --git a/src/Ryujinx.Graphics.Gpu/Image/TextureCache.cs b/src/Ryujinx.Graphics.Gpu/Image/TextureCache.cs index ff7f11142..71de06e2c 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TextureCache.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TextureCache.cs @@ -128,7 +128,7 @@ namespace Ryujinx.Graphics.Gpu.Image // Any texture that has been unmapped at any point or is partially unmapped // should update their pool references after the remap completes. - foreach (var texture in _partiallyMappedTextures) + foreach (Texture texture in _partiallyMappedTextures) { texture.UpdatePoolMappings(); } @@ -253,7 +253,7 @@ namespace Ryujinx.Graphics.Gpu.Image for (int i = 0; i < overlapCount; i++) { - var other = _textureOverlaps[i]; + Texture other = _textureOverlaps[i]; if (texture != other && (texture.IsViewCompatible(other.Info, other.Range, true, other.LayerSize, _context.Capabilities, out _, out _) != TextureViewCompatibility.Incompatible || @@ -486,7 +486,7 @@ namespace Ryujinx.Graphics.Gpu.Image int layerSize = !isLinear ? colorState.LayerSize * 4 : 0; - var flags = TextureSearchFlags.WithUpscale; + TextureSearchFlags flags = TextureSearchFlags.WithUpscale; if (discard) { @@ -560,7 +560,7 @@ namespace Ryujinx.Graphics.Gpu.Image target, formatInfo); - var flags = TextureSearchFlags.WithUpscale; + TextureSearchFlags flags = TextureSearchFlags.WithUpscale; if (discard) { @@ -947,7 +947,7 @@ namespace Ryujinx.Graphics.Gpu.Image bool hasLayerViews = false; bool hasMipViews = false; - var incompatibleOverlaps = new List(); + List incompatibleOverlaps = new List(); for (int index = 0; index < overlapsCount; index++) { diff --git a/src/Ryujinx.Graphics.Gpu/Image/TextureGroup.cs b/src/Ryujinx.Graphics.Gpu/Image/TextureGroup.cs index 2db5c6290..47a66747b 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TextureGroup.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TextureGroup.cs @@ -231,7 +231,7 @@ namespace Ryujinx.Graphics.Gpu.Image { bool flushed = false; - foreach (var overlap in _incompatibleOverlaps) + foreach (TextureIncompatibleOverlap overlap in _incompatibleOverlaps) { flushed |= overlap.Group.Storage.FlushModified(true); } @@ -403,7 +403,7 @@ namespace Ryujinx.Graphics.Gpu.Image { if (_loadNeeded[baseHandle + i]) { - var info = GetHandleInformation(baseHandle + i); + (int BaseLayer, int BaseLevel, int Levels, int Layers, int Index) info = GetHandleInformation(baseHandle + i); // Ensure the data for this handle is loaded in the span. if (spanEndIndex <= i - 1) @@ -426,7 +426,7 @@ namespace Ryujinx.Graphics.Gpu.Image } } - var endInfo = spanEndIndex == i ? info : GetHandleInformation(baseHandle + spanEndIndex); + (int BaseLayer, int BaseLevel, int Levels, int Layers, int Index) endInfo = spanEndIndex == i ? info : GetHandleInformation(baseHandle + spanEndIndex); spanBase = _allOffsets[info.Index]; int spanLast = _allOffsets[endInfo.Index + endInfo.Layers * endInfo.Levels - 1]; @@ -479,7 +479,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// True if flushes should be tracked, false otherwise private bool ShouldFlushTriggerTracking() { - foreach (var overlap in _incompatibleOverlaps) + foreach (TextureIncompatibleOverlap overlap in _incompatibleOverlaps) { if (overlap.Group._flushIncompatibleOverlaps) { @@ -637,7 +637,7 @@ namespace Ryujinx.Graphics.Gpu.Image bool canImport = Storage.Info.IsLinear && Storage.Info.Stride >= Storage.Info.Width * Storage.Info.FormatInfo.BytesPerPixel; - var hostPointer = canImport ? _physicalMemory.GetHostPointer(Storage.Range) : 0; + IntPtr hostPointer = canImport ? _physicalMemory.GetHostPointer(Storage.Range) : 0; if (hostPointer != 0 && _context.Renderer.PrepareHostMapping(hostPointer, Storage.Size)) { @@ -1019,7 +1019,7 @@ namespace Ryujinx.Graphics.Gpu.Image int endOffset = _allOffsets[viewEnd] + _sliceSizes[lastLevel]; int size = endOffset - offset; - var result = new List(); + List result = new List(); for (int i = 0; i < TextureRange.Count; i++) { @@ -1053,7 +1053,7 @@ namespace Ryujinx.Graphics.Gpu.Image offset = _allOffsets[viewStart]; ulong maxSize = Storage.Size - (ulong)offset; - var groupHandle = new TextureGroupHandle( + TextureGroupHandle groupHandle = new TextureGroupHandle( this, offset, Math.Min(maxSize, (ulong)size), @@ -1160,17 +1160,17 @@ namespace Ryujinx.Graphics.Gpu.Image /// The offset of the old handles in relation to the new ones private void InheritHandles(TextureGroupHandle[] oldHandles, TextureGroupHandle[] handles, int relativeOffset) { - foreach (var group in handles) + foreach (TextureGroupHandle group in handles) { - foreach (var handle in group.Handles) + foreach (RegionHandle handle in group.Handles) { bool dirty = false; - foreach (var oldGroup in oldHandles) + foreach (TextureGroupHandle oldGroup in oldHandles) { if (group.OverlapsWith(oldGroup.Offset + relativeOffset, oldGroup.Size)) { - foreach (var oldHandle in oldGroup.Handles) + foreach (RegionHandle oldHandle in oldGroup.Handles) { if (handle.OverlapsWith(oldHandle.Address, oldHandle.Size)) { @@ -1194,7 +1194,7 @@ namespace Ryujinx.Graphics.Gpu.Image } } - foreach (var oldGroup in oldHandles) + foreach (TextureGroupHandle oldGroup in oldHandles) { oldGroup.Modified = false; } @@ -1254,7 +1254,7 @@ namespace Ryujinx.Graphics.Gpu.Image continue; } - foreach (var oldGroup in _handles) + foreach (TextureGroupHandle oldGroup in _handles) { if (!groupHandle.OverlapsWith(oldGroup.Offset, oldGroup.Size)) { @@ -1265,7 +1265,7 @@ namespace Ryujinx.Graphics.Gpu.Image { bool hasMatch = false; - foreach (var oldHandle in oldGroup.Handles) + foreach (RegionHandle oldHandle in oldGroup.Handles) { if (oldHandle.RangeEquals(handle)) { @@ -1292,9 +1292,9 @@ namespace Ryujinx.Graphics.Gpu.Image InheritHandles(_handles, handles, 0); - foreach (var oldGroup in _handles) + foreach (TextureGroupHandle oldGroup in _handles) { - foreach (var oldHandle in oldGroup.Handles) + foreach (RegionHandle oldHandle in oldGroup.Handles) { oldHandle.Dispose(); } @@ -1320,12 +1320,12 @@ namespace Ryujinx.Graphics.Gpu.Image else if (!(_hasMipViews || _hasLayerViews)) { // Single dirty region. - var cpuRegionHandles = new RegionHandle[TextureRange.Count]; + RegionHandle[] cpuRegionHandles = new RegionHandle[TextureRange.Count]; int count = 0; for (int i = 0; i < TextureRange.Count; i++) { - var currentRange = TextureRange.GetSubRange(i); + MemoryRange currentRange = TextureRange.GetSubRange(i); if (currentRange.Address != MemoryManager.PteUnmapped) { cpuRegionHandles[count++] = GenerateHandle(currentRange.Address, currentRange.Size); @@ -1337,7 +1337,7 @@ namespace Ryujinx.Graphics.Gpu.Image Array.Resize(ref cpuRegionHandles, count); } - var groupHandle = new TextureGroupHandle(this, 0, Storage.Size, _views, 0, 0, 0, _allOffsets.Length, cpuRegionHandles); + TextureGroupHandle groupHandle = new TextureGroupHandle(this, 0, Storage.Size, _views, 0, 0, 0, _allOffsets.Length, cpuRegionHandles); handles = new TextureGroupHandle[] { groupHandle }; } @@ -1355,7 +1355,7 @@ namespace Ryujinx.Graphics.Gpu.Image if (_is3D) { - var handlesList = new List(); + List handlesList = new List(); for (int i = 0; i < levelHandles; i++) { @@ -1438,8 +1438,8 @@ namespace Ryujinx.Graphics.Gpu.Image // Get the location of each texture within its storage, so we can find the handles to apply the dependency to. // This can consist of multiple disjoint regions, for example if this is a mip slice of an array texture. - var targetRange = new List<(int BaseHandle, int RegionCount)>(); - var otherRange = new List<(int BaseHandle, int RegionCount)>(); + List<(int BaseHandle, int RegionCount)> targetRange = new List<(int BaseHandle, int RegionCount)>(); + List<(int BaseHandle, int RegionCount)> otherRange = new List<(int BaseHandle, int RegionCount)>(); EvaluateRelevantHandles(firstLayer, firstLevel, other.Info.GetSlices(), other.Info.Levels, (baseHandle, regionCount, split) => targetRange.Add((baseHandle, regionCount))); otherGroup.EvaluateRelevantHandles(other, (baseHandle, regionCount, split) => otherRange.Add((baseHandle, regionCount))); diff --git a/src/Ryujinx.Graphics.Gpu/Image/TexturePool.cs b/src/Ryujinx.Graphics.Gpu/Image/TexturePool.cs index 3bf122412..3effc39b1 100644 --- a/src/Ryujinx.Graphics.Gpu/Image/TexturePool.cs +++ b/src/Ryujinx.Graphics.Gpu/Image/TexturePool.cs @@ -118,7 +118,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// Texture with the requested format, or null if not found public Texture Find(Format format) { - foreach (var alias in _aliases) + foreach (Alias alias in _aliases) { if (alias.Format == format) { @@ -134,7 +134,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// public void Destroy() { - foreach (var entry in _aliases) + foreach (Alias entry in _aliases) { entry.Texture.DecrementReferenceCount(); } @@ -361,7 +361,7 @@ namespace Ryujinx.Graphics.Gpu.Image /// If true, queue the dereference to happen on the render thread, otherwise dereference immediately public void ForceRemove(Texture texture, int id, bool deferred) { - var previous = Interlocked.Exchange(ref Items[id], null); + Texture previous = Interlocked.Exchange(ref Items[id], null); if (deferred) { diff --git a/src/Ryujinx.Graphics.Gpu/Memory/Buffer.cs b/src/Ryujinx.Graphics.Gpu/Memory/Buffer.cs index e060e0b4f..6cc603b76 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/Buffer.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/Buffer.cs @@ -735,7 +735,7 @@ namespace Ryujinx.Graphics.Gpu.Memory { _context.Renderer.BackgroundContextAction(() => { - var ranges = _modifiedRanges; + BufferModifiedRangeList ranges = _modifiedRanges; if (ranges != null) { @@ -850,7 +850,7 @@ namespace Ryujinx.Graphics.Gpu.Memory { if (_virtualDependencies != null) { - foreach (var virtualBuffer in _virtualDependencies) + foreach (MultiRangeBuffer virtualBuffer in _virtualDependencies) { CopyToDependantVirtualBuffer(virtualBuffer, address, size); } @@ -875,7 +875,7 @@ namespace Ryujinx.Graphics.Gpu.Memory [MethodImpl(MethodImplOptions.NoInlining)] private void CopyFromDependantVirtualBuffersImpl() { - foreach (var virtualBuffer in _virtualDependencies.OrderBy(x => x.ModificationSequenceNumber)) + foreach (MultiRangeBuffer virtualBuffer in _virtualDependencies.OrderBy(x => x.ModificationSequenceNumber)) { virtualBuffer.ConsumeModifiedRegion(this, (mAddress, mSize) => { @@ -914,7 +914,7 @@ namespace Ryujinx.Graphics.Gpu.Memory { byte[] storage = dataSpan.ToArray(); - foreach (var virtualBuffer in _virtualDependencies.OrderBy(x => x.ModificationSequenceNumber)) + foreach (MultiRangeBuffer virtualBuffer in _virtualDependencies.OrderBy(x => x.ModificationSequenceNumber)) { virtualBuffer.ConsumeModifiedRegion(address, size, (mAddress, mSize) => { diff --git a/src/Ryujinx.Graphics.Gpu/Memory/BufferBackingState.cs b/src/Ryujinx.Graphics.Gpu/Memory/BufferBackingState.cs index 3f65131e6..56bc9143f 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/BufferBackingState.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/BufferBackingState.cs @@ -81,7 +81,7 @@ namespace Ryujinx.Graphics.Gpu.Memory { // Storage buffer bindings may require special treatment. - var rawStage = stage & BufferStage.StageMask; + BufferStage rawStage = stage & BufferStage.StageMask; if (rawStage == BufferStage.Fragment) { @@ -225,7 +225,7 @@ namespace Ryujinx.Graphics.Gpu.Memory // Storage write. _writeCount++; - var rawStage = stage & BufferStage.StageMask; + BufferStage rawStage = stage & BufferStage.StageMask; if (rawStage == BufferStage.Fragment) { diff --git a/src/Ryujinx.Graphics.Gpu/Memory/BufferCache.cs b/src/Ryujinx.Graphics.Gpu/Memory/BufferCache.cs index 66d2cdb62..2368da90f 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/BufferCache.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/BufferCache.cs @@ -412,7 +412,7 @@ namespace Ryujinx.Graphics.Gpu.Memory dstOffset += subRange.Size; } - foreach (var buffer in physicalBuffers) + foreach (Buffer buffer in physicalBuffers) { buffer.CopyToDependantVirtualBuffer(virtualBuffer); } @@ -1037,7 +1037,7 @@ namespace Ryujinx.Graphics.Gpu.Memory /// List used to track entries to delete private static void Prune(Dictionary dictionary, ref List toDelete) { - foreach (var entry in dictionary) + foreach (KeyValuePair entry in dictionary) { if (entry.Value.UnmappedSequence != entry.Value.Buffer.UnmappedSequence) { diff --git a/src/Ryujinx.Graphics.Gpu/Memory/BufferManager.cs b/src/Ryujinx.Graphics.Gpu/Memory/BufferManager.cs index 409867e09..a07e3445b 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/BufferManager.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/BufferManager.cs @@ -478,7 +478,7 @@ namespace Ryujinx.Graphics.Gpu.Memory /// public void CommitComputeBindings() { - var bufferCache = _channel.MemoryManager.Physical.BufferCache; + BufferCache bufferCache = _channel.MemoryManager.Physical.BufferCache; BindBuffers(bufferCache, _cpStorageBuffers, isStorage: true); BindBuffers(bufferCache, _cpUniformBuffers, isStorage: false); @@ -499,10 +499,10 @@ namespace Ryujinx.Graphics.Gpu.Memory { if (_bufferTextures.Count > 0) { - foreach (var binding in _bufferTextures) + foreach (BufferTextureBinding binding in _bufferTextures) { - var isStore = binding.BindingInfo.Flags.HasFlag(TextureUsageFlags.ImageStore); - var range = bufferCache.GetBufferRange(binding.Range, BufferStageUtils.TextureBuffer(binding.Stage, binding.BindingInfo.Flags), isStore); + bool isStore = binding.BindingInfo.Flags.HasFlag(TextureUsageFlags.ImageStore); + BufferRange range = bufferCache.GetBufferRange(binding.Range, BufferStageUtils.TextureBuffer(binding.Stage, binding.BindingInfo.Flags), isStore); binding.Texture.SetStorage(range); // The texture must be rebound to use the new storage if it was updated. @@ -524,19 +524,19 @@ namespace Ryujinx.Graphics.Gpu.Memory { ITexture[] textureArray = new ITexture[1]; - foreach (var binding in _bufferTextureArrays) + foreach (BufferTextureArrayBinding binding in _bufferTextureArrays) { - var range = bufferCache.GetBufferRange(binding.Range, BufferStage.None); + BufferRange range = bufferCache.GetBufferRange(binding.Range, BufferStage.None); binding.Texture.SetStorage(range); textureArray[0] = binding.Texture; binding.Array.SetTextures(binding.Index, textureArray); } - foreach (var binding in _bufferImageArrays) + foreach (BufferTextureArrayBinding binding in _bufferImageArrays) { - var isStore = binding.BindingInfo.Flags.HasFlag(TextureUsageFlags.ImageStore); - var range = bufferCache.GetBufferRange(binding.Range, BufferStage.None, isStore); + bool isStore = binding.BindingInfo.Flags.HasFlag(TextureUsageFlags.ImageStore); + BufferRange range = bufferCache.GetBufferRange(binding.Range, BufferStage.None, isStore); binding.Texture.SetStorage(range); textureArray[0] = binding.Texture; @@ -555,7 +555,7 @@ namespace Ryujinx.Graphics.Gpu.Memory /// True if the index buffer is in use public void CommitGraphicsBindings(bool indexed) { - var bufferCache = _channel.MemoryManager.Physical.BufferCache; + BufferCache bufferCache = _channel.MemoryManager.Physical.BufferCache; if (indexed) { @@ -750,19 +750,19 @@ namespace Ryujinx.Graphics.Gpu.Memory for (ShaderStage stage = ShaderStage.Vertex; stage <= ShaderStage.Fragment; stage++) { - ref var buffers = ref bindings[(int)stage - 1]; + ref BuffersPerStage buffers = ref bindings[(int)stage - 1]; BufferStage bufferStage = BufferStageUtils.FromShaderStage(stage); for (int index = 0; index < buffers.Count; index++) { - ref var bindingInfo = ref buffers.Bindings[index]; + ref BufferDescriptor bindingInfo = ref buffers.Bindings[index]; BufferBounds bounds = buffers.Buffers[bindingInfo.Slot]; if (!bounds.IsUnmapped) { - var isWrite = bounds.Flags.HasFlag(BufferUsageFlags.Write); - var range = isStorage + bool isWrite = bounds.Flags.HasFlag(BufferUsageFlags.Write); + BufferRange range = isStorage ? bufferCache.GetBufferRangeAligned(bounds.Range, bufferStage | BufferStageUtils.FromUsage(bounds.Flags), isWrite) : bufferCache.GetBufferRange(bounds.Range, bufferStage); @@ -792,14 +792,14 @@ namespace Ryujinx.Graphics.Gpu.Memory for (int index = 0; index < buffers.Count; index++) { - ref var bindingInfo = ref buffers.Bindings[index]; + ref BufferDescriptor bindingInfo = ref buffers.Bindings[index]; BufferBounds bounds = buffers.Buffers[bindingInfo.Slot]; if (!bounds.IsUnmapped) { - var isWrite = bounds.Flags.HasFlag(BufferUsageFlags.Write); - var range = isStorage + bool isWrite = bounds.Flags.HasFlag(BufferUsageFlags.Write); + BufferRange range = isStorage ? bufferCache.GetBufferRangeAligned(bounds.Range, BufferStageUtils.ComputeStorage(bounds.Flags), isWrite) : bufferCache.GetBufferRange(bounds.Range, BufferStage.Compute); @@ -841,11 +841,11 @@ namespace Ryujinx.Graphics.Gpu.Memory { for (ShaderStage stage = ShaderStage.Vertex; stage <= ShaderStage.Fragment; stage++) { - ref var buffers = ref bindings[(int)stage - 1]; + ref BuffersPerStage buffers = ref bindings[(int)stage - 1]; for (int index = 0; index < buffers.Count; index++) { - ref var binding = ref buffers.Bindings[index]; + ref BufferDescriptor binding = ref buffers.Bindings[index]; BufferBounds bounds = buffers.Buffers[binding.Slot]; diff --git a/src/Ryujinx.Graphics.Gpu/Memory/BufferModifiedRangeList.cs b/src/Ryujinx.Graphics.Gpu/Memory/BufferModifiedRangeList.cs index c5a12c1fc..105082f31 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/BufferModifiedRangeList.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/BufferModifiedRangeList.cs @@ -117,7 +117,7 @@ namespace Ryujinx.Graphics.Gpu.Memory lock (_lock) { // Slices a given region using the modified regions in the list. Calls the action for the new slices. - ref var overlaps = ref ThreadStaticArray.Get(); + ref BufferModifiedRange[] overlaps = ref ThreadStaticArray.Get(); int count = FindOverlapsNonOverlapping(address, size, ref overlaps); @@ -156,7 +156,7 @@ namespace Ryujinx.Graphics.Gpu.Memory lock (_lock) { // We may overlap with some existing modified regions. They must be cut into by the new entry. - ref var overlaps = ref ThreadStaticArray.Get(); + ref BufferModifiedRange[] overlaps = ref ThreadStaticArray.Get(); int count = FindOverlapsNonOverlapping(address, size, ref overlaps); @@ -210,7 +210,7 @@ namespace Ryujinx.Graphics.Gpu.Memory { int count = 0; - ref var overlaps = ref ThreadStaticArray.Get(); + ref BufferModifiedRange[] overlaps = ref ThreadStaticArray.Get(); // Range list must be consistent for this operation. lock (_lock) @@ -239,7 +239,7 @@ namespace Ryujinx.Graphics.Gpu.Memory { int count = 0; - ref var overlaps = ref ThreadStaticArray.Get(); + ref BufferModifiedRange[] overlaps = ref ThreadStaticArray.Get(); // Range list must be consistent for this operation. lock (_lock) @@ -355,7 +355,7 @@ namespace Ryujinx.Graphics.Gpu.Memory int rangeCount = 0; - ref var overlaps = ref ThreadStaticArray.Get(); + ref BufferModifiedRange[] overlaps = ref ThreadStaticArray.Get(); // Range list must be consistent for this operation lock (_lock) diff --git a/src/Ryujinx.Graphics.Gpu/Memory/BufferUpdater.cs b/src/Ryujinx.Graphics.Gpu/Memory/BufferUpdater.cs index 02090c04f..a5ee3ab70 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/BufferUpdater.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/BufferUpdater.cs @@ -73,7 +73,7 @@ namespace Ryujinx.Graphics.Gpu.Memory if (binding >= 0) { - var range = new BufferRange(_handle, 0, data.Length); + BufferRange range = new BufferRange(_handle, 0, data.Length); _renderer.Pipeline.SetUniformBuffers(stackalloc[] { new BufferAssignment(0, range) }); } }; diff --git a/src/Ryujinx.Graphics.Gpu/Memory/GpuRegionHandle.cs b/src/Ryujinx.Graphics.Gpu/Memory/GpuRegionHandle.cs index bdb7cf2c2..77eb7c4a4 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/GpuRegionHandle.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/GpuRegionHandle.cs @@ -14,7 +14,7 @@ namespace Ryujinx.Graphics.Gpu.Memory { get { - foreach (var regionHandle in _cpuRegionHandles) + foreach (RegionHandle regionHandle in _cpuRegionHandles) { if (regionHandle.Dirty) { @@ -44,7 +44,7 @@ namespace Ryujinx.Graphics.Gpu.Memory /// public void Dispose() { - foreach (var regionHandle in _cpuRegionHandles) + foreach (RegionHandle regionHandle in _cpuRegionHandles) { regionHandle.Dispose(); } @@ -57,7 +57,7 @@ namespace Ryujinx.Graphics.Gpu.Memory /// Action to call on read or write public void RegisterAction(RegionSignal action) { - foreach (var regionHandle in _cpuRegionHandles) + foreach (RegionHandle regionHandle in _cpuRegionHandles) { regionHandle.RegisterAction(action); } @@ -70,7 +70,7 @@ namespace Ryujinx.Graphics.Gpu.Memory /// Action to call on read or write public void RegisterPreciseAction(PreciseRegionSignal action) { - foreach (var regionHandle in _cpuRegionHandles) + foreach (RegionHandle regionHandle in _cpuRegionHandles) { regionHandle.RegisterPreciseAction(action); } @@ -81,7 +81,7 @@ namespace Ryujinx.Graphics.Gpu.Memory /// public void Reprotect(bool asDirty = false) { - foreach (var regionHandle in _cpuRegionHandles) + foreach (RegionHandle regionHandle in _cpuRegionHandles) { regionHandle.Reprotect(asDirty); } @@ -92,7 +92,7 @@ namespace Ryujinx.Graphics.Gpu.Memory /// public void ForceDirty() { - foreach (var regionHandle in _cpuRegionHandles) + foreach (RegionHandle regionHandle in _cpuRegionHandles) { regionHandle.ForceDirty(); } diff --git a/src/Ryujinx.Graphics.Gpu/Memory/MemoryManager.cs b/src/Ryujinx.Graphics.Gpu/Memory/MemoryManager.cs index 59e618c02..5ee5ce456 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/MemoryManager.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/MemoryManager.cs @@ -458,7 +458,7 @@ namespace Ryujinx.Graphics.Gpu.Memory int pages = (int)((endVaRounded - va) / PageSize); - var regions = new List(); + List regions = new List(); for (int page = 0; page < pages - 1; page++) { diff --git a/src/Ryujinx.Graphics.Gpu/Memory/MultiRangeBuffer.cs b/src/Ryujinx.Graphics.Gpu/Memory/MultiRangeBuffer.cs index d92b0836e..19ef56bb1 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/MultiRangeBuffer.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/MultiRangeBuffer.cs @@ -149,7 +149,7 @@ namespace Ryujinx.Graphics.Gpu.Memory if (_dependencies != null) { - foreach (var dependency in _dependencies) + foreach (PhysicalDependency dependency in _dependencies) { if (dependency.PhysicalBuffer == buffer && dependency.VirtualOffset >= minimumVirtOffset) { @@ -231,7 +231,7 @@ namespace Ryujinx.Graphics.Gpu.Memory { if (_dependencies != null) { - foreach (var dependency in _dependencies) + foreach (PhysicalDependency dependency in _dependencies) { dependency.PhysicalBuffer.RemoveVirtualDependency(this); } diff --git a/src/Ryujinx.Graphics.Gpu/Memory/PhysicalMemory.cs b/src/Ryujinx.Graphics.Gpu/Memory/PhysicalMemory.cs index b22cc01b8..d9dd7f1d9 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/PhysicalMemory.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/PhysicalMemory.cs @@ -102,10 +102,10 @@ namespace Ryujinx.Graphics.Gpu.Memory { if (range.Count == 1) { - var singleRange = range.GetSubRange(0); + MemoryRange singleRange = range.GetSubRange(0); if (singleRange.Address != MemoryManager.PteUnmapped) { - var regions = _cpuMemory.GetHostRegions(singleRange.Address, singleRange.Size); + IEnumerable regions = _cpuMemory.GetHostRegions(singleRange.Address, singleRange.Size); if (regions != null && regions.Count() == 1) { @@ -139,7 +139,7 @@ namespace Ryujinx.Graphics.Gpu.Memory { if (range.Count == 1) { - var singleRange = range.GetSubRange(0); + MemoryRange singleRange = range.GetSubRange(0); if (singleRange.Address != MemoryManager.PteUnmapped) { return _cpuMemory.GetSpan(singleRange.Address, (int)singleRange.Size, tracked); @@ -152,7 +152,7 @@ namespace Ryujinx.Graphics.Gpu.Memory for (int i = 0; i < range.Count; i++) { - var currentRange = range.GetSubRange(i); + MemoryRange currentRange = range.GetSubRange(i); int size = (int)currentRange.Size; if (currentRange.Address != MemoryManager.PteUnmapped) { @@ -199,7 +199,7 @@ namespace Ryujinx.Graphics.Gpu.Memory int offset = 0; for (int i = 0; i < range.Count; i++) { - var currentRange = range.GetSubRange(i); + MemoryRange currentRange = range.GetSubRange(i); int size = (int)currentRange.Size; if (currentRange.Address != MemoryManager.PteUnmapped) { @@ -322,7 +322,7 @@ namespace Ryujinx.Graphics.Gpu.Memory { if (range.Count == 1) { - var singleRange = range.GetSubRange(0); + MemoryRange singleRange = range.GetSubRange(0); if (singleRange.Address != MemoryManager.PteUnmapped) { writeCallback(singleRange.Address, data); @@ -334,7 +334,7 @@ namespace Ryujinx.Graphics.Gpu.Memory for (int i = 0; i < range.Count; i++) { - var currentRange = range.GetSubRange(i); + MemoryRange currentRange = range.GetSubRange(i); int size = (int)currentRange.Size; if (currentRange.Address != MemoryManager.PteUnmapped) { @@ -382,12 +382,12 @@ namespace Ryujinx.Graphics.Gpu.Memory /// The memory tracking handle public GpuRegionHandle BeginTracking(MultiRange range, ResourceKind kind) { - var cpuRegionHandles = new RegionHandle[range.Count]; + RegionHandle[] cpuRegionHandles = new RegionHandle[range.Count]; int count = 0; for (int i = 0; i < range.Count; i++) { - var currentRange = range.GetSubRange(i); + MemoryRange currentRange = range.GetSubRange(i); if (currentRange.Address != MemoryManager.PteUnmapped) { cpuRegionHandles[count++] = _cpuMemory.BeginTracking(currentRange.Address, currentRange.Size, (int)kind); diff --git a/src/Ryujinx.Graphics.Gpu/Memory/SupportBufferUpdater.cs b/src/Ryujinx.Graphics.Gpu/Memory/SupportBufferUpdater.cs index fc444f49c..20831fa99 100644 --- a/src/Ryujinx.Graphics.Gpu/Memory/SupportBufferUpdater.cs +++ b/src/Ryujinx.Graphics.Gpu/Memory/SupportBufferUpdater.cs @@ -19,7 +19,7 @@ namespace Ryujinx.Graphics.Gpu.Memory /// Renderer that the support buffer will be used with public SupportBufferUpdater(IRenderer renderer) : base(renderer) { - var defaultScale = new Vector4 { X = 1f, Y = 0f, Z = 0f, W = 0f }; + Vector4 defaultScale = new Vector4 { X = 1f, Y = 0f, Z = 0f, W = 0f }; _data.RenderScale.AsSpan().Fill(defaultScale); DirtyRenderScale(0, SupportBuffer.RenderScaleMaxCount); } diff --git a/src/Ryujinx.Graphics.Gpu/Shader/CachedShaderBindings.cs b/src/Ryujinx.Graphics.Gpu/Shader/CachedShaderBindings.cs index 018c5fdc0..a4bcbc6f5 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/CachedShaderBindings.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/CachedShaderBindings.cs @@ -60,7 +60,7 @@ namespace Ryujinx.Graphics.Gpu.Shader { Target target = descriptor.Type != SamplerType.None ? ShaderTexture.GetTarget(descriptor.Type) : default; - var result = new TextureBindingInfo( + TextureBindingInfo result = new TextureBindingInfo( target, descriptor.Set, descriptor.Binding, @@ -88,7 +88,7 @@ namespace Ryujinx.Graphics.Gpu.Shader Target target = ShaderTexture.GetTarget(descriptor.Type); FormatInfo formatInfo = ShaderTexture.GetFormatInfo(descriptor.Format); - var result = new TextureBindingInfo( + TextureBindingInfo result = new TextureBindingInfo( target, formatInfo, descriptor.Set, diff --git a/src/Ryujinx.Graphics.Gpu/Shader/ComputeShaderCacheHashTable.cs b/src/Ryujinx.Graphics.Gpu/Shader/ComputeShaderCacheHashTable.cs index 0119a6a33..49516b310 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/ComputeShaderCacheHashTable.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/ComputeShaderCacheHashTable.cs @@ -26,7 +26,7 @@ namespace Ryujinx.Graphics.Gpu.Shader /// Program to be added public void Add(CachedShaderProgram program) { - var specList = _cache.GetOrAdd(program.Shaders[0].Code, new ShaderSpecializationList()); + ShaderSpecializationList specList = _cache.GetOrAdd(program.Shaders[0].Code, new ShaderSpecializationList()); specList.Add(program); _shaderPrograms.Add(program); } @@ -51,7 +51,7 @@ namespace Ryujinx.Graphics.Gpu.Shader { program = null; ShaderCodeAccessor codeAccessor = new(channel.MemoryManager, gpuVa); - bool hasSpecList = _cache.TryFindItem(codeAccessor, out var specList, out cachedGuestCode); + bool hasSpecList = _cache.TryFindItem(codeAccessor, out ShaderSpecializationList specList, out cachedGuestCode); return hasSpecList && specList.TryFindForCompute(channel, poolState, computeState, out program); } @@ -62,7 +62,7 @@ namespace Ryujinx.Graphics.Gpu.Shader /// Programs added to the table public IEnumerable GetPrograms() { - foreach (var program in _shaderPrograms) + foreach (CachedShaderProgram program in _shaderPrograms) { yield return program; } diff --git a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheGuestStorage.cs b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheGuestStorage.cs index 22af88d31..237ae18ec 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheGuestStorage.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheGuestStorage.cs @@ -180,8 +180,8 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// public void ClearCache() { - using var tocFileStream = DiskCacheCommon.OpenFile(_basePath, TocFileName, writable: true); - using var dataFileStream = DiskCacheCommon.OpenFile(_basePath, DataFileName, writable: true); + using FileStream tocFileStream = DiskCacheCommon.OpenFile(_basePath, TocFileName, writable: true); + using FileStream dataFileStream = DiskCacheCommon.OpenFile(_basePath, DataFileName, writable: true); tocFileStream.SetLength(0); dataFileStream.SetLength(0); @@ -258,8 +258,8 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// Index of the shader on the cache public int AddShader(ReadOnlySpan data, ReadOnlySpan cb1Data) { - using var tocFileStream = DiskCacheCommon.OpenFile(_basePath, TocFileName, writable: true); - using var dataFileStream = DiskCacheCommon.OpenFile(_basePath, DataFileName, writable: true); + using FileStream tocFileStream = DiskCacheCommon.OpenFile(_basePath, TocFileName, writable: true); + using FileStream dataFileStream = DiskCacheCommon.OpenFile(_basePath, DataFileName, writable: true); TocHeader header = new(); @@ -267,9 +267,9 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache uint hash = CalcHash(data, cb1Data); - if (_toc.TryGetValue(hash, out var list)) + if (_toc.TryGetValue(hash, out List list)) { - foreach (var entry in list) + foreach (TocMemoryEntry entry in list) { if (data.Length != entry.CodeSize || cb1Data.Length != entry.Cb1DataSize) { @@ -427,7 +427,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// Index of the data on the cache private void AddTocMemoryEntry(uint dataOffset, uint codeSize, uint cb1DataSize, uint hash, int index) { - if (!_toc.TryGetValue(hash, out var list)) + if (!_toc.TryGetValue(hash, out List list)) { _toc.Add(hash, list = new List()); } diff --git a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheHostStorage.cs b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheHostStorage.cs index b6b811389..4ef0caced 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheHostStorage.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/DiskCacheHostStorage.cs @@ -301,11 +301,11 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache try { - using var tocFileStream = DiskCacheCommon.OpenFile(_basePath, SharedTocFileName, writable: false); - using var dataFileStream = DiskCacheCommon.OpenFile(_basePath, SharedDataFileName, writable: false); + using FileStream tocFileStream = DiskCacheCommon.OpenFile(_basePath, SharedTocFileName, writable: false); + using FileStream dataFileStream = DiskCacheCommon.OpenFile(_basePath, SharedDataFileName, writable: false); - using var guestTocFileStream = _guestStorage.OpenTocFileStream(); - using var guestDataFileStream = _guestStorage.OpenDataFileStream(); + using Stream guestTocFileStream = _guestStorage.OpenTocFileStream(); + using Stream guestDataFileStream = _guestStorage.OpenDataFileStream(); BinarySerializer tocReader = new(tocFileStream); BinarySerializer dataReader = new(dataFileStream); @@ -547,11 +547,11 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// A collection of disk cache output streams public DiskCacheOutputStreams GetOutputStreams(GpuContext context) { - var tocFileStream = DiskCacheCommon.OpenFile(_basePath, SharedTocFileName, writable: true); - var dataFileStream = DiskCacheCommon.OpenFile(_basePath, SharedDataFileName, writable: true); + FileStream tocFileStream = DiskCacheCommon.OpenFile(_basePath, SharedTocFileName, writable: true); + FileStream dataFileStream = DiskCacheCommon.OpenFile(_basePath, SharedDataFileName, writable: true); - var hostTocFileStream = DiskCacheCommon.OpenFile(_basePath, GetHostTocFileName(context), writable: true); - var hostDataFileStream = DiskCacheCommon.OpenFile(_basePath, GetHostDataFileName(context), writable: true); + FileStream hostTocFileStream = DiskCacheCommon.OpenFile(_basePath, GetHostTocFileName(context), writable: true); + FileStream hostDataFileStream = DiskCacheCommon.OpenFile(_basePath, GetHostDataFileName(context), writable: true); return new DiskCacheOutputStreams(tocFileStream, dataFileStream, hostTocFileStream, hostDataFileStream); } @@ -569,7 +569,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache for (int index = 0; index < program.Shaders.Length; index++) { - var shader = program.Shaders[index]; + CachedShaderStage shader = program.Shaders[index]; if (shader == null || (shader.Info != null && shader.Info.Stage == ShaderStage.Compute)) { continue; @@ -578,8 +578,8 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache stagesBitMask |= 1u << index; } - var tocFileStream = streams != null ? streams.TocFileStream : DiskCacheCommon.OpenFile(_basePath, SharedTocFileName, writable: true); - var dataFileStream = streams != null ? streams.DataFileStream : DiskCacheCommon.OpenFile(_basePath, SharedDataFileName, writable: true); + FileStream tocFileStream = streams != null ? streams.TocFileStream : DiskCacheCommon.OpenFile(_basePath, SharedTocFileName, writable: true); + FileStream dataFileStream = streams != null ? streams.DataFileStream : DiskCacheCommon.OpenFile(_basePath, SharedDataFileName, writable: true); ulong timestamp = (ulong)DateTime.UtcNow.Subtract(DateTime.UnixEpoch).TotalSeconds; @@ -610,7 +610,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache for (int index = 0; index < program.Shaders.Length; index++) { - var shader = program.Shaders[index]; + CachedShaderStage shader = program.Shaders[index]; if (shader == null) { continue; @@ -655,8 +655,8 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// GPU context public void ClearSharedCache() { - using var tocFileStream = DiskCacheCommon.OpenFile(_basePath, SharedTocFileName, writable: true); - using var dataFileStream = DiskCacheCommon.OpenFile(_basePath, SharedDataFileName, writable: true); + using FileStream tocFileStream = DiskCacheCommon.OpenFile(_basePath, SharedTocFileName, writable: true); + using FileStream dataFileStream = DiskCacheCommon.OpenFile(_basePath, SharedDataFileName, writable: true); tocFileStream.SetLength(0); dataFileStream.SetLength(0); @@ -668,8 +668,8 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache /// GPU context public void ClearHostCache(GpuContext context) { - using var tocFileStream = DiskCacheCommon.OpenFile(_basePath, GetHostTocFileName(context), writable: true); - using var dataFileStream = DiskCacheCommon.OpenFile(_basePath, GetHostDataFileName(context), writable: true); + using FileStream tocFileStream = DiskCacheCommon.OpenFile(_basePath, GetHostTocFileName(context), writable: true); + using FileStream dataFileStream = DiskCacheCommon.OpenFile(_basePath, GetHostDataFileName(context), writable: true); tocFileStream.SetLength(0); dataFileStream.SetLength(0); @@ -690,8 +690,8 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache DiskCacheOutputStreams streams, ulong timestamp) { - var tocFileStream = streams != null ? streams.HostTocFileStream : DiskCacheCommon.OpenFile(_basePath, GetHostTocFileName(context), writable: true); - var dataFileStream = streams != null ? streams.HostDataFileStream : DiskCacheCommon.OpenFile(_basePath, GetHostDataFileName(context), writable: true); + FileStream tocFileStream = streams != null ? streams.HostTocFileStream : DiskCacheCommon.OpenFile(_basePath, GetHostTocFileName(context), writable: true); + FileStream dataFileStream = streams != null ? streams.HostDataFileStream : DiskCacheCommon.OpenFile(_basePath, GetHostDataFileName(context), writable: true); if (tocFileStream.Length == 0) { @@ -853,25 +853,25 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache for (int index = 0; index < info.CBuffers.Count; index++) { - var entry = info.CBuffers[index]; + BufferDescriptor entry = info.CBuffers[index]; dataWriter.WriteWithMagicAndSize(ref entry, BufdMagic); } for (int index = 0; index < info.SBuffers.Count; index++) { - var entry = info.SBuffers[index]; + BufferDescriptor entry = info.SBuffers[index]; dataWriter.WriteWithMagicAndSize(ref entry, BufdMagic); } for (int index = 0; index < info.Textures.Count; index++) { - var entry = info.Textures[index]; + TextureDescriptor entry = info.Textures[index]; dataWriter.WriteWithMagicAndSize(ref entry, TexdMagic); } for (int index = 0; index < info.Images.Count; index++) { - var entry = info.Images[index]; + TextureDescriptor entry = info.Images[index]; dataWriter.WriteWithMagicAndSize(ref entry, TexdMagic); } } diff --git a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/ParallelDiskCacheLoader.cs b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/ParallelDiskCacheLoader.cs index eb0f72af1..9424a1084 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/ParallelDiskCacheLoader.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/DiskCache/ParallelDiskCacheLoader.cs @@ -303,10 +303,10 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache Logger.Info?.Print(LogClass.Gpu, $"Rebuilding {_programList.Count} shaders..."); - using var streams = _hostStorage.GetOutputStreams(_context); + using DiskCacheOutputStreams streams = _hostStorage.GetOutputStreams(_context); int packagedShaders = 0; - foreach (var kv in _programList) + foreach (KeyValuePair kv in _programList) { if (!Active) { diff --git a/src/Ryujinx.Graphics.Gpu/Shader/GpuAccessor.cs b/src/Ryujinx.Graphics.Gpu/Shader/GpuAccessor.cs index 4e9134291..c7d86a47e 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/GpuAccessor.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/GpuAccessor.cs @@ -4,6 +4,7 @@ using Ryujinx.Graphics.Shader; using Ryujinx.Graphics.Shader.Translation; using System; using System.Runtime.InteropServices; +using TextureDescriptor = Ryujinx.Graphics.Gpu.Image.TextureDescriptor; namespace Ryujinx.Graphics.Gpu.Shader { @@ -177,7 +178,7 @@ namespace Ryujinx.Graphics.Gpu.Shader public TextureFormat QueryTextureFormat(int handle, int cbufSlot) { _state.SpecializationState?.RecordTextureFormat(_stageIndex, handle, cbufSlot); - var descriptor = GetTextureDescriptor(handle, cbufSlot); + TextureDescriptor descriptor = GetTextureDescriptor(handle, cbufSlot); return ConvertToTextureFormat(descriptor.UnpackFormat(), descriptor.UnpackSrgb()); } diff --git a/src/Ryujinx.Graphics.Gpu/Shader/ShaderCache.cs b/src/Ryujinx.Graphics.Gpu/Shader/ShaderCache.cs index b50ea174d..3ff92896b 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/ShaderCache.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/ShaderCache.cs @@ -205,7 +205,7 @@ namespace Ryujinx.Graphics.Gpu.Shader GpuChannelComputeState computeState, ulong gpuVa) { - if (_cpPrograms.TryGetValue(gpuVa, out var cpShader) && IsShaderEqual(channel, poolState, computeState, cpShader, gpuVa)) + if (_cpPrograms.TryGetValue(gpuVa, out CachedShaderProgram cpShader) && IsShaderEqual(channel, poolState, computeState, cpShader, gpuVa)) { return cpShader; } @@ -255,8 +255,8 @@ namespace Ryujinx.Graphics.Gpu.Shader { channel.TextureManager.UpdateRenderTargets(); - var rtControl = state.RtControl; - var msaaMode = state.RtMsaaMode; + RtControl rtControl = state.RtControl; + TextureMsaaMode msaaMode = state.RtMsaaMode; pipeline.SamplesCount = msaaMode.SamplesInX() * msaaMode.SamplesInY(); @@ -266,7 +266,7 @@ namespace Ryujinx.Graphics.Gpu.Shader { int rtIndex = rtControl.UnpackPermutationIndex(index); - var colorState = state.RtColorState[rtIndex]; + RtColorState colorState = state.RtColorState[rtIndex]; if (index >= count || colorState.Format == 0 || colorState.WidthOrStride == 0) { @@ -311,12 +311,12 @@ namespace Ryujinx.Graphics.Gpu.Shader ref GpuChannelGraphicsState graphicsState, ShaderAddresses addresses) { - if (_gpPrograms.TryGetValue(addresses, out var gpShaders) && IsShaderEqual(channel, ref poolState, ref graphicsState, gpShaders, addresses)) + if (_gpPrograms.TryGetValue(addresses, out CachedShaderProgram gpShaders) && IsShaderEqual(channel, ref poolState, ref graphicsState, gpShaders, addresses)) { return gpShaders; } - if (_graphicsShaderCache.TryFind(channel, ref poolState, ref graphicsState, addresses, out gpShaders, out var cachedGuestCode)) + if (_graphicsShaderCache.TryFind(channel, ref poolState, ref graphicsState, addresses, out gpShaders, out CachedGraphicsGuestCode cachedGuestCode)) { _gpPrograms[addresses] = gpShaders; return gpShaders; @@ -587,7 +587,7 @@ namespace Ryujinx.Graphics.Gpu.Shader for (int i = 0; i < Constants.TotalTransformFeedbackBuffers; i++) { - var tf = state.TfState[i]; + TfState tf = state.TfState[i]; descs[i] = new TransformFeedbackDescriptor( tf.BufferIndex, @@ -693,7 +693,7 @@ namespace Ryujinx.Graphics.Gpu.Shader /// The generated translator context public static TranslatorContext DecodeComputeShader(IGpuAccessor gpuAccessor, TargetApi api, ulong gpuVa) { - var options = CreateTranslationOptions(api, DefaultFlags | TranslationFlags.Compute); + TranslationOptions options = CreateTranslationOptions(api, DefaultFlags | TranslationFlags.Compute); return Translator.CreateContext(gpuVa, gpuAccessor, options); } @@ -710,7 +710,7 @@ namespace Ryujinx.Graphics.Gpu.Shader /// The generated translator context public static TranslatorContext DecodeGraphicsShader(IGpuAccessor gpuAccessor, TargetApi api, TranslationFlags flags, ulong gpuVa) { - var options = CreateTranslationOptions(api, flags); + TranslationOptions options = CreateTranslationOptions(api, flags); return Translator.CreateContext(gpuVa, gpuAccessor, options); } @@ -736,7 +736,7 @@ namespace Ryujinx.Graphics.Gpu.Shader { ulong cb1DataAddress = channel.BufferManager.GetGraphicsUniformBufferAddress(0, 1); - var memoryManager = channel.MemoryManager; + MemoryManager memoryManager = channel.MemoryManager; codeA ??= memoryManager.GetSpan(vertexA.Address, vertexA.Size).ToArray(); codeB ??= memoryManager.GetSpan(currentStage.Address, currentStage.Size).ToArray(); @@ -774,7 +774,7 @@ namespace Ryujinx.Graphics.Gpu.Shader /// Compiled graphics shader code private static TranslatedShader TranslateShader(ShaderDumper dumper, GpuChannel channel, TranslatorContext context, byte[] code, bool asCompute) { - var memoryManager = channel.MemoryManager; + MemoryManager memoryManager = channel.MemoryManager; ulong cb1DataAddress = context.Stage == ShaderStage.Compute ? channel.BufferManager.GetComputeUniformBufferAddress(1) diff --git a/src/Ryujinx.Graphics.Gpu/Shader/ShaderCacheHashTable.cs b/src/Ryujinx.Graphics.Gpu/Shader/ShaderCacheHashTable.cs index e65a1dec9..562837791 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/ShaderCacheHashTable.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/ShaderCacheHashTable.cs @@ -156,7 +156,7 @@ namespace Ryujinx.Graphics.Gpu.Shader { IdTable idTable = new(); - foreach (var shader in program.Shaders) + foreach (CachedShaderStage shader in program.Shaders) { if (shader == null) { @@ -221,7 +221,7 @@ namespace Ryujinx.Graphics.Gpu.Shader out CachedShaderProgram program, out CachedGraphicsGuestCode guestCode) { - var memoryManager = channel.MemoryManager; + MemoryManager memoryManager = channel.MemoryManager; IdTable idTable = new(); guestCode = new CachedGraphicsGuestCode(); @@ -270,9 +270,9 @@ namespace Ryujinx.Graphics.Gpu.Shader /// Programs added to the table public IEnumerable GetPrograms() { - foreach (var specList in _shaderPrograms.Values) + foreach (ShaderSpecializationList specList in _shaderPrograms.Values) { - foreach (var program in specList) + foreach (CachedShaderProgram program in specList) { yield return program; } diff --git a/src/Ryujinx.Graphics.Gpu/Shader/ShaderInfoBuilder.cs b/src/Ryujinx.Graphics.Gpu/Shader/ShaderInfoBuilder.cs index e283d0832..50061db60 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/ShaderInfoBuilder.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/ShaderInfoBuilder.cs @@ -372,8 +372,8 @@ namespace Ryujinx.Graphics.Gpu.Shader { int totalSets = _resourceDescriptors.Length; - var descriptors = new ResourceDescriptorCollection[totalSets]; - var usages = new ResourceUsageCollection[totalSets]; + ResourceDescriptorCollection[] descriptors = new ResourceDescriptorCollection[totalSets]; + ResourceUsageCollection[] usages = new ResourceUsageCollection[totalSets]; for (int index = 0; index < totalSets; index++) { diff --git a/src/Ryujinx.Graphics.Gpu/Shader/ShaderSpecializationList.cs b/src/Ryujinx.Graphics.Gpu/Shader/ShaderSpecializationList.cs index 3c2f0b9be..25ed6e7ef 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/ShaderSpecializationList.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/ShaderSpecializationList.cs @@ -33,7 +33,7 @@ namespace Ryujinx.Graphics.Gpu.Shader ref GpuChannelGraphicsState graphicsState, out CachedShaderProgram program) { - foreach (var entry in _entries) + foreach (CachedShaderProgram entry in _entries) { bool vertexAsCompute = entry.VertexAsCompute != null; bool usesDrawParameters = entry.Shaders[1]?.Info.UsesDrawParameters ?? false; @@ -65,7 +65,7 @@ namespace Ryujinx.Graphics.Gpu.Shader /// True if a compatible program is found, false otherwise public bool TryFindForCompute(GpuChannel channel, GpuChannelPoolState poolState, GpuChannelComputeState computeState, out CachedShaderProgram program) { - foreach (var entry in _entries) + foreach (CachedShaderProgram entry in _entries) { if (entry.SpecializationState.MatchesCompute(channel, ref poolState, computeState, true)) { diff --git a/src/Ryujinx.Graphics.Gpu/Shader/ShaderSpecializationState.cs b/src/Ryujinx.Graphics.Gpu/Shader/ShaderSpecializationState.cs index 1230c0580..4bb4392e1 100644 --- a/src/Ryujinx.Graphics.Gpu/Shader/ShaderSpecializationState.cs +++ b/src/Ryujinx.Graphics.Gpu/Shader/ShaderSpecializationState.cs @@ -6,10 +6,12 @@ using Ryujinx.Graphics.Gpu.Shader.DiskCache; using Ryujinx.Graphics.Shader; using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Linq; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using TextureDescriptor = Ryujinx.Graphics.Shader.TextureDescriptor; namespace Ryujinx.Graphics.Gpu.Shader { @@ -214,23 +216,23 @@ namespace Ryujinx.Graphics.Gpu.Shader CachedShaderStage stage = stages[i]; if (stage?.Info != null) { - var textures = stage.Info.Textures; - var images = stage.Info.Images; + ReadOnlyCollection textures = stage.Info.Textures; + ReadOnlyCollection images = stage.Info.Images; - var texBindings = new Box[textures.Count]; - var imageBindings = new Box[images.Count]; + Box[] texBindings = new Box[textures.Count]; + Box[] imageBindings = new Box[images.Count]; int stageIndex = Math.Max(i - 1, 0); // Don't count VertexA for looking up spec state. No-Op for compute. for (int j = 0; j < textures.Count; j++) { - var texture = textures[j]; + TextureDescriptor texture = textures[j]; texBindings[j] = GetTextureSpecState(stageIndex, texture.HandleIndex, texture.CbufSlot); } for (int j = 0; j < images.Count; j++) { - var image = images[j]; + TextureDescriptor image = images[j]; imageBindings[j] = GetTextureSpecState(stageIndex, image.HandleIndex, image.CbufSlot); } @@ -753,7 +755,7 @@ namespace Ryujinx.Graphics.Gpu.Shader ReadOnlySpan cachedTextureBuffer = Span.Empty; ReadOnlySpan cachedSamplerBuffer = Span.Empty; - foreach (var kv in _allTextures) + foreach (KeyValuePair> kv in _allTextures) { TextureKey textureKey = kv.Key; @@ -1009,10 +1011,10 @@ namespace Ryujinx.Graphics.Gpu.Shader ushort count = (ushort)_textureSpecialization.Count; dataWriter.Write(ref count); - foreach (var kv in _textureSpecialization) + foreach (KeyValuePair> kv in _textureSpecialization) { - var textureKey = kv.Key; - var textureState = kv.Value; + TextureKey textureKey = kv.Key; + Box textureState = kv.Value; dataWriter.WriteWithMagicAndSize(ref textureKey, TexkMagic); dataWriter.WriteWithMagicAndSize(ref textureState.Value, TexsMagic); @@ -1023,10 +1025,10 @@ namespace Ryujinx.Graphics.Gpu.Shader count = (ushort)_textureArrayFromBufferSpecialization.Count; dataWriter.Write(ref count); - foreach (var kv in _textureArrayFromBufferSpecialization) + foreach (KeyValuePair kv in _textureArrayFromBufferSpecialization) { - var textureKey = kv.Key; - var length = kv.Value; + TextureKey textureKey = kv.Key; + int length = kv.Value; dataWriter.WriteWithMagicAndSize(ref textureKey, TexkMagic); dataWriter.Write(ref length); @@ -1038,10 +1040,10 @@ namespace Ryujinx.Graphics.Gpu.Shader count = (ushort)_textureArrayFromPoolSpecialization.Count; dataWriter.Write(ref count); - foreach (var kv in _textureArrayFromPoolSpecialization) + foreach (KeyValuePair kv in _textureArrayFromPoolSpecialization) { - var textureKey = kv.Key; - var length = kv.Value; + bool textureKey = kv.Key; + int length = kv.Value; dataWriter.WriteWithMagicAndSize(ref textureKey, TexkMagic); dataWriter.Write(ref length); diff --git a/src/Ryujinx.Graphics.Gpu/Synchronization/SynchronizationManager.cs b/src/Ryujinx.Graphics.Gpu/Synchronization/SynchronizationManager.cs index 1042a4db8..b68a64a47 100644 --- a/src/Ryujinx.Graphics.Gpu/Synchronization/SynchronizationManager.cs +++ b/src/Ryujinx.Graphics.Gpu/Synchronization/SynchronizationManager.cs @@ -87,7 +87,7 @@ namespace Ryujinx.Graphics.Gpu.Synchronization } using ManualResetEvent waitEvent = new(false); - var info = _syncpoints[id].RegisterCallback(threshold, (x) => waitEvent.Set()); + SyncpointWaiterHandle info = _syncpoints[id].RegisterCallback(threshold, (x) => waitEvent.Set()); if (info == null) { diff --git a/src/Ryujinx.Graphics.Gpu/Window.cs b/src/Ryujinx.Graphics.Gpu/Window.cs index 59cd4c8a6..5c3463f2a 100644 --- a/src/Ryujinx.Graphics.Gpu/Window.cs +++ b/src/Ryujinx.Graphics.Gpu/Window.cs @@ -1,5 +1,6 @@ using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.Gpu.Image; +using Ryujinx.Graphics.Gpu.Memory; using Ryujinx.Graphics.Texture; using Ryujinx.Memory.Range; using System; @@ -137,7 +138,7 @@ namespace Ryujinx.Graphics.Gpu Action releaseCallback, object userObj) { - if (!_context.PhysicalMemoryRegistry.TryGetValue(pid, out var physicalMemory)) + if (!_context.PhysicalMemoryRegistry.TryGetValue(pid, out PhysicalMemory physicalMemory)) { return false; } diff --git a/src/Ryujinx.Graphics.Host1x/Devices.cs b/src/Ryujinx.Graphics.Host1x/Devices.cs index 9de2b81a9..984a5abd6 100644 --- a/src/Ryujinx.Graphics.Host1x/Devices.cs +++ b/src/Ryujinx.Graphics.Host1x/Devices.cs @@ -20,7 +20,7 @@ namespace Ryujinx.Graphics.Host1x public void Dispose() { - foreach (var device in _devices.Values) + foreach (IDeviceState device in _devices.Values) { if (device is ThiDevice thi) { diff --git a/src/Ryujinx.Graphics.Host1x/Host1xDevice.cs b/src/Ryujinx.Graphics.Host1x/Host1xDevice.cs index 2db74ce5e..62fcef348 100644 --- a/src/Ryujinx.Graphics.Host1x/Host1xDevice.cs +++ b/src/Ryujinx.Graphics.Host1x/Host1xDevice.cs @@ -46,7 +46,7 @@ namespace Ryujinx.Graphics.Host1x public void RegisterDevice(ClassId classId, IDeviceState device) { - var thi = new ThiDevice(classId, device ?? throw new ArgumentNullException(nameof(device)), _syncptIncrMgr); + ThiDevice thi = new ThiDevice(classId, device ?? throw new ArgumentNullException(nameof(device)), _syncptIncrMgr); _devices.RegisterDevice(classId, thi); } From 76ec047eb77f2d3ea33a720e49772ad9904d0b0e Mon Sep 17 00:00:00 2001 From: Evan Husted Date: Sat, 25 Jan 2025 14:06:26 -0600 Subject: [PATCH 07/19] misc: chore: Use explicit types in Metal project --- src/Ryujinx.Graphics.Host1x/Host1xDevice.cs | 2 +- .../BackgroundResources.cs | 2 +- src/Ryujinx.Graphics.Metal/BufferHolder.cs | 18 +- src/Ryujinx.Graphics.Metal/BufferManager.cs | 24 +-- .../CommandBufferEncoder.cs | 8 +- .../CommandBufferPool.cs | 22 +-- .../DepthStencilCache.cs | 6 +- src/Ryujinx.Graphics.Metal/EncoderState.cs | 4 +- .../EncoderStateManager.cs | 169 +++++++++--------- src/Ryujinx.Graphics.Metal/FormatTable.cs | 2 +- src/Ryujinx.Graphics.Metal/HardwareInfo.cs | 22 +-- src/Ryujinx.Graphics.Metal/HashTableSlim.cs | 14 +- src/Ryujinx.Graphics.Metal/HelperShader.cs | 104 +++++------ .../IndexBufferState.cs | 2 +- src/Ryujinx.Graphics.Metal/MetalRenderer.cs | 8 +- .../MultiFenceHolder.cs | 8 +- .../PersistentFlushBuffer.cs | 25 +-- src/Ryujinx.Graphics.Metal/Pipeline.cs | 58 +++--- src/Ryujinx.Graphics.Metal/Program.cs | 10 +- .../ResourceLayoutBuilder.cs | 4 +- src/Ryujinx.Graphics.Metal/SamplerHolder.cs | 4 +- src/Ryujinx.Graphics.Metal/StagingBuffer.cs | 14 +- .../State/PipelineState.cs | 26 +-- .../State/PipelineUid.cs | 2 +- src/Ryujinx.Graphics.Metal/StateCache.cs | 4 +- src/Ryujinx.Graphics.Metal/Texture.cs | 60 +++---- .../VertexBufferState.cs | 2 +- src/Ryujinx.Graphics.Metal/Window.cs | 4 +- 28 files changed, 315 insertions(+), 313 deletions(-) diff --git a/src/Ryujinx.Graphics.Host1x/Host1xDevice.cs b/src/Ryujinx.Graphics.Host1x/Host1xDevice.cs index 62fcef348..bf9b14f89 100644 --- a/src/Ryujinx.Graphics.Host1x/Host1xDevice.cs +++ b/src/Ryujinx.Graphics.Host1x/Host1xDevice.cs @@ -46,7 +46,7 @@ namespace Ryujinx.Graphics.Host1x public void RegisterDevice(ClassId classId, IDeviceState device) { - ThiDevice thi = new ThiDevice(classId, device ?? throw new ArgumentNullException(nameof(device)), _syncptIncrMgr); + ThiDevice thi = new(classId, device ?? throw new ArgumentNullException(nameof(device)), _syncptIncrMgr); _devices.RegisterDevice(classId, thi); } diff --git a/src/Ryujinx.Graphics.Metal/BackgroundResources.cs b/src/Ryujinx.Graphics.Metal/BackgroundResources.cs index 8bf6b92bd..e38b877a6 100644 --- a/src/Ryujinx.Graphics.Metal/BackgroundResources.cs +++ b/src/Ryujinx.Graphics.Metal/BackgroundResources.cs @@ -97,7 +97,7 @@ namespace Ryujinx.Graphics.Metal { lock (_resources) { - foreach (var resource in _resources.Values) + foreach (BackgroundResource resource in _resources.Values) { resource.Dispose(); } diff --git a/src/Ryujinx.Graphics.Metal/BufferHolder.cs b/src/Ryujinx.Graphics.Metal/BufferHolder.cs index cc86a403f..5a44dc1fe 100644 --- a/src/Ryujinx.Graphics.Metal/BufferHolder.cs +++ b/src/Ryujinx.Graphics.Metal/BufferHolder.cs @@ -103,7 +103,7 @@ namespace Ryujinx.Graphics.Metal if (_flushFence != null) { - var fence = _flushFence; + FenceHolder fence = _flushFence; Interlocked.Increment(ref _flushWaiting); // Don't wait in the lock. @@ -219,8 +219,8 @@ namespace Ryujinx.Graphics.Metal BufferHolder srcHolder = _renderer.BufferManager.Create(dataSize); srcHolder.SetDataUnchecked(0, data); - var srcBuffer = srcHolder.GetBuffer(); - var dstBuffer = this.GetBuffer(true); + Auto srcBuffer = srcHolder.GetBuffer(); + Auto dstBuffer = this.GetBuffer(true); Copy(cbs.Value, srcBuffer, dstBuffer, 0, offset, dataSize); @@ -262,8 +262,8 @@ namespace Ryujinx.Graphics.Metal int size, bool registerSrcUsage = true) { - var srcBuffer = registerSrcUsage ? src.Get(cbs, srcOffset, size).Value : src.GetUnsafe().Value; - var dstbuffer = dst.Get(cbs, dstOffset, size, true).Value; + MTLBuffer srcBuffer = registerSrcUsage ? src.Get(cbs, srcOffset, size).Value : src.GetUnsafe().Value; + MTLBuffer dstbuffer = dst.Get(cbs, dstOffset, size, true).Value; cbs.Encoders.EnsureBlitEncoder().CopyFromBuffer( srcBuffer, @@ -302,9 +302,9 @@ namespace Ryujinx.Graphics.Metal return null; } - var key = new I8ToI16CacheKey(_renderer); + I8ToI16CacheKey key = new I8ToI16CacheKey(_renderer); - if (!_cachedConvertedBuffers.TryGetValue(offset, size, key, out var holder)) + if (!_cachedConvertedBuffers.TryGetValue(offset, size, key, out BufferHolder holder)) { holder = _renderer.BufferManager.Create((size * 2 + 3) & ~3); @@ -325,9 +325,9 @@ namespace Ryujinx.Graphics.Metal return null; } - var key = new TopologyConversionCacheKey(_renderer, pattern, indexSize); + TopologyConversionCacheKey key = new TopologyConversionCacheKey(_renderer, pattern, indexSize); - if (!_cachedConvertedBuffers.TryGetValue(offset, size, key, out var holder)) + if (!_cachedConvertedBuffers.TryGetValue(offset, size, key, out BufferHolder holder)) { // The destination index size is always I32. diff --git a/src/Ryujinx.Graphics.Metal/BufferManager.cs b/src/Ryujinx.Graphics.Metal/BufferManager.cs index 07a686223..166f5b4f2 100644 --- a/src/Ryujinx.Graphics.Metal/BufferManager.cs +++ b/src/Ryujinx.Graphics.Metal/BufferManager.cs @@ -65,7 +65,7 @@ namespace Ryujinx.Graphics.Metal public BufferHandle Create(nint pointer, int size) { // TODO: This is the wrong Metal method, we need no-copy which SharpMetal isn't giving us. - var buffer = _device.NewBuffer(pointer, (ulong)size, MTLResourceOptions.ResourceStorageModeShared); + MTLBuffer buffer = _device.NewBuffer(pointer, (ulong)size, MTLResourceOptions.ResourceStorageModeShared); if (buffer == IntPtr.Zero) { @@ -74,7 +74,7 @@ namespace Ryujinx.Graphics.Metal return BufferHandle.Null; } - var holder = new BufferHolder(_renderer, _pipeline, buffer, size); + BufferHolder holder = new BufferHolder(_renderer, _pipeline, buffer, size); BufferCount++; @@ -123,7 +123,7 @@ namespace Ryujinx.Graphics.Metal public BufferHolder Create(int size) { - var buffer = _device.NewBuffer((ulong)size, MTLResourceOptions.ResourceStorageModeShared); + MTLBuffer buffer = _device.NewBuffer((ulong)size, MTLResourceOptions.ResourceStorageModeShared); if (buffer != IntPtr.Zero) { @@ -137,7 +137,7 @@ namespace Ryujinx.Graphics.Metal public Auto GetBuffer(BufferHandle handle, bool isWrite, out int size) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { size = holder.Size; return holder.GetBuffer(isWrite); @@ -149,7 +149,7 @@ namespace Ryujinx.Graphics.Metal public Auto GetBuffer(BufferHandle handle, int offset, int size, bool isWrite) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { return holder.GetBuffer(offset, size, isWrite); } @@ -159,7 +159,7 @@ namespace Ryujinx.Graphics.Metal public Auto GetBuffer(BufferHandle handle, bool isWrite) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { return holder.GetBuffer(isWrite); } @@ -169,7 +169,7 @@ namespace Ryujinx.Graphics.Metal public Auto GetBufferI8ToI16(CommandBufferScoped cbs, BufferHandle handle, int offset, int size) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { return holder.GetBufferI8ToI16(cbs, offset, size); } @@ -179,7 +179,7 @@ namespace Ryujinx.Graphics.Metal public Auto GetBufferTopologyConversion(CommandBufferScoped cbs, BufferHandle handle, int offset, int size, IndexBufferPattern pattern, int indexSize) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { return holder.GetBufferTopologyConversion(cbs, offset, size, pattern, indexSize); } @@ -189,7 +189,7 @@ namespace Ryujinx.Graphics.Metal public PinnedSpan GetData(BufferHandle handle, int offset, int size) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { return holder.GetData(offset, size); } @@ -204,7 +204,7 @@ namespace Ryujinx.Graphics.Metal public void SetData(BufferHandle handle, int offset, ReadOnlySpan data, CommandBufferScoped? cbs) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { holder.SetData(offset, data, cbs); } @@ -212,7 +212,7 @@ namespace Ryujinx.Graphics.Metal public void Delete(BufferHandle handle) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { holder.Dispose(); _buffers.Remove((int)Unsafe.As(ref handle)); @@ -228,7 +228,7 @@ namespace Ryujinx.Graphics.Metal { StagingBuffer.Dispose(); - foreach (var buffer in _buffers) + foreach (BufferHolder buffer in _buffers) { buffer.Dispose(); } diff --git a/src/Ryujinx.Graphics.Metal/CommandBufferEncoder.cs b/src/Ryujinx.Graphics.Metal/CommandBufferEncoder.cs index ec4150030..c9a337bb0 100644 --- a/src/Ryujinx.Graphics.Metal/CommandBufferEncoder.cs +++ b/src/Ryujinx.Graphics.Metal/CommandBufferEncoder.cs @@ -137,7 +137,7 @@ class CommandBufferEncoder { EndCurrentPass(); - var renderCommandEncoder = _encoderFactory.CreateRenderCommandEncoder(); + MTLRenderCommandEncoder renderCommandEncoder = _encoderFactory.CreateRenderCommandEncoder(); CurrentEncoder = renderCommandEncoder; CurrentEncoderType = EncoderType.Render; @@ -149,8 +149,8 @@ class CommandBufferEncoder { EndCurrentPass(); - using var descriptor = new MTLBlitPassDescriptor(); - var blitCommandEncoder = _commandBuffer.BlitCommandEncoder(descriptor); + using MTLBlitPassDescriptor descriptor = new MTLBlitPassDescriptor(); + MTLBlitCommandEncoder blitCommandEncoder = _commandBuffer.BlitCommandEncoder(descriptor); CurrentEncoder = blitCommandEncoder; CurrentEncoderType = EncoderType.Blit; @@ -161,7 +161,7 @@ class CommandBufferEncoder { EndCurrentPass(); - var computeCommandEncoder = _encoderFactory.CreateComputeCommandEncoder(); + MTLComputeCommandEncoder computeCommandEncoder = _encoderFactory.CreateComputeCommandEncoder(); CurrentEncoder = computeCommandEncoder; CurrentEncoderType = EncoderType.Compute; diff --git a/src/Ryujinx.Graphics.Metal/CommandBufferPool.cs b/src/Ryujinx.Graphics.Metal/CommandBufferPool.cs index 5e7576b37..53f11dd08 100644 --- a/src/Ryujinx.Graphics.Metal/CommandBufferPool.cs +++ b/src/Ryujinx.Graphics.Metal/CommandBufferPool.cs @@ -101,7 +101,7 @@ namespace Ryujinx.Graphics.Metal { for (int i = 0; i < _totalCommandBuffers; i++) { - ref var entry = ref _commandBuffers[i]; + ref ReservedCommandBuffer entry = ref _commandBuffers[i]; if (entry.InConsumption) { @@ -117,7 +117,7 @@ namespace Ryujinx.Graphics.Metal { for (int i = 0; i < _totalCommandBuffers; i++) { - ref var entry = ref _commandBuffers[i]; + ref ReservedCommandBuffer entry = ref _commandBuffers[i]; if (entry.InUse) { @@ -129,7 +129,7 @@ namespace Ryujinx.Graphics.Metal public void AddWaitable(int cbIndex, MultiFenceHolder waitable) { - ref var entry = ref _commandBuffers[cbIndex]; + ref ReservedCommandBuffer entry = ref _commandBuffers[cbIndex]; if (waitable.AddFence(cbIndex, entry.Fence)) { entry.Waitables.Add(waitable); @@ -142,7 +142,7 @@ namespace Ryujinx.Graphics.Metal { for (int i = 0; i < _totalCommandBuffers; i++) { - ref var entry = ref _commandBuffers[i]; + ref ReservedCommandBuffer entry = ref _commandBuffers[i]; if (entry.InUse && entry.Fence == fence) { @@ -172,7 +172,7 @@ namespace Ryujinx.Graphics.Metal { int index = _queuedIndexes[_queuedIndexesPtr]; - ref var entry = ref _commandBuffers[index]; + ref ReservedCommandBuffer entry = ref _commandBuffers[index]; if (wait || !entry.InConsumption || entry.Fence.IsSignaled()) { @@ -207,7 +207,7 @@ namespace Ryujinx.Graphics.Metal for (int i = 0; i < _totalCommandBuffers; i++) { - ref var entry = ref _commandBuffers[cursor]; + ref ReservedCommandBuffer entry = ref _commandBuffers[cursor]; if (!entry.InUse && !entry.InConsumption) { @@ -234,7 +234,7 @@ namespace Ryujinx.Graphics.Metal { int cbIndex = cbs.CommandBufferIndex; - ref var entry = ref _commandBuffers[cbIndex]; + ref ReservedCommandBuffer entry = ref _commandBuffers[cbIndex]; Debug.Assert(entry.InUse); Debug.Assert(entry.CommandBuffer.NativePtr == cbs.CommandBuffer.NativePtr); @@ -243,7 +243,7 @@ namespace Ryujinx.Graphics.Metal entry.SubmissionCount++; _inUseCount--; - var commandBuffer = entry.CommandBuffer; + MTLCommandBuffer commandBuffer = entry.CommandBuffer; commandBuffer.Commit(); int ptr = (_queuedIndexesPtr + _queuedCount) % _totalCommandBuffers; @@ -254,7 +254,7 @@ namespace Ryujinx.Graphics.Metal private void WaitAndDecrementRef(int cbIndex) { - ref var entry = ref _commandBuffers[cbIndex]; + ref ReservedCommandBuffer entry = ref _commandBuffers[cbIndex]; if (entry.InConsumption) { @@ -262,12 +262,12 @@ namespace Ryujinx.Graphics.Metal entry.InConsumption = false; } - foreach (var dependant in entry.Dependants) + foreach (IAuto dependant in entry.Dependants) { dependant.DecrementReferenceCount(cbIndex); } - foreach (var waitable in entry.Waitables) + foreach (MultiFenceHolder waitable in entry.Waitables) { waitable.RemoveFence(cbIndex); waitable.RemoveBufferUses(cbIndex); diff --git a/src/Ryujinx.Graphics.Metal/DepthStencilCache.cs b/src/Ryujinx.Graphics.Metal/DepthStencilCache.cs index bb6e4c180..92a24b99d 100644 --- a/src/Ryujinx.Graphics.Metal/DepthStencilCache.cs +++ b/src/Ryujinx.Graphics.Metal/DepthStencilCache.cs @@ -25,7 +25,7 @@ namespace Ryujinx.Graphics.Metal ref StencilUid frontUid = ref descriptor.FrontFace; - using var frontFaceStencil = new MTLStencilDescriptor + using MTLStencilDescriptor frontFaceStencil = new MTLStencilDescriptor { StencilFailureOperation = frontUid.StencilFailureOperation, DepthFailureOperation = frontUid.DepthFailureOperation, @@ -37,7 +37,7 @@ namespace Ryujinx.Graphics.Metal ref StencilUid backUid = ref descriptor.BackFace; - using var backFaceStencil = new MTLStencilDescriptor + using MTLStencilDescriptor backFaceStencil = new MTLStencilDescriptor { StencilFailureOperation = backUid.StencilFailureOperation, DepthFailureOperation = backUid.DepthFailureOperation, @@ -47,7 +47,7 @@ namespace Ryujinx.Graphics.Metal WriteMask = backUid.WriteMask }; - var mtlDescriptor = new MTLDepthStencilDescriptor + MTLDepthStencilDescriptor mtlDescriptor = new MTLDepthStencilDescriptor { DepthCompareFunction = descriptor.DepthCompareFunction, DepthWriteEnabled = descriptor.DepthWriteEnabled diff --git a/src/Ryujinx.Graphics.Metal/EncoderState.cs b/src/Ryujinx.Graphics.Metal/EncoderState.cs index 34de168a6..28b59736a 100644 --- a/src/Ryujinx.Graphics.Metal/EncoderState.cs +++ b/src/Ryujinx.Graphics.Metal/EncoderState.cs @@ -165,7 +165,7 @@ namespace Ryujinx.Graphics.Metal { // Inherit render target related information without causing a render encoder split. - var oldState = new RenderTargetCopy + RenderTargetCopy oldState = new RenderTargetCopy { Scissors = other.Scissors, RenderTargets = other.RenderTargets, @@ -180,7 +180,7 @@ namespace Ryujinx.Graphics.Metal Pipeline.Internal.ColorBlendState = other.Pipeline.Internal.ColorBlendState; Pipeline.DepthStencilFormat = other.Pipeline.DepthStencilFormat; - ref var blendStates = ref Pipeline.Internal.ColorBlendState; + ref Array8 blendStates = ref Pipeline.Internal.ColorBlendState; // Mask out irrelevant attachments. for (int i = 0; i < blendStates.Length; i++) diff --git a/src/Ryujinx.Graphics.Metal/EncoderStateManager.cs b/src/Ryujinx.Graphics.Metal/EncoderStateManager.cs index 169e0142d..bfd9a0348 100644 --- a/src/Ryujinx.Graphics.Metal/EncoderStateManager.cs +++ b/src/Ryujinx.Graphics.Metal/EncoderStateManager.cs @@ -1,4 +1,5 @@ using Ryujinx.Common.Logging; +using Ryujinx.Common.Memory; using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.Metal.State; using Ryujinx.Graphics.Shader; @@ -124,21 +125,21 @@ namespace Ryujinx.Graphics.Metal public readonly MTLRenderCommandEncoder CreateRenderCommandEncoder() { // Initialise Pass & State - using var renderPassDescriptor = new MTLRenderPassDescriptor(); + using MTLRenderPassDescriptor renderPassDescriptor = new MTLRenderPassDescriptor(); for (int i = 0; i < Constants.MaxColorAttachments; i++) { if (_currentState.RenderTargets[i] is Texture tex) { - var passAttachment = renderPassDescriptor.ColorAttachments.Object((ulong)i); + MTLRenderPassColorAttachmentDescriptor passAttachment = renderPassDescriptor.ColorAttachments.Object((ulong)i); tex.PopulateRenderPassAttachment(passAttachment); passAttachment.LoadAction = _currentState.ClearLoadAction ? MTLLoadAction.Clear : MTLLoadAction.Load; passAttachment.StoreAction = MTLStoreAction.Store; } } - var depthAttachment = renderPassDescriptor.DepthAttachment; - var stencilAttachment = renderPassDescriptor.StencilAttachment; + MTLRenderPassDepthAttachmentDescriptor depthAttachment = renderPassDescriptor.DepthAttachment; + MTLRenderPassStencilAttachmentDescriptor stencilAttachment = renderPassDescriptor.StencilAttachment; if (_currentState.DepthStencil != null) { @@ -177,15 +178,15 @@ namespace Ryujinx.Graphics.Metal } // Initialise Encoder - var renderCommandEncoder = _pipeline.CommandBuffer.RenderCommandEncoder(renderPassDescriptor); + MTLRenderCommandEncoder renderCommandEncoder = _pipeline.CommandBuffer.RenderCommandEncoder(renderPassDescriptor); return renderCommandEncoder; } public readonly MTLComputeCommandEncoder CreateComputeCommandEncoder() { - using var descriptor = new MTLComputePassDescriptor(); - var computeCommandEncoder = _pipeline.CommandBuffer.ComputeCommandEncoder(descriptor); + using MTLComputePassDescriptor descriptor = new MTLComputePassDescriptor(); + MTLComputeCommandEncoder computeCommandEncoder = _pipeline.CommandBuffer.ComputeCommandEncoder(descriptor); return computeCommandEncoder; } @@ -292,17 +293,17 @@ namespace Ryujinx.Graphics.Metal SetScissors(renderCommandEncoder); } - foreach (var resource in _currentState.RenderEncoderBindings.Resources) + foreach (Resource resource in _currentState.RenderEncoderBindings.Resources) { renderCommandEncoder.UseResource(resource.MtlResource, resource.ResourceUsage, resource.Stages); } - foreach (var buffer in _currentState.RenderEncoderBindings.VertexBuffers) + foreach (BufferResource buffer in _currentState.RenderEncoderBindings.VertexBuffers) { renderCommandEncoder.SetVertexBuffer(buffer.Buffer, buffer.Offset, buffer.Binding); } - foreach (var buffer in _currentState.RenderEncoderBindings.FragmentBuffers) + foreach (BufferResource buffer in _currentState.RenderEncoderBindings.FragmentBuffers) { renderCommandEncoder.SetFragmentBuffer(buffer.Buffer, buffer.Offset, buffer.Binding); } @@ -317,12 +318,12 @@ namespace Ryujinx.Graphics.Metal SetComputePipelineState(computeCommandEncoder); } - foreach (var resource in _currentState.ComputeEncoderBindings.Resources) + foreach (Resource resource in _currentState.ComputeEncoderBindings.Resources) { computeCommandEncoder.UseResource(resource.MtlResource, resource.ResourceUsage); } - foreach (var buffer in _currentState.ComputeEncoderBindings.Buffers) + foreach (BufferResource buffer in _currentState.ComputeEncoderBindings.Buffers) { computeCommandEncoder.SetBuffer(buffer.Buffer, buffer.Offset, buffer.Binding); } @@ -350,7 +351,7 @@ namespace Ryujinx.Graphics.Metal return; } - var pipelineState = PipelineState.CreateComputePipeline(_device, _currentState.ComputeProgram); + MTLComputePipelineState pipelineState = PipelineState.CreateComputePipeline(_device, _currentState.ComputeProgram); computeCommandEncoder.SetComputePipelineState(pipelineState); } @@ -418,7 +419,7 @@ namespace Ryujinx.Graphics.Metal public readonly void UpdateRenderTargetColorMasks(ReadOnlySpan componentMask) { - ref var blendState = ref _currentState.Pipeline.Internal.ColorBlendState; + ref Array8 blendState = ref _currentState.Pipeline.Internal.ColorBlendState; for (int i = 0; i < componentMask.Length; i++) { @@ -427,7 +428,7 @@ namespace Ryujinx.Graphics.Metal bool blue = (componentMask[i] & (0x1 << 2)) != 0; bool alpha = (componentMask[i] & (0x1 << 3)) != 0; - var mask = MTLColorWriteMask.None; + MTLColorWriteMask mask = MTLColorWriteMask.None; mask |= red ? MTLColorWriteMask.Red : 0; mask |= green ? MTLColorWriteMask.Green : 0; @@ -480,7 +481,7 @@ namespace Ryujinx.Graphics.Metal // Look for textures that are masked out. ref PipelineState pipeline = ref _currentState.Pipeline; - ref var blendState = ref pipeline.Internal.ColorBlendState; + ref Array8 blendState = ref pipeline.Internal.ColorBlendState; pipeline.ColorBlendAttachmentStateCount = (uint)colors.Length; @@ -491,7 +492,7 @@ namespace Ryujinx.Graphics.Metal continue; } - var mtlMask = blendState[i].WriteMask; + MTLColorWriteMask mtlMask = blendState[i].WriteMask; for (int j = 0; j < i; j++) { @@ -501,7 +502,7 @@ namespace Ryujinx.Graphics.Metal { // Prefer the binding with no write mask. - var mtlMask2 = blendState[j].WriteMask; + MTLColorWriteMask mtlMask2 = blendState[j].WriteMask; if (mtlMask == 0) { @@ -574,7 +575,7 @@ namespace Ryujinx.Graphics.Metal public readonly void UpdateBlendDescriptors(int index, BlendDescriptor blend) { - ref var blendState = ref _currentState.Pipeline.Internal.ColorBlendState[index]; + ref ColorBlendStateUid blendState = ref _currentState.Pipeline.Internal.ColorBlendState[index]; blendState.Enable = blend.Enable; blendState.AlphaBlendOperation = blend.AlphaOp.Convert(); @@ -687,7 +688,7 @@ namespace Ryujinx.Graphics.Metal { for (int i = 0; i < regions.Length; i++) { - var region = regions[i]; + Rectangle region = regions[i]; _currentState.Scissors[i] = new MTLScissorRect { @@ -717,7 +718,7 @@ namespace Ryujinx.Graphics.Metal for (int i = 0; i < viewports.Length; i++) { - var viewport = viewports[i]; + Viewport viewport = viewports[i]; // Y coordinate is inverted _currentState.Viewports[i] = new MTLViewport { @@ -746,7 +747,7 @@ namespace Ryujinx.Graphics.Metal { if (i < vertexBuffers.Length) { - var vertexBuffer = vertexBuffers[i]; + VertexBufferDescriptor vertexBuffer = vertexBuffers[i]; _currentState.VertexBuffers[i] = new VertexBufferState( vertexBuffer.Buffer.Handle, @@ -771,7 +772,7 @@ namespace Ryujinx.Graphics.Metal { foreach (BufferAssignment assignment in buffers) { - var buffer = assignment.Range; + BufferRange buffer = assignment.Range; int index = assignment.Binding; Auto mtlBuffer = buffer.Handle == BufferHandle.Null @@ -788,7 +789,7 @@ namespace Ryujinx.Graphics.Metal { foreach (BufferAssignment assignment in buffers) { - var buffer = assignment.Range; + BufferRange buffer = assignment.Range; int index = assignment.Binding; Auto mtlBuffer = buffer.Handle == BufferHandle.Null @@ -805,7 +806,7 @@ namespace Ryujinx.Graphics.Metal { for (int i = 0; i < buffers.Length; i++) { - var mtlBuffer = buffers[i]; + Auto mtlBuffer = buffers[i]; int index = first + i; _currentState.StorageBufferRefs[index] = new BufferRef(mtlBuffer); @@ -816,7 +817,7 @@ namespace Ryujinx.Graphics.Metal public void UpdateCullMode(bool enable, Face face) { - var dirtyScissor = (face == Face.FrontAndBack) != _currentState.CullBoth; + bool dirtyScissor = (face == Face.FrontAndBack) != _currentState.CullBoth; _currentState.CullMode = enable ? face.Convert() : MTLCullMode.None; _currentState.CullBoth = face == Face.FrontAndBack; @@ -980,8 +981,8 @@ namespace Ryujinx.Graphics.Metal private unsafe void SetScissors(MTLRenderCommandEncoder renderCommandEncoder) { - var isTriangles = (_currentState.Topology == PrimitiveTopology.Triangles) || - (_currentState.Topology == PrimitiveTopology.TriangleStrip); + bool isTriangles = (_currentState.Topology == PrimitiveTopology.Triangles) || + (_currentState.Topology == PrimitiveTopology.TriangleStrip); if (_currentState.CullBoth && isTriangles) { @@ -1017,7 +1018,7 @@ namespace Ryujinx.Graphics.Metal for (int i = 0; i < attribDescriptors.Length; i++) { - ref var attrib = ref pipeline.Internal.VertexAttributes[i]; + ref VertexInputAttributeUid attrib = ref pipeline.Internal.VertexAttributes[i]; if (attribDescriptors[i].IsZero) { @@ -1037,7 +1038,7 @@ namespace Ryujinx.Graphics.Metal for (int i = 0; i < bufferDescriptors.Length; i++) { - ref var layout = ref pipeline.Internal.VertexBindings[i]; + ref VertexInputLayoutUid layout = ref pipeline.Internal.VertexBindings[i]; if ((indexMask & (1u << i)) != 0) { @@ -1069,7 +1070,7 @@ namespace Ryujinx.Graphics.Metal } } - ref var zeroBufLayout = ref pipeline.Internal.VertexBindings[(int)Constants.ZeroBufferIndex]; + ref VertexInputLayoutUid zeroBufLayout = ref pipeline.Internal.VertexBindings[(int)Constants.ZeroBufferIndex]; // Zero buffer if ((indexMask & (1u << (int)Constants.ZeroBufferIndex)) != 0) @@ -1108,7 +1109,7 @@ namespace Ryujinx.Graphics.Metal return; } - var zeroMtlBuffer = autoZeroBuffer.Get(_pipeline.Cbs).Value; + MTLBuffer zeroMtlBuffer = autoZeroBuffer.Get(_pipeline.Cbs).Value; bindings.VertexBuffers.Add(new BufferResource(zeroMtlBuffer, 0, Constants.ZeroBufferIndex)); } @@ -1117,12 +1118,12 @@ namespace Ryujinx.Graphics.Metal ulong gpuAddress = 0; IntPtr nativePtr = IntPtr.Zero; - var range = buffer.Range; - var autoBuffer = buffer.Buffer; + BufferRange? range = buffer.Range; + Auto autoBuffer = buffer.Buffer; if (autoBuffer != null) { - var offset = 0; + int offset = 0; MTLBuffer mtlBuffer; if (range.HasValue) @@ -1144,7 +1145,7 @@ namespace Ryujinx.Graphics.Metal private readonly (ulong gpuAddress, IntPtr nativePtr) AddressForTexture(ref TextureRef texture) { - var storage = texture.Storage; + TextureBase storage = texture.Storage; ulong gpuAddress = 0; IntPtr nativePtr = IntPtr.Zero; @@ -1156,7 +1157,7 @@ namespace Ryujinx.Graphics.Metal textureBuffer.RebuildStorage(false); } - var mtlTexture = storage.GetHandle(); + MTLTexture mtlTexture = storage.GetHandle(); gpuAddress = mtlTexture.GpuResourceID._impl; nativePtr = mtlTexture.NativePtr; @@ -1167,14 +1168,14 @@ namespace Ryujinx.Graphics.Metal private readonly (ulong gpuAddress, IntPtr nativePtr) AddressForImage(ref ImageRef image) { - var storage = image.Storage; + Texture storage = image.Storage; ulong gpuAddress = 0; IntPtr nativePtr = IntPtr.Zero; if (storage != null) { - var mtlTexture = storage.GetHandle(); + MTLTexture mtlTexture = storage.GetHandle(); gpuAddress = mtlTexture.GpuResourceID._impl; nativePtr = mtlTexture.NativePtr; @@ -1192,7 +1193,7 @@ namespace Ryujinx.Graphics.Metal { bufferTexture.RebuildStorage(false); - var mtlTexture = bufferTexture.GetHandle(); + MTLTexture mtlTexture = bufferTexture.GetHandle(); gpuAddress = mtlTexture.GpuResourceID._impl; nativePtr = mtlTexture.NativePtr; @@ -1221,7 +1222,7 @@ namespace Ryujinx.Graphics.Metal private readonly void UpdateAndBind(Program program, uint setIndex, ref readonly RenderEncoderBindings bindings) { - var bindingSegments = program.BindingSegments[setIndex]; + ResourceBindingSegment[] bindingSegments = program.BindingSegments[setIndex]; if (bindingSegments.Length == 0) { @@ -1244,8 +1245,8 @@ namespace Ryujinx.Graphics.Metal Span vertResourceIds = stackalloc ulong[program.ArgumentBufferSizes[setIndex]]; Span fragResourceIds = stackalloc ulong[program.FragArgumentBufferSizes[setIndex]]; - var vertResourceIdIndex = 0; - var fragResourceIdIndex = 0; + int vertResourceIdIndex = 0; + int fragResourceIdIndex = 0; foreach (ResourceBindingSegment segment in bindingSegments) { @@ -1260,7 +1261,7 @@ namespace Ryujinx.Graphics.Metal int index = binding + i; ref BufferRef buffer = ref _currentState.UniformBufferRefs[index]; - var (gpuAddress, nativePtr) = AddressForBuffer(ref buffer); + (ulong gpuAddress, IntPtr nativePtr) = AddressForBuffer(ref buffer); MTLRenderStages renderStages = 0; @@ -1289,7 +1290,7 @@ namespace Ryujinx.Graphics.Metal int index = binding + i; ref BufferRef buffer = ref _currentState.StorageBufferRefs[index]; - var (gpuAddress, nativePtr) = AddressForBuffer(ref buffer); + (ulong gpuAddress, IntPtr nativePtr) = AddressForBuffer(ref buffer); MTLRenderStages renderStages = 0; @@ -1319,8 +1320,8 @@ namespace Ryujinx.Graphics.Metal { int index = binding + i; - ref var texture = ref _currentState.TextureRefs[index]; - var (gpuAddress, nativePtr) = AddressForTexture(ref texture); + ref TextureRef texture = ref _currentState.TextureRefs[index]; + (ulong gpuAddress, IntPtr nativePtr) = AddressForTexture(ref texture); MTLRenderStages renderStages = 0; @@ -1357,17 +1358,17 @@ namespace Ryujinx.Graphics.Metal } else { - var textureArray = _currentState.TextureArrayRefs[binding].Array; + TextureArray textureArray = _currentState.TextureArrayRefs[binding].Array; if (segment.Type != ResourceType.BufferTexture) { - var textures = textureArray.GetTextureRefs(); - var samplers = new Auto[textures.Length]; + TextureRef[] textures = textureArray.GetTextureRefs(); + Auto[] samplers = new Auto[textures.Length]; for (int i = 0; i < textures.Length; i++) { TextureRef texture = textures[i]; - var (gpuAddress, nativePtr) = AddressForTexture(ref texture); + (ulong gpuAddress, IntPtr nativePtr) = AddressForTexture(ref texture); samplers[i] = texture.Sampler; @@ -1392,7 +1393,7 @@ namespace Ryujinx.Graphics.Metal AddResource(nativePtr, MTLResourceUsage.Read, renderStages, in bindings); } - foreach (var sampler in samplers) + foreach (Auto sampler in samplers) { ulong gpuAddress = 0; @@ -1416,12 +1417,12 @@ namespace Ryujinx.Graphics.Metal } else { - var bufferTextures = textureArray.GetBufferTextureRefs(); + TextureBuffer[] bufferTextures = textureArray.GetBufferTextureRefs(); for (int i = 0; i < bufferTextures.Length; i++) { TextureBuffer bufferTexture = bufferTextures[i]; - var (gpuAddress, nativePtr) = AddressForTextureBuffer(ref bufferTexture); + (ulong gpuAddress, IntPtr nativePtr) = AddressForTextureBuffer(ref bufferTexture); MTLRenderStages renderStages = 0; @@ -1453,8 +1454,8 @@ namespace Ryujinx.Graphics.Metal { int index = binding + i; - ref var image = ref _currentState.ImageRefs[index]; - var (gpuAddress, nativePtr) = AddressForImage(ref image); + ref ImageRef image = ref _currentState.ImageRefs[index]; + (ulong gpuAddress, IntPtr nativePtr) = AddressForImage(ref image); MTLRenderStages renderStages = 0; @@ -1477,16 +1478,16 @@ namespace Ryujinx.Graphics.Metal } else { - var imageArray = _currentState.ImageArrayRefs[binding].Array; + ImageArray imageArray = _currentState.ImageArrayRefs[binding].Array; if (segment.Type != ResourceType.BufferImage) { - var images = imageArray.GetTextureRefs(); + TextureRef[] images = imageArray.GetTextureRefs(); for (int i = 0; i < images.Length; i++) { TextureRef image = images[i]; - var (gpuAddress, nativePtr) = AddressForTexture(ref image); + (ulong gpuAddress, IntPtr nativePtr) = AddressForTexture(ref image); MTLRenderStages renderStages = 0; @@ -1509,12 +1510,12 @@ namespace Ryujinx.Graphics.Metal } else { - var bufferImages = imageArray.GetBufferTextureRefs(); + TextureBuffer[] bufferImages = imageArray.GetBufferTextureRefs(); for (int i = 0; i < bufferImages.Length; i++) { TextureBuffer image = bufferImages[i]; - var (gpuAddress, nativePtr) = AddressForTextureBuffer(ref image); + (ulong gpuAddress, IntPtr nativePtr) = AddressForTextureBuffer(ref image); MTLRenderStages renderStages = 0; @@ -1543,21 +1544,21 @@ namespace Ryujinx.Graphics.Metal if (program.ArgumentBufferSizes[setIndex] > 0) { vertArgBuffer.Holder.SetDataUnchecked(vertArgBuffer.Offset, MemoryMarshal.AsBytes(vertResourceIds)); - var mtlVertArgBuffer = _bufferManager.GetBuffer(vertArgBuffer.Handle, false).Get(_pipeline.Cbs).Value; + MTLBuffer mtlVertArgBuffer = _bufferManager.GetBuffer(vertArgBuffer.Handle, false).Get(_pipeline.Cbs).Value; bindings.VertexBuffers.Add(new BufferResource(mtlVertArgBuffer, (uint)vertArgBuffer.Range.Offset, SetIndexToBindingIndex(setIndex))); } if (program.FragArgumentBufferSizes[setIndex] > 0) { fragArgBuffer.Holder.SetDataUnchecked(fragArgBuffer.Offset, MemoryMarshal.AsBytes(fragResourceIds)); - var mtlFragArgBuffer = _bufferManager.GetBuffer(fragArgBuffer.Handle, false).Get(_pipeline.Cbs).Value; + MTLBuffer mtlFragArgBuffer = _bufferManager.GetBuffer(fragArgBuffer.Handle, false).Get(_pipeline.Cbs).Value; bindings.FragmentBuffers.Add(new BufferResource(mtlFragArgBuffer, (uint)fragArgBuffer.Range.Offset, SetIndexToBindingIndex(setIndex))); } } private readonly void UpdateAndBind(Program program, uint setIndex, ref readonly ComputeEncoderBindings bindings) { - var bindingSegments = program.BindingSegments[setIndex]; + ResourceBindingSegment[] bindingSegments = program.BindingSegments[setIndex]; if (bindingSegments.Length == 0) { @@ -1572,7 +1573,7 @@ namespace Ryujinx.Graphics.Metal } Span resourceIds = stackalloc ulong[program.ArgumentBufferSizes[setIndex]]; - var resourceIdIndex = 0; + int resourceIdIndex = 0; foreach (ResourceBindingSegment segment in bindingSegments) { @@ -1587,7 +1588,7 @@ namespace Ryujinx.Graphics.Metal int index = binding + i; ref BufferRef buffer = ref _currentState.UniformBufferRefs[index]; - var (gpuAddress, nativePtr) = AddressForBuffer(ref buffer); + (ulong gpuAddress, IntPtr nativePtr) = AddressForBuffer(ref buffer); if ((segment.Stages & ResourceStages.Compute) != 0) { @@ -1604,7 +1605,7 @@ namespace Ryujinx.Graphics.Metal int index = binding + i; ref BufferRef buffer = ref _currentState.StorageBufferRefs[index]; - var (gpuAddress, nativePtr) = AddressForBuffer(ref buffer); + (ulong gpuAddress, IntPtr nativePtr) = AddressForBuffer(ref buffer); if ((segment.Stages & ResourceStages.Compute) != 0) { @@ -1621,8 +1622,8 @@ namespace Ryujinx.Graphics.Metal { int index = binding + i; - ref var texture = ref _currentState.TextureRefs[index]; - var (gpuAddress, nativePtr) = AddressForTexture(ref texture); + ref TextureRef texture = ref _currentState.TextureRefs[index]; + (ulong gpuAddress, IntPtr nativePtr) = AddressForTexture(ref texture); if ((segment.Stages & ResourceStages.Compute) != 0) { @@ -1640,17 +1641,17 @@ namespace Ryujinx.Graphics.Metal } else { - var textureArray = _currentState.TextureArrayRefs[binding].Array; + TextureArray textureArray = _currentState.TextureArrayRefs[binding].Array; if (segment.Type != ResourceType.BufferTexture) { - var textures = textureArray.GetTextureRefs(); - var samplers = new Auto[textures.Length]; + TextureRef[] textures = textureArray.GetTextureRefs(); + Auto[] samplers = new Auto[textures.Length]; for (int i = 0; i < textures.Length; i++) { TextureRef texture = textures[i]; - var (gpuAddress, nativePtr) = AddressForTexture(ref texture); + (ulong gpuAddress, IntPtr nativePtr) = AddressForTexture(ref texture); if ((segment.Stages & ResourceStages.Compute) != 0) { @@ -1662,7 +1663,7 @@ namespace Ryujinx.Graphics.Metal } } - foreach (var sampler in samplers) + foreach (Auto sampler in samplers) { if (sampler != null) { @@ -1673,12 +1674,12 @@ namespace Ryujinx.Graphics.Metal } else { - var bufferTextures = textureArray.GetBufferTextureRefs(); + TextureBuffer[] bufferTextures = textureArray.GetBufferTextureRefs(); for (int i = 0; i < bufferTextures.Length; i++) { TextureBuffer bufferTexture = bufferTextures[i]; - var (gpuAddress, nativePtr) = AddressForTextureBuffer(ref bufferTexture); + (ulong gpuAddress, IntPtr nativePtr) = AddressForTextureBuffer(ref bufferTexture); if ((segment.Stages & ResourceStages.Compute) != 0) { @@ -1697,8 +1698,8 @@ namespace Ryujinx.Graphics.Metal { int index = binding + i; - ref var image = ref _currentState.ImageRefs[index]; - var (gpuAddress, nativePtr) = AddressForImage(ref image); + ref ImageRef image = ref _currentState.ImageRefs[index]; + (ulong gpuAddress, IntPtr nativePtr) = AddressForImage(ref image); if ((segment.Stages & ResourceStages.Compute) != 0) { @@ -1710,16 +1711,16 @@ namespace Ryujinx.Graphics.Metal } else { - var imageArray = _currentState.ImageArrayRefs[binding].Array; + ImageArray imageArray = _currentState.ImageArrayRefs[binding].Array; if (segment.Type != ResourceType.BufferImage) { - var images = imageArray.GetTextureRefs(); + TextureRef[] images = imageArray.GetTextureRefs(); for (int i = 0; i < images.Length; i++) { TextureRef image = images[i]; - var (gpuAddress, nativePtr) = AddressForTexture(ref image); + (ulong gpuAddress, IntPtr nativePtr) = AddressForTexture(ref image); if ((segment.Stages & ResourceStages.Compute) != 0) { @@ -1731,12 +1732,12 @@ namespace Ryujinx.Graphics.Metal } else { - var bufferImages = imageArray.GetBufferTextureRefs(); + TextureBuffer[] bufferImages = imageArray.GetBufferTextureRefs(); for (int i = 0; i < bufferImages.Length; i++) { TextureBuffer image = bufferImages[i]; - var (gpuAddress, nativePtr) = AddressForTextureBuffer(ref image); + (ulong gpuAddress, IntPtr nativePtr) = AddressForTextureBuffer(ref image); if ((segment.Stages & ResourceStages.Compute) != 0) { @@ -1754,7 +1755,7 @@ namespace Ryujinx.Graphics.Metal if (program.ArgumentBufferSizes[setIndex] > 0) { argBuffer.Holder.SetDataUnchecked(argBuffer.Offset, MemoryMarshal.AsBytes(resourceIds)); - var mtlArgBuffer = _bufferManager.GetBuffer(argBuffer.Handle, false).Get(_pipeline.Cbs).Value; + MTLBuffer mtlArgBuffer = _bufferManager.GetBuffer(argBuffer.Handle, false).Get(_pipeline.Cbs).Value; bindings.Buffers.Add(new BufferResource(mtlArgBuffer, (uint)argBuffer.Range.Offset, SetIndexToBindingIndex(setIndex))); } } diff --git a/src/Ryujinx.Graphics.Metal/FormatTable.cs b/src/Ryujinx.Graphics.Metal/FormatTable.cs index c1f8923f9..10c8b435c 100644 --- a/src/Ryujinx.Graphics.Metal/FormatTable.cs +++ b/src/Ryujinx.Graphics.Metal/FormatTable.cs @@ -170,7 +170,7 @@ namespace Ryujinx.Graphics.Metal public static MTLPixelFormat GetFormat(Format format) { - var mtlFormat = _table[(int)format]; + MTLPixelFormat mtlFormat = _table[(int)format]; if (IsD24S8(format)) { diff --git a/src/Ryujinx.Graphics.Metal/HardwareInfo.cs b/src/Ryujinx.Graphics.Metal/HardwareInfo.cs index 4b3b710f8..413fabf09 100644 --- a/src/Ryujinx.Graphics.Metal/HardwareInfo.cs +++ b/src/Ryujinx.Graphics.Metal/HardwareInfo.cs @@ -45,33 +45,33 @@ namespace Ryujinx.Graphics.Metal public static string GetVendor() { - var serviceDict = IOServiceMatching("IOGPU"); - var service = IOServiceGetMatchingService(IntPtr.Zero, serviceDict); - var cfString = CFStringCreateWithCString(_kCFAllocatorDefault, "vendor-id", _kCFStringEncodingASCII); - var cfProperty = IORegistryEntryCreateCFProperty(service, cfString, _kCFAllocatorDefault, 0); + IntPtr serviceDict = IOServiceMatching("IOGPU"); + IntPtr service = IOServiceGetMatchingService(IntPtr.Zero, serviceDict); + IntPtr cfString = CFStringCreateWithCString(_kCFAllocatorDefault, "vendor-id", _kCFStringEncodingASCII); + IntPtr cfProperty = IORegistryEntryCreateCFProperty(service, cfString, _kCFAllocatorDefault, 0); byte[] buffer = new byte[4]; - var bufferPtr = CFDataGetBytePtr(cfProperty); + IntPtr bufferPtr = CFDataGetBytePtr(cfProperty); Marshal.Copy(bufferPtr, buffer, 0, buffer.Length); - var vendorId = BitConverter.ToUInt32(buffer); + uint vendorId = BitConverter.ToUInt32(buffer); return GetNameFromId(vendorId); } public static string GetModel() { - var serviceDict = IOServiceMatching("IOGPU"); - var service = IOServiceGetMatchingService(IntPtr.Zero, serviceDict); - var cfString = CFStringCreateWithCString(_kCFAllocatorDefault, "model", _kCFStringEncodingASCII); - var cfProperty = IORegistryEntryCreateCFProperty(service, cfString, _kCFAllocatorDefault, 0); + IntPtr serviceDict = IOServiceMatching("IOGPU"); + IntPtr service = IOServiceGetMatchingService(IntPtr.Zero, serviceDict); + IntPtr cfString = CFStringCreateWithCString(_kCFAllocatorDefault, "model", _kCFStringEncodingASCII); + IntPtr cfProperty = IORegistryEntryCreateCFProperty(service, cfString, _kCFAllocatorDefault, 0); char[] buffer = new char[64]; IntPtr bufferPtr = Marshal.AllocHGlobal(buffer.Length); if (CFStringGetCString(cfProperty, bufferPtr, buffer.Length, _kCFStringEncodingASCII)) { - var model = Marshal.PtrToStringUTF8(bufferPtr); + string model = Marshal.PtrToStringUTF8(bufferPtr); Marshal.FreeHGlobal(bufferPtr); return model; } diff --git a/src/Ryujinx.Graphics.Metal/HashTableSlim.cs b/src/Ryujinx.Graphics.Metal/HashTableSlim.cs index a27a53d47..34f38ee24 100644 --- a/src/Ryujinx.Graphics.Metal/HashTableSlim.cs +++ b/src/Ryujinx.Graphics.Metal/HashTableSlim.cs @@ -65,7 +65,7 @@ namespace Ryujinx.Graphics.Metal public void Add(ref TKey key, TValue value) { - var entry = new Entry + Entry entry = new() { Hash = key.GetHashCode(), Key = key, @@ -75,7 +75,7 @@ namespace Ryujinx.Graphics.Metal int hashCode = key.GetHashCode(); int bucketIndex = hashCode & TotalBucketsMask; - ref var bucket = ref _hashTable[bucketIndex]; + ref Bucket bucket = ref _hashTable[bucketIndex]; if (bucket.Entries != null) { int index = bucket.Length; @@ -102,11 +102,11 @@ namespace Ryujinx.Graphics.Metal { int hashCode = key.GetHashCode(); - ref var bucket = ref _hashTable[hashCode & TotalBucketsMask]; - var entries = bucket.AsSpan(); + ref Bucket bucket = ref _hashTable[hashCode & TotalBucketsMask]; + Span entries = bucket.AsSpan(); for (int i = 0; i < entries.Length; i++) { - ref var entry = ref entries[i]; + ref Entry entry = ref entries[i]; if (entry.Hash == hashCode && entry.Key.Equals(ref key)) { @@ -124,10 +124,10 @@ namespace Ryujinx.Graphics.Metal { int hashCode = key.GetHashCode(); - var entries = _hashTable[hashCode & TotalBucketsMask].AsSpan(); + Span entries = _hashTable[hashCode & TotalBucketsMask].AsSpan(); for (int i = 0; i < entries.Length; i++) { - ref var entry = ref entries[i]; + ref Entry entry = ref entries[i]; if (entry.Hash == hashCode && entry.Key.Equals(ref key)) { diff --git a/src/Ryujinx.Graphics.Metal/HelperShader.cs b/src/Ryujinx.Graphics.Metal/HelperShader.cs index 53f503207..e72ab6991 100644 --- a/src/Ryujinx.Graphics.Metal/HelperShader.cs +++ b/src/Ryujinx.Graphics.Metal/HelperShader.cs @@ -50,58 +50,58 @@ namespace Ryujinx.Graphics.Metal _samplerNearest = new SamplerHolder(renderer, _device, SamplerCreateInfo.Create(MinFilter.Nearest, MagFilter.Nearest)); _samplerLinear = new SamplerHolder(renderer, _device, SamplerCreateInfo.Create(MinFilter.Linear, MagFilter.Linear)); - var blitResourceLayout = new ResourceLayoutBuilder() + ResourceLayout blitResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Vertex, ResourceType.UniformBuffer, 0) .Add(ResourceStages.Fragment, ResourceType.TextureAndSampler, 0).Build(); - var blitSource = ReadMsl("Blit.metal"); + string blitSource = ReadMsl("Blit.metal"); - var blitSourceF = blitSource.Replace("FORMAT", "float", StringComparison.Ordinal); + string blitSourceF = blitSource.Replace("FORMAT", "float", StringComparison.Ordinal); _programColorBlitF = new Program(renderer, device, [ new ShaderSource(blitSourceF, ShaderStage.Fragment, TargetLanguage.Msl), new ShaderSource(blitSourceF, ShaderStage.Vertex, TargetLanguage.Msl) ], blitResourceLayout); - var blitSourceI = blitSource.Replace("FORMAT", "int"); + string blitSourceI = blitSource.Replace("FORMAT", "int"); _programColorBlitI = new Program(renderer, device, [ new ShaderSource(blitSourceI, ShaderStage.Fragment, TargetLanguage.Msl), new ShaderSource(blitSourceI, ShaderStage.Vertex, TargetLanguage.Msl) ], blitResourceLayout); - var blitSourceU = blitSource.Replace("FORMAT", "uint"); + string blitSourceU = blitSource.Replace("FORMAT", "uint"); _programColorBlitU = new Program(renderer, device, [ new ShaderSource(blitSourceU, ShaderStage.Fragment, TargetLanguage.Msl), new ShaderSource(blitSourceU, ShaderStage.Vertex, TargetLanguage.Msl) ], blitResourceLayout); - var blitMsSource = ReadMsl("BlitMs.metal"); + string blitMsSource = ReadMsl("BlitMs.metal"); - var blitMsSourceF = blitMsSource.Replace("FORMAT", "float"); + string blitMsSourceF = blitMsSource.Replace("FORMAT", "float"); _programColorBlitMsF = new Program(renderer, device, [ new ShaderSource(blitMsSourceF, ShaderStage.Fragment, TargetLanguage.Msl), new ShaderSource(blitMsSourceF, ShaderStage.Vertex, TargetLanguage.Msl) ], blitResourceLayout); - var blitMsSourceI = blitMsSource.Replace("FORMAT", "int"); + string blitMsSourceI = blitMsSource.Replace("FORMAT", "int"); _programColorBlitMsI = new Program(renderer, device, [ new ShaderSource(blitMsSourceI, ShaderStage.Fragment, TargetLanguage.Msl), new ShaderSource(blitMsSourceI, ShaderStage.Vertex, TargetLanguage.Msl) ], blitResourceLayout); - var blitMsSourceU = blitMsSource.Replace("FORMAT", "uint"); + string blitMsSourceU = blitMsSource.Replace("FORMAT", "uint"); _programColorBlitMsU = new Program(renderer, device, [ new ShaderSource(blitMsSourceU, ShaderStage.Fragment, TargetLanguage.Msl), new ShaderSource(blitMsSourceU, ShaderStage.Vertex, TargetLanguage.Msl) ], blitResourceLayout); - var colorClearResourceLayout = new ResourceLayoutBuilder() + ResourceLayout colorClearResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Fragment, ResourceType.UniformBuffer, 0).Build(); - var colorClearSource = ReadMsl("ColorClear.metal"); + string colorClearSource = ReadMsl("ColorClear.metal"); for (int i = 0; i < Constants.MaxColorAttachments; i++) { - var crntSource = colorClearSource.Replace("COLOR_ATTACHMENT_INDEX", i.ToString()).Replace("FORMAT", "float"); + string crntSource = colorClearSource.Replace("COLOR_ATTACHMENT_INDEX", i.ToString()).Replace("FORMAT", "float"); _programsColorClearF.Add(new Program(renderer, device, [ new ShaderSource(crntSource, ShaderStage.Fragment, TargetLanguage.Msl), new ShaderSource(crntSource, ShaderStage.Vertex, TargetLanguage.Msl) @@ -110,7 +110,7 @@ namespace Ryujinx.Graphics.Metal for (int i = 0; i < Constants.MaxColorAttachments; i++) { - var crntSource = colorClearSource.Replace("COLOR_ATTACHMENT_INDEX", i.ToString()).Replace("FORMAT", "int"); + string crntSource = colorClearSource.Replace("COLOR_ATTACHMENT_INDEX", i.ToString()).Replace("FORMAT", "int"); _programsColorClearI.Add(new Program(renderer, device, [ new ShaderSource(crntSource, ShaderStage.Fragment, TargetLanguage.Msl), new ShaderSource(crntSource, ShaderStage.Vertex, TargetLanguage.Msl) @@ -119,68 +119,68 @@ namespace Ryujinx.Graphics.Metal for (int i = 0; i < Constants.MaxColorAttachments; i++) { - var crntSource = colorClearSource.Replace("COLOR_ATTACHMENT_INDEX", i.ToString()).Replace("FORMAT", "uint"); + string crntSource = colorClearSource.Replace("COLOR_ATTACHMENT_INDEX", i.ToString()).Replace("FORMAT", "uint"); _programsColorClearU.Add(new Program(renderer, device, [ new ShaderSource(crntSource, ShaderStage.Fragment, TargetLanguage.Msl), new ShaderSource(crntSource, ShaderStage.Vertex, TargetLanguage.Msl) ], colorClearResourceLayout)); } - var depthStencilClearSource = ReadMsl("DepthStencilClear.metal"); + string depthStencilClearSource = ReadMsl("DepthStencilClear.metal"); _programDepthStencilClear = new Program(renderer, device, [ new ShaderSource(depthStencilClearSource, ShaderStage.Fragment, TargetLanguage.Msl), new ShaderSource(depthStencilClearSource, ShaderStage.Vertex, TargetLanguage.Msl) ], colorClearResourceLayout); - var strideChangeResourceLayout = new ResourceLayoutBuilder() + ResourceLayout strideChangeResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 0) .Add(ResourceStages.Compute, ResourceType.StorageBuffer, 1) .Add(ResourceStages.Compute, ResourceType.StorageBuffer, 2, true).Build(); - var strideChangeSource = ReadMsl("ChangeBufferStride.metal"); + string strideChangeSource = ReadMsl("ChangeBufferStride.metal"); _programStrideChange = new Program(renderer, device, [ new ShaderSource(strideChangeSource, ShaderStage.Compute, TargetLanguage.Msl) ], strideChangeResourceLayout, new ComputeSize(64, 1, 1)); - var convertD32S8ToD24S8ResourceLayout = new ResourceLayoutBuilder() + ResourceLayout convertD32S8ToD24S8ResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 0) .Add(ResourceStages.Compute, ResourceType.StorageBuffer, 1) .Add(ResourceStages.Compute, ResourceType.StorageBuffer, 2, true).Build(); - var convertD32S8ToD24S8Source = ReadMsl("ConvertD32S8ToD24S8.metal"); + string convertD32S8ToD24S8Source = ReadMsl("ConvertD32S8ToD24S8.metal"); _programConvertD32S8ToD24S8 = new Program(renderer, device, [ new ShaderSource(convertD32S8ToD24S8Source, ShaderStage.Compute, TargetLanguage.Msl) ], convertD32S8ToD24S8ResourceLayout, new ComputeSize(64, 1, 1)); - var convertIndexBufferLayout = new ResourceLayoutBuilder() + ResourceLayout convertIndexBufferLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.StorageBuffer, 1) .Add(ResourceStages.Compute, ResourceType.StorageBuffer, 2, true) .Add(ResourceStages.Compute, ResourceType.StorageBuffer, 3).Build(); - var convertIndexBufferSource = ReadMsl("ConvertIndexBuffer.metal"); + string convertIndexBufferSource = ReadMsl("ConvertIndexBuffer.metal"); _programConvertIndexBuffer = new Program(renderer, device, [ new ShaderSource(convertIndexBufferSource, ShaderStage.Compute, TargetLanguage.Msl) ], convertIndexBufferLayout, new ComputeSize(16, 1, 1)); - var depthBlitSource = ReadMsl("DepthBlit.metal"); + string depthBlitSource = ReadMsl("DepthBlit.metal"); _programDepthBlit = new Program(renderer, device, [ new ShaderSource(depthBlitSource, ShaderStage.Fragment, TargetLanguage.Msl), new ShaderSource(blitSourceF, ShaderStage.Vertex, TargetLanguage.Msl) ], blitResourceLayout); - var depthBlitMsSource = ReadMsl("DepthBlitMs.metal"); + string depthBlitMsSource = ReadMsl("DepthBlitMs.metal"); _programDepthBlitMs = new Program(renderer, device, [ new ShaderSource(depthBlitMsSource, ShaderStage.Fragment, TargetLanguage.Msl), new ShaderSource(blitSourceF, ShaderStage.Vertex, TargetLanguage.Msl) ], blitResourceLayout); - var stencilBlitSource = ReadMsl("StencilBlit.metal"); + string stencilBlitSource = ReadMsl("StencilBlit.metal"); _programStencilBlit = new Program(renderer, device, [ new ShaderSource(stencilBlitSource, ShaderStage.Fragment, TargetLanguage.Msl), new ShaderSource(blitSourceF, ShaderStage.Vertex, TargetLanguage.Msl) ], blitResourceLayout); - var stencilBlitMsSource = ReadMsl("StencilBlitMs.metal"); + string stencilBlitMsSource = ReadMsl("StencilBlitMs.metal"); _programStencilBlitMs = new Program(renderer, device, [ new ShaderSource(stencilBlitMsSource, ShaderStage.Fragment, TargetLanguage.Msl), new ShaderSource(blitSourceF, ShaderStage.Vertex, TargetLanguage.Msl) @@ -189,7 +189,7 @@ namespace Ryujinx.Graphics.Metal private static string ReadMsl(string fileName) { - var msl = EmbeddedResources.ReadAllText(string.Join('/', ShadersSourcePath, fileName)); + string msl = EmbeddedResources.ReadAllText(string.Join('/', ShadersSourcePath, fileName)); #pragma warning disable IDE0055 // Disable formatting msl = msl.Replace("CONSTANT_BUFFERS_INDEX", $"{Constants.ConstantBuffersIndex}") @@ -214,7 +214,7 @@ namespace Ryujinx.Graphics.Metal const int RegionBufferSize = 16; - var sampler = linearFilter ? _samplerLinear : _samplerNearest; + ISampler sampler = linearFilter ? _samplerLinear : _samplerNearest; _pipeline.SetTextureAndSampler(ShaderStage.Fragment, 0, src, sampler); @@ -235,11 +235,11 @@ namespace Ryujinx.Graphics.Metal (region[2], region[3]) = (region[3], region[2]); } - using var buffer = _renderer.BufferManager.ReserveOrCreate(cbs, RegionBufferSize); + using ScopedTemporaryBuffer buffer = _renderer.BufferManager.ReserveOrCreate(cbs, RegionBufferSize); buffer.Holder.SetDataUnchecked(buffer.Offset, region); _pipeline.SetUniformBuffers([new BufferAssignment(0, buffer.Range)]); - var rect = new Rectangle( + Rectangle rect = new Rectangle( MathF.Min(dstRegion.X1, dstRegion.X2), MathF.Min(dstRegion.Y1, dstRegion.Y2), MathF.Abs(dstRegion.X2 - dstRegion.X1), @@ -266,7 +266,7 @@ namespace Ryujinx.Graphics.Metal return; } - var debugGroupName = "Blit Color "; + string debugGroupName = "Blit Color "; if (src.Info.Target.IsMultisample()) { @@ -359,13 +359,13 @@ namespace Ryujinx.Graphics.Metal (region[2], region[3]) = (region[3], region[2]); } - using var buffer = _renderer.BufferManager.ReserveOrCreate(cbs, RegionBufferSize); + using ScopedTemporaryBuffer buffer = _renderer.BufferManager.ReserveOrCreate(cbs, RegionBufferSize); buffer.Holder.SetDataUnchecked(buffer.Offset, region); _pipeline.SetUniformBuffers([new BufferAssignment(0, buffer.Range)]); Span viewports = stackalloc Viewport[16]; - var rect = new Rectangle( + Rectangle rect = new Rectangle( MathF.Min(dstRegion.X1, dstRegion.X2), MathF.Min(dstRegion.Y1, dstRegion.Y2), MathF.Abs(dstRegion.X2 - dstRegion.X1), @@ -400,7 +400,7 @@ namespace Ryujinx.Graphics.Metal Format.D32FloatS8Uint or Format.S8UintD24Unorm) { - var depthTexture = CreateDepthOrStencilView(src, DepthStencilMode.Depth); + Texture depthTexture = CreateDepthOrStencilView(src, DepthStencilMode.Depth); BlitDepthStencilDraw(depthTexture, isDepth: true); @@ -416,7 +416,7 @@ namespace Ryujinx.Graphics.Metal Format.D32FloatS8Uint or Format.S8UintD24Unorm) { - var stencilTexture = CreateDepthOrStencilView(src, DepthStencilMode.Stencil); + Texture stencilTexture = CreateDepthOrStencilView(src, DepthStencilMode.Stencil); BlitDepthStencilDraw(stencilTexture, isDepth: false); @@ -494,7 +494,7 @@ namespace Ryujinx.Graphics.Metal Extents2DF dstRegion) { // Save current state - var state = _pipeline.SavePredrawState(); + PredrawState state = _pipeline.SavePredrawState(); _pipeline.SetFaceCulling(false, Face.Front); _pipeline.SetStencilTest(new StencilTestDescriptor()); @@ -521,13 +521,13 @@ namespace Ryujinx.Graphics.Metal (region[2], region[3]) = (region[3], region[2]); } - var bufferHandle = _renderer.BufferManager.CreateWithHandle(RegionBufferSize); + BufferHandle bufferHandle = _renderer.BufferManager.CreateWithHandle(RegionBufferSize); _renderer.BufferManager.SetData(bufferHandle, 0, region); _pipeline.SetUniformBuffers([new BufferAssignment(0, new BufferRange(bufferHandle, 0, RegionBufferSize))]); Span viewports = stackalloc Viewport[16]; - var rect = new Rectangle( + Rectangle rect = new Rectangle( MathF.Min(dstRegion.X1, dstRegion.X2), MathF.Min(dstRegion.Y1, dstRegion.Y2), MathF.Abs(dstRegion.X2 - dstRegion.X1), @@ -569,8 +569,8 @@ namespace Ryujinx.Graphics.Metal { int elems = size / stride; - var srcBuffer = src.GetBuffer(); - var dstBuffer = dst.GetBuffer(); + Auto srcBuffer = src.GetBuffer(); + Auto dstBuffer = dst.GetBuffer(); const int ParamsBufferSize = 4 * sizeof(int); @@ -584,7 +584,7 @@ namespace Ryujinx.Graphics.Metal shaderParams[2] = size; shaderParams[3] = srcOffset; - using var buffer = _renderer.BufferManager.ReserveOrCreate(cbs, ParamsBufferSize); + using ScopedTemporaryBuffer buffer = _renderer.BufferManager.ReserveOrCreate(cbs, ParamsBufferSize); buffer.Holder.SetDataUnchecked(buffer.Offset, shaderParams); _pipeline.SetUniformBuffers([new BufferAssignment(0, buffer.Range)]); @@ -605,7 +605,7 @@ namespace Ryujinx.Graphics.Metal { int inSize = pixelCount * 2 * sizeof(int); - var srcBuffer = src.GetBuffer(); + Auto srcBuffer = src.GetBuffer(); const int ParamsBufferSize = sizeof(int) * 2; @@ -617,7 +617,7 @@ namespace Ryujinx.Graphics.Metal shaderParams[0] = pixelCount; shaderParams[1] = dstOffset; - using var buffer = _renderer.BufferManager.ReserveOrCreate(cbs, ParamsBufferSize); + using ScopedTemporaryBuffer buffer = _renderer.BufferManager.ReserveOrCreate(cbs, ParamsBufferSize); buffer.Holder.SetDataUnchecked(buffer.Offset, shaderParams); _pipeline.SetUniformBuffers([new BufferAssignment(0, buffer.Range)]); @@ -648,8 +648,8 @@ namespace Ryujinx.Graphics.Metal int primitiveCount = pattern.GetPrimitiveCount(indexCount); int outputIndexSize = 4; - var srcBuffer = src.GetBuffer(); - var dstBuffer = dst.GetBuffer(); + Auto srcBuffer = src.GetBuffer(); + Auto dstBuffer = dst.GetBuffer(); const int ParamsBufferSize = 16 * sizeof(int); @@ -669,7 +669,7 @@ namespace Ryujinx.Graphics.Metal pattern.OffsetIndex.CopyTo(shaderParams[..pattern.OffsetIndex.Length]); - using var patternScoped = _renderer.BufferManager.ReserveOrCreate(cbs, ParamsBufferSize); + using ScopedTemporaryBuffer patternScoped = _renderer.BufferManager.ReserveOrCreate(cbs, ParamsBufferSize); patternScoped.Holder.SetDataUnchecked(patternScoped.Offset, shaderParams); Span> sbRanges = new Auto[2]; @@ -707,7 +707,7 @@ namespace Ryujinx.Graphics.Metal // TODO: Flush - using var buffer = _renderer.BufferManager.ReserveOrCreate(_pipeline.Cbs, ClearColorBufferSize); + using ScopedTemporaryBuffer buffer = _renderer.BufferManager.ReserveOrCreate(_pipeline.Cbs, ClearColorBufferSize); buffer.Holder.SetDataUnchecked(buffer.Offset, clearColor); _pipeline.SetUniformBuffers([new BufferAssignment(0, buffer.Range)]); @@ -726,7 +726,7 @@ namespace Ryujinx.Graphics.Metal Span componentMasks = stackalloc uint[index + 1]; componentMasks[index] = componentMask; - var debugGroupName = "Clear Color "; + string debugGroupName = "Clear Color "; if (format.IsSint()) { @@ -768,7 +768,7 @@ namespace Ryujinx.Graphics.Metal { // Keep original scissor DirtyFlags clearFlags = DirtyFlags.All & (~DirtyFlags.Scissors); - var helperScissors = _helperShaderState.Scissors; + MTLScissorRect[] helperScissors = _helperShaderState.Scissors; // Save current state EncoderState originalState = _pipeline.SwapState(_helperShaderState, clearFlags, false); @@ -778,7 +778,7 @@ namespace Ryujinx.Graphics.Metal const int ClearDepthBufferSize = 16; - using var buffer = _renderer.BufferManager.ReserveOrCreate(_pipeline.Cbs, ClearDepthBufferSize); + using ScopedTemporaryBuffer buffer = _renderer.BufferManager.ReserveOrCreate(_pipeline.Cbs, ClearDepthBufferSize); buffer.Holder.SetDataUnchecked(buffer.Offset, new ReadOnlySpan(ref depthValue)); _pipeline.SetUniformBuffers([new BufferAssignment(0, buffer.Range)]); @@ -844,17 +844,17 @@ namespace Ryujinx.Graphics.Metal _programColorBlitMsI.Dispose(); _programColorBlitMsU.Dispose(); - foreach (var programColorClear in _programsColorClearF) + foreach (IProgram programColorClear in _programsColorClearF) { programColorClear.Dispose(); } - foreach (var programColorClear in _programsColorClearU) + foreach (IProgram programColorClear in _programsColorClearU) { programColorClear.Dispose(); } - foreach (var programColorClear in _programsColorClearI) + foreach (IProgram programColorClear in _programsColorClearI) { programColorClear.Dispose(); } diff --git a/src/Ryujinx.Graphics.Metal/IndexBufferState.cs b/src/Ryujinx.Graphics.Metal/IndexBufferState.cs index 411df9685..02c9ff9ef 100644 --- a/src/Ryujinx.Graphics.Metal/IndexBufferState.cs +++ b/src/Ryujinx.Graphics.Metal/IndexBufferState.cs @@ -76,7 +76,7 @@ namespace Ryujinx.Graphics.Metal int firstIndexOffset = firstIndex * indexSize; - var autoBuffer = renderer.BufferManager.GetBufferTopologyConversion(cbs, _handle, _offset + firstIndexOffset, indexCount * indexSize, pattern, indexSize); + Auto autoBuffer = renderer.BufferManager.GetBufferTopologyConversion(cbs, _handle, _offset + firstIndexOffset, indexCount * indexSize, pattern, indexSize); int size = convertedCount * 4; diff --git a/src/Ryujinx.Graphics.Metal/MetalRenderer.cs b/src/Ryujinx.Graphics.Metal/MetalRenderer.cs index 7afd30886..cfda31e66 100644 --- a/src/Ryujinx.Graphics.Metal/MetalRenderer.cs +++ b/src/Ryujinx.Graphics.Metal/MetalRenderer.cs @@ -61,7 +61,7 @@ namespace Ryujinx.Graphics.Metal public void Initialize(GraphicsDebugLevel logLevel) { - var layer = _getMetalLayer(); + CAMetalLayer layer = _getMetalLayer(); layer.Device = _device; layer.FramebufferOnly = false; @@ -253,7 +253,7 @@ namespace Ryujinx.Graphics.Metal public ICounterEvent ReportCounter(CounterType type, EventHandler resultHandler, float divisor, bool hostReserved) { // https://developer.apple.com/documentation/metal/gpu_counters_and_counter_sample_buffers/creating_a_counter_sample_buffer_to_store_a_gpu_s_counter_data_during_a_pass?language=objc - var counterEvent = new CounterEvent(); + CounterEvent counterEvent = new CounterEvent(); resultHandler?.Invoke(counterEvent, type == CounterType.SamplesPassed ? (ulong)1 : 0); return counterEvent; } @@ -295,12 +295,12 @@ namespace Ryujinx.Graphics.Metal { BackgroundResources.Dispose(); - foreach (var program in Programs) + foreach (Program program in Programs) { program.Dispose(); } - foreach (var sampler in Samplers) + foreach (SamplerHolder sampler in Samplers) { sampler.Dispose(); } diff --git a/src/Ryujinx.Graphics.Metal/MultiFenceHolder.cs b/src/Ryujinx.Graphics.Metal/MultiFenceHolder.cs index cd5ad08ba..89ae1fa77 100644 --- a/src/Ryujinx.Graphics.Metal/MultiFenceHolder.cs +++ b/src/Ryujinx.Graphics.Metal/MultiFenceHolder.cs @@ -189,14 +189,14 @@ namespace Ryujinx.Graphics.Metal if (indefinite) { - foreach (var fence in fences) + foreach (MTLCommandBuffer fence in fences) { fence.WaitUntilCompleted(); } } else { - foreach (var fence in fences) + foreach (MTLCommandBuffer fence in fences) { if (fence.Status != MTLCommandBufferStatus.Completed) { @@ -224,7 +224,7 @@ namespace Ryujinx.Graphics.Metal for (int i = 0; i < _fences.Length; i++) { - var fence = _fences[i]; + FenceHolder fence = _fences[i]; if (fence != null) { @@ -248,7 +248,7 @@ namespace Ryujinx.Graphics.Metal for (int i = 0; i < _fences.Length; i++) { - var fence = _fences[i]; + FenceHolder fence = _fences[i]; if (fence != null && _bufferUsageBitmap.OverlapsWith(i, offset, size)) { diff --git a/src/Ryujinx.Graphics.Metal/PersistentFlushBuffer.cs b/src/Ryujinx.Graphics.Metal/PersistentFlushBuffer.cs index fa3df47db..fc79a40a9 100644 --- a/src/Ryujinx.Graphics.Metal/PersistentFlushBuffer.cs +++ b/src/Ryujinx.Graphics.Metal/PersistentFlushBuffer.cs @@ -1,4 +1,5 @@ using Ryujinx.Graphics.GAL; +using SharpMetal.Metal; using System; using System.Runtime.Versioning; @@ -18,7 +19,7 @@ namespace Ryujinx.Graphics.Metal private BufferHolder ResizeIfNeeded(int size) { - var flushStorage = _flushStorage; + BufferHolder flushStorage = _flushStorage; if (flushStorage == null || size > _flushStorage.Size) { @@ -33,13 +34,13 @@ namespace Ryujinx.Graphics.Metal public Span GetBufferData(CommandBufferPool cbp, BufferHolder buffer, int offset, int size) { - var flushStorage = ResizeIfNeeded(size); + BufferHolder flushStorage = ResizeIfNeeded(size); Auto srcBuffer; - using (var cbs = cbp.Rent()) + using (CommandBufferScoped cbs = cbp.Rent()) { srcBuffer = buffer.GetBuffer(); - var dstBuffer = flushStorage.GetBuffer(); + Auto dstBuffer = flushStorage.GetBuffer(); if (srcBuffer.TryIncrementReferenceCount()) { @@ -61,12 +62,12 @@ namespace Ryujinx.Graphics.Metal { TextureCreateInfo info = view.Info; - var flushStorage = ResizeIfNeeded(size); + BufferHolder flushStorage = ResizeIfNeeded(size); - using (var cbs = cbp.Rent()) + using (CommandBufferScoped cbs = cbp.Rent()) { - var buffer = flushStorage.GetBuffer().Get(cbs).Value; - var image = view.GetHandle(); + MTLBuffer buffer = flushStorage.GetBuffer().Get(cbs).Value; + MTLTexture image = view.GetHandle(); view.CopyFromOrToBuffer(cbs, buffer, image, size, true, 0, 0, info.GetLayers(), info.Levels, singleSlice: false); } @@ -77,12 +78,12 @@ namespace Ryujinx.Graphics.Metal public Span GetTextureData(CommandBufferPool cbp, Texture view, int size, int layer, int level) { - var flushStorage = ResizeIfNeeded(size); + BufferHolder flushStorage = ResizeIfNeeded(size); - using (var cbs = cbp.Rent()) + using (CommandBufferScoped cbs = cbp.Rent()) { - var buffer = flushStorage.GetBuffer().Get(cbs).Value; - var image = view.GetHandle(); + MTLBuffer buffer = flushStorage.GetBuffer().Get(cbs).Value; + MTLTexture image = view.GetHandle(); view.CopyFromOrToBuffer(cbs, buffer, image, size, true, layer, level, 1, 1, singleSlice: true); } diff --git a/src/Ryujinx.Graphics.Metal/Pipeline.cs b/src/Ryujinx.Graphics.Metal/Pipeline.cs index 113974061..d7fbebada 100644 --- a/src/Ryujinx.Graphics.Metal/Pipeline.cs +++ b/src/Ryujinx.Graphics.Metal/Pipeline.cs @@ -149,8 +149,8 @@ namespace Ryujinx.Graphics.Metal public void Present(CAMetalDrawable drawable, Texture src, Extents2D srcRegion, Extents2D dstRegion, bool isLinear) { // TODO: Clean this up - var textureInfo = new TextureCreateInfo((int)drawable.Texture.Width, (int)drawable.Texture.Height, (int)drawable.Texture.Depth, (int)drawable.Texture.MipmapLevelCount, (int)drawable.Texture.SampleCount, 0, 0, 0, Format.B8G8R8A8Unorm, 0, Target.Texture2D, SwizzleComponent.Red, SwizzleComponent.Green, SwizzleComponent.Blue, SwizzleComponent.Alpha); - var dst = new Texture(_device, _renderer, this, textureInfo, drawable.Texture, 0, 0); + TextureCreateInfo textureInfo = new TextureCreateInfo((int)drawable.Texture.Width, (int)drawable.Texture.Height, (int)drawable.Texture.Depth, (int)drawable.Texture.MipmapLevelCount, (int)drawable.Texture.SampleCount, 0, 0, 0, Format.B8G8R8A8Unorm, 0, Target.Texture2D, SwizzleComponent.Red, SwizzleComponent.Green, SwizzleComponent.Blue, SwizzleComponent.Alpha); + Texture dst = new Texture(_device, _renderer, this, textureInfo, drawable.Texture, 0, 0); _renderer.HelperShader.BlitColor(Cbs, src, dst, srcRegion, dstRegion, isLinear, true); @@ -248,14 +248,14 @@ namespace Ryujinx.Graphics.Metal { case EncoderType.Render: { - var scope = MTLBarrierScope.Buffers | MTLBarrierScope.Textures | MTLBarrierScope.RenderTargets; + MTLBarrierScope scope = MTLBarrierScope.Buffers | MTLBarrierScope.Textures | MTLBarrierScope.RenderTargets; MTLRenderStages stages = MTLRenderStages.RenderStageVertex | MTLRenderStages.RenderStageFragment; Encoders.RenderEncoder.MemoryBarrier(scope, stages, stages); break; } case EncoderType.Compute: { - var scope = MTLBarrierScope.Buffers | MTLBarrierScope.Textures | MTLBarrierScope.RenderTargets; + MTLBarrierScope scope = MTLBarrierScope.Buffers | MTLBarrierScope.Textures | MTLBarrierScope.RenderTargets; Encoders.ComputeEncoder.MemoryBarrier(scope); break; } @@ -264,9 +264,9 @@ namespace Ryujinx.Graphics.Metal public void ClearBuffer(BufferHandle destination, int offset, int size, uint value) { - var blitCommandEncoder = GetOrCreateBlitEncoder(); + MTLBlitCommandEncoder blitCommandEncoder = GetOrCreateBlitEncoder(); - var mtlBuffer = _renderer.BufferManager.GetBuffer(destination, offset, size, true).Get(Cbs, offset, size, true).Value; + MTLBuffer mtlBuffer = _renderer.BufferManager.GetBuffer(destination, offset, size, true).Get(Cbs, offset, size, true).Value; // Might need a closer look, range's count, lower, and upper bound // must be a multiple of 4 @@ -282,7 +282,7 @@ namespace Ryujinx.Graphics.Metal public void ClearRenderTargetColor(int index, int layer, int layerCount, uint componentMask, ColorF color) { float[] colors = [color.Red, color.Green, color.Blue, color.Alpha]; - var dst = _encoderStateManager.RenderTargets[index]; + Texture dst = _encoderStateManager.RenderTargets[index]; // TODO: Remove workaround for Wonder which has an invalid texture due to unsupported format if (dst == null) @@ -296,7 +296,7 @@ namespace Ryujinx.Graphics.Metal public void ClearRenderTargetDepthStencil(int layer, int layerCount, float depthValue, bool depthMask, int stencilValue, int stencilMask) { - var depthStencil = _encoderStateManager.DepthStencil; + Texture depthStencil = _encoderStateManager.DepthStencil; if (depthStencil == null) { @@ -313,16 +313,16 @@ namespace Ryujinx.Graphics.Metal public void CopyBuffer(BufferHandle src, BufferHandle dst, int srcOffset, int dstOffset, int size) { - var srcBuffer = _renderer.BufferManager.GetBuffer(src, srcOffset, size, false); - var dstBuffer = _renderer.BufferManager.GetBuffer(dst, dstOffset, size, true); + Auto srcBuffer = _renderer.BufferManager.GetBuffer(src, srcOffset, size, false); + Auto dstBuffer = _renderer.BufferManager.GetBuffer(dst, dstOffset, size, true); BufferHolder.Copy(Cbs, srcBuffer, dstBuffer, srcOffset, dstOffset, size); } public void PushDebugGroup(string name) { - var encoder = Encoders.CurrentEncoder; - var debugGroupName = StringHelper.NSString(name); + MTLCommandEncoder? encoder = Encoders.CurrentEncoder; + NSString debugGroupName = StringHelper.NSString(name); if (encoder == null) { @@ -345,7 +345,7 @@ namespace Ryujinx.Graphics.Metal public void PopDebugGroup() { - var encoder = Encoders.CurrentEncoder; + MTLCommandEncoder? encoder = Encoders.CurrentEncoder; if (encoder == null) { @@ -373,7 +373,7 @@ namespace Ryujinx.Graphics.Metal public void DispatchCompute(int groupsX, int groupsY, int groupsZ, string debugGroupName) { - var computeCommandEncoder = GetOrCreateComputeEncoder(true); + MTLComputeCommandEncoder computeCommandEncoder = GetOrCreateComputeEncoder(true); ComputeSize localSize = _encoderStateManager.ComputeLocalSize; @@ -404,17 +404,17 @@ namespace Ryujinx.Graphics.Metal return; } - var primitiveType = TopologyRemap(_encoderStateManager.Topology).Convert(); + MTLPrimitiveType primitiveType = TopologyRemap(_encoderStateManager.Topology).Convert(); if (TopologyUnsupported(_encoderStateManager.Topology)) { - var pattern = GetIndexBufferPattern(); + IndexBufferPattern pattern = GetIndexBufferPattern(); BufferHandle handle = pattern.GetRepeatingBuffer(vertexCount, out int indexCount); - var buffer = _renderer.BufferManager.GetBuffer(handle, false); - var mtlBuffer = buffer.Get(Cbs, 0, indexCount * sizeof(int)).Value; + Auto buffer = _renderer.BufferManager.GetBuffer(handle, false); + MTLBuffer mtlBuffer = buffer.Get(Cbs, 0, indexCount * sizeof(int)).Value; - var renderCommandEncoder = GetOrCreateRenderEncoder(true); + MTLRenderCommandEncoder renderCommandEncoder = GetOrCreateRenderEncoder(true); renderCommandEncoder.DrawIndexedPrimitives( primitiveType, @@ -425,7 +425,7 @@ namespace Ryujinx.Graphics.Metal } else { - var renderCommandEncoder = GetOrCreateRenderEncoder(true); + MTLRenderCommandEncoder renderCommandEncoder = GetOrCreateRenderEncoder(true); if (debugGroupName != String.Empty) { @@ -488,11 +488,11 @@ namespace Ryujinx.Graphics.Metal MTLIndexType type; int finalIndexCount = indexCount; - var primitiveType = TopologyRemap(_encoderStateManager.Topology).Convert(); + MTLPrimitiveType primitiveType = TopologyRemap(_encoderStateManager.Topology).Convert(); if (TopologyUnsupported(_encoderStateManager.Topology)) { - var pattern = GetIndexBufferPattern(); + IndexBufferPattern pattern = GetIndexBufferPattern(); int convertedCount = pattern.GetConvertedCount(indexCount); finalIndexCount = convertedCount; @@ -506,7 +506,7 @@ namespace Ryujinx.Graphics.Metal if (mtlBuffer.NativePtr != IntPtr.Zero) { - var renderCommandEncoder = GetOrCreateRenderEncoder(true); + MTLRenderCommandEncoder renderCommandEncoder = GetOrCreateRenderEncoder(true); renderCommandEncoder.DrawIndexedPrimitives( primitiveType, @@ -533,17 +533,17 @@ namespace Ryujinx.Graphics.Metal Logger.Warning?.Print(LogClass.Gpu, $"Drawing indexed with unsupported topology: {_encoderStateManager.Topology}"); } - var buffer = _renderer.BufferManager + MTLBuffer buffer = _renderer.BufferManager .GetBuffer(indirectBuffer.Handle, indirectBuffer.Offset, indirectBuffer.Size, false) .Get(Cbs, indirectBuffer.Offset, indirectBuffer.Size).Value; - var primitiveType = TopologyRemap(_encoderStateManager.Topology).Convert(); + MTLPrimitiveType primitiveType = TopologyRemap(_encoderStateManager.Topology).Convert(); (MTLBuffer indexBuffer, int indexOffset, MTLIndexType type) = _encoderStateManager.IndexBuffer.GetIndexBuffer(_renderer, Cbs); if (indexBuffer.NativePtr != IntPtr.Zero && buffer.NativePtr != IntPtr.Zero) { - var renderCommandEncoder = GetOrCreateRenderEncoder(true); + MTLRenderCommandEncoder renderCommandEncoder = GetOrCreateRenderEncoder(true); renderCommandEncoder.DrawIndexedPrimitives( primitiveType, @@ -576,12 +576,12 @@ namespace Ryujinx.Graphics.Metal Logger.Warning?.Print(LogClass.Gpu, $"Drawing indirect with unsupported topology: {_encoderStateManager.Topology}"); } - var buffer = _renderer.BufferManager + MTLBuffer buffer = _renderer.BufferManager .GetBuffer(indirectBuffer.Handle, indirectBuffer.Offset, indirectBuffer.Size, false) .Get(Cbs, indirectBuffer.Offset, indirectBuffer.Size).Value; - var primitiveType = TopologyRemap(_encoderStateManager.Topology).Convert(); - var renderCommandEncoder = GetOrCreateRenderEncoder(true); + MTLPrimitiveType primitiveType = TopologyRemap(_encoderStateManager.Topology).Convert(); + MTLRenderCommandEncoder renderCommandEncoder = GetOrCreateRenderEncoder(true); renderCommandEncoder.DrawPrimitives( primitiveType, diff --git a/src/Ryujinx.Graphics.Metal/Program.cs b/src/Ryujinx.Graphics.Metal/Program.cs index 37bae5817..780725400 100644 --- a/src/Ryujinx.Graphics.Metal/Program.cs +++ b/src/Ryujinx.Graphics.Metal/Program.cs @@ -56,12 +56,12 @@ namespace Ryujinx.Graphics.Metal { ShaderSource shader = _shaders[i]; - using var compileOptions = new MTLCompileOptions + using MTLCompileOptions compileOptions = new MTLCompileOptions { PreserveInvariance = true, LanguageVersion = MTLLanguageVersion.Version31, }; - var index = i; + int index = i; _handles[i] = device.NewLibrary(StringHelper.NSString(shader.Code), compileOptions, (library, error) => CompilationResultHandler(library, error, index)); } @@ -71,7 +71,7 @@ namespace Ryujinx.Graphics.Metal public void CompilationResultHandler(MTLLibrary library, NSError error, int index) { - var shader = _shaders[index]; + ShaderSource shader = _shaders[index]; if (_handles[index].IsAllocated) { @@ -142,7 +142,7 @@ namespace Ryujinx.Graphics.Metal currentUsage.Stages, currentUsage.ArrayLength > 1)); - var size = currentCount * ResourcePointerSize(currentUsage.Type); + int size = currentCount * ResourcePointerSize(currentUsage.Type); if (currentUsage.Stages.HasFlag(ResourceStages.Fragment)) { fragArgBufferSizes[setIndex] += size; @@ -173,7 +173,7 @@ namespace Ryujinx.Graphics.Metal currentUsage.Stages, currentUsage.ArrayLength > 1)); - var size = currentCount * ResourcePointerSize(currentUsage.Type); + int size = currentCount * ResourcePointerSize(currentUsage.Type); if (currentUsage.Stages.HasFlag(ResourceStages.Fragment)) { fragArgBufferSizes[setIndex] += size; diff --git a/src/Ryujinx.Graphics.Metal/ResourceLayoutBuilder.cs b/src/Ryujinx.Graphics.Metal/ResourceLayoutBuilder.cs index 36ae9bac6..6f6000f69 100644 --- a/src/Ryujinx.Graphics.Metal/ResourceLayoutBuilder.cs +++ b/src/Ryujinx.Graphics.Metal/ResourceLayoutBuilder.cs @@ -44,8 +44,8 @@ namespace Ryujinx.Graphics.Metal public ResourceLayout Build() { - var descriptors = new ResourceDescriptorCollection[TotalSets]; - var usages = new ResourceUsageCollection[TotalSets]; + ResourceDescriptorCollection[] descriptors = new ResourceDescriptorCollection[TotalSets]; + ResourceUsageCollection[] usages = new ResourceUsageCollection[TotalSets]; for (int index = 0; index < TotalSets; index++) { diff --git a/src/Ryujinx.Graphics.Metal/SamplerHolder.cs b/src/Ryujinx.Graphics.Metal/SamplerHolder.cs index 3241efa6d..f1270443b 100644 --- a/src/Ryujinx.Graphics.Metal/SamplerHolder.cs +++ b/src/Ryujinx.Graphics.Metal/SamplerHolder.cs @@ -21,7 +21,7 @@ namespace Ryujinx.Graphics.Metal MTLSamplerBorderColor borderColor = GetConstrainedBorderColor(info.BorderColor, out _); - using var descriptor = new MTLSamplerDescriptor + using MTLSamplerDescriptor descriptor = new MTLSamplerDescriptor { BorderColor = borderColor, MinFilter = minFilter, @@ -38,7 +38,7 @@ namespace Ryujinx.Graphics.Metal SupportArgumentBuffers = true }; - var sampler = device.NewSamplerState(descriptor); + MTLSamplerState sampler = device.NewSamplerState(descriptor); _sampler = new Auto(new DisposableSampler(sampler)); } diff --git a/src/Ryujinx.Graphics.Metal/StagingBuffer.cs b/src/Ryujinx.Graphics.Metal/StagingBuffer.cs index b250b87f2..b4838ee33 100644 --- a/src/Ryujinx.Graphics.Metal/StagingBuffer.cs +++ b/src/Ryujinx.Graphics.Metal/StagingBuffer.cs @@ -108,8 +108,8 @@ namespace Ryujinx.Graphics.Metal private void PushDataImpl(CommandBufferScoped cbs, BufferHolder dst, int dstOffset, ReadOnlySpan data) { - var srcBuffer = _buffer.GetBuffer(); - var dstBuffer = dst.GetBuffer(dstOffset, data.Length, true); + Auto srcBuffer = _buffer.GetBuffer(); + Auto dstBuffer = dst.GetBuffer(dstOffset, data.Length, true); int offset = _freeOffset; int capacity = BufferSize - offset; @@ -241,7 +241,7 @@ namespace Ryujinx.Graphics.Metal private bool WaitFreeCompleted(CommandBufferPool cbp) { - if (_pendingCopies.TryPeek(out var pc)) + if (_pendingCopies.TryPeek(out PendingCopy pc)) { if (!pc.Fence.IsSignaled()) { @@ -253,7 +253,7 @@ namespace Ryujinx.Graphics.Metal pc.Fence.Wait(); } - var dequeued = _pendingCopies.Dequeue(); + PendingCopy dequeued = _pendingCopies.Dequeue(); Debug.Assert(dequeued.Fence == pc.Fence); _freeSize += pc.Size; pc.Fence.Put(); @@ -265,10 +265,10 @@ namespace Ryujinx.Graphics.Metal public void FreeCompleted() { FenceHolder signalledFence = null; - while (_pendingCopies.TryPeek(out var pc) && (pc.Fence == signalledFence || pc.Fence.IsSignaled())) + while (_pendingCopies.TryPeek(out PendingCopy pc) && (pc.Fence == signalledFence || pc.Fence.IsSignaled())) { signalledFence = pc.Fence; // Already checked - don't need to do it again. - var dequeued = _pendingCopies.Dequeue(); + PendingCopy dequeued = _pendingCopies.Dequeue(); Debug.Assert(dequeued.Fence == pc.Fence); _freeSize += pc.Size; pc.Fence.Put(); @@ -279,7 +279,7 @@ namespace Ryujinx.Graphics.Metal { _renderer.BufferManager.Delete(Handle); - while (_pendingCopies.TryDequeue(out var pc)) + while (_pendingCopies.TryDequeue(out PendingCopy pc)) { pc.Fence.Put(); } diff --git a/src/Ryujinx.Graphics.Metal/State/PipelineState.cs b/src/Ryujinx.Graphics.Metal/State/PipelineState.cs index 9f88f3061..1fa83e8d7 100644 --- a/src/Ryujinx.Graphics.Metal/State/PipelineState.cs +++ b/src/Ryujinx.Graphics.Metal/State/PipelineState.cs @@ -118,13 +118,13 @@ namespace Ryujinx.Graphics.Metal private readonly MTLVertexDescriptor BuildVertexDescriptor() { - var vertexDescriptor = new MTLVertexDescriptor(); + MTLVertexDescriptor vertexDescriptor = new MTLVertexDescriptor(); for (int i = 0; i < VertexAttributeDescriptionsCount; i++) { VertexInputAttributeUid uid = Internal.VertexAttributes[i]; - var attrib = vertexDescriptor.Attributes.Object((ulong)i); + MTLVertexAttributeDescriptor attrib = vertexDescriptor.Attributes.Object((ulong)i); attrib.Format = uid.Format; attrib.Offset = uid.Offset; attrib.BufferIndex = uid.BufferIndex; @@ -134,7 +134,7 @@ namespace Ryujinx.Graphics.Metal { VertexInputLayoutUid uid = Internal.VertexBindings[i]; - var layout = vertexDescriptor.Layouts.Object((ulong)i); + MTLVertexBufferLayoutDescriptor layout = vertexDescriptor.Layouts.Object((ulong)i); layout.StepFunction = uid.StepFunction; layout.StepRate = uid.StepRate; @@ -146,15 +146,15 @@ namespace Ryujinx.Graphics.Metal private MTLRenderPipelineDescriptor CreateRenderDescriptor(Program program) { - var renderPipelineDescriptor = new MTLRenderPipelineDescriptor(); + MTLRenderPipelineDescriptor renderPipelineDescriptor = new MTLRenderPipelineDescriptor(); for (int i = 0; i < Constants.MaxColorAttachments; i++) { - var blendState = Internal.ColorBlendState[i]; + ColorBlendStateUid blendState = Internal.ColorBlendState[i]; if (blendState.PixelFormat != MTLPixelFormat.Invalid) { - var pipelineAttachment = renderPipelineDescriptor.ColorAttachments.Object((ulong)i); + MTLRenderPipelineColorAttachmentDescriptor pipelineAttachment = renderPipelineDescriptor.ColorAttachments.Object((ulong)i); BuildColorAttachment(pipelineAttachment, blendState); } @@ -195,7 +195,7 @@ namespace Ryujinx.Graphics.Metal renderPipelineDescriptor.RasterizationEnabled = !RasterizerDiscardEnable; renderPipelineDescriptor.SampleCount = Math.Max(1, SamplesCount); - var vertexDescriptor = BuildVertexDescriptor(); + MTLVertexDescriptor vertexDescriptor = BuildVertexDescriptor(); renderPipelineDescriptor.VertexDescriptor = vertexDescriptor; renderPipelineDescriptor.VertexFunction = program.VertexFunction; @@ -210,14 +210,14 @@ namespace Ryujinx.Graphics.Metal public MTLRenderPipelineState CreateRenderPipeline(MTLDevice device, Program program) { - if (program.TryGetGraphicsPipeline(ref Internal, out var pipelineState)) + if (program.TryGetGraphicsPipeline(ref Internal, out MTLRenderPipelineState pipelineState)) { return pipelineState; } - using var descriptor = CreateRenderDescriptor(program); + using MTLRenderPipelineDescriptor descriptor = CreateRenderDescriptor(program); - var error = new NSError(IntPtr.Zero); + NSError error = new NSError(IntPtr.Zero); pipelineState = device.NewRenderPipelineState(descriptor, ref error); if (error != IntPtr.Zero) { @@ -240,7 +240,7 @@ namespace Ryujinx.Graphics.Metal throw new InvalidOperationException($"Local thread size for compute cannot be 0 in any dimension."); } - var descriptor = new MTLComputePipelineDescriptor + MTLComputePipelineDescriptor descriptor = new MTLComputePipelineDescriptor { ComputeFunction = program.ComputeFunction, MaxTotalThreadsPerThreadgroup = maxThreads, @@ -252,14 +252,14 @@ namespace Ryujinx.Graphics.Metal public static MTLComputePipelineState CreateComputePipeline(MTLDevice device, Program program) { - if (program.TryGetComputePipeline(out var pipelineState)) + if (program.TryGetComputePipeline(out MTLComputePipelineState pipelineState)) { return pipelineState; } using MTLComputePipelineDescriptor descriptor = CreateComputeDescriptor(program); - var error = new NSError(IntPtr.Zero); + NSError error = new NSError(IntPtr.Zero); pipelineState = device.NewComputePipelineState(descriptor, MTLPipelineOption.None, 0, ref error); if (error != IntPtr.Zero) { diff --git a/src/Ryujinx.Graphics.Metal/State/PipelineUid.cs b/src/Ryujinx.Graphics.Metal/State/PipelineUid.cs index c986a7e23..5b514c2c9 100644 --- a/src/Ryujinx.Graphics.Metal/State/PipelineUid.cs +++ b/src/Ryujinx.Graphics.Metal/State/PipelineUid.cs @@ -114,7 +114,7 @@ namespace Ryujinx.Graphics.Metal public void Swap(ColorBlendStateUid uid) { - var format = PixelFormat; + MTLPixelFormat format = PixelFormat; this = uid; PixelFormat = format; diff --git a/src/Ryujinx.Graphics.Metal/StateCache.cs b/src/Ryujinx.Graphics.Metal/StateCache.cs index 9b8391ffc..8a9d175f1 100644 --- a/src/Ryujinx.Graphics.Metal/StateCache.cs +++ b/src/Ryujinx.Graphics.Metal/StateCache.cs @@ -25,14 +25,14 @@ namespace Ryujinx.Graphics.Metal public T GetOrCreate(TDescriptor descriptor) { - var hash = GetHash(descriptor); + THash hash = GetHash(descriptor); if (_cache.TryGetValue(hash, out T value)) { return value; } else { - var newValue = CreateValue(descriptor); + T newValue = CreateValue(descriptor); _cache.Add(hash, newValue); return newValue; diff --git a/src/Ryujinx.Graphics.Metal/Texture.cs b/src/Ryujinx.Graphics.Metal/Texture.cs index 4566d65d8..749da7d48 100644 --- a/src/Ryujinx.Graphics.Metal/Texture.cs +++ b/src/Ryujinx.Graphics.Metal/Texture.cs @@ -18,7 +18,7 @@ namespace Ryujinx.Graphics.Metal { MTLPixelFormat pixelFormat = FormatTable.GetFormat(Info.Format); - var descriptor = new MTLTextureDescriptor + MTLTextureDescriptor descriptor = new MTLTextureDescriptor { PixelFormat = pixelFormat, Usage = MTLTextureUsage.Unknown, @@ -65,7 +65,7 @@ namespace Ryujinx.Graphics.Metal public Texture(MTLDevice device, MetalRenderer renderer, Pipeline pipeline, TextureCreateInfo info, MTLTexture sourceTexture, int firstLayer, int firstLevel) : base(device, renderer, pipeline, info) { - var pixelFormat = FormatTable.GetFormat(Info.Format); + MTLPixelFormat pixelFormat = FormatTable.GetFormat(Info.Format); if (info.DepthStencilMode == DepthStencilMode.Stencil) { @@ -77,7 +77,7 @@ namespace Ryujinx.Graphics.Metal }; } - var textureType = Info.Target.Convert(); + MTLTextureType textureType = Info.Target.Convert(); NSRange levels; levels.location = (ulong)firstLevel; levels.length = (ulong)Info.Levels; @@ -85,7 +85,7 @@ namespace Ryujinx.Graphics.Metal slices.location = (ulong)firstLayer; slices.length = textureType == MTLTextureType.Type3D ? 1 : (ulong)info.GetDepthOrLayers(); - var swizzle = GetSwizzle(info, pixelFormat); + MTLTextureSwizzleChannels swizzle = GetSwizzle(info, pixelFormat); _identitySwizzleHandle = sourceTexture.NewTextureView(pixelFormat, textureType, levels, slices); @@ -131,10 +131,10 @@ namespace Ryujinx.Graphics.Metal private MTLTextureSwizzleChannels GetSwizzle(TextureCreateInfo info, MTLPixelFormat pixelFormat) { - var swizzleR = Info.SwizzleR.Convert(); - var swizzleG = Info.SwizzleG.Convert(); - var swizzleB = Info.SwizzleB.Convert(); - var swizzleA = Info.SwizzleA.Convert(); + MTLTextureSwizzle swizzleR = Info.SwizzleR.Convert(); + MTLTextureSwizzle swizzleG = Info.SwizzleG.Convert(); + MTLTextureSwizzle swizzleB = Info.SwizzleB.Convert(); + MTLTextureSwizzle swizzleA = Info.SwizzleA.Convert(); if (info.Format == Format.R5G5B5A1Unorm || info.Format == Format.R5G5B5X1Unorm || @@ -144,8 +144,8 @@ namespace Ryujinx.Graphics.Metal } else if (pixelFormat == MTLPixelFormat.ABGR4Unorm || info.Format == Format.A1B5G5R5Unorm) { - var tempB = swizzleB; - var tempA = swizzleA; + MTLTextureSwizzle tempB = swizzleB; + MTLTextureSwizzle tempA = swizzleA; swizzleB = swizzleG; swizzleA = swizzleR; @@ -174,8 +174,8 @@ namespace Ryujinx.Graphics.Metal return; } - var srcImage = GetHandle(); - var dstImage = dst.GetHandle(); + MTLTexture srcImage = GetHandle(); + MTLTexture dstImage = dst.GetHandle(); if (!dst.Info.Target.IsMultisample() && Info.Target.IsMultisample()) { @@ -231,8 +231,8 @@ namespace Ryujinx.Graphics.Metal return; } - var srcImage = GetHandle(); - var dstImage = dst.GetHandle(); + MTLTexture srcImage = GetHandle(); + MTLTexture dstImage = dst.GetHandle(); if (!dst.Info.Target.IsMultisample() && Info.Target.IsMultisample()) { @@ -276,7 +276,7 @@ namespace Ryujinx.Graphics.Metal return; } - var dst = (Texture)destination; + Texture dst = (Texture)destination; bool isDepthOrStencil = dst.Info.Format.IsDepthOrStencil(); @@ -285,15 +285,15 @@ namespace Ryujinx.Graphics.Metal public void CopyTo(BufferRange range, int layer, int level, int stride) { - var cbs = Pipeline.Cbs; + CommandBufferScoped cbs = Pipeline.Cbs; int outSize = Info.GetMipSize(level); int hostSize = GetBufferDataLength(outSize); int offset = range.Offset; - var autoBuffer = Renderer.BufferManager.GetBuffer(range.Handle, true); - var mtlBuffer = autoBuffer.Get(cbs, range.Offset, outSize).Value; + Auto autoBuffer = Renderer.BufferManager.GetBuffer(range.Handle, true); + MTLBuffer mtlBuffer = autoBuffer.Get(cbs, range.Offset, outSize).Value; if (PrepareOutputBuffer(cbs, hostSize, mtlBuffer, out MTLBuffer copyToBuffer, out BufferHolder tempCopyHolder)) { @@ -511,13 +511,13 @@ namespace Ryujinx.Graphics.Metal public void SetData(MemoryOwner data) { - var blitCommandEncoder = Pipeline.GetOrCreateBlitEncoder(); + MTLBlitCommandEncoder blitCommandEncoder = Pipeline.GetOrCreateBlitEncoder(); - var dataSpan = data.Memory.Span; + Span dataSpan = data.Memory.Span; - var buffer = Renderer.BufferManager.Create(dataSpan.Length); + BufferHolder buffer = Renderer.BufferManager.Create(dataSpan.Length); buffer.SetDataUnchecked(0, dataSpan); - var mtlBuffer = buffer.GetBuffer(false).Get(Pipeline.Cbs).Value; + MTLBuffer mtlBuffer = buffer.GetBuffer(false).Get(Pipeline.Cbs).Value; int width = Info.Width; int height = Info.Height; @@ -572,16 +572,16 @@ namespace Ryujinx.Graphics.Metal { int bufferDataLength = GetBufferDataLength(data.Length); - using var bufferHolder = Renderer.BufferManager.Create(bufferDataLength); + using BufferHolder bufferHolder = Renderer.BufferManager.Create(bufferDataLength); // TODO: loadInline logic - var cbs = Pipeline.Cbs; + CommandBufferScoped cbs = Pipeline.Cbs; CopyDataToBuffer(bufferHolder.GetDataStorage(0, bufferDataLength), data); - var buffer = bufferHolder.GetBuffer().Get(cbs).Value; - var image = GetHandle(); + MTLBuffer buffer = bufferHolder.GetBuffer().Get(cbs).Value; + MTLTexture image = GetHandle(); CopyFromOrToBuffer(cbs, buffer, image, bufferDataLength, false, layer, level, layers, levels, singleSlice); } @@ -595,7 +595,7 @@ namespace Ryujinx.Graphics.Metal public void SetData(MemoryOwner data, int layer, int level, Rectangle region) { - var blitCommandEncoder = Pipeline.GetOrCreateBlitEncoder(); + MTLBlitCommandEncoder blitCommandEncoder = Pipeline.GetOrCreateBlitEncoder(); ulong bytesPerRow = (ulong)Info.GetMipStride(level); ulong bytesPerImage = 0; @@ -604,11 +604,11 @@ namespace Ryujinx.Graphics.Metal bytesPerImage = bytesPerRow * (ulong)Info.Height; } - var dataSpan = data.Memory.Span; + Span dataSpan = data.Memory.Span; - var buffer = Renderer.BufferManager.Create(dataSpan.Length); + BufferHolder buffer = Renderer.BufferManager.Create(dataSpan.Length); buffer.SetDataUnchecked(0, dataSpan); - var mtlBuffer = buffer.GetBuffer(false).Get(Pipeline.Cbs).Value; + MTLBuffer mtlBuffer = buffer.GetBuffer(false).Get(Pipeline.Cbs).Value; blitCommandEncoder.CopyFromBuffer( mtlBuffer, diff --git a/src/Ryujinx.Graphics.Metal/VertexBufferState.cs b/src/Ryujinx.Graphics.Metal/VertexBufferState.cs index 6591fe6d6..8fb48ef79 100644 --- a/src/Ryujinx.Graphics.Metal/VertexBufferState.cs +++ b/src/Ryujinx.Graphics.Metal/VertexBufferState.cs @@ -49,7 +49,7 @@ namespace Ryujinx.Graphics.Metal if (autoBuffer != null) { int offset = _offset; - var buffer = autoBuffer.Get(cbs, offset, _size).Value; + MTLBuffer buffer = autoBuffer.Get(cbs, offset, _size).Value; return (buffer, offset); } diff --git a/src/Ryujinx.Graphics.Metal/Window.cs b/src/Ryujinx.Graphics.Metal/Window.cs index 1823c0b9a..f3c9133ab 100644 --- a/src/Ryujinx.Graphics.Metal/Window.cs +++ b/src/Ryujinx.Graphics.Metal/Window.cs @@ -47,7 +47,7 @@ namespace Ryujinx.Graphics.Metal if (_requestedWidth != 0 && _requestedHeight != 0) { // TODO: This is actually a CGSize, but there is no overload for that, so fill the first two fields of rect with the size. - var rect = new NSRect(_requestedWidth, _requestedHeight, 0, 0); + NSRect rect = new NSRect(_requestedWidth, _requestedHeight, 0, 0); ObjectiveC.objc_msgSend(_metalLayer, "setDrawableSize:", rect); @@ -62,7 +62,7 @@ namespace Ryujinx.Graphics.Metal { ResizeIfNeeded(); - var drawable = new CAMetalDrawable(ObjectiveC.IntPtr_objc_msgSend(_metalLayer, "nextDrawable")); + CAMetalDrawable drawable = new CAMetalDrawable(ObjectiveC.IntPtr_objc_msgSend(_metalLayer, "nextDrawable")); _width = (int)drawable.Texture.Width; _height = (int)drawable.Texture.Height; From 68bbb29be6d387d0ddc5a023988105d1d2db3684 Mon Sep 17 00:00:00 2001 From: Evan Husted Date: Sat, 25 Jan 2025 14:07:20 -0600 Subject: [PATCH 08/19] misc: chore: Use explicit types in NVDEC projects (except VP9 because there's an open PR and I don't want to cause conflicts) --- .../Native/FFmpegApi.cs | 2 +- src/Ryujinx.Graphics.Nvdec/Image/SurfaceWriter.cs | 13 +++++++------ src/Ryujinx.Graphics.Nvdec/NvdecDevice.cs | 4 ++-- src/Ryujinx.Graphics.Nvdec/Vp9Decoder.cs | 7 ++++--- 4 files changed, 14 insertions(+), 12 deletions(-) diff --git a/src/Ryujinx.Graphics.Nvdec.FFmpeg/Native/FFmpegApi.cs b/src/Ryujinx.Graphics.Nvdec.FFmpeg/Native/FFmpegApi.cs index 7b0c2a8ad..c31d3034e 100644 --- a/src/Ryujinx.Graphics.Nvdec.FFmpeg/Native/FFmpegApi.cs +++ b/src/Ryujinx.Graphics.Nvdec.FFmpeg/Native/FFmpegApi.cs @@ -41,7 +41,7 @@ namespace Ryujinx.Graphics.Nvdec.FFmpeg.Native { handle = nint.Zero; - if (_librariesWhitelist.TryGetValue(libraryName, out var value)) + if (_librariesWhitelist.TryGetValue(libraryName, out (int, int) value)) { (int minVersion, int maxVersion) = value; diff --git a/src/Ryujinx.Graphics.Nvdec/Image/SurfaceWriter.cs b/src/Ryujinx.Graphics.Nvdec/Image/SurfaceWriter.cs index 043be1f2b..e9927c0f8 100644 --- a/src/Ryujinx.Graphics.Nvdec/Image/SurfaceWriter.cs +++ b/src/Ryujinx.Graphics.Nvdec/Image/SurfaceWriter.cs @@ -2,6 +2,7 @@ using Ryujinx.Common; using Ryujinx.Graphics.Device; using Ryujinx.Graphics.Texture; using Ryujinx.Graphics.Video; +using Ryujinx.Memory; using System; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; @@ -16,7 +17,7 @@ namespace Ryujinx.Graphics.Nvdec.Image { int lumaSize = GetBlockLinearSize(surface.Width, surface.Height, 1); - using var luma = mm.GetWritableRegion(ExtendOffset(lumaOffset), lumaSize); + using WritableRegion luma = mm.GetWritableRegion(ExtendOffset(lumaOffset), lumaSize); WriteLuma( luma.Memory.Span, @@ -27,7 +28,7 @@ namespace Ryujinx.Graphics.Nvdec.Image int chromaSize = GetBlockLinearSize(surface.UvWidth, surface.UvHeight, 2); - using var chroma = mm.GetWritableRegion(ExtendOffset(chromaOffset), chromaSize); + using WritableRegion chroma = mm.GetWritableRegion(ExtendOffset(chromaOffset), chromaSize); WriteChroma( chroma.Memory.Span, @@ -48,8 +49,8 @@ namespace Ryujinx.Graphics.Nvdec.Image { int lumaSize = GetBlockLinearSize(surface.Width, surface.Height / 2, 1); - using var lumaTop = mm.GetWritableRegion(ExtendOffset(lumaTopOffset), lumaSize); - using var lumaBottom = mm.GetWritableRegion(ExtendOffset(lumaBottomOffset), lumaSize); + using WritableRegion lumaTop = mm.GetWritableRegion(ExtendOffset(lumaTopOffset), lumaSize); + using WritableRegion lumaBottom = mm.GetWritableRegion(ExtendOffset(lumaBottomOffset), lumaSize); WriteLuma( lumaTop.Memory.Span, @@ -67,8 +68,8 @@ namespace Ryujinx.Graphics.Nvdec.Image int chromaSize = GetBlockLinearSize(surface.UvWidth, surface.UvHeight / 2, 2); - using var chromaTop = mm.GetWritableRegion(ExtendOffset(chromaTopOffset), chromaSize); - using var chromaBottom = mm.GetWritableRegion(ExtendOffset(chromaBottomOffset), chromaSize); + using WritableRegion chromaTop = mm.GetWritableRegion(ExtendOffset(chromaTopOffset), chromaSize); + using WritableRegion chromaBottom = mm.GetWritableRegion(ExtendOffset(chromaBottomOffset), chromaSize); WriteChroma( chromaTop.Memory.Span, diff --git a/src/Ryujinx.Graphics.Nvdec/NvdecDevice.cs b/src/Ryujinx.Graphics.Nvdec/NvdecDevice.cs index 29e260d63..7a8fbf9b6 100644 --- a/src/Ryujinx.Graphics.Nvdec/NvdecDevice.cs +++ b/src/Ryujinx.Graphics.Nvdec/NvdecDevice.cs @@ -36,7 +36,7 @@ namespace Ryujinx.Graphics.Nvdec public void DestroyContext(long id) { - if (_contexts.TryRemove(id, out var context)) + if (_contexts.TryRemove(id, out NvdecDecoderContext context)) { context.Dispose(); } @@ -46,7 +46,7 @@ namespace Ryujinx.Graphics.Nvdec public void BindContext(long id) { - if (_contexts.TryGetValue(id, out var context)) + if (_contexts.TryGetValue(id, out NvdecDecoderContext context)) { _currentContext = context; } diff --git a/src/Ryujinx.Graphics.Nvdec/Vp9Decoder.cs b/src/Ryujinx.Graphics.Nvdec/Vp9Decoder.cs index 5ed508647..6c294adf6 100644 --- a/src/Ryujinx.Graphics.Nvdec/Vp9Decoder.cs +++ b/src/Ryujinx.Graphics.Nvdec/Vp9Decoder.cs @@ -4,6 +4,7 @@ using Ryujinx.Graphics.Nvdec.Image; using Ryujinx.Graphics.Nvdec.Types.Vp9; using Ryujinx.Graphics.Nvdec.Vp9; using Ryujinx.Graphics.Video; +using Ryujinx.Memory; using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -50,7 +51,7 @@ namespace Ryujinx.Graphics.Nvdec int miCols = BitUtils.DivRoundUp(pictureInfo.CurrentFrameSize.Width, 8); int miRows = BitUtils.DivRoundUp(pictureInfo.CurrentFrameSize.Height, 8); - using var mvsRegion = rm.MemoryManager.GetWritableRegion(ExtendOffset(state.Vp9SetColMvWriteBufOffset), miRows * miCols * 16); + using WritableRegion mvsRegion = rm.MemoryManager.GetWritableRegion(ExtendOffset(state.Vp9SetColMvWriteBufOffset), miRows * miCols * 16); Span mvsOut = MemoryMarshal.Cast(mvsRegion.Memory.Span); @@ -80,9 +81,9 @@ namespace Ryujinx.Graphics.Nvdec private static void WriteBackwardUpdates(DeviceMemoryManager mm, uint offset, ref Vp9BackwardUpdates counts) { - using var backwardUpdatesRegion = mm.GetWritableRegion(ExtendOffset(offset), Unsafe.SizeOf()); + using WritableRegion backwardUpdatesRegion = mm.GetWritableRegion(ExtendOffset(offset), Unsafe.SizeOf()); - ref var backwardUpdates = ref MemoryMarshal.Cast(backwardUpdatesRegion.Memory.Span)[0]; + ref BackwardUpdates backwardUpdates = ref MemoryMarshal.Cast(backwardUpdatesRegion.Memory.Span)[0]; backwardUpdates = new BackwardUpdates(ref counts); } From f2aa6b3a5bd3609d3d65bb7bb7709b848fcb554e Mon Sep 17 00:00:00 2001 From: Evan Husted Date: Sat, 25 Jan 2025 14:07:59 -0600 Subject: [PATCH 09/19] misc: chore: Use explicit types in Shader project --- .../CodeGen/Glsl/Declarations.cs | 18 +- .../CodeGen/Glsl/Instructions/InstGenCall.cs | 2 +- .../Glsl/Instructions/InstGenMemory.cs | 2 +- .../CodeGen/Msl/Declarations.cs | 62 ++-- .../CodeGen/Msl/Instructions/InstGen.cs | 4 +- .../Msl/Instructions/InstGenBarrier.cs | 2 +- .../CodeGen/Msl/Instructions/InstGenCall.cs | 2 +- .../CodeGen/Msl/Instructions/InstGenMemory.cs | 16 +- .../CodeGen/Msl/Instructions/IoMap.cs | 2 +- .../CodeGen/Msl/MslGenerator.cs | 10 +- .../CodeGen/Spirv/CodeGenContext.cs | 18 +- .../CodeGen/Spirv/Declarations.cs | 96 ++--- .../CodeGen/Spirv/Instructions.cs | 338 +++++++++--------- .../CodeGen/Spirv/SpirvGenerator.cs | 38 +- .../Decoders/Decoder.cs | 14 +- .../Instructions/AttributeMap.cs | 4 +- .../Instructions/InstEmitAttribute.cs | 2 +- .../Instructions/InstEmitBitfield.cs | 36 +- .../Instructions/InstEmitConversion.cs | 24 +- .../Instructions/InstEmitFloatArithmetic.cs | 172 ++++----- .../Instructions/InstEmitFloatComparison.cs | 98 ++--- .../Instructions/InstEmitFloatMinMax.cs | 36 +- .../Instructions/InstEmitFlowControl.cs | 12 +- .../Instructions/InstEmitIntegerArithmetic.cs | 146 ++++---- .../Instructions/InstEmitIntegerComparison.cs | 50 +-- .../Instructions/InstEmitIntegerLogical.cs | 34 +- .../Instructions/InstEmitIntegerMinMax.cs | 18 +- .../Instructions/InstEmitShift.cs | 36 +- .../Instructions/InstEmitTexture.cs | 12 +- src/Ryujinx.Graphics.Shader/SamplerType.cs | 2 +- .../StructuredIr/ShaderProperties.cs | 4 +- .../Translation/EmitterContext.cs | 5 +- .../Translation/FunctionMatch.cs | 32 +- .../Optimizations/GlobalToStorage.cs | 4 +- .../Translation/RegisterUsage.cs | 2 +- .../Translation/ResourceManager.cs | 38 +- .../Translation/ShaderDefinitions.cs | 8 +- .../Translation/Translator.cs | 4 +- .../Translation/TranslatorContext.cs | 48 +-- 39 files changed, 726 insertions(+), 725 deletions(-) diff --git a/src/Ryujinx.Graphics.Shader/CodeGen/Glsl/Declarations.cs b/src/Ryujinx.Graphics.Shader/CodeGen/Glsl/Declarations.cs index eb6c689b8..2677cba07 100644 --- a/src/Ryujinx.Graphics.Shader/CodeGen/Glsl/Declarations.cs +++ b/src/Ryujinx.Graphics.Shader/CodeGen/Glsl/Declarations.cs @@ -149,7 +149,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl if (context.Definitions.TransformFeedbackEnabled && context.Definitions.LastInVertexPipeline) { - var tfOutput = context.Definitions.GetTransformFeedbackOutput(AttributeConsts.PositionX); + TransformFeedbackOutput tfOutput = context.Definitions.GetTransformFeedbackOutput(AttributeConsts.PositionX); if (tfOutput.Valid) { context.AppendLine($"layout (xfb_buffer = {tfOutput.Buffer}, xfb_offset = {tfOutput.Offset}, xfb_stride = {tfOutput.Stride}) out gl_PerVertex"); @@ -338,7 +338,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl private static void DeclareSamplers(CodeGenContext context, IEnumerable definitions) { - foreach (var definition in definitions) + foreach (TextureDefinition definition in definitions) { string arrayDecl = string.Empty; @@ -366,7 +366,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl private static void DeclareImages(CodeGenContext context, IEnumerable definitions) { - foreach (var definition in definitions) + foreach (TextureDefinition definition in definitions) { string arrayDecl = string.Empty; @@ -413,7 +413,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl } else { - foreach (var ioDefinition in inputs.OrderBy(x => x.Location)) + foreach (IoDefinition ioDefinition in inputs.OrderBy(x => x.Location)) { DeclareInputAttribute(context, ioDefinition.Location, ioDefinition.Component); } @@ -427,7 +427,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl private static void DeclareInputAttributesPerPatch(CodeGenContext context, IEnumerable inputs) { - foreach (var ioDefinition in inputs.OrderBy(x => x.Location)) + foreach (IoDefinition ioDefinition in inputs.OrderBy(x => x.Location)) { DeclareInputAttributePerPatch(context, ioDefinition.Location); } @@ -521,7 +521,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl } } - foreach (var ioDefinition in outputs) + foreach (IoDefinition ioDefinition in outputs) { DeclareOutputAttribute(context, ioDefinition.Location, ioDefinition.Component); } @@ -548,7 +548,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl string xfb = string.Empty; - var tfOutput = context.Definitions.GetTransformFeedbackOutput(location, component); + TransformFeedbackOutput tfOutput = context.Definitions.GetTransformFeedbackOutput(location, component); if (tfOutput.Valid) { xfb = $", xfb_buffer = {tfOutput.Buffer}, xfb_offset = {tfOutput.Offset}, xfb_stride = {tfOutput.Stride}"; @@ -570,7 +570,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl string xfb = string.Empty; - var tfOutput = context.Definitions.GetTransformFeedbackOutput(location, 0); + TransformFeedbackOutput tfOutput = context.Definitions.GetTransformFeedbackOutput(location, 0); if (tfOutput.Valid) { xfb = $", xfb_buffer = {tfOutput.Buffer}, xfb_offset = {tfOutput.Offset}, xfb_stride = {tfOutput.Stride}"; @@ -606,7 +606,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl private static void DeclareOutputAttributesPerPatch(CodeGenContext context, IEnumerable outputs) { - foreach (var ioDefinition in outputs) + foreach (IoDefinition ioDefinition in outputs) { DeclareOutputAttributePerPatch(context, ioDefinition.Location); } diff --git a/src/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGenCall.cs b/src/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGenCall.cs index d5448856d..9d4ea5348 100644 --- a/src/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGenCall.cs +++ b/src/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGenCall.cs @@ -14,7 +14,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions Debug.Assert(funcId.Type == OperandType.Constant); - var function = context.GetFunction(funcId.Value); + StructuredFunction function = context.GetFunction(funcId.Value); string[] args = new string[operation.SourcesCount - 1]; diff --git a/src/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGenMemory.cs b/src/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGenMemory.cs index 56507a2a4..2eeaaa9bc 100644 --- a/src/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGenMemory.cs +++ b/src/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGenMemory.cs @@ -16,7 +16,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions bool isArray = (texOp.Type & SamplerType.Array) != 0; - var texCallBuilder = new StringBuilder(); + StringBuilder texCallBuilder = new StringBuilder(); if (texOp.Inst == Instruction.ImageAtomic) { diff --git a/src/Ryujinx.Graphics.Shader/CodeGen/Msl/Declarations.cs b/src/Ryujinx.Graphics.Shader/CodeGen/Msl/Declarations.cs index 912b162d2..c779f5e8d 100644 --- a/src/Ryujinx.Graphics.Shader/CodeGen/Msl/Declarations.cs +++ b/src/Ryujinx.Graphics.Shader/CodeGen/Msl/Declarations.cs @@ -69,7 +69,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl context.AppendLine("using namespace metal;"); context.AppendLine(); - var fsi = (info.HelperFunctionsMask & HelperFunctionsMask.FSI) != 0; + bool fsi = (info.HelperFunctionsMask & HelperFunctionsMask.FSI) != 0; DeclareInputAttributes(context, info.IoDefinitions.Where(x => IsUserDefined(x, StorageKind.Input))); context.AppendLine(); @@ -79,25 +79,25 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl DeclareBufferStructures(context, context.Properties.StorageBuffers.Values.OrderBy(x => x.Binding).ToArray(), false, fsi); // We need to declare each set as a new struct - var textureDefinitions = context.Properties.Textures.Values + Dictionary textureDefinitions = context.Properties.Textures.Values .GroupBy(x => x.Set) .ToDictionary(x => x.Key, x => x.OrderBy(y => y.Binding).ToArray()); - var imageDefinitions = context.Properties.Images.Values + Dictionary imageDefinitions = context.Properties.Images.Values .GroupBy(x => x.Set) .ToDictionary(x => x.Key, x => x.OrderBy(y => y.Binding).ToArray()); - var textureSets = textureDefinitions.Keys.ToArray(); - var imageSets = imageDefinitions.Keys.ToArray(); + int[] textureSets = textureDefinitions.Keys.ToArray(); + int[] imageSets = imageDefinitions.Keys.ToArray(); - var sets = textureSets.Union(imageSets).ToArray(); + int[] sets = textureSets.Union(imageSets).ToArray(); - foreach (var set in textureDefinitions) + foreach (KeyValuePair set in textureDefinitions) { DeclareTextures(context, set.Value, set.Key); } - foreach (var set in imageDefinitions) + foreach (KeyValuePair set in imageDefinitions) { DeclareImages(context, set.Value, set.Key, fsi); } @@ -186,8 +186,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl public static string GetVarTypeName(AggregateType type, bool atomic = false) { - var s32 = atomic ? "atomic_int" : "int"; - var u32 = atomic ? "atomic_uint" : "uint"; + string s32 = atomic ? "atomic_int" : "int"; + string u32 = atomic ? "atomic_uint" : "uint"; return type switch { @@ -216,22 +216,22 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl { string prefix = isShared ? "threadgroup " : string.Empty; - foreach (var memory in memories) + foreach (MemoryDefinition memory in memories) { string arraySize = ""; if ((memory.Type & AggregateType.Array) != 0) { arraySize = $"[{memory.ArrayLength}]"; } - var typeName = GetVarTypeName(memory.Type & ~AggregateType.Array); + string typeName = GetVarTypeName(memory.Type & ~AggregateType.Array); context.AppendLine($"{prefix}{typeName} {memory.Name}{arraySize};"); } } private static void DeclareBufferStructures(CodeGenContext context, BufferDefinition[] buffers, bool constant, bool fsi) { - var name = constant ? "ConstantBuffers" : "StorageBuffers"; - var addressSpace = constant ? "constant" : "device"; + string name = constant ? "ConstantBuffers" : "StorageBuffers"; + string addressSpace = constant ? "constant" : "device"; string[] bufferDec = new string[buffers.Length]; @@ -239,7 +239,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl { BufferDefinition buffer = buffers[i]; - var needsPadding = buffer.Layout == BufferLayout.Std140; + bool needsPadding = buffer.Layout == BufferLayout.Std140; string fsiSuffix = !constant && fsi ? " [[raster_order_group(0)]]" : ""; bufferDec[i] = $"{addressSpace} {Defaults.StructPrefix}_{buffer.Name}* {buffer.Name}{fsiSuffix};"; @@ -249,7 +249,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl foreach (StructureField field in buffer.Type.Fields) { - var type = field.Type; + AggregateType type = field.Type; type |= (needsPadding && (field.Type & AggregateType.Array) != 0) ? AggregateType.Vector4 : AggregateType.Invalid; @@ -282,7 +282,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl context.AppendLine($"struct {name}"); context.EnterScope(); - foreach (var declaration in bufferDec) + foreach (string declaration in bufferDec) { context.AppendLine(declaration); } @@ -293,7 +293,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl private static void DeclareTextures(CodeGenContext context, TextureDefinition[] textures, int set) { - var setName = GetNameForSet(set); + string setName = GetNameForSet(set); context.AppendLine($"struct {setName}"); context.EnterScope(); @@ -303,7 +303,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl { if (texture.Type != SamplerType.None) { - var textureTypeName = texture.Type.ToMslTextureType(texture.Format.GetComponentType()); + string textureTypeName = texture.Type.ToMslTextureType(texture.Format.GetComponentType()); if (texture.ArrayLength > 1) { @@ -315,7 +315,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl if (!texture.Separate && texture.Type != SamplerType.TextureBuffer) { - var samplerType = "sampler"; + string samplerType = "sampler"; if (texture.ArrayLength > 1) { @@ -326,7 +326,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl } } - foreach (var declaration in textureDec) + foreach (string declaration in textureDec) { context.AppendLine(declaration); } @@ -337,7 +337,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl private static void DeclareImages(CodeGenContext context, TextureDefinition[] images, int set, bool fsi) { - var setName = GetNameForSet(set); + string setName = GetNameForSet(set); context.AppendLine($"struct {setName}"); context.EnterScope(); @@ -347,7 +347,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl { TextureDefinition image = images[i]; - var imageTypeName = image.Type.ToMslTextureType(image.Format.GetComponentType(), true); + string imageTypeName = image.Type.ToMslTextureType(image.Format.GetComponentType(), true); if (image.ArrayLength > 1) { imageTypeName = $"array<{imageTypeName}, {image.ArrayLength}>"; @@ -358,7 +358,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl imageDec[i] = $"{imageTypeName} {image.Name}{fsiSuffix};"; } - foreach (var declaration in imageDec) + foreach (string declaration in imageDec) { context.AppendLine(declaration); } @@ -401,14 +401,14 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl // We need to use the SPIRV-Cross workaround for (int i = 0; i < Constants.MaxAttributes; i++) { - var suffix = context.Definitions.Stage == ShaderStage.Fragment ? $"[[user(loc{i})]]" : $"[[attribute({i})]]"; + string suffix = context.Definitions.Stage == ShaderStage.Fragment ? $"[[user(loc{i})]]" : $"[[attribute({i})]]"; context.AppendLine($"float4 {Defaults.IAttributePrefix}{i} {suffix};"); } } if (inputs.Any()) { - foreach (var ioDefinition in inputs.OrderBy(x => x.Location)) + foreach (IoDefinition ioDefinition in inputs.OrderBy(x => x.Location)) { if (context.Definitions.IaIndexing && ioDefinition.IoVariable == IoVariable.UserDefined) { @@ -500,11 +500,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl IoDefinition firstOutput = outputs.ElementAtOrDefault(0); IoDefinition secondOutput = outputs.ElementAtOrDefault(1); - var type1 = GetVarTypeName(context.Definitions.GetFragmentOutputColorType(firstOutput.Location)); - var type2 = GetVarTypeName(context.Definitions.GetFragmentOutputColorType(secondOutput.Location)); + string type1 = GetVarTypeName(context.Definitions.GetFragmentOutputColorType(firstOutput.Location)); + string type2 = GetVarTypeName(context.Definitions.GetFragmentOutputColorType(secondOutput.Location)); - var name1 = $"color{firstOutput.Location}"; - var name2 = $"color{firstOutput.Location + 1}"; + string name1 = $"color{firstOutput.Location}"; + string name2 = $"color{firstOutput.Location + 1}"; context.AppendLine($"{type1} {name1} [[color({firstOutput.Location}), index(0)]];"); context.AppendLine($"{type2} {name2} [[color({firstOutput.Location}), index(1)]];"); @@ -512,7 +512,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl outputs = outputs.Skip(2); } - foreach (var ioDefinition in outputs) + foreach (IoDefinition ioDefinition in outputs) { if (context.Definitions.OaIndexing && ioDefinition.IoVariable == IoVariable.UserDefined) { diff --git a/src/Ryujinx.Graphics.Shader/CodeGen/Msl/Instructions/InstGen.cs b/src/Ryujinx.Graphics.Shader/CodeGen/Msl/Instructions/InstGen.cs index 57177e402..0be6035b6 100644 --- a/src/Ryujinx.Graphics.Shader/CodeGen/Msl/Instructions/InstGen.cs +++ b/src/Ryujinx.Graphics.Shader/CodeGen/Msl/Instructions/InstGen.cs @@ -49,7 +49,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl.Instructions ? AggregateType.S32 : AggregateType.U32; - var shared = operation.StorageKind == StorageKind.SharedMemory; + bool shared = operation.StorageKind == StorageKind.SharedMemory; builder.Append($"({(shared ? "threadgroup" : "device")} {Declarations.GetVarTypeName(dstType, true)}*)&{GenerateLoadOrStore(context, operation, isStore: false)}"); @@ -120,7 +120,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl.Instructions case 2: if (operation.ForcePrecise) { - var func = (inst & Instruction.Mask) switch + string func = (inst & Instruction.Mask) switch { Instruction.Add => "PreciseFAdd", Instruction.Subtract => "PreciseFSub", diff --git a/src/Ryujinx.Graphics.Shader/CodeGen/Msl/Instructions/InstGenBarrier.cs b/src/Ryujinx.Graphics.Shader/CodeGen/Msl/Instructions/InstGenBarrier.cs index 77f05defc..198b701d6 100644 --- a/src/Ryujinx.Graphics.Shader/CodeGen/Msl/Instructions/InstGenBarrier.cs +++ b/src/Ryujinx.Graphics.Shader/CodeGen/Msl/Instructions/InstGenBarrier.cs @@ -7,7 +7,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl.Instructions { public static string Barrier(CodeGenContext context, AstOperation operation) { - var device = (operation.Inst & Instruction.Mask) == Instruction.MemoryBarrier; + bool device = (operation.Inst & Instruction.Mask) == Instruction.MemoryBarrier; return $"threadgroup_barrier(mem_flags::mem_{(device ? "device" : "threadgroup")})"; } diff --git a/src/Ryujinx.Graphics.Shader/CodeGen/Msl/Instructions/InstGenCall.cs b/src/Ryujinx.Graphics.Shader/CodeGen/Msl/Instructions/InstGenCall.cs index 44881deee..98a8a140e 100644 --- a/src/Ryujinx.Graphics.Shader/CodeGen/Msl/Instructions/InstGenCall.cs +++ b/src/Ryujinx.Graphics.Shader/CodeGen/Msl/Instructions/InstGenCall.cs @@ -10,7 +10,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl.Instructions { AstOperand funcId = (AstOperand)operation.GetSource(0); - var function = context.GetFunction(funcId.Value); + StructuredFunction function = context.GetFunction(funcId.Value); int argCount = operation.SourcesCount - 1; int additionalArgCount = CodeGenContext.AdditionalArgCount + (context.Definitions.Stage != ShaderStage.Compute ? 1 : 0); diff --git a/src/Ryujinx.Graphics.Shader/CodeGen/Msl/Instructions/InstGenMemory.cs b/src/Ryujinx.Graphics.Shader/CodeGen/Msl/Instructions/InstGenMemory.cs index 6ccacc1c4..2cdee1478 100644 --- a/src/Ryujinx.Graphics.Shader/CodeGen/Msl/Instructions/InstGenMemory.cs +++ b/src/Ryujinx.Graphics.Shader/CodeGen/Msl/Instructions/InstGenMemory.cs @@ -157,7 +157,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl.Instructions bool isArray = (texOp.Type & SamplerType.Array) != 0; - var texCallBuilder = new StringBuilder(); + StringBuilder texCallBuilder = new StringBuilder(); int srcIndex = 0; @@ -194,7 +194,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl.Instructions texCallBuilder.Append('('); - var coordsBuilder = new StringBuilder(); + StringBuilder coordsBuilder = new StringBuilder(); int coordsCount = texOp.Type.GetDimensions(); @@ -326,8 +326,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl.Instructions coordsExpr = GetSourceExpr(context, texOp.GetSource(coordsIndex), AggregateType.FP32); } - var clamped = $"{textureName}.calculate_clamped_lod({samplerName}, {coordsExpr})"; - var unclamped = $"{textureName}.calculate_unclamped_lod({samplerName}, {coordsExpr})"; + string clamped = $"{textureName}.calculate_clamped_lod({samplerName}, {coordsExpr})"; + string unclamped = $"{textureName}.calculate_unclamped_lod({samplerName}, {coordsExpr})"; return $"float2({clamped}, {unclamped}){GetMask(texOp.Index)}"; } @@ -352,7 +352,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl.Instructions bool isArray = (texOp.Type & SamplerType.Array) != 0; bool isShadow = (texOp.Type & SamplerType.Shadow) != 0; - var texCallBuilder = new StringBuilder(); + StringBuilder texCallBuilder = new StringBuilder(); bool colorIsVector = isGather || !isShadow; @@ -525,8 +525,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl.Instructions private static string GetSamplerName(CodeGenContext context, AstTextureOperation texOp, ref int srcIndex) { - var index = texOp.IsSeparate ? texOp.GetSamplerSetAndBinding() : texOp.GetTextureSetAndBinding(); - var sourceIndex = texOp.IsSeparate ? srcIndex++ : srcIndex + 1; + SetBindingPair index = texOp.IsSeparate ? texOp.GetSamplerSetAndBinding() : texOp.GetTextureSetAndBinding(); + int sourceIndex = texOp.IsSeparate ? srcIndex++ : srcIndex + 1; TextureDefinition samplerDefinition = context.Properties.Textures[index]; string name = samplerDefinition.Name; @@ -589,7 +589,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl.Instructions { AstTextureOperation texOp = (AstTextureOperation)operation; - var texCallBuilder = new StringBuilder(); + StringBuilder texCallBuilder = new StringBuilder(); int srcIndex = 0; diff --git a/src/Ryujinx.Graphics.Shader/CodeGen/Msl/Instructions/IoMap.cs b/src/Ryujinx.Graphics.Shader/CodeGen/Msl/Instructions/IoMap.cs index e02d0a61f..118612c66 100644 --- a/src/Ryujinx.Graphics.Shader/CodeGen/Msl/Instructions/IoMap.cs +++ b/src/Ryujinx.Graphics.Shader/CodeGen/Msl/Instructions/IoMap.cs @@ -15,7 +15,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl.Instructions bool isOutput, bool isPerPatch) { - var returnValue = ioVariable switch + (string, AggregateType) returnValue = ioVariable switch { IoVariable.BaseInstance => ("base_instance", AggregateType.U32), IoVariable.BaseVertex => ("base_vertex", AggregateType.U32), diff --git a/src/Ryujinx.Graphics.Shader/CodeGen/Msl/MslGenerator.cs b/src/Ryujinx.Graphics.Shader/CodeGen/Msl/MslGenerator.cs index 7de6ee5dd..ddb013c05 100644 --- a/src/Ryujinx.Graphics.Shader/CodeGen/Msl/MslGenerator.cs +++ b/src/Ryujinx.Graphics.Shader/CodeGen/Msl/MslGenerator.cs @@ -20,7 +20,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl CodeGenContext context = new(info, parameters); - var sets = Declarations.Declare(context, info); + int[] sets = Declarations.Declare(context, info); if (info.Functions.Count != 0) { @@ -168,15 +168,15 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Msl args = args.Append($"constant ConstantBuffers &constant_buffers [[buffer({Defaults.ConstantBuffersIndex})]]").ToArray(); args = args.Append($"device StorageBuffers &storage_buffers [[buffer({Defaults.StorageBuffersIndex})]]").ToArray(); - foreach (var set in sets) + foreach (int set in sets) { - var bindingIndex = set + Defaults.BaseSetIndex; + long bindingIndex = set + Defaults.BaseSetIndex; args = args.Append($"constant {Declarations.GetNameForSet(set)} &{Declarations.GetNameForSet(set, true)} [[buffer({bindingIndex})]]").ToArray(); } } - var funcPrefix = $"{funcKeyword} {returnType} {funcName ?? function.Name}("; - var indent = new string(' ', funcPrefix.Length); + string funcPrefix = $"{funcKeyword} {returnType} {funcName ?? function.Name}("; + string indent = new string(' ', funcPrefix.Length); return $"{funcPrefix}{string.Join($", \n{indent}", args)})"; } diff --git a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/CodeGenContext.cs b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/CodeGenContext.cs index cc7977f84..d573fe39a 100644 --- a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/CodeGenContext.cs +++ b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/CodeGenContext.cs @@ -127,7 +127,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private BlockState GetBlockStateLazy(AstBlock block) { - if (!_labels.TryGetValue(block, out var blockState)) + if (!_labels.TryGetValue(block, out BlockState blockState)) { blockState = new BlockState(); @@ -139,7 +139,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv public Instruction NewBlock() { - var label = Label(); + Instruction label = Label(); Branch(label); AddLabel(label); return label; @@ -147,7 +147,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv public Instruction[] GetMainInterface() { - var mainInterface = new List(); + List mainInterface = new List(); mainInterface.AddRange(Inputs.Values); mainInterface.AddRange(Outputs.Values); @@ -196,7 +196,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv { if (node is AstOperation operation) { - var opResult = Instructions.Generate(this, operation); + OperationResult opResult = Instructions.Generate(this, operation); return BitcastIfNeeded(type, opResult.Type, opResult.Value); } else if (node is AstOperand operand) @@ -218,7 +218,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv { if (node is AstOperation operation) { - var opResult = Instructions.Generate(this, operation); + OperationResult opResult = Instructions.Generate(this, operation); type = opResult.Type; return opResult.Value; } @@ -273,13 +273,13 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv public Instruction GetLocal(AggregateType dstType, AstOperand local) { - var srcType = local.VarType; + AggregateType srcType = local.VarType; return BitcastIfNeeded(dstType, srcType, Load(GetType(srcType), GetLocalPointer(local))); } public Instruction GetArgument(AggregateType dstType, AstOperand funcArg) { - var srcType = funcArg.VarType; + AggregateType srcType = funcArg.VarType; return BitcastIfNeeded(dstType, srcType, Load(GetType(srcType), GetArgumentPointer(funcArg))); } @@ -339,8 +339,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } else if (srcType == AggregateType.Bool) { - var intTrue = Constant(TypeS32(), IrConsts.True); - var intFalse = Constant(TypeS32(), IrConsts.False); + Instruction intTrue = Constant(TypeS32(), IrConsts.True); + Instruction intFalse = Constant(TypeS32(), IrConsts.False); return BitcastIfNeeded(dstType, AggregateType.S32, Select(TypeS32(), value, intTrue, intFalse)); } diff --git a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Declarations.cs b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Declarations.cs index 55d35bf0d..0b2ad41fb 100644 --- a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Declarations.cs +++ b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Declarations.cs @@ -20,10 +20,10 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static void DeclareParameters(CodeGenContext context, IEnumerable argTypes, int argIndex) { - foreach (var argType in argTypes) + foreach (AggregateType argType in argTypes) { - var argPointerType = context.TypePointer(StorageClass.Function, context.GetType(argType)); - var spvArg = context.FunctionParameter(argPointerType); + SpvInstruction argPointerType = context.TypePointer(StorageClass.Function, context.GetType(argType)); + SpvInstruction spvArg = context.FunctionParameter(argPointerType); context.DeclareArgument(argIndex++, spvArg); } @@ -33,8 +33,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv { foreach (AstOperand local in function.Locals) { - var localPointerType = context.TypePointer(StorageClass.Function, context.GetType(local.VarType)); - var spvLocal = context.Variable(localPointerType, StorageClass.Function); + SpvInstruction localPointerType = context.TypePointer(StorageClass.Function, context.GetType(local.VarType)); + SpvInstruction spvLocal = context.Variable(localPointerType, StorageClass.Function); context.AddLocalVariable(spvLocal); context.DeclareLocal(local, spvLocal); @@ -60,8 +60,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv { foreach ((int id, MemoryDefinition memory) in memories) { - var pointerType = context.TypePointer(storage, context.GetType(memory.Type, memory.ArrayLength)); - var variable = context.Variable(pointerType, storage); + SpvInstruction pointerType = context.TypePointer(storage, context.GetType(memory.Type, memory.ArrayLength)); + SpvInstruction variable = context.Variable(pointerType, storage); context.AddGlobalVariable(variable); @@ -123,7 +123,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } } - var structType = context.TypeStruct(false, structFieldTypes); + SpvInstruction structType = context.TypeStruct(false, structFieldTypes); if (decoratedTypes.Add(structType)) { @@ -135,8 +135,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } } - var pointerType = context.TypePointer(StorageClass.Uniform, structType); - var variable = context.Variable(pointerType, StorageClass.Uniform); + SpvInstruction pointerType = context.TypePointer(StorageClass.Uniform, structType); + SpvInstruction variable = context.Variable(pointerType, StorageClass.Uniform); context.Name(variable, buffer.Name); context.Decorate(variable, Decoration.DescriptorSet, (LiteralInteger)setIndex); @@ -156,7 +156,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static void DeclareSamplers(CodeGenContext context, IEnumerable samplers) { - foreach (var sampler in samplers) + foreach (TextureDefinition sampler in samplers) { int setIndex = context.TargetApi == TargetApi.Vulkan ? sampler.Set : 0; @@ -165,7 +165,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv if (sampler.Type != SamplerType.None) { - var dim = (sampler.Type & SamplerType.Mask) switch + Dim dim = (sampler.Type & SamplerType.Mask) switch { SamplerType.Texture1D => Dim.Dim1D, SamplerType.Texture2D => Dim.Dim2D, @@ -191,22 +191,22 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv imageType = sampledImageType = context.TypeSampler(); } - var sampledOrSeparateImageType = sampler.Separate ? imageType : sampledImageType; - var sampledImagePointerType = context.TypePointer(StorageClass.UniformConstant, sampledOrSeparateImageType); - var sampledImageArrayPointerType = sampledImagePointerType; + SpvInstruction sampledOrSeparateImageType = sampler.Separate ? imageType : sampledImageType; + SpvInstruction sampledImagePointerType = context.TypePointer(StorageClass.UniformConstant, sampledOrSeparateImageType); + SpvInstruction sampledImageArrayPointerType = sampledImagePointerType; if (sampler.ArrayLength == 0) { - var sampledImageArrayType = context.TypeRuntimeArray(sampledOrSeparateImageType); + SpvInstruction sampledImageArrayType = context.TypeRuntimeArray(sampledOrSeparateImageType); sampledImageArrayPointerType = context.TypePointer(StorageClass.UniformConstant, sampledImageArrayType); } else if (sampler.ArrayLength != 1) { - var sampledImageArrayType = context.TypeArray(sampledOrSeparateImageType, context.Constant(context.TypeU32(), sampler.ArrayLength)); + SpvInstruction sampledImageArrayType = context.TypeArray(sampledOrSeparateImageType, context.Constant(context.TypeU32(), sampler.ArrayLength)); sampledImageArrayPointerType = context.TypePointer(StorageClass.UniformConstant, sampledImageArrayType); } - var sampledImageVariable = context.Variable(sampledImageArrayPointerType, StorageClass.UniformConstant); + SpvInstruction sampledImageVariable = context.Variable(sampledImageArrayPointerType, StorageClass.UniformConstant); context.Samplers.Add(new(sampler.Set, sampler.Binding), new SamplerDeclaration( imageType, @@ -225,13 +225,13 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static void DeclareImages(CodeGenContext context, IEnumerable images) { - foreach (var image in images) + foreach (TextureDefinition image in images) { int setIndex = context.TargetApi == TargetApi.Vulkan ? image.Set : 0; - var dim = GetDim(image.Type); + Dim dim = GetDim(image.Type); - var imageType = context.TypeImage( + SpvInstruction imageType = context.TypeImage( context.GetType(image.Format.GetComponentType()), dim, image.Type.HasFlag(SamplerType.Shadow), @@ -240,21 +240,21 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv AccessQualifier.ReadWrite, GetImageFormat(image.Format)); - var imagePointerType = context.TypePointer(StorageClass.UniformConstant, imageType); - var imageArrayPointerType = imagePointerType; + SpvInstruction imagePointerType = context.TypePointer(StorageClass.UniformConstant, imageType); + SpvInstruction imageArrayPointerType = imagePointerType; if (image.ArrayLength == 0) { - var imageArrayType = context.TypeRuntimeArray(imageType); + SpvInstruction imageArrayType = context.TypeRuntimeArray(imageType); imageArrayPointerType = context.TypePointer(StorageClass.UniformConstant, imageArrayType); } else if (image.ArrayLength != 1) { - var imageArrayType = context.TypeArray(imageType, context.Constant(context.TypeU32(), image.ArrayLength)); + SpvInstruction imageArrayType = context.TypeArray(imageType, context.Constant(context.TypeU32(), image.ArrayLength)); imageArrayPointerType = context.TypePointer(StorageClass.UniformConstant, imageArrayType); } - var imageVariable = context.Variable(imageArrayPointerType, StorageClass.UniformConstant); + SpvInstruction imageVariable = context.Variable(imageArrayPointerType, StorageClass.UniformConstant); context.Images.Add(new(image.Set, image.Binding), new ImageDeclaration(imageType, imagePointerType, imageVariable, image.ArrayLength != 1)); @@ -338,7 +338,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv if (context.Definitions.Stage == ShaderStage.Fragment && context.Definitions.DualSourceBlend) { - foreach (var ioDefinition in info.IoDefinitions) + foreach (IoDefinition ioDefinition in info.IoDefinitions) { if (ioDefinition.IoVariable == IoVariable.FragmentOutputColor && ioDefinition.Location < firstLocation) { @@ -347,13 +347,13 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } } - foreach (var ioDefinition in info.IoDefinitions) + foreach (IoDefinition ioDefinition in info.IoDefinitions) { PixelImap iq = PixelImap.Unused; if (context.Definitions.Stage == ShaderStage.Fragment) { - var ioVariable = ioDefinition.IoVariable; + IoVariable ioVariable = ioDefinition.IoVariable; if (ioVariable == IoVariable.UserDefined) { iq = context.Definitions.ImapTypes[ioDefinition.Location].GetFirstUsedType(); @@ -389,11 +389,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv { if (context.Definitions.Stage != ShaderStage.Vertex) { - var perVertexInputStructType = CreatePerVertexStructType(context); + SpvInstruction perVertexInputStructType = CreatePerVertexStructType(context); int arraySize = context.Definitions.Stage == ShaderStage.Geometry ? context.Definitions.InputTopology.ToInputVertices() : 32; - var perVertexInputArrayType = context.TypeArray(perVertexInputStructType, context.Constant(context.TypeU32(), arraySize)); - var perVertexInputPointerType = context.TypePointer(StorageClass.Input, perVertexInputArrayType); - var perVertexInputVariable = context.Variable(perVertexInputPointerType, StorageClass.Input); + SpvInstruction perVertexInputArrayType = context.TypeArray(perVertexInputStructType, context.Constant(context.TypeU32(), arraySize)); + SpvInstruction perVertexInputPointerType = context.TypePointer(StorageClass.Input, perVertexInputArrayType); + SpvInstruction perVertexInputVariable = context.Variable(perVertexInputPointerType, StorageClass.Input); context.Name(perVertexInputVariable, "gl_in"); @@ -411,11 +411,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } } - var perVertexOutputStructType = CreatePerVertexStructType(context); + SpvInstruction perVertexOutputStructType = CreatePerVertexStructType(context); void DecorateTfo(IoVariable ioVariable, int fieldIndex) { - if (context.Definitions.TryGetTransformFeedbackOutput(ioVariable, 0, 0, out var transformFeedbackOutput)) + if (context.Definitions.TryGetTransformFeedbackOutput(ioVariable, 0, 0, out TransformFeedbackOutput transformFeedbackOutput)) { context.MemberDecorate(perVertexOutputStructType, fieldIndex, Decoration.XfbBuffer, (LiteralInteger)transformFeedbackOutput.Buffer); context.MemberDecorate(perVertexOutputStructType, fieldIndex, Decoration.XfbStride, (LiteralInteger)transformFeedbackOutput.Stride); @@ -439,8 +439,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv perVertexOutputArrayType = perVertexOutputStructType; } - var perVertexOutputPointerType = context.TypePointer(StorageClass.Output, perVertexOutputArrayType); - var perVertexOutputVariable = context.Variable(perVertexOutputPointerType, StorageClass.Output); + SpvInstruction perVertexOutputPointerType = context.TypePointer(StorageClass.Output, perVertexOutputArrayType); + SpvInstruction perVertexOutputVariable = context.Variable(perVertexOutputPointerType, StorageClass.Output); context.AddGlobalVariable(perVertexOutputVariable); context.Outputs.Add(new IoDefinition(StorageKind.Output, IoVariable.Position), perVertexOutputVariable); @@ -449,12 +449,12 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static SpvInstruction CreatePerVertexStructType(CodeGenContext context) { - var vec4FloatType = context.TypeVector(context.TypeFP32(), 4); - var floatType = context.TypeFP32(); - var array8FloatType = context.TypeArray(context.TypeFP32(), context.Constant(context.TypeU32(), 8)); - var array1FloatType = context.TypeArray(context.TypeFP32(), context.Constant(context.TypeU32(), 1)); + SpvInstruction vec4FloatType = context.TypeVector(context.TypeFP32(), 4); + SpvInstruction floatType = context.TypeFP32(); + SpvInstruction array8FloatType = context.TypeArray(context.TypeFP32(), context.Constant(context.TypeU32(), 8)); + SpvInstruction array1FloatType = context.TypeArray(context.TypeFP32(), context.Constant(context.TypeU32(), 1)); - var perVertexStructType = context.TypeStruct(true, vec4FloatType, floatType, array8FloatType, array1FloatType); + SpvInstruction perVertexStructType = context.TypeStruct(true, vec4FloatType, floatType, array8FloatType, array1FloatType); context.Name(perVertexStructType, "gl_PerVertex"); @@ -487,7 +487,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv int firstLocation = 0) { IoVariable ioVariable = ioDefinition.IoVariable; - var storageClass = isOutput ? StorageClass.Output : StorageClass.Input; + StorageClass storageClass = isOutput ? StorageClass.Output : StorageClass.Input; bool isBuiltIn; BuiltIn builtIn = default; @@ -532,7 +532,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv }; } - var spvType = context.GetType(varType, IoMap.GetSpirvBuiltInArrayLength(ioVariable)); + SpvInstruction spvType = context.GetType(varType, IoMap.GetSpirvBuiltInArrayLength(ioVariable)); bool builtInPassthrough = false; if (!isPerPatch && IoMap.IsPerVertex(ioVariable, context.Definitions.Stage, isOutput)) @@ -551,8 +551,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv spvType = context.TypeArray(spvType, context.Constant(context.TypeU32(), context.Definitions.ThreadsPerInputPrimitive)); } - var spvPointerType = context.TypePointer(storageClass, spvType); - var spvVar = context.Variable(spvPointerType, storageClass); + SpvInstruction spvPointerType = context.TypePointer(storageClass, spvType); + SpvInstruction spvVar = context.Variable(spvPointerType, storageClass); if (builtInPassthrough) { @@ -641,7 +641,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv ioVariable, ioDefinition.Location, ioDefinition.Component, - out var transformFeedbackOutput)) + out TransformFeedbackOutput transformFeedbackOutput)) { context.Decorate(spvVar, Decoration.XfbBuffer, (LiteralInteger)transformFeedbackOutput.Buffer); context.Decorate(spvVar, Decoration.XfbStride, (LiteralInteger)transformFeedbackOutput.Stride); @@ -650,7 +650,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv context.AddGlobalVariable(spvVar); - var dict = isPerPatch + Dictionary dict = isPerPatch ? (isOutput ? context.OutputsPerPatch : context.InputsPerPatch) : (isOutput ? context.Outputs : context.Inputs); dict.Add(ioDefinition, spvVar); diff --git a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Instructions.cs b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Instructions.cs index 6206985d8..7796bccbe 100644 --- a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Instructions.cs +++ b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Instructions.cs @@ -153,7 +153,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv public static OperationResult Generate(CodeGenContext context, AstOperation operation) { - var handler = _instTable[(int)(operation.Inst & Instruction.Mask)]; + Func handler = _instTable[(int)(operation.Inst & Instruction.Mask)]; if (handler != null) { return handler(context, operation); @@ -226,13 +226,13 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static OperationResult GenerateBallot(CodeGenContext context, AstOperation operation) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); - var uvec4Type = context.TypeVector(context.TypeU32(), 4); - var execution = context.Constant(context.TypeU32(), Scope.Subgroup); + SpvInstruction uvec4Type = context.TypeVector(context.TypeU32(), 4); + SpvInstruction execution = context.Constant(context.TypeU32(), Scope.Subgroup); - var maskVector = context.GroupNonUniformBallot(uvec4Type, execution, context.Get(AggregateType.Bool, source)); - var mask = context.CompositeExtract(context.TypeU32(), maskVector, (SpvLiteralInteger)operation.Index); + SpvInstruction maskVector = context.GroupNonUniformBallot(uvec4Type, execution, context.Get(AggregateType.Bool, source)); + SpvInstruction mask = context.CompositeExtract(context.TypeU32(), maskVector, (SpvLiteralInteger)operation.Index); return new OperationResult(AggregateType.U32, mask); } @@ -308,21 +308,21 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv Debug.Assert(funcId.Type == OperandType.Constant); - var (function, spvFunc) = context.GetFunction(funcId.Value); + (StructuredFunction function, SpvInstruction spvFunc) = context.GetFunction(funcId.Value); - var args = new SpvInstruction[operation.SourcesCount - 1]; + SpvInstruction[] args = new SpvInstruction[operation.SourcesCount - 1]; for (int i = 0; i < args.Length; i++) { - var operand = operation.GetSource(i + 1); + IAstNode operand = operation.GetSource(i + 1); AstOperand local = (AstOperand)operand; Debug.Assert(local.Type == OperandType.LocalVariable); args[i] = context.GetLocalPointer(local); } - var retType = function.ReturnType; - var result = context.FunctionCall(context.GetType(retType), spvFunc, args); + AggregateType retType = function.ReturnType; + SpvInstruction result = context.FunctionCall(context.GetType(retType), spvFunc, args); return new OperationResult(retType, result); } @@ -398,11 +398,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static OperationResult GenerateConditionalSelect(CodeGenContext context, AstOperation operation) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); - var src3 = operation.GetSource(2); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); + IAstNode src3 = operation.GetSource(2); - var cond = context.Get(AggregateType.Bool, src1); + SpvInstruction cond = context.Get(AggregateType.Bool, src1); if (operation.Inst.HasFlag(Instruction.FP64)) { @@ -420,70 +420,70 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static OperationResult GenerateConvertFP32ToFP64(CodeGenContext context, AstOperation operation) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.FP64, context.FConvert(context.TypeFP64(), context.GetFP32(source))); } private static OperationResult GenerateConvertFP32ToS32(CodeGenContext context, AstOperation operation) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.S32, context.ConvertFToS(context.TypeS32(), context.GetFP32(source))); } private static OperationResult GenerateConvertFP32ToU32(CodeGenContext context, AstOperation operation) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.U32, context.ConvertFToU(context.TypeU32(), context.GetFP32(source))); } private static OperationResult GenerateConvertFP64ToFP32(CodeGenContext context, AstOperation operation) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.FP32, context.FConvert(context.TypeFP32(), context.GetFP64(source))); } private static OperationResult GenerateConvertFP64ToS32(CodeGenContext context, AstOperation operation) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.S32, context.ConvertFToS(context.TypeS32(), context.GetFP64(source))); } private static OperationResult GenerateConvertFP64ToU32(CodeGenContext context, AstOperation operation) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.U32, context.ConvertFToU(context.TypeU32(), context.GetFP64(source))); } private static OperationResult GenerateConvertS32ToFP32(CodeGenContext context, AstOperation operation) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.FP32, context.ConvertSToF(context.TypeFP32(), context.GetS32(source))); } private static OperationResult GenerateConvertS32ToFP64(CodeGenContext context, AstOperation operation) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.FP64, context.ConvertSToF(context.TypeFP64(), context.GetS32(source))); } private static OperationResult GenerateConvertU32ToFP32(CodeGenContext context, AstOperation operation) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.FP32, context.ConvertUToF(context.TypeFP32(), context.GetU32(source))); } private static OperationResult GenerateConvertU32ToFP64(CodeGenContext context, AstOperation operation) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.FP64, context.ConvertUToF(context.TypeFP64(), context.GetU32(source))); } @@ -555,19 +555,19 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static OperationResult GenerateFindLSB(CodeGenContext context, AstOperation operation) { - var source = context.GetU32(operation.GetSource(0)); + SpvInstruction source = context.GetU32(operation.GetSource(0)); return new OperationResult(AggregateType.U32, context.GlslFindILsb(context.TypeU32(), source)); } private static OperationResult GenerateFindMSBS32(CodeGenContext context, AstOperation operation) { - var source = context.GetS32(operation.GetSource(0)); + SpvInstruction source = context.GetS32(operation.GetSource(0)); return new OperationResult(AggregateType.U32, context.GlslFindSMsb(context.TypeU32(), source)); } private static OperationResult GenerateFindMSBU32(CodeGenContext context, AstOperation operation) { - var source = context.GetU32(operation.GetSource(0)); + SpvInstruction source = context.GetU32(operation.GetSource(0)); return new OperationResult(AggregateType.U32, context.GlslFindUMsb(context.TypeU32(), source)); } @@ -591,7 +591,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv { AstTextureOperation texOp = (AstTextureOperation)operation; - var componentType = texOp.Format.GetComponentType(); + AggregateType componentType = texOp.Format.GetComponentType(); bool isArray = (texOp.Type & SamplerType.Array) != 0; @@ -630,7 +630,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv elems[i] = Src(AggregateType.S32); } - var vectorType = context.TypeVector(context.TypeS32(), pCount); + SpvInstruction vectorType = context.TypeVector(context.TypeS32(), pCount); pCoords = context.CompositeConstruct(vectorType, elems); } else @@ -640,11 +640,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv SpvInstruction value = Src(componentType); - var pointer = context.ImageTexelPointer(imagePointerType, image, pCoords, context.Constant(context.TypeU32(), 0)); - var one = context.Constant(context.TypeU32(), 1); - var zero = context.Constant(context.TypeU32(), 0); + SpvInstruction pointer = context.ImageTexelPointer(imagePointerType, image, pCoords, context.Constant(context.TypeU32(), 0)); + SpvInstruction one = context.Constant(context.TypeU32(), 1); + SpvInstruction zero = context.Constant(context.TypeU32(), 0); - var result = (texOp.Flags & TextureFlags.AtomicMask) switch + SpvInstruction result = (texOp.Flags & TextureFlags.AtomicMask) switch { TextureFlags.Add => context.AtomicIAdd(resultType, pointer, one, zero, value), TextureFlags.Minimum => componentType == AggregateType.S32 @@ -670,7 +670,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv { AstTextureOperation texOp = (AstTextureOperation)operation; - var componentType = texOp.Format.GetComponentType(); + AggregateType componentType = texOp.Format.GetComponentType(); bool isArray = (texOp.Type & SamplerType.Array) != 0; @@ -708,7 +708,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv elems[i] = Src(AggregateType.S32); } - var vectorType = context.TypeVector(context.TypeS32(), pCount); + SpvInstruction vectorType = context.TypeVector(context.TypeS32(), pCount); pCoords = context.CompositeConstruct(vectorType, elems); } else @@ -716,11 +716,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv pCoords = Src(AggregateType.S32); } - var imageComponentType = context.GetType(componentType); - var swizzledResultType = texOp.GetVectorType(componentType); + SpvInstruction imageComponentType = context.GetType(componentType); + AggregateType swizzledResultType = texOp.GetVectorType(componentType); - var texel = context.ImageRead(context.TypeVector(imageComponentType, 4), image, pCoords, ImageOperandsMask.MaskNone); - var result = GetSwizzledResult(context, texel, swizzledResultType, texOp.Index); + SpvInstruction texel = context.ImageRead(context.TypeVector(imageComponentType, 4), image, pCoords, ImageOperandsMask.MaskNone); + SpvInstruction result = GetSwizzledResult(context, texel, swizzledResultType, texOp.Index); return new OperationResult(componentType, result); } @@ -765,7 +765,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv elems[i] = Src(AggregateType.S32); } - var vectorType = context.TypeVector(context.TypeS32(), pCount); + SpvInstruction vectorType = context.TypeVector(context.TypeS32(), pCount); pCoords = context.CompositeConstruct(vectorType, elems); } else @@ -773,7 +773,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv pCoords = Src(AggregateType.S32); } - var componentType = texOp.Format.GetComponentType(); + AggregateType componentType = texOp.Format.GetComponentType(); const int ComponentsCount = 4; @@ -796,7 +796,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } } - var texel = context.CompositeConstruct(context.TypeVector(context.GetType(componentType), ComponentsCount), cElems); + SpvInstruction texel = context.CompositeConstruct(context.TypeVector(context.GetType(componentType), ComponentsCount), cElems); context.ImageWrite(image, pCoords, texel, ImageOperandsMask.MaskNone); @@ -805,7 +805,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static OperationResult GenerateIsNan(CodeGenContext context, AstOperation operation) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); SpvInstruction result; @@ -853,7 +853,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv elems[i] = Src(AggregateType.FP32); } - var vectorType = context.TypeVector(context.TypeFP32(), pCount); + SpvInstruction vectorType = context.TypeVector(context.TypeFP32(), pCount); pCoords = context.CompositeConstruct(vectorType, elems); } else @@ -861,9 +861,9 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv pCoords = Src(AggregateType.FP32); } - var resultType = context.TypeVector(context.TypeFP32(), 2); - var packed = context.ImageQueryLod(resultType, image, pCoords); - var result = context.CompositeExtract(context.TypeFP32(), packed, (SpvLiteralInteger)texOp.Index); + SpvInstruction resultType = context.TypeVector(context.TypeFP32(), 2); + SpvInstruction packed = context.ImageQueryLod(resultType, image, pCoords); + SpvInstruction result = context.CompositeExtract(context.TypeFP32(), packed, (SpvLiteralInteger)texOp.Index); return new OperationResult(AggregateType.FP32, result); } @@ -959,11 +959,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static OperationResult GenerateMultiplyHighS32(CodeGenContext context, AstOperation operation) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); - var resultType = context.TypeStruct(false, context.TypeS32(), context.TypeS32()); - var result = context.SMulExtended(resultType, context.GetS32(src1), context.GetS32(src2)); + SpvInstruction resultType = context.TypeStruct(false, context.TypeS32(), context.TypeS32()); + SpvInstruction result = context.SMulExtended(resultType, context.GetS32(src1), context.GetS32(src2)); result = context.CompositeExtract(context.TypeS32(), result, 1); return new OperationResult(AggregateType.S32, result); @@ -971,11 +971,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static OperationResult GenerateMultiplyHighU32(CodeGenContext context, AstOperation operation) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); - var resultType = context.TypeStruct(false, context.TypeU32(), context.TypeU32()); - var result = context.UMulExtended(resultType, context.GetU32(src1), context.GetU32(src2)); + SpvInstruction resultType = context.TypeStruct(false, context.TypeU32(), context.TypeU32()); + SpvInstruction result = context.UMulExtended(resultType, context.GetU32(src1), context.GetU32(src2)); result = context.CompositeExtract(context.TypeU32(), result, 1); return new OperationResult(AggregateType.U32, result); @@ -988,20 +988,20 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static OperationResult GeneratePackDouble2x32(CodeGenContext context, AstOperation operation) { - var value0 = context.GetU32(operation.GetSource(0)); - var value1 = context.GetU32(operation.GetSource(1)); - var vector = context.CompositeConstruct(context.TypeVector(context.TypeU32(), 2), value0, value1); - var result = context.GlslPackDouble2x32(context.TypeFP64(), vector); + SpvInstruction value0 = context.GetU32(operation.GetSource(0)); + SpvInstruction value1 = context.GetU32(operation.GetSource(1)); + SpvInstruction vector = context.CompositeConstruct(context.TypeVector(context.TypeU32(), 2), value0, value1); + SpvInstruction result = context.GlslPackDouble2x32(context.TypeFP64(), vector); return new OperationResult(AggregateType.FP64, result); } private static OperationResult GeneratePackHalf2x16(CodeGenContext context, AstOperation operation) { - var value0 = context.GetFP32(operation.GetSource(0)); - var value1 = context.GetFP32(operation.GetSource(1)); - var vector = context.CompositeConstruct(context.TypeVector(context.TypeFP32(), 2), value0, value1); - var result = context.GlslPackHalf2x16(context.TypeU32(), vector); + SpvInstruction value0 = context.GetFP32(operation.GetSource(0)); + SpvInstruction value1 = context.GetFP32(operation.GetSource(1)); + SpvInstruction vector = context.CompositeConstruct(context.TypeVector(context.TypeFP32(), 2), value0, value1); + SpvInstruction result = context.GlslPackHalf2x16(context.TypeU32(), vector); return new OperationResult(AggregateType.U32, result); } @@ -1049,40 +1049,40 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static OperationResult GenerateShuffle(CodeGenContext context, AstOperation operation) { - var value = context.GetFP32(operation.GetSource(0)); - var index = context.GetU32(operation.GetSource(1)); + SpvInstruction value = context.GetFP32(operation.GetSource(0)); + SpvInstruction index = context.GetU32(operation.GetSource(1)); - var result = context.GroupNonUniformShuffle(context.TypeFP32(), context.Constant(context.TypeU32(), (int)Scope.Subgroup), value, index); + SpvInstruction result = context.GroupNonUniformShuffle(context.TypeFP32(), context.Constant(context.TypeU32(), (int)Scope.Subgroup), value, index); return new OperationResult(AggregateType.FP32, result); } private static OperationResult GenerateShuffleDown(CodeGenContext context, AstOperation operation) { - var value = context.GetFP32(operation.GetSource(0)); - var index = context.GetU32(operation.GetSource(1)); + SpvInstruction value = context.GetFP32(operation.GetSource(0)); + SpvInstruction index = context.GetU32(operation.GetSource(1)); - var result = context.GroupNonUniformShuffleDown(context.TypeFP32(), context.Constant(context.TypeU32(), (int)Scope.Subgroup), value, index); + SpvInstruction result = context.GroupNonUniformShuffleDown(context.TypeFP32(), context.Constant(context.TypeU32(), (int)Scope.Subgroup), value, index); return new OperationResult(AggregateType.FP32, result); } private static OperationResult GenerateShuffleUp(CodeGenContext context, AstOperation operation) { - var value = context.GetFP32(operation.GetSource(0)); - var index = context.GetU32(operation.GetSource(1)); + SpvInstruction value = context.GetFP32(operation.GetSource(0)); + SpvInstruction index = context.GetU32(operation.GetSource(1)); - var result = context.GroupNonUniformShuffleUp(context.TypeFP32(), context.Constant(context.TypeU32(), (int)Scope.Subgroup), value, index); + SpvInstruction result = context.GroupNonUniformShuffleUp(context.TypeFP32(), context.Constant(context.TypeU32(), (int)Scope.Subgroup), value, index); return new OperationResult(AggregateType.FP32, result); } private static OperationResult GenerateShuffleXor(CodeGenContext context, AstOperation operation) { - var value = context.GetFP32(operation.GetSource(0)); - var index = context.GetU32(operation.GetSource(1)); + SpvInstruction value = context.GetFP32(operation.GetSource(0)); + SpvInstruction index = context.GetU32(operation.GetSource(1)); - var result = context.GroupNonUniformShuffleXor(context.TypeFP32(), context.Constant(context.TypeU32(), (int)Scope.Subgroup), value, index); + SpvInstruction result = context.GroupNonUniformShuffleXor(context.TypeFP32(), context.Constant(context.TypeU32(), (int)Scope.Subgroup), value, index); return new OperationResult(AggregateType.FP32, result); } @@ -1109,31 +1109,31 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static OperationResult GenerateSwizzleAdd(CodeGenContext context, AstOperation operation) { - var x = context.Get(AggregateType.FP32, operation.GetSource(0)); - var y = context.Get(AggregateType.FP32, operation.GetSource(1)); - var mask = context.Get(AggregateType.U32, operation.GetSource(2)); + SpvInstruction x = context.Get(AggregateType.FP32, operation.GetSource(0)); + SpvInstruction y = context.Get(AggregateType.FP32, operation.GetSource(1)); + SpvInstruction mask = context.Get(AggregateType.U32, operation.GetSource(2)); - var v4float = context.TypeVector(context.TypeFP32(), 4); - var one = context.Constant(context.TypeFP32(), 1.0f); - var minusOne = context.Constant(context.TypeFP32(), -1.0f); - var zero = context.Constant(context.TypeFP32(), 0.0f); - var xLut = context.ConstantComposite(v4float, one, minusOne, one, zero); - var yLut = context.ConstantComposite(v4float, one, one, minusOne, one); + SpvInstruction v4float = context.TypeVector(context.TypeFP32(), 4); + SpvInstruction one = context.Constant(context.TypeFP32(), 1.0f); + SpvInstruction minusOne = context.Constant(context.TypeFP32(), -1.0f); + SpvInstruction zero = context.Constant(context.TypeFP32(), 0.0f); + SpvInstruction xLut = context.ConstantComposite(v4float, one, minusOne, one, zero); + SpvInstruction yLut = context.ConstantComposite(v4float, one, one, minusOne, one); - var three = context.Constant(context.TypeU32(), 3); + SpvInstruction three = context.Constant(context.TypeU32(), 3); - var threadId = GetScalarInput(context, IoVariable.SubgroupLaneId); - var shift = context.BitwiseAnd(context.TypeU32(), threadId, three); + SpvInstruction threadId = GetScalarInput(context, IoVariable.SubgroupLaneId); + SpvInstruction shift = context.BitwiseAnd(context.TypeU32(), threadId, three); shift = context.ShiftLeftLogical(context.TypeU32(), shift, context.Constant(context.TypeU32(), 1)); - var lutIdx = context.ShiftRightLogical(context.TypeU32(), mask, shift); + SpvInstruction lutIdx = context.ShiftRightLogical(context.TypeU32(), mask, shift); lutIdx = context.BitwiseAnd(context.TypeU32(), lutIdx, three); - var xLutValue = context.VectorExtractDynamic(context.TypeFP32(), xLut, lutIdx); - var yLutValue = context.VectorExtractDynamic(context.TypeFP32(), yLut, lutIdx); + SpvInstruction xLutValue = context.VectorExtractDynamic(context.TypeFP32(), xLut, lutIdx); + SpvInstruction yLutValue = context.VectorExtractDynamic(context.TypeFP32(), yLut, lutIdx); - var xResult = context.FMul(context.TypeFP32(), x, xLutValue); - var yResult = context.FMul(context.TypeFP32(), y, yLutValue); - var result = context.FAdd(context.TypeFP32(), xResult, yResult); + SpvInstruction xResult = context.FMul(context.TypeFP32(), x, xLutValue); + SpvInstruction yResult = context.FMul(context.TypeFP32(), y, yLutValue); + SpvInstruction result = context.FAdd(context.TypeFP32(), xResult, yResult); return new OperationResult(AggregateType.FP32, result); } @@ -1200,7 +1200,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } } - var vectorType = context.TypeVector(intCoords ? context.TypeS32() : context.TypeFP32(), count); + SpvInstruction vectorType = context.TypeVector(intCoords ? context.TypeS32() : context.TypeFP32(), count); return context.CompositeConstruct(vectorType, elems); } else @@ -1222,7 +1222,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv elems[index] = Src(AggregateType.FP32); } - var vectorType = context.TypeVector(context.TypeFP32(), count); + SpvInstruction vectorType = context.TypeVector(context.TypeFP32(), count); return context.CompositeConstruct(vectorType, elems); } else @@ -1272,7 +1272,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv elems[index] = Src(AggregateType.S32); } - var vectorType = context.TypeVector(context.TypeS32(), count); + SpvInstruction vectorType = context.TypeVector(context.TypeS32(), count); return context.ConstantComposite(vectorType, elems); } @@ -1327,8 +1327,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv compIdx = Src(AggregateType.S32); } - var operandsList = new List(); - var operandsMask = ImageOperandsMask.MaskNone; + List operandsList = new List(); + ImageOperandsMask operandsMask = ImageOperandsMask.MaskNone; if (hasLodBias) { @@ -1369,14 +1369,14 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv bool colorIsVector = isGather || !isShadow; - var resultType = colorIsVector ? context.TypeVector(context.TypeFP32(), 4) : context.TypeFP32(); + SpvInstruction resultType = colorIsVector ? context.TypeVector(context.TypeFP32(), 4) : context.TypeFP32(); if (intCoords) { image = context.Image(declaration.ImageType, image); } - var operands = operandsList.ToArray(); + SpvInstruction[] operands = operandsList.ToArray(); SpvInstruction result; @@ -1415,7 +1415,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv result = context.ImageSampleImplicitLod(resultType, image, pCoords, operandsMask, operands); } - var swizzledResultType = AggregateType.FP32; + AggregateType swizzledResultType = AggregateType.FP32; if (colorIsVector) { @@ -1460,7 +1460,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } else { - var type = context.SamplersTypes[texOp.GetTextureSetAndBinding()]; + SamplerType type = context.SamplersTypes[texOp.GetTextureSetAndBinding()]; bool hasLod = !type.HasFlag(SamplerType.Multisample) && type != SamplerType.TextureBuffer; int dimensions = (type & SamplerType.Mask) == SamplerType.TextureCube ? 2 : type.GetDimensions(); @@ -1470,13 +1470,13 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv dimensions++; } - var resultType = dimensions == 1 ? context.TypeS32() : context.TypeVector(context.TypeS32(), dimensions); + SpvInstruction resultType = dimensions == 1 ? context.TypeS32() : context.TypeVector(context.TypeS32(), dimensions); SpvInstruction result; if (hasLod) { - var lod = context.GetS32(operation.GetSource(srcIndex)); + SpvInstruction lod = context.GetS32(operation.GetSource(srcIndex)); result = context.ImageQuerySizeLod(resultType, image, lod); } else @@ -1500,27 +1500,27 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static OperationResult GenerateUnpackDouble2x32(CodeGenContext context, AstOperation operation) { - var value = context.GetFP64(operation.GetSource(0)); - var vector = context.GlslUnpackDouble2x32(context.TypeVector(context.TypeU32(), 2), value); - var result = context.CompositeExtract(context.TypeU32(), vector, operation.Index); + SpvInstruction value = context.GetFP64(operation.GetSource(0)); + SpvInstruction vector = context.GlslUnpackDouble2x32(context.TypeVector(context.TypeU32(), 2), value); + SpvInstruction result = context.CompositeExtract(context.TypeU32(), vector, operation.Index); return new OperationResult(AggregateType.U32, result); } private static OperationResult GenerateUnpackHalf2x16(CodeGenContext context, AstOperation operation) { - var value = context.GetU32(operation.GetSource(0)); - var vector = context.GlslUnpackHalf2x16(context.TypeVector(context.TypeFP32(), 2), value); - var result = context.CompositeExtract(context.TypeFP32(), vector, operation.Index); + SpvInstruction value = context.GetU32(operation.GetSource(0)); + SpvInstruction vector = context.GlslUnpackHalf2x16(context.TypeVector(context.TypeFP32(), 2), value); + SpvInstruction result = context.CompositeExtract(context.TypeFP32(), vector, operation.Index); return new OperationResult(AggregateType.FP32, result); } private static OperationResult GenerateVectorExtract(CodeGenContext context, AstOperation operation) { - var vector = context.GetWithType(operation.GetSource(0), out AggregateType vectorType); - var scalarType = vectorType & ~AggregateType.ElementCountMask; - var resultType = context.GetType(scalarType); + SpvInstruction vector = context.GetWithType(operation.GetSource(0), out AggregateType vectorType); + AggregateType scalarType = vectorType & ~AggregateType.ElementCountMask; + SpvInstruction resultType = context.GetType(scalarType); SpvInstruction result; if (operation.GetSource(1) is AstOperand indexOperand && indexOperand.Type == OperandType.Constant) @@ -1529,7 +1529,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } else { - var index = context.Get(AggregateType.S32, operation.GetSource(1)); + SpvInstruction index = context.Get(AggregateType.S32, operation.GetSource(1)); result = context.VectorExtractDynamic(resultType, vector, index); } @@ -1538,22 +1538,22 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static OperationResult GenerateVoteAll(CodeGenContext context, AstOperation operation) { - var execution = context.Constant(context.TypeU32(), Scope.Subgroup); - var result = context.GroupNonUniformAll(context.TypeBool(), execution, context.Get(AggregateType.Bool, operation.GetSource(0))); + SpvInstruction execution = context.Constant(context.TypeU32(), Scope.Subgroup); + SpvInstruction result = context.GroupNonUniformAll(context.TypeBool(), execution, context.Get(AggregateType.Bool, operation.GetSource(0))); return new OperationResult(AggregateType.Bool, result); } private static OperationResult GenerateVoteAllEqual(CodeGenContext context, AstOperation operation) { - var execution = context.Constant(context.TypeU32(), Scope.Subgroup); - var result = context.GroupNonUniformAllEqual(context.TypeBool(), execution, context.Get(AggregateType.Bool, operation.GetSource(0))); + SpvInstruction execution = context.Constant(context.TypeU32(), Scope.Subgroup); + SpvInstruction result = context.GroupNonUniformAllEqual(context.TypeBool(), execution, context.Get(AggregateType.Bool, operation.GetSource(0))); return new OperationResult(AggregateType.Bool, result); } private static OperationResult GenerateVoteAny(CodeGenContext context, AstOperation operation) { - var execution = context.Constant(context.TypeU32(), Scope.Subgroup); - var result = context.GroupNonUniformAny(context.TypeBool(), execution, context.Get(AggregateType.Bool, operation.GetSource(0))); + SpvInstruction execution = context.Constant(context.TypeU32(), Scope.Subgroup); + SpvInstruction result = context.GroupNonUniformAny(context.TypeBool(), execution, context.Get(AggregateType.Bool, operation.GetSource(0))); return new OperationResult(AggregateType.Bool, result); } @@ -1563,8 +1563,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv Func emitF, Func emitI) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); SpvInstruction result; @@ -1589,10 +1589,10 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv AstOperation operation, Func emitU) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); - var result = emitU(context.TypeBool(), context.GetU32(src1), context.GetU32(src2)); + SpvInstruction result = emitU(context.TypeBool(), context.GetU32(src1), context.GetU32(src2)); return new OperationResult(AggregateType.Bool, result); } @@ -1604,10 +1604,10 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv { SpvInstruction elemPointer = GetStoragePointer(context, operation, out AggregateType varType); - var value = context.Get(varType, operation.GetSource(operation.SourcesCount - 1)); + SpvInstruction value = context.Get(varType, operation.GetSource(operation.SourcesCount - 1)); - var one = context.Constant(context.TypeU32(), 1); - var zero = context.Constant(context.TypeU32(), 0); + SpvInstruction one = context.Constant(context.TypeU32(), 1); + SpvInstruction zero = context.Constant(context.TypeU32(), 0); return new OperationResult(varType, emitU(context.GetType(varType), elemPointer, one, zero, value)); } @@ -1616,11 +1616,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv { SpvInstruction elemPointer = GetStoragePointer(context, operation, out AggregateType varType); - var value0 = context.Get(varType, operation.GetSource(operation.SourcesCount - 2)); - var value1 = context.Get(varType, operation.GetSource(operation.SourcesCount - 1)); + SpvInstruction value0 = context.Get(varType, operation.GetSource(operation.SourcesCount - 2)); + SpvInstruction value1 = context.Get(varType, operation.GetSource(operation.SourcesCount - 1)); - var one = context.Constant(context.TypeU32(), 1); - var zero = context.Constant(context.TypeU32(), 0); + SpvInstruction one = context.Constant(context.TypeU32(), 1); + SpvInstruction zero = context.Constant(context.TypeU32(), 0); return new OperationResult(varType, context.AtomicCompareExchange(context.GetType(varType), elemPointer, one, zero, zero, value1, value0)); } @@ -1636,7 +1636,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } else { - var result = context.Load(context.GetType(varType), pointer); + SpvInstruction result = context.Load(context.GetType(varType), pointer); return new OperationResult(varType, result); } } @@ -1754,8 +1754,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv storageClass = isOutput ? StorageClass.Output : StorageClass.Input; - var ioDefinition = new IoDefinition(storageKind, ioVariable, location, component); - var dict = isPerPatch + IoDefinition ioDefinition = new IoDefinition(storageKind, ioVariable, location, component); + Dictionary dict = isPerPatch ? (isOutput ? context.OutputsPerPatch : context.InputsPerPatch) : (isOutput ? context.Outputs : context.Inputs); @@ -1773,7 +1773,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv { int fieldIndex = IoMap.GetPerVertexStructFieldIndex(perVertexBuiltIn.Value); - var indexes = new SpvInstruction[inputsCount + 1]; + SpvInstruction[] indexes = new SpvInstruction[inputsCount + 1]; int index = 0; if (IoMap.IsPerVertexArrayBuiltIn(storageKind, context.Definitions.Stage)) @@ -1823,7 +1823,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv pointer = context.AccessChain(context.TypePointer(storageClass, context.GetType(varType)), baseObj, e0, e1, e2); break; default: - var indexes = new SpvInstruction[inputsCount]; + SpvInstruction[] indexes = new SpvInstruction[inputsCount]; int index = 0; for (; index < inputsCount; srcIndex++, index++) @@ -1840,10 +1840,10 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static SpvInstruction GetScalarInput(CodeGenContext context, IoVariable ioVariable) { - var (_, varType) = IoMap.GetSpirvBuiltIn(ioVariable); + (_, AggregateType varType) = IoMap.GetSpirvBuiltIn(ioVariable); varType &= AggregateType.ElementTypeMask; - var ioDefinition = new IoDefinition(StorageKind.Input, ioVariable); + IoDefinition ioDefinition = new IoDefinition(StorageKind.Input, ioVariable); return context.Load(context.GetType(varType), context.Inputs[ioDefinition]); } @@ -1917,7 +1917,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv Func emitF, Func emitI) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); if (operation.Inst.HasFlag(Instruction.FP64)) { @@ -1938,7 +1938,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv AstOperation operation, Func emitB) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.Bool, emitB(context.TypeBool(), context.Get(AggregateType.Bool, source))); } @@ -1947,7 +1947,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv AstOperation operation, Func emit) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.FP32, emit(context.TypeFP32(), context.GetFP32(source))); } @@ -1956,7 +1956,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv AstOperation operation, Func emitS) { - var source = operation.GetSource(0); + IAstNode source = operation.GetSource(0); return new OperationResult(AggregateType.S32, emitS(context.TypeS32(), context.GetS32(source))); } @@ -1966,12 +1966,12 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv Func emitF, Func emitI) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); if (operation.Inst.HasFlag(Instruction.FP64)) { - var result = emitF(context.TypeFP64(), context.GetFP64(src1), context.GetFP64(src2)); + SpvInstruction result = emitF(context.TypeFP64(), context.GetFP64(src1), context.GetFP64(src2)); if (!context.HostCapabilities.ReducedPrecision || operation.ForcePrecise) { @@ -1982,7 +1982,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } else if (operation.Inst.HasFlag(Instruction.FP32)) { - var result = emitF(context.TypeFP32(), context.GetFP32(src1), context.GetFP32(src2)); + SpvInstruction result = emitF(context.TypeFP32(), context.GetFP32(src1), context.GetFP32(src2)); if (!context.HostCapabilities.ReducedPrecision || operation.ForcePrecise) { @@ -2002,8 +2002,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv AstOperation operation, Func emitB) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); return new OperationResult(AggregateType.Bool, emitB(context.TypeBool(), context.Get(AggregateType.Bool, src1), context.Get(AggregateType.Bool, src2))); } @@ -2013,8 +2013,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv AstOperation operation, Func emitS) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); return new OperationResult(AggregateType.S32, emitS(context.TypeS32(), context.GetS32(src1), context.GetS32(src2))); } @@ -2024,8 +2024,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv AstOperation operation, Func emitU) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); return new OperationResult(AggregateType.U32, emitU(context.TypeU32(), context.GetU32(src1), context.GetU32(src2))); } @@ -2036,13 +2036,13 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv Func emitF, Func emitI) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); - var src3 = operation.GetSource(2); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); + IAstNode src3 = operation.GetSource(2); if (operation.Inst.HasFlag(Instruction.FP64)) { - var result = emitF(context.TypeFP64(), context.GetFP64(src1), context.GetFP64(src2), context.GetFP64(src3)); + SpvInstruction result = emitF(context.TypeFP64(), context.GetFP64(src1), context.GetFP64(src2), context.GetFP64(src3)); if (!context.HostCapabilities.ReducedPrecision || operation.ForcePrecise) { @@ -2053,7 +2053,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } else if (operation.Inst.HasFlag(Instruction.FP32)) { - var result = emitF(context.TypeFP32(), context.GetFP32(src1), context.GetFP32(src2), context.GetFP32(src3)); + SpvInstruction result = emitF(context.TypeFP32(), context.GetFP32(src1), context.GetFP32(src2), context.GetFP32(src3)); if (!context.HostCapabilities.ReducedPrecision || operation.ForcePrecise) { @@ -2073,9 +2073,9 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv AstOperation operation, Func emitU) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); - var src3 = operation.GetSource(2); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); + IAstNode src3 = operation.GetSource(2); return new OperationResult(AggregateType.U32, emitU( context.TypeU32(), @@ -2089,9 +2089,9 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv AstOperation operation, Func emitS) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); - var src3 = operation.GetSource(2); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); + IAstNode src3 = operation.GetSource(2); return new OperationResult(AggregateType.S32, emitS( context.TypeS32(), @@ -2105,10 +2105,10 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv AstOperation operation, Func emitS) { - var src1 = operation.GetSource(0); - var src2 = operation.GetSource(1); - var src3 = operation.GetSource(2); - var src4 = operation.GetSource(3); + IAstNode src1 = operation.GetSource(0); + IAstNode src2 = operation.GetSource(1); + IAstNode src3 = operation.GetSource(2); + IAstNode src4 = operation.GetSource(3); return new OperationResult(AggregateType.U32, emitS( context.TypeU32(), diff --git a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/SpirvGenerator.cs b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/SpirvGenerator.cs index 105812ebf..73af3b850 100644 --- a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/SpirvGenerator.cs +++ b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/SpirvGenerator.cs @@ -124,20 +124,20 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv for (int funcIndex = 0; funcIndex < info.Functions.Count; funcIndex++) { - var function = info.Functions[funcIndex]; - var retType = context.GetType(function.ReturnType); + StructuredFunction function = info.Functions[funcIndex]; + SpvInstruction retType = context.GetType(function.ReturnType); - var funcArgs = new SpvInstruction[function.InArguments.Length + function.OutArguments.Length]; + SpvInstruction[] funcArgs = new SpvInstruction[function.InArguments.Length + function.OutArguments.Length]; for (int argIndex = 0; argIndex < funcArgs.Length; argIndex++) { - var argType = context.GetType(function.GetArgumentType(argIndex)); - var argPointerType = context.TypePointer(StorageClass.Function, argType); + SpvInstruction argType = context.GetType(function.GetArgumentType(argIndex)); + SpvInstruction argPointerType = context.TypePointer(StorageClass.Function, argType); funcArgs[argIndex] = argPointerType; } - var funcType = context.TypeFunction(retType, false, funcArgs); - var spvFunc = context.Function(retType, FunctionControlMask.MaskNone, funcType); + SpvInstruction funcType = context.TypeFunction(retType, false, funcArgs); + SpvInstruction spvFunc = context.Function(retType, FunctionControlMask.MaskNone, funcType); context.DeclareFunction(funcIndex, function, spvFunc); } @@ -160,7 +160,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv private static void Generate(CodeGenContext context, StructuredProgramInfo info, int funcIndex) { - var (function, spvFunc) = context.GetFunction(funcIndex); + (StructuredFunction function, SpvInstruction spvFunc) = context.GetFunction(funcIndex); context.CurrentFunction = function; context.AddFunction(spvFunc); @@ -284,9 +284,9 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv } else if (context.Definitions.Stage == ShaderStage.Compute) { - var localSizeX = (SpvLiteralInteger)context.Definitions.ComputeLocalSizeX; - var localSizeY = (SpvLiteralInteger)context.Definitions.ComputeLocalSizeY; - var localSizeZ = (SpvLiteralInteger)context.Definitions.ComputeLocalSizeZ; + SpvLiteralInteger localSizeX = (SpvLiteralInteger)context.Definitions.ComputeLocalSizeX; + SpvLiteralInteger localSizeY = (SpvLiteralInteger)context.Definitions.ComputeLocalSizeY; + SpvLiteralInteger localSizeZ = (SpvLiteralInteger)context.Definitions.ComputeLocalSizeZ; context.AddExecutionMode( spvFunc, @@ -307,7 +307,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv { AstBlockVisitor visitor = new(block); - var loopTargets = new Dictionary(); + Dictionary loopTargets = new Dictionary(); context.LoopTargets = loopTargets; @@ -329,14 +329,14 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv ifFalseBlock = mergeBlock; } - var condition = context.Get(AggregateType.Bool, e.Block.Condition); + SpvInstruction condition = context.Get(AggregateType.Bool, e.Block.Condition); context.SelectionMerge(context.GetNextLabel(mergeBlock), SelectionControlMask.MaskNone); context.BranchConditional(condition, context.GetNextLabel(ifTrueBlock), context.GetNextLabel(ifFalseBlock)); } else if (e.Block.Type == AstBlockType.DoWhile) { - var continueTarget = context.Label(); + SpvInstruction continueTarget = context.Label(); loopTargets.Add(e.Block, (context.NewBlock(), continueTarget)); @@ -357,12 +357,12 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv // if the condition is true. AstBlock mergeBlock = e.Block.Parent; - var (loopTarget, continueTarget) = loopTargets[e.Block]; + (SpvInstruction loopTarget, SpvInstruction continueTarget) = loopTargets[e.Block]; context.Branch(continueTarget); context.AddLabel(continueTarget); - var condition = context.Get(AggregateType.Bool, e.Block.Condition); + SpvInstruction condition = context.Get(AggregateType.Bool, e.Block.Condition); context.BranchConditional(condition, loopTarget, context.GetNextLabel(mergeBlock)); } @@ -398,16 +398,16 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv { if (node is AstAssignment assignment) { - var dest = (AstOperand)assignment.Destination; + AstOperand dest = (AstOperand)assignment.Destination; if (dest.Type == OperandType.LocalVariable) { - var source = context.Get(dest.VarType, assignment.Source); + SpvInstruction source = context.Get(dest.VarType, assignment.Source); context.Store(context.GetLocalPointer(dest), source); } else if (dest.Type == OperandType.Argument) { - var source = context.Get(dest.VarType, assignment.Source); + SpvInstruction source = context.Get(dest.VarType, assignment.Source); context.Store(context.GetArgumentPointer(dest), source); } else diff --git a/src/Ryujinx.Graphics.Shader/Decoders/Decoder.cs b/src/Ryujinx.Graphics.Shader/Decoders/Decoder.cs index 1211e561f..d9f4dd5eb 100644 --- a/src/Ryujinx.Graphics.Shader/Decoders/Decoder.cs +++ b/src/Ryujinx.Graphics.Shader/Decoders/Decoder.cs @@ -568,39 +568,39 @@ namespace Ryujinx.Graphics.Shader.Decoders HashSet visited = new(); - var ldcLocation = FindFirstRegWrite(visited, new BlockLocation(block, block.OpCodes.Count - 1), brxReg); + BlockLocation ldcLocation = FindFirstRegWrite(visited, new BlockLocation(block, block.OpCodes.Count - 1), brxReg); if (ldcLocation.Block == null || ldcLocation.Block.OpCodes[ldcLocation.Index].Name != InstName.Ldc) { return (0, 0); } - GetOp(ldcLocation, out var opLdc); + GetOp(ldcLocation, out InstLdc opLdc); if (opLdc.CbufSlot != 1 || opLdc.AddressMode != 0) { return (0, 0); } - var shlLocation = FindFirstRegWrite(visited, ldcLocation, opLdc.SrcA); + BlockLocation shlLocation = FindFirstRegWrite(visited, ldcLocation, opLdc.SrcA); if (shlLocation.Block == null || !shlLocation.IsImmInst(InstName.Shl)) { return (0, 0); } - GetOp(shlLocation, out var opShl); + GetOp(shlLocation, out InstShlI opShl); if (opShl.Imm20 != 2) { return (0, 0); } - var imnmxLocation = FindFirstRegWrite(visited, shlLocation, opShl.SrcA); + BlockLocation imnmxLocation = FindFirstRegWrite(visited, shlLocation, opShl.SrcA); if (imnmxLocation.Block == null || !imnmxLocation.IsImmInst(InstName.Imnmx)) { return (0, 0); } - GetOp(imnmxLocation, out var opImnmx); + GetOp(imnmxLocation, out InstImnmxI opImnmx); if (opImnmx.Signed || opImnmx.SrcPred != RegisterConsts.PredicateTrueIndex || opImnmx.SrcPredInv) { @@ -640,7 +640,7 @@ namespace Ryujinx.Graphics.Shader.Decoders toVisit.Enqueue(location); visited.Add(location.Block); - while (toVisit.TryDequeue(out var currentLocation)) + while (toVisit.TryDequeue(out BlockLocation currentLocation)) { Block block = currentLocation.Block; for (int i = currentLocation.Index - 1; i >= 0; i--) diff --git a/src/Ryujinx.Graphics.Shader/Instructions/AttributeMap.cs b/src/Ryujinx.Graphics.Shader/Instructions/AttributeMap.cs index 54705acaf..b4ecf9abe 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/AttributeMap.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/AttributeMap.cs @@ -57,7 +57,7 @@ namespace Ryujinx.Graphics.Shader.Instructions private static IReadOnlyDictionary CreateMap() { - var map = new Dictionary(); + Dictionary map = new Dictionary(); Add(map, 0x060, AggregateType.S32, IoVariable.PrimitiveId, StagesMask.TessellationGeometryFragment, StagesMask.Geometry); Add(map, 0x064, AggregateType.S32, IoVariable.Layer, StagesMask.Fragment, StagesMask.VertexTessellationGeometry); @@ -84,7 +84,7 @@ namespace Ryujinx.Graphics.Shader.Instructions private static IReadOnlyDictionary CreatePerPatchMap() { - var map = new Dictionary(); + Dictionary map = new Dictionary(); Add(map, 0x000, AggregateType.Vector4 | AggregateType.FP32, IoVariable.TessellationLevelOuter, StagesMask.TessellationEvaluation, StagesMask.TessellationControl); Add(map, 0x010, AggregateType.Vector2 | AggregateType.FP32, IoVariable.TessellationLevelInner, StagesMask.TessellationEvaluation, StagesMask.TessellationControl); diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitAttribute.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitAttribute.cs index c704156bc..89b7e9831 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitAttribute.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitAttribute.cs @@ -261,7 +261,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { if (context.TranslatorContext.Definitions.LastInVertexPipeline) { - context.PrepareForVertexReturn(out var tempXLocal, out var tempYLocal, out var tempZLocal); + context.PrepareForVertexReturn(out Operand tempXLocal, out Operand tempYLocal, out Operand tempZLocal); context.EmitVertex(); diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitBitfield.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitBitfield.cs index 3a8419698..97b08aefd 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitBitfield.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitBitfield.cs @@ -13,8 +13,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstBfeR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitBfe(context, srcA, srcB, op.Dest, op.Brev, op.Signed); } @@ -23,8 +23,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstBfeI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); EmitBfe(context, srcA, srcB, op.Dest, op.Brev, op.Signed); } @@ -33,8 +33,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstBfeC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitBfe(context, srcA, srcB, op.Dest, op.Brev, op.Signed); } @@ -43,9 +43,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstBfiR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcC = GetSrcReg(context, op.SrcC); EmitBfi(context, srcA, srcB, srcC, op.Dest); } @@ -54,9 +54,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstBfiI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcC = GetSrcReg(context, op.SrcC); EmitBfi(context, srcA, srcB, srcC, op.Dest); } @@ -65,9 +65,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstBfiC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcC = GetSrcReg(context, op.SrcC); EmitBfi(context, srcA, srcB, srcC, op.Dest); } @@ -76,9 +76,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstBfiRc op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcC); - var srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcC); + Operand srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitBfi(context, srcA, srcB, srcC, op.Dest); } diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitConversion.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitConversion.cs index e7e0fba92..198c9077a 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitConversion.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitConversion.cs @@ -14,7 +14,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstF2fR op = context.GetOp(); - var src = UnpackReg(context, op.SrcFmt, op.Sh, op.SrcB); + Operand src = UnpackReg(context, op.SrcFmt, op.Sh, op.SrcB); EmitF2F(context, op.SrcFmt, op.DstFmt, op.RoundMode, src, op.Dest, op.AbsB, op.NegB, op.Sat); } @@ -23,7 +23,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstF2fI op = context.GetOp(); - var src = UnpackImm(context, op.SrcFmt, op.Sh, Imm20ToFloat(op.Imm20)); + Operand src = UnpackImm(context, op.SrcFmt, op.Sh, Imm20ToFloat(op.Imm20)); EmitF2F(context, op.SrcFmt, op.DstFmt, op.RoundMode, src, op.Dest, op.AbsB, op.NegB, op.Sat); } @@ -32,7 +32,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstF2fC op = context.GetOp(); - var src = UnpackCbuf(context, op.SrcFmt, op.Sh, op.CbufSlot, op.CbufOffset); + Operand src = UnpackCbuf(context, op.SrcFmt, op.Sh, op.CbufSlot, op.CbufOffset); EmitF2F(context, op.SrcFmt, op.DstFmt, op.RoundMode, src, op.Dest, op.AbsB, op.NegB, op.Sat); } @@ -41,7 +41,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstF2iR op = context.GetOp(); - var src = UnpackReg(context, op.SrcFmt, op.Sh, op.SrcB); + Operand src = UnpackReg(context, op.SrcFmt, op.Sh, op.SrcB); EmitF2I(context, op.SrcFmt, op.IDstFmt, op.RoundMode, src, op.Dest, op.AbsB, op.NegB); } @@ -50,7 +50,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstF2iI op = context.GetOp(); - var src = UnpackImm(context, op.SrcFmt, op.Sh, Imm20ToFloat(op.Imm20)); + Operand src = UnpackImm(context, op.SrcFmt, op.Sh, Imm20ToFloat(op.Imm20)); EmitF2I(context, op.SrcFmt, op.IDstFmt, op.RoundMode, src, op.Dest, op.AbsB, op.NegB); } @@ -59,7 +59,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstF2iC op = context.GetOp(); - var src = UnpackCbuf(context, op.SrcFmt, op.Sh, op.CbufSlot, op.CbufOffset); + Operand src = UnpackCbuf(context, op.SrcFmt, op.Sh, op.CbufSlot, op.CbufOffset); EmitF2I(context, op.SrcFmt, op.IDstFmt, op.RoundMode, src, op.Dest, op.AbsB, op.NegB); } @@ -68,7 +68,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstI2fR op = context.GetOp(); - var src = GetSrcReg(context, op.SrcB); + Operand src = GetSrcReg(context, op.SrcB); EmitI2F(context, op.ISrcFmt, op.DstFmt, src, op.ByteSel, op.Dest, op.AbsB, op.NegB); } @@ -77,7 +77,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstI2fI op = context.GetOp(); - var src = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand src = GetSrcImm(context, Imm20ToSInt(op.Imm20)); EmitI2F(context, op.ISrcFmt, op.DstFmt, src, op.ByteSel, op.Dest, op.AbsB, op.NegB); } @@ -86,7 +86,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstI2fC op = context.GetOp(); - var src = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand src = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitI2F(context, op.ISrcFmt, op.DstFmt, src, op.ByteSel, op.Dest, op.AbsB, op.NegB); } @@ -95,7 +95,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstI2iR op = context.GetOp(); - var src = GetSrcReg(context, op.SrcB); + Operand src = GetSrcReg(context, op.SrcB); EmitI2I(context, op.ISrcFmt, op.IDstFmt, src, op.ByteSel, op.Dest, op.AbsB, op.NegB, op.Sat, op.WriteCC); } @@ -104,7 +104,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstI2iI op = context.GetOp(); - var src = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand src = GetSrcImm(context, Imm20ToSInt(op.Imm20)); EmitI2I(context, op.ISrcFmt, op.IDstFmt, src, op.ByteSel, op.Dest, op.AbsB, op.NegB, op.Sat, op.WriteCC); } @@ -113,7 +113,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstI2iC op = context.GetOp(); - var src = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand src = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitI2I(context, op.ISrcFmt, op.IDstFmt, src, op.ByteSel, op.Dest, op.AbsB, op.NegB, op.Sat, op.WriteCC); } diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFloatArithmetic.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFloatArithmetic.cs index 04dbd20eb..7d974a370 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFloatArithmetic.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFloatArithmetic.cs @@ -13,8 +13,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDaddR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcReg(context, op.SrcB, isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcReg(context, op.SrcB, isFP64: true); EmitFadd(context, Instruction.FP64, srcA, srcB, op.Dest, op.NegA, op.NegB, op.AbsA, op.AbsB, false, op.WriteCC); } @@ -23,8 +23,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDaddI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20), isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20), isFP64: true); EmitFadd(context, Instruction.FP64, srcA, srcB, op.Dest, op.NegA, op.NegB, op.AbsA, op.AbsB, false, op.WriteCC); } @@ -33,8 +33,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDaddC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); EmitFadd(context, Instruction.FP64, srcA, srcB, op.Dest, op.NegA, op.NegB, op.AbsA, op.AbsB, false, op.WriteCC); } @@ -43,9 +43,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDfmaR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcReg(context, op.SrcB, isFP64: true); - var srcC = GetSrcReg(context, op.SrcC, isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcReg(context, op.SrcB, isFP64: true); + Operand srcC = GetSrcReg(context, op.SrcC, isFP64: true); EmitFfma(context, Instruction.FP64, srcA, srcB, srcC, op.Dest, op.NegA, op.NegC, false, op.WriteCC); } @@ -54,9 +54,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDfmaI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20), isFP64: true); - var srcC = GetSrcReg(context, op.SrcC, isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20), isFP64: true); + Operand srcC = GetSrcReg(context, op.SrcC, isFP64: true); EmitFfma(context, Instruction.FP64, srcA, srcB, srcC, op.Dest, op.NegA, op.NegC, false, op.WriteCC); } @@ -65,9 +65,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDfmaC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); - var srcC = GetSrcReg(context, op.SrcC, isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); + Operand srcC = GetSrcReg(context, op.SrcC, isFP64: true); EmitFfma(context, Instruction.FP64, srcA, srcB, srcC, op.Dest, op.NegA, op.NegC, false, op.WriteCC); } @@ -76,9 +76,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDfmaRc op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcReg(context, op.SrcC, isFP64: true); - var srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcReg(context, op.SrcC, isFP64: true); + Operand srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); EmitFfma(context, Instruction.FP64, srcA, srcB, srcC, op.Dest, op.NegA, op.NegC, false, op.WriteCC); } @@ -87,8 +87,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDmulR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcReg(context, op.SrcB, isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcReg(context, op.SrcB, isFP64: true); EmitFmul(context, Instruction.FP64, MultiplyScale.NoScale, srcA, srcB, op.Dest, op.NegA, false, op.WriteCC); } @@ -97,8 +97,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDmulI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20), isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20), isFP64: true); EmitFmul(context, Instruction.FP64, MultiplyScale.NoScale, srcA, srcB, op.Dest, op.NegA, false, op.WriteCC); } @@ -107,8 +107,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDmulC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); EmitFmul(context, Instruction.FP64, MultiplyScale.NoScale, srcA, srcB, op.Dest, op.NegA, false, op.WriteCC); } @@ -117,8 +117,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFaddR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitFadd(context, Instruction.FP32, srcA, srcB, op.Dest, op.NegA, op.NegB, op.AbsA, op.AbsB, op.Sat, op.WriteCC); } @@ -127,8 +127,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFaddI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); EmitFadd(context, Instruction.FP32, srcA, srcB, op.Dest, op.NegA, op.NegB, op.AbsA, op.AbsB, op.Sat, op.WriteCC); } @@ -137,8 +137,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFaddC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitFadd(context, Instruction.FP32, srcA, srcB, op.Dest, op.NegA, op.NegB, op.AbsA, op.AbsB, op.Sat, op.WriteCC); } @@ -147,8 +147,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFadd32i op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, op.Imm32); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, op.Imm32); EmitFadd(context, Instruction.FP32, srcA, srcB, op.Dest, op.NegA, op.NegB, op.AbsA, op.AbsB, false, op.WriteCC); } @@ -157,9 +157,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFfmaR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcC = GetSrcReg(context, op.SrcC); EmitFfma(context, Instruction.FP32, srcA, srcB, srcC, op.Dest, op.NegA, op.NegC, op.Sat, op.WriteCC); } @@ -168,9 +168,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFfmaI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); + Operand srcC = GetSrcReg(context, op.SrcC); EmitFfma(context, Instruction.FP32, srcA, srcB, srcC, op.Dest, op.NegA, op.NegC, op.Sat, op.WriteCC); } @@ -179,9 +179,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFfmaC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcC = GetSrcReg(context, op.SrcC); EmitFfma(context, Instruction.FP32, srcA, srcB, srcC, op.Dest, op.NegA, op.NegC, op.Sat, op.WriteCC); } @@ -190,9 +190,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFfmaRc op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcC); - var srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcC); + Operand srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitFfma(context, Instruction.FP32, srcA, srcB, srcC, op.Dest, op.NegA, op.NegC, op.Sat, op.WriteCC); } @@ -201,9 +201,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFfma32i op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, op.Imm32); - var srcC = GetSrcReg(context, op.Dest); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, op.Imm32); + Operand srcC = GetSrcReg(context, op.Dest); EmitFfma(context, Instruction.FP32, srcA, srcB, srcC, op.Dest, op.NegA, op.NegC, op.Sat, op.WriteCC); } @@ -212,8 +212,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFmulR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitFmul(context, Instruction.FP32, op.Scale, srcA, srcB, op.Dest, op.NegA, op.Sat, op.WriteCC); } @@ -222,8 +222,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFmulI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); EmitFmul(context, Instruction.FP32, op.Scale, srcA, srcB, op.Dest, op.NegA, op.Sat, op.WriteCC); } @@ -232,8 +232,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFmulC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitFmul(context, Instruction.FP32, op.Scale, srcA, srcB, op.Dest, op.NegA, op.Sat, op.WriteCC); } @@ -242,8 +242,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFmul32i op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, op.Imm32); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, op.Imm32); EmitFmul(context, Instruction.FP32, MultiplyScale.NoScale, srcA, srcB, op.Dest, false, op.Sat, op.WriteCC); } @@ -252,8 +252,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHadd2R op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); - var srcB = GetHalfSrc(context, op.BSwizzle, op.SrcB, op.NegB, op.AbsB); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); + Operand[] srcB = GetHalfSrc(context, op.BSwizzle, op.SrcB, op.NegB, op.AbsB); EmitHadd2Hmul2(context, op.OFmt, srcA, srcB, isAdd: true, op.Dest, op.Sat); } @@ -262,8 +262,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHadd2I op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); - var srcB = GetHalfSrc(context, op.BimmH0, op.BimmH1); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); + Operand[] srcB = GetHalfSrc(context, op.BimmH0, op.BimmH1); EmitHadd2Hmul2(context, op.OFmt, srcA, srcB, isAdd: true, op.Dest, op.Sat); } @@ -272,8 +272,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHadd2C op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); - var srcB = GetHalfSrc(context, HalfSwizzle.F32, op.CbufSlot, op.CbufOffset, op.NegB, op.AbsB); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); + Operand[] srcB = GetHalfSrc(context, HalfSwizzle.F32, op.CbufSlot, op.CbufOffset, op.NegB, op.AbsB); EmitHadd2Hmul2(context, op.OFmt, srcA, srcB, isAdd: true, op.Dest, op.Sat); } @@ -282,8 +282,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHadd232i op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, false); - var srcB = GetHalfSrc(context, op.Imm); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, false); + Operand[] srcB = GetHalfSrc(context, op.Imm); EmitHadd2Hmul2(context, OFmt.F16, srcA, srcB, isAdd: true, op.Dest, op.Sat); } @@ -292,9 +292,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHfma2R op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, false); - var srcB = GetHalfSrc(context, op.BSwizzle, op.SrcB, op.NegA, false); - var srcC = GetHalfSrc(context, op.CSwizzle, op.SrcC, op.NegC, false); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, false); + Operand[] srcB = GetHalfSrc(context, op.BSwizzle, op.SrcB, op.NegA, false); + Operand[] srcC = GetHalfSrc(context, op.CSwizzle, op.SrcC, op.NegC, false); EmitHfma2(context, op.OFmt, srcA, srcB, srcC, op.Dest, op.Sat); } @@ -303,9 +303,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHfma2I op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, false); - var srcB = GetHalfSrc(context, op.BimmH0, op.BimmH1); - var srcC = GetHalfSrc(context, op.CSwizzle, op.SrcC, op.NegC, false); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, false); + Operand[] srcB = GetHalfSrc(context, op.BimmH0, op.BimmH1); + Operand[] srcC = GetHalfSrc(context, op.CSwizzle, op.SrcC, op.NegC, false); EmitHfma2(context, op.OFmt, srcA, srcB, srcC, op.Dest, op.Sat); } @@ -314,9 +314,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHfma2C op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, false); - var srcB = GetHalfSrc(context, HalfSwizzle.F32, op.CbufSlot, op.CbufOffset, op.NegA, false); - var srcC = GetHalfSrc(context, op.CSwizzle, op.SrcC, op.NegC, false); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, false); + Operand[] srcB = GetHalfSrc(context, HalfSwizzle.F32, op.CbufSlot, op.CbufOffset, op.NegA, false); + Operand[] srcC = GetHalfSrc(context, op.CSwizzle, op.SrcC, op.NegC, false); EmitHfma2(context, op.OFmt, srcA, srcB, srcC, op.Dest, op.Sat); } @@ -325,9 +325,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHfma2Rc op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, false); - var srcB = GetHalfSrc(context, op.CSwizzle, op.SrcC, op.NegA, false); - var srcC = GetHalfSrc(context, HalfSwizzle.F32, op.CbufSlot, op.CbufOffset, op.NegC, false); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, false); + Operand[] srcB = GetHalfSrc(context, op.CSwizzle, op.SrcC, op.NegA, false); + Operand[] srcC = GetHalfSrc(context, HalfSwizzle.F32, op.CbufSlot, op.CbufOffset, op.NegC, false); EmitHfma2(context, op.OFmt, srcA, srcB, srcC, op.Dest, op.Sat); } @@ -336,9 +336,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHfma232i op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, false); - var srcB = GetHalfSrc(context, op.Imm); - var srcC = GetHalfSrc(context, HalfSwizzle.F16, op.Dest, op.NegC, false); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, false); + Operand[] srcB = GetHalfSrc(context, op.Imm); + Operand[] srcC = GetHalfSrc(context, HalfSwizzle.F16, op.Dest, op.NegC, false); EmitHfma2(context, OFmt.F16, srcA, srcB, srcC, op.Dest, saturate: false); } @@ -347,8 +347,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHmul2R op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, op.AbsA); - var srcB = GetHalfSrc(context, op.BSwizzle, op.SrcB, op.NegA, op.AbsB); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, op.AbsA); + Operand[] srcB = GetHalfSrc(context, op.BSwizzle, op.SrcB, op.NegA, op.AbsB); EmitHadd2Hmul2(context, op.OFmt, srcA, srcB, isAdd: false, op.Dest, op.Sat); } @@ -357,8 +357,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHmul2I op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); - var srcB = GetHalfSrc(context, op.BimmH0, op.BimmH1); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); + Operand[] srcB = GetHalfSrc(context, op.BimmH0, op.BimmH1); EmitHadd2Hmul2(context, op.OFmt, srcA, srcB, isAdd: false, op.Dest, op.Sat); } @@ -367,8 +367,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHmul2C op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, op.AbsA); - var srcB = GetHalfSrc(context, HalfSwizzle.F32, op.CbufSlot, op.CbufOffset, op.NegA, op.AbsB); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, op.AbsA); + Operand[] srcB = GetHalfSrc(context, HalfSwizzle.F32, op.CbufSlot, op.CbufOffset, op.NegA, op.AbsB); EmitHadd2Hmul2(context, op.OFmt, srcA, srcB, isAdd: false, op.Dest, op.Sat); } @@ -377,8 +377,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHmul232i op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, false); - var srcB = GetHalfSrc(context, op.Imm32); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, false, false); + Operand[] srcB = GetHalfSrc(context, op.Imm32); EmitHadd2Hmul2(context, OFmt.F16, srcA, srcB, isAdd: false, op.Dest, op.Sat); } diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFloatComparison.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFloatComparison.cs index 59ad7a5de..314ab917c 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFloatComparison.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFloatComparison.cs @@ -14,8 +14,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDsetR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcReg(context, op.SrcB, isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcReg(context, op.SrcB, isFP64: true); EmitFset( context, @@ -39,8 +39,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDsetI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20), isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20), isFP64: true); EmitFset( context, @@ -64,8 +64,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDsetC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); EmitFset( context, @@ -89,8 +89,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDsetpR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcReg(context, op.SrcB, isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcReg(context, op.SrcB, isFP64: true); EmitFsetp( context, @@ -114,8 +114,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDsetpI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20), isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20), isFP64: true); EmitFsetp( context, @@ -139,8 +139,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDsetpC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); EmitFsetp( context, @@ -164,9 +164,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFcmpR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcC = GetSrcReg(context, op.SrcC); EmitFcmp(context, op.FComp, srcA, srcB, srcC, op.Dest); } @@ -175,9 +175,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFcmpI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); + Operand srcC = GetSrcReg(context, op.SrcC); EmitFcmp(context, op.FComp, srcA, srcB, srcC, op.Dest); } @@ -186,9 +186,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFcmpC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcC = GetSrcReg(context, op.SrcC); EmitFcmp(context, op.FComp, srcA, srcB, srcC, op.Dest); } @@ -197,9 +197,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFcmpRc op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcC); - var srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcC); + Operand srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitFcmp(context, op.FComp, srcA, srcB, srcC, op.Dest); } @@ -208,8 +208,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFsetR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitFset(context, op.FComp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.Dest, op.AbsA, op.AbsB, op.NegA, op.NegB, op.BVal, op.WriteCC); } @@ -218,8 +218,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFsetC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitFset(context, op.FComp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.Dest, op.AbsA, op.AbsB, op.NegA, op.NegB, op.BVal, op.WriteCC); } @@ -228,8 +228,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFsetI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); EmitFset(context, op.FComp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.Dest, op.AbsA, op.AbsB, op.NegA, op.NegB, op.BVal, op.WriteCC); } @@ -238,8 +238,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFsetpR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitFsetp( context, @@ -262,8 +262,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFsetpI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); EmitFsetp( context, @@ -286,8 +286,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFsetpC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitFsetp( context, @@ -310,8 +310,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHset2R op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); - var srcB = GetHalfSrc(context, op.BSwizzle, op.SrcB, op.NegB, op.AbsB); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); + Operand[] srcB = GetHalfSrc(context, op.BSwizzle, op.SrcB, op.NegB, op.AbsB); EmitHset2(context, op.Cmp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.Dest, op.Bval); } @@ -320,8 +320,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHset2I op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); - var srcB = GetHalfSrc(context, op.BimmH0, op.BimmH1); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); + Operand[] srcB = GetHalfSrc(context, op.BimmH0, op.BimmH1); EmitHset2(context, op.Cmp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.Dest, op.Bval); } @@ -330,8 +330,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHset2C op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); - var srcB = GetHalfSrc(context, HalfSwizzle.F32, op.CbufSlot, op.CbufOffset, op.NegB, false); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); + Operand[] srcB = GetHalfSrc(context, HalfSwizzle.F32, op.CbufSlot, op.CbufOffset, op.NegB, false); EmitHset2(context, op.Cmp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.Dest, op.Bval); } @@ -340,8 +340,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHsetp2R op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); - var srcB = GetHalfSrc(context, op.BSwizzle, op.SrcB, op.NegB, op.AbsB); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); + Operand[] srcB = GetHalfSrc(context, op.BSwizzle, op.SrcB, op.NegB, op.AbsB); EmitHsetp2(context, op.FComp2, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.DestPred, op.DestPredInv, op.HAnd); } @@ -350,8 +350,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHsetp2I op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); - var srcB = GetHalfSrc(context, op.BimmH0, op.BimmH1); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); + Operand[] srcB = GetHalfSrc(context, op.BimmH0, op.BimmH1); EmitHsetp2(context, op.FComp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.DestPred, op.DestPredInv, op.HAnd); } @@ -360,8 +360,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstHsetp2C op = context.GetOp(); - var srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); - var srcB = GetHalfSrc(context, HalfSwizzle.F32, op.CbufSlot, op.CbufOffset, op.NegB, op.AbsB); + Operand[] srcA = GetHalfSrc(context, op.ASwizzle, op.SrcA, op.NegA, op.AbsA); + Operand[] srcB = GetHalfSrc(context, HalfSwizzle.F32, op.CbufSlot, op.CbufOffset, op.NegB, op.AbsB); EmitHsetp2(context, op.FComp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.DestPred, op.DestPredInv, op.HAnd); } @@ -545,7 +545,7 @@ namespace Ryujinx.Graphics.Shader.Instructions } else { - var inst = (cond & ~FComp.Nan) switch + Instruction inst = (cond & ~FComp.Nan) switch { FComp.Lt => Instruction.CompareLess, FComp.Eq => Instruction.CompareEqual, diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFloatMinMax.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFloatMinMax.cs index 5757e4fb0..4a3337bca 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFloatMinMax.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFloatMinMax.cs @@ -13,9 +13,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDmnmxR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcReg(context, op.SrcB, isFP64: true); - var srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcReg(context, op.SrcB, isFP64: true); + Operand srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); EmitFmnmx(context, srcA, srcB, srcPred, op.Dest, op.AbsA, op.AbsB, op.NegA, op.NegB, op.WriteCC, isFP64: true); } @@ -24,9 +24,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDmnmxI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20), isFP64: true); - var srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20), isFP64: true); + Operand srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); EmitFmnmx(context, srcA, srcB, srcPred, op.Dest, op.AbsA, op.AbsB, op.NegA, op.NegB, op.WriteCC, isFP64: true); } @@ -35,9 +35,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstDmnmxC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA, isFP64: true); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); - var srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); + Operand srcA = GetSrcReg(context, op.SrcA, isFP64: true); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset, isFP64: true); + Operand srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); EmitFmnmx(context, srcA, srcB, srcPred, op.Dest, op.AbsA, op.AbsB, op.NegA, op.NegB, op.WriteCC, isFP64: true); } @@ -46,9 +46,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFmnmxR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); EmitFmnmx(context, srcA, srcB, srcPred, op.Dest, op.AbsA, op.AbsB, op.NegA, op.NegB, op.WriteCC); } @@ -57,9 +57,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFmnmxI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); - var srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToFloat(op.Imm20)); + Operand srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); EmitFmnmx(context, srcA, srcB, srcPred, op.Dest, op.AbsA, op.AbsB, op.NegA, op.NegB, op.WriteCC); } @@ -68,9 +68,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstFmnmxC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); - var srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); EmitFmnmx(context, srcA, srcB, srcPred, op.Dest, op.AbsA, op.AbsB, op.NegA, op.NegB, op.WriteCC); } diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFlowControl.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFlowControl.cs index 803aaa62d..e86328868 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFlowControl.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitFlowControl.cs @@ -39,13 +39,13 @@ namespace Ryujinx.Graphics.Shader.Instructions Operand address = context.IAdd(Register(op.SrcA, RegisterType.Gpr), Const(offset)); - var targets = context.CurrBlock.Successors.Skip(startIndex); + IEnumerable targets = context.CurrBlock.Successors.Skip(startIndex); bool allTargetsSinglePred = true; int total = context.CurrBlock.Successors.Count - startIndex; int count = 0; - foreach (var target in targets.OrderBy(x => x.Address)) + foreach (Block target in targets.OrderBy(x => x.Address)) { if (++count < total && (target.Predecessors.Count > 1 || target.Address <= context.CurrBlock.Address)) { @@ -64,7 +64,7 @@ namespace Ryujinx.Graphics.Shader.Instructions // since it will be too late to insert a label, but this is something that can be improved // in the future if necessary. - var sortedTargets = targets.OrderBy(x => x.Address); + IOrderedEnumerable sortedTargets = targets.OrderBy(x => x.Address); Block currentTarget = null; ulong firstTargetAddress = 0; @@ -93,7 +93,7 @@ namespace Ryujinx.Graphics.Shader.Instructions // Emit the branches sequentially. // This generates slightly worse code, but should work for all cases. - var sortedTargets = targets.OrderByDescending(x => x.Address); + IOrderedEnumerable sortedTargets = targets.OrderByDescending(x => x.Address); ulong lastTargetAddress = ulong.MaxValue; count = 0; @@ -238,7 +238,7 @@ namespace Ryujinx.Graphics.Shader.Instructions private static void EmitPbkPcntSsy(EmitterContext context) { - var consumers = context.CurrBlock.PushOpCodes.First(x => x.Op.Address == context.CurrOp.Address).Consumers; + Dictionary consumers = context.CurrBlock.PushOpCodes.First(x => x.Op.Address == context.CurrOp.Address).Consumers; foreach (KeyValuePair kv in consumers) { @@ -253,7 +253,7 @@ namespace Ryujinx.Graphics.Shader.Instructions private static void EmitBrkContSync(EmitterContext context) { - var targets = context.CurrBlock.SyncTargets; + Dictionary targets = context.CurrBlock.SyncTargets; if (targets.Count == 1) { diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerArithmetic.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerArithmetic.cs index 99922f7a1..2f3988119 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerArithmetic.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerArithmetic.cs @@ -14,8 +14,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIaddR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitIadd(context, srcA, srcB, op.Dest, op.AvgMode, op.X, op.WriteCC); } @@ -24,8 +24,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIaddI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); EmitIadd(context, srcA, srcB, op.Dest, op.AvgMode, op.X, op.WriteCC); } @@ -34,8 +34,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIaddC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitIadd(context, srcA, srcB, op.Dest, op.AvgMode, op.X, op.WriteCC); } @@ -44,8 +44,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIadd32i op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, op.Imm32); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, op.Imm32); EmitIadd(context, srcA, srcB, op.Dest, op.AvgMode, op.X, op.WriteCC); } @@ -54,9 +54,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIadd3R op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcC = GetSrcReg(context, op.SrcC); EmitIadd3(context, op.Lrs, srcA, srcB, srcC, op.Apart, op.Bpart, op.Cpart, op.Dest, op.NegA, op.NegB, op.NegC); } @@ -65,9 +65,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIadd3I op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcC = GetSrcReg(context, op.SrcC); EmitIadd3(context, Lrs.None, srcA, srcB, srcC, HalfSelect.B32, HalfSelect.B32, HalfSelect.B32, op.Dest, op.NegA, op.NegB, op.NegC); } @@ -76,9 +76,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIadd3C op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcC = GetSrcReg(context, op.SrcC); EmitIadd3(context, Lrs.None, srcA, srcB, srcC, HalfSelect.B32, HalfSelect.B32, HalfSelect.B32, op.Dest, op.NegA, op.NegB, op.NegC); } @@ -87,9 +87,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstImadR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcC = GetSrcReg(context, op.SrcC); EmitImad(context, srcA, srcB, srcC, op.Dest, op.AvgMode, op.ASigned, op.BSigned, op.Hilo); } @@ -98,9 +98,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstImadI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcC = GetSrcReg(context, op.SrcC); EmitImad(context, srcA, srcB, srcC, op.Dest, op.AvgMode, op.ASigned, op.BSigned, op.Hilo); } @@ -109,9 +109,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstImadC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcC = GetSrcReg(context, op.SrcC); EmitImad(context, srcA, srcB, srcC, op.Dest, op.AvgMode, op.ASigned, op.BSigned, op.Hilo); } @@ -120,9 +120,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstImadRc op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcC); - var srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcC); + Operand srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitImad(context, srcA, srcB, srcC, op.Dest, op.AvgMode, op.ASigned, op.BSigned, op.Hilo); } @@ -131,9 +131,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstImad32i op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, op.Imm32); - var srcC = GetSrcReg(context, op.Dest); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, op.Imm32); + Operand srcC = GetSrcReg(context, op.Dest); EmitImad(context, srcA, srcB, srcC, op.Dest, op.AvgMode, op.ASigned, op.BSigned, op.Hilo); } @@ -142,8 +142,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstImulR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitImad(context, srcA, srcB, Const(0), op.Dest, AvgMode.NoNeg, op.ASigned, op.BSigned, op.Hilo); } @@ -152,8 +152,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstImulI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); EmitImad(context, srcA, srcB, Const(0), op.Dest, AvgMode.NoNeg, op.ASigned, op.BSigned, op.Hilo); } @@ -162,8 +162,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstImulC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitImad(context, srcA, srcB, Const(0), op.Dest, AvgMode.NoNeg, op.ASigned, op.BSigned, op.Hilo); } @@ -172,8 +172,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstImul32i op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, op.Imm32); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, op.Imm32); EmitImad(context, srcA, srcB, Const(0), op.Dest, AvgMode.NoNeg, op.ASigned, op.BSigned, op.Hilo); } @@ -182,8 +182,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIscaddR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitIscadd(context, srcA, srcB, op.Dest, op.Imm5, op.AvgMode, op.WriteCC); } @@ -192,8 +192,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIscaddI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); EmitIscadd(context, srcA, srcB, op.Dest, op.Imm5, op.AvgMode, op.WriteCC); } @@ -202,8 +202,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIscaddC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitIscadd(context, srcA, srcB, op.Dest, op.Imm5, op.AvgMode, op.WriteCC); } @@ -212,8 +212,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIscadd32i op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, op.Imm32); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, op.Imm32); EmitIscadd(context, srcA, srcB, op.Dest, op.Imm5, AvgMode.NoNeg, op.WriteCC); } @@ -222,8 +222,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstLeaR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitLea(context, srcA, srcB, op.Dest, op.NegA, op.ImmU5); } @@ -232,8 +232,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstLeaI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); EmitLea(context, srcA, srcB, op.Dest, op.NegA, op.ImmU5); } @@ -242,8 +242,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstLeaC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitLea(context, srcA, srcB, op.Dest, op.NegA, op.ImmU5); } @@ -252,9 +252,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstLeaHiR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcC = GetSrcReg(context, op.SrcC); EmitLeaHi(context, srcA, srcB, srcC, op.Dest, op.NegA, op.ImmU5); } @@ -263,9 +263,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstLeaHiC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcC = GetSrcReg(context, op.SrcC); EmitLeaHi(context, srcA, srcB, srcC, op.Dest, op.NegA, op.ImmU5); } @@ -274,9 +274,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstXmadR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcC = GetSrcReg(context, op.SrcC); EmitXmad(context, op.XmadCop, srcA, srcB, srcC, op.Dest, op.ASigned, op.BSigned, op.HiloA, op.HiloB, op.Psl, op.Mrg, op.X, op.WriteCC); } @@ -285,9 +285,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstXmadI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, op.Imm16); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, op.Imm16); + Operand srcC = GetSrcReg(context, op.SrcC); EmitXmad(context, op.XmadCop, srcA, srcB, srcC, op.Dest, op.ASigned, op.BSigned, op.HiloA, false, op.Psl, op.Mrg, op.X, op.WriteCC); } @@ -296,9 +296,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstXmadC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcC = GetSrcReg(context, op.SrcC); EmitXmad(context, op.XmadCop, srcA, srcB, srcC, op.Dest, op.ASigned, op.BSigned, op.HiloA, op.HiloB, op.Psl, op.Mrg, op.X, op.WriteCC); } @@ -307,9 +307,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstXmadRc op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcC); - var srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcC); + Operand srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitXmad(context, op.XmadCop, srcA, srcB, srcC, op.Dest, op.ASigned, op.BSigned, op.HiloA, op.HiloB, false, false, op.X, op.WriteCC); } @@ -578,7 +578,7 @@ namespace Ryujinx.Graphics.Shader.Instructions bool extended, bool writeCC) { - var srcBUnmodified = srcB; + Operand srcBUnmodified = srcB; Operand Extend16To32(Operand src, bool high, bool signed) { diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerComparison.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerComparison.cs index 18d4e3d19..c97e53bfe 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerComparison.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerComparison.cs @@ -14,9 +14,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIcmpR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcC = GetSrcReg(context, op.SrcC); EmitIcmp(context, op.IComp, srcA, srcB, srcC, op.Dest, op.Signed); } @@ -25,9 +25,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIcmpI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcC = GetSrcReg(context, op.SrcC); EmitIcmp(context, op.IComp, srcA, srcB, srcC, op.Dest, op.Signed); } @@ -36,9 +36,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIcmpC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcC = GetSrcReg(context, op.SrcC); EmitIcmp(context, op.IComp, srcA, srcB, srcC, op.Dest, op.Signed); } @@ -47,9 +47,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIcmpRc op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcC); - var srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcC); + Operand srcC = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitIcmp(context, op.IComp, srcA, srcB, srcC, op.Dest, op.Signed); } @@ -58,8 +58,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIsetR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitIset(context, op.IComp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.Dest, op.BVal, op.Signed, op.X, op.WriteCC); } @@ -68,8 +68,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIsetI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); EmitIset(context, op.IComp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.Dest, op.BVal, op.Signed, op.X, op.WriteCC); } @@ -78,8 +78,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIsetC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitIset(context, op.IComp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.Dest, op.BVal, op.Signed, op.X, op.WriteCC); } @@ -88,8 +88,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIsetpR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitIsetp(context, op.IComp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.DestPred, op.DestPredInv, op.Signed, op.X); } @@ -98,8 +98,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIsetpI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); EmitIsetp(context, op.IComp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.DestPred, op.DestPredInv, op.Signed, op.X); } @@ -108,8 +108,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstIsetpC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitIsetp(context, op.IComp, op.Bop, srcA, srcB, op.SrcPred, op.SrcPredInv, op.DestPred, op.DestPredInv, op.Signed, op.X); } @@ -280,7 +280,7 @@ namespace Ryujinx.Graphics.Shader.Instructions } else { - var inst = cond switch + Instruction inst = cond switch { IComp.Lt => Instruction.CompareLessU32, IComp.Eq => Instruction.CompareEqual, diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerLogical.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerLogical.cs index 5993c93dd..2e2d951d2 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerLogical.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerLogical.cs @@ -15,8 +15,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstLopR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitLop(context, op.Lop, op.PredicateOp, srcA, srcB, op.Dest, op.DestPred, op.NegA, op.NegB, op.X, op.WriteCC); } @@ -25,8 +25,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstLopI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); EmitLop(context, op.LogicOp, op.PredicateOp, srcA, srcB, op.Dest, op.DestPred, op.NegA, op.NegB, op.X, op.WriteCC); } @@ -35,8 +35,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstLopC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitLop(context, op.LogicOp, op.PredicateOp, srcA, srcB, op.Dest, op.DestPred, op.NegA, op.NegB, op.X, op.WriteCC); } @@ -45,8 +45,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstLop32i op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, op.Imm32); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, op.Imm32); EmitLop(context, op.LogicOp, PredicateOp.F, srcA, srcB, op.Dest, PT, op.NegA, op.NegB, op.X, op.WriteCC); } @@ -55,9 +55,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstLop3R op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcC = GetSrcReg(context, op.SrcC); EmitLop3(context, op.Imm, op.PredicateOp, srcA, srcB, srcC, op.Dest, op.DestPred, op.X, op.WriteCC); } @@ -66,9 +66,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstLop3I op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcC = GetSrcReg(context, op.SrcC); EmitLop3(context, op.Imm, PredicateOp.F, srcA, srcB, srcC, op.Dest, PT, false, op.WriteCC); } @@ -77,9 +77,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstLop3C op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcC = GetSrcReg(context, op.SrcC); EmitLop3(context, op.Imm, PredicateOp.F, srcA, srcB, srcC, op.Dest, PT, false, op.WriteCC); } diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerMinMax.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerMinMax.cs index 739e94413..f34efc6f3 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerMinMax.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitIntegerMinMax.cs @@ -13,9 +13,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstImnmxR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); EmitImnmx(context, srcA, srcB, srcPred, op.Dest, op.Signed, op.WriteCC); } @@ -24,9 +24,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstImnmxI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); - var srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); EmitImnmx(context, srcA, srcB, srcPred, op.Dest, op.Signed, op.WriteCC); } @@ -35,9 +35,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstImnmxC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); - var srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcPred = GetPredicate(context, op.SrcPred, op.SrcPredInv); EmitImnmx(context, srcA, srcB, srcPred, op.Dest, op.Signed, op.WriteCC); } diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitShift.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitShift.cs index ee0dac155..7e2145c37 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitShift.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitShift.cs @@ -13,9 +13,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstShfLR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcC = GetSrcReg(context, op.SrcC); EmitShf(context, op.MaxShift, srcA, srcB, srcC, op.Dest, op.M, left: true, op.WriteCC); } @@ -24,9 +24,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstShfRR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); + Operand srcC = GetSrcReg(context, op.SrcC); EmitShf(context, op.MaxShift, srcA, srcB, srcC, op.Dest, op.M, left: false, op.WriteCC); } @@ -35,9 +35,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstShfLI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = Const(op.Imm6); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = Const(op.Imm6); + Operand srcC = GetSrcReg(context, op.SrcC); EmitShf(context, op.MaxShift, srcA, srcB, srcC, op.Dest, op.M, left: true, op.WriteCC); } @@ -46,9 +46,9 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstShfRI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = Const(op.Imm6); - var srcC = GetSrcReg(context, op.SrcC); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = Const(op.Imm6); + Operand srcC = GetSrcReg(context, op.SrcC); EmitShf(context, op.MaxShift, srcA, srcB, srcC, op.Dest, op.M, left: false, op.WriteCC); } @@ -78,8 +78,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstShrR op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcReg(context, op.SrcB); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcReg(context, op.SrcB); EmitShr(context, srcA, srcB, op.Dest, op.M, op.Brev, op.Signed); } @@ -88,8 +88,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstShrI op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcImm(context, Imm20ToSInt(op.Imm20)); EmitShr(context, srcA, srcB, op.Dest, op.M, op.Brev, op.Signed); } @@ -98,8 +98,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstShrC op = context.GetOp(); - var srcA = GetSrcReg(context, op.SrcA); - var srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); + Operand srcA = GetSrcReg(context, op.SrcA); + Operand srcB = GetSrcCbuf(context, op.CbufSlot, op.CbufOffset); EmitShr(context, srcA, srcB, op.Dest, op.M, op.Brev, op.Signed); } diff --git a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitTexture.cs b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitTexture.cs index 2076262da..52a004c0e 100644 --- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitTexture.cs +++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitTexture.cs @@ -57,7 +57,7 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstTld op = context.GetOp(); - var lod = op.Lod ? Lod.Ll : Lod.Lz; + Lod lod = op.Lod ? Lod.Ll : Lod.Lz; EmitTex(context, TextureFlags.IntCoords, op.Dim, lod, op.TidB, op.WMask, op.SrcA, op.SrcB, op.Dest, op.Ms, false, op.Toff); } @@ -66,8 +66,8 @@ namespace Ryujinx.Graphics.Shader.Instructions { InstTldB op = context.GetOp(); - var flags = TextureFlags.IntCoords | TextureFlags.Bindless; - var lod = op.Lod ? Lod.Ll : Lod.Lz; + TextureFlags flags = TextureFlags.IntCoords | TextureFlags.Bindless; + Lod lod = op.Lod ? Lod.Ll : Lod.Lz; EmitTex(context, flags, op.Dim, lod, 0, op.WMask, op.SrcA, op.SrcB, op.Dest, op.Ms, false, op.Toff); } @@ -376,7 +376,7 @@ namespace Ryujinx.Graphics.Shader.Instructions if (texsType == TexsType.Texs) { - var texsOp = context.GetOp(); + InstTexs texsOp = context.GetOp(); type = ConvertSamplerType(texsOp.Target); @@ -468,7 +468,7 @@ namespace Ryujinx.Graphics.Shader.Instructions } else if (texsType == TexsType.Tlds) { - var tldsOp = context.GetOp(); + InstTlds tldsOp = context.GetOp(); type = ConvertSamplerType(tldsOp.Target); @@ -562,7 +562,7 @@ namespace Ryujinx.Graphics.Shader.Instructions } else if (texsType == TexsType.Tld4s) { - var tld4sOp = context.GetOp(); + InstTld4s tld4sOp = context.GetOp(); if (!(tld4sOp.Dc || tld4sOp.Aoffi)) { diff --git a/src/Ryujinx.Graphics.Shader/SamplerType.cs b/src/Ryujinx.Graphics.Shader/SamplerType.cs index 18285cd70..20352d13e 100644 --- a/src/Ryujinx.Graphics.Shader/SamplerType.cs +++ b/src/Ryujinx.Graphics.Shader/SamplerType.cs @@ -192,7 +192,7 @@ namespace Ryujinx.Graphics.Shader typeName += "_array"; } - var format = aggregateType switch + string format = aggregateType switch { AggregateType.S32 => "int", AggregateType.U32 => "uint", diff --git a/src/Ryujinx.Graphics.Shader/StructuredIr/ShaderProperties.cs b/src/Ryujinx.Graphics.Shader/StructuredIr/ShaderProperties.cs index 53ed6bfcc..f56d7bff3 100644 --- a/src/Ryujinx.Graphics.Shader/StructuredIr/ShaderProperties.cs +++ b/src/Ryujinx.Graphics.Shader/StructuredIr/ShaderProperties.cs @@ -73,7 +73,7 @@ namespace Ryujinx.Graphics.Shader.StructuredIr return TextureFormat.Unknown; } - var format = gpuAccessor.QueryTextureFormat(handle, cbufSlot); + TextureFormat format = gpuAccessor.QueryTextureFormat(handle, cbufSlot); if (format == TextureFormat.Unknown) { @@ -95,7 +95,7 @@ namespace Ryujinx.Graphics.Shader.StructuredIr // Atomic image instructions do not support GL_EXT_shader_image_load_formatted, // and must have a type specified. Default to R32Sint if not available. - var format = gpuAccessor.QueryTextureFormat(handle, cbufSlot); + TextureFormat format = gpuAccessor.QueryTextureFormat(handle, cbufSlot); if (!FormatSupportsAtomic(format)) { diff --git a/src/Ryujinx.Graphics.Shader/Translation/EmitterContext.cs b/src/Ryujinx.Graphics.Shader/Translation/EmitterContext.cs index 5e07b39f1..25ecb8621 100644 --- a/src/Ryujinx.Graphics.Shader/Translation/EmitterContext.cs +++ b/src/Ryujinx.Graphics.Shader/Translation/EmitterContext.cs @@ -1,5 +1,6 @@ using Ryujinx.Graphics.Shader.Decoders; using Ryujinx.Graphics.Shader.IntermediateRepresentation; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Numerics; @@ -256,8 +257,8 @@ namespace Ryujinx.Graphics.Shader.Translation for (int tfbIndex = 0; tfbIndex < ResourceReservations.TfeBuffersCount; tfbIndex++) { - var locations = TranslatorContext.GpuAccessor.QueryTransformFeedbackVaryingLocations(tfbIndex); - var stride = TranslatorContext.GpuAccessor.QueryTransformFeedbackStride(tfbIndex); + ReadOnlySpan locations = TranslatorContext.GpuAccessor.QueryTransformFeedbackVaryingLocations(tfbIndex); + int stride = TranslatorContext.GpuAccessor.QueryTransformFeedbackStride(tfbIndex); Operand baseOffset = this.Load(StorageKind.ConstantBuffer, SupportBuffer.Binding, Const((int)SupportBufferField.TfeOffset), Const(tfbIndex)); Operand baseVertex = this.Load(StorageKind.Input, IoVariable.BaseVertex); diff --git a/src/Ryujinx.Graphics.Shader/Translation/FunctionMatch.cs b/src/Ryujinx.Graphics.Shader/Translation/FunctionMatch.cs index b792776df..ba9685433 100644 --- a/src/Ryujinx.Graphics.Shader/Translation/FunctionMatch.cs +++ b/src/Ryujinx.Graphics.Shader/Translation/FunctionMatch.cs @@ -490,8 +490,8 @@ namespace Ryujinx.Graphics.Shader.Translation for (int index = 0; index < pTreeNode.Uses.Count; index++) { - var pUse = pTreeNode.Uses[index]; - var cUse = cTreeNode.Uses[index]; + PatternTreeNodeUse pUse = pTreeNode.Uses[index]; + TreeNodeUse cUse = cTreeNode.Uses[index]; if (pUse.Index <= -2) { @@ -524,8 +524,8 @@ namespace Ryujinx.Graphics.Shader.Translation { public static IPatternTreeNode[] GetFsiGetAddress() { - var affinityValue = S2r(SReg.Affinity).Use(PT).Out; - var orderingTicketValue = S2r(SReg.OrderingTicket).Use(PT).Out; + PatternTreeNodeUse affinityValue = S2r(SReg.Affinity).Use(PT).Out; + PatternTreeNodeUse orderingTicketValue = S2r(SReg.OrderingTicket).Use(PT).Out; return new IPatternTreeNode[] { @@ -554,8 +554,8 @@ namespace Ryujinx.Graphics.Shader.Translation public static IPatternTreeNode[] GetFsiGetAddressV2() { - var affinityValue = S2r(SReg.Affinity).Use(PT).Out; - var orderingTicketValue = S2r(SReg.OrderingTicket).Use(PT).Out; + PatternTreeNodeUse affinityValue = S2r(SReg.Affinity).Use(PT).Out; + PatternTreeNodeUse orderingTicketValue = S2r(SReg.OrderingTicket).Use(PT).Out; return new IPatternTreeNode[] { @@ -582,8 +582,8 @@ namespace Ryujinx.Graphics.Shader.Translation public static IPatternTreeNode[] GetFsiIsLastWarpThread() { - var threadKillValue = S2r(SReg.ThreadKill).Use(PT).Out; - var laneIdValue = S2r(SReg.LaneId).Use(PT).Out; + PatternTreeNodeUse threadKillValue = S2r(SReg.ThreadKill).Use(PT).Out; + PatternTreeNodeUse laneIdValue = S2r(SReg.LaneId).Use(PT).Out; return new IPatternTreeNode[] { @@ -609,11 +609,11 @@ namespace Ryujinx.Graphics.Shader.Translation public static IPatternTreeNode[] GetFsiBeginPattern() { - var addressLowValue = CallArg(1); + PatternTreeNodeUse addressLowValue = CallArg(1); static PatternTreeNodeUse HighU16Equals(PatternTreeNodeUse x) { - var expectedValue = CallArg(3); + PatternTreeNodeUse expectedValue = CallArg(3); return IsetpU32(IComp.Eq) .Use(PT) @@ -644,13 +644,13 @@ namespace Ryujinx.Graphics.Shader.Translation public static IPatternTreeNode[] GetFsiEndPattern() { - var voteResult = Vote(VoteMode.All).Use(PT).Use(PT).OutAt(1); - var popcResult = Popc().Use(PT).Use(voteResult).Out; - var threadKillValue = S2r(SReg.ThreadKill).Use(PT).Out; - var laneIdValue = S2r(SReg.LaneId).Use(PT).Out; + PatternTreeNodeUse voteResult = Vote(VoteMode.All).Use(PT).Use(PT).OutAt(1); + PatternTreeNodeUse popcResult = Popc().Use(PT).Use(voteResult).Out; + PatternTreeNodeUse threadKillValue = S2r(SReg.ThreadKill).Use(PT).Out; + PatternTreeNodeUse laneIdValue = S2r(SReg.LaneId).Use(PT).Out; - var addressLowValue = CallArg(1); - var incrementValue = CallArg(2); + PatternTreeNodeUse addressLowValue = CallArg(1); + PatternTreeNodeUse incrementValue = CallArg(2); return new IPatternTreeNode[] { diff --git a/src/Ryujinx.Graphics.Shader/Translation/Optimizations/GlobalToStorage.cs b/src/Ryujinx.Graphics.Shader/Translation/Optimizations/GlobalToStorage.cs index 8a730ef74..8628b3236 100644 --- a/src/Ryujinx.Graphics.Shader/Translation/Optimizations/GlobalToStorage.cs +++ b/src/Ryujinx.Graphics.Shader/Translation/Optimizations/GlobalToStorage.cs @@ -267,7 +267,7 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations { Operand value = operation.GetSource(operation.SourcesCount - 1); - var result = FindUniqueBaseAddressCb(gtsContext, block, value, needsOffset: false); + SearchResult result = FindUniqueBaseAddressCb(gtsContext, block, value, needsOffset: false); if (result.Found) { uint targetCb = PackCbSlotAndOffset(result.SbCbSlot, result.SbCbOffset); @@ -1018,7 +1018,7 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations offset = src1; } - var result = GetBaseAddressCbWithOffset(baseAddr, offset, 0); + SearchResult result = GetBaseAddressCbWithOffset(baseAddr, offset, 0); if (result.Found) { return result; diff --git a/src/Ryujinx.Graphics.Shader/Translation/RegisterUsage.cs b/src/Ryujinx.Graphics.Shader/Translation/RegisterUsage.cs index 1c724223c..2851381ae 100644 --- a/src/Ryujinx.Graphics.Shader/Translation/RegisterUsage.cs +++ b/src/Ryujinx.Graphics.Shader/Translation/RegisterUsage.cs @@ -302,7 +302,7 @@ namespace Ryujinx.Graphics.Shader.Translation Debug.Assert(funcId.Type == OperandType.Constant); - var fru = frus[funcId.Value]; + FunctionRegisterUsage fru = frus[funcId.Value]; Operand[] inRegs = new Operand[fru.InArguments.Length]; diff --git a/src/Ryujinx.Graphics.Shader/Translation/ResourceManager.cs b/src/Ryujinx.Graphics.Shader/Translation/ResourceManager.cs index 83e4dc0ac..c733e5b55 100644 --- a/src/Ryujinx.Graphics.Shader/Translation/ResourceManager.cs +++ b/src/Ryujinx.Graphics.Shader/Translation/ResourceManager.cs @@ -103,7 +103,7 @@ namespace Ryujinx.Graphics.Shader.Translation size = DefaultLocalMemorySize; } - var lmem = new MemoryDefinition("local_memory", AggregateType.Array | AggregateType.U32, BitUtils.DivRoundUp(size, sizeof(uint))); + MemoryDefinition lmem = new MemoryDefinition("local_memory", AggregateType.Array | AggregateType.U32, BitUtils.DivRoundUp(size, sizeof(uint))); LocalMemoryId = Properties.AddLocalMemory(lmem); } @@ -122,7 +122,7 @@ namespace Ryujinx.Graphics.Shader.Translation size = DefaultSharedMemorySize; } - var smem = new MemoryDefinition("shared_memory", AggregateType.Array | AggregateType.U32, BitUtils.DivRoundUp(size, sizeof(uint))); + MemoryDefinition smem = new MemoryDefinition("shared_memory", AggregateType.Array | AggregateType.U32, BitUtils.DivRoundUp(size, sizeof(uint))); SharedMemoryId = Properties.AddSharedMemory(smem); } @@ -283,16 +283,16 @@ namespace Ryujinx.Graphics.Shader.Translation bool coherent, bool separate) { - var dimensions = type == SamplerType.None ? 0 : type.GetDimensions(); - var dict = isImage ? _usedImages : _usedTextures; + int dimensions = type == SamplerType.None ? 0 : type.GetDimensions(); + Dictionary dict = isImage ? _usedImages : _usedTextures; - var usageFlags = TextureUsageFlags.None; + TextureUsageFlags usageFlags = TextureUsageFlags.None; if (intCoords) { usageFlags |= TextureUsageFlags.NeedsScaleValue; - var canScale = _stage.SupportsRenderScale() && arrayLength == 1 && !write && dimensions == 2; + bool canScale = _stage.SupportsRenderScale() && arrayLength == 1 && !write && dimensions == 2; if (!canScale) { @@ -314,9 +314,9 @@ namespace Ryujinx.Graphics.Shader.Translation // For array textures, we also want to use type as key, // since we may have texture handles stores in the same buffer, but for textures with different types. - var keyType = arrayLength > 1 ? type : SamplerType.None; - var info = new TextureInfo(cbufSlot, handle, arrayLength, separate, keyType, format); - var meta = new TextureMeta() + SamplerType keyType = arrayLength > 1 ? type : SamplerType.None; + TextureInfo info = new TextureInfo(cbufSlot, handle, arrayLength, separate, keyType, format); + TextureMeta meta = new TextureMeta() { AccurateType = accurateType, Type = type, @@ -326,7 +326,7 @@ namespace Ryujinx.Graphics.Shader.Translation int setIndex; int binding; - if (dict.TryGetValue(info, out var existingMeta)) + if (dict.TryGetValue(info, out TextureMeta existingMeta)) { dict[info] = MergeTextureMeta(meta, existingMeta); setIndex = existingMeta.Set; @@ -383,7 +383,7 @@ namespace Ryujinx.Graphics.Shader.Translation nameSuffix = cbufSlot < 0 ? $"{prefix}_tcb_{handle:X}" : $"{prefix}_cb{cbufSlot}_{handle:X}"; } - var definition = new TextureDefinition( + TextureDefinition definition = new TextureDefinition( setIndex, binding, arrayLength, @@ -443,8 +443,8 @@ namespace Ryujinx.Graphics.Shader.Translation { selectedMeta.UsageFlags |= TextureUsageFlags.NeedsScaleValue; - var dimensions = type.GetDimensions(); - var canScale = _stage.SupportsRenderScale() && selectedInfo.ArrayLength == 1 && dimensions == 2; + int dimensions = type.GetDimensions(); + bool canScale = _stage.SupportsRenderScale() && selectedInfo.ArrayLength == 1 && dimensions == 2; if (!canScale) { @@ -464,7 +464,7 @@ namespace Ryujinx.Graphics.Shader.Translation public BufferDescriptor[] GetConstantBufferDescriptors() { - var descriptors = new BufferDescriptor[_usedConstantBufferBindings.Count]; + BufferDescriptor[] descriptors = new BufferDescriptor[_usedConstantBufferBindings.Count]; int descriptorIndex = 0; @@ -488,7 +488,7 @@ namespace Ryujinx.Graphics.Shader.Translation public BufferDescriptor[] GetStorageBufferDescriptors() { - var descriptors = new BufferDescriptor[_sbSlots.Count]; + BufferDescriptor[] descriptors = new BufferDescriptor[_sbSlots.Count]; int descriptorIndex = 0; @@ -575,7 +575,7 @@ namespace Ryujinx.Graphics.Shader.Translation public ShaderProgramInfo GetVertexAsComputeInfo(bool isVertex = false) { - var cbDescriptors = new BufferDescriptor[_vacConstantBuffers.Count]; + BufferDescriptor[] cbDescriptors = new BufferDescriptor[_vacConstantBuffers.Count]; int cbDescriptorIndex = 0; foreach (BufferDefinition definition in _vacConstantBuffers) @@ -583,7 +583,7 @@ namespace Ryujinx.Graphics.Shader.Translation cbDescriptors[cbDescriptorIndex++] = new BufferDescriptor(definition.Set, definition.Binding, 0, 0, 0, BufferUsageFlags.None); } - var sbDescriptors = new BufferDescriptor[_vacStorageBuffers.Count]; + BufferDescriptor[] sbDescriptors = new BufferDescriptor[_vacStorageBuffers.Count]; int sbDescriptorIndex = 0; foreach (BufferDefinition definition in _vacStorageBuffers) @@ -591,7 +591,7 @@ namespace Ryujinx.Graphics.Shader.Translation sbDescriptors[sbDescriptorIndex++] = new BufferDescriptor(definition.Set, definition.Binding, 0, 0, 0, BufferUsageFlags.Write); } - var tDescriptors = new TextureDescriptor[_vacTextures.Count]; + TextureDescriptor[] tDescriptors = new TextureDescriptor[_vacTextures.Count]; int tDescriptorIndex = 0; foreach (TextureDefinition definition in _vacTextures) @@ -608,7 +608,7 @@ namespace Ryujinx.Graphics.Shader.Translation definition.Flags); } - var iDescriptors = new TextureDescriptor[_vacImages.Count]; + TextureDescriptor[] iDescriptors = new TextureDescriptor[_vacImages.Count]; int iDescriptorIndex = 0; foreach (TextureDefinition definition in _vacImages) diff --git a/src/Ryujinx.Graphics.Shader/Translation/ShaderDefinitions.cs b/src/Ryujinx.Graphics.Shader/Translation/ShaderDefinitions.cs index f831ec940..5cb900df7 100644 --- a/src/Ryujinx.Graphics.Shader/Translation/ShaderDefinitions.cs +++ b/src/Ryujinx.Graphics.Shader/Translation/ShaderDefinitions.cs @@ -192,7 +192,7 @@ namespace Ryujinx.Graphics.Shader.Translation component = subIndex; } - var transformFeedbackVariable = new TransformFeedbackVariable(ioVariable, location, component); + TransformFeedbackVariable transformFeedbackVariable = new TransformFeedbackVariable(ioVariable, location, component); _transformFeedbackDefinitions.TryAdd(transformFeedbackVariable, transformFeedbackOutputs[wordOffset]); } } @@ -219,7 +219,7 @@ namespace Ryujinx.Graphics.Shader.Translation return false; } - var transformFeedbackVariable = new TransformFeedbackVariable(ioVariable, location, component); + TransformFeedbackVariable transformFeedbackVariable = new TransformFeedbackVariable(ioVariable, location, component); return _transformFeedbackDefinitions.TryGetValue(transformFeedbackVariable, out transformFeedbackOutput); } @@ -271,8 +271,8 @@ namespace Ryujinx.Graphics.Shader.Translation for (; count < 4; count++) { - ref var prev = ref _transformFeedbackOutputs[baseIndex + count - 1]; - ref var curr = ref _transformFeedbackOutputs[baseIndex + count]; + ref TransformFeedbackOutput prev = ref _transformFeedbackOutputs[baseIndex + count - 1]; + ref TransformFeedbackOutput curr = ref _transformFeedbackOutputs[baseIndex + count]; int prevOffset = prev.Offset; int currOffset = curr.Offset; diff --git a/src/Ryujinx.Graphics.Shader/Translation/Translator.cs b/src/Ryujinx.Graphics.Shader/Translation/Translator.cs index d1fbca0eb..7f276044a 100644 --- a/src/Ryujinx.Graphics.Shader/Translation/Translator.cs +++ b/src/Ryujinx.Graphics.Shader/Translation/Translator.cs @@ -110,8 +110,8 @@ namespace Ryujinx.Graphics.Shader.Translation for (int tfbIndex = 0; tfbIndex < 4; tfbIndex++) { - var locations = gpuAccessor.QueryTransformFeedbackVaryingLocations(tfbIndex); - var stride = gpuAccessor.QueryTransformFeedbackStride(tfbIndex); + ReadOnlySpan locations = gpuAccessor.QueryTransformFeedbackVaryingLocations(tfbIndex); + int stride = gpuAccessor.QueryTransformFeedbackStride(tfbIndex); for (int i = 0; i < locations.Length; i++) { diff --git a/src/Ryujinx.Graphics.Shader/Translation/TranslatorContext.cs b/src/Ryujinx.Graphics.Shader/Translation/TranslatorContext.cs index bec20bc2c..40cf62231 100644 --- a/src/Ryujinx.Graphics.Shader/Translation/TranslatorContext.cs +++ b/src/Ryujinx.Graphics.Shader/Translation/TranslatorContext.cs @@ -243,8 +243,8 @@ namespace Ryujinx.Graphics.Shader.Translation usedFeatures |= FeatureFlags.VtgAsCompute; } - var cfgs = new ControlFlowGraph[functions.Length]; - var frus = new RegisterUsage.FunctionRegisterUsage[functions.Length]; + ControlFlowGraph[] cfgs = new ControlFlowGraph[functions.Length]; + RegisterUsage.FunctionRegisterUsage[] frus = new RegisterUsage.FunctionRegisterUsage[functions.Length]; for (int i = 0; i < functions.Length; i++) { @@ -267,14 +267,14 @@ namespace Ryujinx.Graphics.Shader.Translation for (int i = 0; i < functions.Length; i++) { - var cfg = cfgs[i]; + ControlFlowGraph cfg = cfgs[i]; int inArgumentsCount = 0; int outArgumentsCount = 0; if (i != 0) { - var fru = frus[i]; + RegisterUsage.FunctionRegisterUsage fru = frus[i]; inArgumentsCount = fru.InArguments.Length; outArgumentsCount = fru.OutArguments.Length; @@ -326,7 +326,7 @@ namespace Ryujinx.Graphics.Shader.Translation FeatureFlags usedFeatures, byte clipDistancesWritten) { - var sInfo = StructuredProgram.MakeStructuredProgram( + StructuredProgramInfo sInfo = StructuredProgram.MakeStructuredProgram( funcs, attributeUsage, definitions, @@ -342,7 +342,7 @@ namespace Ryujinx.Graphics.Shader.Translation _ => 1 }; - var info = new ShaderProgramInfo( + ShaderProgramInfo info = new ShaderProgramInfo( resourceManager.GetConstantBufferDescriptors(), resourceManager.GetStorageBufferDescriptors(), resourceManager.GetTextureDescriptors(), @@ -358,7 +358,7 @@ namespace Ryujinx.Graphics.Shader.Translation clipDistancesWritten, originalDefinitions.OmapTargets); - var hostCapabilities = new HostCapabilities( + HostCapabilities hostCapabilities = new HostCapabilities( GpuAccessor.QueryHostReducedPrecision(), GpuAccessor.QueryHostSupportsFragmentShaderInterlock(), GpuAccessor.QueryHostSupportsFragmentShaderOrderingIntel(), @@ -369,7 +369,7 @@ namespace Ryujinx.Graphics.Shader.Translation GpuAccessor.QueryHostSupportsTextureShadowLod(), GpuAccessor.QueryHostSupportsViewportMask()); - var parameters = new CodeGenParameters(attributeUsage, definitions, resourceManager.Properties, hostCapabilities, GpuAccessor, Options.TargetApi); + CodeGenParameters parameters = new CodeGenParameters(attributeUsage, definitions, resourceManager.Properties, hostCapabilities, GpuAccessor, Options.TargetApi); return Options.TargetLanguage switch { @@ -494,10 +494,10 @@ namespace Ryujinx.Graphics.Shader.Translation public (ShaderProgram, ShaderProgramInfo) GenerateVertexPassthroughForCompute() { - var attributeUsage = new AttributeUsage(GpuAccessor); - var resourceManager = new ResourceManager(ShaderStage.Vertex, GpuAccessor); + AttributeUsage attributeUsage = new AttributeUsage(GpuAccessor); + ResourceManager resourceManager = new ResourceManager(ShaderStage.Vertex, GpuAccessor); - var reservations = GetResourceReservations(); + ResourceReservations reservations = GetResourceReservations(); int vertexInfoCbBinding = reservations.VertexInfoConstantBufferBinding; @@ -516,7 +516,7 @@ namespace Ryujinx.Graphics.Shader.Translation BufferDefinition vertexOutputBuffer = new(BufferLayout.Std430, 1, vertexDataSbBinding, "vb_input", vertexInputStruct); resourceManager.AddVertexAsComputeStorageBuffer(vertexOutputBuffer); - var context = new EmitterContext(); + EmitterContext context = new EmitterContext(); Operand vertexIndex = Options.TargetApi == TargetApi.OpenGL ? context.Load(StorageKind.Input, IoVariable.VertexId) @@ -561,13 +561,13 @@ namespace Ryujinx.Graphics.Shader.Translation } } - var operations = context.GetOperations(); - var cfg = ControlFlowGraph.Create(operations); - var function = new Function(cfg.Blocks, "main", false, 0, 0); + Operation[] operations = context.GetOperations(); + ControlFlowGraph cfg = ControlFlowGraph.Create(operations); + Function function = new Function(cfg.Blocks, "main", false, 0, 0); - var transformFeedbackOutputs = GetTransformFeedbackOutputs(GpuAccessor, out ulong transformFeedbackVecMap); + TransformFeedbackOutput[] transformFeedbackOutputs = GetTransformFeedbackOutputs(GpuAccessor, out ulong transformFeedbackVecMap); - var definitions = new ShaderDefinitions(ShaderStage.Vertex, transformFeedbackVecMap, transformFeedbackOutputs) + ShaderDefinitions definitions = new ShaderDefinitions(ShaderStage.Vertex, transformFeedbackVecMap, transformFeedbackOutputs) { LastInVertexPipeline = true }; @@ -612,10 +612,10 @@ namespace Ryujinx.Graphics.Shader.Translation break; } - var attributeUsage = new AttributeUsage(GpuAccessor); - var resourceManager = new ResourceManager(ShaderStage.Geometry, GpuAccessor); + AttributeUsage attributeUsage = new AttributeUsage(GpuAccessor); + ResourceManager resourceManager = new ResourceManager(ShaderStage.Geometry, GpuAccessor); - var context = new EmitterContext(); + EmitterContext context = new EmitterContext(); for (int v = 0; v < maxOutputVertices; v++) { @@ -656,11 +656,11 @@ namespace Ryujinx.Graphics.Shader.Translation context.EndPrimitive(); - var operations = context.GetOperations(); - var cfg = ControlFlowGraph.Create(operations); - var function = new Function(cfg.Blocks, "main", false, 0, 0); + Operation[] operations = context.GetOperations(); + ControlFlowGraph cfg = ControlFlowGraph.Create(operations); + Function function = new Function(cfg.Blocks, "main", false, 0, 0); - var definitions = new ShaderDefinitions( + ShaderDefinitions definitions = new ShaderDefinitions( ShaderStage.Geometry, GpuAccessor.QueryGraphicsState(), false, From 1712d69dcdc94438d37ec8fbeb827dacbb0fb53e Mon Sep 17 00:00:00 2001 From: Evan Husted Date: Sat, 25 Jan 2025 14:08:35 -0600 Subject: [PATCH 10/19] misc: chore: Use explicit types in Texture & Vic --- src/Ryujinx.Graphics.Texture/Encoders/BC7Encoder.cs | 2 +- src/Ryujinx.Graphics.Vic/VicDevice.cs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Ryujinx.Graphics.Texture/Encoders/BC7Encoder.cs b/src/Ryujinx.Graphics.Texture/Encoders/BC7Encoder.cs index 5fdc9e917..5b333f91f 100644 --- a/src/Ryujinx.Graphics.Texture/Encoders/BC7Encoder.cs +++ b/src/Ryujinx.Graphics.Texture/Encoders/BC7Encoder.cs @@ -67,7 +67,7 @@ namespace Ryujinx.Graphics.Texture.Encoders int w = Math.Min(4, width - x); int h = Math.Min(4, height - y); - var dataUint = MemoryMarshal.Cast(data); + ReadOnlySpan dataUint = MemoryMarshal.Cast(data); int baseOffset = y * width + x; diff --git a/src/Ryujinx.Graphics.Vic/VicDevice.cs b/src/Ryujinx.Graphics.Vic/VicDevice.cs index 2b25a74c8..7cc5dda54 100644 --- a/src/Ryujinx.Graphics.Vic/VicDevice.cs +++ b/src/Ryujinx.Graphics.Vic/VicDevice.cs @@ -1,3 +1,4 @@ +using Ryujinx.Common.Memory; using Ryujinx.Graphics.Device; using Ryujinx.Graphics.Vic.Image; using Ryujinx.Graphics.Vic.Types; @@ -43,7 +44,7 @@ namespace Ryujinx.Graphics.Vic continue; } - ref var offsets = ref _state.State.SetSurfacexSlotx[i]; + ref Array8 offsets = ref _state.State.SetSurfacexSlotx[i]; using Surface src = SurfaceReader.Read(_rm, ref slot.SlotConfig, ref slot.SlotSurfaceConfig, ref offsets); From ac401034d75b9056766b4d723eace2228a30e1aa Mon Sep 17 00:00:00 2001 From: Evan Husted Date: Sat, 25 Jan 2025 14:09:05 -0600 Subject: [PATCH 11/19] misc: chore: Use explicit types in input projects --- src/Ryujinx.Input.SDL2/SDL2Gamepad.cs | 2 +- src/Ryujinx.Input.SDL2/SDLKeyboardDriver.cs | 2 +- src/Ryujinx.Input/Assigner/GamepadButtonAssigner.cs | 2 +- src/Ryujinx.Input/GamepadStateSnapshot.cs | 2 +- src/Ryujinx.Input/HLE/NpadController.cs | 4 ++-- src/Ryujinx.Input/HLE/NpadManager.cs | 11 ++++++----- src/Ryujinx.Input/HLE/TouchScreenManager.cs | 5 +++-- src/Ryujinx.Input/Motion/CemuHook/Client.cs | 10 +++++----- 8 files changed, 20 insertions(+), 18 deletions(-) diff --git a/src/Ryujinx.Input.SDL2/SDL2Gamepad.cs b/src/Ryujinx.Input.SDL2/SDL2Gamepad.cs index 3ed2880ce..8809c83f0 100644 --- a/src/Ryujinx.Input.SDL2/SDL2Gamepad.cs +++ b/src/Ryujinx.Input.SDL2/SDL2Gamepad.cs @@ -373,7 +373,7 @@ namespace Ryujinx.Input.SDL2 if (HasConfiguration) { - var joyconStickConfig = GetLogicalJoyStickConfig(inputId); + JoyconConfigControllerStick joyconStickConfig = GetLogicalJoyStickConfig(inputId); if (joyconStickConfig != null) { diff --git a/src/Ryujinx.Input.SDL2/SDLKeyboardDriver.cs b/src/Ryujinx.Input.SDL2/SDLKeyboardDriver.cs index 69e12bda0..fef6de788 100644 --- a/src/Ryujinx.Input.SDL2/SDLKeyboardDriver.cs +++ b/src/Ryujinx.Input.SDL2/SDLKeyboardDriver.cs @@ -55,7 +55,7 @@ namespace Ryujinx.Input.SDL2 public IEnumerable GetGamepads() { - foreach (var keyboardId in _keyboardIdentifers) + foreach (string keyboardId in _keyboardIdentifers) { yield return GetGamepad(keyboardId); } diff --git a/src/Ryujinx.Input/Assigner/GamepadButtonAssigner.cs b/src/Ryujinx.Input/Assigner/GamepadButtonAssigner.cs index 80fed2b82..4c8682da5 100644 --- a/src/Ryujinx.Input/Assigner/GamepadButtonAssigner.cs +++ b/src/Ryujinx.Input/Assigner/GamepadButtonAssigner.cs @@ -144,7 +144,7 @@ namespace Ryujinx.Input.Assigner { StringWriter writer = new(); - foreach (var kvp in _stats) + foreach (KeyValuePair kvp in _stats) { writer.WriteLine($"Button {kvp.Key} -> {kvp.Value}"); } diff --git a/src/Ryujinx.Input/GamepadStateSnapshot.cs b/src/Ryujinx.Input/GamepadStateSnapshot.cs index 3de08f574..ed1bf5fe8 100644 --- a/src/Ryujinx.Input/GamepadStateSnapshot.cs +++ b/src/Ryujinx.Input/GamepadStateSnapshot.cs @@ -49,7 +49,7 @@ namespace Ryujinx.Input [MethodImpl(MethodImplOptions.AggressiveInlining)] public (float, float) GetStick(StickInputId inputId) { - var result = _joysticksState[(int)inputId]; + Array2 result = _joysticksState[(int)inputId]; return (result[0], result[1]); } diff --git a/src/Ryujinx.Input/HLE/NpadController.cs b/src/Ryujinx.Input/HLE/NpadController.cs index 380745283..357299fdd 100644 --- a/src/Ryujinx.Input/HLE/NpadController.cs +++ b/src/Ryujinx.Input/HLE/NpadController.cs @@ -276,7 +276,7 @@ namespace Ryujinx.Input.HLE public void Update() { // _gamepad may be altered by other threads - var gamepad = _gamepad; + IGamepad gamepad = _gamepad; if (gamepad != null && GamepadDriver != null) { @@ -489,7 +489,7 @@ namespace Ryujinx.Input.HLE public static KeyboardInput GetHLEKeyboardInput(IGamepadDriver KeyboardDriver) { - var keyboard = KeyboardDriver.GetGamepad("0") as IKeyboard; + IKeyboard keyboard = KeyboardDriver.GetGamepad("0") as IKeyboard; KeyboardStateSnapshot keyboardState = keyboard.GetKeyboardStateSnapshot(); diff --git a/src/Ryujinx.Input/HLE/NpadManager.cs b/src/Ryujinx.Input/HLE/NpadManager.cs index 08f222a91..0b3278be5 100644 --- a/src/Ryujinx.Input/HLE/NpadManager.cs +++ b/src/Ryujinx.Input/HLE/NpadManager.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; +using System.Numerics; using System.Runtime.CompilerServices; using System.Threading; using CemuHookClient = Ryujinx.Input.Motion.CemuHook.Client; @@ -56,7 +57,7 @@ namespace Ryujinx.Input.HLE lock (_lock) { List validInputs = new(); - foreach (var inputConfigEntry in _inputConfig) + foreach (InputConfig inputConfigEntry in _inputConfig) { if (_controllers[(int)inputConfigEntry.PlayerIndex] != null) { @@ -234,7 +235,7 @@ namespace Ryujinx.Input.HLE isJoyconPair = inputConfig.ControllerType == ControllerType.JoyconPair; - var altMotionState = isJoyconPair ? controller.GetHLEMotionState(true) : default; + SixAxisInput altMotionState = isJoyconPair ? controller.GetHLEMotionState(true) : default; motionState = (controller.GetHLEMotionState(), altMotionState); } @@ -273,9 +274,9 @@ namespace Ryujinx.Input.HLE if (_enableMouse) { - var mouse = _mouseDriver.GetGamepad("0") as IMouse; + IMouse mouse = _mouseDriver.GetGamepad("0") as IMouse; - var mouseInput = IMouse.GetMouseStateSnapshot(mouse); + MouseStateSnapshot mouseInput = IMouse.GetMouseStateSnapshot(mouse); uint buttons = 0; @@ -304,7 +305,7 @@ namespace Ryujinx.Input.HLE buttons |= 1 << 4; } - var position = IMouse.GetScreenPosition(mouseInput.Position, mouse.ClientSize, aspectRatio); + Vector2 position = IMouse.GetScreenPosition(mouseInput.Position, mouse.ClientSize, aspectRatio); _device.Hid.Mouse.Update((int)position.X, (int)position.Y, buttons, (int)mouseInput.Scroll.X, (int)mouseInput.Scroll.Y, true); } diff --git a/src/Ryujinx.Input/HLE/TouchScreenManager.cs b/src/Ryujinx.Input/HLE/TouchScreenManager.cs index c613f9281..28d800d18 100644 --- a/src/Ryujinx.Input/HLE/TouchScreenManager.cs +++ b/src/Ryujinx.Input/HLE/TouchScreenManager.cs @@ -2,6 +2,7 @@ using Ryujinx.HLE; using Ryujinx.HLE.HOS.Services.Hid; using Ryujinx.HLE.HOS.Services.Hid.Types.SharedMemory.TouchScreen; using System; +using System.Numerics; namespace Ryujinx.Input.HLE { @@ -29,7 +30,7 @@ namespace Ryujinx.Input.HLE if (_wasClicking && !isClicking) { MouseStateSnapshot snapshot = IMouse.GetMouseStateSnapshot(_mouse); - var touchPosition = IMouse.GetScreenPosition(snapshot.Position, _mouse.ClientSize, aspectRatio); + Vector2 touchPosition = IMouse.GetScreenPosition(snapshot.Position, _mouse.ClientSize, aspectRatio); TouchPoint currentPoint = new() { @@ -58,7 +59,7 @@ namespace Ryujinx.Input.HLE if (aspectRatio > 0) { MouseStateSnapshot snapshot = IMouse.GetMouseStateSnapshot(_mouse); - var touchPosition = IMouse.GetScreenPosition(snapshot.Position, _mouse.ClientSize, aspectRatio); + Vector2 touchPosition = IMouse.GetScreenPosition(snapshot.Position, _mouse.ClientSize, aspectRatio); TouchAttribute attribute = TouchAttribute.None; diff --git a/src/Ryujinx.Input/Motion/CemuHook/Client.cs b/src/Ryujinx.Input/Motion/CemuHook/Client.cs index e19f3d847..d07ae6431 100644 --- a/src/Ryujinx.Input/Motion/CemuHook/Client.cs +++ b/src/Ryujinx.Input/Motion/CemuHook/Client.cs @@ -48,7 +48,7 @@ namespace Ryujinx.Input.Motion.CemuHook lock (_clients) { - foreach (var client in _clients) + foreach (KeyValuePair client in _clients) { try { @@ -209,7 +209,7 @@ namespace Ryujinx.Input.Motion.CemuHook { client.Client.ReceiveTimeout = timeout; - var result = client?.Receive(ref endPoint); + byte[] result = client?.Receive(ref endPoint); if (result.Length > 0) { @@ -225,7 +225,7 @@ namespace Ryujinx.Input.Motion.CemuHook private void SetRetryTimer(int clientId) { - var elapsedMs = PerformanceCounter.ElapsedMilliseconds; + long elapsedMs = PerformanceCounter.ElapsedMilliseconds; _clientRetryTimer[clientId] = elapsedMs; } @@ -338,9 +338,9 @@ namespace Ryujinx.Input.Motion.CemuHook { int slot = inputData.Shared.Slot; - if (_motionData.TryGetValue(clientId, out var motionDataItem)) + if (_motionData.TryGetValue(clientId, out Dictionary motionDataItem)) { - if (motionDataItem.TryGetValue(slot, out var previousData)) + if (motionDataItem.TryGetValue(slot, out MotionInput previousData)) { previousData.Update(accelerometer, gyroscrope, timestamp, cemuHookConfig.Sensitivity, (float)cemuHookConfig.GyroDeadzone); } From fe661dc750e2eb6712d476572ecc73b915e71651 Mon Sep 17 00:00:00 2001 From: Evan Husted Date: Sat, 25 Jan 2025 14:09:36 -0600 Subject: [PATCH 12/19] misc: chore: Use explicit types in Memory project --- src/Ryujinx.Memory/AddressSpaceManager.cs | 6 ++-- .../BytesReadOnlySequenceSegment.cs | 6 ++-- src/Ryujinx.Memory/IVirtualMemoryManager.cs | 2 +- src/Ryujinx.Memory/MemoryManagementWindows.cs | 2 +- src/Ryujinx.Memory/Range/MultiRange.cs | 2 +- src/Ryujinx.Memory/Range/MultiRangeList.cs | 10 +++--- .../Range/NonOverlappingRangeList.cs | 2 +- src/Ryujinx.Memory/Tracking/MemoryTracking.cs | 10 +++--- .../Tracking/MultiRegionHandle.cs | 4 +-- src/Ryujinx.Memory/Tracking/RegionHandle.cs | 6 ++-- .../Tracking/SmartMultiRegionHandle.cs | 8 ++--- src/Ryujinx.Memory/Tracking/VirtualRegion.cs | 4 +-- .../VirtualMemoryManagerBase.cs | 2 +- .../WindowsShared/PlaceholderManager.cs | 32 +++++++++---------- 14 files changed, 48 insertions(+), 48 deletions(-) diff --git a/src/Ryujinx.Memory/AddressSpaceManager.cs b/src/Ryujinx.Memory/AddressSpaceManager.cs index 7bd572d7a..76c679d41 100644 --- a/src/Ryujinx.Memory/AddressSpaceManager.cs +++ b/src/Ryujinx.Memory/AddressSpaceManager.cs @@ -109,7 +109,7 @@ namespace Ryujinx.Memory yield break; } - foreach (var hostRegion in GetHostRegionsImpl(va, size)) + foreach (HostMemoryRange hostRegion in GetHostRegionsImpl(va, size)) { yield return hostRegion; } @@ -123,7 +123,7 @@ namespace Ryujinx.Memory yield break; } - var hostRegions = GetHostRegionsImpl(va, size); + IEnumerable hostRegions = GetHostRegionsImpl(va, size); if (hostRegions == null) { yield break; @@ -132,7 +132,7 @@ namespace Ryujinx.Memory ulong backingStart = (ulong)_backingMemory.Pointer; ulong backingEnd = backingStart + _backingMemory.Size; - foreach (var hostRegion in hostRegions) + foreach (HostMemoryRange hostRegion in hostRegions) { if (hostRegion.Address >= backingStart && hostRegion.Address < backingEnd) { diff --git a/src/Ryujinx.Memory/BytesReadOnlySequenceSegment.cs b/src/Ryujinx.Memory/BytesReadOnlySequenceSegment.cs index 5fe8d936c..6ac83464c 100644 --- a/src/Ryujinx.Memory/BytesReadOnlySequenceSegment.cs +++ b/src/Ryujinx.Memory/BytesReadOnlySequenceSegment.cs @@ -14,7 +14,7 @@ namespace Ryujinx.Memory public BytesReadOnlySequenceSegment Append(Memory memory) { - var nextSegment = new BytesReadOnlySequenceSegment(memory) + BytesReadOnlySequenceSegment nextSegment = new BytesReadOnlySequenceSegment(memory) { RunningIndex = RunningIndex + Memory.Length }; @@ -34,8 +34,8 @@ namespace Ryujinx.Memory /// True if the segments are contiguous, otherwise false public unsafe bool IsContiguousWith(Memory other, out nuint contiguousStart, out int contiguousSize) { - if (MemoryMarshal.TryGetMemoryManager>(Memory, out var thisMemoryManager) && - MemoryMarshal.TryGetMemoryManager>(other, out var otherMemoryManager) && + if (MemoryMarshal.TryGetMemoryManager>(Memory, out NativeMemoryManager thisMemoryManager) && + MemoryMarshal.TryGetMemoryManager>(other, out NativeMemoryManager otherMemoryManager) && thisMemoryManager.Pointer + thisMemoryManager.Length == otherMemoryManager.Pointer) { contiguousStart = (nuint)thisMemoryManager.Pointer; diff --git a/src/Ryujinx.Memory/IVirtualMemoryManager.cs b/src/Ryujinx.Memory/IVirtualMemoryManager.cs index 102cedc94..1f8ca37aa 100644 --- a/src/Ryujinx.Memory/IVirtualMemoryManager.cs +++ b/src/Ryujinx.Memory/IVirtualMemoryManager.cs @@ -118,7 +118,7 @@ namespace Ryujinx.Memory { int copySize = (int)Math.Min(MaxChunkSize, size - subOffset); - using var writableRegion = GetWritableRegion(va + subOffset, copySize); + using WritableRegion writableRegion = GetWritableRegion(va + subOffset, copySize); writableRegion.Memory.Span.Fill(value); } diff --git a/src/Ryujinx.Memory/MemoryManagementWindows.cs b/src/Ryujinx.Memory/MemoryManagementWindows.cs index 468355dd0..e5a50f866 100644 --- a/src/Ryujinx.Memory/MemoryManagementWindows.cs +++ b/src/Ryujinx.Memory/MemoryManagementWindows.cs @@ -102,7 +102,7 @@ namespace Ryujinx.Memory public static nint CreateSharedMemory(nint size, bool reserve) { - var prot = reserve ? FileMapProtection.SectionReserve : FileMapProtection.SectionCommit; + FileMapProtection prot = reserve ? FileMapProtection.SectionReserve : FileMapProtection.SectionCommit; nint handle = WindowsApi.CreateFileMapping( WindowsApi.InvalidHandleValue, diff --git a/src/Ryujinx.Memory/Range/MultiRange.cs b/src/Ryujinx.Memory/Range/MultiRange.cs index 093e21903..c3bb99f35 100644 --- a/src/Ryujinx.Memory/Range/MultiRange.cs +++ b/src/Ryujinx.Memory/Range/MultiRange.cs @@ -73,7 +73,7 @@ namespace Ryujinx.Memory.Range } else { - var ranges = new List(); + List ranges = []; foreach (MemoryRange range in _ranges) { diff --git a/src/Ryujinx.Memory/Range/MultiRangeList.cs b/src/Ryujinx.Memory/Range/MultiRangeList.cs index c3c6ae797..f5fd6164d 100644 --- a/src/Ryujinx.Memory/Range/MultiRangeList.cs +++ b/src/Ryujinx.Memory/Range/MultiRangeList.cs @@ -28,7 +28,7 @@ namespace Ryujinx.Memory.Range for (int i = 0; i < range.Count; i++) { - var subrange = range.GetSubRange(i); + MemoryRange subrange = range.GetSubRange(i); if (MemoryRange.IsInvalid(ref subrange)) { @@ -54,7 +54,7 @@ namespace Ryujinx.Memory.Range for (int i = 0; i < range.Count; i++) { - var subrange = range.GetSubRange(i); + MemoryRange subrange = range.GetSubRange(i); if (MemoryRange.IsInvalid(ref subrange)) { @@ -97,7 +97,7 @@ namespace Ryujinx.Memory.Range for (int i = 0; i < range.Count; i++) { - var subrange = range.GetSubRange(i); + MemoryRange subrange = range.GetSubRange(i); if (MemoryRange.IsInvalid(ref subrange)) { @@ -172,8 +172,8 @@ namespace Ryujinx.Memory.Range private List GetList() { - var items = _items.AsList(); - var result = new List(); + List> items = _items.AsList(); + List result = new List(); foreach (RangeNode item in items) { diff --git a/src/Ryujinx.Memory/Range/NonOverlappingRangeList.cs b/src/Ryujinx.Memory/Range/NonOverlappingRangeList.cs index 511589176..894078aee 100644 --- a/src/Ryujinx.Memory/Range/NonOverlappingRangeList.cs +++ b/src/Ryujinx.Memory/Range/NonOverlappingRangeList.cs @@ -26,7 +26,7 @@ namespace Ryujinx.Memory.Range // For instance, while a virtual mapping could cover 0-2 in physical space, the space 0-1 may have already been reserved... // So we need to return both the split 0-1 and 1-2 ranges. - var results = new T[1]; + T[] results = new T[1]; int count = FindOverlapsNonOverlapping(address, size, ref results); if (count == 0) diff --git a/src/Ryujinx.Memory/Tracking/MemoryTracking.cs b/src/Ryujinx.Memory/Tracking/MemoryTracking.cs index 96cb2c5f5..d60a3bd8f 100644 --- a/src/Ryujinx.Memory/Tracking/MemoryTracking.cs +++ b/src/Ryujinx.Memory/Tracking/MemoryTracking.cs @@ -76,7 +76,7 @@ namespace Ryujinx.Memory.Tracking lock (TrackingLock) { - ref var overlaps = ref ThreadStaticArray.Get(); + ref VirtualRegion[] overlaps = ref ThreadStaticArray.Get(); for (int type = 0; type < 2; type++) { @@ -114,7 +114,7 @@ namespace Ryujinx.Memory.Tracking lock (TrackingLock) { - ref var overlaps = ref ThreadStaticArray.Get(); + ref VirtualRegion[] overlaps = ref ThreadStaticArray.Get(); for (int type = 0; type < 2; type++) { @@ -228,7 +228,7 @@ namespace Ryujinx.Memory.Tracking /// The memory tracking handle public RegionHandle BeginTracking(ulong address, ulong size, int id, RegionFlags flags = RegionFlags.None) { - var (paAddress, paSize) = PageAlign(address, size); + (ulong paAddress, ulong paSize) = PageAlign(address, size); lock (TrackingLock) { @@ -251,7 +251,7 @@ namespace Ryujinx.Memory.Tracking /// The memory tracking handle internal RegionHandle BeginTrackingBitmap(ulong address, ulong size, ConcurrentBitmap bitmap, int bit, int id, RegionFlags flags = RegionFlags.None) { - var (paAddress, paSize) = PageAlign(address, size); + (ulong paAddress, ulong paSize) = PageAlign(address, size); lock (TrackingLock) { @@ -296,7 +296,7 @@ namespace Ryujinx.Memory.Tracking lock (TrackingLock) { - ref var overlaps = ref ThreadStaticArray.Get(); + ref VirtualRegion[] overlaps = ref ThreadStaticArray.Get(); NonOverlappingRangeList regions = guest ? _guestVirtualRegions : _virtualRegions; diff --git a/src/Ryujinx.Memory/Tracking/MultiRegionHandle.cs b/src/Ryujinx.Memory/Tracking/MultiRegionHandle.cs index 6fdca69f5..a9b79ab3e 100644 --- a/src/Ryujinx.Memory/Tracking/MultiRegionHandle.cs +++ b/src/Ryujinx.Memory/Tracking/MultiRegionHandle.cs @@ -320,7 +320,7 @@ namespace Ryujinx.Memory.Tracking if (startHandle == lastHandle) { - var handle = _handles[startHandle]; + RegionHandle handle = _handles[startHandle]; if (_sequenceNumberBitmap.Set(startHandle)) { _uncheckedHandles--; @@ -410,7 +410,7 @@ namespace Ryujinx.Memory.Tracking { GC.SuppressFinalize(this); - foreach (var handle in _handles) + foreach (RegionHandle handle in _handles) { handle.Dispose(); } diff --git a/src/Ryujinx.Memory/Tracking/RegionHandle.cs b/src/Ryujinx.Memory/Tracking/RegionHandle.cs index 4e81a9723..b938c6ea9 100644 --- a/src/Ryujinx.Memory/Tracking/RegionHandle.cs +++ b/src/Ryujinx.Memory/Tracking/RegionHandle.cs @@ -199,7 +199,7 @@ namespace Ryujinx.Memory.Tracking _allRegions.AddRange(_regions); _allRegions.AddRange(_guestRegions); - foreach (var region in _allRegions) + foreach (VirtualRegion region in _allRegions) { region.Handles.Add(this); } @@ -217,8 +217,8 @@ namespace Ryujinx.Memory.Tracking { // Assumes the tracking lock is held, so nothing else can signal right now. - var oldBitmap = Bitmap; - var oldBit = DirtyBit; + ConcurrentBitmap oldBitmap = Bitmap; + int oldBit = DirtyBit; bitmap.Set(bit, Dirty); diff --git a/src/Ryujinx.Memory/Tracking/SmartMultiRegionHandle.cs b/src/Ryujinx.Memory/Tracking/SmartMultiRegionHandle.cs index 57129a182..1e44c0916 100644 --- a/src/Ryujinx.Memory/Tracking/SmartMultiRegionHandle.cs +++ b/src/Ryujinx.Memory/Tracking/SmartMultiRegionHandle.cs @@ -45,7 +45,7 @@ namespace Ryujinx.Memory.Tracking public void ForceDirty(ulong address, ulong size) { - foreach (var handle in _handles) + foreach (RegionHandle handle in _handles) { if (handle != null && handle.OverlapsWith(address, size)) { @@ -56,7 +56,7 @@ namespace Ryujinx.Memory.Tracking public void RegisterAction(RegionSignal action) { - foreach (var handle in _handles) + foreach (RegionHandle handle in _handles) { if (handle != null) { @@ -67,7 +67,7 @@ namespace Ryujinx.Memory.Tracking public void RegisterPreciseAction(PreciseRegionSignal action) { - foreach (var handle in _handles) + foreach (RegionHandle handle in _handles) { if (handle != null) { @@ -273,7 +273,7 @@ namespace Ryujinx.Memory.Tracking { GC.SuppressFinalize(this); - foreach (var handle in _handles) + foreach (RegionHandle handle in _handles) { handle?.Dispose(); } diff --git a/src/Ryujinx.Memory/Tracking/VirtualRegion.cs b/src/Ryujinx.Memory/Tracking/VirtualRegion.cs index 35e9c2d9b..7f5eb9b11 100644 --- a/src/Ryujinx.Memory/Tracking/VirtualRegion.cs +++ b/src/Ryujinx.Memory/Tracking/VirtualRegion.cs @@ -90,7 +90,7 @@ namespace Ryujinx.Memory.Tracking MemoryPermission result = MemoryPermission.ReadAndWrite; - foreach (var handle in Handles) + foreach (RegionHandle handle in Handles) { result &= handle.RequiredPermission; if (result == 0) @@ -143,7 +143,7 @@ namespace Ryujinx.Memory.Tracking // The new region inherits all of our parents. newRegion.Handles = new List(Handles); - foreach (var parent in Handles) + foreach (RegionHandle parent in Handles) { parent.AddChild(newRegion); } diff --git a/src/Ryujinx.Memory/VirtualMemoryManagerBase.cs b/src/Ryujinx.Memory/VirtualMemoryManagerBase.cs index f41072244..eb5d66829 100644 --- a/src/Ryujinx.Memory/VirtualMemoryManagerBase.cs +++ b/src/Ryujinx.Memory/VirtualMemoryManagerBase.cs @@ -234,7 +234,7 @@ namespace Ryujinx.Memory nuint pa = TranslateVirtualAddressChecked(va); - var target = GetPhysicalAddressSpan(pa, data.Length); + Span target = GetPhysicalAddressSpan(pa, data.Length); bool changed = !data.SequenceEqual(target); diff --git a/src/Ryujinx.Memory/WindowsShared/PlaceholderManager.cs b/src/Ryujinx.Memory/WindowsShared/PlaceholderManager.cs index 2a294bba9..f1bbf2f41 100644 --- a/src/Ryujinx.Memory/WindowsShared/PlaceholderManager.cs +++ b/src/Ryujinx.Memory/WindowsShared/PlaceholderManager.cs @@ -128,7 +128,7 @@ namespace Ryujinx.Memory.WindowsShared /// Memory block that owns the mapping public void MapView(nint sharedMemory, ulong srcOffset, nint location, nint size, MemoryBlock owner) { - ref var partialUnmapLock = ref GetPartialUnmapState().PartialUnmapLock; + ref NativeReaderWriterLock partialUnmapLock = ref GetPartialUnmapState().PartialUnmapLock; partialUnmapLock.AcquireReaderLock(); try @@ -155,7 +155,7 @@ namespace Ryujinx.Memory.WindowsShared { SplitForMap((ulong)location, (ulong)size, srcOffset); - var ptr = WindowsApi.MapViewOfFile3( + IntPtr ptr = WindowsApi.MapViewOfFile3( sharedMemory, WindowsApi.CurrentProcessHandle, location, @@ -187,7 +187,7 @@ namespace Ryujinx.Memory.WindowsShared { ulong endAddress = address + size; - var overlaps = new RangeNode[InitialOverlapsSize]; + RangeNode[] overlaps = new RangeNode[InitialOverlapsSize]; lock (_mappings) { @@ -196,7 +196,7 @@ namespace Ryujinx.Memory.WindowsShared Debug.Assert(count == 1); Debug.Assert(!IsMapped(overlaps[0].Value)); - var overlap = overlaps[0]; + RangeNode overlap = overlaps[0]; ulong overlapStart = overlap.Start; ulong overlapEnd = overlap.End; @@ -257,7 +257,7 @@ namespace Ryujinx.Memory.WindowsShared /// Memory block that owns the mapping public void UnmapView(nint sharedMemory, nint location, nint size, MemoryBlock owner) { - ref var partialUnmapLock = ref GetPartialUnmapState().PartialUnmapLock; + ref NativeReaderWriterLock partialUnmapLock = ref GetPartialUnmapState().PartialUnmapLock; partialUnmapLock.AcquireReaderLock(); try @@ -289,7 +289,7 @@ namespace Ryujinx.Memory.WindowsShared ulong unmapSize = (ulong)size; ulong endAddress = startAddress + unmapSize; - var overlaps = new RangeNode[InitialOverlapsSize]; + RangeNode[] overlaps = new RangeNode[InitialOverlapsSize]; int count; lock (_mappings) @@ -299,7 +299,7 @@ namespace Ryujinx.Memory.WindowsShared for (int index = 0; index < count; index++) { - var overlap = overlaps[index]; + RangeNode overlap = overlaps[index]; if (IsMapped(overlap.Value)) { @@ -319,8 +319,8 @@ namespace Ryujinx.Memory.WindowsShared // This is necessary because Windows does not support partial view unmaps. // That is, you can only fully unmap a view that was previously mapped, you can't just unmap a chunck of it. - ref var partialUnmapState = ref GetPartialUnmapState(); - ref var partialUnmapLock = ref partialUnmapState.PartialUnmapLock; + ref PartialUnmapState partialUnmapState = ref GetPartialUnmapState(); + ref NativeReaderWriterLock partialUnmapLock = ref partialUnmapState.PartialUnmapLock; partialUnmapLock.UpgradeToWriterLock(); try @@ -400,7 +400,7 @@ namespace Ryujinx.Memory.WindowsShared for (; node != null; node = successor) { successor = node.Successor; - var overlap = node; + RangeNode overlap = node; if (!IsMapped(overlap.Value)) { @@ -456,7 +456,7 @@ namespace Ryujinx.Memory.WindowsShared /// True if the reprotection was successful, false otherwise public bool ReprotectView(nint address, nint size, MemoryPermission permission) { - ref var partialUnmapLock = ref GetPartialUnmapState().PartialUnmapLock; + ref NativeReaderWriterLock partialUnmapLock = ref GetPartialUnmapState().PartialUnmapLock; partialUnmapLock.AcquireReaderLock(); try @@ -494,7 +494,7 @@ namespace Ryujinx.Memory.WindowsShared for (; node != null; node = successorNode) { successorNode = node.Successor; - var overlap = node; + RangeNode overlap = node; ulong mappedAddress = overlap.Start; ulong mappedSize = overlap.End - overlap.Start; @@ -604,7 +604,7 @@ namespace Ryujinx.Memory.WindowsShared for (; node != null; node = successorNode) { successorNode = node.Successor; - var protection = node; + RangeNode protection = node; ulong protAddress = protection.Start; ulong protEndAddress = protection.End; @@ -664,7 +664,7 @@ namespace Ryujinx.Memory.WindowsShared for (; node != null; node = successorNode) { successorNode = node.Successor; - var protection = node; + RangeNode protection = node; ulong protAddress = protection.Start; ulong protEndAddress = protection.End; @@ -698,7 +698,7 @@ namespace Ryujinx.Memory.WindowsShared private void RestoreRangeProtection(ulong address, ulong size) { ulong endAddress = address + size; - var overlaps = new RangeNode[InitialOverlapsSize]; + RangeNode[] overlaps = new RangeNode[InitialOverlapsSize]; int count; lock (_protections) @@ -708,7 +708,7 @@ namespace Ryujinx.Memory.WindowsShared for (int index = 0; index < count; index++) { - var protection = overlaps[index]; + RangeNode protection = overlaps[index]; // If protection is R/W we don't need to reprotect as views are initially mapped as R/W. if (protection.Value == MemoryPermission.ReadAndWrite) From e6b393e4208166dc04c1ccbcb549f29c7dbc8b6f Mon Sep 17 00:00:00 2001 From: Evan Husted Date: Sat, 25 Jan 2025 14:11:46 -0600 Subject: [PATCH 13/19] misc: chore: Use explicit types in Generator projects --- .../IpcServiceGenerator.cs | 20 ++++++------- .../Hipc/HipcGenerator.cs | 28 +++++++++---------- .../Hipc/HipcSyntaxReceiver.cs | 6 ++-- .../SyscallGenerator.cs | 8 +++--- .../SyscallSyntaxReceiver.cs | 2 +- .../LocaleGenerator.cs | 7 +++-- src/Spv.Generator/Instruction.cs | 4 +-- src/Spv.Generator/InstructionOperands.cs | 6 ++-- src/Spv.Generator/Module.cs | 8 +++--- 9 files changed, 45 insertions(+), 44 deletions(-) diff --git a/src/Ryujinx.HLE.Generators/IpcServiceGenerator.cs b/src/Ryujinx.HLE.Generators/IpcServiceGenerator.cs index 5cac4d13a..4de100cf8 100644 --- a/src/Ryujinx.HLE.Generators/IpcServiceGenerator.cs +++ b/src/Ryujinx.HLE.Generators/IpcServiceGenerator.cs @@ -10,8 +10,8 @@ namespace Ryujinx.HLE.Generators { public void Execute(GeneratorExecutionContext context) { - var syntaxReceiver = (ServiceSyntaxReceiver)context.SyntaxReceiver; - CodeGenerator generator = new CodeGenerator(); + ServiceSyntaxReceiver syntaxReceiver = (ServiceSyntaxReceiver)context.SyntaxReceiver; + CodeGenerator generator = new(); generator.AppendLine("#nullable enable"); generator.AppendLine("using System;"); @@ -19,14 +19,14 @@ namespace Ryujinx.HLE.Generators generator.EnterScope($"partial class IUserInterface"); generator.EnterScope($"public IpcService? GetServiceInstance(Type type, ServiceCtx context, object? parameter = null)"); - foreach (var className in syntaxReceiver.Types) + foreach (ClassDeclarationSyntax className in syntaxReceiver.Types) { if (className.Modifiers.Any(SyntaxKind.AbstractKeyword) || className.Modifiers.Any(SyntaxKind.PrivateKeyword) || !className.AttributeLists.Any(x => x.Attributes.Any(y => y.ToString().StartsWith("Service")))) continue; - var name = GetFullName(className, context).Replace("global::", string.Empty); + string name = GetFullName(className, context).Replace("global::", string.Empty); if (!name.StartsWith("Ryujinx.HLE.HOS.Services")) continue; - var constructors = className.ChildNodes().Where(x => x.IsKind(SyntaxKind.ConstructorDeclaration)).Select(y => y as ConstructorDeclarationSyntax).ToArray(); + ConstructorDeclarationSyntax[] constructors = className.ChildNodes().Where(x => x.IsKind(SyntaxKind.ConstructorDeclaration)).Select(y => y as ConstructorDeclarationSyntax).ToArray(); if (!constructors.Any(x => x.ParameterList.Parameters.Count >= 1)) continue; @@ -36,10 +36,10 @@ namespace Ryujinx.HLE.Generators generator.EnterScope($"if (type == typeof({GetFullName(className, context)}))"); if (constructors.Any(x => x.ParameterList.Parameters.Count == 2)) { - var type = constructors.Where(x => x.ParameterList.Parameters.Count == 2).FirstOrDefault().ParameterList.Parameters[1].Type; - var model = context.Compilation.GetSemanticModel(type.SyntaxTree); - var typeSymbol = model.GetSymbolInfo(type).Symbol as INamedTypeSymbol; - var fullName = typeSymbol.ToString(); + TypeSyntax type = constructors.Where(x => x.ParameterList.Parameters.Count == 2).FirstOrDefault().ParameterList.Parameters[1].Type; + SemanticModel model = context.Compilation.GetSemanticModel(type.SyntaxTree); + INamedTypeSymbol typeSymbol = model.GetSymbolInfo(type).Symbol as INamedTypeSymbol; + string fullName = typeSymbol.ToString(); generator.EnterScope("if (parameter != null)"); generator.AppendLine($"return new {GetFullName(className, context)}(context, ({fullName})parameter);"); generator.LeaveScope(); @@ -65,7 +65,7 @@ namespace Ryujinx.HLE.Generators private string GetFullName(ClassDeclarationSyntax syntaxNode, GeneratorExecutionContext context) { - var typeSymbol = context.Compilation.GetSemanticModel(syntaxNode.SyntaxTree).GetDeclaredSymbol(syntaxNode); + INamedTypeSymbol typeSymbol = context.Compilation.GetSemanticModel(syntaxNode.SyntaxTree).GetDeclaredSymbol(syntaxNode); return typeSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); } diff --git a/src/Ryujinx.Horizon.Generators/Hipc/HipcGenerator.cs b/src/Ryujinx.Horizon.Generators/Hipc/HipcGenerator.cs index d1be8298d..e66a3efa9 100644 --- a/src/Ryujinx.Horizon.Generators/Hipc/HipcGenerator.cs +++ b/src/Ryujinx.Horizon.Generators/Hipc/HipcGenerator.cs @@ -61,7 +61,7 @@ namespace Ryujinx.Horizon.Generators.Hipc { HipcSyntaxReceiver syntaxReceiver = (HipcSyntaxReceiver)context.SyntaxReceiver; - foreach (var commandInterface in syntaxReceiver.CommandInterfaces) + foreach (CommandInterface commandInterface in syntaxReceiver.CommandInterfaces) { if (!NeedsIServiceObjectImplementation(context.Compilation, commandInterface.ClassDeclarationSyntax)) { @@ -86,7 +86,7 @@ namespace Ryujinx.Horizon.Generators.Hipc GenerateMethodTable(generator, context.Compilation, commandInterface); - foreach (var method in commandInterface.CommandImplementations) + foreach (MethodDeclarationSyntax method in commandInterface.CommandImplementations) { generator.AppendLine(); @@ -127,9 +127,9 @@ namespace Ryujinx.Horizon.Generators.Hipc { generator.EnterScope($"return FrozenDictionary.ToFrozenDictionary(new []"); - foreach (var method in commandInterface.CommandImplementations) + foreach (MethodDeclarationSyntax method in commandInterface.CommandImplementations) { - foreach (var commandId in GetAttributeArguments(compilation, method, TypeCommandAttribute, 0)) + foreach (string commandId in GetAttributeArguments(compilation, method, TypeCommandAttribute, 0)) { string[] args = new string[method.ParameterList.Parameters.Count]; @@ -141,7 +141,7 @@ namespace Ryujinx.Horizon.Generators.Hipc { int index = 0; - foreach (var parameter in method.ParameterList.Parameters) + foreach (ParameterSyntax parameter in method.ParameterList.Parameters) { string canonicalTypeName = GetCanonicalTypeNameWithGenericArguments(compilation, parameter.Type); CommandArgType argType = GetCommandArgType(compilation, parameter); @@ -191,7 +191,7 @@ namespace Ryujinx.Horizon.Generators.Hipc { ISymbol symbol = compilation.GetSemanticModel(syntaxNode.SyntaxTree).GetDeclaredSymbol(syntaxNode); - foreach (var attribute in symbol.GetAttributes()) + foreach (AttributeData attribute in symbol.GetAttributes()) { if (attribute.AttributeClass.ToDisplayString() == attributeName && (uint)argIndex < (uint)attribute.ConstructorArguments.Length) { @@ -211,7 +211,7 @@ namespace Ryujinx.Horizon.Generators.Hipc int outObjectsCount = 0; int buffersCount = 0; - foreach (var parameter in method.ParameterList.Parameters) + foreach (ParameterSyntax parameter in method.ParameterList.Parameters) { if (IsObject(compilation, parameter)) { @@ -285,7 +285,7 @@ namespace Ryujinx.Horizon.Generators.Hipc int inMoveHandleIndex = 0; int inObjectIndex = 0; - foreach (var parameter in method.ParameterList.Parameters) + foreach (ParameterSyntax parameter in method.ParameterList.Parameters) { string name = parameter.Identifier.Text; string argName = GetPrefixedArgName(name); @@ -555,11 +555,11 @@ namespace Ryujinx.Horizon.Generators.Hipc { ISymbol symbol = compilation.GetSemanticModel(syntaxNode.SyntaxTree).GetTypeInfo(syntaxNode).Type; - foreach (var attribute in symbol.GetAttributes()) + foreach (AttributeData attribute in symbol.GetAttributes()) { if (attribute.AttributeClass.ToDisplayString() == attributeName) { - foreach (var kv in attribute.NamedArguments) + foreach (KeyValuePair kv in attribute.NamedArguments) { if (kv.Key == argName) { @@ -764,9 +764,9 @@ namespace Ryujinx.Horizon.Generators.Hipc private static bool HasAttribute(Compilation compilation, ParameterSyntax parameterSyntax, string fullAttributeName) { - foreach (var attributeList in parameterSyntax.AttributeLists) + foreach (AttributeListSyntax attributeList in parameterSyntax.AttributeLists) { - foreach (var attribute in attributeList.Attributes) + foreach (AttributeSyntax attribute in attributeList.Attributes) { if (GetCanonicalTypeName(compilation, attribute) == fullAttributeName) { @@ -781,8 +781,8 @@ namespace Ryujinx.Horizon.Generators.Hipc private static bool NeedsIServiceObjectImplementation(Compilation compilation, ClassDeclarationSyntax classDeclarationSyntax) { ITypeSymbol type = compilation.GetSemanticModel(classDeclarationSyntax.SyntaxTree).GetDeclaredSymbol(classDeclarationSyntax); - var serviceObjectInterface = type.AllInterfaces.FirstOrDefault(x => x.ToDisplayString() == TypeIServiceObject); - var interfaceMember = serviceObjectInterface?.GetMembers().FirstOrDefault(x => x.Name == "GetCommandHandlers"); + INamedTypeSymbol serviceObjectInterface = type.AllInterfaces.FirstOrDefault(x => x.ToDisplayString() == TypeIServiceObject); + ISymbol interfaceMember = serviceObjectInterface?.GetMembers().FirstOrDefault(x => x.Name == "GetCommandHandlers"); // Return true only if the class implements IServiceObject but does not actually implement the method // that the interface defines, since this is the only case we want to handle, if the method already exists diff --git a/src/Ryujinx.Horizon.Generators/Hipc/HipcSyntaxReceiver.cs b/src/Ryujinx.Horizon.Generators/Hipc/HipcSyntaxReceiver.cs index 9b3421076..5eced63ec 100644 --- a/src/Ryujinx.Horizon.Generators/Hipc/HipcSyntaxReceiver.cs +++ b/src/Ryujinx.Horizon.Generators/Hipc/HipcSyntaxReceiver.cs @@ -24,9 +24,9 @@ namespace Ryujinx.Horizon.Generators.Hipc return; } - CommandInterface commandInterface = new CommandInterface(classDeclaration); + CommandInterface commandInterface = new(classDeclaration); - foreach (var memberDeclaration in classDeclaration.Members) + foreach (MemberDeclarationSyntax memberDeclaration in classDeclaration.Members) { if (memberDeclaration is MethodDeclarationSyntax methodDeclaration) { @@ -44,7 +44,7 @@ namespace Ryujinx.Horizon.Generators.Hipc if (methodDeclaration.AttributeLists.Count != 0) { - foreach (var attributeList in methodDeclaration.AttributeLists) + foreach (AttributeListSyntax attributeList in methodDeclaration.AttributeLists) { if (attributeList.Attributes.Any(x => x.Name.ToString().Contains(attributeName))) { diff --git a/src/Ryujinx.Horizon.Kernel.Generators/SyscallGenerator.cs b/src/Ryujinx.Horizon.Kernel.Generators/SyscallGenerator.cs index 06b98e09d..91eb08c77 100644 --- a/src/Ryujinx.Horizon.Kernel.Generators/SyscallGenerator.cs +++ b/src/Ryujinx.Horizon.Kernel.Generators/SyscallGenerator.cs @@ -147,7 +147,7 @@ namespace Ryujinx.Horizon.Kernel.Generators List syscalls = new List(); - foreach (var method in syntaxReceiver.SvcImplementations) + foreach (MethodDeclarationSyntax method in syntaxReceiver.SvcImplementations) { GenerateMethod32(generator, context.Compilation, method); GenerateMethod64(generator, context.Compilation, method); @@ -206,7 +206,7 @@ namespace Ryujinx.Horizon.Kernel.Generators List logInArgs = new List(); List logOutArgs = new List(); - foreach (var methodParameter in method.ParameterList.Parameters) + foreach (ParameterSyntax methodParameter in method.ParameterList.Parameters) { string name = methodParameter.Identifier.Text; string argName = GetPrefixedArgName(name); @@ -325,7 +325,7 @@ namespace Ryujinx.Horizon.Kernel.Generators List logInArgs = new List(); List logOutArgs = new List(); - foreach (var methodParameter in method.ParameterList.Parameters) + foreach (ParameterSyntax methodParameter in method.ParameterList.Parameters) { string name = methodParameter.Identifier.Text; string argName = GetPrefixedArgName(name); @@ -468,7 +468,7 @@ namespace Ryujinx.Horizon.Kernel.Generators generator.EnterScope($"public static void Dispatch{suffix}(Syscall syscall, {TypeExecutionContext} context, int id)"); generator.EnterScope("switch (id)"); - foreach (var syscall in syscalls) + foreach (SyscallIdAndName syscall in syscalls) { generator.AppendLine($"case {syscall.Id}:"); generator.IncreaseIndentation(); diff --git a/src/Ryujinx.Horizon.Kernel.Generators/SyscallSyntaxReceiver.cs b/src/Ryujinx.Horizon.Kernel.Generators/SyscallSyntaxReceiver.cs index 1542fed6a..76200713d 100644 --- a/src/Ryujinx.Horizon.Kernel.Generators/SyscallSyntaxReceiver.cs +++ b/src/Ryujinx.Horizon.Kernel.Generators/SyscallSyntaxReceiver.cs @@ -27,7 +27,7 @@ namespace Ryujinx.Horizon.Kernel.Generators return; } - foreach (var memberDeclaration in classDeclaration.Members) + foreach (MemberDeclarationSyntax memberDeclaration in classDeclaration.Members) { if (memberDeclaration is MethodDeclarationSyntax methodDeclaration) { diff --git a/src/Ryujinx.UI.LocaleGenerator/LocaleGenerator.cs b/src/Ryujinx.UI.LocaleGenerator/LocaleGenerator.cs index 2ba0b60a3..a3d16c660 100644 --- a/src/Ryujinx.UI.LocaleGenerator/LocaleGenerator.cs +++ b/src/Ryujinx.UI.LocaleGenerator/LocaleGenerator.cs @@ -1,4 +1,5 @@ using Microsoft.CodeAnalysis; +using System.Collections.Generic; using System.Linq; using System.Text; @@ -9,19 +10,19 @@ namespace Ryujinx.UI.LocaleGenerator { public void Initialize(IncrementalGeneratorInitializationContext context) { - var localeFile = context.AdditionalTextsProvider.Where(static x => x.Path.EndsWith("locales.json")); + IncrementalValuesProvider localeFile = context.AdditionalTextsProvider.Where(static x => x.Path.EndsWith("locales.json")); IncrementalValuesProvider contents = localeFile.Select((text, cancellationToken) => text.GetText(cancellationToken)!.ToString()); context.RegisterSourceOutput(contents, (spc, content) => { - var lines = content.Split('\n').Where(x => x.Trim().StartsWith("\"ID\":")).Select(x => x.Split(':')[1].Trim().Replace("\"", string.Empty).Replace(",", string.Empty)); + IEnumerable lines = content.Split('\n').Where(x => x.Trim().StartsWith("\"ID\":")).Select(x => x.Split(':')[1].Trim().Replace("\"", string.Empty).Replace(",", string.Empty)); StringBuilder enumSourceBuilder = new(); enumSourceBuilder.AppendLine("namespace Ryujinx.Ava.Common.Locale;"); enumSourceBuilder.AppendLine("public enum LocaleKeys"); enumSourceBuilder.AppendLine("{"); - foreach (var line in lines) + foreach (string? line in lines) { enumSourceBuilder.AppendLine($" {line},"); } diff --git a/src/Spv.Generator/Instruction.cs b/src/Spv.Generator/Instruction.cs index 741b30d6d..a19677a93 100644 --- a/src/Spv.Generator/Instruction.cs +++ b/src/Spv.Generator/Instruction.cs @@ -239,8 +239,8 @@ namespace Spv.Generator public override string ToString() { - var labels = _operandLabels.TryGetValue(Opcode, out var opLabels) ? opLabels : Array.Empty(); - var result = _resultType == null ? string.Empty : $"{_resultType} "; + string[] labels = _operandLabels.TryGetValue(Opcode, out string[] opLabels) ? opLabels : Array.Empty(); + string result = _resultType == null ? string.Empty : $"{_resultType} "; return $"{result}{Opcode}{_operands.ToString(labels)}"; } } diff --git a/src/Spv.Generator/InstructionOperands.cs b/src/Spv.Generator/InstructionOperands.cs index de74f1127..06feb300f 100644 --- a/src/Spv.Generator/InstructionOperands.cs +++ b/src/Spv.Generator/InstructionOperands.cs @@ -63,9 +63,9 @@ namespace Spv.Generator public readonly string ToString(string[] labels) { - var labeledParams = AllOperands.Zip(labels, (op, label) => $"{label}: {op}"); - var unlabeledParams = AllOperands.Skip(labels.Length).Select(op => op.ToString()); - var paramsToPrint = labeledParams.Concat(unlabeledParams); + IEnumerable labeledParams = AllOperands.Zip(labels, (op, label) => $"{label}: {op}"); + IEnumerable unlabeledParams = AllOperands.Skip(labels.Length).Select(op => op.ToString()); + IEnumerable paramsToPrint = labeledParams.Concat(unlabeledParams); return $"({string.Join(", ", paramsToPrint)})"; } } diff --git a/src/Spv.Generator/Module.cs b/src/Spv.Generator/Module.cs index fdcd62752..5945d9b6d 100644 --- a/src/Spv.Generator/Module.cs +++ b/src/Spv.Generator/Module.cs @@ -85,7 +85,7 @@ namespace Spv.Generator public Instruction NewInstruction(Op opcode, uint id = Instruction.InvalidId, Instruction resultType = null) { - var result = _instPool.Allocate(); + Instruction result = _instPool.Allocate(); result.Set(opcode, id, resultType); return result; @@ -93,7 +93,7 @@ namespace Spv.Generator public Instruction AddExtInstImport(string import) { - var key = new DeterministicStringKey(import); + DeterministicStringKey key = new DeterministicStringKey(import); if (_extInstImports.TryGetValue(key, out Instruction extInstImport)) { @@ -113,7 +113,7 @@ namespace Spv.Generator private void AddTypeDeclaration(Instruction instruction, bool forceIdAllocation) { - var key = new TypeDeclarationKey(instruction); + TypeDeclarationKey key = new TypeDeclarationKey(instruction); if (!forceIdAllocation) { @@ -214,7 +214,7 @@ namespace Spv.Generator constant.Opcode == Op.OpConstantNull || constant.Opcode == Op.OpConstantComposite); - var key = new ConstantKey(constant); + ConstantKey key = new ConstantKey(constant); if (_constants.TryGetValue(key, out Instruction global)) { From 2d1a4c3ce5c0d0b2a820a62064ff1fcfc30060eb Mon Sep 17 00:00:00 2001 From: Evan Husted Date: Sat, 25 Jan 2025 14:12:17 -0600 Subject: [PATCH 14/19] misc: chore: Use explicit types in Vulkan project --- src/Ryujinx.Graphics.Vulkan/Auto.cs | 2 +- .../BackgroundResources.cs | 2 +- src/Ryujinx.Graphics.Vulkan/BarrierBatch.cs | 4 +- src/Ryujinx.Graphics.Vulkan/BitMapStruct.cs | 8 +- src/Ryujinx.Graphics.Vulkan/BufferHolder.cs | 48 +++--- src/Ryujinx.Graphics.Vulkan/BufferManager.cs | 84 ++++----- .../BufferMirrorRangeList.cs | 20 +-- src/Ryujinx.Graphics.Vulkan/BufferState.cs | 3 +- .../CommandBufferPool.cs | 30 ++-- .../DescriptorSetCollection.cs | 14 +- .../DescriptorSetManager.cs | 14 +- .../DescriptorSetTemplate.cs | 4 +- .../DescriptorSetUpdater.cs | 63 +++---- .../Effects/AreaScalingFilter.cs | 6 +- .../Effects/FsrScalingFilter.cs | 16 +- .../Effects/FxaaPostProcessingEffect.cs | 10 +- .../Effects/SmaaPostProcessingEffect.cs | 29 ++-- src/Ryujinx.Graphics.Vulkan/FenceHolder.cs | 2 +- .../FormatCapabilities.cs | 20 +-- .../FramebufferParams.cs | 19 ++- src/Ryujinx.Graphics.Vulkan/HashTableSlim.cs | 14 +- src/Ryujinx.Graphics.Vulkan/HelperShader.cs | 161 +++++++++--------- .../HostMemoryAllocator.cs | 14 +- src/Ryujinx.Graphics.Vulkan/ImageArray.cs | 4 +- .../IndexBufferState.cs | 2 +- .../MemoryAllocator.cs | 6 +- .../MemoryAllocatorBlockList.cs | 14 +- .../MoltenVK/MVKInitialization.cs | 2 +- .../MultiFenceHolder.cs | 4 +- .../PersistentFlushBuffer.cs | 26 +-- src/Ryujinx.Graphics.Vulkan/PipelineBase.cs | 115 +++++++------ .../PipelineConverter.cs | 22 +-- src/Ryujinx.Graphics.Vulkan/PipelineFull.cs | 10 +- .../PipelineLayoutCache.cs | 6 +- .../PipelineLayoutCacheEntry.cs | 32 ++-- .../PipelineLayoutFactory.cs | 4 +- src/Ryujinx.Graphics.Vulkan/PipelineState.cs | 38 ++--- .../Queries/BufferedQuery.cs | 7 +- .../Queries/Counters.cs | 6 +- .../RenderPassCacheKey.cs | 2 +- .../RenderPassHolder.cs | 20 +-- src/Ryujinx.Graphics.Vulkan/ResourceArray.cs | 2 +- .../ResourceLayoutBuilder.cs | 4 +- src/Ryujinx.Graphics.Vulkan/SamplerHolder.cs | 8 +- src/Ryujinx.Graphics.Vulkan/Shader.cs | 7 +- .../ShaderCollection.cs | 22 +-- src/Ryujinx.Graphics.Vulkan/SpecInfo.cs | 4 +- src/Ryujinx.Graphics.Vulkan/StagingBuffer.cs | 14 +- src/Ryujinx.Graphics.Vulkan/TextureArray.cs | 4 +- src/Ryujinx.Graphics.Vulkan/TextureCopy.cs | 58 +++---- src/Ryujinx.Graphics.Vulkan/TextureStorage.cs | 48 +++--- src/Ryujinx.Graphics.Vulkan/TextureView.cs | 120 ++++++------- .../VertexBufferState.cs | 7 +- .../VulkanDebugMessenger.cs | 8 +- .../VulkanInitialization.cs | 49 +++--- .../VulkanPhysicalDevice.cs | 2 +- src/Ryujinx.Graphics.Vulkan/VulkanRenderer.cs | 29 ++-- src/Ryujinx.Graphics.Vulkan/Window.cs | 56 +++--- 58 files changed, 682 insertions(+), 667 deletions(-) diff --git a/src/Ryujinx.Graphics.Vulkan/Auto.cs b/src/Ryujinx.Graphics.Vulkan/Auto.cs index 606c088e9..7ce309a5d 100644 --- a/src/Ryujinx.Graphics.Vulkan/Auto.cs +++ b/src/Ryujinx.Graphics.Vulkan/Auto.cs @@ -62,7 +62,7 @@ namespace Ryujinx.Graphics.Vulkan public T GetMirrorable(CommandBufferScoped cbs, ref int offset, int size, out bool mirrored) { - var mirror = _mirrorable.GetMirrorable(cbs, ref offset, size, out mirrored); + Auto mirror = _mirrorable.GetMirrorable(cbs, ref offset, size, out mirrored); mirror._waitable?.AddBufferUse(cbs.CommandBufferIndex, offset, size, false); return mirror.Get(cbs); } diff --git a/src/Ryujinx.Graphics.Vulkan/BackgroundResources.cs b/src/Ryujinx.Graphics.Vulkan/BackgroundResources.cs index e4b68fa40..5260c5d8b 100644 --- a/src/Ryujinx.Graphics.Vulkan/BackgroundResources.cs +++ b/src/Ryujinx.Graphics.Vulkan/BackgroundResources.cs @@ -110,7 +110,7 @@ namespace Ryujinx.Graphics.Vulkan { lock (_resources) { - foreach (var resource in _resources.Values) + foreach (BackgroundResource resource in _resources.Values) { resource.Dispose(); } diff --git a/src/Ryujinx.Graphics.Vulkan/BarrierBatch.cs b/src/Ryujinx.Graphics.Vulkan/BarrierBatch.cs index bcfb3dbfe..38517bfd9 100644 --- a/src/Ryujinx.Graphics.Vulkan/BarrierBatch.cs +++ b/src/Ryujinx.Graphics.Vulkan/BarrierBatch.cs @@ -350,7 +350,7 @@ namespace Ryujinx.Graphics.Vulkan { // Generic pipeline memory barriers will work for desktop GPUs. // They do require a few more access flags on the subpass dependency, though. - foreach (var barrier in _imageBarriers) + foreach (BarrierWithStageFlags barrier in _imageBarriers) { _memoryBarriers.Add(new BarrierWithStageFlags( barrier.Flags, @@ -370,7 +370,7 @@ namespace Ryujinx.Graphics.Vulkan { PipelineStageFlags allFlags = PipelineStageFlags.None; - foreach (var barrier in _memoryBarriers) + foreach (BarrierWithStageFlags barrier in _memoryBarriers) { allFlags |= barrier.Flags.Dest; } diff --git a/src/Ryujinx.Graphics.Vulkan/BitMapStruct.cs b/src/Ryujinx.Graphics.Vulkan/BitMapStruct.cs index 43107427c..7af8c42f6 100644 --- a/src/Ryujinx.Graphics.Vulkan/BitMapStruct.cs +++ b/src/Ryujinx.Graphics.Vulkan/BitMapStruct.cs @@ -220,11 +220,11 @@ namespace Ryujinx.Graphics.Vulkan public BitMapStruct Union(BitMapStruct other) { - var result = new BitMapStruct(); + BitMapStruct result = new BitMapStruct(); - ref var masks = ref _masks; - ref var otherMasks = ref other._masks; - ref var newMasks = ref result._masks; + ref T masks = ref _masks; + ref T otherMasks = ref other._masks; + ref T newMasks = ref result._masks; for (int i = 0; i < masks.Length; i++) { diff --git a/src/Ryujinx.Graphics.Vulkan/BufferHolder.cs b/src/Ryujinx.Graphics.Vulkan/BufferHolder.cs index 6dce6abb5..df5b96637 100644 --- a/src/Ryujinx.Graphics.Vulkan/BufferHolder.cs +++ b/src/Ryujinx.Graphics.Vulkan/BufferHolder.cs @@ -113,7 +113,7 @@ namespace Ryujinx.Graphics.Vulkan public unsafe Auto CreateView(VkFormat format, int offset, int size, Action invalidateView) { - var bufferViewCreateInfo = new BufferViewCreateInfo + BufferViewCreateInfo bufferViewCreateInfo = new BufferViewCreateInfo { SType = StructureType.BufferViewCreateInfo, Buffer = new VkBuffer(_bufferHandle), @@ -122,7 +122,7 @@ namespace Ryujinx.Graphics.Vulkan Range = (uint)size, }; - _gd.Api.CreateBufferView(_device, in bufferViewCreateInfo, null, out var bufferView).ThrowOnError(); + _gd.Api.CreateBufferView(_device, in bufferViewCreateInfo, null, out BufferView bufferView).ThrowOnError(); return new Auto(new DisposableBufferView(_gd.Api, _device, bufferView), this, _waitable, _buffer); } @@ -183,7 +183,7 @@ namespace Ryujinx.Graphics.Vulkan return false; } - var key = ToMirrorKey(offset, size); + ulong key = ToMirrorKey(offset, size); if (_mirrors.TryGetValue(key, out StagingBufferReserved reserved)) { @@ -205,14 +205,14 @@ namespace Ryujinx.Graphics.Vulkan // Build data for the new mirror. - var baseData = new Span((void*)(_map + offset), size); - var modData = _pendingData.AsSpan(offset, size); + Span baseData = new Span((void*)(_map + offset), size); + Span modData = _pendingData.AsSpan(offset, size); StagingBufferReserved? newMirror = _gd.BufferManager.StagingBuffer.TryReserveData(cbs, size); if (newMirror != null) { - var mirror = newMirror.Value; + StagingBufferReserved mirror = newMirror.Value; _pendingDataRanges.FillData(baseData, modData, offset, new Span((void*)(mirror.Buffer._map + mirror.Offset), size)); if (_mirrors.Count == 0) @@ -319,13 +319,13 @@ namespace Ryujinx.Graphics.Vulkan private void UploadPendingData(CommandBufferScoped cbs, int offset, int size) { - var ranges = _pendingDataRanges.FindOverlaps(offset, size); + List ranges = _pendingDataRanges.FindOverlaps(offset, size); if (ranges != null) { _pendingDataRanges.Remove(offset, size); - foreach (var range in ranges) + foreach (BufferMirrorRangeList.Range range in ranges) { int rangeOffset = Math.Max(offset, range.Offset); int rangeSize = Math.Min(offset + size, range.End) - rangeOffset; @@ -366,7 +366,7 @@ namespace Ryujinx.Graphics.Vulkan public BufferHandle GetHandle() { - var handle = _bufferHandle; + ulong handle = _bufferHandle; return Unsafe.As(ref handle); } @@ -403,7 +403,7 @@ namespace Ryujinx.Graphics.Vulkan if (_flushFence != null) { - var fence = _flushFence; + FenceHolder fence = _flushFence; Interlocked.Increment(ref _flushWaiting); // Don't wait in the lock. @@ -481,7 +481,7 @@ namespace Ryujinx.Graphics.Vulkan public bool RemoveOverlappingMirrors(int offset, int size) { List toRemove = null; - foreach (var key in _mirrors.Keys) + foreach (ulong key in _mirrors.Keys) { (int keyOffset, int keySize) = FromMirrorKey(key); if (!(offset + size <= keyOffset || offset >= keyOffset + keySize)) @@ -494,7 +494,7 @@ namespace Ryujinx.Graphics.Vulkan if (toRemove != null) { - foreach (var key in toRemove) + foreach (ulong key in toRemove) { _mirrors.Remove(key); } @@ -606,8 +606,8 @@ namespace Ryujinx.Graphics.Vulkan BufferHolder srcHolder = _gd.BufferManager.Create(_gd, dataSize, baseType: BufferAllocationType.HostMapped); srcHolder.SetDataUnchecked(0, data); - var srcBuffer = srcHolder.GetBuffer(); - var dstBuffer = this.GetBuffer(cbs.Value.CommandBuffer, true); + Auto srcBuffer = srcHolder.GetBuffer(); + Auto dstBuffer = this.GetBuffer(cbs.Value.CommandBuffer, true); Copy(_gd, cbs.Value, srcBuffer, dstBuffer, 0, offset, dataSize); @@ -662,7 +662,7 @@ namespace Ryujinx.Graphics.Vulkan endRenderPass?.Invoke(); - var dstBuffer = GetBuffer(cbs.CommandBuffer, dstOffset, data.Length, true).Get(cbs, dstOffset, data.Length, true).Value; + VkBuffer dstBuffer = GetBuffer(cbs.CommandBuffer, dstOffset, data.Length, true).Get(cbs, dstOffset, data.Length, true).Value; InsertBufferBarrier( _gd, @@ -709,8 +709,8 @@ namespace Ryujinx.Graphics.Vulkan int size, bool registerSrcUsage = true) { - var srcBuffer = registerSrcUsage ? src.Get(cbs, srcOffset, size).Value : src.GetUnsafe().Value; - var dstBuffer = dst.Get(cbs, dstOffset, size, true).Value; + VkBuffer srcBuffer = registerSrcUsage ? src.Get(cbs, srcOffset, size).Value : src.GetUnsafe().Value; + VkBuffer dstBuffer = dst.Get(cbs, dstOffset, size, true).Value; InsertBufferBarrier( gd, @@ -723,7 +723,7 @@ namespace Ryujinx.Graphics.Vulkan dstOffset, size); - var region = new BufferCopy((ulong)srcOffset, (ulong)dstOffset, (ulong)size); + BufferCopy region = new BufferCopy((ulong)srcOffset, (ulong)dstOffset, (ulong)size); gd.Api.CmdCopyBuffer(cbs.CommandBuffer, srcBuffer, dstBuffer, 1, ®ion); @@ -804,9 +804,9 @@ namespace Ryujinx.Graphics.Vulkan return null; } - var key = new I8ToI16CacheKey(_gd); + I8ToI16CacheKey key = new I8ToI16CacheKey(_gd); - if (!_cachedConvertedBuffers.TryGetValue(offset, size, key, out var holder)) + if (!_cachedConvertedBuffers.TryGetValue(offset, size, key, out BufferHolder holder)) { holder = _gd.BufferManager.Create(_gd, (size * 2 + 3) & ~3, baseType: BufferAllocationType.DeviceLocal); @@ -828,9 +828,9 @@ namespace Ryujinx.Graphics.Vulkan return null; } - var key = new AlignedVertexBufferCacheKey(_gd, stride, alignment); + AlignedVertexBufferCacheKey key = new AlignedVertexBufferCacheKey(_gd, stride, alignment); - if (!_cachedConvertedBuffers.TryGetValue(offset, size, key, out var holder)) + if (!_cachedConvertedBuffers.TryGetValue(offset, size, key, out BufferHolder holder)) { int alignedStride = (stride + (alignment - 1)) & -alignment; @@ -854,9 +854,9 @@ namespace Ryujinx.Graphics.Vulkan return null; } - var key = new TopologyConversionCacheKey(_gd, pattern, indexSize); + TopologyConversionCacheKey key = new TopologyConversionCacheKey(_gd, pattern, indexSize); - if (!_cachedConvertedBuffers.TryGetValue(offset, size, key, out var holder)) + if (!_cachedConvertedBuffers.TryGetValue(offset, size, key, out BufferHolder holder)) { // The destination index size is always I32. diff --git a/src/Ryujinx.Graphics.Vulkan/BufferManager.cs b/src/Ryujinx.Graphics.Vulkan/BufferManager.cs index 7523913ec..e2c33ce65 100644 --- a/src/Ryujinx.Graphics.Vulkan/BufferManager.cs +++ b/src/Ryujinx.Graphics.Vulkan/BufferManager.cs @@ -96,20 +96,20 @@ namespace Ryujinx.Graphics.Vulkan public unsafe BufferHandle CreateHostImported(VulkanRenderer gd, nint pointer, int size) { - var usage = HostImportedBufferUsageFlags; + BufferUsageFlags usage = HostImportedBufferUsageFlags; if (gd.Capabilities.SupportsIndirectParameters) { usage |= BufferUsageFlags.IndirectBufferBit; } - var externalMemoryBuffer = new ExternalMemoryBufferCreateInfo + ExternalMemoryBufferCreateInfo externalMemoryBuffer = new ExternalMemoryBufferCreateInfo { SType = StructureType.ExternalMemoryBufferCreateInfo, HandleTypes = ExternalMemoryHandleTypeFlags.HostAllocationBitExt, }; - var bufferCreateInfo = new BufferCreateInfo + BufferCreateInfo bufferCreateInfo = new BufferCreateInfo { SType = StructureType.BufferCreateInfo, Size = (ulong)size, @@ -118,13 +118,13 @@ namespace Ryujinx.Graphics.Vulkan PNext = &externalMemoryBuffer, }; - gd.Api.CreateBuffer(_device, in bufferCreateInfo, null, out var buffer).ThrowOnError(); + gd.Api.CreateBuffer(_device, in bufferCreateInfo, null, out VkBuffer buffer).ThrowOnError(); (Auto allocation, ulong offset) = gd.HostMemoryAllocator.GetExistingAllocation(pointer, (ulong)size); gd.Api.BindBufferMemory(_device, buffer, allocation.GetUnsafe().Memory, allocation.GetUnsafe().Offset + offset); - var holder = new BufferHolder(gd, _device, buffer, allocation, size, BufferAllocationType.HostMapped, BufferAllocationType.HostMapped, (int)offset); + BufferHolder holder = new BufferHolder(gd, _device, buffer, allocation, size, BufferAllocationType.HostMapped, BufferAllocationType.HostMapped, (int)offset); BufferCount++; @@ -135,7 +135,7 @@ namespace Ryujinx.Graphics.Vulkan public unsafe BufferHandle CreateSparse(VulkanRenderer gd, ReadOnlySpan storageBuffers) { - var usage = DefaultBufferUsageFlags; + BufferUsageFlags usage = DefaultBufferUsageFlags; if (gd.Capabilities.SupportsIndirectParameters) { @@ -149,7 +149,7 @@ namespace Ryujinx.Graphics.Vulkan size += (ulong)range.Size; } - var bufferCreateInfo = new BufferCreateInfo() + BufferCreateInfo bufferCreateInfo = new BufferCreateInfo() { SType = StructureType.BufferCreateInfo, Size = size, @@ -158,10 +158,10 @@ namespace Ryujinx.Graphics.Vulkan Flags = BufferCreateFlags.SparseBindingBit | BufferCreateFlags.SparseAliasedBit }; - gd.Api.CreateBuffer(_device, in bufferCreateInfo, null, out var buffer).ThrowOnError(); + gd.Api.CreateBuffer(_device, in bufferCreateInfo, null, out VkBuffer buffer).ThrowOnError(); - var memoryBinds = new SparseMemoryBind[storageBuffers.Length]; - var storageAllocations = new Auto[storageBuffers.Length]; + SparseMemoryBind[] memoryBinds = new SparseMemoryBind[storageBuffers.Length]; + Auto[] storageAllocations = new Auto[storageBuffers.Length]; int storageAllocationsCount = 0; ulong dstOffset = 0; @@ -170,9 +170,9 @@ namespace Ryujinx.Graphics.Vulkan { BufferRange range = storageBuffers[index]; - if (TryGetBuffer(range.Handle, out var existingHolder)) + if (TryGetBuffer(range.Handle, out BufferHolder existingHolder)) { - (var memory, var offset) = existingHolder.GetDeviceMemoryAndOffset(); + (DeviceMemory memory, ulong offset) = existingHolder.GetDeviceMemoryAndOffset(); memoryBinds[index] = new SparseMemoryBind() { @@ -224,7 +224,7 @@ namespace Ryujinx.Graphics.Vulkan gd.Api.QueueBindSparse(gd.Queue, 1, in bindSparseInfo, default).ThrowOnError(); } - var holder = new BufferHolder(gd, _device, buffer, (int)size, storageAllocations); + BufferHolder holder = new BufferHolder(gd, _device, buffer, (int)size, storageAllocations); BufferCount++; @@ -288,14 +288,14 @@ namespace Ryujinx.Graphics.Vulkan public unsafe MemoryRequirements GetHostImportedUsageRequirements(VulkanRenderer gd) { - var usage = HostImportedBufferUsageFlags; + BufferUsageFlags usage = HostImportedBufferUsageFlags; if (gd.Capabilities.SupportsIndirectParameters) { usage |= BufferUsageFlags.IndirectBufferBit; } - var bufferCreateInfo = new BufferCreateInfo + BufferCreateInfo bufferCreateInfo = new BufferCreateInfo { SType = StructureType.BufferCreateInfo, Size = (ulong)Environment.SystemPageSize, @@ -303,9 +303,9 @@ namespace Ryujinx.Graphics.Vulkan SharingMode = SharingMode.Exclusive, }; - gd.Api.CreateBuffer(_device, in bufferCreateInfo, null, out var buffer).ThrowOnError(); + gd.Api.CreateBuffer(_device, in bufferCreateInfo, null, out VkBuffer buffer).ThrowOnError(); - gd.Api.GetBufferMemoryRequirements(_device, buffer, out var requirements); + gd.Api.GetBufferMemoryRequirements(_device, buffer, out MemoryRequirements requirements); gd.Api.DestroyBuffer(_device, buffer, null); @@ -320,7 +320,7 @@ namespace Ryujinx.Graphics.Vulkan bool sparseCompatible = false, BufferAllocationType fallbackType = BufferAllocationType.Auto) { - var usage = DefaultBufferUsageFlags; + BufferUsageFlags usage = DefaultBufferUsageFlags; if (forConditionalRendering && gd.Capabilities.SupportsConditionalRendering) { @@ -331,7 +331,7 @@ namespace Ryujinx.Graphics.Vulkan usage |= BufferUsageFlags.IndirectBufferBit; } - var bufferCreateInfo = new BufferCreateInfo + BufferCreateInfo bufferCreateInfo = new BufferCreateInfo { SType = StructureType.BufferCreateInfo, Size = (ulong)size, @@ -339,8 +339,8 @@ namespace Ryujinx.Graphics.Vulkan SharingMode = SharingMode.Exclusive, }; - gd.Api.CreateBuffer(_device, in bufferCreateInfo, null, out var buffer).ThrowOnError(); - gd.Api.GetBufferMemoryRequirements(_device, buffer, out var requirements); + gd.Api.CreateBuffer(_device, in bufferCreateInfo, null, out VkBuffer buffer).ThrowOnError(); + gd.Api.GetBufferMemoryRequirements(_device, buffer, out MemoryRequirements requirements); if (sparseCompatible) { @@ -351,7 +351,7 @@ namespace Ryujinx.Graphics.Vulkan do { - var allocateFlags = type switch + MemoryPropertyFlags allocateFlags = type switch { BufferAllocationType.HostMappedNoCache => DefaultBufferMemoryNoCacheFlags, BufferAllocationType.HostMapped => DefaultBufferMemoryFlags, @@ -402,7 +402,7 @@ namespace Ryujinx.Graphics.Vulkan if (buffer.Handle != 0) { - var holder = new BufferHolder(gd, _device, buffer, allocation, size, baseType, resultType); + BufferHolder holder = new BufferHolder(gd, _device, buffer, allocation, size, baseType, resultType); return holder; } @@ -414,7 +414,7 @@ namespace Ryujinx.Graphics.Vulkan public Auto CreateView(BufferHandle handle, VkFormat format, int offset, int size, Action invalidateView) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { return holder.CreateView(format, offset, size, invalidateView); } @@ -424,7 +424,7 @@ namespace Ryujinx.Graphics.Vulkan public Auto GetBuffer(CommandBuffer commandBuffer, BufferHandle handle, bool isWrite, bool isSSBO = false) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { return holder.GetBuffer(commandBuffer, isWrite, isSSBO); } @@ -434,7 +434,7 @@ namespace Ryujinx.Graphics.Vulkan public Auto GetBuffer(CommandBuffer commandBuffer, BufferHandle handle, int offset, int size, bool isWrite) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { return holder.GetBuffer(commandBuffer, offset, size, isWrite); } @@ -444,7 +444,7 @@ namespace Ryujinx.Graphics.Vulkan public Auto GetBufferI8ToI16(CommandBufferScoped cbs, BufferHandle handle, int offset, int size) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { return holder.GetBufferI8ToI16(cbs, offset, size); } @@ -454,7 +454,7 @@ namespace Ryujinx.Graphics.Vulkan public Auto GetAlignedVertexBuffer(CommandBufferScoped cbs, BufferHandle handle, int offset, int size, int stride, int alignment) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { return holder.GetAlignedVertexBuffer(cbs, offset, size, stride, alignment); } @@ -464,7 +464,7 @@ namespace Ryujinx.Graphics.Vulkan public Auto GetBufferTopologyConversion(CommandBufferScoped cbs, BufferHandle handle, int offset, int size, IndexBufferPattern pattern, int indexSize) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { return holder.GetBufferTopologyConversion(cbs, offset, size, pattern, indexSize); } @@ -486,14 +486,14 @@ namespace Ryujinx.Graphics.Vulkan { BufferHolder drawCountBufferHolder = null; - if (!TryGetBuffer(indexBuffer.Handle, out var indexBufferHolder) || - !TryGetBuffer(indirectBuffer.Handle, out var indirectBufferHolder) || + if (!TryGetBuffer(indexBuffer.Handle, out BufferHolder indexBufferHolder) || + !TryGetBuffer(indirectBuffer.Handle, out BufferHolder indirectBufferHolder) || (hasDrawCount && !TryGetBuffer(drawCountBuffer.Handle, out drawCountBufferHolder))) { return (null, null); } - var indexBufferKey = new TopologyConversionIndirectCacheKey( + TopologyConversionIndirectCacheKey indexBufferKey = new TopologyConversionIndirectCacheKey( gd, pattern, indexSize, @@ -505,16 +505,16 @@ namespace Ryujinx.Graphics.Vulkan indexBuffer.Offset, indexBuffer.Size, indexBufferKey, - out var convertedIndexBuffer); + out BufferHolder convertedIndexBuffer); - var indirectBufferKey = new IndirectDataCacheKey(pattern); + IndirectDataCacheKey indirectBufferKey = new IndirectDataCacheKey(pattern); bool hasConvertedIndirectBuffer = indirectBufferHolder.TryGetCachedConvertedBuffer( indirectBuffer.Offset, indirectBuffer.Size, indirectBufferKey, - out var convertedIndirectBuffer); + out BufferHolder convertedIndirectBuffer); - var drawCountBufferKey = new DrawCountCacheKey(); + DrawCountCacheKey drawCountBufferKey = new DrawCountCacheKey(); bool hasCachedDrawCount = true; if (hasDrawCount) @@ -568,7 +568,7 @@ namespace Ryujinx.Graphics.Vulkan // Any modification of the indirect buffer should invalidate the index buffers that are associated with it, // since we used the indirect data to find the range of the index buffer that is used. - var indexBufferDependency = new Dependency( + Dependency indexBufferDependency = new Dependency( indexBufferHolder, indexBuffer.Offset, indexBuffer.Size, @@ -590,7 +590,7 @@ namespace Ryujinx.Graphics.Vulkan // If we have a draw count, any modification of the draw count should invalidate all indirect buffers // where we used it to find the range of indirect data that is actually used. - var indirectBufferDependency = new Dependency( + Dependency indirectBufferDependency = new Dependency( indirectBufferHolder, indirectBuffer.Offset, indirectBuffer.Size, @@ -609,7 +609,7 @@ namespace Ryujinx.Graphics.Vulkan public Auto GetBuffer(CommandBuffer commandBuffer, BufferHandle handle, bool isWrite, out int size) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { size = holder.Size; return holder.GetBuffer(commandBuffer, isWrite); @@ -621,7 +621,7 @@ namespace Ryujinx.Graphics.Vulkan public PinnedSpan GetData(BufferHandle handle, int offset, int size) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { return holder.GetData(offset, size); } @@ -636,7 +636,7 @@ namespace Ryujinx.Graphics.Vulkan public void SetData(BufferHandle handle, int offset, ReadOnlySpan data, CommandBufferScoped? cbs, Action endRenderPass) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { holder.SetData(offset, data, cbs, endRenderPass); } @@ -644,7 +644,7 @@ namespace Ryujinx.Graphics.Vulkan public void Delete(BufferHandle handle) { - if (TryGetBuffer(handle, out var holder)) + if (TryGetBuffer(handle, out BufferHolder holder)) { holder.Dispose(); _buffers.Remove((int)Unsafe.As(ref handle)); diff --git a/src/Ryujinx.Graphics.Vulkan/BufferMirrorRangeList.cs b/src/Ryujinx.Graphics.Vulkan/BufferMirrorRangeList.cs index f7f78b613..022880b53 100644 --- a/src/Ryujinx.Graphics.Vulkan/BufferMirrorRangeList.cs +++ b/src/Ryujinx.Graphics.Vulkan/BufferMirrorRangeList.cs @@ -38,7 +38,7 @@ namespace Ryujinx.Graphics.Vulkan public readonly bool Remove(int offset, int size) { - var list = _ranges; + List list = _ranges; bool removedAny = false; if (list != null) { @@ -56,7 +56,7 @@ namespace Ryujinx.Graphics.Vulkan int endOffset = offset + size; int startIndex = overlapIndex; - var currentOverlap = list[overlapIndex]; + Range currentOverlap = list[overlapIndex]; // Orphan the start of the overlap. if (currentOverlap.Offset < offset) @@ -102,7 +102,7 @@ namespace Ryujinx.Graphics.Vulkan public void Add(int offset, int size) { - var list = _ranges; + List list = _ranges; if (list != null) { int overlapIndex = BinarySearch(list, offset, size); @@ -118,8 +118,8 @@ namespace Ryujinx.Graphics.Vulkan while (overlapIndex < list.Count && list[overlapIndex].OverlapsWith(offset, size)) { - var currentOverlap = list[overlapIndex]; - var currentOverlapEndOffset = currentOverlap.Offset + currentOverlap.Size; + Range currentOverlap = list[overlapIndex]; + int currentOverlapEndOffset = currentOverlap.Offset + currentOverlap.Size; if (offset > currentOverlap.Offset) { @@ -159,7 +159,7 @@ namespace Ryujinx.Graphics.Vulkan public readonly bool OverlapsWith(int offset, int size) { - var list = _ranges; + List list = _ranges; if (list == null) { return false; @@ -170,7 +170,7 @@ namespace Ryujinx.Graphics.Vulkan public readonly List FindOverlaps(int offset, int size) { - var list = _ranges; + List list = _ranges; if (list == null) { return null; @@ -208,7 +208,7 @@ namespace Ryujinx.Graphics.Vulkan int middle = left + (range >> 1); - var item = list[middle]; + Range item = list[middle]; if (item.OverlapsWith(offset, size)) { @@ -233,7 +233,7 @@ namespace Ryujinx.Graphics.Vulkan int size = baseData.Length; int endOffset = offset + size; - var list = _ranges; + List list = _ranges; if (list == null) { baseData.CopyTo(result); @@ -245,7 +245,7 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < list.Count; i++) { - var range = list[i]; + Range range = list[i]; int rangeEnd = range.Offset + range.Size; diff --git a/src/Ryujinx.Graphics.Vulkan/BufferState.cs b/src/Ryujinx.Graphics.Vulkan/BufferState.cs index e49df765d..bc7c847f1 100644 --- a/src/Ryujinx.Graphics.Vulkan/BufferState.cs +++ b/src/Ryujinx.Graphics.Vulkan/BufferState.cs @@ -1,4 +1,5 @@ using System; +using Buffer = Silk.NET.Vulkan.Buffer; namespace Ryujinx.Graphics.Vulkan { @@ -23,7 +24,7 @@ namespace Ryujinx.Graphics.Vulkan { if (_buffer != null) { - var buffer = _buffer.Get(cbs, _offset, _size, true).Value; + Buffer buffer = _buffer.Get(cbs, _offset, _size, true).Value; ulong offset = (ulong)_offset; ulong size = (ulong)_size; diff --git a/src/Ryujinx.Graphics.Vulkan/CommandBufferPool.cs b/src/Ryujinx.Graphics.Vulkan/CommandBufferPool.cs index ed76c6566..255277ff6 100644 --- a/src/Ryujinx.Graphics.Vulkan/CommandBufferPool.cs +++ b/src/Ryujinx.Graphics.Vulkan/CommandBufferPool.cs @@ -37,7 +37,7 @@ namespace Ryujinx.Graphics.Vulkan public void Initialize(Vk api, Device device, CommandPool pool) { - var allocateInfo = new CommandBufferAllocateInfo + CommandBufferAllocateInfo allocateInfo = new CommandBufferAllocateInfo { SType = StructureType.CommandBufferAllocateInfo, CommandBufferCount = 1, @@ -75,7 +75,7 @@ namespace Ryujinx.Graphics.Vulkan _concurrentFenceWaitUnsupported = concurrentFenceWaitUnsupported; _owner = Thread.CurrentThread; - var commandPoolCreateInfo = new CommandPoolCreateInfo + CommandPoolCreateInfo commandPoolCreateInfo = new CommandPoolCreateInfo { SType = StructureType.CommandPoolCreateInfo, QueueFamilyIndex = queueFamilyIndex, @@ -114,7 +114,7 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < _totalCommandBuffers; i++) { - ref var entry = ref _commandBuffers[i]; + ref ReservedCommandBuffer entry = ref _commandBuffers[i]; if (entry.InConsumption) { @@ -130,7 +130,7 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < _totalCommandBuffers; i++) { - ref var entry = ref _commandBuffers[i]; + ref ReservedCommandBuffer entry = ref _commandBuffers[i]; if (entry.InUse) { @@ -142,7 +142,7 @@ namespace Ryujinx.Graphics.Vulkan public void AddWaitable(int cbIndex, MultiFenceHolder waitable) { - ref var entry = ref _commandBuffers[cbIndex]; + ref ReservedCommandBuffer entry = ref _commandBuffers[cbIndex]; if (waitable.AddFence(cbIndex, entry.Fence)) { entry.Waitables.Add(waitable); @@ -155,7 +155,7 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < _totalCommandBuffers; i++) { - ref var entry = ref _commandBuffers[i]; + ref ReservedCommandBuffer entry = ref _commandBuffers[i]; if (entry.InUse && waitable.HasFence(i) && @@ -175,7 +175,7 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < _totalCommandBuffers; i++) { - ref var entry = ref _commandBuffers[i]; + ref ReservedCommandBuffer entry = ref _commandBuffers[i]; if (entry.InUse && entry.Fence == fence) { @@ -205,7 +205,7 @@ namespace Ryujinx.Graphics.Vulkan { int index = _queuedIndexes[_queuedIndexesPtr]; - ref var entry = ref _commandBuffers[index]; + ref ReservedCommandBuffer entry = ref _commandBuffers[index]; if (wait || !entry.InConsumption || entry.Fence.IsSignaled()) { @@ -240,7 +240,7 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < _totalCommandBuffers; i++) { - ref var entry = ref _commandBuffers[cursor]; + ref ReservedCommandBuffer entry = ref _commandBuffers[cursor]; if (!entry.InUse && !entry.InConsumption) { @@ -248,7 +248,7 @@ namespace Ryujinx.Graphics.Vulkan _inUseCount++; - var commandBufferBeginInfo = new CommandBufferBeginInfo + CommandBufferBeginInfo commandBufferBeginInfo = new CommandBufferBeginInfo { SType = StructureType.CommandBufferBeginInfo, }; @@ -280,7 +280,7 @@ namespace Ryujinx.Graphics.Vulkan { int cbIndex = cbs.CommandBufferIndex; - ref var entry = ref _commandBuffers[cbIndex]; + ref ReservedCommandBuffer entry = ref _commandBuffers[cbIndex]; Debug.Assert(entry.InUse); Debug.Assert(entry.CommandBuffer.Handle == cbs.CommandBuffer.Handle); @@ -289,7 +289,7 @@ namespace Ryujinx.Graphics.Vulkan entry.SubmissionCount++; _inUseCount--; - var commandBuffer = entry.CommandBuffer; + CommandBuffer commandBuffer = entry.CommandBuffer; _api.EndCommandBuffer(commandBuffer).ThrowOnError(); @@ -324,7 +324,7 @@ namespace Ryujinx.Graphics.Vulkan private void WaitAndDecrementRef(int cbIndex, bool refreshFence = true) { - ref var entry = ref _commandBuffers[cbIndex]; + ref ReservedCommandBuffer entry = ref _commandBuffers[cbIndex]; if (entry.InConsumption) { @@ -332,12 +332,12 @@ namespace Ryujinx.Graphics.Vulkan entry.InConsumption = false; } - foreach (var dependant in entry.Dependants) + foreach (IAuto dependant in entry.Dependants) { dependant.DecrementReferenceCount(cbIndex); } - foreach (var waitable in entry.Waitables) + foreach (MultiFenceHolder waitable in entry.Waitables) { waitable.RemoveFence(cbIndex); waitable.RemoveBufferUses(cbIndex); diff --git a/src/Ryujinx.Graphics.Vulkan/DescriptorSetCollection.cs b/src/Ryujinx.Graphics.Vulkan/DescriptorSetCollection.cs index 40fc01b24..439f58815 100644 --- a/src/Ryujinx.Graphics.Vulkan/DescriptorSetCollection.cs +++ b/src/Ryujinx.Graphics.Vulkan/DescriptorSetCollection.cs @@ -33,7 +33,7 @@ namespace Ryujinx.Graphics.Vulkan { if (bufferInfo.Buffer.Handle != 0UL) { - var writeDescriptorSet = new WriteDescriptorSet + WriteDescriptorSet writeDescriptorSet = new WriteDescriptorSet { SType = StructureType.WriteDescriptorSet, DstSet = _descriptorSets[setIndex], @@ -56,7 +56,7 @@ namespace Ryujinx.Graphics.Vulkan fixed (DescriptorBufferInfo* pBufferInfo = bufferInfo) { - var writeDescriptorSet = new WriteDescriptorSet + WriteDescriptorSet writeDescriptorSet = new WriteDescriptorSet { SType = StructureType.WriteDescriptorSet, DstSet = _descriptorSets[setIndex], @@ -74,7 +74,7 @@ namespace Ryujinx.Graphics.Vulkan { if (imageInfo.ImageView.Handle != 0UL) { - var writeDescriptorSet = new WriteDescriptorSet + WriteDescriptorSet writeDescriptorSet = new WriteDescriptorSet { SType = StructureType.WriteDescriptorSet, DstSet = _descriptorSets[setIndex], @@ -97,7 +97,7 @@ namespace Ryujinx.Graphics.Vulkan fixed (DescriptorImageInfo* pImageInfo = imageInfo) { - var writeDescriptorSet = new WriteDescriptorSet + WriteDescriptorSet writeDescriptorSet = new WriteDescriptorSet { SType = StructureType.WriteDescriptorSet, DstSet = _descriptorSets[setIndex], @@ -134,7 +134,7 @@ namespace Ryujinx.Graphics.Vulkan count++; } - var writeDescriptorSet = new WriteDescriptorSet + WriteDescriptorSet writeDescriptorSet = new WriteDescriptorSet { SType = StructureType.WriteDescriptorSet, DstSet = _descriptorSets[setIndex], @@ -156,7 +156,7 @@ namespace Ryujinx.Graphics.Vulkan { if (texelBufferView.Handle != 0UL) { - var writeDescriptorSet = new WriteDescriptorSet + WriteDescriptorSet writeDescriptorSet = new WriteDescriptorSet { SType = StructureType.WriteDescriptorSet, DstSet = _descriptorSets[setIndex], @@ -190,7 +190,7 @@ namespace Ryujinx.Graphics.Vulkan count++; } - var writeDescriptorSet = new WriteDescriptorSet + WriteDescriptorSet writeDescriptorSet = new WriteDescriptorSet { SType = StructureType.WriteDescriptorSet, DstSet = _descriptorSets[setIndex], diff --git a/src/Ryujinx.Graphics.Vulkan/DescriptorSetManager.cs b/src/Ryujinx.Graphics.Vulkan/DescriptorSetManager.cs index 97669942c..1d68407b9 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; - foreach (var poolSize in poolSizes) + foreach (DescriptorPoolSize poolSize in poolSizes) { _freeDescriptors += (int)poolSize.DescriptorCount; } fixed (DescriptorPoolSize* pPoolsSize = poolSizes) { - var descriptorPoolCreateInfo = new DescriptorPoolCreateInfo + DescriptorPoolCreateInfo descriptorPoolCreateInfo = new DescriptorPoolCreateInfo { SType = StructureType.DescriptorPoolCreateInfo, Flags = updateAfterBind ? DescriptorPoolCreateFlags.UpdateAfterBindBit : DescriptorPoolCreateFlags.None, @@ -46,7 +46,7 @@ namespace Ryujinx.Graphics.Vulkan public unsafe DescriptorSetCollection AllocateDescriptorSets(ReadOnlySpan layouts, int consumedDescriptors) { - TryAllocateDescriptorSets(layouts, consumedDescriptors, isTry: false, out var dsc); + TryAllocateDescriptorSets(layouts, consumedDescriptors, isTry: false, out DescriptorSetCollection dsc); return dsc; } @@ -69,7 +69,7 @@ namespace Ryujinx.Graphics.Vulkan { fixed (DescriptorSetLayout* pLayouts = layouts) { - var descriptorSetAllocateInfo = new DescriptorSetAllocateInfo + DescriptorSetAllocateInfo descriptorSetAllocateInfo = new DescriptorSetAllocateInfo { SType = StructureType.DescriptorSetAllocateInfo, DescriptorPool = _pool, @@ -77,7 +77,7 @@ namespace Ryujinx.Graphics.Vulkan PSetLayouts = pLayouts, }; - var result = Api.AllocateDescriptorSets(Device, &descriptorSetAllocateInfo, pDescriptorSets); + Result result = Api.AllocateDescriptorSets(Device, &descriptorSetAllocateInfo, pDescriptorSets); if (isTry && result == Result.ErrorOutOfPoolMemory) { _totalSets = (int)MaxSets; @@ -182,8 +182,8 @@ namespace Ryujinx.Graphics.Vulkan { // If we fail the first time, just create a new pool and try again. - var pool = GetPool(api, poolSizes, poolIndex, layouts.Length, consumedDescriptors, updateAfterBind); - if (!pool.TryAllocateDescriptorSets(layouts, consumedDescriptors, out var dsc)) + DescriptorPoolHolder pool = GetPool(api, poolSizes, poolIndex, layouts.Length, consumedDescriptors, updateAfterBind); + if (!pool.TryAllocateDescriptorSets(layouts, consumedDescriptors, out DescriptorSetCollection dsc)) { pool = GetPool(api, poolSizes, poolIndex, layouts.Length, consumedDescriptors, updateAfterBind); dsc = pool.AllocateDescriptorSets(layouts, consumedDescriptors); diff --git a/src/Ryujinx.Graphics.Vulkan/DescriptorSetTemplate.cs b/src/Ryujinx.Graphics.Vulkan/DescriptorSetTemplate.cs index 117f79bb4..5dc7afb48 100644 --- a/src/Ryujinx.Graphics.Vulkan/DescriptorSetTemplate.cs +++ b/src/Ryujinx.Graphics.Vulkan/DescriptorSetTemplate.cs @@ -86,7 +86,7 @@ namespace Ryujinx.Graphics.Vulkan Size = (int)structureOffset; - var info = new DescriptorUpdateTemplateCreateInfo() + DescriptorUpdateTemplateCreateInfo info = new DescriptorUpdateTemplateCreateInfo() { SType = StructureType.DescriptorUpdateTemplateCreateInfo, DescriptorUpdateEntryCount = (uint)segments.Length, @@ -173,7 +173,7 @@ namespace Ryujinx.Graphics.Vulkan Size = (int)structureOffset; - var info = new DescriptorUpdateTemplateCreateInfo() + DescriptorUpdateTemplateCreateInfo info = new DescriptorUpdateTemplateCreateInfo() { SType = StructureType.DescriptorUpdateTemplateCreateInfo, DescriptorUpdateEntryCount = (uint)entry, diff --git a/src/Ryujinx.Graphics.Vulkan/DescriptorSetUpdater.cs b/src/Ryujinx.Graphics.Vulkan/DescriptorSetUpdater.cs index 3780dc174..2c98b80c7 100644 --- a/src/Ryujinx.Graphics.Vulkan/DescriptorSetUpdater.cs +++ b/src/Ryujinx.Graphics.Vulkan/DescriptorSetUpdater.cs @@ -7,6 +7,7 @@ using System.Buffers; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using Buffer = Silk.NET.Vulkan.Buffer; using CompareOp = Ryujinx.Graphics.GAL.CompareOp; using Format = Ryujinx.Graphics.GAL.Format; using SamplerCreateInfo = Ryujinx.Graphics.GAL.SamplerCreateInfo; @@ -156,7 +157,7 @@ namespace Ryujinx.Graphics.Vulkan _uniformSetPd = new int[Constants.MaxUniformBufferBindings]; - var initialImageInfo = new DescriptorImageInfo + DescriptorImageInfo initialImageInfo = new DescriptorImageInfo { ImageLayout = ImageLayout.General, }; @@ -301,13 +302,13 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < segment.Count; i++) { - ref var texture = ref _textureRefs[segment.Binding + i]; + ref TextureRef texture = ref _textureRefs[segment.Binding + i]; texture.View?.PrepareForUsage(cbs, texture.Stage.ConvertToPipelineStageFlags(), FeedbackLoopHazards); } } else { - ref var arrayRef = ref _textureArrayRefs[segment.Binding]; + ref ArrayRef arrayRef = ref _textureArrayRefs[segment.Binding]; PipelineStageFlags stageFlags = arrayRef.Stage.ConvertToPipelineStageFlags(); arrayRef.Array?.QueueWriteToReadBarriers(cbs, stageFlags); } @@ -322,13 +323,13 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < segment.Count; i++) { - ref var image = ref _imageRefs[segment.Binding + i]; + ref ImageRef image = ref _imageRefs[segment.Binding + i]; image.View?.PrepareForUsage(cbs, image.Stage.ConvertToPipelineStageFlags(), FeedbackLoopHazards); } } else { - ref var arrayRef = ref _imageArrayRefs[segment.Binding]; + ref ArrayRef arrayRef = ref _imageArrayRefs[segment.Binding]; PipelineStageFlags stageFlags = arrayRef.Stage.ConvertToPipelineStageFlags(); arrayRef.Array?.QueueWriteToReadBarriers(cbs, stageFlags); } @@ -337,7 +338,7 @@ namespace Ryujinx.Graphics.Vulkan for (int setIndex = PipelineBase.DescriptorSetLayouts; setIndex < _program.BindingSegments.Length; setIndex++) { - var bindingSegments = _program.BindingSegments[setIndex]; + ResourceBindingSegment[] bindingSegments = _program.BindingSegments[setIndex]; if (bindingSegments.Length == 0) { @@ -353,13 +354,13 @@ namespace Ryujinx.Graphics.Vulkan segment.Type == ResourceType.TextureAndSampler || segment.Type == ResourceType.BufferTexture) { - ref var arrayRef = ref _textureArrayExtraRefs[setIndex - PipelineBase.DescriptorSetLayouts]; + ref ArrayRef arrayRef = ref _textureArrayExtraRefs[setIndex - PipelineBase.DescriptorSetLayouts]; PipelineStageFlags stageFlags = arrayRef.Stage.ConvertToPipelineStageFlags(); arrayRef.Array?.QueueWriteToReadBarriers(cbs, stageFlags); } else if (segment.Type == ResourceType.Image || segment.Type == ResourceType.BufferImage) { - ref var arrayRef = ref _imageArrayExtraRefs[setIndex - PipelineBase.DescriptorSetLayouts]; + ref ArrayRef arrayRef = ref _imageArrayExtraRefs[setIndex - PipelineBase.DescriptorSetLayouts]; PipelineStageFlags stageFlags = arrayRef.Stage.ConvertToPipelineStageFlags(); arrayRef.Array?.QueueWriteToReadBarriers(cbs, stageFlags); } @@ -424,8 +425,8 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < buffers.Length; i++) { - var assignment = buffers[i]; - var buffer = assignment.Range; + BufferAssignment assignment = buffers[i]; + BufferRange buffer = assignment.Range; int index = assignment.Binding; Auto vkBuffer = buffer.Handle == BufferHandle.Null @@ -440,7 +441,7 @@ namespace Ryujinx.Graphics.Vulkan Range = (ulong)buffer.Size, }; - var newRef = new BufferRef(vkBuffer, ref buffer); + BufferRef newRef = new BufferRef(vkBuffer, ref buffer); ref DescriptorBufferInfo currentInfo = ref _storageBuffers[index]; @@ -460,7 +461,7 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < buffers.Length; i++) { - var vkBuffer = buffers[i]; + Auto vkBuffer = buffers[i]; int index = first + i; ref BufferRef currentBufferRef = ref _storageBufferRefs[index]; @@ -633,8 +634,8 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < buffers.Length; i++) { - var assignment = buffers[i]; - var buffer = assignment.Range; + BufferAssignment assignment = buffers[i]; + BufferRange buffer = assignment.Range; int index = assignment.Binding; Auto vkBuffer = buffer.Handle == BufferHandle.Null @@ -678,7 +679,7 @@ namespace Ryujinx.Graphics.Vulkan return; } - var program = _program; + ShaderCollection program = _program; if (_dirty.HasFlag(DirtyFlags.Uniform)) { @@ -760,14 +761,14 @@ namespace Ryujinx.Graphics.Vulkan [MethodImpl(MethodImplOptions.AggressiveInlining)] private void UpdateAndBind(CommandBufferScoped cbs, ShaderCollection program, int setIndex, PipelineBindPoint pbp) { - var bindingSegments = program.BindingSegments[setIndex]; + ResourceBindingSegment[] bindingSegments = program.BindingSegments[setIndex]; if (bindingSegments.Length == 0) { return; } - var dummyBuffer = _dummyBuffer?.GetBuffer(); + Auto dummyBuffer = _dummyBuffer?.GetBuffer(); if (_updateDescriptorCacheCbIndex) { @@ -775,7 +776,7 @@ namespace Ryujinx.Graphics.Vulkan program.UpdateDescriptorCacheCommandBufferIndex(cbs.CommandBufferIndex); } - var dsc = program.GetNewDescriptorSetCollection(setIndex, out var isNew).Get(cbs); + DescriptorSetCollection dsc = program.GetNewDescriptorSetCollection(setIndex, out bool isNew).Get(cbs); if (!program.HasMinimalLayout) { @@ -824,7 +825,7 @@ namespace Ryujinx.Graphics.Vulkan if (_storageSet.Set(index)) { - ref var info = ref _storageBuffers[index]; + ref DescriptorBufferInfo info = ref _storageBuffers[index]; bool mirrored = UpdateBuffer(cbs, ref info, @@ -850,8 +851,8 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < count; i++) { - ref var texture = ref textures[i]; - ref var refs = ref _textureRefs[binding + i]; + ref DescriptorImageInfo texture = ref textures[i]; + ref TextureRef refs = ref _textureRefs[binding + i]; texture.ImageView = refs.ImageView?.Get(cbs).Value ?? default; texture.Sampler = refs.Sampler?.Get(cbs).Value ?? default; @@ -934,7 +935,7 @@ namespace Ryujinx.Graphics.Vulkan } } - var sets = dsc.GetSets(); + DescriptorSet[] sets = dsc.GetSets(); _templateUpdater.Commit(_gd, _device, sets[0]); _gd.Api.CmdBindDescriptorSets(cbs.CommandBuffer, pbp, _program.PipelineLayout, (uint)setIndex, 1, sets, 0, ReadOnlySpan.Empty); @@ -943,7 +944,7 @@ namespace Ryujinx.Graphics.Vulkan private void UpdateAndBindTexturesWithoutTemplate(CommandBufferScoped cbs, ShaderCollection program, PipelineBindPoint pbp) { int setIndex = PipelineBase.TextureSetIndex; - var bindingSegments = program.BindingSegments[setIndex]; + ResourceBindingSegment[] bindingSegments = program.BindingSegments[setIndex]; if (bindingSegments.Length == 0) { @@ -956,7 +957,7 @@ namespace Ryujinx.Graphics.Vulkan program.UpdateDescriptorCacheCommandBufferIndex(cbs.CommandBufferIndex); } - var dsc = program.GetNewDescriptorSetCollection(setIndex, out _).Get(cbs); + DescriptorSetCollection dsc = program.GetNewDescriptorSetCollection(setIndex, out _).Get(cbs); foreach (ResourceBindingSegment segment in bindingSegments) { @@ -971,8 +972,8 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < count; i++) { - ref var texture = ref textures[i]; - ref var refs = ref _textureRefs[binding + i]; + ref DescriptorImageInfo texture = ref textures[i]; + ref TextureRef refs = ref _textureRefs[binding + i]; texture.ImageView = refs.ImageView?.Get(cbs).Value ?? default; texture.Sampler = refs.Sampler?.Get(cbs).Value ?? default; @@ -1015,7 +1016,7 @@ namespace Ryujinx.Graphics.Vulkan } } - var sets = dsc.GetSets(); + DescriptorSet[] sets = dsc.GetSets(); _gd.Api.CmdBindDescriptorSets(cbs.CommandBuffer, pbp, _program.PipelineLayout, (uint)setIndex, 1, sets, 0, ReadOnlySpan.Empty); } @@ -1024,8 +1025,8 @@ namespace Ryujinx.Graphics.Vulkan private void UpdateAndBindUniformBufferPd(CommandBufferScoped cbs) { int sequence = _pdSequence; - var bindingSegments = _program.BindingSegments[PipelineBase.UniformSetIndex]; - var dummyBuffer = _dummyBuffer?.GetBuffer(); + ResourceBindingSegment[] bindingSegments = _program.BindingSegments[PipelineBase.UniformSetIndex]; + Auto dummyBuffer = _dummyBuffer?.GetBuffer(); long updatedBindings = 0; DescriptorSetTemplateWriter writer = _templateUpdater.Begin(32 * Unsafe.SizeOf()); @@ -1077,7 +1078,7 @@ namespace Ryujinx.Graphics.Vulkan return; } - var dummyBuffer = _dummyBuffer?.GetBuffer().Get(cbs).Value ?? default; + Buffer dummyBuffer = _dummyBuffer?.GetBuffer().Get(cbs).Value ?? default; foreach (ResourceBindingSegment segment in _program.ClearSegments[setIndex]) { @@ -1089,7 +1090,7 @@ namespace Ryujinx.Graphics.Vulkan { for (int setIndex = PipelineBase.DescriptorSetLayouts; setIndex < program.BindingSegments.Length; setIndex++) { - var bindingSegments = program.BindingSegments[setIndex]; + ResourceBindingSegment[] bindingSegments = program.BindingSegments[setIndex]; if (bindingSegments.Length == 0) { diff --git a/src/Ryujinx.Graphics.Vulkan/Effects/AreaScalingFilter.cs b/src/Ryujinx.Graphics.Vulkan/Effects/AreaScalingFilter.cs index 87b46df80..695a5d706 100644 --- a/src/Ryujinx.Graphics.Vulkan/Effects/AreaScalingFilter.cs +++ b/src/Ryujinx.Graphics.Vulkan/Effects/AreaScalingFilter.cs @@ -41,9 +41,9 @@ namespace Ryujinx.Graphics.Vulkan.Effects _pipeline.Initialize(); - var scalingShader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/AreaScaling.spv"); + byte[] scalingShader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/AreaScaling.spv"); - var scalingResourceLayout = new ResourceLayoutBuilder() + ResourceLayout scalingResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 2) .Add(ResourceStages.Compute, ResourceType.TextureAndSampler, 1) .Add(ResourceStages.Compute, ResourceType.Image, 0, true).Build(); @@ -83,7 +83,7 @@ namespace Ryujinx.Graphics.Vulkan.Effects }; int rangeSize = dimensionsBuffer.Length * sizeof(float); - using var buffer = _renderer.BufferManager.ReserveOrCreate(_renderer, cbs, rangeSize); + using ScopedTemporaryBuffer buffer = _renderer.BufferManager.ReserveOrCreate(_renderer, cbs, rangeSize); buffer.Holder.SetDataUnchecked(buffer.Offset, dimensionsBuffer); int threadGroupWorkRegionDim = 16; diff --git a/src/Ryujinx.Graphics.Vulkan/Effects/FsrScalingFilter.cs b/src/Ryujinx.Graphics.Vulkan/Effects/FsrScalingFilter.cs index 080dde5e5..5834b63a3 100644 --- a/src/Ryujinx.Graphics.Vulkan/Effects/FsrScalingFilter.cs +++ b/src/Ryujinx.Graphics.Vulkan/Effects/FsrScalingFilter.cs @@ -53,15 +53,15 @@ namespace Ryujinx.Graphics.Vulkan.Effects _pipeline.Initialize(); - var scalingShader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/FsrScaling.spv"); - var sharpeningShader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/FsrSharpening.spv"); + byte[] scalingShader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/FsrScaling.spv"); + byte[] sharpeningShader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/FsrSharpening.spv"); - var scalingResourceLayout = new ResourceLayoutBuilder() + ResourceLayout scalingResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 2) .Add(ResourceStages.Compute, ResourceType.TextureAndSampler, 1) .Add(ResourceStages.Compute, ResourceType.Image, 0, true).Build(); - var sharpeningResourceLayout = new ResourceLayoutBuilder() + ResourceLayout sharpeningResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 2) .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 3) .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 4) @@ -96,9 +96,9 @@ namespace Ryujinx.Graphics.Vulkan.Effects || _intermediaryTexture.Info.Height != height || !_intermediaryTexture.Info.Equals(view.Info)) { - var originalInfo = view.Info; + TextureCreateInfo originalInfo = view.Info; - var info = new TextureCreateInfo( + TextureCreateInfo info = new TextureCreateInfo( width, height, originalInfo.Depth, @@ -142,11 +142,11 @@ namespace Ryujinx.Graphics.Vulkan.Effects }; int rangeSize = dimensionsBuffer.Length * sizeof(float); - using var buffer = _renderer.BufferManager.ReserveOrCreate(_renderer, cbs, rangeSize); + using ScopedTemporaryBuffer buffer = _renderer.BufferManager.ReserveOrCreate(_renderer, cbs, rangeSize); buffer.Holder.SetDataUnchecked(buffer.Offset, dimensionsBuffer); ReadOnlySpan sharpeningBufferData = stackalloc float[] { 1.5f - (Level * 0.01f * 1.5f) }; - using var sharpeningBuffer = _renderer.BufferManager.ReserveOrCreate(_renderer, cbs, sizeof(float)); + using ScopedTemporaryBuffer sharpeningBuffer = _renderer.BufferManager.ReserveOrCreate(_renderer, cbs, sizeof(float)); sharpeningBuffer.Holder.SetDataUnchecked(sharpeningBuffer.Offset, sharpeningBufferData); int threadGroupWorkRegionDim = 16; diff --git a/src/Ryujinx.Graphics.Vulkan/Effects/FxaaPostProcessingEffect.cs b/src/Ryujinx.Graphics.Vulkan/Effects/FxaaPostProcessingEffect.cs index 26314b7bf..ad436371e 100644 --- a/src/Ryujinx.Graphics.Vulkan/Effects/FxaaPostProcessingEffect.cs +++ b/src/Ryujinx.Graphics.Vulkan/Effects/FxaaPostProcessingEffect.cs @@ -37,9 +37,9 @@ namespace Ryujinx.Graphics.Vulkan.Effects { _pipeline.Initialize(); - var shader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/Fxaa.spv"); + byte[] shader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/Fxaa.spv"); - var resourceLayout = new ResourceLayoutBuilder() + ResourceLayout resourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 2) .Add(ResourceStages.Compute, ResourceType.TextureAndSampler, 1) .Add(ResourceStages.Compute, ResourceType.Image, 0, true).Build(); @@ -66,14 +66,14 @@ namespace Ryujinx.Graphics.Vulkan.Effects ReadOnlySpan resolutionBuffer = stackalloc float[] { view.Width, view.Height }; int rangeSize = resolutionBuffer.Length * sizeof(float); - using var buffer = _renderer.BufferManager.ReserveOrCreate(_renderer, cbs, rangeSize); + using ScopedTemporaryBuffer buffer = _renderer.BufferManager.ReserveOrCreate(_renderer, cbs, rangeSize); buffer.Holder.SetDataUnchecked(buffer.Offset, resolutionBuffer); _pipeline.SetUniformBuffers(stackalloc[] { new BufferAssignment(2, buffer.Range) }); - var dispatchX = BitUtils.DivRoundUp(view.Width, IPostProcessingEffect.LocalGroupSize); - var dispatchY = BitUtils.DivRoundUp(view.Height, IPostProcessingEffect.LocalGroupSize); + int dispatchX = BitUtils.DivRoundUp(view.Width, IPostProcessingEffect.LocalGroupSize); + int dispatchY = BitUtils.DivRoundUp(view.Height, IPostProcessingEffect.LocalGroupSize); _pipeline.SetImage(ShaderStage.Compute, 0, _texture.GetView(FormatTable.ConvertRgba8SrgbToUnorm(view.Info.Format))); _pipeline.DispatchCompute(dispatchX, dispatchY, 1); diff --git a/src/Ryujinx.Graphics.Vulkan/Effects/SmaaPostProcessingEffect.cs b/src/Ryujinx.Graphics.Vulkan/Effects/SmaaPostProcessingEffect.cs index a8e68f429..23c265d13 100644 --- a/src/Ryujinx.Graphics.Vulkan/Effects/SmaaPostProcessingEffect.cs +++ b/src/Ryujinx.Graphics.Vulkan/Effects/SmaaPostProcessingEffect.cs @@ -1,4 +1,5 @@ using Ryujinx.Common; +using Ryujinx.Common.Memory; using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.Shader; using Ryujinx.Graphics.Shader.Translation; @@ -74,23 +75,23 @@ namespace Ryujinx.Graphics.Vulkan.Effects _pipeline.Initialize(); - var edgeShader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/SmaaEdge.spv"); - var blendShader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/SmaaBlend.spv"); - var neighbourShader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/SmaaNeighbour.spv"); + byte[] edgeShader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/SmaaEdge.spv"); + byte[] blendShader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/SmaaBlend.spv"); + byte[] neighbourShader = EmbeddedResources.Read("Ryujinx.Graphics.Vulkan/Effects/Shaders/SmaaNeighbour.spv"); - var edgeResourceLayout = new ResourceLayoutBuilder() + ResourceLayout edgeResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 2) .Add(ResourceStages.Compute, ResourceType.TextureAndSampler, 1) .Add(ResourceStages.Compute, ResourceType.Image, 0, true).Build(); - var blendResourceLayout = new ResourceLayoutBuilder() + ResourceLayout blendResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 2) .Add(ResourceStages.Compute, ResourceType.TextureAndSampler, 1) .Add(ResourceStages.Compute, ResourceType.TextureAndSampler, 3) .Add(ResourceStages.Compute, ResourceType.TextureAndSampler, 4) .Add(ResourceStages.Compute, ResourceType.Image, 0, true).Build(); - var neighbourResourceLayout = new ResourceLayoutBuilder() + ResourceLayout neighbourResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 2) .Add(ResourceStages.Compute, ResourceType.TextureAndSampler, 1) .Add(ResourceStages.Compute, ResourceType.TextureAndSampler, 3) @@ -108,7 +109,7 @@ namespace Ryujinx.Graphics.Vulkan.Effects QualityUltra = Quality == 3 ? 1 : 0, }; - var specInfo = new SpecDescription( + SpecDescription specInfo = new SpecDescription( (0, SpecConstType.Int32), (1, SpecConstType.Int32), (2, SpecConstType.Int32), @@ -142,7 +143,7 @@ namespace Ryujinx.Graphics.Vulkan.Effects private void Initialize() { - var areaInfo = new TextureCreateInfo(AreaWidth, + TextureCreateInfo areaInfo = new TextureCreateInfo(AreaWidth, AreaHeight, 1, 1, @@ -158,7 +159,7 @@ namespace Ryujinx.Graphics.Vulkan.Effects SwizzleComponent.Blue, SwizzleComponent.Alpha); - var searchInfo = new TextureCreateInfo(SearchWidth, + TextureCreateInfo searchInfo = new TextureCreateInfo(SearchWidth, SearchHeight, 1, 1, @@ -174,8 +175,8 @@ namespace Ryujinx.Graphics.Vulkan.Effects SwizzleComponent.Blue, SwizzleComponent.Alpha); - var areaTexture = EmbeddedResources.ReadFileToRentedMemory("Ryujinx.Graphics.Vulkan/Effects/Textures/SmaaAreaTexture.bin"); - var searchTexture = EmbeddedResources.ReadFileToRentedMemory("Ryujinx.Graphics.Vulkan/Effects/Textures/SmaaSearchTexture.bin"); + MemoryOwner areaTexture = EmbeddedResources.ReadFileToRentedMemory("Ryujinx.Graphics.Vulkan/Effects/Textures/SmaaAreaTexture.bin"); + MemoryOwner searchTexture = EmbeddedResources.ReadFileToRentedMemory("Ryujinx.Graphics.Vulkan/Effects/Textures/SmaaSearchTexture.bin"); _areaTexture = _renderer.CreateTexture(areaInfo) as TextureView; _searchTexture = _renderer.CreateTexture(searchInfo) as TextureView; @@ -205,8 +206,8 @@ namespace Ryujinx.Graphics.Vulkan.Effects _renderer.Pipeline.TextureBarrier(); - var dispatchX = BitUtils.DivRoundUp(view.Width, IPostProcessingEffect.LocalGroupSize); - var dispatchY = BitUtils.DivRoundUp(view.Height, IPostProcessingEffect.LocalGroupSize); + int dispatchX = BitUtils.DivRoundUp(view.Width, IPostProcessingEffect.LocalGroupSize); + int dispatchY = BitUtils.DivRoundUp(view.Height, IPostProcessingEffect.LocalGroupSize); // Edge pass _pipeline.SetProgram(_edgeProgram); @@ -215,7 +216,7 @@ namespace Ryujinx.Graphics.Vulkan.Effects ReadOnlySpan resolutionBuffer = stackalloc float[] { view.Width, view.Height }; int rangeSize = resolutionBuffer.Length * sizeof(float); - using var buffer = _renderer.BufferManager.ReserveOrCreate(_renderer, cbs, rangeSize); + using ScopedTemporaryBuffer buffer = _renderer.BufferManager.ReserveOrCreate(_renderer, cbs, rangeSize); buffer.Holder.SetDataUnchecked(buffer.Offset, resolutionBuffer); _pipeline.SetUniformBuffers(stackalloc[] { new BufferAssignment(2, buffer.Range) }); diff --git a/src/Ryujinx.Graphics.Vulkan/FenceHolder.cs b/src/Ryujinx.Graphics.Vulkan/FenceHolder.cs index 0cdb93f20..a26d1a767 100644 --- a/src/Ryujinx.Graphics.Vulkan/FenceHolder.cs +++ b/src/Ryujinx.Graphics.Vulkan/FenceHolder.cs @@ -20,7 +20,7 @@ namespace Ryujinx.Graphics.Vulkan _device = device; _concurrentWaitUnsupported = concurrentWaitUnsupported; - var fenceCreateInfo = new FenceCreateInfo + FenceCreateInfo fenceCreateInfo = new FenceCreateInfo { SType = StructureType.FenceCreateInfo, }; diff --git a/src/Ryujinx.Graphics.Vulkan/FormatCapabilities.cs b/src/Ryujinx.Graphics.Vulkan/FormatCapabilities.cs index 09f22889c..2b567709e 100644 --- a/src/Ryujinx.Graphics.Vulkan/FormatCapabilities.cs +++ b/src/Ryujinx.Graphics.Vulkan/FormatCapabilities.cs @@ -96,11 +96,11 @@ namespace Ryujinx.Graphics.Vulkan public bool BufferFormatSupports(FormatFeatureFlags flags, Format format) { - var formatFeatureFlags = _bufferTable[(int)format]; + FormatFeatureFlags formatFeatureFlags = _bufferTable[(int)format]; if (formatFeatureFlags == 0) { - _api.GetPhysicalDeviceFormatProperties(_physicalDevice, FormatTable.GetFormat(format), out var fp); + _api.GetPhysicalDeviceFormatProperties(_physicalDevice, FormatTable.GetFormat(format), out FormatProperties fp); formatFeatureFlags = fp.BufferFeatures; _bufferTable[(int)format] = formatFeatureFlags; } @@ -129,18 +129,18 @@ namespace Ryujinx.Graphics.Vulkan public bool BufferFormatSupports(FormatFeatureFlags flags, VkFormat format) { - _api.GetPhysicalDeviceFormatProperties(_physicalDevice, format, out var fp); + _api.GetPhysicalDeviceFormatProperties(_physicalDevice, format, out FormatProperties fp); return (fp.BufferFeatures & flags) == flags; } public bool OptimalFormatSupports(FormatFeatureFlags flags, Format format) { - var formatFeatureFlags = _optimalTable[(int)format]; + FormatFeatureFlags formatFeatureFlags = _optimalTable[(int)format]; if (formatFeatureFlags == 0) { - _api.GetPhysicalDeviceFormatProperties(_physicalDevice, FormatTable.GetFormat(format), out var fp); + _api.GetPhysicalDeviceFormatProperties(_physicalDevice, FormatTable.GetFormat(format), out FormatProperties fp); formatFeatureFlags = fp.OptimalTilingFeatures; _optimalTable[(int)format] = formatFeatureFlags; } @@ -150,11 +150,11 @@ namespace Ryujinx.Graphics.Vulkan public VkFormat ConvertToVkFormat(Format srcFormat, bool storageFeatureFlagRequired) { - var format = FormatTable.GetFormat(srcFormat); + VkFormat format = FormatTable.GetFormat(srcFormat); - var requiredFeatures = FormatFeatureFlags.SampledImageBit | - FormatFeatureFlags.TransferSrcBit | - FormatFeatureFlags.TransferDstBit; + FormatFeatureFlags requiredFeatures = FormatFeatureFlags.SampledImageBit | + FormatFeatureFlags.TransferSrcBit | + FormatFeatureFlags.TransferDstBit; if (srcFormat.IsDepthOrStencil()) { @@ -192,7 +192,7 @@ namespace Ryujinx.Graphics.Vulkan public VkFormat ConvertToVertexVkFormat(Format srcFormat) { - var format = FormatTable.GetFormat(srcFormat); + VkFormat format = FormatTable.GetFormat(srcFormat); if (!BufferFormatSupports(FormatFeatureFlags.VertexBufferBit, srcFormat) || (IsRGB16IntFloat(srcFormat) && VulkanConfiguration.ForceRGB16IntFloatUnsupported)) diff --git a/src/Ryujinx.Graphics.Vulkan/FramebufferParams.cs b/src/Ryujinx.Graphics.Vulkan/FramebufferParams.cs index 8d80e9d05..3aa495bd7 100644 --- a/src/Ryujinx.Graphics.Vulkan/FramebufferParams.cs +++ b/src/Ryujinx.Graphics.Vulkan/FramebufferParams.cs @@ -2,6 +2,7 @@ using Ryujinx.Graphics.GAL; using Silk.NET.Vulkan; using System; using System.Linq; +using Format = Ryujinx.Graphics.GAL.Format; using VkFormat = Silk.NET.Vulkan.Format; namespace Ryujinx.Graphics.Vulkan @@ -33,7 +34,7 @@ namespace Ryujinx.Graphics.Vulkan public FramebufferParams(Device device, TextureView view, uint width, uint height) { - var format = view.Info.Format; + Format format = view.Info.Format; bool isDepthStencil = format.IsDepthOrStencil(); @@ -96,7 +97,7 @@ namespace Ryujinx.Graphics.Vulkan { if (IsValidTextureView(color)) { - var texture = (TextureView)color; + TextureView texture = (TextureView)color; _attachments[index] = texture.GetImageViewForAttachment(); _colors[index] = texture; @@ -107,7 +108,7 @@ namespace Ryujinx.Graphics.Vulkan AttachmentFormats[index] = texture.VkFormat; AttachmentIndices[index] = bindIndex; - var format = texture.Info.Format; + Format format = texture.Info.Format; if (format.IsInteger()) { @@ -184,7 +185,7 @@ namespace Ryujinx.Graphics.Vulkan { if (_colors != null && (uint)index < _colors.Length) { - var format = _colors[index].Info.Format; + Format format = _colors[index].Info.Format; if (format.IsSint()) { @@ -239,7 +240,7 @@ namespace Ryujinx.Graphics.Vulkan attachments[i] = _attachments[i].Get(cbs).Value; } - var framebufferCreateInfo = new FramebufferCreateInfo + FramebufferCreateInfo framebufferCreateInfo = new FramebufferCreateInfo { SType = StructureType.FramebufferCreateInfo, RenderPass = renderPass.Get(cbs).Value, @@ -250,13 +251,13 @@ namespace Ryujinx.Graphics.Vulkan Layers = Layers, }; - api.CreateFramebuffer(_device, in framebufferCreateInfo, null, out var framebuffer).ThrowOnError(); + api.CreateFramebuffer(_device, in framebufferCreateInfo, null, out Framebuffer framebuffer).ThrowOnError(); return new Auto(new DisposableFramebuffer(api, _device, framebuffer), null, _attachments); } public TextureView[] GetAttachmentViews() { - var result = new TextureView[_attachments.Length]; + TextureView[] result = new TextureView[_attachments.Length]; _colors?.CopyTo(result, 0); @@ -277,7 +278,7 @@ namespace Ryujinx.Graphics.Vulkan { if (_colors != null) { - foreach (var color in _colors) + foreach (TextureView color in _colors) { // If Clear or DontCare were used, this would need to be write bit. color.Storage?.QueueLoadOpBarrier(cbs, false); @@ -293,7 +294,7 @@ namespace Ryujinx.Graphics.Vulkan { if (_colors != null) { - foreach (var color in _colors) + foreach (TextureView color in _colors) { color.Storage?.AddStoreOpUsage(false); } diff --git a/src/Ryujinx.Graphics.Vulkan/HashTableSlim.cs b/src/Ryujinx.Graphics.Vulkan/HashTableSlim.cs index 3796e3c52..798682962 100644 --- a/src/Ryujinx.Graphics.Vulkan/HashTableSlim.cs +++ b/src/Ryujinx.Graphics.Vulkan/HashTableSlim.cs @@ -65,7 +65,7 @@ namespace Ryujinx.Graphics.Vulkan public void Add(ref TKey key, TValue value) { - var entry = new Entry + Entry entry = new Entry { Hash = key.GetHashCode(), Key = key, @@ -75,7 +75,7 @@ namespace Ryujinx.Graphics.Vulkan int hashCode = key.GetHashCode(); int bucketIndex = hashCode & TotalBucketsMask; - ref var bucket = ref _hashTable[bucketIndex]; + ref Bucket bucket = ref _hashTable[bucketIndex]; if (bucket.Entries != null) { int index = bucket.Length; @@ -102,11 +102,11 @@ namespace Ryujinx.Graphics.Vulkan { int hashCode = key.GetHashCode(); - ref var bucket = ref _hashTable[hashCode & TotalBucketsMask]; - var entries = bucket.AsSpan(); + ref Bucket bucket = ref _hashTable[hashCode & TotalBucketsMask]; + Span entries = bucket.AsSpan(); for (int i = 0; i < entries.Length; i++) { - ref var entry = ref entries[i]; + ref Entry entry = ref entries[i]; if (entry.Hash == hashCode && entry.Key.Equals(ref key)) { @@ -124,10 +124,10 @@ namespace Ryujinx.Graphics.Vulkan { int hashCode = key.GetHashCode(); - var entries = _hashTable[hashCode & TotalBucketsMask].AsSpan(); + Span entries = _hashTable[hashCode & TotalBucketsMask].AsSpan(); for (int i = 0; i < entries.Length; i++) { - ref var entry = ref entries[i]; + ref Entry entry = ref entries[i]; if (entry.Hash == hashCode && entry.Key.Equals(ref key)) { diff --git a/src/Ryujinx.Graphics.Vulkan/HelperShader.cs b/src/Ryujinx.Graphics.Vulkan/HelperShader.cs index b7c42aff0..9cbb931ac 100644 --- a/src/Ryujinx.Graphics.Vulkan/HelperShader.cs +++ b/src/Ryujinx.Graphics.Vulkan/HelperShader.cs @@ -6,6 +6,7 @@ using Silk.NET.Vulkan; using System; using System.Collections.Generic; using System.Numerics; +using Buffer = Silk.NET.Vulkan.Buffer; using CompareOp = Ryujinx.Graphics.GAL.CompareOp; using Format = Ryujinx.Graphics.GAL.Format; using PrimitiveTopology = Ryujinx.Graphics.GAL.PrimitiveTopology; @@ -64,7 +65,7 @@ namespace Ryujinx.Graphics.Vulkan _samplerLinear = gd.CreateSampler(SamplerCreateInfo.Create(MinFilter.Linear, MagFilter.Linear)); _samplerNearest = gd.CreateSampler(SamplerCreateInfo.Create(MinFilter.Nearest, MagFilter.Nearest)); - var blitResourceLayout = new ResourceLayoutBuilder() + ResourceLayout blitResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Vertex, ResourceType.UniformBuffer, 1) .Add(ResourceStages.Fragment, ResourceType.TextureAndSampler, 0).Build(); @@ -86,7 +87,7 @@ namespace Ryujinx.Graphics.Vulkan new ShaderSource(ReadSpirv("ColorBlitClearAlphaFragment.spv"), ShaderStage.Fragment, TargetLanguage.Spirv), }, blitResourceLayout); - var colorClearResourceLayout = new ResourceLayoutBuilder().Add(ResourceStages.Vertex, ResourceType.UniformBuffer, 1).Build(); + ResourceLayout colorClearResourceLayout = new ResourceLayoutBuilder().Add(ResourceStages.Vertex, ResourceType.UniformBuffer, 1).Build(); _programColorClearF = gd.CreateProgramWithMinimalLayout(new[] { @@ -112,7 +113,7 @@ namespace Ryujinx.Graphics.Vulkan new ShaderSource(ReadSpirv("DepthStencilClearFragment.spv"), ShaderStage.Fragment, TargetLanguage.Spirv), }, colorClearResourceLayout); - var strideChangeResourceLayout = new ResourceLayoutBuilder() + ResourceLayout strideChangeResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 0) .Add(ResourceStages.Compute, ResourceType.StorageBuffer, 1) .Add(ResourceStages.Compute, ResourceType.StorageBuffer, 2, true).Build(); @@ -122,7 +123,7 @@ namespace Ryujinx.Graphics.Vulkan new ShaderSource(ReadSpirv("ChangeBufferStride.spv"), ShaderStage.Compute, TargetLanguage.Spirv), }, strideChangeResourceLayout); - var colorCopyResourceLayout = new ResourceLayoutBuilder() + ResourceLayout colorCopyResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 0) .Add(ResourceStages.Compute, ResourceType.TextureAndSampler, 0) .Add(ResourceStages.Compute, ResourceType.Image, 0, true).Build(); @@ -142,7 +143,7 @@ namespace Ryujinx.Graphics.Vulkan new ShaderSource(ReadSpirv("ColorCopyWideningCompute.spv"), ShaderStage.Compute, TargetLanguage.Spirv), }, colorCopyResourceLayout); - var colorDrawToMsResourceLayout = new ResourceLayoutBuilder() + ResourceLayout colorDrawToMsResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Fragment, ResourceType.UniformBuffer, 0) .Add(ResourceStages.Fragment, ResourceType.TextureAndSampler, 0).Build(); @@ -152,7 +153,7 @@ namespace Ryujinx.Graphics.Vulkan new ShaderSource(ReadSpirv("ColorDrawToMsFragment.spv"), ShaderStage.Fragment, TargetLanguage.Spirv), }, colorDrawToMsResourceLayout); - var convertD32S8ToD24S8ResourceLayout = new ResourceLayoutBuilder() + ResourceLayout convertD32S8ToD24S8ResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 0) .Add(ResourceStages.Compute, ResourceType.StorageBuffer, 1) .Add(ResourceStages.Compute, ResourceType.StorageBuffer, 2, true).Build(); @@ -162,7 +163,7 @@ namespace Ryujinx.Graphics.Vulkan new ShaderSource(ReadSpirv("ConvertD32S8ToD24S8.spv"), ShaderStage.Compute, TargetLanguage.Spirv), }, convertD32S8ToD24S8ResourceLayout); - var convertIndexBufferResourceLayout = new ResourceLayoutBuilder() + ResourceLayout convertIndexBufferResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 0) .Add(ResourceStages.Compute, ResourceType.StorageBuffer, 1) .Add(ResourceStages.Compute, ResourceType.StorageBuffer, 2, true).Build(); @@ -172,7 +173,7 @@ namespace Ryujinx.Graphics.Vulkan new ShaderSource(ReadSpirv("ConvertIndexBuffer.spv"), ShaderStage.Compute, TargetLanguage.Spirv), }, convertIndexBufferResourceLayout); - var convertIndirectDataResourceLayout = new ResourceLayoutBuilder() + ResourceLayout convertIndirectDataResourceLayout = new ResourceLayoutBuilder() .Add(ResourceStages.Compute, ResourceType.UniformBuffer, 0) .Add(ResourceStages.Compute, ResourceType.StorageBuffer, 1) .Add(ResourceStages.Compute, ResourceType.StorageBuffer, 2, true) @@ -254,17 +255,17 @@ namespace Ryujinx.Graphics.Vulkan { gd.FlushAllCommands(); - using var cbs = gd.CommandBufferPool.Rent(); + using CommandBufferScoped cbs = gd.CommandBufferPool.Rent(); for (int l = 0; l < levels; l++) { - var mipSrcRegion = new Extents2D( + Extents2D mipSrcRegion = new Extents2D( srcRegion.X1 >> l, srcRegion.Y1 >> l, srcRegion.X2 >> l, srcRegion.Y2 >> l); - var mipDstRegion = new Extents2D( + Extents2D mipDstRegion = new Extents2D( dstRegion.X1 >> l, dstRegion.Y1 >> l, dstRegion.X2 >> l, @@ -272,8 +273,8 @@ namespace Ryujinx.Graphics.Vulkan for (int z = 0; z < layers; z++) { - var srcView = Create2DLayerView(src, z, l); - var dstView = Create2DLayerView(dst, z, l); + TextureView srcView = Create2DLayerView(src, z, l); + TextureView dstView = Create2DLayerView(dst, z, l); if (isDepthOrStencil) { @@ -334,7 +335,7 @@ namespace Ryujinx.Graphics.Vulkan int dstWidth = Math.Max(1, dst.Width >> mipDstLevel); int dstHeight = Math.Max(1, dst.Height >> mipDstLevel); - var extents = new Extents2D( + Extents2D extents = new Extents2D( 0, 0, Math.Min(srcWidth, dstWidth), @@ -342,8 +343,8 @@ namespace Ryujinx.Graphics.Vulkan for (int z = 0; z < depth; z++) { - var srcView = Create2DLayerView(src, srcLayer + z, mipSrcLevel); - var dstView = Create2DLayerView(dst, dstLayer + z, mipDstLevel); + TextureView srcView = Create2DLayerView(src, srcLayer + z, mipSrcLevel); + TextureView dstView = Create2DLayerView(dst, dstLayer + z, mipDstLevel); BlitColor( gd, @@ -381,7 +382,7 @@ namespace Ryujinx.Graphics.Vulkan const int RegionBufferSize = 16; - var sampler = linearFilter ? _samplerLinear : _samplerNearest; + ISampler sampler = linearFilter ? _samplerLinear : _samplerNearest; _pipeline.SetTextureAndSamplerIdentitySwizzle(ShaderStage.Fragment, 0, src, sampler); @@ -402,7 +403,7 @@ namespace Ryujinx.Graphics.Vulkan (region[2], region[3]) = (region[3], region[2]); } - using var buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, RegionBufferSize); + using ScopedTemporaryBuffer buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, RegionBufferSize); buffer.Holder.SetDataUnchecked(buffer.Offset, region); @@ -410,7 +411,7 @@ namespace Ryujinx.Graphics.Vulkan Span viewports = stackalloc Viewport[1]; - var rect = new Rectangle( + Rectangle rect = new Rectangle( MathF.Min(dstRegion.X1, dstRegion.X2), MathF.Min(dstRegion.Y1, dstRegion.Y2), MathF.Abs(dstRegion.X2 - dstRegion.X1), @@ -498,7 +499,7 @@ namespace Ryujinx.Graphics.Vulkan (region[2], region[3]) = (region[3], region[2]); } - using var buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, RegionBufferSize); + using ScopedTemporaryBuffer buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, RegionBufferSize); buffer.Holder.SetDataUnchecked(buffer.Offset, region); @@ -506,7 +507,7 @@ namespace Ryujinx.Graphics.Vulkan Span viewports = stackalloc Viewport[1]; - var rect = new Rectangle( + Rectangle rect = new Rectangle( MathF.Min(dstRegion.X1, dstRegion.X2), MathF.Min(dstRegion.Y1, dstRegion.Y2), MathF.Abs(dstRegion.X2 - dstRegion.X1), @@ -529,11 +530,11 @@ namespace Ryujinx.Graphics.Vulkan _pipeline.SetViewports(viewports); _pipeline.SetPrimitiveTopology(PrimitiveTopology.TriangleStrip); - var aspectFlags = src.Info.Format.ConvertAspectFlags(); + ImageAspectFlags aspectFlags = src.Info.Format.ConvertAspectFlags(); if (aspectFlags.HasFlag(ImageAspectFlags.DepthBit)) { - var depthTexture = CreateDepthOrStencilView(src, DepthStencilMode.Depth); + TextureView depthTexture = CreateDepthOrStencilView(src, DepthStencilMode.Depth); BlitDepthStencilDraw(depthTexture, isDepth: true); @@ -545,7 +546,7 @@ namespace Ryujinx.Graphics.Vulkan if (aspectFlags.HasFlag(ImageAspectFlags.StencilBit) && _programStencilBlit != null) { - var stencilTexture = CreateDepthOrStencilView(src, DepthStencilMode.Stencil); + TextureView stencilTexture = CreateDepthOrStencilView(src, DepthStencilMode.Stencil); BlitDepthStencilDraw(stencilTexture, isDepth: false); @@ -648,11 +649,11 @@ namespace Ryujinx.Graphics.Vulkan gd.FlushAllCommands(); - using var cbs = gd.CommandBufferPool.Rent(); + using CommandBufferScoped cbs = gd.CommandBufferPool.Rent(); _pipeline.SetCommandBuffer(cbs); - using var buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ClearColorBufferSize); + using ScopedTemporaryBuffer buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ClearColorBufferSize); buffer.Holder.SetDataUnchecked(buffer.Offset, clearColor); @@ -710,11 +711,11 @@ namespace Ryujinx.Graphics.Vulkan gd.FlushAllCommands(); - using var cbs = gd.CommandBufferPool.Rent(); + using CommandBufferScoped cbs = gd.CommandBufferPool.Rent(); _pipeline.SetCommandBuffer(cbs); - using var buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ClearColorBufferSize); + using ScopedTemporaryBuffer buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ClearColorBufferSize); buffer.Holder.SetDataUnchecked(buffer.Offset, stackalloc float[] { depthValue }); @@ -771,7 +772,7 @@ namespace Ryujinx.Graphics.Vulkan (region[2], region[3]) = (region[3], region[2]); } - var bufferHandle = gd.BufferManager.CreateWithHandle(gd, RegionBufferSize); + BufferHandle bufferHandle = gd.BufferManager.CreateWithHandle(gd, RegionBufferSize); gd.BufferManager.SetData(bufferHandle, 0, region); @@ -779,7 +780,7 @@ namespace Ryujinx.Graphics.Vulkan Span viewports = stackalloc Viewport[1]; - var rect = new Rectangle( + Rectangle rect = new Rectangle( MathF.Min(dstRegion.X1, dstRegion.X2), MathF.Min(dstRegion.Y1, dstRegion.Y2), MathF.Abs(dstRegion.X2 - dstRegion.X1), @@ -814,14 +815,14 @@ namespace Ryujinx.Graphics.Vulkan int elems = size / stride; int newSize = elems * newStride; - var srcBufferAuto = src.GetBuffer(); - var dstBufferAuto = dst.GetBuffer(); + Auto srcBufferAuto = src.GetBuffer(); + Auto dstBufferAuto = dst.GetBuffer(); - var srcBuffer = srcBufferAuto.Get(cbs, srcOffset, size).Value; - var dstBuffer = dstBufferAuto.Get(cbs, 0, newSize).Value; + Buffer srcBuffer = srcBufferAuto.Get(cbs, srcOffset, size).Value; + Buffer dstBuffer = dstBufferAuto.Get(cbs, 0, newSize).Value; - var access = supportsUint8 ? AccessFlags.ShaderWriteBit : AccessFlags.TransferWriteBit; - var stage = supportsUint8 ? PipelineStageFlags.ComputeShaderBit : PipelineStageFlags.TransferBit; + AccessFlags access = supportsUint8 ? AccessFlags.ShaderWriteBit : AccessFlags.TransferWriteBit; + PipelineStageFlags stage = supportsUint8 ? PipelineStageFlags.ComputeShaderBit : PipelineStageFlags.TransferBit; BufferHolder.InsertBufferBarrier( gd, @@ -845,7 +846,7 @@ namespace Ryujinx.Graphics.Vulkan shaderParams[2] = size; shaderParams[3] = srcOffset; - using var buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); + using ScopedTemporaryBuffer buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); buffer.Holder.SetDataUnchecked(buffer.Offset, shaderParams); @@ -869,7 +870,7 @@ namespace Ryujinx.Graphics.Vulkan { gd.Api.CmdFillBuffer(cbs.CommandBuffer, dstBuffer, 0, Vk.WholeSize, 0); - var bufferCopy = new BufferCopy[elems]; + BufferCopy[] bufferCopy = new BufferCopy[elems]; for (ulong i = 0; i < (ulong)elems; i++) { @@ -909,19 +910,19 @@ namespace Ryujinx.Graphics.Vulkan int convertedCount = pattern.GetConvertedCount(indexCount); int outputIndexSize = 4; - var srcBuffer = src.GetBuffer().Get(cbs, srcOffset, indexCount * indexSize).Value; - var dstBuffer = dst.GetBuffer().Get(cbs, 0, convertedCount * outputIndexSize).Value; + Buffer srcBuffer = src.GetBuffer().Get(cbs, srcOffset, indexCount * indexSize).Value; + Buffer dstBuffer = dst.GetBuffer().Get(cbs, 0, convertedCount * outputIndexSize).Value; gd.Api.CmdFillBuffer(cbs.CommandBuffer, dstBuffer, 0, Vk.WholeSize, 0); - var bufferCopy = new List(); + List bufferCopy = new List(); int outputOffset = 0; // Try to merge copies of adjacent indices to reduce copy count. int sequenceStart = 0; int sequenceLength = 0; - foreach (var index in pattern.GetIndexMapping(indexCount)) + foreach (int index in pattern.GetIndexMapping(indexCount)) { if (sequenceLength > 0) { @@ -946,7 +947,7 @@ namespace Ryujinx.Graphics.Vulkan bufferCopy.Add(new BufferCopy((ulong)(srcOffset + sequenceStart * indexSize), (ulong)outputOffset, (ulong)(indexSize * sequenceLength))); } - var bufferCopyArray = bufferCopy.ToArray(); + BufferCopy[] bufferCopyArray = bufferCopy.ToArray(); BufferHolder.InsertBufferBarrier( gd, @@ -999,7 +1000,7 @@ namespace Ryujinx.Graphics.Vulkan shaderParams[0] = BitOperations.Log2((uint)ratio); - using var buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); + using ScopedTemporaryBuffer buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); buffer.Holder.SetDataUnchecked(buffer.Offset, shaderParams); @@ -1026,8 +1027,8 @@ namespace Ryujinx.Graphics.Vulkan // - Maximum component size is 4 (R32). int componentSize = Math.Min(Math.Min(srcBpp, dstBpp), 4); - var srcFormat = GetFormat(componentSize, srcBpp / componentSize); - var dstFormat = GetFormat(componentSize, dstBpp / componentSize); + Format srcFormat = GetFormat(componentSize, srcBpp / componentSize); + Format dstFormat = GetFormat(componentSize, dstBpp / componentSize); _pipeline.SetUniformBuffers(stackalloc[] { new BufferAssignment(0, buffer.Range) }); @@ -1035,8 +1036,8 @@ namespace Ryujinx.Graphics.Vulkan { for (int z = 0; z < depth; z++) { - var srcView = Create2DLayerView(src, srcLayer + z, srcLevel + l, srcFormat); - var dstView = Create2DLayerView(dst, dstLayer + z, dstLevel + l); + TextureView srcView = Create2DLayerView(src, srcLayer + z, srcLevel + l, srcFormat); + TextureView dstView = Create2DLayerView(dst, dstLayer + z, dstLevel + l); _pipeline.SetTextureAndSamplerIdentitySwizzle(ShaderStage.Compute, 0, srcView, null); _pipeline.SetImage(ShaderStage.Compute, 0, dstView.GetView(dstFormat)); @@ -1083,7 +1084,7 @@ namespace Ryujinx.Graphics.Vulkan int samples = src.Info.Samples; bool isDepthOrStencil = src.Info.Format.IsDepthOrStencil(); - var aspectFlags = src.Info.Format.ConvertAspectFlags(); + ImageAspectFlags aspectFlags = src.Info.Format.ConvertAspectFlags(); // X and Y are the expected texture samples. // Z and W are the actual texture samples used. @@ -1091,7 +1092,7 @@ namespace Ryujinx.Graphics.Vulkan (shaderParams[0], shaderParams[1]) = GetSampleCountXYLog2(samples); (shaderParams[2], shaderParams[3]) = GetSampleCountXYLog2((int)TextureStorage.ConvertToSampleCountFlags(gd.Capabilities.SupportedSampleCounts, (uint)samples)); - using var buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); + using ScopedTemporaryBuffer buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); buffer.Holder.SetDataUnchecked(buffer.Offset, shaderParams); @@ -1118,7 +1119,7 @@ namespace Ryujinx.Graphics.Vulkan Span viewports = stackalloc Viewport[1]; - var rect = new Rectangle(0, 0, dst.Width, dst.Height); + Rectangle rect = new Rectangle(0, 0, dst.Width, dst.Height); viewports[0] = new Viewport( rect, @@ -1135,8 +1136,8 @@ namespace Ryujinx.Graphics.Vulkan for (int z = 0; z < depth; z++) { - var srcView = Create2DLayerView(src, srcLayer + z, 0); - var dstView = Create2DLayerView(dst, dstLayer + z, 0); + TextureView srcView = Create2DLayerView(src, srcLayer + z, 0); + TextureView dstView = Create2DLayerView(dst, dstLayer + z, 0); _pipeline.SetRenderTarget(dstView, (uint)dst.Width, (uint)dst.Height); @@ -1155,7 +1156,7 @@ namespace Ryujinx.Graphics.Vulkan } else { - var format = GetFormat(src.Info.BytesPerPixel); + Format format = GetFormat(src.Info.BytesPerPixel); int dispatchX = (dst.Info.Width + 31) / 32; int dispatchY = (dst.Info.Height + 31) / 32; @@ -1164,8 +1165,8 @@ namespace Ryujinx.Graphics.Vulkan for (int z = 0; z < depth; z++) { - var srcView = Create2DLayerView(src, srcLayer + z, 0, format); - var dstView = Create2DLayerView(dst, dstLayer + z, 0); + TextureView srcView = Create2DLayerView(src, srcLayer + z, 0, format); + TextureView dstView = Create2DLayerView(dst, dstLayer + z, 0); _pipeline.SetTextureAndSamplerIdentitySwizzle(ShaderStage.Compute, 0, srcView, null); _pipeline.SetImage(ShaderStage.Compute, 0, dstView.GetView(format)); @@ -1209,7 +1210,7 @@ namespace Ryujinx.Graphics.Vulkan int samples = dst.Info.Samples; bool isDepthOrStencil = src.Info.Format.IsDepthOrStencil(); - var aspectFlags = src.Info.Format.ConvertAspectFlags(); + ImageAspectFlags aspectFlags = src.Info.Format.ConvertAspectFlags(); // X and Y are the expected texture samples. // Z and W are the actual texture samples used. @@ -1217,7 +1218,7 @@ namespace Ryujinx.Graphics.Vulkan (shaderParams[0], shaderParams[1]) = GetSampleCountXYLog2(samples); (shaderParams[2], shaderParams[3]) = GetSampleCountXYLog2((int)TextureStorage.ConvertToSampleCountFlags(gd.Capabilities.SupportedSampleCounts, (uint)samples)); - using var buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); + using ScopedTemporaryBuffer buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); buffer.Holder.SetDataUnchecked(buffer.Offset, shaderParams); @@ -1239,7 +1240,7 @@ namespace Ryujinx.Graphics.Vulkan Span viewports = stackalloc Viewport[1]; - var rect = new Rectangle(0, 0, dst.Width, dst.Height); + Rectangle rect = new Rectangle(0, 0, dst.Width, dst.Height); viewports[0] = new Viewport( rect, @@ -1261,8 +1262,8 @@ namespace Ryujinx.Graphics.Vulkan { for (int z = 0; z < depth; z++) { - var srcView = Create2DLayerView(src, srcLayer + z, 0); - var dstView = Create2DLayerView(dst, dstLayer + z, 0); + TextureView srcView = Create2DLayerView(src, srcLayer + z, 0); + TextureView dstView = Create2DLayerView(dst, dstLayer + z, 0); _pipeline.SetRenderTarget(dstView, (uint)dst.Width, (uint)dst.Height); @@ -1283,13 +1284,13 @@ namespace Ryujinx.Graphics.Vulkan { _pipeline.SetProgram(_programColorDrawToMs); - var format = GetFormat(src.Info.BytesPerPixel); - var vkFormat = FormatTable.GetFormat(format); + Format format = GetFormat(src.Info.BytesPerPixel); + VkFormat vkFormat = FormatTable.GetFormat(format); for (int z = 0; z < depth; z++) { - var srcView = Create2DLayerView(src, srcLayer + z, 0, format); - var dstView = Create2DLayerView(dst, dstLayer + z, 0); + TextureView srcView = Create2DLayerView(src, srcLayer + z, 0, format); + TextureView dstView = Create2DLayerView(dst, dstLayer + z, 0); _pipeline.SetTextureAndSamplerIdentitySwizzle(ShaderStage.Fragment, 0, srcView, null); _pipeline.SetRenderTarget(dstView.GetView(format), (uint)dst.Width, (uint)dst.Height); @@ -1329,7 +1330,7 @@ namespace Ryujinx.Graphics.Vulkan { if (aspectFlags.HasFlag(ImageAspectFlags.DepthBit)) { - var depthTexture = CreateDepthOrStencilView(src, DepthStencilMode.Depth); + TextureView depthTexture = CreateDepthOrStencilView(src, DepthStencilMode.Depth); CopyMSAspectDraw(depthTexture, fromMS, isDepth: true); @@ -1341,7 +1342,7 @@ namespace Ryujinx.Graphics.Vulkan if (aspectFlags.HasFlag(ImageAspectFlags.StencilBit) && _programStencilDrawToMs != null) { - var stencilTexture = CreateDepthOrStencilView(src, DepthStencilMode.Stencil); + TextureView stencilTexture = CreateDepthOrStencilView(src, DepthStencilMode.Stencil); CopyMSAspectDraw(stencilTexture, fromMS, isDepth: false); @@ -1421,14 +1422,14 @@ namespace Ryujinx.Graphics.Vulkan return from; } - var target = from.Info.Target switch + Target target = from.Info.Target switch { Target.Texture1DArray => Target.Texture1D, Target.Texture2DMultisampleArray => Target.Texture2DMultisample, _ => Target.Texture2D, }; - var info = new TextureCreateInfo( + TextureCreateInfo info = new TextureCreateInfo( Math.Max(1, from.Info.Width >> level), Math.Max(1, from.Info.Height >> level), 1, @@ -1530,8 +1531,8 @@ namespace Ryujinx.Graphics.Vulkan int convertedCount = pattern.GetConvertedCount(indexCount); int outputIndexSize = 4; - var srcBuffer = srcIndexBuffer.GetBuffer().Get(cbs, srcIndexBufferOffset, indexCount * indexSize).Value; - var dstBuffer = dstIndexBuffer.GetBuffer().Get(cbs, 0, convertedCount * outputIndexSize).Value; + Buffer srcBuffer = srcIndexBuffer.GetBuffer().Get(cbs, srcIndexBufferOffset, indexCount * indexSize).Value; + Buffer dstBuffer = dstIndexBuffer.GetBuffer().Get(cbs, 0, convertedCount * outputIndexSize).Value; const int ParamsBufferSize = 24 * sizeof(int); const int ParamsIndirectDispatchOffset = 16 * sizeof(int); @@ -1558,9 +1559,9 @@ namespace Ryujinx.Graphics.Vulkan pattern.OffsetIndex.CopyTo(shaderParams[..pattern.OffsetIndex.Length]); - using var patternScoped = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); - var patternBuffer = patternScoped.Holder; - var patternBufferAuto = patternBuffer.GetBuffer(); + using ScopedTemporaryBuffer patternScoped = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); + BufferHolder patternBuffer = patternScoped.Holder; + Auto patternBufferAuto = patternBuffer.GetBuffer(); patternBuffer.SetDataUnchecked(patternScoped.Offset, shaderParams); @@ -1631,13 +1632,13 @@ namespace Ryujinx.Graphics.Vulkan int inSize = pixelCount * 2 * sizeof(int); int outSize = pixelCount * sizeof(int); - var srcBufferAuto = src.GetBuffer(); + Auto srcBufferAuto = src.GetBuffer(); - var srcBuffer = srcBufferAuto.Get(cbs, 0, inSize).Value; - var dstBuffer = dstBufferAuto.Get(cbs, dstOffset, outSize).Value; + Buffer srcBuffer = srcBufferAuto.Get(cbs, 0, inSize).Value; + Buffer dstBuffer = dstBufferAuto.Get(cbs, dstOffset, outSize).Value; - var access = AccessFlags.ShaderWriteBit; - var stage = PipelineStageFlags.ComputeShaderBit; + AccessFlags access = AccessFlags.ShaderWriteBit; + PipelineStageFlags stage = PipelineStageFlags.ComputeShaderBit; BufferHolder.InsertBufferBarrier( gd, @@ -1668,7 +1669,7 @@ namespace Ryujinx.Graphics.Vulkan shaderParams[0] = pixelCount; shaderParams[1] = dstOffset; - using var buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); + using ScopedTemporaryBuffer buffer = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize); buffer.Holder.SetDataUnchecked(buffer.Offset, shaderParams); diff --git a/src/Ryujinx.Graphics.Vulkan/HostMemoryAllocator.cs b/src/Ryujinx.Graphics.Vulkan/HostMemoryAllocator.cs index 5c8b2a761..23273b811 100644 --- a/src/Ryujinx.Graphics.Vulkan/HostMemoryAllocator.cs +++ b/src/Ryujinx.Graphics.Vulkan/HostMemoryAllocator.cs @@ -57,7 +57,7 @@ namespace Ryujinx.Graphics.Vulkan lock (_lock) { // Does a compatible allocation exist in the tree? - var allocations = new HostMemoryAllocation[10]; + HostMemoryAllocation[] allocations = new HostMemoryAllocation[10]; ulong start = (ulong)pointer; ulong end = start + size; @@ -108,7 +108,7 @@ namespace Ryujinx.Graphics.Vulkan PHostPointer = (void*)pageAlignedPointer, }; - var memoryAllocateInfo = new MemoryAllocateInfo + MemoryAllocateInfo memoryAllocateInfo = new MemoryAllocateInfo { SType = StructureType.MemoryAllocateInfo, AllocationSize = pageAlignedSize, @@ -116,7 +116,7 @@ namespace Ryujinx.Graphics.Vulkan PNext = &importInfo, }; - Result result = _api.AllocateMemory(_device, in memoryAllocateInfo, null, out var deviceMemory); + Result result = _api.AllocateMemory(_device, in memoryAllocateInfo, null, out DeviceMemory deviceMemory); if (result < Result.Success) { @@ -124,9 +124,9 @@ namespace Ryujinx.Graphics.Vulkan return false; } - var allocation = new MemoryAllocation(this, deviceMemory, pageAlignedPointer, 0, pageAlignedSize); - var allocAuto = new Auto(allocation); - var hostAlloc = new HostMemoryAllocation(allocAuto, pageAlignedPointer, pageAlignedSize); + MemoryAllocation allocation = new MemoryAllocation(this, deviceMemory, pageAlignedPointer, 0, pageAlignedSize); + Auto allocAuto = new Auto(allocation); + HostMemoryAllocation hostAlloc = new HostMemoryAllocation(allocAuto, pageAlignedPointer, pageAlignedSize); allocAuto.IncrementReferenceCount(); allocAuto.Dispose(); // Kept alive by ref count only. @@ -145,7 +145,7 @@ namespace Ryujinx.Graphics.Vulkan lock (_lock) { // Does a compatible allocation exist in the tree? - var allocations = new HostMemoryAllocation[10]; + HostMemoryAllocation[] allocations = new HostMemoryAllocation[10]; ulong start = (ulong)pointer; ulong end = start + size; diff --git a/src/Ryujinx.Graphics.Vulkan/ImageArray.cs b/src/Ryujinx.Graphics.Vulkan/ImageArray.cs index 019286d28..40ef32769 100644 --- a/src/Ryujinx.Graphics.Vulkan/ImageArray.cs +++ b/src/Ryujinx.Graphics.Vulkan/ImageArray.cs @@ -128,8 +128,8 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < textures.Length; i++) { - ref var texture = ref textures[i]; - ref var refs = ref _textureRefs[i]; + ref DescriptorImageInfo texture = ref textures[i]; + ref TextureRef refs = ref _textureRefs[i]; if (i > 0 && _textureRefs[i - 1].View == refs.View) { diff --git a/src/Ryujinx.Graphics.Vulkan/IndexBufferState.cs b/src/Ryujinx.Graphics.Vulkan/IndexBufferState.cs index d26fea307..88976e8bb 100644 --- a/src/Ryujinx.Graphics.Vulkan/IndexBufferState.cs +++ b/src/Ryujinx.Graphics.Vulkan/IndexBufferState.cs @@ -115,7 +115,7 @@ namespace Ryujinx.Graphics.Vulkan // Convert the index buffer using the given pattern. int indexSize = GetIndexSize(); - (var indexBufferAuto, var indirectBufferAuto) = gd.BufferManager.GetBufferTopologyConversionIndirect( + (Auto indexBufferAuto, Auto indirectBufferAuto) = gd.BufferManager.GetBufferTopologyConversionIndirect( gd, cbs, new BufferRange(_handle, _offset, _size), diff --git a/src/Ryujinx.Graphics.Vulkan/MemoryAllocator.cs b/src/Ryujinx.Graphics.Vulkan/MemoryAllocator.cs index a28322a25..2fb7aaea0 100644 --- a/src/Ryujinx.Graphics.Vulkan/MemoryAllocator.cs +++ b/src/Ryujinx.Graphics.Vulkan/MemoryAllocator.cs @@ -49,7 +49,7 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < _blockLists.Count; i++) { - var bl = _blockLists[i]; + MemoryAllocatorBlockList bl = _blockLists[i]; if (bl.MemoryTypeIndex == memoryTypeIndex && bl.ForBuffer == isBuffer) { return bl.Allocate(size, alignment, map); @@ -65,7 +65,7 @@ namespace Ryujinx.Graphics.Vulkan try { - var newBl = new MemoryAllocatorBlockList(_api, _device, memoryTypeIndex, _blockAlignment, isBuffer); + MemoryAllocatorBlockList newBl = new MemoryAllocatorBlockList(_api, _device, memoryTypeIndex, _blockAlignment, isBuffer); _blockLists.Add(newBl); return newBl.Allocate(size, alignment, map); @@ -80,7 +80,7 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < _physicalDevice.PhysicalDeviceMemoryProperties.MemoryTypeCount; i++) { - var type = _physicalDevice.PhysicalDeviceMemoryProperties.MemoryTypes[i]; + MemoryType type = _physicalDevice.PhysicalDeviceMemoryProperties.MemoryTypes[i]; if ((memoryTypeBits & (1 << i)) != 0) { diff --git a/src/Ryujinx.Graphics.Vulkan/MemoryAllocatorBlockList.cs b/src/Ryujinx.Graphics.Vulkan/MemoryAllocatorBlockList.cs index 4a0cb2a74..cbf6bdad5 100644 --- a/src/Ryujinx.Graphics.Vulkan/MemoryAllocatorBlockList.cs +++ b/src/Ryujinx.Graphics.Vulkan/MemoryAllocatorBlockList.cs @@ -52,7 +52,7 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < _freeRanges.Count; i++) { - var range = _freeRanges[i]; + Range range = _freeRanges[i]; ulong alignedOffset = BitUtils.AlignUp(range.Offset, alignment); ulong sizeDelta = alignedOffset - range.Offset; @@ -88,7 +88,7 @@ namespace Ryujinx.Graphics.Vulkan private void InsertFreeRange(ulong offset, ulong size) { - var range = new Range(offset, size); + Range range = new Range(offset, size); int index = _freeRanges.BinarySearch(range); if (index < 0) { @@ -101,7 +101,7 @@ namespace Ryujinx.Graphics.Vulkan private void InsertFreeRangeComingled(ulong offset, ulong size) { ulong endOffset = offset + size; - var range = new Range(offset, size); + Range range = new Range(offset, size); int index = _freeRanges.BinarySearch(range); if (index < 0) { @@ -194,7 +194,7 @@ namespace Ryujinx.Graphics.Vulkan { for (int i = 0; i < _blocks.Count; i++) { - var block = _blocks[i]; + Block block = _blocks[i]; if (block.Mapped == map && block.Size >= size) { @@ -213,14 +213,14 @@ namespace Ryujinx.Graphics.Vulkan ulong blockAlignedSize = BitUtils.AlignUp(size, (ulong)_blockAlignment); - var memoryAllocateInfo = new MemoryAllocateInfo + MemoryAllocateInfo memoryAllocateInfo = new MemoryAllocateInfo { SType = StructureType.MemoryAllocateInfo, AllocationSize = blockAlignedSize, MemoryTypeIndex = (uint)MemoryTypeIndex, }; - _api.AllocateMemory(_device, in memoryAllocateInfo, null, out var deviceMemory).ThrowOnError(); + _api.AllocateMemory(_device, in memoryAllocateInfo, null, out DeviceMemory deviceMemory).ThrowOnError(); nint hostPointer = nint.Zero; @@ -231,7 +231,7 @@ namespace Ryujinx.Graphics.Vulkan hostPointer = (nint)pointer; } - var newBlock = new Block(deviceMemory, hostPointer, blockAlignedSize); + Block newBlock = new Block(deviceMemory, hostPointer, blockAlignedSize); InsertBlock(newBlock); diff --git a/src/Ryujinx.Graphics.Vulkan/MoltenVK/MVKInitialization.cs b/src/Ryujinx.Graphics.Vulkan/MoltenVK/MVKInitialization.cs index 086c4e1df..3af2cae26 100644 --- a/src/Ryujinx.Graphics.Vulkan/MoltenVK/MVKInitialization.cs +++ b/src/Ryujinx.Graphics.Vulkan/MoltenVK/MVKInitialization.cs @@ -19,7 +19,7 @@ namespace Ryujinx.Graphics.Vulkan.MoltenVK public static void Initialize() { - var configSize = (nint)Marshal.SizeOf(); + IntPtr configSize = (nint)Marshal.SizeOf(); vkGetMoltenVKConfigurationMVK(nint.Zero, out MVKConfiguration config, configSize); diff --git a/src/Ryujinx.Graphics.Vulkan/MultiFenceHolder.cs b/src/Ryujinx.Graphics.Vulkan/MultiFenceHolder.cs index b42524712..e9ef39cda 100644 --- a/src/Ryujinx.Graphics.Vulkan/MultiFenceHolder.cs +++ b/src/Ryujinx.Graphics.Vulkan/MultiFenceHolder.cs @@ -229,7 +229,7 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < _fences.Length; i++) { - var fence = _fences[i]; + FenceHolder fence = _fences[i]; if (fence != null) { @@ -253,7 +253,7 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < _fences.Length; i++) { - var fence = _fences[i]; + FenceHolder fence = _fences[i]; if (fence != null && _bufferUsageBitmap.OverlapsWith(i, offset, size)) { diff --git a/src/Ryujinx.Graphics.Vulkan/PersistentFlushBuffer.cs b/src/Ryujinx.Graphics.Vulkan/PersistentFlushBuffer.cs index 5e0ed077b..79879e04e 100644 --- a/src/Ryujinx.Graphics.Vulkan/PersistentFlushBuffer.cs +++ b/src/Ryujinx.Graphics.Vulkan/PersistentFlushBuffer.cs @@ -1,5 +1,7 @@ using Ryujinx.Graphics.GAL; +using Silk.NET.Vulkan; using System; +using Buffer = Silk.NET.Vulkan.Buffer; namespace Ryujinx.Graphics.Vulkan { @@ -16,7 +18,7 @@ namespace Ryujinx.Graphics.Vulkan private BufferHolder ResizeIfNeeded(int size) { - var flushStorage = _flushStorage; + BufferHolder flushStorage = _flushStorage; if (flushStorage == null || size > _flushStorage.Size) { @@ -31,13 +33,13 @@ namespace Ryujinx.Graphics.Vulkan public Span GetBufferData(CommandBufferPool cbp, BufferHolder buffer, int offset, int size) { - var flushStorage = ResizeIfNeeded(size); + BufferHolder flushStorage = ResizeIfNeeded(size); Auto srcBuffer; - using (var cbs = cbp.Rent()) + using (CommandBufferScoped cbs = cbp.Rent()) { srcBuffer = buffer.GetBuffer(cbs.CommandBuffer); - var dstBuffer = flushStorage.GetBuffer(cbs.CommandBuffer); + Auto dstBuffer = flushStorage.GetBuffer(cbs.CommandBuffer); if (srcBuffer.TryIncrementReferenceCount()) { @@ -59,12 +61,12 @@ namespace Ryujinx.Graphics.Vulkan { TextureCreateInfo info = view.Info; - var flushStorage = ResizeIfNeeded(size); + BufferHolder flushStorage = ResizeIfNeeded(size); - using (var cbs = cbp.Rent()) + using (CommandBufferScoped cbs = cbp.Rent()) { - var buffer = flushStorage.GetBuffer(cbs.CommandBuffer).Get(cbs).Value; - var image = view.GetImage().Get(cbs).Value; + Buffer buffer = flushStorage.GetBuffer(cbs.CommandBuffer).Get(cbs).Value; + Image image = view.GetImage().Get(cbs).Value; view.CopyFromOrToBuffer(cbs.CommandBuffer, buffer, image, size, true, 0, 0, info.GetLayers(), info.Levels, singleSlice: false); } @@ -75,12 +77,12 @@ namespace Ryujinx.Graphics.Vulkan public Span GetTextureData(CommandBufferPool cbp, TextureView view, int size, int layer, int level) { - var flushStorage = ResizeIfNeeded(size); + BufferHolder flushStorage = ResizeIfNeeded(size); - using (var cbs = cbp.Rent()) + using (CommandBufferScoped cbs = cbp.Rent()) { - var buffer = flushStorage.GetBuffer(cbs.CommandBuffer).Get(cbs).Value; - var image = view.GetImage().Get(cbs).Value; + Buffer buffer = flushStorage.GetBuffer(cbs.CommandBuffer).Get(cbs).Value; + Image image = view.GetImage().Get(cbs).Value; view.CopyFromOrToBuffer(cbs.CommandBuffer, buffer, image, size, true, layer, level, 1, 1, singleSlice: true); } diff --git a/src/Ryujinx.Graphics.Vulkan/PipelineBase.cs b/src/Ryujinx.Graphics.Vulkan/PipelineBase.cs index addad83fd..803712591 100644 --- a/src/Ryujinx.Graphics.Vulkan/PipelineBase.cs +++ b/src/Ryujinx.Graphics.Vulkan/PipelineBase.cs @@ -1,3 +1,4 @@ +using Ryujinx.Common.Memory; using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.Shader; using Silk.NET.Vulkan; @@ -7,6 +8,8 @@ using System.Linq; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using BlendOp = Silk.NET.Vulkan.BlendOp; +using Buffer = Silk.NET.Vulkan.Buffer; using CompareOp = Ryujinx.Graphics.GAL.CompareOp; using Format = Ryujinx.Graphics.GAL.Format; using FrontFace = Ryujinx.Graphics.GAL.FrontFace; @@ -102,7 +105,7 @@ namespace Ryujinx.Graphics.Vulkan AutoFlush = new AutoFlushCounter(gd); EndRenderPassDelegate = EndRenderPass; - var pipelineCacheCreateInfo = new PipelineCacheCreateInfo + PipelineCacheCreateInfo pipelineCacheCreateInfo = new PipelineCacheCreateInfo { SType = StructureType.PipelineCacheCreateInfo, }; @@ -117,7 +120,7 @@ namespace Ryujinx.Graphics.Vulkan const int EmptyVbSize = 16; - using var emptyVb = gd.BufferManager.Create(gd, EmptyVbSize); + using BufferHolder emptyVb = gd.BufferManager.Create(gd, EmptyVbSize); emptyVb.SetData(0, new byte[EmptyVbSize]); _vertexBuffers[0] = new VertexBufferState(emptyVb.GetBuffer(), 0, 0, EmptyVbSize); _vertexBuffersDirty = ulong.MaxValue >> (64 - _vertexBuffers.Length); @@ -174,7 +177,7 @@ namespace Ryujinx.Graphics.Vulkan { EndRenderPass(); - var dst = Gd.BufferManager.GetBuffer(CommandBuffer, destination, offset, size, true).Get(Cbs, offset, size, true).Value; + Buffer dst = Gd.BufferManager.GetBuffer(CommandBuffer, destination, offset, size, true).Get(Cbs, offset, size, true).Value; BufferHolder.InsertBufferBarrier( Gd, @@ -217,9 +220,9 @@ namespace Ryujinx.Graphics.Vulkan BeginRenderPass(); - var clearValue = new ClearValue(new ClearColorValue(color.Red, color.Green, color.Blue, color.Alpha)); - var attachment = new ClearAttachment(ImageAspectFlags.ColorBit, (uint)index, clearValue); - var clearRect = FramebufferParams.GetClearRect(ClearScissor, layer, layerCount); + ClearValue clearValue = new ClearValue(new ClearColorValue(color.Red, color.Green, color.Blue, color.Alpha)); + ClearAttachment attachment = new ClearAttachment(ImageAspectFlags.ColorBit, (uint)index, clearValue); + ClearRect clearRect = FramebufferParams.GetClearRect(ClearScissor, layer, layerCount); Gd.Api.CmdClearAttachments(CommandBuffer, 1, &attachment, 1, &clearRect); } @@ -231,8 +234,8 @@ namespace Ryujinx.Graphics.Vulkan return; } - var clearValue = new ClearValue(null, new ClearDepthStencilValue(depthValue, (uint)stencilValue)); - var flags = depthMask ? ImageAspectFlags.DepthBit : 0; + ClearValue clearValue = new ClearValue(null, new ClearDepthStencilValue(depthValue, (uint)stencilValue)); + ImageAspectFlags flags = depthMask ? ImageAspectFlags.DepthBit : 0; if (stencilMask) { @@ -255,8 +258,8 @@ namespace Ryujinx.Graphics.Vulkan BeginRenderPass(); - var attachment = new ClearAttachment(flags, 0, clearValue); - var clearRect = FramebufferParams.GetClearRect(ClearScissor, layer, layerCount); + ClearAttachment attachment = new ClearAttachment(flags, 0, clearValue); + ClearRect clearRect = FramebufferParams.GetClearRect(ClearScissor, layer, layerCount); Gd.Api.CmdClearAttachments(CommandBuffer, 1, &attachment, 1, &clearRect); } @@ -270,8 +273,8 @@ namespace Ryujinx.Graphics.Vulkan { EndRenderPass(); - var src = Gd.BufferManager.GetBuffer(CommandBuffer, source, srcOffset, size, false); - var dst = Gd.BufferManager.GetBuffer(CommandBuffer, destination, dstOffset, size, true); + Auto src = Gd.BufferManager.GetBuffer(CommandBuffer, source, srcOffset, size, false); + Auto dst = Gd.BufferManager.GetBuffer(CommandBuffer, destination, dstOffset, size, true); BufferHolder.Copy(Gd, Cbs, src, dst, srcOffset, dstOffset, size); } @@ -350,7 +353,7 @@ namespace Ryujinx.Graphics.Vulkan }; BufferHandle handle = pattern.GetRepeatingBuffer(vertexCount, out int indexCount); - var buffer = Gd.BufferManager.GetBuffer(CommandBuffer, handle, false); + Auto buffer = Gd.BufferManager.GetBuffer(CommandBuffer, handle, false); Gd.Api.CmdBindIndexBuffer(CommandBuffer, buffer.Get(Cbs, 0, indexCount * sizeof(int)).Value, 0, Silk.NET.Vulkan.IndexType.Uint32); @@ -435,7 +438,7 @@ namespace Ryujinx.Graphics.Vulkan public void DrawIndexedIndirect(BufferRange indirectBuffer) { - var buffer = Gd.BufferManager + Buffer buffer = Gd.BufferManager .GetBuffer(CommandBuffer, indirectBuffer.Handle, indirectBuffer.Offset, indirectBuffer.Size, false) .Get(Cbs, indirectBuffer.Offset, indirectBuffer.Size).Value; @@ -481,11 +484,11 @@ namespace Ryujinx.Graphics.Vulkan public void DrawIndexedIndirectCount(BufferRange indirectBuffer, BufferRange parameterBuffer, int maxDrawCount, int stride) { - var countBuffer = Gd.BufferManager + Buffer countBuffer = Gd.BufferManager .GetBuffer(CommandBuffer, parameterBuffer.Handle, parameterBuffer.Offset, parameterBuffer.Size, false) .Get(Cbs, parameterBuffer.Offset, parameterBuffer.Size).Value; - var buffer = Gd.BufferManager + Buffer buffer = Gd.BufferManager .GetBuffer(CommandBuffer, indirectBuffer.Handle, indirectBuffer.Offset, indirectBuffer.Size, false) .Get(Cbs, indirectBuffer.Offset, indirectBuffer.Size).Value; @@ -575,7 +578,7 @@ namespace Ryujinx.Graphics.Vulkan { // TODO: Support quads and other unsupported topologies. - var buffer = Gd.BufferManager + Buffer buffer = Gd.BufferManager .GetBuffer(CommandBuffer, indirectBuffer.Handle, indirectBuffer.Offset, indirectBuffer.Size, false) .Get(Cbs, indirectBuffer.Offset, indirectBuffer.Size, false).Value; @@ -599,11 +602,11 @@ namespace Ryujinx.Graphics.Vulkan throw new NotSupportedException(); } - var buffer = Gd.BufferManager + Buffer buffer = Gd.BufferManager .GetBuffer(CommandBuffer, indirectBuffer.Handle, indirectBuffer.Offset, indirectBuffer.Size, false) .Get(Cbs, indirectBuffer.Offset, indirectBuffer.Size, false).Value; - var countBuffer = Gd.BufferManager + Buffer countBuffer = Gd.BufferManager .GetBuffer(CommandBuffer, parameterBuffer.Handle, parameterBuffer.Offset, parameterBuffer.Size, false) .Get(Cbs, parameterBuffer.Offset, parameterBuffer.Size, false).Value; @@ -632,13 +635,13 @@ namespace Ryujinx.Graphics.Vulkan { if (texture is TextureView srcTexture) { - var oldCullMode = _newState.CullMode; - var oldStencilTestEnable = _newState.StencilTestEnable; - var oldDepthTestEnable = _newState.DepthTestEnable; - var oldDepthWriteEnable = _newState.DepthWriteEnable; - var oldViewports = DynamicState.Viewports; - var oldViewportsCount = _newState.ViewportsCount; - var oldTopology = _topology; + CullModeFlags oldCullMode = _newState.CullMode; + bool oldStencilTestEnable = _newState.StencilTestEnable; + bool oldDepthTestEnable = _newState.DepthTestEnable; + bool oldDepthWriteEnable = _newState.DepthWriteEnable; + Array16 oldViewports = DynamicState.Viewports; + uint oldViewportsCount = _newState.ViewportsCount; + PrimitiveTopology oldTopology = _topology; _newState.CullMode = CullModeFlags.None; _newState.StencilTestEnable = false; @@ -710,11 +713,11 @@ namespace Ryujinx.Graphics.Vulkan { for (int index = 0; index < Constants.MaxRenderTargets; index++) { - ref var vkBlend = ref _newState.Internal.ColorBlendAttachmentState[index]; + ref PipelineColorBlendAttachmentState vkBlend = ref _newState.Internal.ColorBlendAttachmentState[index]; if (index == 0) { - var blendOp = blend.Op.Convert(); + BlendOp blendOp = blend.Op.Convert(); vkBlend = new PipelineColorBlendAttachmentState( blendEnable: true, @@ -751,7 +754,7 @@ namespace Ryujinx.Graphics.Vulkan public void SetBlendState(int index, BlendDescriptor blend) { - ref var vkBlend = ref _newState.Internal.ColorBlendAttachmentState[index]; + ref PipelineColorBlendAttachmentState vkBlend = ref _newState.Internal.ColorBlendAttachmentState[index]; if (blend.Enable) { @@ -919,7 +922,7 @@ namespace Ryujinx.Graphics.Vulkan { _topology = topology; - var vkTopology = Gd.TopologyRemap(topology).Convert(); + Silk.NET.Vulkan.PrimitiveTopology vkTopology = Gd.TopologyRemap(topology).Convert(); _newState.Topology = vkTopology; @@ -928,8 +931,8 @@ namespace Ryujinx.Graphics.Vulkan public void SetProgram(IProgram program) { - var internalProgram = (ShaderCollection)program; - var stages = internalProgram.GetInfos(); + ShaderCollection internalProgram = (ShaderCollection)program; + PipelineShaderStageCreateInfo[] stages = internalProgram.GetInfos(); _program = internalProgram; @@ -952,7 +955,7 @@ namespace Ryujinx.Graphics.Vulkan public void Specialize(in T data) where T : unmanaged { - var dataSpan = MemoryMarshal.AsBytes(MemoryMarshal.CreateReadOnlySpan(ref Unsafe.AsRef(in data), 1)); + ReadOnlySpan dataSpan = MemoryMarshal.AsBytes(MemoryMarshal.CreateReadOnlySpan(ref Unsafe.AsRef(in data), 1)); if (!dataSpan.SequenceEqual(_newState.SpecializationData.Span)) { @@ -986,8 +989,8 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < count; i++) { - ref var vkBlend = ref _newState.Internal.ColorBlendAttachmentState[i]; - var newMask = (ColorComponentFlags)componentMask[i]; + ref PipelineColorBlendAttachmentState vkBlend = ref _newState.Internal.ColorBlendAttachmentState[i]; + ColorComponentFlags newMask = (ColorComponentFlags)componentMask[i]; // When color write mask is 0, remove all blend state to help the pipeline cache. // Restore it when the mask becomes non-zero. @@ -1054,9 +1057,9 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < count; i++) { - var region = regions[i]; - var offset = new Offset2D(region.X, region.Y); - var extent = new Extent2D((uint)region.Width, (uint)region.Height); + Rectangle region = regions[i]; + Offset2D offset = new Offset2D(region.X, region.Y); + Extent2D extent = new Extent2D((uint)region.Width, (uint)region.Height); DynamicState.SetScissor(i, new Rect2D(offset, extent)); } @@ -1129,7 +1132,7 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < count; i++) { - var range = buffers[i]; + BufferRange range = buffers[i]; _transformFeedbackBuffers[i].Dispose(); @@ -1158,7 +1161,7 @@ namespace Ryujinx.Graphics.Vulkan public void SetVertexAttribs(ReadOnlySpan vertexAttribs) { - var formatCapabilities = Gd.FormatCapabilities; + FormatCapabilities formatCapabilities = Gd.FormatCapabilities; Span newVbScalarSizes = stackalloc int[Constants.MaxVertexBuffers]; @@ -1167,9 +1170,9 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < count; i++) { - var attribute = vertexAttribs[i]; - var rawIndex = attribute.BufferIndex; - var bufferIndex = attribute.IsZero ? 0 : rawIndex + 1; + VertexAttribDescriptor attribute = vertexAttribs[i]; + int rawIndex = attribute.BufferIndex; + int bufferIndex = attribute.IsZero ? 0 : rawIndex + 1; if (!attribute.IsZero) { @@ -1188,7 +1191,7 @@ namespace Ryujinx.Graphics.Vulkan { int dirtyBit = BitOperations.TrailingZeroCount(dirtyVbSizes); - ref var buffer = ref _vertexBuffers[dirtyBit + 1]; + ref VertexBufferState buffer = ref _vertexBuffers[dirtyBit + 1]; if (buffer.AttributeScalarAlignment != newVbScalarSizes[dirtyBit]) { @@ -1216,10 +1219,10 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < count; i++) { - var vertexBuffer = vertexBuffers[i]; + VertexBufferDescriptor vertexBuffer = vertexBuffers[i]; // TODO: Support divisor > 1 - var inputRate = vertexBuffer.Divisor != 0 ? VertexInputRate.Instance : VertexInputRate.Vertex; + VertexInputRate inputRate = vertexBuffer.Divisor != 0 ? VertexInputRate.Instance : VertexInputRate.Vertex; if (vertexBuffer.Buffer.Handle != BufferHandle.Null) { @@ -1253,7 +1256,7 @@ namespace Ryujinx.Graphics.Vulkan } } - ref var buffer = ref _vertexBuffers[binding]; + ref VertexBufferState buffer = ref _vertexBuffers[binding]; int oldScalarAlign = buffer.AttributeScalarAlignment; if (Gd.Capabilities.VertexBufferAlignment < 2 && @@ -1314,7 +1317,7 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < count; i++) { - var viewport = viewports[i]; + Viewport viewport = viewports[i]; DynamicState.SetViewport(i, new Silk.NET.Vulkan.Viewport( viewport.Region.X, @@ -1410,7 +1413,7 @@ namespace Ryujinx.Graphics.Vulkan continue; } - ref var vkBlend = ref _newState.Internal.ColorBlendAttachmentState[i]; + ref PipelineColorBlendAttachmentState vkBlend = ref _newState.Internal.ColorBlendAttachmentState[i]; for (int j = 0; j < i; j++) { @@ -1419,7 +1422,7 @@ namespace Ryujinx.Graphics.Vulkan if (colors[i] == colors[j]) { // Prefer the binding with no write mask. - ref var vkBlend2 = ref _newState.Internal.ColorBlendAttachmentState[j]; + ref PipelineColorBlendAttachmentState vkBlend2 = ref _newState.Internal.ColorBlendAttachmentState[j]; if (vkBlend.ColorWriteMask == 0) { colors[i] = null; @@ -1457,7 +1460,7 @@ namespace Ryujinx.Graphics.Vulkan protected void UpdatePipelineAttachmentFormats() { - var dstAttachmentFormats = _newState.Internal.AttachmentFormats.AsSpan(); + Span dstAttachmentFormats = _newState.Internal.AttachmentFormats.AsSpan(); FramebufferParams.AttachmentFormats.CopyTo(dstAttachmentFormats); _newState.Internal.AttachmentIntegerFormatMask = FramebufferParams.AttachmentIntegerFormatMask; _newState.Internal.LogicOpsAllowed = FramebufferParams.LogicOpsAllowed; @@ -1474,7 +1477,7 @@ namespace Ryujinx.Graphics.Vulkan protected unsafe void CreateRenderPass() { - var hasFramebuffer = FramebufferParams != null; + bool hasFramebuffer = FramebufferParams != null; EndRenderPass(); @@ -1679,7 +1682,7 @@ namespace Ryujinx.Graphics.Vulkan return false; } - var pipeline = pbp == PipelineBindPoint.Compute + Auto pipeline = pbp == PipelineBindPoint.Compute ? _newState.CreateComputePipeline(Gd, Device, _program, PipelineCache) : _newState.CreateGraphicsPipeline(Gd, Device, _program, PipelineCache, _renderPass.Get(Cbs).Value); @@ -1711,10 +1714,10 @@ namespace Ryujinx.Graphics.Vulkan { FramebufferParams.InsertLoadOpBarriers(Gd, Cbs); - var renderArea = new Rect2D(null, new Extent2D(FramebufferParams.Width, FramebufferParams.Height)); - var clearValue = new ClearValue(); + Rect2D renderArea = new Rect2D(null, new Extent2D(FramebufferParams.Width, FramebufferParams.Height)); + ClearValue clearValue = new ClearValue(); - var renderPassBeginInfo = new RenderPassBeginInfo + RenderPassBeginInfo renderPassBeginInfo = new RenderPassBeginInfo { SType = StructureType.RenderPassBeginInfo, RenderPass = _renderPass.Get(Cbs).Value, diff --git a/src/Ryujinx.Graphics.Vulkan/PipelineConverter.cs b/src/Ryujinx.Graphics.Vulkan/PipelineConverter.cs index 8a895f927..69544e433 100644 --- a/src/Ryujinx.Graphics.Vulkan/PipelineConverter.cs +++ b/src/Ryujinx.Graphics.Vulkan/PipelineConverter.cs @@ -15,7 +15,7 @@ namespace Ryujinx.Graphics.Vulkan AttachmentDescription[] attachmentDescs = null; - var subpass = new SubpassDescription + SubpassDescription subpass = new SubpassDescription { PipelineBindPoint = PipelineBindPoint.Graphics, }; @@ -107,11 +107,11 @@ namespace Ryujinx.Graphics.Vulkan } } - var subpassDependency = CreateSubpassDependency(gd); + SubpassDependency subpassDependency = CreateSubpassDependency(gd); fixed (AttachmentDescription* pAttachmentDescs = attachmentDescs) { - var renderPassCreateInfo = new RenderPassCreateInfo + RenderPassCreateInfo renderPassCreateInfo = new RenderPassCreateInfo { SType = StructureType.RenderPassCreateInfo, PAttachments = pAttachmentDescs, @@ -122,7 +122,7 @@ namespace Ryujinx.Graphics.Vulkan DependencyCount = 1, }; - gd.Api.CreateRenderPass(device, in renderPassCreateInfo, null, out var renderPass).ThrowOnError(); + gd.Api.CreateRenderPass(device, in renderPassCreateInfo, null, out RenderPass renderPass).ThrowOnError(); return new DisposableRenderPass(gd.Api, device, renderPass); } @@ -130,7 +130,7 @@ namespace Ryujinx.Graphics.Vulkan public static SubpassDependency CreateSubpassDependency(VulkanRenderer gd) { - var (access, stages) = BarrierBatch.GetSubpassAccessSuperset(gd); + (AccessFlags access, PipelineStageFlags stages) = BarrierBatch.GetSubpassAccessSuperset(gd); return new SubpassDependency( 0, @@ -144,7 +144,7 @@ namespace Ryujinx.Graphics.Vulkan public unsafe static SubpassDependency2 CreateSubpassDependency2(VulkanRenderer gd) { - var (access, stages) = BarrierBatch.GetSubpassAccessSuperset(gd); + (AccessFlags access, PipelineStageFlags stages) = BarrierBatch.GetSubpassAccessSuperset(gd); return new SubpassDependency2( StructureType.SubpassDependency2, @@ -225,8 +225,8 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < vaCount; i++) { - var attribute = state.VertexAttribs[i]; - var bufferIndex = attribute.IsZero ? 0 : attribute.BufferIndex + 1; + VertexAttribDescriptor attribute = state.VertexAttribs[i]; + int bufferIndex = attribute.IsZero ? 0 : attribute.BufferIndex + 1; pipeline.Internal.VertexAttributeDescriptions[i] = new VertexInputAttributeDescription( (uint)i, @@ -245,11 +245,11 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < vbCount; i++) { - var vertexBuffer = state.VertexBuffers[i]; + BufferPipelineDescriptor vertexBuffer = state.VertexBuffers[i]; if (vertexBuffer.Enable) { - var inputRate = vertexBuffer.Divisor != 0 ? VertexInputRate.Instance : VertexInputRate.Vertex; + VertexInputRate inputRate = vertexBuffer.Divisor != 0 ? VertexInputRate.Instance : VertexInputRate.Vertex; int alignedStride = vertexBuffer.Stride; @@ -272,7 +272,7 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < Constants.MaxRenderTargets; i++) { - var blend = state.BlendDescriptors[i]; + BlendDescriptor blend = state.BlendDescriptors[i]; if (blend.Enable && state.ColorWriteMask[i] != 0) { diff --git a/src/Ryujinx.Graphics.Vulkan/PipelineFull.cs b/src/Ryujinx.Graphics.Vulkan/PipelineFull.cs index 54d43bdba..965e131ee 100644 --- a/src/Ryujinx.Graphics.Vulkan/PipelineFull.cs +++ b/src/Ryujinx.Graphics.Vulkan/PipelineFull.cs @@ -34,7 +34,7 @@ namespace Ryujinx.Graphics.Vulkan private void CopyPendingQuery() { - foreach (var query in _pendingQueryCopies) + foreach (BufferedQuery query in _pendingQueryCopies) { query.PoolCopy(Cbs); } @@ -54,7 +54,7 @@ namespace Ryujinx.Graphics.Vulkan // We can't use CmdClearAttachments if not writing all components, // because on Vulkan, the pipeline state does not affect clears. // On proprietary Adreno drivers, CmdClearAttachments appears to execute out of order, so it's better to not use it at all. - var dstTexture = FramebufferParams.GetColorView(index); + TextureView dstTexture = FramebufferParams.GetColorView(index); if (dstTexture == null) { return; @@ -95,7 +95,7 @@ namespace Ryujinx.Graphics.Vulkan // We can't use CmdClearAttachments if not clearing all (mask is all ones, 0xFF) or none (mask is 0) of the stencil bits, // because on Vulkan, the pipeline state does not affect clears. // On proprietary Adreno drivers, CmdClearAttachments appears to execute out of order, so it's better to not use it at all. - var dstTexture = FramebufferParams.GetDepthStencilView(); + TextureView dstTexture = FramebufferParams.GetDepthStencilView(); if (dstTexture == null) { return; @@ -246,7 +246,7 @@ namespace Ryujinx.Graphics.Vulkan AutoFlush.RegisterFlush(DrawCount); EndRenderPass(); - foreach ((var queryPool, _) in _activeQueries) + foreach ((QueryPool queryPool, _) in _activeQueries) { Gd.Api.CmdEndQuery(CommandBuffer, queryPool, 0); } @@ -271,7 +271,7 @@ namespace Ryujinx.Graphics.Vulkan _activeBufferMirrors.Clear(); - foreach ((var queryPool, var isOcclusion) in _activeQueries) + foreach ((QueryPool queryPool, bool isOcclusion) in _activeQueries) { bool isPrecise = Gd.Capabilities.SupportsPreciseOcclusionQueries && isOcclusion; diff --git a/src/Ryujinx.Graphics.Vulkan/PipelineLayoutCache.cs b/src/Ryujinx.Graphics.Vulkan/PipelineLayoutCache.cs index 5d0cada96..8f1b34b0c 100644 --- a/src/Ryujinx.Graphics.Vulkan/PipelineLayoutCache.cs +++ b/src/Ryujinx.Graphics.Vulkan/PipelineLayoutCache.cs @@ -25,7 +25,7 @@ namespace Ryujinx.Graphics.Vulkan if (SetDescriptors != null) { - foreach (var setDescriptor in SetDescriptors) + foreach (ResourceDescriptorCollection setDescriptor in SetDescriptors) { hasher.Add(setDescriptor); } @@ -81,7 +81,7 @@ namespace Ryujinx.Graphics.Vulkan ReadOnlyCollection setDescriptors, bool usePushDescriptors) { - var key = new PlceKey(setDescriptors, usePushDescriptors); + PlceKey key = new PlceKey(setDescriptors, usePushDescriptors); return _plces.GetOrAdd(key, newKey => new PipelineLayoutCacheEntry(gd, device, setDescriptors, usePushDescriptors)); } @@ -90,7 +90,7 @@ namespace Ryujinx.Graphics.Vulkan { if (disposing) { - foreach (var plce in _plces.Values) + foreach (PipelineLayoutCacheEntry plce in _plces.Values) { plce.Dispose(); } diff --git a/src/Ryujinx.Graphics.Vulkan/PipelineLayoutCacheEntry.cs b/src/Ryujinx.Graphics.Vulkan/PipelineLayoutCacheEntry.cs index ae296b033..3c78a3ec1 100644 --- a/src/Ryujinx.Graphics.Vulkan/PipelineLayoutCacheEntry.cs +++ b/src/Ryujinx.Graphics.Vulkan/PipelineLayoutCacheEntry.cs @@ -114,7 +114,7 @@ namespace Ryujinx.Graphics.Vulkan { int count = 0; - foreach (var descriptor in setDescriptors[setIndex].Descriptors) + foreach (ResourceDescriptor descriptor in setDescriptors[setIndex].Descriptors) { count += descriptor.Count; } @@ -148,11 +148,11 @@ namespace Ryujinx.Graphics.Vulkan public Auto GetNewDescriptorSetCollection(int setIndex, out bool isNew) { - var list = _currentDsCache[setIndex]; + List> list = _currentDsCache[setIndex]; int index = _dsCacheCursor[setIndex]++; if (index == list.Count) { - var dsc = _descriptorSetManager.AllocateDescriptorSet( + Auto dsc = _descriptorSetManager.AllocateDescriptorSet( _gd.Api, DescriptorSetLayouts[setIndex], _poolSizes[setIndex], @@ -173,8 +173,8 @@ namespace Ryujinx.Graphics.Vulkan { FreeCompletedManualDescriptorSets(); - var list = _manualDsCache[setIndex] ??= new(); - var span = CollectionsMarshal.AsSpan(list); + List list = _manualDsCache[setIndex] ??= new(); + Span span = CollectionsMarshal.AsSpan(list); Queue freeQueue = _freeManualDsCacheEntries[setIndex]; @@ -195,7 +195,7 @@ namespace Ryujinx.Graphics.Vulkan } // Otherwise create a new descriptor set, and add to our pending queue for command buffer consumption tracking. - var dsc = _descriptorSetManager.AllocateDescriptorSet( + Auto dsc = _descriptorSetManager.AllocateDescriptorSet( _gd.Api, DescriptorSetLayouts[setIndex], _poolSizes[setIndex], @@ -214,9 +214,9 @@ namespace Ryujinx.Graphics.Vulkan { FreeCompletedManualDescriptorSets(); - var list = _manualDsCache[setIndex]; - var span = CollectionsMarshal.AsSpan(list); - ref var entry = ref span[cacheIndex]; + List list = _manualDsCache[setIndex]; + Span span = CollectionsMarshal.AsSpan(list); + ref ManualDescriptorSetEntry entry = ref span[cacheIndex]; uint cbMask = 1u << cbs.CommandBufferIndex; @@ -231,15 +231,15 @@ namespace Ryujinx.Graphics.Vulkan private void FreeCompletedManualDescriptorSets() { FenceHolder signalledFence = null; - while (_pendingManualDsConsumptions.TryPeek(out var pds) && (pds.Fence == signalledFence || pds.Fence.IsSignaled())) + while (_pendingManualDsConsumptions.TryPeek(out PendingManualDsConsumption pds) && (pds.Fence == signalledFence || pds.Fence.IsSignaled())) { signalledFence = pds.Fence; // Already checked - don't need to do it again. - var dequeued = _pendingManualDsConsumptions.Dequeue(); + PendingManualDsConsumption dequeued = _pendingManualDsConsumptions.Dequeue(); Debug.Assert(dequeued.Fence == pds.Fence); pds.Fence.Put(); - var span = CollectionsMarshal.AsSpan(_manualDsCache[dequeued.SetIndex]); - ref var entry = ref span[dequeued.CacheIndex]; + Span span = CollectionsMarshal.AsSpan(_manualDsCache[dequeued.SetIndex]); + ref ManualDescriptorSetEntry entry = ref span[dequeued.CacheIndex]; entry.CbRefMask &= ~(1u << dequeued.CommandBufferIndex); if (!entry.InUse && entry.CbRefMask == 0) @@ -252,8 +252,8 @@ namespace Ryujinx.Graphics.Vulkan public void ReleaseManualDescriptorSetCollection(int setIndex, int cacheIndex) { - var list = _manualDsCache[setIndex]; - var span = CollectionsMarshal.AsSpan(list); + List list = _manualDsCache[setIndex]; + Span span = CollectionsMarshal.AsSpan(list); span[cacheIndex].InUse = false; @@ -366,7 +366,7 @@ namespace Ryujinx.Graphics.Vulkan _gd.Api.DestroyDescriptorSetLayout(_device, DescriptorSetLayouts[i], null); } - while (_pendingManualDsConsumptions.TryDequeue(out var pds)) + while (_pendingManualDsConsumptions.TryDequeue(out PendingManualDsConsumption pds)) { pds.Fence.Put(); } diff --git a/src/Ryujinx.Graphics.Vulkan/PipelineLayoutFactory.cs b/src/Ryujinx.Graphics.Vulkan/PipelineLayoutFactory.cs index 8d7815616..ce2d90e6b 100644 --- a/src/Ryujinx.Graphics.Vulkan/PipelineLayoutFactory.cs +++ b/src/Ryujinx.Graphics.Vulkan/PipelineLayoutFactory.cs @@ -83,7 +83,7 @@ namespace Ryujinx.Graphics.Vulkan updateAfterBindFlags[setIndex] = true; } - var descriptorSetLayoutCreateInfo = new DescriptorSetLayoutCreateInfo + DescriptorSetLayoutCreateInfo descriptorSetLayoutCreateInfo = new DescriptorSetLayoutCreateInfo { SType = StructureType.DescriptorSetLayoutCreateInfo, PBindings = pLayoutBindings, @@ -99,7 +99,7 @@ namespace Ryujinx.Graphics.Vulkan fixed (DescriptorSetLayout* pLayouts = layouts) { - var pipelineLayoutCreateInfo = new PipelineLayoutCreateInfo + PipelineLayoutCreateInfo pipelineLayoutCreateInfo = new PipelineLayoutCreateInfo { SType = StructureType.PipelineLayoutCreateInfo, PSetLayouts = pLayouts, diff --git a/src/Ryujinx.Graphics.Vulkan/PipelineState.cs b/src/Ryujinx.Graphics.Vulkan/PipelineState.cs index a726b9edb..5512e7b1d 100644 --- a/src/Ryujinx.Graphics.Vulkan/PipelineState.cs +++ b/src/Ryujinx.Graphics.Vulkan/PipelineState.cs @@ -333,12 +333,12 @@ namespace Ryujinx.Graphics.Vulkan ShaderCollection program, PipelineCache cache) { - if (program.TryGetComputePipeline(ref SpecializationData, out var pipeline)) + if (program.TryGetComputePipeline(ref SpecializationData, out Auto pipeline)) { return pipeline; } - var pipelineCreateInfo = new ComputePipelineCreateInfo + ComputePipelineCreateInfo pipelineCreateInfo = new ComputePipelineCreateInfo { SType = StructureType.ComputePipelineCreateInfo, Stage = Stages[0], @@ -350,7 +350,7 @@ namespace Ryujinx.Graphics.Vulkan bool hasSpec = program.SpecDescriptions != null; - var desc = hasSpec ? program.SpecDescriptions[0] : SpecDescription.Empty; + SpecDescription desc = hasSpec ? program.SpecDescriptions[0] : SpecDescription.Empty; if (hasSpec && SpecializationData.Length < (int)desc.Info.DataSize) { @@ -386,7 +386,7 @@ namespace Ryujinx.Graphics.Vulkan RenderPass renderPass, bool throwOnError = false) { - if (program.TryGetGraphicsPipeline(ref Internal, out var pipeline)) + if (program.TryGetGraphicsPipeline(ref Internal, out Auto pipeline)) { return pipeline; } @@ -405,7 +405,7 @@ namespace Ryujinx.Graphics.Vulkan fixed (VertexInputBindingDescription* pVertexBindingDescriptions = &Internal.VertexBindingDescriptions[0]) fixed (PipelineColorBlendAttachmentState* pColorBlendAttachmentState = &Internal.ColorBlendAttachmentState[0]) { - var vertexInputState = new PipelineVertexInputStateCreateInfo + PipelineVertexInputStateCreateInfo vertexInputState = new PipelineVertexInputStateCreateInfo { SType = StructureType.PipelineVertexInputStateCreateInfo, VertexAttributeDescriptionCount = VertexAttributeDescriptionsCount, @@ -442,20 +442,20 @@ namespace Ryujinx.Graphics.Vulkan primitiveRestartEnable &= topologySupportsRestart; - var inputAssemblyState = new PipelineInputAssemblyStateCreateInfo + PipelineInputAssemblyStateCreateInfo inputAssemblyState = new PipelineInputAssemblyStateCreateInfo { SType = StructureType.PipelineInputAssemblyStateCreateInfo, PrimitiveRestartEnable = primitiveRestartEnable, Topology = HasTessellationControlShader ? PrimitiveTopology.PatchList : Topology, }; - var tessellationState = new PipelineTessellationStateCreateInfo + PipelineTessellationStateCreateInfo tessellationState = new PipelineTessellationStateCreateInfo { SType = StructureType.PipelineTessellationStateCreateInfo, PatchControlPoints = PatchControlPoints, }; - var rasterizationState = new PipelineRasterizationStateCreateInfo + PipelineRasterizationStateCreateInfo rasterizationState = new PipelineRasterizationStateCreateInfo { SType = StructureType.PipelineRasterizationStateCreateInfo, DepthClampEnable = DepthClampEnable, @@ -467,7 +467,7 @@ namespace Ryujinx.Graphics.Vulkan DepthBiasEnable = DepthBiasEnable, }; - var viewportState = new PipelineViewportStateCreateInfo + PipelineViewportStateCreateInfo viewportState = new PipelineViewportStateCreateInfo { SType = StructureType.PipelineViewportStateCreateInfo, ViewportCount = ViewportsCount, @@ -476,7 +476,7 @@ namespace Ryujinx.Graphics.Vulkan if (gd.Capabilities.SupportsDepthClipControl) { - var viewportDepthClipControlState = new PipelineViewportDepthClipControlCreateInfoEXT + PipelineViewportDepthClipControlCreateInfoEXT viewportDepthClipControlState = new PipelineViewportDepthClipControlCreateInfoEXT { SType = StructureType.PipelineViewportDepthClipControlCreateInfoExt, NegativeOneToOne = DepthMode, @@ -485,7 +485,7 @@ namespace Ryujinx.Graphics.Vulkan viewportState.PNext = &viewportDepthClipControlState; } - var multisampleState = new PipelineMultisampleStateCreateInfo + PipelineMultisampleStateCreateInfo multisampleState = new PipelineMultisampleStateCreateInfo { SType = StructureType.PipelineMultisampleStateCreateInfo, SampleShadingEnable = false, @@ -495,19 +495,19 @@ namespace Ryujinx.Graphics.Vulkan AlphaToOneEnable = AlphaToOneEnable, }; - var stencilFront = new StencilOpState( + StencilOpState stencilFront = new StencilOpState( StencilFrontFailOp, StencilFrontPassOp, StencilFrontDepthFailOp, StencilFrontCompareOp); - var stencilBack = new StencilOpState( + StencilOpState stencilBack = new StencilOpState( StencilBackFailOp, StencilBackPassOp, StencilBackDepthFailOp, StencilBackCompareOp); - var depthStencilState = new PipelineDepthStencilStateCreateInfo + PipelineDepthStencilStateCreateInfo depthStencilState = new PipelineDepthStencilStateCreateInfo { SType = StructureType.PipelineDepthStencilStateCreateInfo, DepthTestEnable = DepthTestEnable, @@ -544,7 +544,7 @@ namespace Ryujinx.Graphics.Vulkan // so we need to force disable them here. bool logicOpEnable = LogicOpEnable && (gd.Vendor == Vendor.Nvidia || Internal.LogicOpsAllowed); - var colorBlendState = new PipelineColorBlendStateCreateInfo + PipelineColorBlendStateCreateInfo colorBlendState = new PipelineColorBlendStateCreateInfo { SType = StructureType.PipelineColorBlendStateCreateInfo, LogicOpEnable = logicOpEnable, @@ -595,7 +595,7 @@ namespace Ryujinx.Graphics.Vulkan dynamicStates[dynamicStatesCount++] = DynamicState.AttachmentFeedbackLoopEnableExt; } - var pipelineDynamicStateCreateInfo = new PipelineDynamicStateCreateInfo + PipelineDynamicStateCreateInfo pipelineDynamicStateCreateInfo = new PipelineDynamicStateCreateInfo { SType = StructureType.PipelineDynamicStateCreateInfo, DynamicStateCount = (uint)dynamicStatesCount, @@ -619,7 +619,7 @@ namespace Ryujinx.Graphics.Vulkan } } - var pipelineCreateInfo = new GraphicsPipelineCreateInfo + GraphicsPipelineCreateInfo pipelineCreateInfo = new GraphicsPipelineCreateInfo { SType = StructureType.GraphicsPipelineCreateInfo, Flags = flags, @@ -677,12 +677,12 @@ namespace Ryujinx.Graphics.Vulkan for (int index = 0; index < VertexAttributeDescriptionsCount; index++) { - var attribute = Internal.VertexAttributeDescriptions[index]; + VertexInputAttributeDescription attribute = Internal.VertexAttributeDescriptions[index]; int vbIndex = GetVertexBufferIndex(attribute.Binding); if (vbIndex >= 0) { - ref var vb = ref Internal.VertexBindingDescriptions[vbIndex]; + ref VertexInputBindingDescription vb = ref Internal.VertexBindingDescriptions[vbIndex]; Format format = attribute.Format; diff --git a/src/Ryujinx.Graphics.Vulkan/Queries/BufferedQuery.cs b/src/Ryujinx.Graphics.Vulkan/Queries/BufferedQuery.cs index 5d48a6622..06e14a9d9 100644 --- a/src/Ryujinx.Graphics.Vulkan/Queries/BufferedQuery.cs +++ b/src/Ryujinx.Graphics.Vulkan/Queries/BufferedQuery.cs @@ -4,6 +4,7 @@ using Silk.NET.Vulkan; using System; using System.Runtime.InteropServices; using System.Threading; +using Buffer = Silk.NET.Vulkan.Buffer; namespace Ryujinx.Graphics.Vulkan.Queries { @@ -44,7 +45,7 @@ namespace Ryujinx.Graphics.Vulkan.Queries QueryPipelineStatisticFlags flags = type == CounterType.PrimitivesGenerated ? QueryPipelineStatisticFlags.GeometryShaderPrimitivesBit : 0; - var queryPoolCreateInfo = new QueryPoolCreateInfo + QueryPoolCreateInfo queryPoolCreateInfo = new QueryPoolCreateInfo { SType = StructureType.QueryPoolCreateInfo, QueryCount = 1, @@ -55,7 +56,7 @@ namespace Ryujinx.Graphics.Vulkan.Queries gd.Api.CreateQueryPool(device, in queryPoolCreateInfo, null, out _queryPool).ThrowOnError(); } - var buffer = gd.BufferManager.Create(gd, sizeof(long), forConditionalRendering: true); + BufferHolder buffer = gd.BufferManager.Create(gd, sizeof(long), forConditionalRendering: true); _bufferMap = buffer.Map(0, sizeof(long)); _defaultValue = result32Bit ? DefaultValueInt : DefaultValue; @@ -183,7 +184,7 @@ namespace Ryujinx.Graphics.Vulkan.Queries public void PoolCopy(CommandBufferScoped cbs) { - var buffer = _buffer.GetBuffer(cbs.CommandBuffer, true).Get(cbs, 0, sizeof(long), true).Value; + Buffer buffer = _buffer.GetBuffer(cbs.CommandBuffer, true).Get(cbs, 0, sizeof(long), true).Value; QueryResultFlags flags = QueryResultFlags.ResultWaitBit; diff --git a/src/Ryujinx.Graphics.Vulkan/Queries/Counters.cs b/src/Ryujinx.Graphics.Vulkan/Queries/Counters.cs index c07e1c09c..c0e848f03 100644 --- a/src/Ryujinx.Graphics.Vulkan/Queries/Counters.cs +++ b/src/Ryujinx.Graphics.Vulkan/Queries/Counters.cs @@ -26,7 +26,7 @@ namespace Ryujinx.Graphics.Vulkan.Queries public void ResetCounterPool() { - foreach (var queue in _counterQueues) + foreach (CounterQueue queue in _counterQueues) { queue.ResetCounterPool(); } @@ -49,7 +49,7 @@ namespace Ryujinx.Graphics.Vulkan.Queries public void Update() { - foreach (var queue in _counterQueues) + foreach (CounterQueue queue in _counterQueues) { queue.Flush(false); } @@ -62,7 +62,7 @@ namespace Ryujinx.Graphics.Vulkan.Queries public void Dispose() { - foreach (var queue in _counterQueues) + foreach (CounterQueue queue in _counterQueues) { queue.Dispose(); } diff --git a/src/Ryujinx.Graphics.Vulkan/RenderPassCacheKey.cs b/src/Ryujinx.Graphics.Vulkan/RenderPassCacheKey.cs index 7c57b8feb..c3c3c2c61 100644 --- a/src/Ryujinx.Graphics.Vulkan/RenderPassCacheKey.cs +++ b/src/Ryujinx.Graphics.Vulkan/RenderPassCacheKey.cs @@ -22,7 +22,7 @@ namespace Ryujinx.Graphics.Vulkan if (_colors != null) { - foreach (var color in _colors) + foreach (TextureView color in _colors) { hc.Add(color); } diff --git a/src/Ryujinx.Graphics.Vulkan/RenderPassHolder.cs b/src/Ryujinx.Graphics.Vulkan/RenderPassHolder.cs index a364c5716..bca18e0ee 100644 --- a/src/Ryujinx.Graphics.Vulkan/RenderPassHolder.cs +++ b/src/Ryujinx.Graphics.Vulkan/RenderPassHolder.cs @@ -47,14 +47,14 @@ namespace Ryujinx.Graphics.Vulkan AttachmentDescription[] attachmentDescs = null; - var subpass = new SubpassDescription + SubpassDescription subpass = new SubpassDescription { PipelineBindPoint = PipelineBindPoint.Graphics, }; AttachmentReference* attachmentReferences = stackalloc AttachmentReference[MaxAttachments]; - var hasFramebuffer = fb != null; + bool hasFramebuffer = fb != null; if (hasFramebuffer && fb.AttachmentsCount != 0) { @@ -110,11 +110,11 @@ namespace Ryujinx.Graphics.Vulkan } } - var subpassDependency = PipelineConverter.CreateSubpassDependency(gd); + SubpassDependency subpassDependency = PipelineConverter.CreateSubpassDependency(gd); fixed (AttachmentDescription* pAttachmentDescs = attachmentDescs) { - var renderPassCreateInfo = new RenderPassCreateInfo + RenderPassCreateInfo renderPassCreateInfo = new RenderPassCreateInfo { SType = StructureType.RenderPassCreateInfo, PAttachments = pAttachmentDescs, @@ -125,7 +125,7 @@ namespace Ryujinx.Graphics.Vulkan DependencyCount = 1, }; - gd.Api.CreateRenderPass(device, in renderPassCreateInfo, null, out var renderPass).ThrowOnError(); + gd.Api.CreateRenderPass(device, in renderPassCreateInfo, null, out RenderPass renderPass).ThrowOnError(); _renderPass = new Auto(new DisposableRenderPass(gd.Api, device, renderPass)); } @@ -134,9 +134,9 @@ namespace Ryujinx.Graphics.Vulkan // Register this render pass with all render target views. - var textures = fb.GetAttachmentViews(); + TextureView[] textures = fb.GetAttachmentViews(); - foreach (var texture in textures) + foreach (TextureView texture in textures) { texture.AddRenderPass(key, this); } @@ -149,7 +149,7 @@ namespace Ryujinx.Graphics.Vulkan public Auto GetFramebuffer(VulkanRenderer gd, CommandBufferScoped cbs, FramebufferParams fb) { - var key = new FramebufferCacheKey(fb.Width, fb.Height, fb.Layers); + FramebufferCacheKey key = new FramebufferCacheKey(fb.Width, fb.Height, fb.Layers); if (!_framebuffers.TryGetValue(ref key, out Auto result)) { @@ -201,14 +201,14 @@ namespace Ryujinx.Graphics.Vulkan { // Dispose all framebuffers. - foreach (var fb in _framebuffers.Values) + foreach (Auto fb in _framebuffers.Values) { fb.Dispose(); } // Notify all texture views that this render pass has been disposed. - foreach (var texture in _textures) + foreach (TextureView texture in _textures) { texture.RemoveRenderPass(_key); } diff --git a/src/Ryujinx.Graphics.Vulkan/ResourceArray.cs b/src/Ryujinx.Graphics.Vulkan/ResourceArray.cs index f96b4a845..c97676858 100644 --- a/src/Ryujinx.Graphics.Vulkan/ResourceArray.cs +++ b/src/Ryujinx.Graphics.Vulkan/ResourceArray.cs @@ -42,7 +42,7 @@ namespace Ryujinx.Graphics.Vulkan return true; } - var dsc = program.GetNewManualDescriptorSetCollection(cbs, setIndex, out _cachedDscIndex).Get(cbs); + DescriptorSetCollection dsc = program.GetNewManualDescriptorSetCollection(cbs, setIndex, out _cachedDscIndex).Get(cbs); sets = dsc.GetSets(); diff --git a/src/Ryujinx.Graphics.Vulkan/ResourceLayoutBuilder.cs b/src/Ryujinx.Graphics.Vulkan/ResourceLayoutBuilder.cs index 730a0a2f9..ff0ed30af 100644 --- a/src/Ryujinx.Graphics.Vulkan/ResourceLayoutBuilder.cs +++ b/src/Ryujinx.Graphics.Vulkan/ResourceLayoutBuilder.cs @@ -42,8 +42,8 @@ namespace Ryujinx.Graphics.Vulkan public ResourceLayout Build() { - var descriptors = new ResourceDescriptorCollection[TotalSets]; - var usages = new ResourceUsageCollection[TotalSets]; + ResourceDescriptorCollection[] descriptors = new ResourceDescriptorCollection[TotalSets]; + ResourceUsageCollection[] usages = new ResourceUsageCollection[TotalSets]; for (int index = 0; index < TotalSets; index++) { diff --git a/src/Ryujinx.Graphics.Vulkan/SamplerHolder.cs b/src/Ryujinx.Graphics.Vulkan/SamplerHolder.cs index 7f37ab139..cf8874e1a 100644 --- a/src/Ryujinx.Graphics.Vulkan/SamplerHolder.cs +++ b/src/Ryujinx.Graphics.Vulkan/SamplerHolder.cs @@ -26,9 +26,9 @@ namespace Ryujinx.Graphics.Vulkan maxLod = 0.25f; } - var borderColor = GetConstrainedBorderColor(info.BorderColor, out var cantConstrain); + BorderColor borderColor = GetConstrainedBorderColor(info.BorderColor, out bool cantConstrain); - var samplerCreateInfo = new Silk.NET.Vulkan.SamplerCreateInfo + Silk.NET.Vulkan.SamplerCreateInfo samplerCreateInfo = new Silk.NET.Vulkan.SamplerCreateInfo { SType = StructureType.SamplerCreateInfo, MagFilter = info.MagFilter.Convert(), @@ -52,7 +52,7 @@ namespace Ryujinx.Graphics.Vulkan if (cantConstrain && gd.Capabilities.SupportsCustomBorderColor) { - var color = new ClearColorValue( + ClearColorValue color = new ClearColorValue( info.BorderColor.Red, info.BorderColor.Green, info.BorderColor.Blue, @@ -68,7 +68,7 @@ namespace Ryujinx.Graphics.Vulkan samplerCreateInfo.BorderColor = BorderColor.FloatCustomExt; } - gd.Api.CreateSampler(device, in samplerCreateInfo, null, out var sampler).ThrowOnError(); + gd.Api.CreateSampler(device, in samplerCreateInfo, null, out Sampler sampler).ThrowOnError(); _sampler = new Auto(new DisposableSampler(gd.Api, device, sampler)); } diff --git a/src/Ryujinx.Graphics.Vulkan/Shader.cs b/src/Ryujinx.Graphics.Vulkan/Shader.cs index 79e2f712a..524939311 100644 --- a/src/Ryujinx.Graphics.Vulkan/Shader.cs +++ b/src/Ryujinx.Graphics.Vulkan/Shader.cs @@ -7,6 +7,7 @@ using System; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; +using Result = shaderc.Result; namespace Ryujinx.Graphics.Vulkan { @@ -58,7 +59,7 @@ namespace Ryujinx.Graphics.Vulkan fixed (byte* pCode = spirv) { - var shaderModuleCreateInfo = new ShaderModuleCreateInfo + ShaderModuleCreateInfo shaderModuleCreateInfo = new ShaderModuleCreateInfo { SType = StructureType.ShaderModuleCreateInfo, CodeSize = (uint)spirv.Length, @@ -87,7 +88,7 @@ namespace Ryujinx.Graphics.Vulkan options.SetTargetEnvironment(TargetEnvironment.Vulkan, EnvironmentVersion.Vulkan_1_2); Compiler compiler = new(options); - var scr = compiler.Compile(glsl, "Ryu", GetShaderCShaderStage(stage)); + Result scr = compiler.Compile(glsl, "Ryu", GetShaderCShaderStage(stage)); lock (_shaderOptionsLock) { @@ -101,7 +102,7 @@ namespace Ryujinx.Graphics.Vulkan return null; } - var spirvBytes = new Span((void*)scr.CodePointer, (int)scr.CodeLength); + Span spirvBytes = new Span((void*)scr.CodePointer, (int)scr.CodeLength); byte[] code = new byte[(scr.CodeLength + 3) & ~3]; diff --git a/src/Ryujinx.Graphics.Vulkan/ShaderCollection.cs b/src/Ryujinx.Graphics.Vulkan/ShaderCollection.cs index 436914330..5d35bbbed 100644 --- a/src/Ryujinx.Graphics.Vulkan/ShaderCollection.cs +++ b/src/Ryujinx.Graphics.Vulkan/ShaderCollection.cs @@ -81,7 +81,7 @@ namespace Ryujinx.Graphics.Vulkan gd.Shaders.Add(this); - var internalShaders = new Shader[shaders.Length]; + Shader[] internalShaders = new Shader[shaders.Length]; _infos = new PipelineShaderStageCreateInfo[shaders.Length]; @@ -93,7 +93,7 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < shaders.Length; i++) { - var shader = new Shader(gd.Api, device, shaders[i]); + Shader shader = new Shader(gd.Api, device, shaders[i]); stages |= 1u << shader.StageFlags switch { @@ -173,7 +173,7 @@ namespace Ryujinx.Graphics.Vulkan // Can't use any of the reserved usages. for (int i = 0; i < uniformUsage.Count; i++) { - var binding = uniformUsage[i].Binding; + int binding = uniformUsage[i].Binding; if (reserved.Contains(binding) || binding >= Constants.MaxPushDescriptorBinding || @@ -203,7 +203,7 @@ namespace Ryujinx.Graphics.Vulkan // The reserved bindings were selected when determining if push descriptors could be used. int[] reserved = gd.GetPushDescriptorReservedBindings(false); - var result = new ResourceDescriptorCollection[sets.Count]; + ResourceDescriptorCollection[] result = new ResourceDescriptorCollection[sets.Count]; for (int i = 0; i < sets.Count; i++) { @@ -212,7 +212,7 @@ namespace Ryujinx.Graphics.Vulkan // Push descriptors apply here. Remove reserved bindings. ResourceDescriptorCollection original = sets[i]; - var pdUniforms = new ResourceDescriptor[original.Descriptors.Count]; + ResourceDescriptor[] pdUniforms = new ResourceDescriptor[original.Descriptors.Count]; int j = 0; foreach (ResourceDescriptor descriptor in original.Descriptors) @@ -364,7 +364,7 @@ namespace Ryujinx.Graphics.Vulkan private DescriptorSetTemplate[] BuildTemplates(bool usePushDescriptors) { - var templates = new DescriptorSetTemplate[BindingSegments.Length]; + DescriptorSetTemplate[] templates = new DescriptorSetTemplate[BindingSegments.Length]; for (int setIndex = 0; setIndex < BindingSegments.Length; setIndex++) { @@ -433,9 +433,9 @@ namespace Ryujinx.Graphics.Vulkan PipelineStageFlags buffer = PipelineStageFlags.None; PipelineStageFlags texture = PipelineStageFlags.None; - foreach (var set in setUsages) + foreach (ResourceUsageCollection set in setUsages) { - foreach (var range in set.Usages) + foreach (ResourceUsage range in set.Usages) { if (range.Write) { @@ -498,7 +498,7 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < _shaders.Length; i++) { - var shader = _shaders[i]; + Shader shader = _shaders[i]; if (shader.CompileStatus != ProgramLinkStatus.Success) { @@ -557,12 +557,12 @@ namespace Ryujinx.Graphics.Vulkan // First, we need to create a render pass object compatible with the one that will be used at runtime. // The active attachment formats have been provided by the abstraction layer. - var renderPass = CreateDummyRenderPass(); + DisposableRenderPass renderPass = CreateDummyRenderPass(); PipelineState pipeline = _state.ToVulkanPipelineState(_gd); // Copy the shader stage info to the pipeline. - var stages = pipeline.Stages.AsSpan(); + Span stages = pipeline.Stages.AsSpan(); for (int i = 0; i < _shaders.Length; i++) { diff --git a/src/Ryujinx.Graphics.Vulkan/SpecInfo.cs b/src/Ryujinx.Graphics.Vulkan/SpecInfo.cs index ecb2abfc6..200fe658b 100644 --- a/src/Ryujinx.Graphics.Vulkan/SpecInfo.cs +++ b/src/Ryujinx.Graphics.Vulkan/SpecInfo.cs @@ -29,7 +29,7 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < Map.Length; ++i) { - var typeSize = SizeOf(description[i].Type); + uint typeSize = SizeOf(description[i].Type); Map[i] = new SpecializationMapEntry(description[i].Id, structSize, typeSize); structSize += typeSize; } @@ -89,7 +89,7 @@ namespace Ryujinx.Graphics.Vulkan _data = new byte[data.Length]; data.CopyTo(_data); - var hc = new HashCode(); + HashCode hc = new HashCode(); hc.AddBytes(data); _hash = hc.ToHashCode(); } diff --git a/src/Ryujinx.Graphics.Vulkan/StagingBuffer.cs b/src/Ryujinx.Graphics.Vulkan/StagingBuffer.cs index 90a47bb67..6470354cf 100644 --- a/src/Ryujinx.Graphics.Vulkan/StagingBuffer.cs +++ b/src/Ryujinx.Graphics.Vulkan/StagingBuffer.cs @@ -107,8 +107,8 @@ namespace Ryujinx.Graphics.Vulkan private void PushDataImpl(CommandBufferScoped cbs, BufferHolder dst, int dstOffset, ReadOnlySpan data) { - var srcBuffer = _buffer.GetBuffer(); - var dstBuffer = dst.GetBuffer(cbs.CommandBuffer, dstOffset, data.Length, true); + Auto srcBuffer = _buffer.GetBuffer(); + Auto dstBuffer = dst.GetBuffer(cbs.CommandBuffer, dstOffset, data.Length, true); int offset = _freeOffset; int capacity = BufferSize - offset; @@ -242,7 +242,7 @@ namespace Ryujinx.Graphics.Vulkan private bool WaitFreeCompleted(CommandBufferPool cbp) { - if (_pendingCopies.TryPeek(out var pc)) + if (_pendingCopies.TryPeek(out PendingCopy pc)) { if (!pc.Fence.IsSignaled()) { @@ -254,7 +254,7 @@ namespace Ryujinx.Graphics.Vulkan pc.Fence.Wait(); } - var dequeued = _pendingCopies.Dequeue(); + PendingCopy dequeued = _pendingCopies.Dequeue(); Debug.Assert(dequeued.Fence == pc.Fence); _freeSize += pc.Size; pc.Fence.Put(); @@ -266,10 +266,10 @@ namespace Ryujinx.Graphics.Vulkan public void FreeCompleted() { FenceHolder signalledFence = null; - while (_pendingCopies.TryPeek(out var pc) && (pc.Fence == signalledFence || pc.Fence.IsSignaled())) + while (_pendingCopies.TryPeek(out PendingCopy pc) && (pc.Fence == signalledFence || pc.Fence.IsSignaled())) { signalledFence = pc.Fence; // Already checked - don't need to do it again. - var dequeued = _pendingCopies.Dequeue(); + PendingCopy dequeued = _pendingCopies.Dequeue(); Debug.Assert(dequeued.Fence == pc.Fence); _freeSize += pc.Size; pc.Fence.Put(); @@ -282,7 +282,7 @@ namespace Ryujinx.Graphics.Vulkan { _gd.BufferManager.Delete(Handle); - while (_pendingCopies.TryDequeue(out var pc)) + while (_pendingCopies.TryDequeue(out PendingCopy pc)) { pc.Fence.Put(); } diff --git a/src/Ryujinx.Graphics.Vulkan/TextureArray.cs b/src/Ryujinx.Graphics.Vulkan/TextureArray.cs index 99238b1f5..74129da92 100644 --- a/src/Ryujinx.Graphics.Vulkan/TextureArray.cs +++ b/src/Ryujinx.Graphics.Vulkan/TextureArray.cs @@ -148,8 +148,8 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < textures.Length; i++) { - ref var texture = ref textures[i]; - ref var refs = ref _textureRefs[i]; + ref DescriptorImageInfo texture = ref textures[i]; + ref TextureRef refs = ref _textureRefs[i]; if (i > 0 && _textureRefs[i - 1].View == refs.View && _textureRefs[i - 1].Sampler == refs.Sampler) { diff --git a/src/Ryujinx.Graphics.Vulkan/TextureCopy.cs b/src/Ryujinx.Graphics.Vulkan/TextureCopy.cs index 45cddd772..ee306e9fa 100644 --- a/src/Ryujinx.Graphics.Vulkan/TextureCopy.cs +++ b/src/Ryujinx.Graphics.Vulkan/TextureCopy.cs @@ -34,8 +34,8 @@ namespace Ryujinx.Graphics.Vulkan return Math.Clamp(value, 0, max); } - var xy1 = new Offset3D(Clamp(extents.X1, width) >> level, Clamp(extents.Y1, height) >> level, 0); - var xy2 = new Offset3D(Clamp(extents.X2, width) >> level, Clamp(extents.Y2, height) >> level, 1); + Offset3D xy1 = new Offset3D(Clamp(extents.X1, width) >> level, Clamp(extents.Y1, height) >> level, 0); + Offset3D xy2 = new Offset3D(Clamp(extents.X2, width) >> level, Clamp(extents.Y2, height) >> level, 1); return (xy1, xy2); } @@ -50,10 +50,10 @@ namespace Ryujinx.Graphics.Vulkan dstAspectFlags = dstInfo.Format.ConvertAspectFlags(); } - var srcOffsets = new ImageBlit.SrcOffsetsBuffer(); - var dstOffsets = new ImageBlit.DstOffsetsBuffer(); + ImageBlit.SrcOffsetsBuffer srcOffsets = new ImageBlit.SrcOffsetsBuffer(); + ImageBlit.DstOffsetsBuffer dstOffsets = new ImageBlit.DstOffsetsBuffer(); - var filter = linearFilter && !dstInfo.Format.IsDepthOrStencil() ? Filter.Linear : Filter.Nearest; + Filter filter = linearFilter && !dstInfo.Format.IsDepthOrStencil() ? Filter.Linear : Filter.Nearest; TextureView.InsertImageBarrier( api, @@ -74,13 +74,13 @@ namespace Ryujinx.Graphics.Vulkan for (int level = 0; level < levels; level++) { - var srcSl = new ImageSubresourceLayers(srcAspectFlags, copySrcLevel, (uint)srcLayer, (uint)layers); - var dstSl = new ImageSubresourceLayers(dstAspectFlags, copyDstLevel, (uint)dstLayer, (uint)layers); + ImageSubresourceLayers srcSl = new ImageSubresourceLayers(srcAspectFlags, copySrcLevel, (uint)srcLayer, (uint)layers); + ImageSubresourceLayers dstSl = new ImageSubresourceLayers(dstAspectFlags, copyDstLevel, (uint)dstLayer, (uint)layers); (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 + ImageBlit region = new ImageBlit { SrcSubresource = srcSl, SrcOffsets = srcOffsets, @@ -299,13 +299,13 @@ namespace Ryujinx.Graphics.Vulkan break; } - var srcSl = new ImageSubresourceLayers( + ImageSubresourceLayers srcSl = new ImageSubresourceLayers( srcAspect, (uint)(srcViewLevel + srcLevel + level), (uint)(srcViewLayer + srcLayer), (uint)srcLayers); - var dstSl = new ImageSubresourceLayers( + ImageSubresourceLayers dstSl = new ImageSubresourceLayers( dstAspect, (uint)(dstViewLevel + dstLevel + level), (uint)(dstViewLayer + dstLayer), @@ -314,17 +314,17 @@ namespace Ryujinx.Graphics.Vulkan int copyWidth = sizeInBlocks ? BitUtils.DivRoundUp(width, blockWidth) : width; int copyHeight = sizeInBlocks ? BitUtils.DivRoundUp(height, blockHeight) : height; - var extent = new Extent3D((uint)copyWidth, (uint)copyHeight, (uint)srcDepth); + Extent3D extent = new Extent3D((uint)copyWidth, (uint)copyHeight, (uint)srcDepth); if (srcInfo.Samples > 1 && srcInfo.Samples != dstInfo.Samples) { - var region = new ImageResolve(srcSl, new Offset3D(0, 0, srcZ), dstSl, new Offset3D(0, 0, dstZ), extent); + ImageResolve region = new ImageResolve(srcSl, new Offset3D(0, 0, srcZ), dstSl, new Offset3D(0, 0, dstZ), extent); api.CmdResolveImage(commandBuffer, srcImage, ImageLayout.General, dstImage, ImageLayout.General, 1, in region); } else { - var region = new ImageCopy(srcSl, new Offset3D(0, 0, srcZ), dstSl, new Offset3D(0, 0, dstZ), extent); + ImageCopy region = new ImageCopy(srcSl, new Offset3D(0, 0, srcZ), dstSl, new Offset3D(0, 0, dstZ), extent); api.CmdCopyImage(commandBuffer, srcImage, ImageLayout.General, dstImage, ImageLayout.General, 1, in region); } @@ -360,10 +360,10 @@ namespace Ryujinx.Graphics.Vulkan TextureView src, TextureView dst) { - var dsAttachmentReference = new AttachmentReference2(StructureType.AttachmentReference2, null, 0, ImageLayout.General); - var dsResolveAttachmentReference = new AttachmentReference2(StructureType.AttachmentReference2, null, 1, ImageLayout.General); + AttachmentReference2 dsAttachmentReference = new AttachmentReference2(StructureType.AttachmentReference2, null, 0, ImageLayout.General); + AttachmentReference2 dsResolveAttachmentReference = new AttachmentReference2(StructureType.AttachmentReference2, null, 1, ImageLayout.General); - var subpassDsResolve = new SubpassDescriptionDepthStencilResolve + SubpassDescriptionDepthStencilResolve subpassDsResolve = new SubpassDescriptionDepthStencilResolve { SType = StructureType.SubpassDescriptionDepthStencilResolve, PDepthStencilResolveAttachment = &dsResolveAttachmentReference, @@ -371,7 +371,7 @@ namespace Ryujinx.Graphics.Vulkan StencilResolveMode = ResolveModeFlags.SampleZeroBit, }; - var subpass = new SubpassDescription2 + SubpassDescription2 subpass = new SubpassDescription2 { SType = StructureType.SubpassDescription2, PipelineBindPoint = PipelineBindPoint.Graphics, @@ -407,11 +407,11 @@ namespace Ryujinx.Graphics.Vulkan ImageLayout.General, ImageLayout.General); - var subpassDependency = PipelineConverter.CreateSubpassDependency2(gd); + SubpassDependency2 subpassDependency = PipelineConverter.CreateSubpassDependency2(gd); fixed (AttachmentDescription2* pAttachmentDescs = attachmentDescs) { - var renderPassCreateInfo = new RenderPassCreateInfo2 + RenderPassCreateInfo2 renderPassCreateInfo = new RenderPassCreateInfo2 { SType = StructureType.RenderPassCreateInfo2, PAttachments = pAttachmentDescs, @@ -422,19 +422,19 @@ namespace Ryujinx.Graphics.Vulkan DependencyCount = 1, }; - gd.Api.CreateRenderPass2(device, in renderPassCreateInfo, null, out var renderPass).ThrowOnError(); + gd.Api.CreateRenderPass2(device, in renderPassCreateInfo, null, out RenderPass renderPass).ThrowOnError(); - using var rp = new Auto(new DisposableRenderPass(gd.Api, device, renderPass)); + using Auto rp = new Auto(new DisposableRenderPass(gd.Api, device, renderPass)); ImageView* attachments = stackalloc ImageView[2]; - var srcView = src.GetImageViewForAttachment(); - var dstView = dst.GetImageViewForAttachment(); + Auto srcView = src.GetImageViewForAttachment(); + Auto dstView = dst.GetImageViewForAttachment(); attachments[0] = srcView.Get(cbs).Value; attachments[1] = dstView.Get(cbs).Value; - var framebufferCreateInfo = new FramebufferCreateInfo + FramebufferCreateInfo framebufferCreateInfo = new FramebufferCreateInfo { SType = StructureType.FramebufferCreateInfo, RenderPass = rp.Get(cbs).Value, @@ -445,13 +445,13 @@ namespace Ryujinx.Graphics.Vulkan Layers = (uint)src.Layers, }; - gd.Api.CreateFramebuffer(device, in framebufferCreateInfo, null, out var framebuffer).ThrowOnError(); - using var fb = new Auto(new DisposableFramebuffer(gd.Api, device, framebuffer), null, srcView, dstView); + gd.Api.CreateFramebuffer(device, in framebufferCreateInfo, null, out Framebuffer framebuffer).ThrowOnError(); + using Auto 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(); + Rect2D renderArea = new Rect2D(null, new Extent2D((uint)src.Info.Width, (uint)src.Info.Height)); + ClearValue clearValue = new ClearValue(); - var renderPassBeginInfo = new RenderPassBeginInfo + RenderPassBeginInfo renderPassBeginInfo = new RenderPassBeginInfo { SType = StructureType.RenderPassBeginInfo, RenderPass = rp.Get(cbs).Value, diff --git a/src/Ryujinx.Graphics.Vulkan/TextureStorage.cs b/src/Ryujinx.Graphics.Vulkan/TextureStorage.cs index 51ef528d4..53a80051f 100644 --- a/src/Ryujinx.Graphics.Vulkan/TextureStorage.cs +++ b/src/Ryujinx.Graphics.Vulkan/TextureStorage.cs @@ -79,23 +79,23 @@ namespace Ryujinx.Graphics.Vulkan bool isMsImageStorageSupported = gd.Capabilities.SupportsShaderStorageImageMultisample || !info.Target.IsMultisample(); - var format = _gd.FormatCapabilities.ConvertToVkFormat(info.Format, isMsImageStorageSupported); - var levels = (uint)info.Levels; - var layers = (uint)info.GetLayers(); - var depth = (uint)(info.Target == Target.Texture3D ? info.Depth : 1); + VkFormat format = _gd.FormatCapabilities.ConvertToVkFormat(info.Format, isMsImageStorageSupported); + uint levels = (uint)info.Levels; + uint layers = (uint)info.GetLayers(); + uint depth = (uint)(info.Target == Target.Texture3D ? info.Depth : 1); VkFormat = format; _depthOrLayers = info.GetDepthOrLayers(); - var type = info.Target.Convert(); + ImageType type = info.Target.Convert(); - var extent = new Extent3D((uint)info.Width, (uint)info.Height, depth); + Extent3D extent = new Extent3D((uint)info.Width, (uint)info.Height, depth); - var sampleCountFlags = ConvertToSampleCountFlags(gd.Capabilities.SupportedSampleCounts, (uint)info.Samples); + SampleCountFlags sampleCountFlags = ConvertToSampleCountFlags(gd.Capabilities.SupportedSampleCounts, (uint)info.Samples); - var usage = GetImageUsage(info.Format, gd.Capabilities, isMsImageStorageSupported, true); + ImageUsageFlags usage = GetImageUsage(info.Format, gd.Capabilities, isMsImageStorageSupported, true); - var flags = ImageCreateFlags.CreateMutableFormatBit | ImageCreateFlags.CreateExtendedUsageBit; + ImageCreateFlags flags = ImageCreateFlags.CreateMutableFormatBit | ImageCreateFlags.CreateExtendedUsageBit; // This flag causes mipmapped texture arrays to break on AMD GCN, so for that copy dependencies are forced for aliasing as cube. bool isCube = info.Target == Target.Cubemap || info.Target == Target.CubemapArray; @@ -111,7 +111,7 @@ namespace Ryujinx.Graphics.Vulkan flags |= ImageCreateFlags.Create2DArrayCompatibleBit; } - var imageCreateInfo = new ImageCreateInfo + ImageCreateInfo imageCreateInfo = new ImageCreateInfo { SType = StructureType.ImageCreateInfo, ImageType = type, @@ -131,8 +131,8 @@ namespace Ryujinx.Graphics.Vulkan if (foreignAllocation == null) { - gd.Api.GetImageMemoryRequirements(device, _image, out var requirements); - var allocation = gd.MemoryAllocator.AllocateDeviceMemory(requirements, DefaultImageMemoryFlags); + gd.Api.GetImageMemoryRequirements(device, _image, out MemoryRequirements requirements); + MemoryAllocation allocation = gd.MemoryAllocator.AllocateDeviceMemory(requirements, DefaultImageMemoryFlags); if (allocation.Memory.Handle == 0UL) { @@ -153,7 +153,7 @@ namespace Ryujinx.Graphics.Vulkan { _foreignAllocationAuto = foreignAllocation; foreignAllocation.IncrementReferenceCount(); - var allocation = foreignAllocation.GetUnsafe(); + MemoryAllocation allocation = foreignAllocation.GetUnsafe(); gd.Api.BindImageMemory(device, _image, allocation.Memory, allocation.Offset).ThrowOnError(); @@ -167,7 +167,7 @@ namespace Ryujinx.Graphics.Vulkan public TextureStorage CreateAliasedColorForDepthStorageUnsafe(Format format) { - var colorFormat = format switch + Format colorFormat = format switch { Format.S8Uint => Format.R8Unorm, Format.D16Unorm => Format.R16Unorm, @@ -182,11 +182,11 @@ namespace Ryujinx.Graphics.Vulkan public TextureStorage CreateAliasedStorageUnsafe(Format format) { - if (_aliasedStorages == null || !_aliasedStorages.TryGetValue(format, out var storage)) + if (_aliasedStorages == null || !_aliasedStorages.TryGetValue(format, out TextureStorage storage)) { _aliasedStorages ??= new Dictionary(); - var info = NewCreateInfoWith(ref _info, format, _info.BytesPerPixel); + TextureCreateInfo info = NewCreateInfoWith(ref _info, format, _info.BytesPerPixel); storage = new TextureStorage(_gd, _device, info, _allocationAuto); @@ -272,11 +272,11 @@ namespace Ryujinx.Graphics.Vulkan } } - var aspectFlags = _info.Format.ConvertAspectFlags(); + ImageAspectFlags aspectFlags = _info.Format.ConvertAspectFlags(); - var subresourceRange = new ImageSubresourceRange(aspectFlags, 0, (uint)_info.Levels, 0, (uint)_info.GetLayers()); + ImageSubresourceRange subresourceRange = new ImageSubresourceRange(aspectFlags, 0, (uint)_info.Levels, 0, (uint)_info.GetLayers()); - var barrier = new ImageMemoryBarrier + ImageMemoryBarrier barrier = new ImageMemoryBarrier { SType = StructureType.ImageMemoryBarrier, SrcAccessMask = 0, @@ -309,7 +309,7 @@ namespace Ryujinx.Graphics.Vulkan public static ImageUsageFlags GetImageUsage(Format format, in HardwareCapabilities capabilities, bool isMsImageStorageSupported, bool extendedUsage) { - var usage = DefaultUsageFlags; + ImageUsageFlags usage = DefaultUsageFlags; if (format.IsDepthOrStencil()) { @@ -402,17 +402,17 @@ namespace Ryujinx.Graphics.Vulkan int rowLength = (Info.GetMipStride(level) / Info.BytesPerPixel) * Info.BlockWidth; - var sl = new ImageSubresourceLayers( + ImageSubresourceLayers sl = new ImageSubresourceLayers( aspectFlags, (uint)(dstLevel + level), (uint)layer, (uint)layers); - var extent = new Extent3D((uint)width, (uint)height, (uint)depth); + Extent3D extent = new Extent3D((uint)width, (uint)height, (uint)depth); int z = is3D ? dstLayer : 0; - var region = new BufferImageCopy( + BufferImageCopy region = new BufferImageCopy( (ulong)offset, (uint)BitUtils.AlignUp(rowLength, Info.BlockWidth), (uint)BitUtils.AlignUp(height, Info.BlockHeight), @@ -601,7 +601,7 @@ namespace Ryujinx.Graphics.Vulkan if (_aliasedStorages != null) { - foreach (var storage in _aliasedStorages.Values) + foreach (TextureStorage storage in _aliasedStorages.Values) { storage.Dispose(); } diff --git a/src/Ryujinx.Graphics.Vulkan/TextureView.cs b/src/Ryujinx.Graphics.Vulkan/TextureView.cs index 64d976a45..45328b73f 100644 --- a/src/Ryujinx.Graphics.Vulkan/TextureView.cs +++ b/src/Ryujinx.Graphics.Vulkan/TextureView.cs @@ -63,20 +63,20 @@ namespace Ryujinx.Graphics.Vulkan bool isMsImageStorageSupported = gd.Capabilities.SupportsShaderStorageImageMultisample || !info.Target.IsMultisample(); - var format = _gd.FormatCapabilities.ConvertToVkFormat(info.Format, isMsImageStorageSupported); - var usage = TextureStorage.GetImageUsage(info.Format, gd.Capabilities, isMsImageStorageSupported, false); + VkFormat format = _gd.FormatCapabilities.ConvertToVkFormat(info.Format, isMsImageStorageSupported); + ImageUsageFlags usage = TextureStorage.GetImageUsage(info.Format, gd.Capabilities, isMsImageStorageSupported, false); - var levels = (uint)info.Levels; - var layers = (uint)info.GetLayers(); + uint levels = (uint)info.Levels; + uint layers = (uint)info.GetLayers(); VkFormat = format; - var type = info.Target.ConvertView(); + ImageViewType type = info.Target.ConvertView(); - var swizzleR = info.SwizzleR.Convert(); - var swizzleG = info.SwizzleG.Convert(); - var swizzleB = info.SwizzleB.Convert(); - var swizzleA = info.SwizzleA.Convert(); + ComponentSwizzle swizzleR = info.SwizzleR.Convert(); + ComponentSwizzle swizzleG = info.SwizzleG.Convert(); + ComponentSwizzle swizzleB = info.SwizzleB.Convert(); + ComponentSwizzle swizzleA = info.SwizzleA.Convert(); if (info.Format == Format.R5G5B5A1Unorm || info.Format == Format.R5G5B5X1Unorm || @@ -86,8 +86,8 @@ namespace Ryujinx.Graphics.Vulkan } else if (VkFormat == VkFormat.R4G4B4A4UnormPack16 || info.Format == Format.A1B5G5R5Unorm) { - var tempB = swizzleB; - var tempA = swizzleA; + ComponentSwizzle tempB = swizzleB; + ComponentSwizzle tempA = swizzleA; swizzleB = swizzleG; swizzleA = swizzleR; @@ -95,23 +95,23 @@ namespace Ryujinx.Graphics.Vulkan swizzleG = tempB; } - var componentMapping = new ComponentMapping(swizzleR, swizzleG, swizzleB, swizzleA); + ComponentMapping componentMapping = new ComponentMapping(swizzleR, swizzleG, swizzleB, swizzleA); - var aspectFlags = info.Format.ConvertAspectFlags(info.DepthStencilMode); - var aspectFlagsDepth = info.Format.ConvertAspectFlags(); + ImageAspectFlags aspectFlags = info.Format.ConvertAspectFlags(info.DepthStencilMode); + ImageAspectFlags aspectFlagsDepth = info.Format.ConvertAspectFlags(); - var subresourceRange = new ImageSubresourceRange(aspectFlags, (uint)firstLevel, levels, (uint)firstLayer, layers); - var subresourceRangeDepth = new ImageSubresourceRange(aspectFlagsDepth, (uint)firstLevel, levels, (uint)firstLayer, layers); + ImageSubresourceRange subresourceRange = new ImageSubresourceRange(aspectFlags, (uint)firstLevel, levels, (uint)firstLayer, layers); + ImageSubresourceRange subresourceRangeDepth = new ImageSubresourceRange(aspectFlagsDepth, (uint)firstLevel, levels, (uint)firstLayer, layers); unsafe Auto CreateImageView(ComponentMapping cm, ImageSubresourceRange sr, ImageViewType viewType, ImageUsageFlags usageFlags) { - var imageViewUsage = new ImageViewUsageCreateInfo + ImageViewUsageCreateInfo imageViewUsage = new ImageViewUsageCreateInfo { SType = StructureType.ImageViewUsageCreateInfo, Usage = usageFlags, }; - var imageCreateInfo = new ImageViewCreateInfo + ImageViewCreateInfo imageCreateInfo = new ImageViewCreateInfo { SType = StructureType.ImageViewCreateInfo, Image = storage.GetImageForViewCreation(), @@ -122,7 +122,7 @@ namespace Ryujinx.Graphics.Vulkan PNext = &imageViewUsage, }; - gd.Api.CreateImageView(device, in imageCreateInfo, null, out var imageView).ThrowOnError(); + gd.Api.CreateImageView(device, in imageCreateInfo, null, out ImageView imageView).ThrowOnError(); return new Auto(new DisposableImageView(gd.Api, device, imageView), null, storage.GetImage()); } @@ -136,7 +136,7 @@ namespace Ryujinx.Graphics.Vulkan _imageView = CreateImageView(componentMapping, subresourceRange, type, shaderUsage); // Framebuffer attachments and storage images requires a identity component mapping. - var identityComponentMapping = new ComponentMapping( + ComponentMapping identityComponentMapping = new ComponentMapping( ComponentSwizzle.R, ComponentSwizzle.G, ComponentSwizzle.B, @@ -210,8 +210,8 @@ namespace Ryujinx.Graphics.Vulkan public void CopyTo(ITexture destination, int firstLayer, int firstLevel) { - var src = this; - var dst = (TextureView)destination; + TextureView src = this; + TextureView dst = (TextureView)destination; if (!Valid || !dst.Valid) { @@ -220,10 +220,10 @@ namespace Ryujinx.Graphics.Vulkan _gd.PipelineInternal.EndRenderPass(); - var cbs = _gd.PipelineInternal.CurrentCommandBuffer; + CommandBufferScoped cbs = _gd.PipelineInternal.CurrentCommandBuffer; - var srcImage = src.GetImage().Get(cbs).Value; - var dstImage = dst.GetImage().Get(cbs).Value; + Image srcImage = src.GetImage().Get(cbs).Value; + Image dstImage = dst.GetImage().Get(cbs).Value; if (!dst.Info.Target.IsMultisample() && Info.Target.IsMultisample()) { @@ -270,8 +270,8 @@ namespace Ryujinx.Graphics.Vulkan public void CopyTo(ITexture destination, int srcLayer, int dstLayer, int srcLevel, int dstLevel) { - var src = this; - var dst = (TextureView)destination; + TextureView src = this; + TextureView dst = (TextureView)destination; if (!Valid || !dst.Valid) { @@ -280,10 +280,10 @@ namespace Ryujinx.Graphics.Vulkan _gd.PipelineInternal.EndRenderPass(); - var cbs = _gd.PipelineInternal.CurrentCommandBuffer; + CommandBufferScoped cbs = _gd.PipelineInternal.CurrentCommandBuffer; - var srcImage = src.GetImage().Get(cbs).Value; - var dstImage = dst.GetImage().Get(cbs).Value; + Image srcImage = src.GetImage().Get(cbs).Value; + Image dstImage = dst.GetImage().Get(cbs).Value; if (!dst.Info.Target.IsMultisample() && Info.Target.IsMultisample()) { @@ -325,21 +325,21 @@ namespace Ryujinx.Graphics.Vulkan public void CopyTo(ITexture destination, Extents2D srcRegion, Extents2D dstRegion, bool linearFilter) { - var dst = (TextureView)destination; + TextureView dst = (TextureView)destination; if (_gd.CommandBufferPool.OwnedByCurrentThread) { _gd.PipelineInternal.EndRenderPass(); - var cbs = _gd.PipelineInternal.CurrentCommandBuffer; + CommandBufferScoped cbs = _gd.PipelineInternal.CurrentCommandBuffer; CopyToImpl(cbs, dst, srcRegion, dstRegion, linearFilter); } else { - var cbp = _gd.BackgroundResources.Get().GetPool(); + CommandBufferPool cbp = _gd.BackgroundResources.Get().GetPool(); - using var cbs = cbp.Rent(); + using CommandBufferScoped cbs = cbp.Rent(); CopyToImpl(cbs, dst, srcRegion, dstRegion, linearFilter); } @@ -347,10 +347,10 @@ namespace Ryujinx.Graphics.Vulkan private void CopyToImpl(CommandBufferScoped cbs, TextureView dst, Extents2D srcRegion, Extents2D dstRegion, bool linearFilter) { - var src = this; + TextureView src = this; - var srcFormat = GetCompatibleGalFormat(src.Info.Format); - var dstFormat = GetCompatibleGalFormat(dst.Info.Format); + Format srcFormat = GetCompatibleGalFormat(src.Info.Format); + Format dstFormat = GetCompatibleGalFormat(dst.Info.Format); bool srcUsesStorageFormat = src.VkFormat == src.Storage.VkFormat; bool dstUsesStorageFormat = dst.VkFormat == dst.Storage.VkFormat; @@ -572,7 +572,7 @@ namespace Ryujinx.Graphics.Vulkan return this; } - if (_selfManagedViews != null && _selfManagedViews.TryGetValue(format, out var view)) + if (_selfManagedViews != null && _selfManagedViews.TryGetValue(format, out TextureView view)) { return view; } @@ -612,12 +612,12 @@ namespace Ryujinx.Graphics.Vulkan public byte[] GetData(int x, int y, int width, int height) { int size = width * height * Info.BytesPerPixel; - using var bufferHolder = _gd.BufferManager.Create(_gd, size); + using BufferHolder bufferHolder = _gd.BufferManager.Create(_gd, size); - using (var cbs = _gd.CommandBufferPool.Rent()) + using (CommandBufferScoped cbs = _gd.CommandBufferPool.Rent()) { - var buffer = bufferHolder.GetBuffer(cbs.CommandBuffer).Get(cbs).Value; - var image = GetImage().Get(cbs).Value; + VkBuffer buffer = bufferHolder.GetBuffer(cbs.CommandBuffer).Get(cbs).Value; + Image image = GetImage().Get(cbs).Value; CopyFromOrToBuffer(cbs.CommandBuffer, buffer, image, size, true, 0, 0, x, y, width, height); } @@ -659,12 +659,12 @@ namespace Ryujinx.Graphics.Vulkan public void CopyTo(BufferRange range, int layer, int level, int stride) { _gd.PipelineInternal.EndRenderPass(); - var cbs = _gd.PipelineInternal.CurrentCommandBuffer; + CommandBufferScoped cbs = _gd.PipelineInternal.CurrentCommandBuffer; int outSize = Info.GetMipSize(level); int hostSize = GetBufferDataLength(outSize); - var image = GetImage().Get(cbs).Value; + Image image = GetImage().Get(cbs).Value; int offset = range.Offset; Auto autoBuffer = _gd.BufferManager.GetBuffer(cbs.CommandBuffer, range.Handle, true); @@ -773,7 +773,7 @@ namespace Ryujinx.Graphics.Vulkan { int bufferDataLength = GetBufferDataLength(data.Length); - using var bufferHolder = _gd.BufferManager.Create(_gd, bufferDataLength); + using BufferHolder bufferHolder = _gd.BufferManager.Create(_gd, bufferDataLength); Auto imageAuto = GetImage(); @@ -781,7 +781,7 @@ namespace Ryujinx.Graphics.Vulkan bool loadInline = Storage.HasCommandBufferDependency(_gd.PipelineInternal.CurrentCommandBuffer); - var cbs = loadInline ? _gd.PipelineInternal.CurrentCommandBuffer : _gd.PipelineInternal.GetPreloadCommandBuffer(); + CommandBufferScoped cbs = loadInline ? _gd.PipelineInternal.CurrentCommandBuffer : _gd.PipelineInternal.GetPreloadCommandBuffer(); if (loadInline) { @@ -790,8 +790,8 @@ namespace Ryujinx.Graphics.Vulkan CopyDataToBuffer(bufferHolder.GetDataStorage(0, bufferDataLength), data); - var buffer = bufferHolder.GetBuffer(cbs.CommandBuffer).Get(cbs).Value; - var image = imageAuto.Get(cbs).Value; + VkBuffer buffer = bufferHolder.GetBuffer(cbs.CommandBuffer).Get(cbs).Value; + Image image = imageAuto.Get(cbs).Value; if (region.HasValue) { @@ -927,24 +927,24 @@ namespace Ryujinx.Graphics.Vulkan int rowLength = ((stride == 0 ? Info.GetMipStride(dstLevel + level) : stride) / Info.BytesPerPixel) * Info.BlockWidth; - var aspectFlags = Info.Format.ConvertAspectFlags(); + ImageAspectFlags aspectFlags = Info.Format.ConvertAspectFlags(); if (aspectFlags == (ImageAspectFlags.DepthBit | ImageAspectFlags.StencilBit)) { aspectFlags = ImageAspectFlags.DepthBit; } - var sl = new ImageSubresourceLayers( + ImageSubresourceLayers sl = new ImageSubresourceLayers( aspectFlags, (uint)(FirstLevel + dstLevel + level), (uint)(FirstLayer + layer), (uint)layers); - var extent = new Extent3D((uint)width, (uint)height, (uint)depth); + Extent3D extent = new Extent3D((uint)width, (uint)height, (uint)depth); int z = is3D ? dstLayer : 0; - var region = new BufferImageCopy( + BufferImageCopy region = new BufferImageCopy( (ulong)offset, (uint)AlignUpNpot(rowLength, Info.BlockWidth), (uint)AlignUpNpot(height, Info.BlockHeight), @@ -986,16 +986,16 @@ namespace Ryujinx.Graphics.Vulkan int width, int height) { - var aspectFlags = Info.Format.ConvertAspectFlags(); + ImageAspectFlags aspectFlags = Info.Format.ConvertAspectFlags(); if (aspectFlags == (ImageAspectFlags.DepthBit | ImageAspectFlags.StencilBit)) { aspectFlags = ImageAspectFlags.DepthBit; } - var sl = new ImageSubresourceLayers(aspectFlags, (uint)(FirstLevel + dstLevel), (uint)(FirstLayer + dstLayer), 1); + ImageSubresourceLayers sl = new ImageSubresourceLayers(aspectFlags, (uint)(FirstLevel + dstLevel), (uint)(FirstLayer + dstLayer), 1); - var extent = new Extent3D((uint)width, (uint)height, 1); + Extent3D extent = new Extent3D((uint)width, (uint)height, 1); int rowLengthAlignment = Info.BlockWidth; @@ -1005,7 +1005,7 @@ namespace Ryujinx.Graphics.Vulkan rowLengthAlignment = 4 / Info.BytesPerPixel; } - var region = new BufferImageCopy( + BufferImageCopy region = new BufferImageCopy( 0, (uint)AlignUpNpot(width, rowLengthAlignment), (uint)AlignUpNpot(height, Info.BlockHeight), @@ -1073,7 +1073,7 @@ namespace Ryujinx.Graphics.Vulkan CommandBufferScoped cbs, FramebufferParams fb) { - var key = fb.GetRenderPassCacheKey(); + RenderPassCacheKey key = fb.GetRenderPassCacheKey(); if (_renderPasses == null || !_renderPasses.TryGetValue(ref key, out RenderPassHolder rpHolder)) { @@ -1121,9 +1121,9 @@ namespace Ryujinx.Graphics.Vulkan if (_renderPasses != null) { - var renderPasses = _renderPasses.Values.ToArray(); + RenderPassHolder[] renderPasses = _renderPasses.Values.ToArray(); - foreach (var pass in renderPasses) + foreach (RenderPassHolder pass in renderPasses) { pass.Dispose(); } @@ -1131,7 +1131,7 @@ namespace Ryujinx.Graphics.Vulkan if (_selfManagedViews != null) { - foreach (var view in _selfManagedViews.Values) + foreach (TextureView view in _selfManagedViews.Values) { view.Dispose(); } diff --git a/src/Ryujinx.Graphics.Vulkan/VertexBufferState.cs b/src/Ryujinx.Graphics.Vulkan/VertexBufferState.cs index ce1293589..236ab8721 100644 --- a/src/Ryujinx.Graphics.Vulkan/VertexBufferState.cs +++ b/src/Ryujinx.Graphics.Vulkan/VertexBufferState.cs @@ -1,4 +1,5 @@ using Ryujinx.Graphics.GAL; +using Silk.NET.Vulkan; namespace Ryujinx.Graphics.Vulkan { @@ -50,7 +51,7 @@ namespace Ryujinx.Graphics.Vulkan public void BindVertexBuffer(VulkanRenderer gd, CommandBufferScoped cbs, uint binding, ref PipelineState state, VertexBufferUpdater updater) { - var autoBuffer = _buffer; + Auto autoBuffer = _buffer; if (_handle != BufferHandle.Null) { @@ -67,7 +68,7 @@ namespace Ryujinx.Graphics.Vulkan int stride = (_stride + (alignment - 1)) & -alignment; int newSize = (_size / _stride) * stride; - var buffer = autoBuffer.Get(cbs, 0, newSize).Value; + Buffer buffer = autoBuffer.Get(cbs, 0, newSize).Value; updater.BindVertexBuffer(cbs, binding, buffer, 0, (ulong)newSize, (ulong)stride); @@ -94,7 +95,7 @@ namespace Ryujinx.Graphics.Vulkan { int offset = _offset; bool mirrorable = _size <= VertexBufferMaxMirrorable; - var buffer = mirrorable ? autoBuffer.GetMirrorable(cbs, ref offset, _size, out _).Value : autoBuffer.Get(cbs, offset, _size).Value; + Buffer buffer = mirrorable ? autoBuffer.GetMirrorable(cbs, ref offset, _size, out _).Value : autoBuffer.Get(cbs, offset, _size).Value; updater.BindVertexBuffer(cbs, binding, buffer, (ulong)offset, (ulong)_size, (ulong)_stride); } diff --git a/src/Ryujinx.Graphics.Vulkan/VulkanDebugMessenger.cs b/src/Ryujinx.Graphics.Vulkan/VulkanDebugMessenger.cs index 6dfcd8b6e..0e48e0200 100644 --- a/src/Ryujinx.Graphics.Vulkan/VulkanDebugMessenger.cs +++ b/src/Ryujinx.Graphics.Vulkan/VulkanDebugMessenger.cs @@ -39,7 +39,7 @@ namespace Ryujinx.Graphics.Vulkan if (_debugUtils != null && _logLevel != GraphicsDebugLevel.None) { - var messageType = _logLevel switch + DebugUtilsMessageTypeFlagsEXT messageType = _logLevel switch { GraphicsDebugLevel.Error => DebugUtilsMessageTypeFlagsEXT.ValidationBitExt, GraphicsDebugLevel.Slowdowns => DebugUtilsMessageTypeFlagsEXT.ValidationBitExt | @@ -50,7 +50,7 @@ namespace Ryujinx.Graphics.Vulkan _ => throw new ArgumentException($"Invalid log level \"{_logLevel}\"."), }; - var messageSeverity = _logLevel switch + DebugUtilsMessageSeverityFlagsEXT messageSeverity = _logLevel switch { GraphicsDebugLevel.Error => DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt, GraphicsDebugLevel.Slowdowns => DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt | @@ -62,7 +62,7 @@ namespace Ryujinx.Graphics.Vulkan _ => throw new ArgumentException($"Invalid log level \"{_logLevel}\"."), }; - var debugUtilsMessengerCreateInfo = new DebugUtilsMessengerCreateInfoEXT + DebugUtilsMessengerCreateInfoEXT debugUtilsMessengerCreateInfo = new DebugUtilsMessengerCreateInfoEXT { SType = StructureType.DebugUtilsMessengerCreateInfoExt, MessageType = messageType, @@ -95,7 +95,7 @@ namespace Ryujinx.Graphics.Vulkan DebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData) { - var msg = Marshal.PtrToStringAnsi((nint)pCallbackData->PMessage); + string msg = Marshal.PtrToStringAnsi((nint)pCallbackData->PMessage); if (messageSeverity.HasFlag(DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt)) { diff --git a/src/Ryujinx.Graphics.Vulkan/VulkanInitialization.cs b/src/Ryujinx.Graphics.Vulkan/VulkanInitialization.cs index 352f271cc..83450bc0a 100644 --- a/src/Ryujinx.Graphics.Vulkan/VulkanInitialization.cs +++ b/src/Ryujinx.Graphics.Vulkan/VulkanInitialization.cs @@ -1,6 +1,7 @@ using Ryujinx.Common.Configuration; using Ryujinx.Common.Logging; using Ryujinx.Graphics.GAL; +using Silk.NET.Core; using Silk.NET.Vulkan; using Silk.NET.Vulkan.Extensions.EXT; using Silk.NET.Vulkan.Extensions.KHR; @@ -54,10 +55,10 @@ namespace Ryujinx.Graphics.Vulkan internal static VulkanInstance CreateInstance(Vk api, GraphicsDebugLevel logLevel, string[] requiredExtensions) { - var enabledLayers = new List(); + List enabledLayers = new List(); - var instanceExtensions = VulkanInstance.GetInstanceExtensions(api); - var instanceLayers = VulkanInstance.GetInstanceLayers(api); + IReadOnlySet instanceExtensions = VulkanInstance.GetInstanceExtensions(api); + IReadOnlySet instanceLayers = VulkanInstance.GetInstanceLayers(api); void AddAvailableLayer(string layerName) { @@ -76,16 +77,16 @@ namespace Ryujinx.Graphics.Vulkan AddAvailableLayer("VK_LAYER_KHRONOS_validation"); } - var enabledExtensions = requiredExtensions; + string[] enabledExtensions = requiredExtensions; if (instanceExtensions.Contains("VK_EXT_debug_utils")) { enabledExtensions = enabledExtensions.Append(ExtDebugUtils.ExtensionName).ToArray(); } - var appName = Marshal.StringToHGlobalAnsi(AppName); + IntPtr appName = Marshal.StringToHGlobalAnsi(AppName); - var applicationInfo = new ApplicationInfo + ApplicationInfo applicationInfo = new ApplicationInfo { PApplicationName = (byte*)appName, ApplicationVersion = 1, @@ -107,7 +108,7 @@ namespace Ryujinx.Graphics.Vulkan ppEnabledLayers[i] = Marshal.StringToHGlobalAnsi(enabledLayers[i]); } - var instanceCreateInfo = new InstanceCreateInfo + InstanceCreateInfo instanceCreateInfo = new InstanceCreateInfo { SType = StructureType.InstanceCreateInfo, PApplicationInfo = &applicationInfo, @@ -117,7 +118,7 @@ namespace Ryujinx.Graphics.Vulkan EnabledLayerCount = (uint)enabledLayers.Count, }; - Result result = VulkanInstance.Create(api, ref instanceCreateInfo, out var instance); + Result result = VulkanInstance.Create(api, ref instanceCreateInfo, out VulkanInstance instance); Marshal.FreeHGlobal(appName); @@ -138,7 +139,7 @@ namespace Ryujinx.Graphics.Vulkan internal static VulkanPhysicalDevice FindSuitablePhysicalDevice(Vk api, VulkanInstance instance, SurfaceKHR surface, string preferredGpuId) { - instance.EnumeratePhysicalDevices(out var physicalDevices).ThrowOnError(); + instance.EnumeratePhysicalDevices(out VulkanPhysicalDevice[] physicalDevices).ThrowOnError(); // First we try to pick the user preferred GPU. for (int i = 0; i < physicalDevices.Length; i++) @@ -163,9 +164,9 @@ namespace Ryujinx.Graphics.Vulkan internal static DeviceInfo[] GetSuitablePhysicalDevices(Vk api) { - var appName = Marshal.StringToHGlobalAnsi(AppName); + IntPtr appName = Marshal.StringToHGlobalAnsi(AppName); - var applicationInfo = new ApplicationInfo + ApplicationInfo applicationInfo = new ApplicationInfo { PApplicationName = (byte*)appName, ApplicationVersion = 1, @@ -174,7 +175,7 @@ namespace Ryujinx.Graphics.Vulkan ApiVersion = _maximumVulkanVersion, }; - var instanceCreateInfo = new InstanceCreateInfo + InstanceCreateInfo instanceCreateInfo = new InstanceCreateInfo { SType = StructureType.InstanceCreateInfo, PApplicationInfo = &applicationInfo, @@ -184,7 +185,7 @@ namespace Ryujinx.Graphics.Vulkan EnabledLayerCount = 0, }; - Result result = VulkanInstance.Create(api, ref instanceCreateInfo, out var rawInstance); + Result result = VulkanInstance.Create(api, ref instanceCreateInfo, out VulkanInstance rawInstance); Marshal.FreeHGlobal(appName); @@ -245,13 +246,13 @@ namespace Ryujinx.Graphics.Vulkan { const QueueFlags RequiredFlags = QueueFlags.GraphicsBit | QueueFlags.ComputeBit; - var khrSurface = new KhrSurface(api.Context); + KhrSurface khrSurface = new KhrSurface(api.Context); for (uint index = 0; index < physicalDevice.QueueFamilyProperties.Length; index++) { ref QueueFamilyProperties property = ref physicalDevice.QueueFamilyProperties[index]; - khrSurface.GetPhysicalDeviceSurfaceSupport(physicalDevice.PhysicalDevice, index, surface, out var surfaceSupported).ThrowOnError(); + khrSurface.GetPhysicalDeviceSurfaceSupport(physicalDevice.PhysicalDevice, index, surface, out Bool32 surfaceSupported).ThrowOnError(); if (property.QueueFlags.HasFlag(RequiredFlags) && surfaceSupported) { @@ -280,7 +281,7 @@ namespace Ryujinx.Graphics.Vulkan queuePriorities[i] = 1f; } - var queueCreateInfo = new DeviceQueueCreateInfo + DeviceQueueCreateInfo queueCreateInfo = new DeviceQueueCreateInfo { SType = StructureType.DeviceQueueCreateInfo, QueueFamilyIndex = queueFamilyIndex, @@ -391,9 +392,9 @@ namespace Ryujinx.Graphics.Vulkan api.GetPhysicalDeviceFeatures2(physicalDevice.PhysicalDevice, &features2); - var supportedFeatures = features2.Features; + PhysicalDeviceFeatures supportedFeatures = features2.Features; - var features = new PhysicalDeviceFeatures + PhysicalDeviceFeatures features = new PhysicalDeviceFeatures { DepthBiasClamp = supportedFeatures.DepthBiasClamp, DepthClamp = supportedFeatures.DepthClamp, @@ -464,7 +465,7 @@ namespace Ryujinx.Graphics.Vulkan pExtendedFeatures = &featuresRobustness2; } - var featuresExtendedDynamicState = new PhysicalDeviceExtendedDynamicStateFeaturesEXT + PhysicalDeviceExtendedDynamicStateFeaturesEXT featuresExtendedDynamicState = new PhysicalDeviceExtendedDynamicStateFeaturesEXT { SType = StructureType.PhysicalDeviceExtendedDynamicStateFeaturesExt, PNext = pExtendedFeatures, @@ -473,7 +474,7 @@ namespace Ryujinx.Graphics.Vulkan pExtendedFeatures = &featuresExtendedDynamicState; - var featuresVk11 = new PhysicalDeviceVulkan11Features + PhysicalDeviceVulkan11Features featuresVk11 = new PhysicalDeviceVulkan11Features { SType = StructureType.PhysicalDeviceVulkan11Features, PNext = pExtendedFeatures, @@ -482,7 +483,7 @@ namespace Ryujinx.Graphics.Vulkan pExtendedFeatures = &featuresVk11; - var featuresVk12 = new PhysicalDeviceVulkan12Features + PhysicalDeviceVulkan12Features featuresVk12 = new PhysicalDeviceVulkan12Features { SType = StructureType.PhysicalDeviceVulkan12Features, PNext = pExtendedFeatures, @@ -585,7 +586,7 @@ namespace Ryujinx.Graphics.Vulkan pExtendedFeatures = &featuresDynamicAttachmentFeedbackLoopLayout; } - var enabledExtensions = _requiredExtensions.Union(_desirableExtensions.Intersect(physicalDevice.DeviceExtensions)).ToArray(); + string[] enabledExtensions = _requiredExtensions.Union(_desirableExtensions.Intersect(physicalDevice.DeviceExtensions)).ToArray(); nint* ppEnabledExtensions = stackalloc nint[enabledExtensions.Length]; @@ -594,7 +595,7 @@ namespace Ryujinx.Graphics.Vulkan ppEnabledExtensions[i] = Marshal.StringToHGlobalAnsi(enabledExtensions[i]); } - var deviceCreateInfo = new DeviceCreateInfo + DeviceCreateInfo deviceCreateInfo = new DeviceCreateInfo { SType = StructureType.DeviceCreateInfo, PNext = pExtendedFeatures, @@ -605,7 +606,7 @@ namespace Ryujinx.Graphics.Vulkan PEnabledFeatures = &features, }; - api.CreateDevice(physicalDevice.PhysicalDevice, in deviceCreateInfo, null, out var device).ThrowOnError(); + api.CreateDevice(physicalDevice.PhysicalDevice, in deviceCreateInfo, null, out Device device).ThrowOnError(); for (int i = 0; i < enabledExtensions.Length; i++) { diff --git a/src/Ryujinx.Graphics.Vulkan/VulkanPhysicalDevice.cs b/src/Ryujinx.Graphics.Vulkan/VulkanPhysicalDevice.cs index b3f8fd756..8ede84100 100644 --- a/src/Ryujinx.Graphics.Vulkan/VulkanPhysicalDevice.cs +++ b/src/Ryujinx.Graphics.Vulkan/VulkanPhysicalDevice.cs @@ -24,7 +24,7 @@ namespace Ryujinx.Graphics.Vulkan PhysicalDevice = physicalDevice; PhysicalDeviceFeatures = api.GetPhysicalDeviceFeature(PhysicalDevice); - api.GetPhysicalDeviceProperties(PhysicalDevice, out var physicalDeviceProperties); + api.GetPhysicalDeviceProperties(PhysicalDevice, out PhysicalDeviceProperties physicalDeviceProperties); PhysicalDeviceProperties = physicalDeviceProperties; api.GetPhysicalDeviceMemoryProperties(PhysicalDevice, out PhysicalDeviceMemoryProperties); diff --git a/src/Ryujinx.Graphics.Vulkan/VulkanRenderer.cs b/src/Ryujinx.Graphics.Vulkan/VulkanRenderer.cs index a4fcf5353..d164c5cb6 100644 --- a/src/Ryujinx.Graphics.Vulkan/VulkanRenderer.cs +++ b/src/Ryujinx.Graphics.Vulkan/VulkanRenderer.cs @@ -12,6 +12,7 @@ using Silk.NET.Vulkan.Extensions.KHR; using System; using System.Collections.Generic; using System.Runtime.InteropServices; +using System.Text.RegularExpressions; using System.Threading; using Format = Ryujinx.Graphics.GAL.Format; using PrimitiveTopology = Ryujinx.Graphics.GAL.PrimitiveTopology; @@ -163,7 +164,7 @@ namespace Ryujinx.Graphics.Vulkan if (maxQueueCount >= 2) { - Api.GetDeviceQueue(_device, queueFamilyIndex, 1, out var backgroundQueue); + Api.GetDeviceQueue(_device, queueFamilyIndex, 1, out Queue backgroundQueue); BackgroundQueue = backgroundQueue; BackgroundQueueLock = new(); } @@ -331,7 +332,7 @@ namespace Ryujinx.Graphics.Vulkan Api.GetPhysicalDeviceProperties2(_physicalDevice.PhysicalDevice, &properties2); Api.GetPhysicalDeviceFeatures2(_physicalDevice.PhysicalDevice, &features2); - var portabilityFlags = PortabilitySubsetFlags.None; + PortabilitySubsetFlags portabilityFlags = PortabilitySubsetFlags.None; uint vertexBufferAlignment = 1; if (usePortability) @@ -348,9 +349,9 @@ namespace Ryujinx.Graphics.Vulkan featuresCustomBorderColor.CustomBorderColors && featuresCustomBorderColor.CustomBorderColorWithoutFormat; - ref var properties = ref properties2.Properties; + ref PhysicalDeviceProperties properties = ref properties2.Properties; - var hasDriverProperties = _physicalDevice.TryGetPhysicalDeviceDriverPropertiesKHR(Api, out var driverProperties); + bool hasDriverProperties = _physicalDevice.TryGetPhysicalDeviceDriverPropertiesKHR(Api, out PhysicalDeviceDriverPropertiesKHR driverProperties); Vendor = VendorUtils.FromId(properties.VendorID); @@ -378,7 +379,7 @@ namespace Ryujinx.Graphics.Vulkan if (Vendor == Vendor.Nvidia) { - var match = VendorUtils.NvidiaConsumerClassRegex().Match(GpuRenderer); + Match match = VendorUtils.NvidiaConsumerClassRegex().Match(GpuRenderer); if (match != null && int.TryParse(match.Groups[2].Value, out int gpuNumber)) { @@ -487,7 +488,7 @@ namespace Ryujinx.Graphics.Vulkan _surface = _getSurface(_instance.Instance, Api); _physicalDevice = VulkanInitialization.FindSuitablePhysicalDevice(Api, _instance, _surface, _preferredGpuId); - var queueFamilyIndex = VulkanInitialization.FindSuitableQueueFamily(Api, _physicalDevice, _surface, out uint maxQueueCount); + uint queueFamilyIndex = VulkanInitialization.FindSuitableQueueFamily(Api, _physicalDevice, _surface, out uint maxQueueCount); _device = VulkanInitialization.CreateDevice(Api, _physicalDevice, queueFamilyIndex, maxQueueCount); @@ -496,7 +497,7 @@ namespace Ryujinx.Graphics.Vulkan SwapchainApi = swapchainApi; } - Api.GetDeviceQueue(_device, queueFamilyIndex, 0, out var queue); + Api.GetDeviceQueue(_device, queueFamilyIndex, 0, out Queue queue); Queue = queue; QueueLock = new(); @@ -590,7 +591,7 @@ namespace Ryujinx.Graphics.Vulkan internal TextureView CreateTextureView(TextureCreateInfo info) { // This should be disposed when all views are destroyed. - var storage = CreateTextureStorage(info); + TextureStorage storage = CreateTextureStorage(info); return storage.CreateView(info, 0, 0); } @@ -713,8 +714,8 @@ namespace Ryujinx.Graphics.Vulkan Api.GetPhysicalDeviceFeatures2(_physicalDevice.PhysicalDevice, &features2); - var limits = _physicalDevice.PhysicalDeviceProperties.Limits; - var mainQueueProperties = _physicalDevice.QueueFamilyProperties[QueueFamilyIndex]; + PhysicalDeviceLimits limits = _physicalDevice.PhysicalDeviceProperties.Limits; + QueueFamilyProperties mainQueueProperties = _physicalDevice.QueueFamilyProperties[QueueFamilyIndex]; SystemMemoryType memoryType; @@ -801,7 +802,7 @@ namespace Ryujinx.Graphics.Vulkan for (int i = 0; i < memoryProperties.MemoryHeapCount; i++) { - var heap = memoryProperties.MemoryHeaps[i]; + MemoryHeap heap = memoryProperties.MemoryHeaps[i]; if ((heap.Flags & MemoryHeapFlags.DeviceLocalBit) == MemoryHeapFlags.DeviceLocalBit) { totalMemory += heap.Size; @@ -1030,17 +1031,17 @@ namespace Ryujinx.Graphics.Vulkan MemoryAllocator.Dispose(); - foreach (var shader in Shaders) + foreach (ShaderCollection shader in Shaders) { shader.Dispose(); } - foreach (var texture in Textures) + foreach (ITexture texture in Textures) { texture.Release(); } - foreach (var sampler in Samplers) + foreach (SamplerHolder sampler in Samplers) { sampler.Dispose(); } diff --git a/src/Ryujinx.Graphics.Vulkan/Window.cs b/src/Ryujinx.Graphics.Vulkan/Window.cs index 8e53e7f7e..b45d59c3a 100644 --- a/src/Ryujinx.Graphics.Vulkan/Window.cs +++ b/src/Ryujinx.Graphics.Vulkan/Window.cs @@ -55,7 +55,7 @@ namespace Ryujinx.Graphics.Vulkan private void RecreateSwapchain() { - var oldSwapchain = _swapchain; + SwapchainKHR oldSwapchain = _swapchain; _swapchainIsDirty = false; for (int i = 0; i < _swapchainImageViews.Length; i++) @@ -87,13 +87,13 @@ namespace Ryujinx.Graphics.Vulkan private unsafe void CreateSwapchain() { - _gd.SurfaceApi.GetPhysicalDeviceSurfaceCapabilities(_physicalDevice, _surface, out var capabilities); + _gd.SurfaceApi.GetPhysicalDeviceSurfaceCapabilities(_physicalDevice, _surface, out SurfaceCapabilitiesKHR capabilities); uint surfaceFormatsCount; _gd.SurfaceApi.GetPhysicalDeviceSurfaceFormats(_physicalDevice, _surface, &surfaceFormatsCount, null); - var surfaceFormats = new SurfaceFormatKHR[surfaceFormatsCount]; + SurfaceFormatKHR[] surfaceFormats = new SurfaceFormatKHR[surfaceFormatsCount]; fixed (SurfaceFormatKHR* pSurfaceFormats = surfaceFormats) { @@ -104,7 +104,7 @@ namespace Ryujinx.Graphics.Vulkan _gd.SurfaceApi.GetPhysicalDeviceSurfacePresentModes(_physicalDevice, _surface, &presentModesCount, null); - var presentModes = new PresentModeKHR[presentModesCount]; + PresentModeKHR[] presentModes = new PresentModeKHR[presentModesCount]; fixed (PresentModeKHR* pPresentModes = presentModes) { @@ -117,17 +117,17 @@ namespace Ryujinx.Graphics.Vulkan imageCount = capabilities.MaxImageCount; } - var surfaceFormat = ChooseSwapSurfaceFormat(surfaceFormats, _colorSpacePassthroughEnabled); + SurfaceFormatKHR surfaceFormat = ChooseSwapSurfaceFormat(surfaceFormats, _colorSpacePassthroughEnabled); - var extent = ChooseSwapExtent(capabilities); + Extent2D extent = ChooseSwapExtent(capabilities); _width = (int)extent.Width; _height = (int)extent.Height; _format = surfaceFormat.Format; - var oldSwapchain = _swapchain; + SwapchainKHR oldSwapchain = _swapchain; - var swapchainCreateInfo = new SwapchainCreateInfoKHR + SwapchainCreateInfoKHR swapchainCreateInfo = new SwapchainCreateInfoKHR { SType = StructureType.SwapchainCreateInfoKhr, Surface = _surface, @@ -144,7 +144,7 @@ namespace Ryujinx.Graphics.Vulkan Clipped = true, }; - var textureCreateInfo = new TextureCreateInfo( + TextureCreateInfo textureCreateInfo = new TextureCreateInfo( _width, _height, 1, @@ -179,7 +179,7 @@ namespace Ryujinx.Graphics.Vulkan _swapchainImageViews[i] = CreateSwapchainImageView(_swapchainImages[i], surfaceFormat.Format, textureCreateInfo); } - var semaphoreCreateInfo = new SemaphoreCreateInfo + SemaphoreCreateInfo semaphoreCreateInfo = new SemaphoreCreateInfo { SType = StructureType.SemaphoreCreateInfo, }; @@ -201,17 +201,17 @@ namespace Ryujinx.Graphics.Vulkan private unsafe TextureView CreateSwapchainImageView(Image swapchainImage, VkFormat format, TextureCreateInfo info) { - var componentMapping = new ComponentMapping( + ComponentMapping componentMapping = new ComponentMapping( ComponentSwizzle.R, ComponentSwizzle.G, ComponentSwizzle.B, ComponentSwizzle.A); - var aspectFlags = ImageAspectFlags.ColorBit; + ImageAspectFlags aspectFlags = ImageAspectFlags.ColorBit; - var subresourceRange = new ImageSubresourceRange(aspectFlags, 0, 1, 0, 1); + ImageSubresourceRange subresourceRange = new ImageSubresourceRange(aspectFlags, 0, 1, 0, 1); - var imageCreateInfo = new ImageViewCreateInfo + ImageViewCreateInfo imageCreateInfo = new ImageViewCreateInfo { SType = StructureType.ImageViewCreateInfo, Image = swapchainImage, @@ -221,7 +221,7 @@ namespace Ryujinx.Graphics.Vulkan SubresourceRange = subresourceRange, }; - _gd.Api.CreateImageView(_device, in imageCreateInfo, null, out var imageView).ThrowOnError(); + _gd.Api.CreateImageView(_device, in imageCreateInfo, null, out ImageView imageView).ThrowOnError(); return new TextureView(_gd, _device, new DisposableImageView(_gd.Api, _device, imageView), info, format); } @@ -233,10 +233,10 @@ namespace Ryujinx.Graphics.Vulkan return new SurfaceFormatKHR(VkFormat.B8G8R8A8Unorm, ColorSpaceKHR.PaceSrgbNonlinearKhr); } - var formatToReturn = availableFormats[0]; + SurfaceFormatKHR formatToReturn = availableFormats[0]; if (colorSpacePassthroughEnabled) { - foreach (var format in availableFormats) + foreach (SurfaceFormatKHR format in availableFormats) { if (format.Format == VkFormat.B8G8R8A8Unorm && format.ColorSpace == ColorSpaceKHR.SpacePassThroughExt) { @@ -251,7 +251,7 @@ namespace Ryujinx.Graphics.Vulkan } else { - foreach (var format in availableFormats) + foreach (SurfaceFormatKHR format in availableFormats) { if (format.Format == VkFormat.B8G8R8A8Unorm && format.ColorSpace == ColorSpaceKHR.PaceSrgbNonlinearKhr) { @@ -318,7 +318,7 @@ namespace Ryujinx.Graphics.Vulkan while (true) { - var acquireResult = _gd.SwapchainApi.AcquireNextImage( + Result acquireResult = _gd.SwapchainApi.AcquireNextImage( _device, _swapchain, ulong.MaxValue, @@ -340,11 +340,11 @@ namespace Ryujinx.Graphics.Vulkan } } - var swapchainImage = _swapchainImages[nextImage]; + Image swapchainImage = _swapchainImages[nextImage]; _gd.FlushAllCommands(); - var cbs = _gd.CommandBufferPool.Rent(); + CommandBufferScoped cbs = _gd.CommandBufferPool.Rent(); Transition( cbs.CommandBuffer, @@ -354,7 +354,7 @@ namespace Ryujinx.Graphics.Vulkan ImageLayout.Undefined, ImageLayout.General); - var view = (TextureView)texture; + TextureView view = (TextureView)texture; UpdateEffect(); @@ -462,12 +462,12 @@ namespace Ryujinx.Graphics.Vulkan stackalloc[] { _renderFinishedSemaphores[semaphoreIndex] }); // TODO: Present queue. - var semaphore = _renderFinishedSemaphores[semaphoreIndex]; - var swapchain = _swapchain; + Semaphore semaphore = _renderFinishedSemaphores[semaphoreIndex]; + SwapchainKHR swapchain = _swapchain; Result result; - var presentInfo = new PresentInfoKHR + PresentInfoKHR presentInfo = new PresentInfoKHR { SType = StructureType.PresentInfoKhr, WaitSemaphoreCount = 1, @@ -534,7 +534,7 @@ namespace Ryujinx.Graphics.Vulkan case AntiAliasing.SmaaMedium: case AntiAliasing.SmaaHigh: case AntiAliasing.SmaaUltra: - var quality = _currentAntiAliasing - AntiAliasing.SmaaLow; + int quality = _currentAntiAliasing - AntiAliasing.SmaaLow; if (_effect is SmaaPostProcessingEffect smaa) { smaa.Quality = quality; @@ -594,9 +594,9 @@ namespace Ryujinx.Graphics.Vulkan ImageLayout srcLayout, ImageLayout dstLayout) { - var subresourceRange = new ImageSubresourceRange(ImageAspectFlags.ColorBit, 0, 1, 0, 1); + ImageSubresourceRange subresourceRange = new ImageSubresourceRange(ImageAspectFlags.ColorBit, 0, 1, 0, 1); - var barrier = new ImageMemoryBarrier + ImageMemoryBarrier barrier = new ImageMemoryBarrier { SType = StructureType.ImageMemoryBarrier, SrcAccessMask = srcAccess, From 58c1ab79893a95a4c76c6fcd76cc96f6e90061c3 Mon Sep 17 00:00:00 2001 From: Evan Husted Date: Sat, 25 Jan 2025 14:12:37 -0600 Subject: [PATCH 15/19] misc: chore: Use explicit types in OpenGL project --- .../Effects/AreaScalingFilter.cs | 2 +- .../Effects/FsrScalingFilter.cs | 14 +++--- .../Effects/FxaaPostProcessingEffect.cs | 6 +-- .../Effects/ShaderHelper.cs | 4 +- .../Effects/SmaaPostProcessingEffect.cs | 49 ++++++++++--------- .../Image/FormatConverter.cs | 24 ++++----- .../Image/TextureBuffer.cs | 2 +- .../Image/TextureCopyIncompatible.cs | 4 +- .../Image/TextureView.cs | 2 +- src/Ryujinx.Graphics.OpenGL/OpenGLRenderer.cs | 3 +- src/Ryujinx.Graphics.OpenGL/Pipeline.cs | 2 +- .../Queries/Counters.cs | 4 +- src/Ryujinx.Graphics.OpenGL/VertexArray.cs | 4 +- src/Ryujinx.Graphics.OpenGL/Window.cs | 8 +-- 14 files changed, 65 insertions(+), 63 deletions(-) diff --git a/src/Ryujinx.Graphics.OpenGL/Effects/AreaScalingFilter.cs b/src/Ryujinx.Graphics.OpenGL/Effects/AreaScalingFilter.cs index 9b19f2f26..927f4cbfe 100644 --- a/src/Ryujinx.Graphics.OpenGL/Effects/AreaScalingFilter.cs +++ b/src/Ryujinx.Graphics.OpenGL/Effects/AreaScalingFilter.cs @@ -41,7 +41,7 @@ namespace Ryujinx.Graphics.OpenGL.Effects private void Initialize() { - var scalingShader = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/area_scaling.glsl"); + string scalingShader = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/area_scaling.glsl"); _scalingShaderProgram = CompileProgram(scalingShader, ShaderType.ComputeShader); diff --git a/src/Ryujinx.Graphics.OpenGL/Effects/FsrScalingFilter.cs b/src/Ryujinx.Graphics.OpenGL/Effects/FsrScalingFilter.cs index 0522e28e0..c1275eb80 100644 --- a/src/Ryujinx.Graphics.OpenGL/Effects/FsrScalingFilter.cs +++ b/src/Ryujinx.Graphics.OpenGL/Effects/FsrScalingFilter.cs @@ -57,10 +57,10 @@ namespace Ryujinx.Graphics.OpenGL.Effects private void Initialize() { - var scalingShader = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/fsr_scaling.glsl"); - var sharpeningShader = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/fsr_sharpening.glsl"); - var fsrA = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/ffx_a.h"); - var fsr1 = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/ffx_fsr1.h"); + string scalingShader = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/fsr_scaling.glsl"); + string sharpeningShader = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/fsr_sharpening.glsl"); + string fsrA = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/ffx_a.h"); + string fsr1 = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/ffx_fsr1.h"); scalingShader = scalingShader.Replace("#include \"ffx_a.h\"", fsrA); scalingShader = scalingShader.Replace("#include \"ffx_fsr1.h\"", fsr1); @@ -97,8 +97,8 @@ namespace Ryujinx.Graphics.OpenGL.Effects if (_intermediaryTexture == null || _intermediaryTexture.Info.Width != width || _intermediaryTexture.Info.Height != height) { _intermediaryTexture?.Dispose(); - var originalInfo = view.Info; - var info = new TextureCreateInfo(width, + TextureCreateInfo originalInfo = view.Info; + TextureCreateInfo info = new TextureCreateInfo(width, height, originalInfo.Depth, originalInfo.Levels, @@ -118,7 +118,7 @@ namespace Ryujinx.Graphics.OpenGL.Effects _intermediaryTexture.CreateDefaultView(); } - var textureView = _intermediaryTexture.CreateView(_intermediaryTexture.Info, 0, 0) as TextureView; + TextureView textureView = _intermediaryTexture.CreateView(_intermediaryTexture.Info, 0, 0) as TextureView; int previousProgram = GL.GetInteger(GetPName.CurrentProgram); int previousUnit = GL.GetInteger(GetPName.ActiveTexture); diff --git a/src/Ryujinx.Graphics.OpenGL/Effects/FxaaPostProcessingEffect.cs b/src/Ryujinx.Graphics.OpenGL/Effects/FxaaPostProcessingEffect.cs index 4e92efe6d..26be5b3ae 100644 --- a/src/Ryujinx.Graphics.OpenGL/Effects/FxaaPostProcessingEffect.cs +++ b/src/Ryujinx.Graphics.OpenGL/Effects/FxaaPostProcessingEffect.cs @@ -47,7 +47,7 @@ namespace Ryujinx.Graphics.OpenGL.Effects _textureStorage.CreateDefaultView(); } - var textureView = _textureStorage.CreateView(view.Info, 0, 0) as TextureView; + TextureView textureView = _textureStorage.CreateView(view.Info, 0, 0) as TextureView; int previousProgram = GL.GetInteger(GetPName.CurrentProgram); int previousUnit = GL.GetInteger(GetPName.ActiveTexture); @@ -57,8 +57,8 @@ namespace Ryujinx.Graphics.OpenGL.Effects GL.BindImageTexture(0, textureView.Handle, 0, false, 0, TextureAccess.ReadWrite, SizedInternalFormat.Rgba8); GL.UseProgram(_shaderProgram); - var dispatchX = BitUtils.DivRoundUp(view.Width, IPostProcessingEffect.LocalGroupSize); - var dispatchY = BitUtils.DivRoundUp(view.Height, IPostProcessingEffect.LocalGroupSize); + int dispatchX = BitUtils.DivRoundUp(view.Width, IPostProcessingEffect.LocalGroupSize); + int dispatchY = BitUtils.DivRoundUp(view.Height, IPostProcessingEffect.LocalGroupSize); view.Bind(0); GL.Uniform1(_inputUniform, 0); diff --git a/src/Ryujinx.Graphics.OpenGL/Effects/ShaderHelper.cs b/src/Ryujinx.Graphics.OpenGL/Effects/ShaderHelper.cs index 637b2fba8..021388f81 100644 --- a/src/Ryujinx.Graphics.OpenGL/Effects/ShaderHelper.cs +++ b/src/Ryujinx.Graphics.OpenGL/Effects/ShaderHelper.cs @@ -12,7 +12,7 @@ namespace Ryujinx.Graphics.OpenGL.Effects public static int CompileProgram(string[] shaders, ShaderType shaderType) { - var shader = GL.CreateShader(shaderType); + int shader = GL.CreateShader(shaderType); GL.ShaderSource(shader, shaders.Length, shaders, (int[])null); GL.CompileShader(shader); @@ -25,7 +25,7 @@ namespace Ryujinx.Graphics.OpenGL.Effects return 0; } - var program = GL.CreateProgram(); + int program = GL.CreateProgram(); GL.AttachShader(program, shader); GL.LinkProgram(program); diff --git a/src/Ryujinx.Graphics.OpenGL/Effects/SmaaPostProcessingEffect.cs b/src/Ryujinx.Graphics.OpenGL/Effects/SmaaPostProcessingEffect.cs index a6c5e4aca..bb320fcec 100644 --- a/src/Ryujinx.Graphics.OpenGL/Effects/SmaaPostProcessingEffect.cs +++ b/src/Ryujinx.Graphics.OpenGL/Effects/SmaaPostProcessingEffect.cs @@ -1,5 +1,6 @@ using OpenTK.Graphics.OpenGL; using Ryujinx.Common; +using Ryujinx.Common.Memory; using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.OpenGL.Image; using System; @@ -78,7 +79,7 @@ namespace Ryujinx.Graphics.OpenGL.Effects.Smaa private unsafe void RecreateShaders(int width, int height) { string baseShader = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/smaa.hlsl"); - var pixelSizeDefine = $"#define SMAA_RT_METRICS float4(1.0 / {width}.0, 1.0 / {height}.0, {width}, {height}) \n"; + string pixelSizeDefine = $"#define SMAA_RT_METRICS float4(1.0 / {width}.0, 1.0 / {height}.0, {width}, {height}) \n"; _edgeShaderPrograms = new int[_qualities.Length]; _blendShaderPrograms = new int[_qualities.Length]; @@ -86,20 +87,20 @@ namespace Ryujinx.Graphics.OpenGL.Effects.Smaa for (int i = 0; i < +_edgeShaderPrograms.Length; i++) { - var presets = $"#version 430 core \n#define {_qualities[i]} 1 \n{pixelSizeDefine}#define SMAA_GLSL_4 1 \nlayout (local_size_x = 16, local_size_y = 16) in;\n{baseShader}"; + string presets = $"#version 430 core \n#define {_qualities[i]} 1 \n{pixelSizeDefine}#define SMAA_GLSL_4 1 \nlayout (local_size_x = 16, local_size_y = 16) in;\n{baseShader}"; - var edgeShaderData = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/smaa_edge.glsl"); - var blendShaderData = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/smaa_blend.glsl"); - var neighbourShaderData = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/smaa_neighbour.glsl"); + string edgeShaderData = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/smaa_edge.glsl"); + string blendShaderData = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/smaa_blend.glsl"); + string neighbourShaderData = EmbeddedResources.ReadAllText("Ryujinx.Graphics.OpenGL/Effects/Shaders/smaa_neighbour.glsl"); - var shaders = new string[] { presets, edgeShaderData }; - var edgeProgram = ShaderHelper.CompileProgram(shaders, ShaderType.ComputeShader); + string[] shaders = new string[] { presets, edgeShaderData }; + int edgeProgram = ShaderHelper.CompileProgram(shaders, ShaderType.ComputeShader); shaders[1] = blendShaderData; - var blendProgram = ShaderHelper.CompileProgram(shaders, ShaderType.ComputeShader); + int blendProgram = ShaderHelper.CompileProgram(shaders, ShaderType.ComputeShader); shaders[1] = neighbourShaderData; - var neighbourProgram = ShaderHelper.CompileProgram(shaders, ShaderType.ComputeShader); + int neighbourProgram = ShaderHelper.CompileProgram(shaders, ShaderType.ComputeShader); _edgeShaderPrograms[i] = edgeProgram; _blendShaderPrograms[i] = blendProgram; @@ -116,7 +117,7 @@ namespace Ryujinx.Graphics.OpenGL.Effects.Smaa private void Initialize() { - var areaInfo = new TextureCreateInfo(AreaWidth, + TextureCreateInfo areaInfo = new TextureCreateInfo(AreaWidth, AreaHeight, 1, 1, @@ -132,7 +133,7 @@ namespace Ryujinx.Graphics.OpenGL.Effects.Smaa SwizzleComponent.Blue, SwizzleComponent.Alpha); - var searchInfo = new TextureCreateInfo(SearchWidth, + TextureCreateInfo searchInfo = new TextureCreateInfo(SearchWidth, SearchHeight, 1, 1, @@ -151,11 +152,11 @@ namespace Ryujinx.Graphics.OpenGL.Effects.Smaa _areaTexture = new TextureStorage(_renderer, areaInfo); _searchTexture = new TextureStorage(_renderer, searchInfo); - var areaTexture = EmbeddedResources.ReadFileToRentedMemory("Ryujinx.Graphics.OpenGL/Effects/Textures/SmaaAreaTexture.bin"); - var searchTexture = EmbeddedResources.ReadFileToRentedMemory("Ryujinx.Graphics.OpenGL/Effects/Textures/SmaaSearchTexture.bin"); + MemoryOwner areaTexture = EmbeddedResources.ReadFileToRentedMemory("Ryujinx.Graphics.OpenGL/Effects/Textures/SmaaAreaTexture.bin"); + MemoryOwner searchTexture = EmbeddedResources.ReadFileToRentedMemory("Ryujinx.Graphics.OpenGL/Effects/Textures/SmaaSearchTexture.bin"); - var areaView = _areaTexture.CreateDefaultView(); - var searchView = _searchTexture.CreateDefaultView(); + ITexture areaView = _areaTexture.CreateDefaultView(); + ITexture searchView = _searchTexture.CreateDefaultView(); areaView.SetData(areaTexture); searchView.SetData(searchTexture); @@ -178,13 +179,13 @@ namespace Ryujinx.Graphics.OpenGL.Effects.Smaa RecreateShaders(view.Width, view.Height); } - var textureView = _outputTexture.CreateView(view.Info, 0, 0) as TextureView; - var edgeOutput = _edgeOutputTexture.DefaultView as TextureView; - var blendOutput = _blendOutputTexture.DefaultView as TextureView; - var areaTexture = _areaTexture.DefaultView as TextureView; - var searchTexture = _searchTexture.DefaultView as TextureView; + TextureView textureView = _outputTexture.CreateView(view.Info, 0, 0) as TextureView; + TextureView edgeOutput = _edgeOutputTexture.DefaultView as TextureView; + TextureView blendOutput = _blendOutputTexture.DefaultView as TextureView; + TextureView areaTexture = _areaTexture.DefaultView as TextureView; + TextureView searchTexture = _searchTexture.DefaultView as TextureView; - var previousFramebuffer = GL.GetInteger(GetPName.FramebufferBinding); + int previousFramebuffer = GL.GetInteger(GetPName.FramebufferBinding); int previousUnit = GL.GetInteger(GetPName.ActiveTexture); GL.ActiveTexture(TextureUnit.Texture0); int previousTextureBinding0 = GL.GetInteger(GetPName.TextureBinding2D); @@ -193,7 +194,7 @@ namespace Ryujinx.Graphics.OpenGL.Effects.Smaa GL.ActiveTexture(TextureUnit.Texture2); int previousTextureBinding2 = GL.GetInteger(GetPName.TextureBinding2D); - var framebuffer = new Framebuffer(); + Framebuffer framebuffer = new Framebuffer(); framebuffer.Bind(); framebuffer.AttachColor(0, edgeOutput); GL.Clear(ClearBufferMask.ColorBufferBit); @@ -206,8 +207,8 @@ namespace Ryujinx.Graphics.OpenGL.Effects.Smaa framebuffer.Dispose(); - var dispatchX = BitUtils.DivRoundUp(view.Width, IPostProcessingEffect.LocalGroupSize); - var dispatchY = BitUtils.DivRoundUp(view.Height, IPostProcessingEffect.LocalGroupSize); + int dispatchX = BitUtils.DivRoundUp(view.Width, IPostProcessingEffect.LocalGroupSize); + int dispatchY = BitUtils.DivRoundUp(view.Height, IPostProcessingEffect.LocalGroupSize); int previousProgram = GL.GetInteger(GetPName.CurrentProgram); GL.BindImageTexture(0, edgeOutput.Handle, 0, false, 0, TextureAccess.ReadWrite, SizedInternalFormat.Rgba8); diff --git a/src/Ryujinx.Graphics.OpenGL/Image/FormatConverter.cs b/src/Ryujinx.Graphics.OpenGL/Image/FormatConverter.cs index 490c0c585..64e4fe36d 100644 --- a/src/Ryujinx.Graphics.OpenGL/Image/FormatConverter.cs +++ b/src/Ryujinx.Graphics.OpenGL/Image/FormatConverter.cs @@ -19,7 +19,7 @@ namespace Ryujinx.Graphics.OpenGL.Image if (Avx2.IsSupported) { - var mask = Vector256.Create( + Vector256 mask = Vector256.Create( (byte)3, (byte)0, (byte)1, (byte)2, (byte)7, (byte)4, (byte)5, (byte)6, (byte)11, (byte)8, (byte)9, (byte)10, @@ -35,7 +35,7 @@ namespace Ryujinx.Graphics.OpenGL.Image { for (uint i = 0; i < sizeAligned; i += 32) { - var dataVec = Avx.LoadVector256(pInput + i); + Vector256 dataVec = Avx.LoadVector256(pInput + i); dataVec = Avx2.Shuffle(dataVec, mask); @@ -47,7 +47,7 @@ namespace Ryujinx.Graphics.OpenGL.Image } else if (Ssse3.IsSupported) { - var mask = Vector128.Create( + Vector128 mask = Vector128.Create( (byte)3, (byte)0, (byte)1, (byte)2, (byte)7, (byte)4, (byte)5, (byte)6, (byte)11, (byte)8, (byte)9, (byte)10, @@ -59,7 +59,7 @@ namespace Ryujinx.Graphics.OpenGL.Image { for (uint i = 0; i < sizeAligned; i += 16) { - var dataVec = Sse2.LoadVector128(pInput + i); + Vector128 dataVec = Sse2.LoadVector128(pInput + i); dataVec = Ssse3.Shuffle(dataVec, mask); @@ -70,8 +70,8 @@ namespace Ryujinx.Graphics.OpenGL.Image start = sizeAligned; } - var outSpan = MemoryMarshal.Cast(output); - var dataSpan = MemoryMarshal.Cast(data); + Span outSpan = MemoryMarshal.Cast(output); + ReadOnlySpan dataSpan = MemoryMarshal.Cast(data); for (int i = start / sizeof(uint); i < dataSpan.Length; i++) { outSpan[i] = BitOperations.RotateLeft(dataSpan[i], 8); @@ -88,7 +88,7 @@ namespace Ryujinx.Graphics.OpenGL.Image if (Avx2.IsSupported) { - var mask = Vector256.Create( + Vector256 mask = Vector256.Create( (byte)1, (byte)2, (byte)3, (byte)0, (byte)5, (byte)6, (byte)7, (byte)4, (byte)9, (byte)10, (byte)11, (byte)8, @@ -104,7 +104,7 @@ namespace Ryujinx.Graphics.OpenGL.Image { for (uint i = 0; i < sizeAligned; i += 32) { - var dataVec = Avx.LoadVector256(pInput + i); + Vector256 dataVec = Avx.LoadVector256(pInput + i); dataVec = Avx2.Shuffle(dataVec, mask); @@ -116,7 +116,7 @@ namespace Ryujinx.Graphics.OpenGL.Image } else if (Ssse3.IsSupported) { - var mask = Vector128.Create( + Vector128 mask = Vector128.Create( (byte)1, (byte)2, (byte)3, (byte)0, (byte)5, (byte)6, (byte)7, (byte)4, (byte)9, (byte)10, (byte)11, (byte)8, @@ -128,7 +128,7 @@ namespace Ryujinx.Graphics.OpenGL.Image { for (uint i = 0; i < sizeAligned; i += 16) { - var dataVec = Sse2.LoadVector128(pInput + i); + Vector128 dataVec = Sse2.LoadVector128(pInput + i); dataVec = Ssse3.Shuffle(dataVec, mask); @@ -139,8 +139,8 @@ namespace Ryujinx.Graphics.OpenGL.Image start = sizeAligned; } - var outSpan = MemoryMarshal.Cast(output); - var dataSpan = MemoryMarshal.Cast(data); + Span outSpan = MemoryMarshal.Cast(output); + ReadOnlySpan dataSpan = MemoryMarshal.Cast(data); for (int i = start / sizeof(uint); i < dataSpan.Length; i++) { outSpan[i] = BitOperations.RotateRight(dataSpan[i], 8); diff --git a/src/Ryujinx.Graphics.OpenGL/Image/TextureBuffer.cs b/src/Ryujinx.Graphics.OpenGL/Image/TextureBuffer.cs index 8e728a2bb..231d9c97b 100644 --- a/src/Ryujinx.Graphics.OpenGL/Image/TextureBuffer.cs +++ b/src/Ryujinx.Graphics.OpenGL/Image/TextureBuffer.cs @@ -57,7 +57,7 @@ namespace Ryujinx.Graphics.OpenGL.Image /// public void SetData(MemoryOwner data) { - var dataSpan = data.Span; + Span dataSpan = data.Span; Buffer.SetData(_buffer, _bufferOffset, dataSpan[..Math.Min(dataSpan.Length, _bufferSize)]); diff --git a/src/Ryujinx.Graphics.OpenGL/Image/TextureCopyIncompatible.cs b/src/Ryujinx.Graphics.OpenGL/Image/TextureCopyIncompatible.cs index 082e6ccf8..1a94660b5 100644 --- a/src/Ryujinx.Graphics.OpenGL/Image/TextureCopyIncompatible.cs +++ b/src/Ryujinx.Graphics.OpenGL/Image/TextureCopyIncompatible.cs @@ -91,8 +91,8 @@ void main() int srcComponentsCount = srcBpp / componentSize; int dstComponentsCount = dstBpp / componentSize; - var srcFormat = GetFormat(componentSize, srcComponentsCount); - var dstFormat = GetFormat(componentSize, dstComponentsCount); + SizedInternalFormat srcFormat = GetFormat(componentSize, srcComponentsCount); + SizedInternalFormat dstFormat = GetFormat(componentSize, dstComponentsCount); GL.UseProgram(srcBpp < dstBpp ? GetWideningShader(componentSize, srcComponentsCount, dstComponentsCount) diff --git a/src/Ryujinx.Graphics.OpenGL/Image/TextureView.cs b/src/Ryujinx.Graphics.OpenGL/Image/TextureView.cs index a89dd5131..2c7b8f98c 100644 --- a/src/Ryujinx.Graphics.OpenGL/Image/TextureView.cs +++ b/src/Ryujinx.Graphics.OpenGL/Image/TextureView.cs @@ -454,7 +454,7 @@ namespace Ryujinx.Graphics.OpenGL.Image { unsafe { - var dataSpan = data.Span; + Span dataSpan = data.Span; fixed (byte* ptr = dataSpan) { ReadFrom((nint)ptr, dataSpan.Length); diff --git a/src/Ryujinx.Graphics.OpenGL/OpenGLRenderer.cs b/src/Ryujinx.Graphics.OpenGL/OpenGLRenderer.cs index 6ead314fd..af1494bbe 100644 --- a/src/Ryujinx.Graphics.OpenGL/OpenGLRenderer.cs +++ b/src/Ryujinx.Graphics.OpenGL/OpenGLRenderer.cs @@ -6,6 +6,7 @@ using Ryujinx.Graphics.OpenGL.Image; using Ryujinx.Graphics.OpenGL.Queries; using Ryujinx.Graphics.Shader.Translation; using System; +using BufferAccess = Ryujinx.Graphics.GAL.BufferAccess; namespace Ryujinx.Graphics.OpenGL { @@ -63,7 +64,7 @@ namespace Ryujinx.Graphics.OpenGL { BufferCount++; - var memType = access & GAL.BufferAccess.MemoryTypeMask; + BufferAccess memType = access & GAL.BufferAccess.MemoryTypeMask; if (memType == GAL.BufferAccess.HostMemory) { diff --git a/src/Ryujinx.Graphics.OpenGL/Pipeline.cs b/src/Ryujinx.Graphics.OpenGL/Pipeline.cs index 096e2e5eb..83319ea6d 100644 --- a/src/Ryujinx.Graphics.OpenGL/Pipeline.cs +++ b/src/Ryujinx.Graphics.OpenGL/Pipeline.cs @@ -1205,7 +1205,7 @@ namespace Ryujinx.Graphics.OpenGL { int vIndex = index * 4; - var region = regions[index]; + Rectangle region = regions[index]; bool enabled = (region.X | region.Y) != 0 || region.Width != 0xffff || region.Height != 0xffff; uint mask = 1u << index; diff --git a/src/Ryujinx.Graphics.OpenGL/Queries/Counters.cs b/src/Ryujinx.Graphics.OpenGL/Queries/Counters.cs index 1530c9d26..436f03756 100644 --- a/src/Ryujinx.Graphics.OpenGL/Queries/Counters.cs +++ b/src/Ryujinx.Graphics.OpenGL/Queries/Counters.cs @@ -35,7 +35,7 @@ namespace Ryujinx.Graphics.OpenGL.Queries public void Update() { - foreach (var queue in _counterQueues) + foreach (CounterQueue queue in _counterQueues) { queue.Flush(false); } @@ -48,7 +48,7 @@ namespace Ryujinx.Graphics.OpenGL.Queries public void Dispose() { - foreach (var queue in _counterQueues) + foreach (CounterQueue queue in _counterQueues) { queue.Dispose(); } diff --git a/src/Ryujinx.Graphics.OpenGL/VertexArray.cs b/src/Ryujinx.Graphics.OpenGL/VertexArray.cs index 2db84421f..bd8e9eafa 100644 --- a/src/Ryujinx.Graphics.OpenGL/VertexArray.cs +++ b/src/Ryujinx.Graphics.OpenGL/VertexArray.cs @@ -177,7 +177,7 @@ namespace Ryujinx.Graphics.OpenGL { int vbIndex = BitOperations.TrailingZeroCount(buffersInUse); - ref var vb = ref _vertexBuffers[vbIndex]; + ref VertexBufferDescriptor vb = ref _vertexBuffers[vbIndex]; int requiredSize = vertexCount * vb.Stride; @@ -232,7 +232,7 @@ namespace Ryujinx.Graphics.OpenGL { int vbIndex = BitOperations.TrailingZeroCount(buffersLimited); - ref var vb = ref _vertexBuffers[vbIndex]; + ref VertexBufferDescriptor vb = ref _vertexBuffers[vbIndex]; GL.BindVertexBuffer(vbIndex, vb.Buffer.Handle.ToInt32(), (nint)vb.Buffer.Offset, vb.Stride); diff --git a/src/Ryujinx.Graphics.OpenGL/Window.cs b/src/Ryujinx.Graphics.OpenGL/Window.cs index f161be506..c75fa5078 100644 --- a/src/Ryujinx.Graphics.OpenGL/Window.cs +++ b/src/Ryujinx.Graphics.OpenGL/Window.cs @@ -76,13 +76,13 @@ namespace Ryujinx.Graphics.OpenGL if (_antiAliasing != null) { - var oldView = viewConverted; + TextureView oldView = viewConverted; viewConverted = _antiAliasing.Run(viewConverted, _width, _height); if (viewConverted.Format.IsBgr()) { - var swappedView = _renderer.TextureCopy.BgraSwap(viewConverted); + TextureView swappedView = _renderer.TextureCopy.BgraSwap(viewConverted); viewConverted?.Dispose(); @@ -330,7 +330,7 @@ namespace Ryujinx.Graphics.OpenGL case AntiAliasing.SmaaMedium: case AntiAliasing.SmaaHigh: case AntiAliasing.SmaaUltra: - var quality = _currentAntiAliasing - AntiAliasing.SmaaLow; + int quality = _currentAntiAliasing - AntiAliasing.SmaaLow; if (_antiAliasing is SmaaPostProcessingEffect smaa) { smaa.Quality = quality; @@ -394,7 +394,7 @@ namespace Ryujinx.Graphics.OpenGL { _upscaledTexture?.Dispose(); - var info = new TextureCreateInfo( + TextureCreateInfo info = new TextureCreateInfo( _width, _height, 1, From 5eba42fa06d83b980019f3b164f87ff73ffd4ec8 Mon Sep 17 00:00:00 2001 From: Evan Husted Date: Sat, 25 Jan 2025 14:13:18 -0600 Subject: [PATCH 16/19] misc: chore: Use explicit types in HLE project --- .../ServiceNotImplementedException.cs | 23 ++--- src/Ryujinx.HLE/FileSystem/ContentManager.cs | 96 +++++++++---------- src/Ryujinx.HLE/FileSystem/ContentMetaData.cs | 2 +- .../FileSystem/VirtualFileSystem.cs | 26 ++--- .../HOS/Applets/Error/ErrorApplet.cs | 2 +- .../SoftwareKeyboardApplet.cs | 16 ++-- .../SoftwareKeyboardRenderer.cs | 4 +- .../SoftwareKeyboardRendererBase.cs | 80 ++++++++-------- .../Applets/SoftwareKeyboard/TimedAction.cs | 10 +- .../HOS/ArmProcessContextFactory.cs | 10 +- .../HOS/Diagnostics/Demangler/Demangler.cs | 2 +- src/Ryujinx.HLE/HOS/Horizon.cs | 16 ++-- src/Ryujinx.HLE/HOS/HorizonFsClient.cs | 6 +- .../HOS/Kernel/Memory/KMemoryManager.cs | 4 +- .../HOS/Kernel/Memory/KMemoryRegionManager.cs | 2 +- .../HOS/Kernel/Memory/KPageBitmap.cs | 2 +- .../HOS/Kernel/Memory/KPageHeap.cs | 2 +- .../HOS/Kernel/Memory/KPageList.cs | 4 +- .../HOS/Kernel/Memory/KPageTable.cs | 18 ++-- .../HOS/Kernel/Memory/KPageTableBase.cs | 12 +-- .../HOS/Kernel/Process/HleProcessDebugger.cs | 9 +- .../HOS/Kernel/SupervisorCall/Syscall.cs | 6 +- .../HOS/Kernel/Threading/KAddressArbiter.cs | 4 +- .../HOS/Kernel/Threading/KPriorityQueue.cs | 4 +- .../HOS/Kernel/Threading/KThread.cs | 2 +- src/Ryujinx.HLE/HOS/LibHacHorizonManager.cs | 2 +- src/Ryujinx.HLE/HOS/ModLoader.cs | 95 +++++++++--------- .../Services/Account/Acc/AccountManager.cs | 4 +- .../Account/Acc/AccountSaveDataManager.cs | 4 +- .../Acc/AccountService/ManagerServer.cs | 2 +- .../SystemAppletProxy/ICommonStateGetter.cs | 2 +- .../HOS/Services/Caps/CaptureManager.cs | 6 +- .../FileSystemProxy/FileSystemProxyHelper.cs | 10 +- .../Services/Fs/FileSystemProxy/IDirectory.cs | 3 +- .../HOS/Services/Fs/FileSystemProxy/IFile.cs | 3 +- .../Fs/FileSystemProxy/IFileSystem.cs | 4 +- .../Services/Fs/FileSystemProxy/IStorage.cs | 3 +- .../HOS/Services/Fs/IFileSystemProxy.cs | 89 ++++++++--------- .../HOS/Services/Fs/ISaveDataInfoReader.cs | 3 +- .../HOS/Services/Hid/Irs/IIrSensorServer.cs | 8 +- .../IUserLocalCommunicationService.cs | 2 +- .../LdnMitm/LanDiscovery.cs | 2 +- .../LdnMitm/Proxy/LdnProxyUdpServer.cs | 4 +- .../LdnRyu/LdnMasterProxyClient.cs | 4 +- .../LdnRyu/Proxy/LdnProxySocket.cs | 2 +- .../HOS/Services/Mii/Types/CoreData.cs | 24 ++--- .../Nfc/AmiiboDecryption/AmiiboDecryptor.cs | 4 +- .../Nfc/AmiiboDecryption/AmiiboDump.cs | 20 ++-- .../HOS/Services/Nv/Host1xContext.cs | 4 +- .../NvHostAsGpu/NvHostAsGpuDeviceFile.cs | 6 +- .../NvHostChannel/NvHostChannelDeviceFile.cs | 2 +- .../QueryPlayStatisticsManager.cs | 2 +- .../HOS/Services/Sdb/Pl/SharedFontManager.cs | 2 +- src/Ryujinx.HLE/HOS/Services/ServerBase.cs | 9 +- .../Settings/ISystemSettingsServer.cs | 2 +- .../HOS/Services/Sockets/Bsd/IClient.cs | 6 +- .../Sockets/Bsd/Impl/WinSockHelper.cs | 4 +- .../Sockets/Bsd/Proxy/SocketHelpers.cs | 6 +- .../Sockets/Sfdnsres/Proxy/DnsMitmResolver.cs | 2 +- .../Services/Ssl/BuiltInCertificateManager.cs | 2 +- .../Services/Ssl/SslService/ISslConnection.cs | 2 +- .../Time/TimeZone/TimeZoneContentManager.cs | 12 +-- .../CodeEmitters/EndConditionalBlock.cs | 2 +- .../HOS/Tamper/InstructionHelper.cs | 2 +- src/Ryujinx.HLE/HOS/TamperMachine.cs | 6 +- .../Loaders/Executables/KipExecutable.cs | 2 +- .../Loaders/Executables/NsoExecutable.cs | 2 +- src/Ryujinx.HLE/Loaders/Mods/IPSPatcher.cs | 4 +- .../Loaders/Mods/IPSwitchPatcher.cs | 8 +- src/Ryujinx.HLE/Loaders/Mods/MemPatch.cs | 4 +- .../Extensions/FileSystemExtensions.cs | 2 +- .../Extensions/LocalFileSystemExtensions.cs | 2 +- .../Extensions/MetaLoaderExtensions.cs | 8 +- .../Processes/Extensions/NcaExtensions.cs | 8 +- .../PartitionFileSystemExtensions.cs | 4 +- .../Loaders/Processes/ProcessLoader.cs | 2 +- .../Loaders/Processes/ProcessLoaderHelper.cs | 10 +- src/Ryujinx.HLE/StructHelpers.cs | 2 +- src/Ryujinx.HLE/UI/Input/NpadReader.cs | 14 +-- .../Utilities/PartitionFileSystemUtils.cs | 2 +- 80 files changed, 410 insertions(+), 397 deletions(-) diff --git a/src/Ryujinx.HLE/Exceptions/ServiceNotImplementedException.cs b/src/Ryujinx.HLE/Exceptions/ServiceNotImplementedException.cs index 408b5baa4..17aab8105 100644 --- a/src/Ryujinx.HLE/Exceptions/ServiceNotImplementedException.cs +++ b/src/Ryujinx.HLE/Exceptions/ServiceNotImplementedException.cs @@ -3,6 +3,7 @@ using Ryujinx.HLE.HOS; using Ryujinx.HLE.HOS.Ipc; using Ryujinx.HLE.HOS.Services; using System; +using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; @@ -53,12 +54,12 @@ namespace Ryujinx.HLE.Exceptions if (callingType != null && callingMethod != null) { // If the type is past 0xF, we are using TIPC - var ipcCommands = Request.Type > IpcMessageType.TipcCloseSession ? Service.TipcCommands : Service.CmifCommands; + IReadOnlyDictionary ipcCommands = Request.Type > IpcMessageType.TipcCloseSession ? Service.TipcCommands : Service.CmifCommands; // Find the handler for the method called - var ipcHandler = ipcCommands.FirstOrDefault(x => x.Value == callingMethod); - var ipcCommandId = ipcHandler.Key; - var ipcMethod = ipcHandler.Value; + KeyValuePair ipcHandler = ipcCommands.FirstOrDefault(x => x.Value == callingMethod); + int ipcCommandId = ipcHandler.Key; + MethodInfo ipcMethod = ipcHandler.Value; if (ipcMethod != null) { @@ -83,7 +84,7 @@ namespace Ryujinx.HLE.Exceptions { sb.AppendLine("\tPtrBuff:"); - foreach (var buff in Request.PtrBuff) + foreach (IpcPtrBuffDesc buff in Request.PtrBuff) { sb.AppendLine($"\t[{buff.Index}] Position: 0x{buff.Position:x16} Size: 0x{buff.Size:x16}"); } @@ -93,7 +94,7 @@ namespace Ryujinx.HLE.Exceptions { sb.AppendLine("\tSendBuff:"); - foreach (var buff in Request.SendBuff) + foreach (IpcBuffDesc buff in Request.SendBuff) { sb.AppendLine($"\tPosition: 0x{buff.Position:x16} Size: 0x{buff.Size:x16} Flags: {buff.Flags}"); } @@ -103,7 +104,7 @@ namespace Ryujinx.HLE.Exceptions { sb.AppendLine("\tReceiveBuff:"); - foreach (var buff in Request.ReceiveBuff) + foreach (IpcBuffDesc buff in Request.ReceiveBuff) { sb.AppendLine($"\tPosition: 0x{buff.Position:x16} Size: 0x{buff.Size:x16} Flags: {buff.Flags}"); } @@ -113,7 +114,7 @@ namespace Ryujinx.HLE.Exceptions { sb.AppendLine("\tExchangeBuff:"); - foreach (var buff in Request.ExchangeBuff) + foreach (IpcBuffDesc buff in Request.ExchangeBuff) { sb.AppendLine($"\tPosition: 0x{buff.Position:x16} Size: 0x{buff.Size:x16} Flags: {buff.Flags}"); } @@ -123,7 +124,7 @@ namespace Ryujinx.HLE.Exceptions { sb.AppendLine("\tRecvListBuff:"); - foreach (var buff in Request.RecvListBuff) + foreach (IpcRecvListBuffDesc buff in Request.RecvListBuff) { sb.AppendLine($"\tPosition: 0x{buff.Position:x16} Size: 0x{buff.Size:x16}"); } @@ -147,8 +148,8 @@ namespace Ryujinx.HLE.Exceptions // Find the IIpcService method that threw this exception while ((frame = trace.GetFrame(i++)) != null) { - var method = frame.GetMethod(); - var declType = method.DeclaringType; + MethodBase method = frame.GetMethod(); + Type declType = method.DeclaringType; if (typeof(IpcService).IsAssignableFrom(declType)) { diff --git a/src/Ryujinx.HLE/FileSystem/ContentManager.cs b/src/Ryujinx.HLE/FileSystem/ContentManager.cs index a87453d00..bce896ea1 100644 --- a/src/Ryujinx.HLE/FileSystem/ContentManager.cs +++ b/src/Ryujinx.HLE/FileSystem/ContentManager.cs @@ -107,15 +107,15 @@ namespace Ryujinx.HLE.FileSystem foreach (StorageId storageId in Enum.GetValues()) { - if (!ContentPath.TryGetContentPath(storageId, out var contentPathString)) + if (!ContentPath.TryGetContentPath(storageId, out string contentPathString)) { continue; } - if (!ContentPath.TryGetRealPath(contentPathString, out var contentDirectory)) + if (!ContentPath.TryGetRealPath(contentPathString, out string contentDirectory)) { continue; } - var registeredDirectory = Path.Combine(contentDirectory, "registered"); + string registeredDirectory = Path.Combine(contentDirectory, "registered"); Directory.CreateDirectory(registeredDirectory); @@ -170,7 +170,7 @@ namespace Ryujinx.HLE.FileSystem } } - if (_locationEntries.TryGetValue(storageId, out var locationEntriesItem) && locationEntriesItem?.Count == 0) + if (_locationEntries.TryGetValue(storageId, out LinkedList locationEntriesItem) && locationEntriesItem?.Count == 0) { _locationEntries.Remove(storageId); } @@ -200,7 +200,7 @@ namespace Ryujinx.HLE.FileSystem if (!mergedToContainer) { - using var pfs = PartitionFileSystemUtils.OpenApplicationFileSystem(containerPath, _virtualFileSystem); + using IFileSystem pfs = PartitionFileSystemUtils.OpenApplicationFileSystem(containerPath, _virtualFileSystem); } } } @@ -217,17 +217,17 @@ namespace Ryujinx.HLE.FileSystem if (AocData.TryGetValue(aocTitleId, out AocItem aoc)) { - var file = new FileStream(aoc.ContainerPath, FileMode.Open, FileAccess.Read); - using var ncaFile = new UniqueRef(); + FileStream file = new FileStream(aoc.ContainerPath, FileMode.Open, FileAccess.Read); + using UniqueRef ncaFile = new UniqueRef(); switch (Path.GetExtension(aoc.ContainerPath)) { case ".xci": - var xci = new Xci(_virtualFileSystem.KeySet, file.AsStorage()).OpenPartition(XciPartitionType.Secure); + XciPartition xci = new Xci(_virtualFileSystem.KeySet, file.AsStorage()).OpenPartition(XciPartitionType.Secure); xci.OpenFile(ref ncaFile.Ref, aoc.NcaPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); break; case ".nsp": - var pfs = new PartitionFileSystem(); + PartitionFileSystem pfs = new PartitionFileSystem(); pfs.Initialize(file.AsStorage()); pfs.OpenFile(ref ncaFile.Ref, aoc.NcaPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); break; @@ -278,7 +278,7 @@ namespace Ryujinx.HLE.FileSystem { if (_contentDictionary.ContainsValue(ncaId)) { - var content = _contentDictionary.FirstOrDefault(x => x.Value == ncaId); + KeyValuePair<(ulong titleId, NcaContentType type), string> content = _contentDictionary.FirstOrDefault(x => x.Value == ncaId); ulong titleId = content.Key.titleId; NcaContentType contentType = content.Key.type; @@ -295,7 +295,7 @@ namespace Ryujinx.HLE.FileSystem { lock (_lock) { - if (_contentDictionary.TryGetValue((titleId, contentType), out var contentDictionaryItem)) + if (_contentDictionary.TryGetValue((titleId, contentType), out string contentDictionaryItem)) { return UInt128Utils.FromHex(contentDictionaryItem); } @@ -430,8 +430,8 @@ namespace Ryujinx.HLE.FileSystem public void InstallFirmware(string firmwareSource) { - ContentPath.TryGetContentPath(StorageId.BuiltInSystem, out var contentPathString); - ContentPath.TryGetRealPath(contentPathString, out var contentDirectory); + ContentPath.TryGetContentPath(StorageId.BuiltInSystem, out string contentPathString); + ContentPath.TryGetRealPath(contentPathString, out string contentDirectory); string registeredDirectory = Path.Combine(contentDirectory, "registered"); string temporaryDirectory = Path.Combine(contentDirectory, "temp"); @@ -480,7 +480,7 @@ namespace Ryujinx.HLE.FileSystem { if (Directory.Exists(keysSource)) { - foreach (var filePath in Directory.EnumerateFiles(keysSource, "*.keys")) + foreach (string filePath in Directory.EnumerateFiles(keysSource, "*.keys")) { VerifyKeysFile(filePath); File.Copy(filePath, Path.Combine(installDirectory, Path.GetFileName(filePath)), true); @@ -523,7 +523,7 @@ namespace Ryujinx.HLE.FileSystem Directory.Delete(temporaryDirectory, true); } Directory.CreateDirectory(temporaryDirectory); - foreach (var entry in archive.Entries) + foreach (ZipArchiveEntry entry in archive.Entries) { if (Path.GetExtension(entry.FullName).Equals(".keys", StringComparison.OrdinalIgnoreCase)) { @@ -563,7 +563,7 @@ namespace Ryujinx.HLE.FileSystem private void InstallFromPartition(IFileSystem filesystem, string temporaryDirectory) { - foreach (var entry in filesystem.EnumerateEntries("/", "*.nca")) + foreach (DirectoryEntryEx entry in filesystem.EnumerateEntries("/", "*.nca")) { Nca nca = new(_virtualFileSystem.KeySet, OpenPossibleFragmentedFile(filesystem, entry.FullPath, OpenMode.Read).AsStorage()); @@ -587,7 +587,7 @@ namespace Ryujinx.HLE.FileSystem private static void InstallFromZip(ZipArchive archive, string temporaryDirectory) { - foreach (var entry in archive.Entries) + foreach (ZipArchiveEntry entry in archive.Entries) { if (entry.FullName.EndsWith(".nca") || entry.FullName.EndsWith(".nca/00")) { @@ -627,7 +627,7 @@ namespace Ryujinx.HLE.FileSystem private static IFile OpenPossibleFragmentedFile(IFileSystem filesystem, string path, OpenMode mode) { - using var file = new UniqueRef(); + using UniqueRef file = new UniqueRef(); if (filesystem.FileExists($"{path}/00")) { @@ -697,7 +697,7 @@ namespace Ryujinx.HLE.FileSystem { SystemVersion systemVersion = null; - foreach (var entry in archive.Entries) + foreach (ZipArchiveEntry entry in archive.Entries) { if (entry.FullName.EndsWith(".nca") || entry.FullName.EndsWith(".nca/00")) { @@ -706,7 +706,7 @@ namespace Ryujinx.HLE.FileSystem Nca nca = new(_virtualFileSystem.KeySet, storage); - if (updateNcas.TryGetValue(nca.Header.TitleId, out var updateNcasItem)) + if (updateNcas.TryGetValue(nca.Header.TitleId, out List<(NcaContentType type, string path)> updateNcasItem)) { updateNcasItem.Add((nca.Header.ContentType, entry.FullName)); } @@ -717,13 +717,13 @@ namespace Ryujinx.HLE.FileSystem } } - if (updateNcas.TryGetValue(SystemUpdateTitleId, out var ncaEntry)) + if (updateNcas.TryGetValue(SystemUpdateTitleId, out List<(NcaContentType type, string path)> ncaEntry)) { string metaPath = ncaEntry.FirstOrDefault(x => x.type == NcaContentType.Meta).path; CnmtContentMetaEntry[] metaEntries = null; - var fileEntry = archive.GetEntry(metaPath); + ZipArchiveEntry fileEntry = archive.GetEntry(metaPath); using (Stream ncaStream = GetZipStream(fileEntry)) { @@ -733,11 +733,11 @@ namespace Ryujinx.HLE.FileSystem string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath; - using var metaFile = new UniqueRef(); + using UniqueRef metaFile = new UniqueRef(); if (fs.OpenFile(ref metaFile.Ref, cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess()) { - var meta = new Cnmt(metaFile.Get.AsStream()); + Cnmt meta = new Cnmt(metaFile.Get.AsStream()); if (meta.Type == ContentMetaType.SystemUpdate) { @@ -753,16 +753,16 @@ namespace Ryujinx.HLE.FileSystem throw new FileNotFoundException("System update title was not found in the firmware package."); } - if (updateNcas.TryGetValue(SystemVersionTitleId, out var updateNcasItem)) + if (updateNcas.TryGetValue(SystemVersionTitleId, out List<(NcaContentType type, string path)> updateNcasItem)) { string versionEntry = updateNcasItem.FirstOrDefault(x => x.type != NcaContentType.Meta).path; using Stream ncaStream = GetZipStream(archive.GetEntry(versionEntry)); Nca nca = new(_virtualFileSystem.KeySet, ncaStream.AsStorage()); - var romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid); + IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid); - using var systemVersionFile = new UniqueRef(); + using UniqueRef systemVersionFile = new UniqueRef(); if (romfs.OpenFile(ref systemVersionFile.Ref, "/file".ToU8Span(), OpenMode.Read).IsSuccess()) { @@ -798,11 +798,11 @@ namespace Ryujinx.HLE.FileSystem string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath; - using var metaFile = new UniqueRef(); + using UniqueRef metaFile = new UniqueRef(); if (fs.OpenFile(ref metaFile.Ref, cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess()) { - var meta = new Cnmt(metaFile.Get.AsStream()); + Cnmt meta = new Cnmt(metaFile.Get.AsStream()); IStorage contentStorage = contentNcaStream.AsStorage(); if (contentStorage.GetSize(out long size).IsSuccess()) @@ -830,9 +830,9 @@ namespace Ryujinx.HLE.FileSystem { StringBuilder extraNcas = new(); - foreach (var entry in updateNcas) + foreach (KeyValuePair> entry in updateNcas) { - foreach (var (type, path) in entry.Value) + foreach ((NcaContentType type, string path) in entry.Value) { extraNcas.AppendLine(path); } @@ -855,7 +855,7 @@ namespace Ryujinx.HLE.FileSystem CnmtContentMetaEntry[] metaEntries = null; - foreach (var entry in filesystem.EnumerateEntries("/", "*.nca")) + foreach (DirectoryEntryEx entry in filesystem.EnumerateEntries("/", "*.nca")) { IStorage ncaStorage = OpenPossibleFragmentedFile(filesystem, entry.FullPath, OpenMode.Read).AsStorage(); @@ -867,11 +867,11 @@ namespace Ryujinx.HLE.FileSystem string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath; - using var metaFile = new UniqueRef(); + using UniqueRef metaFile = new UniqueRef(); if (fs.OpenFile(ref metaFile.Ref, cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess()) { - var meta = new Cnmt(metaFile.Get.AsStream()); + Cnmt meta = new Cnmt(metaFile.Get.AsStream()); if (meta.Type == ContentMetaType.SystemUpdate) { @@ -883,9 +883,9 @@ namespace Ryujinx.HLE.FileSystem } else if (nca.Header.TitleId == SystemVersionTitleId && nca.Header.ContentType == NcaContentType.Data) { - var romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid); + IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid); - using var systemVersionFile = new UniqueRef(); + using UniqueRef systemVersionFile = new UniqueRef(); if (romfs.OpenFile(ref systemVersionFile.Ref, "/file".ToU8Span(), OpenMode.Read).IsSuccess()) { @@ -893,7 +893,7 @@ namespace Ryujinx.HLE.FileSystem } } - if (updateNcas.TryGetValue(nca.Header.TitleId, out var updateNcasItem)) + if (updateNcas.TryGetValue(nca.Header.TitleId, out List<(NcaContentType type, string path)> updateNcasItem)) { updateNcasItem.Add((nca.Header.ContentType, entry.FullPath)); } @@ -912,7 +912,7 @@ namespace Ryujinx.HLE.FileSystem foreach (CnmtContentMetaEntry metaEntry in metaEntries) { - if (updateNcas.TryGetValue(metaEntry.TitleId, out var ncaEntry)) + if (updateNcas.TryGetValue(metaEntry.TitleId, out List<(NcaContentType type, string path)> ncaEntry)) { string metaNcaPath = ncaEntry.FirstOrDefault(x => x.type == NcaContentType.Meta).path; string contentPath = ncaEntry.FirstOrDefault(x => x.type != NcaContentType.Meta).path; @@ -935,11 +935,11 @@ namespace Ryujinx.HLE.FileSystem string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath; - using var metaFile = new UniqueRef(); + using UniqueRef metaFile = new UniqueRef(); if (fs.OpenFile(ref metaFile.Ref, cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess()) { - var meta = new Cnmt(metaFile.Get.AsStream()); + Cnmt meta = new Cnmt(metaFile.Get.AsStream()); if (contentStorage.GetSize(out long size).IsSuccess()) { @@ -966,9 +966,9 @@ namespace Ryujinx.HLE.FileSystem { StringBuilder extraNcas = new(); - foreach (var entry in updateNcas) + foreach (KeyValuePair> entry in updateNcas) { - foreach (var (type, path) in entry.Value) + foreach ((NcaContentType type, string path) in entry.Value) { extraNcas.AppendLine(path); } @@ -987,22 +987,22 @@ namespace Ryujinx.HLE.FileSystem lock (_lock) { - var locationEnties = _locationEntries[StorageId.BuiltInSystem]; + LinkedList locationEnties = _locationEntries[StorageId.BuiltInSystem]; - foreach (var entry in locationEnties) + foreach (LocationEntry entry in locationEnties) { if (entry.ContentType == NcaContentType.Data) { - var path = VirtualFileSystem.SwitchPathToSystemPath(entry.ContentPath); + string path = VirtualFileSystem.SwitchPathToSystemPath(entry.ContentPath); using FileStream fileStream = File.OpenRead(path); Nca nca = new(_virtualFileSystem.KeySet, fileStream.AsStorage()); if (nca.Header.TitleId == SystemVersionTitleId && nca.Header.ContentType == NcaContentType.Data) { - var romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid); + IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid); - using var systemVersionFile = new UniqueRef(); + using UniqueRef systemVersionFile = new UniqueRef(); if (romfs.OpenFile(ref systemVersionFile.Ref, "/file".ToU8Span(), OpenMode.Read).IsSuccess()) { @@ -1073,7 +1073,7 @@ namespace Ryujinx.HLE.FileSystem public bool AreKeysAlredyPresent(string pathToCheck) { string[] fileNames = { "prod.keys", "title.keys", "console.keys", "dev.keys" }; - foreach (var file in fileNames) + foreach (string file in fileNames) { if (File.Exists(Path.Combine(pathToCheck, file))) { diff --git a/src/Ryujinx.HLE/FileSystem/ContentMetaData.cs b/src/Ryujinx.HLE/FileSystem/ContentMetaData.cs index 8cdb889be..a1f29bd13 100644 --- a/src/Ryujinx.HLE/FileSystem/ContentMetaData.cs +++ b/src/Ryujinx.HLE/FileSystem/ContentMetaData.cs @@ -39,7 +39,7 @@ namespace Ryujinx.HLE.FileSystem // TODO: Replace this with a check for IdOffset as soon as LibHac supports it: // && entry.IdOffset == programIndex - foreach (var entry in _cnmt.ContentEntries) + foreach (CnmtContentEntry entry in _cnmt.ContentEntries) { if (entry.Type != type) { diff --git a/src/Ryujinx.HLE/FileSystem/VirtualFileSystem.cs b/src/Ryujinx.HLE/FileSystem/VirtualFileSystem.cs index ef9c493a8..789caee4c 100644 --- a/src/Ryujinx.HLE/FileSystem/VirtualFileSystem.cs +++ b/src/Ryujinx.HLE/FileSystem/VirtualFileSystem.cs @@ -61,7 +61,7 @@ namespace Ryujinx.HLE.FileSystem public void LoadRomFs(ulong pid, string fileName) { - var romfsStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); + FileStream romfsStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); _romFsByPid.AddOrUpdate(pid, romfsStream, (pid, oldStream) => { @@ -140,8 +140,8 @@ namespace Ryujinx.HLE.FileSystem return $"{rawPath}:/"; } - var basePath = rawPath.AsSpan(0, firstSeparatorOffset); - var fileName = rawPath.AsSpan(firstSeparatorOffset + 1); + ReadOnlySpan basePath = rawPath.AsSpan(0, firstSeparatorOffset); + ReadOnlySpan fileName = rawPath.AsSpan(firstSeparatorOffset + 1); return $"{basePath}:/{fileName}"; } @@ -194,7 +194,7 @@ namespace Ryujinx.HLE.FileSystem } fsServerClient = horizon.CreatePrivilegedHorizonClient(); - var fsServer = new FileSystemServer(fsServerClient); + FileSystemServer fsServer = new FileSystemServer(fsServerClient); RandomDataGenerator randomGenerator = Random.Shared.NextBytes; @@ -208,7 +208,7 @@ namespace Ryujinx.HLE.FileSystem SdCard.SetSdCardInserted(true); - var fsServerConfig = new FileSystemServerConfig + FileSystemServerConfig fsServerConfig = new FileSystemServerConfig { ExternalKeySet = KeySet.ExternalKeySet, FsCreators = fsServerObjects.FsCreators, @@ -270,7 +270,7 @@ namespace Ryujinx.HLE.FileSystem { foreach (DirectoryEntryEx ticketEntry in fs.EnumerateEntries("/", "*.tik")) { - using var ticketFile = new UniqueRef(); + using UniqueRef ticketFile = new UniqueRef(); Result result = fs.OpenFile(ref ticketFile.Ref, ticketEntry.FullPath.ToU8Span(), OpenMode.Read); @@ -286,7 +286,7 @@ namespace Ryujinx.HLE.FileSystem continue; Ticket ticket = new(new MemoryStream(ticketData)); - var titleKey = ticket.GetTitleKey(KeySet); + byte[] titleKey = ticket.GetTitleKey(KeySet); if (titleKey != null) { @@ -334,7 +334,7 @@ namespace Ryujinx.HLE.FileSystem { Span info = stackalloc SaveDataInfo[8]; - using var iterator = new UniqueRef(); + using UniqueRef iterator = new UniqueRef(); Result rc = hos.Fs.OpenSaveDataIterator(ref iterator.Ref, spaceId); if (rc.IsFailure()) @@ -398,7 +398,7 @@ namespace Ryujinx.HLE.FileSystem } const string MountName = "SaveDir"; - var mountNameU8 = MountName.ToU8Span(); + U8Span mountNameU8 = MountName.ToU8Span(); BisPartitionId partitionId = info.SpaceId switch { @@ -415,7 +415,7 @@ namespace Ryujinx.HLE.FileSystem try { - var path = $"{MountName}:/save/{info.SaveDataId:x16}".ToU8Span(); + U8Span path = $"{MountName}:/save/{info.SaveDataId:x16}".ToU8Span(); rc = hos.Fs.GetEntryType(out _, path); @@ -437,7 +437,7 @@ namespace Ryujinx.HLE.FileSystem { list = null; - var mountName = "system".ToU8Span(); + U8Span mountName = "system".ToU8Span(); DirectoryHandle handle = default; List localList = new(); @@ -498,7 +498,7 @@ namespace Ryujinx.HLE.FileSystem // Only save data IDs added to SystemExtraDataFixInfo will be fixed. private static Result FixUnindexedSystemSaves(HorizonClient hos, List existingSaveIds) { - foreach (var fixInfo in _systemExtraDataFixInfo) + foreach (ExtraDataFixInfo fixInfo in _systemExtraDataFixInfo) { if (!existingSaveIds.Contains(fixInfo.StaticSaveDataId)) { @@ -665,7 +665,7 @@ namespace Ryujinx.HLE.FileSystem { if (disposing) { - foreach (var stream in _romFsByPid.Values) + foreach (Stream stream in _romFsByPid.Values) { stream.Close(); } diff --git a/src/Ryujinx.HLE/HOS/Applets/Error/ErrorApplet.cs b/src/Ryujinx.HLE/HOS/Applets/Error/ErrorApplet.cs index 0e043cc45..a7917a157 100644 --- a/src/Ryujinx.HLE/HOS/Applets/Error/ErrorApplet.cs +++ b/src/Ryujinx.HLE/HOS/Applets/Error/ErrorApplet.cs @@ -122,7 +122,7 @@ namespace Ryujinx.HLE.HOS.Applets.Error if (romfs.FileExists(filePath)) { - using var binaryFile = new UniqueRef(); + using UniqueRef binaryFile = new UniqueRef(); romfs.OpenFile(ref binaryFile.Ref, filePath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); StreamReader reader = new(binaryFile.Get.AsStream(), Encoding.Unicode); diff --git a/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/SoftwareKeyboardApplet.cs b/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/SoftwareKeyboardApplet.cs index 8fda00a7d..ea906659f 100644 --- a/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/SoftwareKeyboardApplet.cs +++ b/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/SoftwareKeyboardApplet.cs @@ -81,8 +81,8 @@ namespace Ryujinx.HLE.HOS.Applets _interactiveSession.DataAvailable += OnInteractiveData; - var launchParams = _normalSession.Pop(); - var keyboardConfig = _normalSession.Pop(); + byte[] launchParams = _normalSession.Pop(); + byte[] keyboardConfig = _normalSession.Pop(); _isBackground = keyboardConfig.Length == Unsafe.SizeOf(); @@ -205,7 +205,7 @@ namespace Ryujinx.HLE.HOS.Applets else { // Call the configured GUI handler to get user's input. - var args = new SoftwareKeyboardUIArgs + SoftwareKeyboardUIArgs args = new SoftwareKeyboardUIArgs { KeyboardMode = _keyboardForegroundConfig.Mode, HeaderText = StripUnicodeControlCodes(_keyboardForegroundConfig.HeaderText), @@ -265,7 +265,7 @@ namespace Ryujinx.HLE.HOS.Applets private void OnInteractiveData(object sender, EventArgs e) { // Obtain the validation status response. - var data = _interactiveSession.Pop(); + byte[] data = _interactiveSession.Pop(); if (_isBackground) { @@ -320,7 +320,7 @@ namespace Ryujinx.HLE.HOS.Applets using MemoryStream stream = new(data); using BinaryReader reader = new(stream); - var request = (InlineKeyboardRequest)reader.ReadUInt32(); + InlineKeyboardRequest request = (InlineKeyboardRequest)reader.ReadUInt32(); long remaining; @@ -400,14 +400,14 @@ namespace Ryujinx.HLE.HOS.Applets remaining = stream.Length - stream.Position; if (remaining == Marshal.SizeOf()) { - var keyboardCalcData = reader.ReadBytes((int)remaining); - var keyboardCalc = ReadStruct(keyboardCalcData); + byte[] keyboardCalcData = reader.ReadBytes((int)remaining); + SoftwareKeyboardCalc keyboardCalc = ReadStruct(keyboardCalcData); newCalc = keyboardCalc.ToExtended(); } else if (remaining == Marshal.SizeOf() || remaining == SoftwareKeyboardCalcEx.AlternativeSize) { - var keyboardCalcData = reader.ReadBytes((int)remaining); + byte[] keyboardCalcData = reader.ReadBytes((int)remaining); newCalc = ReadStruct(keyboardCalcData); } diff --git a/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/SoftwareKeyboardRenderer.cs b/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/SoftwareKeyboardRenderer.cs index 239535ad5..f65d6a018 100644 --- a/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/SoftwareKeyboardRenderer.cs +++ b/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/SoftwareKeyboardRenderer.cs @@ -117,8 +117,8 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard _state.OverwriteMode = overwriteMode.GetValueOrDefault(_state.OverwriteMode); _state.TypingEnabled = typingEnabled.GetValueOrDefault(_state.TypingEnabled); - var begin = _state.CursorBegin; - var end = _state.CursorEnd; + int begin = _state.CursorBegin; + int end = _state.CursorEnd; _state.CursorBegin = Math.Min(begin, end); _state.CursorEnd = Math.Max(begin, end); diff --git a/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/SoftwareKeyboardRendererBase.cs b/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/SoftwareKeyboardRendererBase.cs index e17b36911..9e861ad10 100644 --- a/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/SoftwareKeyboardRendererBase.cs +++ b/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/SoftwareKeyboardRendererBase.cs @@ -75,10 +75,10 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard _padCancelIcon = LoadResource(typeof(SoftwareKeyboardRendererBase).Assembly, padCancelIconPath, 0, 0); _keyModeIcon = LoadResource(typeof(SoftwareKeyboardRendererBase).Assembly, keyModeIconPath, 0, 0); - var panelColor = ToColor(uiTheme.DefaultBackgroundColor, 255); - var panelTransparentColor = ToColor(uiTheme.DefaultBackgroundColor, 150); - var borderColor = ToColor(uiTheme.DefaultBorderColor); - var selectionBackgroundColor = ToColor(uiTheme.SelectionBackgroundColor); + SKColor panelColor = ToColor(uiTheme.DefaultBackgroundColor, 255); + SKColor panelTransparentColor = ToColor(uiTheme.DefaultBackgroundColor, 150); + SKColor borderColor = ToColor(uiTheme.DefaultBorderColor); + SKColor selectionBackgroundColor = ToColor(uiTheme.SelectionBackgroundColor); _textNormalColor = ToColor(uiTheme.DefaultForegroundColor); _textSelectedColor = ToColor(uiTheme.SelectionForegroundColor); @@ -134,7 +134,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard { try { - using var typeface = SKTypeface.FromFamilyName(fontFamily, SKFontStyle.Normal); + using SKTypeface typeface = SKTypeface.FromFamilyName(fontFamily, SKFontStyle.Normal); _messageFont = new SKFont(typeface, 26); _inputTextFont = new SKFont(typeface, _inputTextFontSize); _labelsTextFont = new SKFont(typeface, 24); @@ -151,10 +151,10 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard private static SKColor ToColor(ThemeColor color, byte? overrideAlpha = null, bool flipRgb = false) { - var a = (byte)(color.A * 255); - var r = (byte)(color.R * 255); - var g = (byte)(color.G * 255); - var b = (byte)(color.B * 255); + byte a = (byte)(color.A * 255); + byte r = (byte)(color.R * 255); + byte g = (byte)(color.G * 255); + byte b = (byte)(color.B * 255); if (flipRgb) { @@ -177,11 +177,11 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard { Debug.Assert(resourceStream != null); - var bitmap = SKBitmap.Decode(resourceStream); + SKBitmap bitmap = SKBitmap.Decode(resourceStream); if (newHeight != 0 && newWidth != 0) { - var resized = bitmap.Resize(new SKImageInfo(newWidth, newHeight), SKFilterQuality.High); + SKBitmap resized = bitmap.Resize(new SKImageInfo(newWidth, newHeight), SKFilterQuality.High); if (resized != null) { bitmap.Dispose(); @@ -198,7 +198,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard { return; } - var canvas = _surface.Canvas; + SKCanvas canvas = _surface.Canvas; canvas.Clear(SKColors.Transparent); canvas.DrawRect(_panelRectangle, _panelBrush); @@ -219,18 +219,18 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard return; } - using var paint = new SKPaint(_messageFont) + using SKPaint paint = new SKPaint(_messageFont) { Color = _textNormalColor, IsAntialias = true }; - var canvas = _surface.Canvas; - var messageRectangle = MeasureString(MessageText, paint); + SKCanvas canvas = _surface.Canvas; + SKRect messageRectangle = MeasureString(MessageText, paint); float messagePositionX = (_panelRectangle.Width - messageRectangle.Width) / 2 - messageRectangle.Left; float messagePositionY = _messagePositionY - messageRectangle.Top; - var messagePosition = new SKPoint(messagePositionX, messagePositionY); - var messageBoundRectangle = SKRect.Create(messagePositionX, messagePositionY, messageRectangle.Width, messageRectangle.Height); + SKPoint messagePosition = new SKPoint(messagePositionX, messagePositionY); + SKRect messageBoundRectangle = SKRect.Create(messagePositionX, messagePositionY, messageRectangle.Width, messageRectangle.Height); canvas.DrawRect(messageBoundRectangle, _panelBrush); @@ -336,12 +336,12 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard private void DrawTextBox(SKCanvas canvas, SoftwareKeyboardUIState state) { - using var textPaint = new SKPaint(_labelsTextFont) + using SKPaint textPaint = new SKPaint(_labelsTextFont) { IsAntialias = true, Color = _textNormalColor }; - var inputTextRectangle = MeasureString(state.InputText, textPaint); + SKRect inputTextRectangle = MeasureString(state.InputText, textPaint); float boxWidth = (int)(Math.Max(300, inputTextRectangle.Width + inputTextRectangle.Left + 8)); float boxHeight = 32; @@ -360,7 +360,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard float inputTextX = (_panelRectangle.Width - inputTextRectangle.Width) / 2 - inputTextRectangle.Left; float inputTextY = boxY + 5; - var inputTextPosition = new SKPoint(inputTextX, inputTextY); + SKPoint inputTextPosition = new SKPoint(inputTextX, inputTextY); canvas.DrawText(state.InputText, inputTextPosition.X, inputTextPosition.Y + (_labelsTextFont.Metrics.XHeight + _labelsTextFont.Metrics.Descent), textPaint); // Draw the cursor on top of the text and redraw the text with a different color if necessary. @@ -387,8 +387,8 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard ReadOnlySpan textUntilBegin = state.InputText.AsSpan(0, state.CursorBegin); ReadOnlySpan textUntilEnd = state.InputText.AsSpan(0, state.CursorEnd); - var selectionBeginRectangle = MeasureString(textUntilBegin, textPaint); - var selectionEndRectangle = MeasureString(textUntilEnd, textPaint); + SKRect selectionBeginRectangle = MeasureString(textUntilBegin, textPaint); + SKRect selectionEndRectangle = MeasureString(textUntilEnd, textPaint); cursorVisible = true; cursorPositionXLeft = inputTextX + selectionBeginRectangle.Width + selectionBeginRectangle.Left; @@ -406,7 +406,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard int cursorBegin = Math.Min(state.InputText.Length, state.CursorBegin); ReadOnlySpan textUntilCursor = state.InputText.AsSpan(0, cursorBegin); - var cursorTextRectangle = MeasureString(textUntilCursor, textPaint); + SKRect cursorTextRectangle = MeasureString(textUntilCursor, textPaint); cursorVisible = true; cursorPositionXLeft = inputTextX + cursorTextRectangle.Width + cursorTextRectangle.Left; @@ -452,16 +452,16 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard } else { - var cursorRectangle = SKRect.Create(cursorPositionXLeft, cursorPositionYTop, cursorWidth, cursorHeight); + SKRect cursorRectangle = SKRect.Create(cursorPositionXLeft, cursorPositionYTop, cursorWidth, cursorHeight); canvas.DrawRect(cursorRectangle, cursorPen); canvas.DrawRect(cursorRectangle, cursorBrush); - using var textOverCursor = SKSurface.Create(new SKImageInfo((int)cursorRectangle.Width, (int)cursorRectangle.Height, SKColorType.Rgba8888)); - var textOverCanvas = textOverCursor.Canvas; - var textRelativePosition = new SKPoint(inputTextPosition.X - cursorRectangle.Left, inputTextPosition.Y - cursorRectangle.Top); + using SKSurface textOverCursor = SKSurface.Create(new SKImageInfo((int)cursorRectangle.Width, (int)cursorRectangle.Height, SKColorType.Rgba8888)); + SKCanvas textOverCanvas = textOverCursor.Canvas; + SKPoint textRelativePosition = new SKPoint(inputTextPosition.X - cursorRectangle.Left, inputTextPosition.Y - cursorRectangle.Top); - using var cursorPaint = new SKPaint(_inputTextFont) + using SKPaint cursorPaint = new SKPaint(_inputTextFont) { Color = cursorTextColor, IsAntialias = true @@ -469,7 +469,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard textOverCanvas.DrawText(state.InputText, textRelativePosition.X, textRelativePosition.Y + _inputTextFont.Metrics.XHeight + _inputTextFont.Metrics.Descent, cursorPaint); - var cursorPosition = new SKPoint((int)cursorRectangle.Left, (int)cursorRectangle.Top); + SKPoint cursorPosition = new SKPoint((int)cursorRectangle.Left, (int)cursorRectangle.Top); textOverCursor.Flush(); canvas.DrawSurface(textOverCursor, cursorPosition); } @@ -492,13 +492,13 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard float iconWidth = icon.Width; float iconHeight = icon.Height; - using var paint = new SKPaint(_labelsTextFont) + using SKPaint paint = new SKPaint(_labelsTextFont) { Color = _textNormalColor, IsAntialias = true }; - var labelRectangle = MeasureString(label, paint); + SKRect labelRectangle = MeasureString(label, paint); float labelPositionX = iconWidth + 8 - labelRectangle.Left; float labelPositionY = 3; @@ -514,13 +514,13 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard iconX += originX; iconY += originY; - var iconPosition = new SKPoint((int)iconX, (int)iconY); - var labelPosition = new SKPoint(labelPositionX + originX, labelPositionY + originY); + SKPoint iconPosition = new SKPoint((int)iconX, (int)iconY); + SKPoint labelPosition = new SKPoint(labelPositionX + originX, labelPositionY + originY); - var selectedRectangle = SKRect.Create(originX - 2 * _padPressedPenWidth, originY - 2 * _padPressedPenWidth, + SKRect selectedRectangle = SKRect.Create(originX - 2 * _padPressedPenWidth, originY - 2 * _padPressedPenWidth, fullWidth + 4 * _padPressedPenWidth, fullHeight + 4 * _padPressedPenWidth); - var boundRectangle = SKRect.Create(originX, originY, fullWidth, fullHeight); + SKRect boundRectangle = SKRect.Create(originX, originY, fullWidth, fullHeight); boundRectangle.Inflate(4 * _padPressedPenWidth, 4 * _padPressedPenWidth); canvas.DrawRect(boundRectangle, _panelBrush); @@ -545,12 +545,12 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard private void DrawControllerToggle(SKCanvas canvas, SKPoint point) { - using var paint = new SKPaint(_labelsTextFont) + using SKPaint paint = new SKPaint(_labelsTextFont) { IsAntialias = true, Color = _textNormalColor }; - var labelRectangle = MeasureString(ControllerToggleText, paint); + SKRect labelRectangle = MeasureString(ControllerToggleText, paint); // Use relative positions so we can center the entire drawing later. @@ -574,8 +574,8 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard keyX += originX; keyY += originY; - var labelPosition = new SKPoint(labelPositionX + originX, labelPositionY + originY); - var overlayPosition = new SKPoint((int)keyX, (int)keyY); + SKPoint labelPosition = new SKPoint(labelPositionX + originX, labelPositionY + originY); + SKPoint overlayPosition = new SKPoint((int)keyX, (int)keyY); canvas.DrawBitmap(_keyModeIcon, overlayPosition); canvas.DrawText(ControllerToggleText, labelPosition.X, labelPosition.Y + _labelsTextFont.Metrics.XHeight, paint); @@ -593,7 +593,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard // Convert the pixel format used in the image to the one used in the Switch surface. _surface.Flush(); - var buffer = new byte[_imageInfo.BytesSize]; + byte[] buffer = new byte[_imageInfo.BytesSize]; fixed (byte* bufferPtr = buffer) { if (!_surface.ReadPixels(_imageInfo, (nint)bufferPtr, _imageInfo.RowBytes, 0, 0)) diff --git a/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/TimedAction.cs b/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/TimedAction.cs index a8b137df2..e98dadb77 100644 --- a/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/TimedAction.cs +++ b/src/Ryujinx.HLE/HOS/Applets/SoftwareKeyboard/TimedAction.cs @@ -79,11 +79,11 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard public void Reset(Action action, int totalMilliseconds, int sleepMilliseconds) { // Create a dedicated cancel token for each task. - var cancelled = new TRef(false); + TRef cancelled = new TRef(false); Reset(new Thread(() => { - var substepData = new SleepSubstepData(sleepMilliseconds); + SleepSubstepData substepData = new SleepSubstepData(sleepMilliseconds); int totalCount = totalMilliseconds / sleepMilliseconds; int totalRemainder = totalMilliseconds - totalCount * sleepMilliseconds; @@ -126,11 +126,11 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard public void Reset(Action action, int sleepMilliseconds) { // Create a dedicated cancel token for each task. - var cancelled = new TRef(false); + TRef cancelled = new TRef(false); Reset(new Thread(() => { - var substepData = new SleepSubstepData(sleepMilliseconds); + SleepSubstepData substepData = new SleepSubstepData(sleepMilliseconds); while (!Volatile.Read(ref cancelled.Value)) { @@ -147,7 +147,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard public void Reset(Action action) { // Create a dedicated cancel token for each task. - var cancelled = new TRef(false); + TRef cancelled = new TRef(false); Reset(new Thread(() => { diff --git a/src/Ryujinx.HLE/HOS/ArmProcessContextFactory.cs b/src/Ryujinx.HLE/HOS/ArmProcessContextFactory.cs index 14775fb1d..621a081fd 100644 --- a/src/Ryujinx.HLE/HOS/ArmProcessContextFactory.cs +++ b/src/Ryujinx.HLE/HOS/ArmProcessContextFactory.cs @@ -51,8 +51,8 @@ namespace Ryujinx.HLE.HOS if (OperatingSystem.IsMacOS() && isArm64Host && for64Bit && context.Device.Configuration.UseHypervisor) { - var cpuEngine = new HvEngine(_tickSource); - var memoryManager = new HvMemoryManager(context.Memory, addressSpaceSize, invalidAccessHandler); + HvEngine cpuEngine = new HvEngine(_tickSource); + HvMemoryManager memoryManager = new HvMemoryManager(context.Memory, addressSpaceSize, invalidAccessHandler); processContext = new ArmProcessContext(pid, cpuEngine, _gpu, memoryManager, addressSpaceSize, for64Bit); } else @@ -86,7 +86,7 @@ namespace Ryujinx.HLE.HOS switch (mode) { case MemoryManagerMode.SoftwarePageTable: - var memoryManager = new MemoryManager(context.Memory, addressSpaceSize, invalidAccessHandler); + MemoryManager memoryManager = new MemoryManager(context.Memory, addressSpaceSize, invalidAccessHandler); processContext = new ArmProcessContext(pid, cpuEngine, _gpu, memoryManager, addressSpaceSize, for64Bit); break; @@ -94,7 +94,7 @@ namespace Ryujinx.HLE.HOS case MemoryManagerMode.HostMappedUnsafe: if (addressSpace == null) { - var memoryManagerHostTracked = new MemoryManagerHostTracked(context.Memory, addressSpaceSize, mode == MemoryManagerMode.HostMappedUnsafe, invalidAccessHandler); + MemoryManagerHostTracked memoryManagerHostTracked = new MemoryManagerHostTracked(context.Memory, addressSpaceSize, mode == MemoryManagerMode.HostMappedUnsafe, invalidAccessHandler); processContext = new ArmProcessContext(pid, cpuEngine, _gpu, memoryManagerHostTracked, addressSpaceSize, for64Bit); } else @@ -104,7 +104,7 @@ namespace Ryujinx.HLE.HOS Logger.Warning?.Print(LogClass.Emulation, $"Allocated address space (0x{addressSpace.AddressSpaceSize:X}) is smaller than guest application requirements (0x{addressSpaceSize:X})"); } - var memoryManagerHostMapped = new MemoryManagerHostMapped(addressSpace, mode == MemoryManagerMode.HostMappedUnsafe, invalidAccessHandler); + MemoryManagerHostMapped memoryManagerHostMapped = new MemoryManagerHostMapped(addressSpace, mode == MemoryManagerMode.HostMappedUnsafe, invalidAccessHandler); processContext = new ArmProcessContext(pid, cpuEngine, _gpu, memoryManagerHostMapped, addressSpace.AddressSpaceSize, for64Bit); } break; diff --git a/src/Ryujinx.HLE/HOS/Diagnostics/Demangler/Demangler.cs b/src/Ryujinx.HLE/HOS/Diagnostics/Demangler/Demangler.cs index 2e7b8ee76..59ce69b73 100644 --- a/src/Ryujinx.HLE/HOS/Diagnostics/Demangler/Demangler.cs +++ b/src/Ryujinx.HLE/HOS/Diagnostics/Demangler/Demangler.cs @@ -32,7 +32,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler private bool ConsumeIf(string toConsume) { - var mangledPart = Mangled.AsSpan(_position); + ReadOnlySpan mangledPart = Mangled.AsSpan(_position); if (mangledPart.StartsWith(toConsume.AsSpan())) { diff --git a/src/Ryujinx.HLE/HOS/Horizon.cs b/src/Ryujinx.HLE/HOS/Horizon.cs index 627b649df..e0dd0f1c9 100644 --- a/src/Ryujinx.HLE/HOS/Horizon.cs +++ b/src/Ryujinx.HLE/HOS/Horizon.cs @@ -154,11 +154,11 @@ namespace Ryujinx.HLE.HOS timePageList.AddRange(timePa, TimeSize / KPageTableBase.PageSize); appletCaptureBufferPageList.AddRange(appletCaptureBufferPa, AppletCaptureBufferSize / KPageTableBase.PageSize); - var hidStorage = new SharedMemoryStorage(KernelContext, hidPageList); - var fontStorage = new SharedMemoryStorage(KernelContext, fontPageList); - var iirsStorage = new SharedMemoryStorage(KernelContext, iirsPageList); - var timeStorage = new SharedMemoryStorage(KernelContext, timePageList); - var appletCaptureBufferStorage = new SharedMemoryStorage(KernelContext, appletCaptureBufferPageList); + SharedMemoryStorage hidStorage = new SharedMemoryStorage(KernelContext, hidPageList); + SharedMemoryStorage fontStorage = new SharedMemoryStorage(KernelContext, fontPageList); + SharedMemoryStorage iirsStorage = new SharedMemoryStorage(KernelContext, iirsPageList); + SharedMemoryStorage timeStorage = new SharedMemoryStorage(KernelContext, timePageList); + SharedMemoryStorage appletCaptureBufferStorage = new SharedMemoryStorage(KernelContext, appletCaptureBufferPageList); HidStorage = hidStorage; @@ -265,7 +265,7 @@ namespace Ryujinx.HLE.HOS HorizonFsClient fsClient = new(this); ServiceTable = new ServiceTable(); - var services = ServiceTable.GetServices(new HorizonOptions + IEnumerable services = ServiceTable.GetServices(new HorizonOptions (Device.Configuration.IgnoreMissingServices, LibHacHorizonManager.BcatClient, fsClient, @@ -273,7 +273,7 @@ namespace Ryujinx.HLE.HOS Device.AudioDeviceDriver, TickSource)); - foreach (var service in services) + foreach (ServiceEntry service in services) { const ProcessCreationFlags Flags = ProcessCreationFlags.EnableAslr | @@ -304,7 +304,7 @@ namespace Ryujinx.HLE.HOS public bool LoadKip(string kipPath) { - using var kipFile = new SharedRef(new LocalStorage(kipPath, FileAccess.Read)); + using SharedRef kipFile = new SharedRef(new LocalStorage(kipPath, FileAccess.Read)); return ProcessLoaderHelper.LoadKip(KernelContext, new KipExecutable(in kipFile)); } diff --git a/src/Ryujinx.HLE/HOS/HorizonFsClient.cs b/src/Ryujinx.HLE/HOS/HorizonFsClient.cs index 3dbafa88b..67b3d9b14 100644 --- a/src/Ryujinx.HLE/HOS/HorizonFsClient.cs +++ b/src/Ryujinx.HLE/HOS/HorizonFsClient.cs @@ -55,8 +55,8 @@ namespace Ryujinx.HLE.HOS Nca nca = new(_system.KeySet, ncaStorage); - using var ncaFileSystem = nca.OpenFileSystem(NcaSectionType.Data, _system.FsIntegrityCheckLevel); - using var ncaFsRef = new UniqueRef(ncaFileSystem); + using IFileSystem ncaFileSystem = nca.OpenFileSystem(NcaSectionType.Data, _system.FsIntegrityCheckLevel); + using UniqueRef ncaFsRef = new UniqueRef(ncaFileSystem); Result result = _fsClient.Register(mountName.ToU8Span(), ref ncaFsRef.Ref).ToHorizonResult(); if (result.IsFailure) @@ -86,7 +86,7 @@ namespace Ryujinx.HLE.HOS public Result OpenFile(out FileHandle handle, string path, OpenMode openMode) { - var result = _fsClient.OpenFile(out var libhacHandle, path.ToU8Span(), (LibHac.Fs.OpenMode)openMode); + LibHac.Result result = _fsClient.OpenFile(out LibHac.Fs.FileHandle libhacHandle, path.ToU8Span(), (LibHac.Fs.OpenMode)openMode); handle = new(libhacHandle); return result.ToHorizonResult(); diff --git a/src/Ryujinx.HLE/HOS/Kernel/Memory/KMemoryManager.cs b/src/Ryujinx.HLE/HOS/Kernel/Memory/KMemoryManager.cs index e56304d9d..a27bb0074 100644 --- a/src/Ryujinx.HLE/HOS/Kernel/Memory/KMemoryManager.cs +++ b/src/Ryujinx.HLE/HOS/Kernel/Memory/KMemoryManager.cs @@ -16,7 +16,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory { for (int i = 0; i < MemoryRegions.Length; i++) { - var region = MemoryRegions[i]; + KMemoryRegionManager region = MemoryRegions[i]; if (address >= region.Address && address < region.EndAddr) { @@ -41,7 +41,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory { while (pagesCount != 0) { - var region = GetMemoryRegion(address); + KMemoryRegionManager region = GetMemoryRegion(address); ulong countToProcess = Math.Min(pagesCount, region.GetPageOffsetFromEnd(address)); diff --git a/src/Ryujinx.HLE/HOS/Kernel/Memory/KMemoryRegionManager.cs b/src/Ryujinx.HLE/HOS/Kernel/Memory/KMemoryRegionManager.cs index 2eff616c4..270c4ff32 100644 --- a/src/Ryujinx.HLE/HOS/Kernel/Memory/KMemoryRegionManager.cs +++ b/src/Ryujinx.HLE/HOS/Kernel/Memory/KMemoryRegionManager.cs @@ -40,7 +40,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory if (result == Result.Success) { - foreach (var node in pageList) + foreach (KPageNode node in pageList) { IncrementPagesReferenceCount(node.Address, node.PagesCount); } diff --git a/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageBitmap.cs b/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageBitmap.cs index 947983d61..a044ba8b3 100644 --- a/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageBitmap.cs +++ b/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageBitmap.cs @@ -162,7 +162,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory public bool ClearRange(ulong offset, int count) { int depth = HighestDepthIndex; - var bits = _bitStorages[depth]; + ArraySegment bits = _bitStorages[depth]; int bitInd = (int)(offset / UInt64BitSize); diff --git a/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageHeap.cs b/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageHeap.cs index ee5d6e2b6..3c3c83bb9 100644 --- a/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageHeap.cs +++ b/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageHeap.cs @@ -105,7 +105,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory _blocksCount = blockShifts.Length; _blocks = new Block[_memoryBlockPageShifts.Length]; - var currBitmapStorage = new ArraySegment(new ulong[CalculateManagementOverheadSize(size, blockShifts)]); + ArraySegment currBitmapStorage = new ArraySegment(new ulong[CalculateManagementOverheadSize(size, blockShifts)]); for (int i = 0; i < blockShifts.Length; i++) { diff --git a/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageList.cs b/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageList.cs index 60514824a..38e2b6f95 100644 --- a/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageList.cs +++ b/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageList.cs @@ -70,7 +70,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory public void IncrementPagesReferenceCount(KMemoryManager manager) { - foreach (var node in this) + foreach (KPageNode node in this) { manager.IncrementPagesReferenceCount(node.Address, node.PagesCount); } @@ -78,7 +78,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory public void DecrementPagesReferenceCount(KMemoryManager manager) { - foreach (var node in this) + foreach (KPageNode node in this) { manager.DecrementPagesReferenceCount(node.Address, node.PagesCount); } diff --git a/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageTable.cs b/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageTable.cs index 4ffa447dd..8258c16c8 100644 --- a/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageTable.cs +++ b/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageTable.cs @@ -28,8 +28,8 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory /// protected override void GetPhysicalRegions(ulong va, ulong size, KPageList pageList) { - var ranges = _cpuMemory.GetPhysicalRegions(va, size); - foreach (var range in ranges) + IEnumerable ranges = _cpuMemory.GetPhysicalRegions(va, size); + foreach (MemoryRange range in ranges) { pageList.AddRange(range.Address + DramMemoryMap.DramBase, range.Size / PageSize); } @@ -143,11 +143,11 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory bool shouldFillPages, byte fillValue) { - using var scopedPageList = new KScopedPageList(Context.MemoryManager, pageList); + using KScopedPageList scopedPageList = new KScopedPageList(Context.MemoryManager, pageList); ulong currentVa = address; - foreach (var pageNode in pageList) + foreach (KPageNode pageNode in pageList) { ulong addr = pageNode.Address - DramMemoryMap.DramBase; ulong size = pageNode.PagesCount * PageSize; @@ -188,16 +188,16 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory } } - using var scopedPageList = new KScopedPageList(Context.MemoryManager, pageList); + using KScopedPageList scopedPageList = new KScopedPageList(Context.MemoryManager, pageList); - foreach (var pageNode in pageList) + foreach (KPageNode pageNode in pageList) { Context.CommitMemory(pageNode.Address - DramMemoryMap.DramBase, pageNode.PagesCount * PageSize); } ulong offset = 0; - foreach (var region in regions) + foreach (HostMemoryRange region in regions) { _cpuMemory.MapForeign(va + offset, region.Address, region.Size); @@ -214,9 +214,9 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory { KPageList pagesToClose = new(); - var regions = _cpuMemory.GetPhysicalRegions(address, pagesCount * PageSize); + IEnumerable regions = _cpuMemory.GetPhysicalRegions(address, pagesCount * PageSize); - foreach (var region in regions) + foreach (MemoryRange region in regions) { ulong pa = region.Address + DramMemoryMap.DramBase; if (DramMemoryMap.IsHeapPhysicalAddress(pa)) diff --git a/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageTableBase.cs b/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageTableBase.cs index bf2bbb97b..1b7cd7cad 100644 --- a/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageTableBase.cs +++ b/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageTableBase.cs @@ -617,7 +617,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory return result; } - using var _ = new OnScopeExit(() => pageList.DecrementPagesReferenceCount(Context.MemoryManager)); + using OnScopeExit _ = new OnScopeExit(() => pageList.DecrementPagesReferenceCount(Context.MemoryManager)); return MapPages(address, pageList, permission, MemoryMapFlags.Private); } @@ -769,7 +769,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory Result result = region.AllocatePages(out KPageList pageList, pagesCount); - using var _ = new OnScopeExit(() => pageList.DecrementPagesReferenceCount(Context.MemoryManager)); + using OnScopeExit _ = new OnScopeExit(() => pageList.DecrementPagesReferenceCount(Context.MemoryManager)); void CleanUpForError() { @@ -1341,7 +1341,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory Result result = region.AllocatePages(out KPageList pageList, remainingPages); - using var _ = new OnScopeExit(() => pageList.DecrementPagesReferenceCount(Context.MemoryManager)); + using OnScopeExit _ = new OnScopeExit(() => pageList.DecrementPagesReferenceCount(Context.MemoryManager)); void CleanUpForError() { @@ -1867,7 +1867,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory ulong dstLastPagePa = 0; ulong currentVa = va; - using var _ = new OnScopeExit(() => + using OnScopeExit _ = new OnScopeExit(() => { if (dstFirstPagePa != 0) { @@ -1928,7 +1928,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory Context.Memory.Fill(GetDramAddressFromPa(dstFirstPagePa), unusedSizeBefore, (byte)_ipcFillValue); ulong copySize = addressRounded <= endAddr ? addressRounded - address : size; - var data = srcPageTable.GetReadOnlySequence(addressTruncated + unusedSizeBefore, (int)copySize); + ReadOnlySequence data = srcPageTable.GetReadOnlySequence(addressTruncated + unusedSizeBefore, (int)copySize); ((IWritableBlock)Context.Memory).Write(GetDramAddressFromPa(dstFirstPagePa + unusedSizeBefore), data); @@ -1994,7 +1994,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory if (send) { ulong copySize = endAddr - endAddrTruncated; - var data = srcPageTable.GetReadOnlySequence(endAddrTruncated, (int)copySize); + ReadOnlySequence data = srcPageTable.GetReadOnlySequence(endAddrTruncated, (int)copySize); ((IWritableBlock)Context.Memory).Write(GetDramAddressFromPa(dstLastPagePa), data); diff --git a/src/Ryujinx.HLE/HOS/Kernel/Process/HleProcessDebugger.cs b/src/Ryujinx.HLE/HOS/Kernel/Process/HleProcessDebugger.cs index ff3de4a17..a9f87f2ca 100644 --- a/src/Ryujinx.HLE/HOS/Kernel/Process/HleProcessDebugger.cs +++ b/src/Ryujinx.HLE/HOS/Kernel/Process/HleProcessDebugger.cs @@ -1,3 +1,4 @@ +using Ryujinx.Cpu; using Ryujinx.HLE.HOS.Diagnostics.Demangler; using Ryujinx.HLE.HOS.Kernel.Memory; using Ryujinx.HLE.HOS.Kernel.Threading; @@ -47,7 +48,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Process { EnsureLoaded(); - var context = thread.Context; + IExecutionContext context = thread.Context; StringBuilder trace = new(); @@ -109,13 +110,13 @@ namespace Ryujinx.HLE.HOS.Kernel.Process { EnsureLoaded(); - var context = thread.Context; + IExecutionContext context = thread.Context; StringBuilder sb = new(); string GetReg(int x) { - var v = x == 32 ? context.Pc : context.GetX(x); + ulong v = x == 32 ? context.Pc : context.GetX(x); if (!AnalyzePointer(out PointerInfo info, v, thread)) { return $"0x{v:x16}"; @@ -251,7 +252,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Process info = default; ulong sp = thread.Context.GetX(31); - var memoryInfo = _owner.MemoryManager.QueryMemory(address); + KMemoryInfo memoryInfo = _owner.MemoryManager.QueryMemory(address); MemoryState memoryState = memoryInfo.State; if (!memoryState.HasFlag(MemoryState.Stack)) // Is this pointer within the stack? diff --git a/src/Ryujinx.HLE/HOS/Kernel/SupervisorCall/Syscall.cs b/src/Ryujinx.HLE/HOS/Kernel/SupervisorCall/Syscall.cs index 1b6433af6..c439a8fff 100644 --- a/src/Ryujinx.HLE/HOS/Kernel/SupervisorCall/Syscall.cs +++ b/src/Ryujinx.HLE/HOS/Kernel/SupervisorCall/Syscall.cs @@ -105,7 +105,7 @@ namespace Ryujinx.HLE.HOS.Kernel.SupervisorCall KProcess process = new(_context); - using var _ = new OnScopeExit(process.DecrementReferenceCount); + using OnScopeExit _ = new OnScopeExit(process.DecrementReferenceCount); KResourceLimit resourceLimit; @@ -1425,7 +1425,7 @@ namespace Ryujinx.HLE.HOS.Kernel.SupervisorCall KCodeMemory codeMemory = new(_context); - using var _ = new OnScopeExit(codeMemory.DecrementReferenceCount); + using OnScopeExit _ = new OnScopeExit(codeMemory.DecrementReferenceCount); KProcess currentProcess = KernelStatic.GetCurrentProcess(); @@ -2854,7 +2854,7 @@ namespace Ryujinx.HLE.HOS.Kernel.SupervisorCall KThread currentThread = KernelStatic.GetCurrentThread(); - var syncObjs = new Span(currentThread.WaitSyncObjects)[..handles.Length]; + Span syncObjs = new Span(currentThread.WaitSyncObjects)[..handles.Length]; if (handles.Length != 0) { diff --git a/src/Ryujinx.HLE/HOS/Kernel/Threading/KAddressArbiter.cs b/src/Ryujinx.HLE/HOS/Kernel/Threading/KAddressArbiter.cs index 0c63c7e0e..ca4aedb7a 100644 --- a/src/Ryujinx.HLE/HOS/Kernel/Threading/KAddressArbiter.cs +++ b/src/Ryujinx.HLE/HOS/Kernel/Threading/KAddressArbiter.cs @@ -562,8 +562,8 @@ namespace Ryujinx.HLE.HOS.Kernel.Threading Action removeCallback, Func predicate) { - var candidates = threads.Where(predicate).OrderBy(x => x.DynamicPriority); - var toSignal = (count > 0 ? candidates.Take(count) : candidates).ToArray(); + IOrderedEnumerable candidates = threads.Where(predicate).OrderBy(x => x.DynamicPriority); + KThread[] toSignal = (count > 0 ? candidates.Take(count) : candidates).ToArray(); foreach (KThread thread in toSignal) { diff --git a/src/Ryujinx.HLE/HOS/Kernel/Threading/KPriorityQueue.cs b/src/Ryujinx.HLE/HOS/Kernel/Threading/KPriorityQueue.cs index 1608db095..7951fab5b 100644 --- a/src/Ryujinx.HLE/HOS/Kernel/Threading/KPriorityQueue.cs +++ b/src/Ryujinx.HLE/HOS/Kernel/Threading/KPriorityQueue.cs @@ -127,7 +127,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Threading public KThread ScheduledThreadsElementAtOrDefault(int core, int index) { int currentIndex = 0; - foreach (var scheduledThread in ScheduledThreads(core)) + foreach (KThread scheduledThread in ScheduledThreads(core)) { if (currentIndex == index) { @@ -144,7 +144,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Threading public KThread ScheduledThreadsWithDynamicPriorityFirstOrDefault(int core, int dynamicPriority) { - foreach (var scheduledThread in ScheduledThreads(core)) + foreach (KThread scheduledThread in ScheduledThreads(core)) { if (scheduledThread.DynamicPriority == dynamicPriority) { diff --git a/src/Ryujinx.HLE/HOS/Kernel/Threading/KThread.cs b/src/Ryujinx.HLE/HOS/Kernel/Threading/KThread.cs index 35ff74cb3..ce0810990 100644 --- a/src/Ryujinx.HLE/HOS/Kernel/Threading/KThread.cs +++ b/src/Ryujinx.HLE/HOS/Kernel/Threading/KThread.cs @@ -1232,7 +1232,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Threading { if (_schedulerWaitEvent == null) { - var schedulerWaitEvent = new ManualResetEvent(false); + ManualResetEvent schedulerWaitEvent = new ManualResetEvent(false); if (Interlocked.Exchange(ref _schedulerWaitEvent, schedulerWaitEvent) == null) { diff --git a/src/Ryujinx.HLE/HOS/LibHacHorizonManager.cs b/src/Ryujinx.HLE/HOS/LibHacHorizonManager.cs index e8ef15dce..46c27da40 100644 --- a/src/Ryujinx.HLE/HOS/LibHacHorizonManager.cs +++ b/src/Ryujinx.HLE/HOS/LibHacHorizonManager.cs @@ -54,7 +54,7 @@ namespace Ryujinx.HLE.HOS public void InitializeFsServer(VirtualFileSystem virtualFileSystem) { - virtualFileSystem.InitializeFsServer(Server, out var fsClient); + virtualFileSystem.InitializeFsServer(Server, out HorizonClient fsClient); FsClient = fsClient; } diff --git a/src/Ryujinx.HLE/HOS/ModLoader.cs b/src/Ryujinx.HLE/HOS/ModLoader.cs index 4bd695ae5..76edcc322 100644 --- a/src/Ryujinx.HLE/HOS/ModLoader.cs +++ b/src/Ryujinx.HLE/HOS/ModLoader.cs @@ -3,6 +3,7 @@ using LibHac.Fs; using LibHac.Fs.Fsa; using LibHac.FsSystem; using LibHac.Loader; +using LibHac.Tools.Fs; using LibHac.Tools.FsSystem; using LibHac.Tools.FsSystem.RomFs; using Ryujinx.Common.Configuration; @@ -143,7 +144,7 @@ namespace Ryujinx.HLE.HOS private static string EnsureBaseDirStructure(string modsBasePath) { - var modsDir = new DirectoryInfo(modsBasePath); + DirectoryInfo modsDir = new DirectoryInfo(modsBasePath); modsDir.CreateSubdirectory(AmsContentsDir); modsDir.CreateSubdirectory(AmsNsoPatchDir); @@ -161,23 +162,23 @@ namespace Ryujinx.HLE.HOS { System.Text.StringBuilder types = new(); - foreach (var modDir in dir.EnumerateDirectories()) + foreach (DirectoryInfo modDir in dir.EnumerateDirectories()) { types.Clear(); Mod mod = new(string.Empty, null, true); if (StrEquals(RomfsDir, modDir.Name)) { - var modData = modMetadata.Mods.FirstOrDefault(x => modDir.FullName.Contains(x.Path)); - var enabled = modData?.Enabled ?? true; + Mod modData = modMetadata.Mods.FirstOrDefault(x => modDir.FullName.Contains(x.Path)); + bool enabled = modData?.Enabled ?? true; mods.RomfsDirs.Add(mod = new Mod(dir.Name, modDir, enabled)); types.Append('R'); } else if (StrEquals(ExefsDir, modDir.Name)) { - var modData = modMetadata.Mods.FirstOrDefault(x => modDir.FullName.Contains(x.Path)); - var enabled = modData?.Enabled ?? true; + Mod modData = modMetadata.Mods.FirstOrDefault(x => modDir.FullName.Contains(x.Path)); + bool enabled = modData?.Enabled ?? true; mods.ExefsDirs.Add(mod = new Mod(dir.Name, modDir, enabled)); types.Append('E'); @@ -200,8 +201,8 @@ namespace Ryujinx.HLE.HOS public static string GetApplicationDir(string modsBasePath, string applicationId) { - var contentsDir = new DirectoryInfo(Path.Combine(modsBasePath, AmsContentsDir)); - var applicationModsPath = FindApplicationDir(contentsDir, applicationId); + DirectoryInfo contentsDir = new DirectoryInfo(Path.Combine(modsBasePath, AmsContentsDir)); + DirectoryInfo applicationModsPath = FindApplicationDir(contentsDir, applicationId); if (applicationModsPath == null) { @@ -243,7 +244,7 @@ namespace Ryujinx.HLE.HOS return; } - foreach (var modDir in patchDir.EnumerateDirectories()) + foreach (DirectoryInfo modDir in patchDir.EnumerateDirectories()) { patches.Add(new Mod(modDir.Name, modDir, true)); Logger.Info?.Print(LogClass.ModLoader, $"Found {type} patch '{modDir.Name}'"); @@ -272,11 +273,11 @@ namespace Ryujinx.HLE.HOS } } - var fsFile = new FileInfo(Path.Combine(applicationDir.FullName, RomfsContainer)); + FileInfo fsFile = new FileInfo(Path.Combine(applicationDir.FullName, RomfsContainer)); if (fsFile.Exists) { - var modData = modMetadata.Mods.FirstOrDefault(x => fsFile.FullName.Contains(x.Path)); - var enabled = modData == null || modData.Enabled; + Mod modData = modMetadata.Mods.FirstOrDefault(x => fsFile.FullName.Contains(x.Path)); + bool enabled = modData == null || modData.Enabled; mods.RomfsContainers.Add(new Mod($"<{applicationDir.Name} RomFs>", fsFile, enabled)); } @@ -284,8 +285,8 @@ namespace Ryujinx.HLE.HOS fsFile = new FileInfo(Path.Combine(applicationDir.FullName, ExefsContainer)); if (fsFile.Exists) { - var modData = modMetadata.Mods.FirstOrDefault(x => fsFile.FullName.Contains(x.Path)); - var enabled = modData == null || modData.Enabled; + Mod modData = modMetadata.Mods.FirstOrDefault(x => fsFile.FullName.Contains(x.Path)); + bool enabled = modData == null || modData.Enabled; mods.ExefsContainers.Add(new Mod($"<{applicationDir.Name} ExeFs>", fsFile, enabled)); } @@ -302,7 +303,7 @@ namespace Ryujinx.HLE.HOS Logger.Info?.Print(LogClass.ModLoader, $"Searching mods for {((applicationId & 0x1000) != 0 ? "DLC" : "Application")} {applicationId:X16} in \"{contentsDir.FullName}\""); - var applicationDir = FindApplicationDir(contentsDir, $"{applicationId:x16}"); + DirectoryInfo applicationDir = FindApplicationDir(contentsDir, $"{applicationId:x16}"); if (applicationDir != null) { @@ -429,9 +430,9 @@ namespace Ryujinx.HLE.HOS return false; } - foreach (var path in searchDirPaths) + foreach (string path in searchDirPaths) { - var searchDir = new DirectoryInfo(path); + DirectoryInfo searchDir = new DirectoryInfo(path); if (!searchDir.Exists) { Logger.Warning?.Print(LogClass.ModLoader, $"Mod Search Dir '{searchDir.FullName}' doesn't exist"); @@ -440,7 +441,7 @@ namespace Ryujinx.HLE.HOS if (!TryQuery(searchDir, patches, modCaches)) { - foreach (var subdir in searchDir.EnumerateDirectories()) + foreach (DirectoryInfo subdir in searchDir.EnumerateDirectories()) { TryQuery(subdir, patches, modCaches); } @@ -469,14 +470,14 @@ namespace Ryujinx.HLE.HOS return baseStorage; } - var fileSet = new HashSet(); - var builder = new RomFsBuilder(); + HashSet fileSet = new HashSet(); + RomFsBuilder builder = new RomFsBuilder(); int count = 0; Logger.Info?.Print(LogClass.ModLoader, $"Applying RomFS mods for Application {applicationId:X16}"); // Prioritize loose files first - foreach (var mod in mods.RomfsDirs) + foreach (Mod mod in mods.RomfsDirs) { if (!mod.Enabled) { @@ -491,7 +492,7 @@ namespace Ryujinx.HLE.HOS } // Then files inside images - foreach (var mod in mods.RomfsContainers) + foreach (Mod mod in mods.RomfsContainers) { if (!mod.Enabled) { @@ -516,12 +517,12 @@ namespace Ryujinx.HLE.HOS Logger.Info?.Print(LogClass.ModLoader, $"Replaced {fileSet.Count} file(s) over {count} mod(s). Processing base storage..."); // And finally, the base romfs - var baseRom = new RomFsFileSystem(baseStorage); - foreach (var entry in baseRom.EnumerateEntries() + RomFsFileSystem baseRom = new RomFsFileSystem(baseStorage); + foreach (DirectoryEntryEx entry in baseRom.EnumerateEntries() .Where(f => f.Type == DirectoryEntryType.File && !fileSet.Contains(f.FullPath)) .OrderBy(f => f.FullPath, StringComparer.Ordinal)) { - using var file = new UniqueRef(); + using UniqueRef file = new UniqueRef(); baseRom.OpenFile(ref file.Ref, entry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); builder.AddFile(entry.FullPath, file.Release()); @@ -536,12 +537,12 @@ namespace Ryujinx.HLE.HOS private static void AddFiles(IFileSystem fs, string modName, string rootPath, ISet fileSet, RomFsBuilder builder) { - foreach (var entry in fs.EnumerateEntries() + foreach (DirectoryEntryEx entry in fs.EnumerateEntries() .AsParallel() .Where(f => f.Type == DirectoryEntryType.File) .OrderBy(f => f.FullPath, StringComparer.Ordinal)) { - var file = new LazyFile(entry.FullPath, rootPath, fs); + LazyFile file = new LazyFile(entry.FullPath, rootPath, fs); if (fileSet.Add(entry.FullPath)) { @@ -568,7 +569,7 @@ namespace Ryujinx.HLE.HOS Logger.Info?.Print(LogClass.ModLoader, "Using replacement ExeFS partition"); - var pfs = new PartitionFileSystem(); + PartitionFileSystem pfs = new PartitionFileSystem(); pfs.Initialize(mods.ExefsContainers[0].Path.OpenRead().AsStorage()).ThrowIfFailure(); exefs = pfs; @@ -602,9 +603,9 @@ namespace Ryujinx.HLE.HOS throw new ArgumentOutOfRangeException(nameof(nsos), nsos.Length, "NSO Count is incorrect"); } - var exeMods = mods.ExefsDirs; + List> exeMods = mods.ExefsDirs; - foreach (var mod in exeMods) + foreach (Mod mod in exeMods) { if (!mod.Enabled) { @@ -613,7 +614,7 @@ namespace Ryujinx.HLE.HOS for (int i = 0; i < ProcessConst.ExeFsPrefixes.Length; ++i) { - var nsoName = ProcessConst.ExeFsPrefixes[i]; + string nsoName = ProcessConst.ExeFsPrefixes[i]; FileInfo nsoFile = new(Path.Combine(mod.Path.FullName, nsoName)); if (nsoFile.Exists) @@ -665,7 +666,7 @@ namespace Ryujinx.HLE.HOS internal void ApplyNroPatches(NroExecutable nro) { - var nroPatches = _patches.NroPatches; + List> nroPatches = _patches.NroPatches; if (nroPatches.Count == 0) { @@ -707,11 +708,11 @@ namespace Ryujinx.HLE.HOS return; } - var cheats = mods.Cheats; - var processExes = tamperInfo.BuildIds.Zip(tamperInfo.CodeAddresses, (k, v) => new { k, v }) + List cheats = mods.Cheats; + Dictionary processExes = tamperInfo.BuildIds.Zip(tamperInfo.CodeAddresses, (k, v) => new { k, v }) .ToDictionary(x => x.k[..Math.Min(Cheat.CheatIdSize, x.k.Length)], x => x.v); - foreach (var cheat in cheats) + foreach (Cheat cheat in cheats) { string cheatId = Path.GetFileNameWithoutExtension(cheat.Path.Name).ToUpper(); @@ -732,7 +733,7 @@ namespace Ryujinx.HLE.HOS internal static void EnableCheats(ulong applicationId, TamperMachine tamperMachine) { - var contentDirectory = FindApplicationDir(new DirectoryInfo(Path.Combine(GetModsBasePath(), AmsContentsDir)), $"{applicationId:x16}"); + DirectoryInfo contentDirectory = FindApplicationDir(new DirectoryInfo(Path.Combine(GetModsBasePath(), AmsContentsDir)), $"{applicationId:x16}"); string enabledCheatsPath = Path.Combine(contentDirectory.FullName, CheatDir, "enabled.txt"); if (File.Exists(enabledCheatsPath)) @@ -752,11 +753,11 @@ namespace Ryujinx.HLE.HOS patches[i] = new MemPatch(); } - var buildIds = new List(programs.Length); + List buildIds = new List(programs.Length); foreach (IExecutable p in programs) { - var buildId = p switch + string buildId = p switch { NsoExecutable nso => Convert.ToHexString(nso.BuildId.ItemsRo.ToArray()).TrimEnd('0'), NroExecutable nro => Convert.ToHexString(nro.Header.BuildId).TrimEnd('0'), @@ -768,15 +769,15 @@ namespace Ryujinx.HLE.HOS int GetIndex(string buildId) => buildIds.FindIndex(id => id == buildId); // O(n) but list is small // Collect patches - foreach (var mod in mods) + foreach (Mod mod in mods) { if (!mod.Enabled) { continue; } - var patchDir = mod.Path; - foreach (var patchFile in patchDir.EnumerateFiles()) + DirectoryInfo patchDir = mod.Path; + foreach (FileInfo patchFile in patchDir.EnumerateFiles()) { if (StrEquals(".ips", patchFile.Extension)) // IPS|IPS32 { @@ -791,18 +792,18 @@ namespace Ryujinx.HLE.HOS Logger.Info?.Print(LogClass.ModLoader, $"Matching IPS patch '{patchFile.Name}' in '{mod.Name}' bid={buildId}"); - using var fs = patchFile.OpenRead(); - using var reader = new BinaryReader(fs); + using FileStream fs = patchFile.OpenRead(); + using BinaryReader reader = new BinaryReader(fs); - var patcher = new IpsPatcher(reader); + IpsPatcher patcher = new IpsPatcher(reader); patcher.AddPatches(patches[index]); } else if (StrEquals(".pchtxt", patchFile.Extension)) // IPSwitch { - using var fs = patchFile.OpenRead(); - using var reader = new StreamReader(fs); + using FileStream fs = patchFile.OpenRead(); + using StreamReader reader = new StreamReader(fs); - var patcher = new IPSwitchPatcher(reader); + IPSwitchPatcher patcher = new IPSwitchPatcher(reader); int index = GetIndex(patcher.BuildId); if (index == -1) diff --git a/src/Ryujinx.HLE/HOS/Services/Account/Acc/AccountManager.cs b/src/Ryujinx.HLE/HOS/Services/Account/Acc/AccountManager.cs index d2da9e248..279e696be 100644 --- a/src/Ryujinx.HLE/HOS/Services/Account/Acc/AccountManager.cs +++ b/src/Ryujinx.HLE/HOS/Services/Account/Acc/AccountManager.cs @@ -191,10 +191,10 @@ namespace Ryujinx.HLE.HOS.Services.Account.Acc private void DeleteSaveData(UserId userId) { - var saveDataFilter = SaveDataFilter.Make(programId: default, saveType: default, + SaveDataFilter saveDataFilter = SaveDataFilter.Make(programId: default, saveType: default, new LibHac.Fs.UserId((ulong)userId.High, (ulong)userId.Low), saveDataId: default, index: default); - using var saveDataIterator = new UniqueRef(); + using UniqueRef saveDataIterator = new UniqueRef(); _horizonClient.Fs.OpenSaveDataIterator(ref saveDataIterator.Ref, SaveDataSpaceId.User, in saveDataFilter).ThrowIfFailure(); diff --git a/src/Ryujinx.HLE/HOS/Services/Account/Acc/AccountSaveDataManager.cs b/src/Ryujinx.HLE/HOS/Services/Account/Acc/AccountSaveDataManager.cs index 6fdfe1398..aa6fa57c4 100644 --- a/src/Ryujinx.HLE/HOS/Services/Account/Acc/AccountSaveDataManager.cs +++ b/src/Ryujinx.HLE/HOS/Services/Account/Acc/AccountSaveDataManager.cs @@ -29,7 +29,7 @@ namespace Ryujinx.HLE.HOS.Services.Account.Acc { ProfilesJson profilesJson = JsonHelper.DeserializeFromFile(_profilesJsonPath, _serializerContext.ProfilesJson); - foreach (var profile in profilesJson.Profiles) + foreach (UserProfileJson profile in profilesJson.Profiles) { UserProfile addedProfile = new(new UserId(profile.UserId), profile.Name, profile.Image, profile.LastModifiedTimestamp); @@ -69,7 +69,7 @@ namespace Ryujinx.HLE.HOS.Services.Account.Acc LastOpened = LastOpened.ToString(), }; - foreach (var profile in profiles) + foreach (KeyValuePair profile in profiles) { profilesJson.Profiles.Add(new UserProfileJson() { diff --git a/src/Ryujinx.HLE/HOS/Services/Account/Acc/AccountService/ManagerServer.cs b/src/Ryujinx.HLE/HOS/Services/Account/Acc/AccountService/ManagerServer.cs index 75bad0e3f..7f98b0044 100644 --- a/src/Ryujinx.HLE/HOS/Services/Account/Acc/AccountService/ManagerServer.cs +++ b/src/Ryujinx.HLE/HOS/Services/Account/Acc/AccountService/ManagerServer.cs @@ -51,7 +51,7 @@ namespace Ryujinx.HLE.HOS.Services.Account.Acc.AccountService byte[] deviceAccountId = new byte[0x10]; RandomNumberGenerator.Fill(deviceId); - var descriptor = new SecurityTokenDescriptor + SecurityTokenDescriptor descriptor = new SecurityTokenDescriptor { Subject = new GenericIdentity(Convert.ToHexString(rawUserId).ToLower()), SigningCredentials = credentials, diff --git a/src/Ryujinx.HLE/HOS/Services/Am/AppletAE/AllSystemAppletProxiesService/SystemAppletProxy/ICommonStateGetter.cs b/src/Ryujinx.HLE/HOS/Services/Am/AppletAE/AllSystemAppletProxiesService/SystemAppletProxy/ICommonStateGetter.cs index 602fc2c4d..f58e5b891 100644 --- a/src/Ryujinx.HLE/HOS/Services/Am/AppletAE/AllSystemAppletProxiesService/SystemAppletProxy/ICommonStateGetter.cs +++ b/src/Ryujinx.HLE/HOS/Services/Am/AppletAE/AllSystemAppletProxiesService/SystemAppletProxy/ICommonStateGetter.cs @@ -214,7 +214,7 @@ namespace Ryujinx.HLE.HOS.Services.Am.AppletAE.AllSystemAppletProxiesService.Sys _vrModeEnabled = vrModeEnabled; - using var lblApi = new LblApi(); + using LblApi lblApi = new LblApi(); if (vrModeEnabled) { diff --git a/src/Ryujinx.HLE/HOS/Services/Caps/CaptureManager.cs b/src/Ryujinx.HLE/HOS/Services/Caps/CaptureManager.cs index bf0c7e9dc..67cbb81ac 100644 --- a/src/Ryujinx.HLE/HOS/Services/Caps/CaptureManager.cs +++ b/src/Ryujinx.HLE/HOS/Services/Caps/CaptureManager.cs @@ -118,10 +118,10 @@ namespace Ryujinx.HLE.HOS.Services.Caps } // NOTE: The saved JPEG file doesn't have the limitation in the extra EXIF data. - using var bitmap = new SKBitmap(new SKImageInfo(1280, 720, SKColorType.Rgba8888)); + using SKBitmap bitmap = new SKBitmap(new SKImageInfo(1280, 720, SKColorType.Rgba8888)); Marshal.Copy(screenshotData, 0, bitmap.GetPixels(), screenshotData.Length); - using var data = bitmap.Encode(SKEncodedImageFormat.Jpeg, 80); - using var file = File.OpenWrite(filePath); + using SKData data = bitmap.Encode(SKEncodedImageFormat.Jpeg, 80); + using FileStream file = File.OpenWrite(filePath); data.SaveTo(file); return ResultCode.Success; diff --git a/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/FileSystemProxyHelper.cs b/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/FileSystemProxyHelper.cs index 20ffb996d..796ece16c 100644 --- a/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/FileSystemProxyHelper.cs +++ b/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/FileSystemProxyHelper.cs @@ -26,7 +26,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy try { LocalStorage storage = new(pfsPath, FileAccess.Read, FileMode.Open); - var pfs = new PartitionFileSystem(); + PartitionFileSystem pfs = new PartitionFileSystem(); using SharedRef nsp = new(pfs); pfs.Initialize(storage).ThrowIfFailure(); @@ -58,7 +58,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy } LibHac.Fs.Fsa.IFileSystem fileSystem = nca.OpenFileSystem(NcaSectionType.Data, context.Device.System.FsIntegrityCheckLevel); - using var sharedFs = new SharedRef(fileSystem); + using SharedRef sharedFs = new SharedRef(fileSystem); using SharedRef adapter = FileSystemInterfaceAdapter.CreateShared(ref sharedFs.Ref, true); @@ -99,7 +99,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy string filename = fullPath.Replace(archivePath.FullName, string.Empty).TrimStart('\\'); - using var ncaFile = new UniqueRef(); + using UniqueRef ncaFile = new UniqueRef(); Result result = nsp.OpenFile(ref ncaFile.Ref, filename.ToU8Span(), OpenMode.Read); if (result.IsFailure()) @@ -122,14 +122,14 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy { foreach (DirectoryEntryEx ticketEntry in nsp.EnumerateEntries("/", "*.tik")) { - using var ticketFile = new UniqueRef(); + using UniqueRef ticketFile = new UniqueRef(); Result result = nsp.OpenFile(ref ticketFile.Ref, ticketEntry.FullPath.ToU8Span(), OpenMode.Read); if (result.IsSuccess()) { Ticket ticket = new(ticketFile.Get.AsStream()); - var titleKey = ticket.GetTitleKey(keySet); + byte[] titleKey = ticket.GetTitleKey(keySet); if (titleKey != null) { diff --git a/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IDirectory.cs b/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IDirectory.cs index 70d3a6bd8..0fe7bcdd6 100644 --- a/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IDirectory.cs +++ b/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IDirectory.cs @@ -1,6 +1,7 @@ using LibHac; using LibHac.Common; using LibHac.Sf; +using Ryujinx.Memory; namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy { @@ -20,7 +21,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy ulong bufferAddress = context.Request.ReceiveBuff[0].Position; ulong bufferLen = context.Request.ReceiveBuff[0].Size; - using var region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true); + using WritableRegion region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true); Result result = _baseDirectory.Get.Read(out long entriesRead, new OutBuffer(region.Memory.Span)); context.ResponseData.Write(entriesRead); diff --git a/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IFile.cs b/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IFile.cs index dcc34a754..0ea57f5a4 100644 --- a/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IFile.cs +++ b/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IFile.cs @@ -3,6 +3,7 @@ using LibHac.Common; using LibHac.Fs; using LibHac.Sf; using Ryujinx.Common; +using Ryujinx.Memory; namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy { @@ -28,7 +29,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy long offset = context.RequestData.ReadInt64(); long size = context.RequestData.ReadInt64(); - using var region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true); + using WritableRegion region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true); Result result = _baseFile.Get.Read(out long bytesRead, offset, new OutBuffer(region.Memory.Span), size, readOption); context.ResponseData.Write(bytesRead); diff --git a/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IFileSystem.cs b/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IFileSystem.cs index e19d17912..ff0cb7aed 100644 --- a/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IFileSystem.cs +++ b/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IFileSystem.cs @@ -111,7 +111,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy uint mode = context.RequestData.ReadUInt32(); ref readonly Path name = ref FileSystemProxyHelper.GetSfPath(context); - using var file = new SharedRef(); + using SharedRef file = new SharedRef(); Result result = _fileSystem.Get.OpenFile(ref file.Ref, in name, mode); @@ -132,7 +132,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy uint mode = context.RequestData.ReadUInt32(); ref readonly Path name = ref FileSystemProxyHelper.GetSfPath(context); - using var dir = new SharedRef(); + using SharedRef dir = new SharedRef(); Result result = _fileSystem.Get.OpenDirectory(ref dir.Ref, name, mode); diff --git a/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IStorage.cs b/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IStorage.cs index ad4cccc44..04dc6c688 100644 --- a/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IStorage.cs +++ b/src/Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IStorage.cs @@ -3,6 +3,7 @@ using LibHac.Common; using LibHac.Sf; using Ryujinx.Common; using Ryujinx.Common.Configuration; +using Ryujinx.Memory; using System.Threading; namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy @@ -38,7 +39,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy size = bufferLen; } - using var region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true); + using WritableRegion region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true); Result result = _baseStorage.Get.Read((long)offset, new OutBuffer(region.Memory.Span), (long)size); if (context.Device.DirtyHacks.IsEnabled(DirtyHack.Xc2MenuSoftlockFix) && IsXc2) diff --git a/src/Ryujinx.HLE/HOS/Services/Fs/IFileSystemProxy.cs b/src/Ryujinx.HLE/HOS/Services/Fs/IFileSystemProxy.cs index 24dd1e9be..4ccc7cc92 100644 --- a/src/Ryujinx.HLE/HOS/Services/Fs/IFileSystemProxy.cs +++ b/src/Ryujinx.HLE/HOS/Services/Fs/IFileSystemProxy.cs @@ -3,6 +3,7 @@ using LibHac.Common; using LibHac.Fs; using LibHac.Fs.Shim; using LibHac.FsSrv.Impl; +using LibHac.FsSrv.Sf; using LibHac.FsSystem; using LibHac.Ncm; using LibHac.Sf; @@ -12,10 +13,12 @@ using LibHac.Tools.FsSystem.NcaUtils; using Ryujinx.Common; using Ryujinx.Common.Logging; using Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy; +using Ryujinx.Memory; using System; using System.IO; using static Ryujinx.HLE.Utilities.StringUtils; using GameCardHandle = System.UInt32; +using IFile = Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy.IFile; using IFileSystem = LibHac.FsSrv.Sf.IFileSystem; using IStorage = LibHac.FsSrv.Sf.IStorage; @@ -29,7 +32,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs public IFileSystemProxy(ServiceCtx context) : base(context.Device.System.FsServer) { - var applicationClient = context.Device.System.LibHacHorizonManager.ApplicationClient; + HorizonClient applicationClient = context.Device.System.LibHacHorizonManager.ApplicationClient; _baseFileSystemProxy = applicationClient.Fs.Impl.GetFileSystemProxyServiceObject(); } @@ -106,8 +109,8 @@ namespace Ryujinx.HLE.HOS.Services.Fs { BisPartitionId bisPartitionId = (BisPartitionId)context.RequestData.ReadInt32(); - ref readonly var path = ref FileSystemProxyHelper.GetFspPath(context); - using var fileSystem = new SharedRef(); + ref readonly FspPath path = ref FileSystemProxyHelper.GetFspPath(context); + using SharedRef fileSystem = new SharedRef(); Result result = _baseFileSystemProxy.Get.OpenBisFileSystem(ref fileSystem.Ref, in path, bisPartitionId); if (result.IsFailure()) @@ -125,7 +128,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs public ResultCode OpenBisStorage(ServiceCtx context) { BisPartitionId bisPartitionId = (BisPartitionId)context.RequestData.ReadInt32(); - using var storage = new SharedRef(); + using SharedRef storage = new SharedRef(); Result result = _baseFileSystemProxy.Get.OpenBisStorage(ref storage.Ref, bisPartitionId); if (result.IsFailure()) @@ -149,7 +152,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs // OpenSdCardFileSystem() -> object public ResultCode OpenSdCardFileSystem(ServiceCtx context) { - using var fileSystem = new SharedRef(); + using SharedRef fileSystem = new SharedRef(); Result result = _baseFileSystemProxy.Get.OpenSdCardFileSystem(ref fileSystem.Ref); if (result.IsFailure()) @@ -257,7 +260,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs { GameCardHandle handle = context.RequestData.ReadUInt32(); GameCardPartitionRaw partitionId = (GameCardPartitionRaw)context.RequestData.ReadInt32(); - using var storage = new SharedRef(); + using SharedRef storage = new SharedRef(); Result result = _baseFileSystemProxy.Get.OpenGameCardStorage(ref storage.Ref, handle, partitionId); if (result.IsFailure()) @@ -276,7 +279,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs { GameCardHandle handle = context.RequestData.ReadUInt32(); GameCardPartition partitionId = (GameCardPartition)context.RequestData.ReadInt32(); - using var fileSystem = new SharedRef(); + using SharedRef fileSystem = new SharedRef(); Result result = _baseFileSystemProxy.Get.OpenGameCardFileSystem(ref fileSystem.Ref, handle, partitionId); if (result.IsFailure()) @@ -357,7 +360,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs { SaveDataSpaceId spaceId = (SaveDataSpaceId)context.RequestData.ReadInt64(); SaveDataAttribute attribute = context.RequestData.ReadStruct(); - using var fileSystem = new SharedRef(); + using SharedRef fileSystem = new SharedRef(); Result result = _baseFileSystemProxy.Get.OpenSaveDataFileSystem(ref fileSystem.Ref, spaceId, in attribute); if (result.IsFailure()) @@ -376,7 +379,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs { SaveDataSpaceId spaceId = (SaveDataSpaceId)context.RequestData.ReadInt64(); SaveDataAttribute attribute = context.RequestData.ReadStruct(); - using var fileSystem = new SharedRef(); + using SharedRef fileSystem = new SharedRef(); Result result = _baseFileSystemProxy.Get.OpenSaveDataFileSystemBySystemSaveDataId(ref fileSystem.Ref, spaceId, in attribute); if (result.IsFailure()) @@ -395,7 +398,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs { SaveDataSpaceId spaceId = (SaveDataSpaceId)context.RequestData.ReadInt64(); SaveDataAttribute attribute = context.RequestData.ReadStruct(); - using var fileSystem = new SharedRef(); + using SharedRef fileSystem = new SharedRef(); Result result = _baseFileSystemProxy.Get.OpenReadOnlySaveDataFileSystem(ref fileSystem.Ref, spaceId, in attribute); if (result.IsFailure()) @@ -466,7 +469,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs // OpenSaveDataInfoReader() -> object public ResultCode OpenSaveDataInfoReader(ServiceCtx context) { - using var infoReader = new SharedRef(); + using SharedRef infoReader = new SharedRef(); Result result = _baseFileSystemProxy.Get.OpenSaveDataInfoReader(ref infoReader.Ref); if (result.IsFailure()) @@ -484,7 +487,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs public ResultCode OpenSaveDataInfoReaderBySaveDataSpaceId(ServiceCtx context) { SaveDataSpaceId spaceId = (SaveDataSpaceId)context.RequestData.ReadByte(); - using var infoReader = new SharedRef(); + using SharedRef infoReader = new SharedRef(); Result result = _baseFileSystemProxy.Get.OpenSaveDataInfoReaderBySaveDataSpaceId(ref infoReader.Ref, spaceId); if (result.IsFailure()) @@ -501,7 +504,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs // OpenSaveDataInfoReaderOnlyCacheStorage() -> object public ResultCode OpenSaveDataInfoReaderOnlyCacheStorage(ServiceCtx context) { - using var infoReader = new SharedRef(); + using SharedRef infoReader = new SharedRef(); Result result = _baseFileSystemProxy.Get.OpenSaveDataInfoReaderOnlyCacheStorage(ref infoReader.Ref); if (result.IsFailure()) @@ -520,7 +523,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs { SaveDataSpaceId spaceId = (SaveDataSpaceId)context.RequestData.ReadInt64(); ulong saveDataId = context.RequestData.ReadUInt64(); - using var fileSystem = new SharedRef(); + using SharedRef fileSystem = new SharedRef(); Result result = _baseFileSystemProxy.Get.OpenSaveDataInternalStorageFileSystem(ref fileSystem.Ref, spaceId, saveDataId); if (result.IsFailure()) @@ -567,7 +570,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs ulong bufferAddress = context.Request.ReceiveBuff[0].Position; ulong bufferLen = context.Request.ReceiveBuff[0].Size; - using var region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true); + using WritableRegion region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true); Result result = _baseFileSystemProxy.Get.FindSaveDataWithFilter(out long count, new OutBuffer(region.Memory.Span), spaceId, in filter); if (result.IsFailure()) { @@ -584,7 +587,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs { SaveDataSpaceId spaceId = (SaveDataSpaceId)context.RequestData.ReadInt64(); SaveDataFilter filter = context.RequestData.ReadStruct(); - using var infoReader = new SharedRef(); + using SharedRef infoReader = new SharedRef(); Result result = _baseFileSystemProxy.Get.OpenSaveDataInfoReaderWithFilter(ref infoReader.Ref, spaceId, in filter); if (result.IsFailure()) @@ -661,7 +664,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs SaveDataSpaceId spaceId = (SaveDataSpaceId)context.RequestData.ReadInt32(); SaveDataMetaType metaType = (SaveDataMetaType)context.RequestData.ReadInt32(); SaveDataAttribute attribute = context.RequestData.ReadStruct(); - using var file = new SharedRef(); + using SharedRef file = new SharedRef(); Result result = _baseFileSystemProxy.Get.OpenSaveDataMetaFile(ref file.Ref, spaceId, in attribute, metaType); if (result.IsFailure()) @@ -699,7 +702,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs public ResultCode OpenImageDirectoryFileSystem(ServiceCtx context) { ImageDirectoryId directoryId = (ImageDirectoryId)context.RequestData.ReadInt32(); - using var fileSystem = new SharedRef(); + using SharedRef fileSystem = new SharedRef(); Result result = _baseFileSystemProxy.Get.OpenImageDirectoryFileSystem(ref fileSystem.Ref, directoryId); if (result.IsFailure()) @@ -716,7 +719,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs public ResultCode OpenBaseFileSystem(ServiceCtx context) { BaseFileSystemId fileSystemId = (BaseFileSystemId)context.RequestData.ReadInt32(); - using var fileSystem = new SharedRef(); + using SharedRef fileSystem = new SharedRef(); Result result = _baseFileSystemProxy.Get.OpenBaseFileSystem(ref fileSystem.Ref, fileSystemId); if (result.IsFailure()) @@ -733,7 +736,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs public ResultCode OpenContentStorageFileSystem(ServiceCtx context) { ContentStorageId contentStorageId = (ContentStorageId)context.RequestData.ReadInt32(); - using var fileSystem = new SharedRef(); + using SharedRef fileSystem = new SharedRef(); Result result = _baseFileSystemProxy.Get.OpenContentStorageFileSystem(ref fileSystem.Ref, contentStorageId); if (result.IsFailure()) @@ -750,7 +753,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs public ResultCode OpenCloudBackupWorkStorageFileSystem(ServiceCtx context) { CloudBackupWorkStorageId storageId = (CloudBackupWorkStorageId)context.RequestData.ReadInt32(); - using var fileSystem = new SharedRef(); + using SharedRef fileSystem = new SharedRef(); Result result = _baseFileSystemProxy.Get.OpenCloudBackupWorkStorageFileSystem(ref fileSystem.Ref, storageId); if (result.IsFailure()) @@ -767,7 +770,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs public ResultCode OpenCustomStorageFileSystem(ServiceCtx context) { CustomStorageId customStorageId = (CustomStorageId)context.RequestData.ReadInt32(); - using var fileSystem = new SharedRef(); + using SharedRef fileSystem = new SharedRef(); Result result = _baseFileSystemProxy.Get.OpenCustomStorageFileSystem(ref fileSystem.Ref, customStorageId); if (result.IsFailure()) @@ -784,9 +787,9 @@ namespace Ryujinx.HLE.HOS.Services.Fs // OpenDataStorageByCurrentProcess() -> object dataStorage public ResultCode OpenDataStorageByCurrentProcess(ServiceCtx context) { - var storage = context.Device.FileSystem.GetRomFs(_pid).AsStorage(true); - using var sharedStorage = new SharedRef(storage); - using var sfStorage = new SharedRef(new StorageInterfaceAdapter(ref sharedStorage.Ref)); + LibHac.Fs.IStorage storage = context.Device.FileSystem.GetRomFs(_pid).AsStorage(true); + using SharedRef sharedStorage = new SharedRef(storage); + using SharedRef sfStorage = new SharedRef(new StorageInterfaceAdapter(ref sharedStorage.Ref)); MakeObject(context, new FileSystemProxy.IStorage(ref sfStorage.Ref)); @@ -809,9 +812,9 @@ namespace Ryujinx.HLE.HOS.Services.Fs { Logger.Info?.Print(LogClass.Loader, $"Opened AddOnContent Data TitleID={titleId:X16}"); - var storage = context.Device.FileSystem.ModLoader.ApplyRomFsMods(titleId, aocStorage); - using var sharedStorage = new SharedRef(storage); - using var sfStorage = new SharedRef(new StorageInterfaceAdapter(ref sharedStorage.Ref)); + LibHac.Fs.IStorage storage = context.Device.FileSystem.ModLoader.ApplyRomFsMods(titleId, aocStorage); + using SharedRef sharedStorage = new SharedRef(storage); + using SharedRef sfStorage = new SharedRef(new StorageInterfaceAdapter(ref sharedStorage.Ref)); MakeObject(context, new FileSystemProxy.IStorage(ref sfStorage.Ref)); @@ -845,8 +848,8 @@ namespace Ryujinx.HLE.HOS.Services.Fs LibHac.Fs.IStorage ncaStorage = new LocalStorage(ncaPath, FileAccess.Read, FileMode.Open); Nca nca = new(context.Device.System.KeySet, ncaStorage); LibHac.Fs.IStorage romfsStorage = nca.OpenStorage(NcaSectionType.Data, context.Device.System.FsIntegrityCheckLevel); - using var sharedStorage = new SharedRef(romfsStorage); - using var sfStorage = new SharedRef(new StorageInterfaceAdapter(ref sharedStorage.Ref)); + using SharedRef sharedStorage = new SharedRef(romfsStorage); + using SharedRef sfStorage = new SharedRef(new StorageInterfaceAdapter(ref sharedStorage.Ref)); MakeObject(context, new FileSystemProxy.IStorage(ref sfStorage.Ref)); } @@ -875,9 +878,9 @@ namespace Ryujinx.HLE.HOS.Services.Fs // OpenPatchDataStorageByCurrentProcess() -> object public ResultCode OpenPatchDataStorageByCurrentProcess(ServiceCtx context) { - var storage = context.Device.FileSystem.GetRomFs(_pid).AsStorage(true); - using var sharedStorage = new SharedRef(storage); - using var sfStorage = new SharedRef(new StorageInterfaceAdapter(ref sharedStorage.Ref)); + LibHac.Fs.IStorage storage = context.Device.FileSystem.GetRomFs(_pid).AsStorage(true); + using SharedRef sharedStorage = new SharedRef(storage); + using SharedRef sfStorage = new SharedRef(new StorageInterfaceAdapter(ref sharedStorage.Ref)); MakeObject(context, new FileSystemProxy.IStorage(ref sfStorage.Ref)); @@ -895,9 +898,9 @@ namespace Ryujinx.HLE.HOS.Services.Fs throw new NotImplementedException($"Accessing storage from other programs is not supported (program index = {programIndex})."); } - var storage = context.Device.FileSystem.GetRomFs(_pid).AsStorage(true); - using var sharedStorage = new SharedRef(storage); - using var sfStorage = new SharedRef(new StorageInterfaceAdapter(ref sharedStorage.Ref)); + LibHac.Fs.IStorage storage = context.Device.FileSystem.GetRomFs(_pid).AsStorage(true); + using SharedRef sharedStorage = new SharedRef(storage); + using SharedRef sfStorage = new SharedRef(new StorageInterfaceAdapter(ref sharedStorage.Ref)); MakeObject(context, new FileSystemProxy.IStorage(ref sfStorage.Ref)); @@ -908,7 +911,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs // OpenDataStorageByCurrentProcess() -> object dataStorage public ResultCode OpenDeviceOperator(ServiceCtx context) { - using var deviceOperator = new SharedRef(); + using SharedRef deviceOperator = new SharedRef(); Result result = _baseFileSystemProxy.Get.OpenDeviceOperator(ref deviceOperator.Ref); if (result.IsFailure()) @@ -1023,7 +1026,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs [CommandCmif(609)] public ResultCode GetRightsIdByPath(ServiceCtx context) { - ref readonly var path = ref FileSystemProxyHelper.GetFspPath(context); + ref readonly FspPath path = ref FileSystemProxyHelper.GetFspPath(context); Result result = _baseFileSystemProxy.Get.GetRightsIdByPath(out RightsId rightsId, in path); if (result.IsFailure()) @@ -1039,7 +1042,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs [CommandCmif(610)] public ResultCode GetRightsIdAndKeyGenerationByPath(ServiceCtx context) { - ref readonly var path = ref FileSystemProxyHelper.GetFspPath(context); + ref readonly FspPath path = ref FileSystemProxyHelper.GetFspPath(context); Result result = _baseFileSystemProxy.Get.GetRightsIdAndKeyGenerationByPath(out RightsId rightsId, out byte keyGeneration, in path); if (result.IsFailure()) @@ -1236,7 +1239,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs public ResultCode SetBisRootForHost(ServiceCtx context) { BisPartitionId partitionId = (BisPartitionId)context.RequestData.ReadInt32(); - ref readonly var path = ref FileSystemProxyHelper.GetFspPath(context); + ref readonly FspPath path = ref FileSystemProxyHelper.GetFspPath(context); return (ResultCode)_baseFileSystemProxy.Get.SetBisRootForHost(partitionId, in path).Value; } @@ -1253,7 +1256,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs [CommandCmif(1002)] public ResultCode SetSaveDataRootPath(ServiceCtx context) { - ref readonly var path = ref FileSystemProxyHelper.GetFspPath(context); + ref readonly FspPath path = ref FileSystemProxyHelper.GetFspPath(context); return (ResultCode)_baseFileSystemProxy.Get.SetSaveDataRootPath(in path).Value; } @@ -1307,7 +1310,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs [CommandCmif(1008)] public ResultCode OpenRegisteredUpdatePartition(ServiceCtx context) { - using var fileSystem = new SharedRef(); + using SharedRef fileSystem = new SharedRef(); Result result = _baseFileSystemProxy.Get.OpenRegisteredUpdatePartition(ref fileSystem.Ref); if (result.IsFailure()) @@ -1417,7 +1420,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs // OpenMultiCommitManager() -> object public ResultCode OpenMultiCommitManager(ServiceCtx context) { - using var commitManager = new SharedRef(); + using SharedRef commitManager = new SharedRef(); Result result = _baseFileSystemProxy.Get.OpenMultiCommitManager(ref commitManager.Ref); if (result.IsFailure()) diff --git a/src/Ryujinx.HLE/HOS/Services/Fs/ISaveDataInfoReader.cs b/src/Ryujinx.HLE/HOS/Services/Fs/ISaveDataInfoReader.cs index 7ed6dadc2..b86eb1fa1 100644 --- a/src/Ryujinx.HLE/HOS/Services/Fs/ISaveDataInfoReader.cs +++ b/src/Ryujinx.HLE/HOS/Services/Fs/ISaveDataInfoReader.cs @@ -1,6 +1,7 @@ using LibHac; using LibHac.Common; using LibHac.Sf; +using Ryujinx.Memory; namespace Ryujinx.HLE.HOS.Services.Fs { @@ -20,7 +21,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs ulong bufferAddress = context.Request.ReceiveBuff[0].Position; ulong bufferLen = context.Request.ReceiveBuff[0].Size; - using var region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true); + using WritableRegion region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true); Result result = _baseReader.Get.Read(out long readCount, new OutBuffer(region.Memory.Span)); context.ResponseData.Write(readCount); diff --git a/src/Ryujinx.HLE/HOS/Services/Hid/Irs/IIrSensorServer.cs b/src/Ryujinx.HLE/HOS/Services/Hid/Irs/IIrSensorServer.cs index a13e77e72..28caf4459 100644 --- a/src/Ryujinx.HLE/HOS/Services/Hid/Irs/IIrSensorServer.cs +++ b/src/Ryujinx.HLE/HOS/Services/Hid/Irs/IIrSensorServer.cs @@ -81,7 +81,7 @@ namespace Ryujinx.HLE.HOS.Services.Hid.Irs { IrCameraHandle irCameraHandle = context.RequestData.ReadStruct(); ulong appletResourceUserId = context.RequestData.ReadUInt64(); - var packedMomentProcessorConfig = context.RequestData.ReadStruct(); + PackedMomentProcessorConfig packedMomentProcessorConfig = context.RequestData.ReadStruct(); CheckCameraHandle(irCameraHandle); @@ -96,7 +96,7 @@ namespace Ryujinx.HLE.HOS.Services.Hid.Irs { IrCameraHandle irCameraHandle = context.RequestData.ReadStruct(); ulong appletResourceUserId = context.RequestData.ReadUInt64(); - var packedClusteringProcessorConfig = context.RequestData.ReadStruct(); + PackedClusteringProcessorConfig packedClusteringProcessorConfig = context.RequestData.ReadStruct(); CheckCameraHandle(irCameraHandle); @@ -111,7 +111,7 @@ namespace Ryujinx.HLE.HOS.Services.Hid.Irs { IrCameraHandle irCameraHandle = context.RequestData.ReadStruct(); ulong appletResourceUserId = context.RequestData.ReadUInt64(); - var packedImageTransferProcessorConfig = context.RequestData.ReadStruct(); + PackedImageTransferProcessorConfig packedImageTransferProcessorConfig = context.RequestData.ReadStruct(); CheckCameraHandle(irCameraHandle); @@ -157,7 +157,7 @@ namespace Ryujinx.HLE.HOS.Services.Hid.Irs { IrCameraHandle irCameraHandle = context.RequestData.ReadStruct(); ulong appletResourceUserId = context.RequestData.ReadUInt64(); - var packedTeraPluginProcessorConfig = context.RequestData.ReadStruct(); + PackedTeraPluginProcessorConfig packedTeraPluginProcessorConfig = context.RequestData.ReadStruct(); CheckCameraHandle(irCameraHandle); diff --git a/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/IUserLocalCommunicationService.cs b/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/IUserLocalCommunicationService.cs index b8b3014f1..438f532ee 100644 --- a/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/IUserLocalCommunicationService.cs +++ b/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/IUserLocalCommunicationService.cs @@ -65,7 +65,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator // TODO: Call nn::arp::GetApplicationControlProperty here when implemented. ApplicationControlProperty controlProperty = context.Device.Processes.ActiveApplication.ApplicationControlProperties; - foreach (var localCommunicationId in controlProperty.LocalCommunicationId.ItemsRo) + foreach (ulong localCommunicationId in controlProperty.LocalCommunicationId.ItemsRo) { if (localCommunicationId == localCommunicationIdChecked) { diff --git a/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnMitm/LanDiscovery.cs b/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnMitm/LanDiscovery.cs index 8b7af42a0..e6b8ab1ec 100644 --- a/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnMitm/LanDiscovery.cs +++ b/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnMitm/LanDiscovery.cs @@ -244,7 +244,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnMitm byte[] ip = address.GetAddressBytes(); - var macAddress = new Array6(); + Array6 macAddress = new Array6(); new byte[] { 0x02, 0x00, ip[0], ip[1], ip[2], ip[3] }.CopyTo(macAddress.AsSpan()); return macAddress; diff --git a/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnMitm/Proxy/LdnProxyUdpServer.cs b/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnMitm/Proxy/LdnProxyUdpServer.cs index 536ae476d..b1040e646 100644 --- a/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnMitm/Proxy/LdnProxyUdpServer.cs +++ b/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnMitm/Proxy/LdnProxyUdpServer.cs @@ -112,7 +112,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnMitm.Proxy lock (_scanLock) { - var newResults = _scanResultsLast; + Dictionary newResults = _scanResultsLast; newResults.Clear(); _scanResultsLast = _scanResults; @@ -138,7 +138,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnMitm.Proxy lock (_scanLock) { - var results = new Dictionary(); + Dictionary results = new Dictionary(); foreach (KeyValuePair last in _scanResultsLast) { diff --git a/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnRyu/LdnMasterProxyClient.cs b/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnRyu/LdnMasterProxyClient.cs index 4c7814b8e..a21fb190a 100644 --- a/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnRyu/LdnMasterProxyClient.cs +++ b/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnRyu/LdnMasterProxyClient.cs @@ -490,7 +490,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu SendAsync(_protocol.Encode(PacketId.CreateAccessPoint, request, advertiseData)); // Send a network change event with dummy data immediately. Necessary to avoid crashes in some games - var networkChangeEvent = new NetworkChangeEventArgs(new NetworkInfo() + NetworkChangeEventArgs networkChangeEvent = new NetworkChangeEventArgs(new NetworkInfo() { Common = new CommonNetworkInfo() { @@ -610,7 +610,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu SendAsync(_protocol.Encode(PacketId.Connect, request)); - var networkChangeEvent = new NetworkChangeEventArgs(new NetworkInfo() + NetworkChangeEventArgs networkChangeEvent = new NetworkChangeEventArgs(new NetworkInfo() { Common = request.NetworkInfo.Common, Ldn = request.NetworkInfo.Ldn diff --git a/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnRyu/Proxy/LdnProxySocket.cs b/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnRyu/Proxy/LdnProxySocket.cs index ed7a9c751..705e67ecd 100644 --- a/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnRyu/Proxy/LdnProxySocket.cs +++ b/src/Ryujinx.HLE/HOS/Services/Ldn/UserServiceCreator/LdnRyu/Proxy/LdnProxySocket.cs @@ -256,7 +256,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu.Proxy { _proxy.ReturnEphemeralPort(ProtocolType, (ushort)((IPEndPoint)LocalEndPoint).Port); } - var asIPEndpoint = (IPEndPoint)localEP; + IPEndPoint asIPEndpoint = (IPEndPoint)localEP; if (asIPEndpoint.Port == 0) { asIPEndpoint.Port = (ushort)_proxy.GetEphemeralPort(ProtocolType); diff --git a/src/Ryujinx.HLE/HOS/Services/Mii/Types/CoreData.cs b/src/Ryujinx.HLE/HOS/Services/Mii/Types/CoreData.cs index aaeb8aa10..bbef717ae 100644 --- a/src/Ryujinx.HLE/HOS/Services/Mii/Types/CoreData.cs +++ b/src/Ryujinx.HLE/HOS/Services/Mii/Types/CoreData.cs @@ -440,18 +440,18 @@ namespace Ryujinx.HLE.HOS.Services.Mii.Types int indexFor4 = 3 * (int)age + 9 * (int)gender + (int)race; - var facelineTypeInfo = RandomMiiFacelineArray[indexFor4]; - var facelineColorInfo = RandomMiiFacelineColorArray[3 * (int)gender + (int)race]; - var facelineWrinkleInfo = RandomMiiFacelineWrinkleArray[indexFor4]; - var facelineMakeInfo = RandomMiiFacelineMakeArray[indexFor4]; - var hairTypeInfo = RandomMiiHairTypeArray[indexFor4]; - var hairColorInfo = RandomMiiHairColorArray[3 * (int)race + (int)age]; - var eyeTypeInfo = RandomMiiEyeTypeArray[indexFor4]; - var eyeColorInfo = RandomMiiEyeColorArray[(int)race]; - var eyebrowTypeInfo = RandomMiiEyebrowTypeArray[indexFor4]; - var noseTypeInfo = RandomMiiNoseTypeArray[indexFor4]; - var mouthTypeInfo = RandomMiiMouthTypeArray[indexFor4]; - var glassTypeInfo = RandomMiiGlassTypeArray[(int)age]; + RandomMiiData4 facelineTypeInfo = RandomMiiFacelineArray[indexFor4]; + RandomMiiData3 facelineColorInfo = RandomMiiFacelineColorArray[3 * (int)gender + (int)race]; + RandomMiiData4 facelineWrinkleInfo = RandomMiiFacelineWrinkleArray[indexFor4]; + RandomMiiData4 facelineMakeInfo = RandomMiiFacelineMakeArray[indexFor4]; + RandomMiiData4 hairTypeInfo = RandomMiiHairTypeArray[indexFor4]; + RandomMiiData3 hairColorInfo = RandomMiiHairColorArray[3 * (int)race + (int)age]; + RandomMiiData4 eyeTypeInfo = RandomMiiEyeTypeArray[indexFor4]; + RandomMiiData2 eyeColorInfo = RandomMiiEyeColorArray[(int)race]; + RandomMiiData4 eyebrowTypeInfo = RandomMiiEyebrowTypeArray[indexFor4]; + RandomMiiData4 noseTypeInfo = RandomMiiNoseTypeArray[indexFor4]; + RandomMiiData4 mouthTypeInfo = RandomMiiMouthTypeArray[indexFor4]; + RandomMiiData2 glassTypeInfo = RandomMiiGlassTypeArray[(int)age]; // Faceline coreData.FacelineType = (FacelineType)facelineTypeInfo.Values[utilImpl.GetRandom(facelineTypeInfo.ValuesCount)]; diff --git a/src/Ryujinx.HLE/HOS/Services/Nfc/AmiiboDecryption/AmiiboDecryptor.cs b/src/Ryujinx.HLE/HOS/Services/Nfc/AmiiboDecryption/AmiiboDecryptor.cs index cc6d02ea2..245c37742 100644 --- a/src/Ryujinx.HLE/HOS/Services/Nfc/AmiiboDecryption/AmiiboDecryptor.cs +++ b/src/Ryujinx.HLE/HOS/Services/Nfc/AmiiboDecryption/AmiiboDecryptor.cs @@ -9,8 +9,8 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption public AmiiboDecryptor(string keyRetailBinPath) { - var combinedKeys = File.ReadAllBytes(keyRetailBinPath); - var keys = AmiiboMasterKey.FromCombinedBin(combinedKeys); + byte[] combinedKeys = File.ReadAllBytes(keyRetailBinPath); + (AmiiboMasterKey DataKey, AmiiboMasterKey TagKey) keys = AmiiboMasterKey.FromCombinedBin(combinedKeys); DataKey = keys.DataKey; TagKey = keys.TagKey; } diff --git a/src/Ryujinx.HLE/HOS/Services/Nfc/AmiiboDecryption/AmiiboDump.cs b/src/Ryujinx.HLE/HOS/Services/Nfc/AmiiboDecryption/AmiiboDump.cs index 37d587dac..c5788a4b9 100644 --- a/src/Ryujinx.HLE/HOS/Services/Nfc/AmiiboDecryption/AmiiboDump.cs +++ b/src/Ryujinx.HLE/HOS/Services/Nfc/AmiiboDecryption/AmiiboDump.cs @@ -85,13 +85,13 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption if (deriveAes) { // Derive AES Key and IV - var dataForAes = new byte[2 + seedBytes.Length]; + byte[] dataForAes = new byte[2 + seedBytes.Length]; dataForAes[0] = 0x00; dataForAes[1] = 0x00; // Counter (0) Array.Copy(seedBytes, 0, dataForAes, 2, seedBytes.Length); byte[] derivedBytes; - using (var hmac = new HMACSHA256(key.HmacKey)) + using (HMACSHA256 hmac = new HMACSHA256(key.HmacKey)) { derivedBytes = hmac.ComputeHash(dataForAes); } @@ -100,12 +100,12 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption derivedAesIv = derivedBytes.Skip(16).Take(16).ToArray(); // Derive HMAC Key - var dataForHmacKey = new byte[2 + seedBytes.Length]; + byte[] dataForHmacKey = new byte[2 + seedBytes.Length]; dataForHmacKey[0] = 0x00; dataForHmacKey[1] = 0x01; // Counter (1) Array.Copy(seedBytes, 0, dataForHmacKey, 2, seedBytes.Length); - using (var hmac = new HMACSHA256(key.HmacKey)) + using (HMACSHA256 hmac = new HMACSHA256(key.HmacKey)) { derivedBytes = hmac.ComputeHash(dataForHmacKey); } @@ -115,13 +115,13 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption else { // Derive HMAC Key only - var dataForHmacKey = new byte[2 + seedBytes.Length]; + byte[] dataForHmacKey = new byte[2 + seedBytes.Length]; dataForHmacKey[0] = 0x00; dataForHmacKey[1] = 0x01; // Counter (1) Array.Copy(seedBytes, 0, dataForHmacKey, 2, seedBytes.Length); byte[] derivedBytes; - using (var hmac = new HMACSHA256(key.HmacKey)) + using (HMACSHA256 hmac = new HMACSHA256(key.HmacKey)) { derivedBytes = hmac.ComputeHash(dataForHmacKey); } @@ -229,7 +229,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption Array.Copy(data, 0x054, tagHmacData, 8, 44); byte[] tagHmac; - using (var hmac = new HMACSHA256(hmacTagKey)) + using (HMACSHA256 hmac = new HMACSHA256(hmacTagKey)) { tagHmac = hmac.ComputeHash(tagHmacData); } @@ -258,7 +258,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption Array.Copy(data, 0x054, dataHmacData, offset, len5); byte[] dataHmac; - using (var hmac = new HMACSHA256(hmacDataKey)) + using (HMACSHA256 hmac = new HMACSHA256(hmacDataKey)) { dataHmac = hmac.ComputeHash(dataHmacData); } @@ -278,7 +278,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption Array.Copy(data, 0x054, tagHmacData, 8, 44); byte[] calculatedTagHmac; - using (var hmac = new HMACSHA256(hmacTagKey)) + using (HMACSHA256 hmac = new HMACSHA256(hmacTagKey)) { calculatedTagHmac = hmac.ComputeHash(tagHmacData); } @@ -312,7 +312,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption Array.Copy(data, 0x054, dataHmacData, offset, len5); byte[] calculatedDataHmac; - using (var hmac = new HMACSHA256(hmacDataKey)) + using (HMACSHA256 hmac = new HMACSHA256(hmacDataKey)) { calculatedDataHmac = hmac.ComputeHash(dataHmacData); } diff --git a/src/Ryujinx.HLE/HOS/Services/Nv/Host1xContext.cs b/src/Ryujinx.HLE/HOS/Services/Nv/Host1xContext.cs index 7c7ebf22d..57b31e662 100644 --- a/src/Ryujinx.HLE/HOS/Services/Nv/Host1xContext.cs +++ b/src/Ryujinx.HLE/HOS/Services/Nv/Host1xContext.cs @@ -18,8 +18,8 @@ namespace Ryujinx.HLE.HOS.Services.Nv MemoryAllocator = new NvMemoryAllocator(); Host1x = new Host1xDevice(gpu.Synchronization); Smmu = gpu.CreateDeviceMemoryManager(pid); - var nvdec = new NvdecDevice(Smmu); - var vic = new VicDevice(Smmu); + NvdecDevice nvdec = new NvdecDevice(Smmu); + VicDevice vic = new VicDevice(Smmu); Host1x.RegisterDevice(ClassId.Nvdec, nvdec); Host1x.RegisterDevice(ClassId.Vic, vic); } diff --git a/src/Ryujinx.HLE/HOS/Services/Nv/NvDrvServices/NvHostAsGpu/NvHostAsGpuDeviceFile.cs b/src/Ryujinx.HLE/HOS/Services/Nv/NvDrvServices/NvHostAsGpu/NvHostAsGpuDeviceFile.cs index 0f5d7547c..3422343fd 100644 --- a/src/Ryujinx.HLE/HOS/Services/Nv/NvDrvServices/NvHostAsGpu/NvHostAsGpuDeviceFile.cs +++ b/src/Ryujinx.HLE/HOS/Services/Nv/NvDrvServices/NvHostAsGpu/NvHostAsGpuDeviceFile.cs @@ -104,7 +104,7 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostAsGpu private NvInternalResult BindChannel(ref BindChannelArguments arguments) { - var channelDeviceFile = INvDrvServices.DeviceFileIdRegistry.GetData(arguments.Fd); + NvHostChannelDeviceFile channelDeviceFile = INvDrvServices.DeviceFileIdRegistry.GetData(arguments.Fd); if (channelDeviceFile == null) { // TODO: Return invalid Fd error. @@ -336,9 +336,9 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostAsGpu for (uint i = 0; i < writeEntries; i++) { - ref var region = ref arguments.Regions[(int)i]; + ref VaRegion region = ref arguments.Regions[(int)i]; - var vmRegion = _vmRegions[i]; + VmRegion vmRegion = _vmRegions[i]; uint pageSize = _pageSizes[i]; region.PageSize = pageSize; diff --git a/src/Ryujinx.HLE/HOS/Services/Nv/NvDrvServices/NvHostChannel/NvHostChannelDeviceFile.cs b/src/Ryujinx.HLE/HOS/Services/Nv/NvDrvServices/NvHostChannel/NvHostChannelDeviceFile.cs index bc70b05cf..f81c2edef 100644 --- a/src/Ryujinx.HLE/HOS/Services/Nv/NvDrvServices/NvHostChannel/NvHostChannelDeviceFile.cs +++ b/src/Ryujinx.HLE/HOS/Services/Nv/NvDrvServices/NvHostChannel/NvHostChannelDeviceFile.cs @@ -169,7 +169,7 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostChannel { NvMapHandle map = NvMapDeviceFile.GetMapFromHandle(Owner, commandBuffer.Mem); - var data = _memory.GetSpan(map.Address + commandBuffer.Offset, commandBuffer.WordsCount * 4); + ReadOnlySpan data = _memory.GetSpan(map.Address + commandBuffer.Offset, commandBuffer.WordsCount * 4); _host1xContext.Host1x.Submit(MemoryMarshal.Cast(data), _contextId); } diff --git a/src/Ryujinx.HLE/HOS/Services/Sdb/Pdm/QueryService/QueryPlayStatisticsManager.cs b/src/Ryujinx.HLE/HOS/Services/Sdb/Pdm/QueryService/QueryPlayStatisticsManager.cs index 56d389cd2..25666c2fd 100644 --- a/src/Ryujinx.HLE/HOS/Services/Sdb/Pdm/QueryService/QueryPlayStatisticsManager.cs +++ b/src/Ryujinx.HLE/HOS/Services/Sdb/Pdm/QueryService/QueryPlayStatisticsManager.cs @@ -55,7 +55,7 @@ namespace Ryujinx.HLE.HOS.Services.Sdb.Pdm.QueryService MemoryHelper.FillWithZeros(context.Memory, outputPosition, (int)outputSize); // Return ResultCode.ServiceUnavailable if data is locked by another process. - var filteredApplicationPlayStatistics = _applicationPlayStatistics.AsEnumerable(); + IEnumerable> filteredApplicationPlayStatistics = _applicationPlayStatistics.AsEnumerable(); if (queryCapability == PlayLogQueryCapability.None) { diff --git a/src/Ryujinx.HLE/HOS/Services/Sdb/Pl/SharedFontManager.cs b/src/Ryujinx.HLE/HOS/Services/Sdb/Pl/SharedFontManager.cs index 0e02220a0..3cc43a551 100644 --- a/src/Ryujinx.HLE/HOS/Services/Sdb/Pl/SharedFontManager.cs +++ b/src/Ryujinx.HLE/HOS/Services/Sdb/Pl/SharedFontManager.cs @@ -76,7 +76,7 @@ namespace Ryujinx.HLE.HOS.Services.Sdb.Pl Nca nca = new(_device.System.KeySet, ncaFileStream); IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _device.System.FsIntegrityCheckLevel); - using var fontFile = new UniqueRef(); + using UniqueRef fontFile = new UniqueRef(); romfs.OpenFile(ref fontFile.Ref, ("/" + fontFilename).ToU8Span(), OpenMode.Read).ThrowIfFailure(); diff --git a/src/Ryujinx.HLE/HOS/Services/ServerBase.cs b/src/Ryujinx.HLE/HOS/Services/ServerBase.cs index 40329aa36..0fd5ab670 100644 --- a/src/Ryujinx.HLE/HOS/Services/ServerBase.cs +++ b/src/Ryujinx.HLE/HOS/Services/ServerBase.cs @@ -1,3 +1,4 @@ +using Microsoft.IO; using Ryujinx.Common; using Ryujinx.Common.Logging; using Ryujinx.Common.Memory; @@ -235,7 +236,7 @@ namespace Ryujinx.HLE.HOS.Services } } - var rc = _context.Syscall.ReplyAndReceive(out int signaledIndex, handles.AsSpan(0, handleCount), replyTargetHandle, -1); + Result rc = _context.Syscall.ReplyAndReceive(out int signaledIndex, handles.AsSpan(0, handleCount), replyTargetHandle, -1); _selfThread.HandlePostSyscall(); @@ -307,7 +308,7 @@ namespace Ryujinx.HLE.HOS.Services { _context.Syscall.CloseHandle(serverSessionHandle); - if (RemoveSessionObj(serverSessionHandle, out var session)) + if (RemoveSessionObj(serverSessionHandle, out IpcService session)) { (session as IDisposable)?.Dispose(); } @@ -453,7 +454,7 @@ namespace Ryujinx.HLE.HOS.Services response.RawData = _responseDataStream.ToArray(); - using var responseStream = response.GetStreamTipc(); + using RecyclableMemoryStream responseStream = response.GetStreamTipc(); _selfProcess.CpuMemory.Write(_selfThread.TlsAddress, responseStream.GetReadOnlySequence()); } else @@ -463,7 +464,7 @@ namespace Ryujinx.HLE.HOS.Services if (!isTipcCommunication) { - using var responseStream = response.GetStream((long)_selfThread.TlsAddress, recvListAddr | ((ulong)PointerBufferSize << 48)); + using RecyclableMemoryStream responseStream = response.GetStream((long)_selfThread.TlsAddress, recvListAddr | ((ulong)PointerBufferSize << 48)); _selfProcess.CpuMemory.Write(_selfThread.TlsAddress, responseStream.GetReadOnlySequence()); } diff --git a/src/Ryujinx.HLE/HOS/Services/Settings/ISystemSettingsServer.cs b/src/Ryujinx.HLE/HOS/Services/Settings/ISystemSettingsServer.cs index 846c4dc4f..df2f76563 100644 --- a/src/Ryujinx.HLE/HOS/Services/Settings/ISystemSettingsServer.cs +++ b/src/Ryujinx.HLE/HOS/Services/Settings/ISystemSettingsServer.cs @@ -326,7 +326,7 @@ namespace Ryujinx.HLE.HOS.Services.Settings IFileSystem firmwareRomFs = firmwareContent.OpenFileSystem(NcaSectionType.Data, device.System.FsIntegrityCheckLevel); - using var firmwareFile = new UniqueRef(); + using UniqueRef firmwareFile = new UniqueRef(); Result result = firmwareRomFs.OpenFile(ref firmwareFile.Ref, "/file".ToU8Span(), OpenMode.Read); if (result.IsFailure()) diff --git a/src/Ryujinx.HLE/HOS/Services/Sockets/Bsd/IClient.cs b/src/Ryujinx.HLE/HOS/Services/Sockets/Bsd/IClient.cs index 3a40a4ac5..273f6c5ca 100644 --- a/src/Ryujinx.HLE/HOS/Services/Sockets/Bsd/IClient.cs +++ b/src/Ryujinx.HLE/HOS/Services/Sockets/Bsd/IClient.cs @@ -315,9 +315,9 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd } } - using var readFdsOut = context.Memory.GetWritableRegion(readFdsOutBufferPosition, (int)readFdsOutBufferSize); - using var writeFdsOut = context.Memory.GetWritableRegion(writeFdsOutBufferPosition, (int)writeFdsOutBufferSize); - using var errorFdsOut = context.Memory.GetWritableRegion(errorFdsOutBufferPosition, (int)errorFdsOutBufferSize); + using WritableRegion readFdsOut = context.Memory.GetWritableRegion(readFdsOutBufferPosition, (int)readFdsOutBufferSize); + using WritableRegion writeFdsOut = context.Memory.GetWritableRegion(writeFdsOutBufferPosition, (int)writeFdsOutBufferSize); + using WritableRegion errorFdsOut = context.Memory.GetWritableRegion(errorFdsOutBufferPosition, (int)errorFdsOutBufferSize); _context.BuildMask(readFds, readFdsOut.Memory.Span); _context.BuildMask(writeFds, writeFdsOut.Memory.Span); diff --git a/src/Ryujinx.HLE/HOS/Services/Sockets/Bsd/Impl/WinSockHelper.cs b/src/Ryujinx.HLE/HOS/Services/Sockets/Bsd/Impl/WinSockHelper.cs index e2ef75f80..3db2712f3 100644 --- a/src/Ryujinx.HLE/HOS/Services/Sockets/Bsd/Impl/WinSockHelper.cs +++ b/src/Ryujinx.HLE/HOS/Services/Sockets/Bsd/Impl/WinSockHelper.cs @@ -303,7 +303,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl public static bool TryConvertSocketOption(BsdSocketOption option, SocketOptionLevel level, out SocketOptionName name) { - var table = level switch + Dictionary table = level switch { SocketOptionLevel.Socket => _soSocketOptionMap, SocketOptionLevel.IP => _ipSocketOptionMap, @@ -322,7 +322,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl public static LinuxError ValidateSocketOption(BsdSocketOption option, SocketOptionLevel level, bool write) { - var table = level switch + Dictionary table = level switch { SocketOptionLevel.Socket => _validSoSocketOptionMap, SocketOptionLevel.IP => _validIpSocketOptionMap, diff --git a/src/Ryujinx.HLE/HOS/Services/Sockets/Bsd/Proxy/SocketHelpers.cs b/src/Ryujinx.HLE/HOS/Services/Sockets/Bsd/Proxy/SocketHelpers.cs index 485a7f86b..9f206176d 100644 --- a/src/Ryujinx.HLE/HOS/Services/Sockets/Bsd/Proxy/SocketHelpers.cs +++ b/src/Ryujinx.HLE/HOS/Services/Sockets/Bsd/Proxy/SocketHelpers.cs @@ -12,9 +12,9 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Proxy public static void Select(List readEvents, List writeEvents, List errorEvents, int timeout) { - var readDefault = readEvents.Select(x => (x as DefaultSocket)?.BaseSocket).Where(x => x != null).ToList(); - var writeDefault = writeEvents.Select(x => (x as DefaultSocket)?.BaseSocket).Where(x => x != null).ToList(); - var errorDefault = errorEvents.Select(x => (x as DefaultSocket)?.BaseSocket).Where(x => x != null).ToList(); + List readDefault = readEvents.Select(x => (x as DefaultSocket)?.BaseSocket).Where(x => x != null).ToList(); + List writeDefault = writeEvents.Select(x => (x as DefaultSocket)?.BaseSocket).Where(x => x != null).ToList(); + List errorDefault = errorEvents.Select(x => (x as DefaultSocket)?.BaseSocket).Where(x => x != null).ToList(); if (readDefault.Count != 0 || writeDefault.Count != 0 || errorDefault.Count != 0) { diff --git a/src/Ryujinx.HLE/HOS/Services/Sockets/Sfdnsres/Proxy/DnsMitmResolver.cs b/src/Ryujinx.HLE/HOS/Services/Sockets/Sfdnsres/Proxy/DnsMitmResolver.cs index d17a999dc..b0e282031 100644 --- a/src/Ryujinx.HLE/HOS/Services/Sockets/Sfdnsres/Proxy/DnsMitmResolver.cs +++ b/src/Ryujinx.HLE/HOS/Services/Sockets/Sfdnsres/Proxy/DnsMitmResolver.cs @@ -82,7 +82,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Sfdnsres.Proxy public IPHostEntry ResolveAddress(string host) { - foreach (var hostEntry in _mitmHostEntries) + foreach (KeyValuePair hostEntry in _mitmHostEntries) { // Check for AMS hosts file extension: "*" // NOTE: MatchesSimpleExpression also allows "?" as a wildcard diff --git a/src/Ryujinx.HLE/HOS/Services/Ssl/BuiltInCertificateManager.cs b/src/Ryujinx.HLE/HOS/Services/Ssl/BuiltInCertificateManager.cs index 622b62c16..adde15b32 100644 --- a/src/Ryujinx.HLE/HOS/Services/Ssl/BuiltInCertificateManager.cs +++ b/src/Ryujinx.HLE/HOS/Services/Ssl/BuiltInCertificateManager.cs @@ -129,7 +129,7 @@ namespace Ryujinx.HLE.HOS.Services.Ssl IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _fsIntegrityCheckLevel); - using var trustedCertsFileRef = new UniqueRef(); + using UniqueRef trustedCertsFileRef = new UniqueRef(); Result result = romfs.OpenFile(ref trustedCertsFileRef.Ref, "/ssl_TrustedCerts.bdf".ToU8Span(), OpenMode.Read); diff --git a/src/Ryujinx.HLE/HOS/Services/Ssl/SslService/ISslConnection.cs b/src/Ryujinx.HLE/HOS/Services/Ssl/SslService/ISslConnection.cs index b5c608d3d..92e73f9f1 100644 --- a/src/Ryujinx.HLE/HOS/Services/Ssl/SslService/ISslConnection.cs +++ b/src/Ryujinx.HLE/HOS/Services/Ssl/SslService/ISslConnection.cs @@ -145,7 +145,7 @@ namespace Ryujinx.HLE.HOS.Services.Ssl.SslService ulong bufferAddress = context.Request.ReceiveBuff[0].Position; ulong bufferLen = context.Request.ReceiveBuff[0].Size; - using (var region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true)) + using (WritableRegion region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true)) { Encoding.ASCII.GetBytes(_hostName, region.Memory.Span); } diff --git a/src/Ryujinx.HLE/HOS/Services/Time/TimeZone/TimeZoneContentManager.cs b/src/Ryujinx.HLE/HOS/Services/Time/TimeZone/TimeZoneContentManager.cs index 222698a7f..82d33578e 100644 --- a/src/Ryujinx.HLE/HOS/Services/Time/TimeZone/TimeZoneContentManager.cs +++ b/src/Ryujinx.HLE/HOS/Services/Time/TimeZone/TimeZoneContentManager.cs @@ -94,7 +94,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone Nca nca = new(_virtualFileSystem.KeySet, ncaFileStream); IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _fsIntegrityCheckLevel); - using var binaryListFile = new UniqueRef(); + using UniqueRef binaryListFile = new UniqueRef(); romfs.OpenFile(ref binaryListFile.Ref, "/binaryList.txt".ToU8Span(), OpenMode.Read).ThrowIfFailure(); @@ -120,7 +120,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone public IEnumerable<(int Offset, string Location, string Abbr)> ParseTzOffsets() { - var tzBinaryContentPath = GetTimeZoneBinaryTitleContentPath(); + string tzBinaryContentPath = GetTimeZoneBinaryTitleContentPath(); if (string.IsNullOrEmpty(tzBinaryContentPath)) { @@ -128,7 +128,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone } List<(int Offset, string Location, string Abbr)> outList = new(); - var now = DateTimeOffset.Now.ToUnixTimeSeconds(); + long now = DateTimeOffset.Now.ToUnixTimeSeconds(); using (IStorage ncaStorage = new LocalStorage(VirtualFileSystem.SwitchPathToSystemPath(tzBinaryContentPath), FileAccess.Read, FileMode.Open)) using (IFileSystem romfs = new Nca(_virtualFileSystem.KeySet, ncaStorage).OpenFileSystem(NcaSectionType.Data, _fsIntegrityCheckLevel)) { @@ -139,7 +139,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone continue; } - using var tzif = new UniqueRef(); + using UniqueRef tzif = new UniqueRef(); if (romfs.OpenFile(ref tzif.Ref, $"/zoneinfo/{locName}".ToU8Span(), OpenMode.Read).IsFailure()) { @@ -176,7 +176,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone continue; } - var abbrStart = tzRule.Chars[ttInfo.AbbreviationListIndex..]; + Span abbrStart = tzRule.Chars[ttInfo.AbbreviationListIndex..]; int abbrEnd = abbrStart.IndexOf((byte)0); outList.Add((ttInfo.GmtOffset, locName, Encoding.UTF8.GetString(abbrStart[..abbrEnd]))); @@ -269,7 +269,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone Nca nca = new(_virtualFileSystem.KeySet, ncaFile); IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _fsIntegrityCheckLevel); - using var timeZoneBinaryFile = new UniqueRef(); + using UniqueRef timeZoneBinaryFile = new UniqueRef(); Result result = romfs.OpenFile(ref timeZoneBinaryFile.Ref, $"/zoneinfo/{locationName}".ToU8Span(), OpenMode.Read); diff --git a/src/Ryujinx.HLE/HOS/Tamper/CodeEmitters/EndConditionalBlock.cs b/src/Ryujinx.HLE/HOS/Tamper/CodeEmitters/EndConditionalBlock.cs index fc7edd62b..5eaed6530 100644 --- a/src/Ryujinx.HLE/HOS/Tamper/CodeEmitters/EndConditionalBlock.cs +++ b/src/Ryujinx.HLE/HOS/Tamper/CodeEmitters/EndConditionalBlock.cs @@ -40,7 +40,7 @@ namespace Ryujinx.HLE.HOS.Tamper.CodeEmitters } // Use the conditional begin instruction stored in the stack. - var upperInstruction = context.CurrentBlock.BaseInstruction; + byte[] upperInstruction = context.CurrentBlock.BaseInstruction; CodeType codeType = InstructionHelper.GetCodeType(upperInstruction); // Pop the current block of operations from the stack so control instructions diff --git a/src/Ryujinx.HLE/HOS/Tamper/InstructionHelper.cs b/src/Ryujinx.HLE/HOS/Tamper/InstructionHelper.cs index 759ba5f90..46e4fd9f7 100644 --- a/src/Ryujinx.HLE/HOS/Tamper/InstructionHelper.cs +++ b/src/Ryujinx.HLE/HOS/Tamper/InstructionHelper.cs @@ -96,7 +96,7 @@ namespace Ryujinx.HLE.HOS.Tamper // Instructions are multi-word, with 32bit words. Split the raw instruction // and parse each word into individual nybbles of bits. - var words = rawInstruction.Split((char[])null, StringSplitOptions.RemoveEmptyEntries); + string[] words = rawInstruction.Split((char[])null, StringSplitOptions.RemoveEmptyEntries); byte[] instruction = new byte[WordSize * words.Length]; diff --git a/src/Ryujinx.HLE/HOS/TamperMachine.cs b/src/Ryujinx.HLE/HOS/TamperMachine.cs index 609221535..d9f4fb157 100644 --- a/src/Ryujinx.HLE/HOS/TamperMachine.cs +++ b/src/Ryujinx.HLE/HOS/TamperMachine.cs @@ -70,14 +70,14 @@ namespace Ryujinx.HLE.HOS public void EnableCheats(string[] enabledCheats) { - foreach (var program in _programDictionary.Values) + foreach (ITamperProgram program in _programDictionary.Values) { program.IsEnabled = false; } - foreach (var cheat in enabledCheats) + foreach (string cheat in enabledCheats) { - if (_programDictionary.TryGetValue(cheat, out var program)) + if (_programDictionary.TryGetValue(cheat, out ITamperProgram program)) { program.IsEnabled = true; } diff --git a/src/Ryujinx.HLE/Loaders/Executables/KipExecutable.cs b/src/Ryujinx.HLE/Loaders/Executables/KipExecutable.cs index 83380ff45..293e5f846 100644 --- a/src/Ryujinx.HLE/Loaders/Executables/KipExecutable.cs +++ b/src/Ryujinx.HLE/Loaders/Executables/KipExecutable.cs @@ -76,7 +76,7 @@ namespace Ryujinx.HLE.Loaders.Executables { reader.GetSegmentSize(segmentType, out int uncompressedSize).ThrowIfFailure(); - var span = program.AsSpan((int)offset, uncompressedSize); + Span span = program.AsSpan((int)offset, uncompressedSize); reader.ReadSegment(segmentType, span).ThrowIfFailure(); diff --git a/src/Ryujinx.HLE/Loaders/Executables/NsoExecutable.cs b/src/Ryujinx.HLE/Loaders/Executables/NsoExecutable.cs index 1caedb51e..5217612b9 100644 --- a/src/Ryujinx.HLE/Loaders/Executables/NsoExecutable.cs +++ b/src/Ryujinx.HLE/Loaders/Executables/NsoExecutable.cs @@ -65,7 +65,7 @@ namespace Ryujinx.HLE.Loaders.Executables { reader.GetSegmentSize(segmentType, out uint uncompressedSize).ThrowIfFailure(); - var span = Program.AsSpan((int)offset, (int)uncompressedSize); + Span span = Program.AsSpan((int)offset, (int)uncompressedSize); reader.ReadSegment(segmentType, span).ThrowIfFailure(); diff --git a/src/Ryujinx.HLE/Loaders/Mods/IPSPatcher.cs b/src/Ryujinx.HLE/Loaders/Mods/IPSPatcher.cs index cf316b565..d457682cf 100644 --- a/src/Ryujinx.HLE/Loaders/Mods/IPSPatcher.cs +++ b/src/Ryujinx.HLE/Loaders/Mods/IPSPatcher.cs @@ -25,7 +25,7 @@ namespace Ryujinx.HLE.Loaders.Mods ReadOnlySpan ips32TailMagic = "EEOF"u8; MemPatch patches = new(); - var header = reader.ReadBytes(ipsHeaderMagic.Length).AsSpan(); + Span header = reader.ReadBytes(ipsHeaderMagic.Length).AsSpan(); if (header.Length != ipsHeaderMagic.Length) { @@ -94,7 +94,7 @@ namespace Ryujinx.HLE.Loaders.Mods } else // Copy mode { - var patch = reader.ReadBytes(patchSize); + byte[] patch = reader.ReadBytes(patchSize); if (patch.Length != patchSize) { diff --git a/src/Ryujinx.HLE/Loaders/Mods/IPSwitchPatcher.cs b/src/Ryujinx.HLE/Loaders/Mods/IPSwitchPatcher.cs index 693e03888..b6b2c9759 100644 --- a/src/Ryujinx.HLE/Loaders/Mods/IPSwitchPatcher.cs +++ b/src/Ryujinx.HLE/Loaders/Mods/IPSwitchPatcher.cs @@ -200,7 +200,7 @@ namespace Ryujinx.HLE.Loaders.Mods } else if (line.StartsWith("@flag")) { - var tokens = line.Split(' ', 3, StringSplitOptions.RemoveEmptyEntries); + string[] tokens = line.Split(' ', 3, StringSplitOptions.RemoveEmptyEntries); if (tokens.Length < 2) { @@ -234,7 +234,7 @@ namespace Ryujinx.HLE.Loaders.Mods continue; } - var tokens = line.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries); + string[] tokens = line.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries); if (tokens.Length < 2) { @@ -259,12 +259,12 @@ namespace Ryujinx.HLE.Loaders.Mods if (tokens[1][0] == '"') { - var patch = Encoding.ASCII.GetBytes(tokens[1].Trim('"') + "\0"); + byte[] patch = Encoding.ASCII.GetBytes(tokens[1].Trim('"') + "\0"); patches.Add((uint)offset, patch); } else { - var patch = Hex2ByteArrayBE(tokens[1]); + byte[] patch = Hex2ByteArrayBE(tokens[1]); patches.Add((uint)offset, patch); } } diff --git a/src/Ryujinx.HLE/Loaders/Mods/MemPatch.cs b/src/Ryujinx.HLE/Loaders/Mods/MemPatch.cs index 0a1f12b18..9a1931433 100644 --- a/src/Ryujinx.HLE/Loaders/Mods/MemPatch.cs +++ b/src/Ryujinx.HLE/Loaders/Mods/MemPatch.cs @@ -46,7 +46,7 @@ namespace Ryujinx.HLE.Loaders.Mods return; } - foreach (var (patchOffset, patch) in patches._patches) + foreach ((uint patchOffset, byte[] patch) in patches._patches) { _patches[patchOffset] = patch; } @@ -66,7 +66,7 @@ namespace Ryujinx.HLE.Loaders.Mods public int Patch(Span memory, int protectedOffset = 0) { int count = 0; - foreach (var (offset, patch) in _patches.OrderBy(item => item.Key)) + foreach ((uint offset, byte[] patch) in _patches.OrderBy(item => item.Key)) { int patchOffset = (int)offset; int patchSize = patch.Length; diff --git a/src/Ryujinx.HLE/Loaders/Processes/Extensions/FileSystemExtensions.cs b/src/Ryujinx.HLE/Loaders/Processes/Extensions/FileSystemExtensions.cs index d1d13b00f..d68b1e200 100644 --- a/src/Ryujinx.HLE/Loaders/Processes/Extensions/FileSystemExtensions.cs +++ b/src/Ryujinx.HLE/Loaders/Processes/Extensions/FileSystemExtensions.cs @@ -62,7 +62,7 @@ namespace Ryujinx.HLE.Loaders.Processes.Extensions Logger.Info?.Print(LogClass.Loader, $"Loading {name}..."); - using var nsoFile = new UniqueRef(); + using UniqueRef nsoFile = new UniqueRef(); exeFs.OpenFile(ref nsoFile.Ref, $"/{name}".ToU8Span(), OpenMode.Read).ThrowIfFailure(); diff --git a/src/Ryujinx.HLE/Loaders/Processes/Extensions/LocalFileSystemExtensions.cs b/src/Ryujinx.HLE/Loaders/Processes/Extensions/LocalFileSystemExtensions.cs index e3ae9bf5f..a5c22177f 100644 --- a/src/Ryujinx.HLE/Loaders/Processes/Extensions/LocalFileSystemExtensions.cs +++ b/src/Ryujinx.HLE/Loaders/Processes/Extensions/LocalFileSystemExtensions.cs @@ -12,7 +12,7 @@ namespace Ryujinx.HLE.Loaders.Processes public static ProcessResult Load(this LocalFileSystem exeFs, Switch device, string romFsPath = "") { MetaLoader metaLoader = exeFs.GetNpdm(); - var nacpData = new BlitStruct(1); + BlitStruct nacpData = new BlitStruct(1); ulong programId = metaLoader.GetProgramId(); device.Configuration.VirtualFileSystem.ModLoader.CollectMods([programId]); diff --git a/src/Ryujinx.HLE/Loaders/Processes/Extensions/MetaLoaderExtensions.cs b/src/Ryujinx.HLE/Loaders/Processes/Extensions/MetaLoaderExtensions.cs index 92e71cb5a..eed7a1be5 100644 --- a/src/Ryujinx.HLE/Loaders/Processes/Extensions/MetaLoaderExtensions.cs +++ b/src/Ryujinx.HLE/Loaders/Processes/Extensions/MetaLoaderExtensions.cs @@ -12,21 +12,21 @@ namespace Ryujinx.HLE.Loaders.Processes.Extensions { public static ulong GetProgramId(this MetaLoader metaLoader) { - metaLoader.GetNpdm(out var npdm).ThrowIfFailure(); + metaLoader.GetNpdm(out LibHac.Loader.Npdm npdm).ThrowIfFailure(); return npdm.Aci.ProgramId.Value; } public static string GetProgramName(this MetaLoader metaLoader) { - metaLoader.GetNpdm(out var npdm).ThrowIfFailure(); + metaLoader.GetNpdm(out LibHac.Loader.Npdm npdm).ThrowIfFailure(); return StringUtils.Utf8ZToString(npdm.Meta.ProgramName); } public static bool IsProgram64Bit(this MetaLoader metaLoader) { - metaLoader.GetNpdm(out var npdm).ThrowIfFailure(); + metaLoader.GetNpdm(out LibHac.Loader.Npdm npdm).ThrowIfFailure(); return (npdm.Meta.Flags & 1) != 0; } @@ -45,7 +45,7 @@ namespace Ryujinx.HLE.Loaders.Processes.Extensions path = ProcessConst.MainNpdmPath; } - using var npdmFile = new UniqueRef(); + using UniqueRef npdmFile = new UniqueRef(); fileSystem.OpenFile(ref npdmFile.Ref, path.ToU8Span(), OpenMode.Read).ThrowIfFailure(); diff --git a/src/Ryujinx.HLE/Loaders/Processes/Extensions/NcaExtensions.cs b/src/Ryujinx.HLE/Loaders/Processes/Extensions/NcaExtensions.cs index 361a9159e..c4d47d5bd 100644 --- a/src/Ryujinx.HLE/Loaders/Processes/Extensions/NcaExtensions.cs +++ b/src/Ryujinx.HLE/Loaders/Processes/Extensions/NcaExtensions.cs @@ -49,7 +49,7 @@ namespace Ryujinx.HLE.Loaders.Processes.Extensions ModLoader.GetSdModsBasePath()); // Load Nacp file. - var nacpData = new BlitStruct(1); + BlitStruct nacpData = new BlitStruct(1); if (controlNca != null) { @@ -214,9 +214,9 @@ namespace Ryujinx.HLE.Loaders.Processes.Extensions public static BlitStruct GetNacp(this Nca controlNca, Switch device) { - var nacpData = new BlitStruct(1); + BlitStruct nacpData = new BlitStruct(1); - using var controlFile = new UniqueRef(); + using UniqueRef controlFile = new UniqueRef(); Result result = controlNca.OpenFileSystem(NcaSectionType.Data, device.System.FsIntegrityCheckLevel) .OpenFile(ref controlFile.Ref, "/control.nacp".ToU8Span(), OpenMode.Read); @@ -236,7 +236,7 @@ namespace Ryujinx.HLE.Loaders.Processes.Extensions public static Cnmt GetCnmt(this Nca cnmtNca, IntegrityCheckLevel checkLevel, ContentMetaType metaType) { string path = $"/{metaType}_{cnmtNca.Header.TitleId:x16}.cnmt"; - using var cnmtFile = new UniqueRef(); + using UniqueRef cnmtFile = new UniqueRef(); try { diff --git a/src/Ryujinx.HLE/Loaders/Processes/Extensions/PartitionFileSystemExtensions.cs b/src/Ryujinx.HLE/Loaders/Processes/Extensions/PartitionFileSystemExtensions.cs index b3590d9bd..4a9eafea1 100644 --- a/src/Ryujinx.HLE/Loaders/Processes/Extensions/PartitionFileSystemExtensions.cs +++ b/src/Ryujinx.HLE/Loaders/Processes/Extensions/PartitionFileSystemExtensions.cs @@ -28,7 +28,7 @@ namespace Ryujinx.HLE.Loaders.Processes.Extensions { fileSystem.ImportTickets(partitionFileSystem); - var programs = new Dictionary(); + Dictionary programs = new Dictionary(); foreach (DirectoryEntryEx fileEntry in partitionFileSystem.EnumerateEntries("/", "*.cnmt.nca")) { @@ -152,7 +152,7 @@ namespace Ryujinx.HLE.Loaders.Processes.Extensions public static Nca GetNca(this IFileSystem fileSystem, KeySet keySet, string path) { - using var ncaFile = new UniqueRef(); + using UniqueRef ncaFile = new UniqueRef(); fileSystem.OpenFile(ref ncaFile.Ref, path.ToU8Span(), OpenMode.Read).ThrowIfFailure(); diff --git a/src/Ryujinx.HLE/Loaders/Processes/ProcessLoader.cs b/src/Ryujinx.HLE/Loaders/Processes/ProcessLoader.cs index 6279ec3b4..b9746da16 100644 --- a/src/Ryujinx.HLE/Loaders/Processes/ProcessLoader.cs +++ b/src/Ryujinx.HLE/Loaders/Processes/ProcessLoader.cs @@ -161,7 +161,7 @@ namespace Ryujinx.HLE.Loaders.Processes public bool LoadNxo(string path) { - var nacpData = new BlitStruct(1); + BlitStruct nacpData = new BlitStruct(1); IFileSystem dummyExeFs = null; Stream romfsStream = null; diff --git a/src/Ryujinx.HLE/Loaders/Processes/ProcessLoaderHelper.cs b/src/Ryujinx.HLE/Loaders/Processes/ProcessLoaderHelper.cs index e4286ae90..32266d5ca 100644 --- a/src/Ryujinx.HLE/Loaders/Processes/ProcessLoaderHelper.cs +++ b/src/Ryujinx.HLE/Loaders/Processes/ProcessLoaderHelper.cs @@ -180,7 +180,7 @@ namespace Ryujinx.HLE.Loaders.Processes KProcess process = new(context); - var processContextFactory = new ArmProcessContextFactory( + ArmProcessContextFactory processContextFactory = new ArmProcessContextFactory( context.Device.System.TickSource, context.Device.Gpu, string.Empty, @@ -235,7 +235,7 @@ namespace Ryujinx.HLE.Loaders.Processes { context.Device.System.ServiceTable.WaitServicesReady(); - LibHac.Result resultCode = metaLoader.GetNpdm(out var npdm); + LibHac.Result resultCode = metaLoader.GetNpdm(out LibHac.Loader.Npdm npdm); if (resultCode.IsFailure()) { @@ -244,14 +244,14 @@ namespace Ryujinx.HLE.Loaders.Processes return ProcessResult.Failed; } - ref readonly var meta = ref npdm.Meta; + ref readonly Meta meta = ref npdm.Meta; ulong argsStart = 0; uint argsSize = 0; ulong codeStart = ((meta.Flags & 1) != 0 ? 0x8000000UL : 0x200000UL) + CodeStartOffset; uint codeSize = 0; - var buildIds = new string[executables.Length]; + string[] buildIds = new string[executables.Length]; for (int i = 0; i < executables.Length; i++) { @@ -373,7 +373,7 @@ namespace Ryujinx.HLE.Loaders.Processes displayVersion = device.System.ContentManager.GetCurrentFirmwareVersion()?.VersionString ?? string.Empty; } - var processContextFactory = new ArmProcessContextFactory( + ArmProcessContextFactory processContextFactory = new ArmProcessContextFactory( context.Device.System.TickSource, context.Device.Gpu, $"{programId:x16}", diff --git a/src/Ryujinx.HLE/StructHelpers.cs b/src/Ryujinx.HLE/StructHelpers.cs index 6e6af8cea..f573f0eb6 100644 --- a/src/Ryujinx.HLE/StructHelpers.cs +++ b/src/Ryujinx.HLE/StructHelpers.cs @@ -18,7 +18,7 @@ namespace Ryujinx.HLE const int OffsetOfApplicationPublisherStrings = 0x200; - var nacpData = new BlitStruct(1); + BlitStruct nacpData = new BlitStruct(1); // name and publisher buffer // repeat once for each locale (the ApplicationControlProperty has 16 locales) diff --git a/src/Ryujinx.HLE/UI/Input/NpadReader.cs b/src/Ryujinx.HLE/UI/Input/NpadReader.cs index 8276d6160..8b4888a26 100644 --- a/src/Ryujinx.HLE/UI/Input/NpadReader.cs +++ b/src/Ryujinx.HLE/UI/Input/NpadReader.cs @@ -1,5 +1,7 @@ +using Ryujinx.Common.Memory; using Ryujinx.HLE.HOS.Services.Hid.Types.SharedMemory.Common; using Ryujinx.HLE.HOS.Services.Hid.Types.SharedMemory.Npad; +using System; namespace Ryujinx.HLE.UI.Input { @@ -29,7 +31,7 @@ namespace Ryujinx.HLE.UI.Input { NpadButton buttons = 0; - foreach (var state in _lastStates) + foreach (NpadCommonState state in _lastStates) { buttons |= state.Buttons; } @@ -60,7 +62,7 @@ namespace Ryujinx.HLE.UI.Input public void Update(bool supressEvents = false) { - ref var npads = ref _device.Hid.SharedMemory.Npads; + ref Array10 npads = ref _device.Hid.SharedMemory.Npads; // Process each input individually. for (int npadIndex = 0; npadIndex < npads.Length; npadIndex++) @@ -73,10 +75,10 @@ namespace Ryujinx.HLE.UI.Input { const int MaxEntries = 1024; - ref var npadState = ref _device.Hid.SharedMemory.Npads[npadIndex]; - ref var lastEntry = ref _lastStates[npadIndex]; + ref NpadState npadState = ref _device.Hid.SharedMemory.Npads[npadIndex]; + ref NpadCommonState lastEntry = ref _lastStates[npadIndex]; - var fullKeyEntries = GetCommonStateLifo(ref npadState.InternalState).ReadEntries(MaxEntries); + ReadOnlySpan> fullKeyEntries = GetCommonStateLifo(ref npadState.InternalState).ReadEntries(MaxEntries); int firstEntryNum; @@ -94,7 +96,7 @@ namespace Ryujinx.HLE.UI.Input for (; firstEntryNum >= 0; firstEntryNum--) { - var entry = fullKeyEntries[firstEntryNum]; + AtomicStorage entry = fullKeyEntries[firstEntryNum]; // The interval of valid entries should be contiguous. if (entry.SamplingNumber < lastEntry.SamplingNumber) diff --git a/src/Ryujinx.HLE/Utilities/PartitionFileSystemUtils.cs b/src/Ryujinx.HLE/Utilities/PartitionFileSystemUtils.cs index 3c4ce0850..1bd6e0ff7 100644 --- a/src/Ryujinx.HLE/Utilities/PartitionFileSystemUtils.cs +++ b/src/Ryujinx.HLE/Utilities/PartitionFileSystemUtils.cs @@ -22,7 +22,7 @@ namespace Ryujinx.HLE.Utilities } else { - var pfsTemp = new PartitionFileSystem(); + PartitionFileSystem pfsTemp = new PartitionFileSystem(); Result initResult = pfsTemp.Initialize(file.AsStorage()); if (throwOnFailure) From 69e0b79bd9cd2667769ed907f411d9d244d2fde6 Mon Sep 17 00:00:00 2001 From: Evan Husted Date: Sat, 25 Jan 2025 14:14:13 -0600 Subject: [PATCH 17/19] misc: chore: Use explicit types in Horizon project --- .../Bcat/Ipc/ServiceCreator.cs | 8 +++--- .../DeliveryCacheStorageService.cs | 8 +++--- src/Ryujinx.Horizon/HeapAllocator.cs | 6 ++--- src/Ryujinx.Horizon/Sdk/Arp/ArpApi.cs | 2 +- .../Sdk/Audio/Detail/AudioInManager.cs | 3 ++- .../Sdk/Audio/Detail/AudioOutManager.cs | 3 ++- .../Sdk/Audio/Detail/AudioRendererManager.cs | 9 ++++--- src/Ryujinx.Horizon/Sdk/Lbl/LblApi.cs | 2 +- .../Sdk/Ngc/Detail/CompressedArray.cs | 4 +-- .../Sdk/OsTypes/OsSystemEvent.cs | 2 +- src/Ryujinx.Horizon/Sdk/ServiceUtil.cs | 5 ++-- .../Cmif/DomainServiceObjectDispatchTable.cs | 6 ++--- .../Sf/Cmif/DomainServiceObjectProcessor.cs | 4 +-- .../Sdk/Sf/Cmif/ServerDomainManager.cs | 16 ++++++------ .../Sdk/Sf/Cmif/ServiceDispatchTableBase.cs | 6 ++--- src/Ryujinx.Horizon/Sdk/Sf/CommandHandler.cs | 2 +- .../Sdk/Sf/CommandSerialization.cs | 2 +- src/Ryujinx.Horizon/Sdk/Sf/Hipc/Api.cs | 4 +-- .../Sdk/Sf/Hipc/HipcManager.cs | 6 ++--- .../Sdk/Sf/Hipc/ServerManagerBase.cs | 5 ++-- .../Sdk/Sf/Hipc/ServerSessionManager.cs | 6 ++--- .../Sdk/Sf/HipcCommandProcessor.cs | 26 +++++++++---------- src/Ryujinx.Horizon/Sm/Impl/ServiceManager.cs | 2 +- 23 files changed, 71 insertions(+), 66 deletions(-) diff --git a/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator.cs b/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator.cs index 78114c51f..6984d69c4 100644 --- a/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator.cs +++ b/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator.cs @@ -39,9 +39,9 @@ namespace Ryujinx.Horizon.Bcat.Ipc [CmifCommand(1)] public Result CreateDeliveryCacheStorageService(out IDeliveryCacheStorageService service, [ClientProcessId] ulong pid) { - using var libHacService = new SharedRef(); + using SharedRef libHacService = new SharedRef(); - var resultCode = _libHacService.Get.CreateDeliveryCacheStorageService(ref libHacService.Ref, pid); + LibHac.Result resultCode = _libHacService.Get.CreateDeliveryCacheStorageService(ref libHacService.Ref, pid); if (resultCode.IsSuccess()) { @@ -58,9 +58,9 @@ namespace Ryujinx.Horizon.Bcat.Ipc [CmifCommand(2)] public Result CreateDeliveryCacheStorageServiceWithApplicationId(out IDeliveryCacheStorageService service, ApplicationId applicationId) { - using var libHacService = new SharedRef(); + using SharedRef libHacService = new SharedRef(); - var resultCode = _libHacService.Get.CreateDeliveryCacheStorageServiceWithApplicationId(ref libHacService.Ref, new LibHac.ApplicationId(applicationId.Id)); + LibHac.Result resultCode = _libHacService.Get.CreateDeliveryCacheStorageServiceWithApplicationId(ref libHacService.Ref, new LibHac.ApplicationId(applicationId.Id)); if (resultCode.IsSuccess()) { diff --git a/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/DeliveryCacheStorageService.cs b/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/DeliveryCacheStorageService.cs index ecbc4bdb7..4142c14f8 100644 --- a/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/DeliveryCacheStorageService.cs +++ b/src/Ryujinx.Horizon/Bcat/Ipc/ServiceCreator/DeliveryCacheStorageService.cs @@ -22,9 +22,9 @@ namespace Ryujinx.Horizon.Bcat.Ipc [CmifCommand(0)] public Result CreateFileService(out IDeliveryCacheFileService service) { - using var libHacService = new SharedRef(); + using SharedRef libHacService = new SharedRef(); - var resultCode = _libHacService.Get.CreateFileService(ref libHacService.Ref); + LibHac.Result resultCode = _libHacService.Get.CreateFileService(ref libHacService.Ref); if (resultCode.IsSuccess()) { @@ -41,9 +41,9 @@ namespace Ryujinx.Horizon.Bcat.Ipc [CmifCommand(1)] public Result CreateDirectoryService(out IDeliveryCacheDirectoryService service) { - using var libHacService = new SharedRef(); + using SharedRef libHacService = new SharedRef(); - var resultCode = _libHacService.Get.CreateDirectoryService(ref libHacService.Ref); + LibHac.Result resultCode = _libHacService.Get.CreateDirectoryService(ref libHacService.Ref); if (resultCode.IsSuccess()) { diff --git a/src/Ryujinx.Horizon/HeapAllocator.cs b/src/Ryujinx.Horizon/HeapAllocator.cs index fc125387e..838e505d3 100644 --- a/src/Ryujinx.Horizon/HeapAllocator.cs +++ b/src/Ryujinx.Horizon/HeapAllocator.cs @@ -67,7 +67,7 @@ namespace Ryujinx.Horizon { for (int i = 0; i < _freeRanges.Count; i++) { - var range = _freeRanges[i]; + Range range = _freeRanges[i]; ulong alignedOffset = BitUtils.AlignUp(range.Offset, alignment); ulong sizeDelta = alignedOffset - range.Offset; @@ -103,7 +103,7 @@ namespace Ryujinx.Horizon private void InsertFreeRange(ulong offset, ulong size) { - var range = new Range(offset, size); + Range range = new Range(offset, size); int index = _freeRanges.BinarySearch(range); if (index < 0) { @@ -116,7 +116,7 @@ namespace Ryujinx.Horizon private void InsertFreeRangeComingled(ulong offset, ulong size) { ulong endOffset = offset + size; - var range = new Range(offset, size); + Range range = new Range(offset, size); int index = _freeRanges.BinarySearch(range); if (index < 0) { diff --git a/src/Ryujinx.Horizon/Sdk/Arp/ArpApi.cs b/src/Ryujinx.Horizon/Sdk/Arp/ArpApi.cs index b0acc0062..496de62ff 100644 --- a/src/Ryujinx.Horizon/Sdk/Arp/ArpApi.cs +++ b/src/Ryujinx.Horizon/Sdk/Arp/ArpApi.cs @@ -25,7 +25,7 @@ namespace Ryujinx.Horizon.Sdk.Arp { if (_sessionHandle == 0) { - using var smApi = new SmApi(); + using SmApi smApi = new(); smApi.Initialize(); smApi.GetServiceHandle(out _sessionHandle, ServiceName.Encode(ArpRName)).AbortOnFailure(); diff --git a/src/Ryujinx.Horizon/Sdk/Audio/Detail/AudioInManager.cs b/src/Ryujinx.Horizon/Sdk/Audio/Detail/AudioInManager.cs index d5d047201..b190cb8ae 100644 --- a/src/Ryujinx.Horizon/Sdk/Audio/Detail/AudioInManager.cs +++ b/src/Ryujinx.Horizon/Sdk/Audio/Detail/AudioInManager.cs @@ -5,6 +5,7 @@ using Ryujinx.Horizon.Common; using Ryujinx.Horizon.Sdk.Applet; using Ryujinx.Horizon.Sdk.Sf; using Ryujinx.Horizon.Sdk.Sf.Hipc; +using Ryujinx.Memory; using System; namespace Ryujinx.Horizon.Sdk.Audio.Detail @@ -49,7 +50,7 @@ namespace Ryujinx.Horizon.Sdk.Audio.Detail [Buffer(HipcBufferFlags.In | HipcBufferFlags.MapAlias)] ReadOnlySpan name, [ClientProcessId] ulong pid) { - var clientMemoryManager = HorizonStatic.Syscall.GetMemoryManagerByProcessHandle(processHandle); + IVirtualMemoryManager clientMemoryManager = HorizonStatic.Syscall.GetMemoryManagerByProcessHandle(processHandle); ResultCode rc = _impl.OpenAudioIn( out string outputDeviceName, diff --git a/src/Ryujinx.Horizon/Sdk/Audio/Detail/AudioOutManager.cs b/src/Ryujinx.Horizon/Sdk/Audio/Detail/AudioOutManager.cs index 3d129470c..facfbbc03 100644 --- a/src/Ryujinx.Horizon/Sdk/Audio/Detail/AudioOutManager.cs +++ b/src/Ryujinx.Horizon/Sdk/Audio/Detail/AudioOutManager.cs @@ -5,6 +5,7 @@ using Ryujinx.Horizon.Common; using Ryujinx.Horizon.Sdk.Applet; using Ryujinx.Horizon.Sdk.Sf; using Ryujinx.Horizon.Sdk.Sf.Hipc; +using Ryujinx.Memory; using System; namespace Ryujinx.Horizon.Sdk.Audio.Detail @@ -49,7 +50,7 @@ namespace Ryujinx.Horizon.Sdk.Audio.Detail [Buffer(HipcBufferFlags.In | HipcBufferFlags.MapAlias)] ReadOnlySpan name, [ClientProcessId] ulong pid) { - var clientMemoryManager = HorizonStatic.Syscall.GetMemoryManagerByProcessHandle(processHandle); + IVirtualMemoryManager clientMemoryManager = HorizonStatic.Syscall.GetMemoryManagerByProcessHandle(processHandle); ResultCode rc = _impl.OpenAudioOut( out string outputDeviceName, diff --git a/src/Ryujinx.Horizon/Sdk/Audio/Detail/AudioRendererManager.cs b/src/Ryujinx.Horizon/Sdk/Audio/Detail/AudioRendererManager.cs index 7138d27ce..c1c7453a1 100644 --- a/src/Ryujinx.Horizon/Sdk/Audio/Detail/AudioRendererManager.cs +++ b/src/Ryujinx.Horizon/Sdk/Audio/Detail/AudioRendererManager.cs @@ -4,6 +4,7 @@ using Ryujinx.Common.Logging; using Ryujinx.Horizon.Common; using Ryujinx.Horizon.Sdk.Applet; using Ryujinx.Horizon.Sdk.Sf; +using Ryujinx.Memory; namespace Ryujinx.Horizon.Sdk.Audio.Detail { @@ -30,11 +31,11 @@ namespace Ryujinx.Horizon.Sdk.Audio.Detail AppletResourceUserId appletResourceId, [ClientProcessId] ulong pid) { - var clientMemoryManager = HorizonStatic.Syscall.GetMemoryManagerByProcessHandle(processHandle); + IVirtualMemoryManager clientMemoryManager = HorizonStatic.Syscall.GetMemoryManagerByProcessHandle(processHandle); ulong workBufferAddress = HorizonStatic.Syscall.GetTransferMemoryAddress(workBufferHandle); Result result = new Result((int)_impl.OpenAudioRenderer( - out var renderSystem, + out AudioRenderSystem renderSystem, clientMemoryManager, ref parameter.Configuration, appletResourceId.Id, @@ -96,10 +97,10 @@ namespace Ryujinx.Horizon.Sdk.Audio.Detail AppletResourceUserId appletResourceId, [ClientProcessId] ulong pid) { - var clientMemoryManager = HorizonStatic.Syscall.GetMemoryManagerByProcessHandle(processHandle); + IVirtualMemoryManager clientMemoryManager = HorizonStatic.Syscall.GetMemoryManagerByProcessHandle(processHandle); Result result = new Result((int)_impl.OpenAudioRenderer( - out var renderSystem, + out AudioRenderSystem renderSystem, clientMemoryManager, ref parameter.Configuration, appletResourceId.Id, diff --git a/src/Ryujinx.Horizon/Sdk/Lbl/LblApi.cs b/src/Ryujinx.Horizon/Sdk/Lbl/LblApi.cs index a5622d4aa..ef42d777f 100644 --- a/src/Ryujinx.Horizon/Sdk/Lbl/LblApi.cs +++ b/src/Ryujinx.Horizon/Sdk/Lbl/LblApi.cs @@ -12,7 +12,7 @@ namespace Ryujinx.Horizon.Sdk.Lbl public LblApi() { - using var smApi = new SmApi(); + using SmApi smApi = new SmApi(); smApi.Initialize(); smApi.GetServiceHandle(out _sessionHandle, ServiceName.Encode(LblName)).AbortOnFailure(); diff --git a/src/Ryujinx.Horizon/Sdk/Ngc/Detail/CompressedArray.cs b/src/Ryujinx.Horizon/Sdk/Ngc/Detail/CompressedArray.cs index fc5cd683d..899ea57f5 100644 --- a/src/Ryujinx.Horizon/Sdk/Ngc/Detail/CompressedArray.cs +++ b/src/Ryujinx.Horizon/Sdk/Ngc/Detail/CompressedArray.cs @@ -35,13 +35,13 @@ namespace Ryujinx.Horizon.Sdk.Ngc.Detail { get { - var ranges = GetBitfieldRanges(); + ReadOnlySpan ranges = GetBitfieldRanges(); int rangeBlockIndex = index / CompressedEntriesPerBlock; if (rangeBlockIndex < ranges.Length) { - var range = ranges[rangeBlockIndex]; + BitfieldRange range = ranges[rangeBlockIndex]; int bitfieldLength = range.BitfieldLength; int bitfieldOffset = (index % CompressedEntriesPerBlock) * bitfieldLength; diff --git a/src/Ryujinx.Horizon/Sdk/OsTypes/OsSystemEvent.cs b/src/Ryujinx.Horizon/Sdk/OsTypes/OsSystemEvent.cs index 8fac94abe..701db76e0 100644 --- a/src/Ryujinx.Horizon/Sdk/OsTypes/OsSystemEvent.cs +++ b/src/Ryujinx.Horizon/Sdk/OsTypes/OsSystemEvent.cs @@ -31,7 +31,7 @@ namespace Ryujinx.Horizon.Sdk.OsTypes public static void DestroySystemEvent(ref SystemEventType sysEvent) { - var oldState = sysEvent.State; + SystemEventType.InitializationState oldState = sysEvent.State; sysEvent.State = SystemEventType.InitializationState.NotInitialized; switch (oldState) diff --git a/src/Ryujinx.Horizon/Sdk/ServiceUtil.cs b/src/Ryujinx.Horizon/Sdk/ServiceUtil.cs index 5527c1e35..b5bf853b3 100644 --- a/src/Ryujinx.Horizon/Sdk/ServiceUtil.cs +++ b/src/Ryujinx.Horizon/Sdk/ServiceUtil.cs @@ -1,6 +1,7 @@ using Ryujinx.Horizon.Common; using Ryujinx.Horizon.Sdk.Sf.Cmif; using Ryujinx.Horizon.Sdk.Sf.Hipc; +using Ryujinx.Memory; using System; namespace Ryujinx.Horizon.Sdk @@ -12,7 +13,7 @@ namespace Ryujinx.Horizon.Sdk ulong tlsAddress = HorizonStatic.ThreadContext.TlsAddress; int tlsSize = Api.TlsMessageBufferSize; - using (var tlsRegion = HorizonStatic.AddressSpace.GetWritableRegion(tlsAddress, tlsSize)) + using (WritableRegion tlsRegion = HorizonStatic.AddressSpace.GetWritableRegion(tlsAddress, tlsSize)) { CmifRequest request = CmifMessage.CreateRequest(tlsRegion.Memory.Span, new CmifRequestFormat { @@ -48,7 +49,7 @@ namespace Ryujinx.Horizon.Sdk ulong tlsAddress = HorizonStatic.ThreadContext.TlsAddress; int tlsSize = Api.TlsMessageBufferSize; - using (var tlsRegion = HorizonStatic.AddressSpace.GetWritableRegion(tlsAddress, tlsSize)) + using (WritableRegion tlsRegion = HorizonStatic.AddressSpace.GetWritableRegion(tlsAddress, tlsSize)) { CmifRequestFormat format = new() { diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/DomainServiceObjectDispatchTable.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/DomainServiceObjectDispatchTable.cs index 58957a701..1a14164c3 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/DomainServiceObjectDispatchTable.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/DomainServiceObjectDispatchTable.cs @@ -19,7 +19,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif return SfResult.InvalidHeaderSize; } - var inHeader = MemoryMarshal.Cast(inRawData)[0]; + CmifDomainInHeader inHeader = MemoryMarshal.Cast(inRawData)[0]; ReadOnlySpan inDomainRawData = inRawData[Unsafe.SizeOf()..]; @@ -28,7 +28,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif switch (inHeader.Type) { case CmifDomainRequestType.SendMessage: - var targetObject = domain.GetObject(targetObjectId); + ServiceObjectHolder targetObject = domain.GetObject(targetObjectId); if (targetObject == null) { return SfResult.TargetNotFound; @@ -48,7 +48,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif int[] inObjectIds = new int[inHeader.ObjectsCount]; - var domainProcessor = new DomainServiceObjectProcessor(domain, inObjectIds); + DomainServiceObjectProcessor domainProcessor = new DomainServiceObjectProcessor(domain, inObjectIds); if (context.Processor == null) { diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/DomainServiceObjectProcessor.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/DomainServiceObjectProcessor.cs index f677e0598..f99584610 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/DomainServiceObjectProcessor.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/DomainServiceObjectProcessor.cs @@ -44,7 +44,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif public override ServerMessageRuntimeMetadata GetRuntimeMetadata() { - var runtimeMetadata = _implProcessor.GetRuntimeMetadata(); + ServerMessageRuntimeMetadata runtimeMetadata = _implProcessor.GetRuntimeMetadata(); return new ServerMessageRuntimeMetadata( (ushort)(runtimeMetadata.InDataSize + runtimeMetadata.InObjectsCount * sizeof(int)), @@ -84,7 +84,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif public override HipcMessageData PrepareForReply(scoped ref ServiceDispatchContext context, out Span outRawData, ServerMessageRuntimeMetadata runtimeMetadata) { - var response = _implProcessor.PrepareForReply(ref context, out outRawData, runtimeMetadata); + HipcMessageData response = _implProcessor.PrepareForReply(ref context, out outRawData, runtimeMetadata); int outHeaderSize = Unsafe.SizeOf(); int implOutDataTotalSize = ImplOutDataTotalSize; diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServerDomainManager.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServerDomainManager.cs index 13f9fb7a9..ae909c9b7 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServerDomainManager.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServerDomainManager.cs @@ -45,7 +45,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif return null; } - var entry = _freeList.First.Value; + Entry entry = _freeList.First.Value; _freeList.RemoveFirst(); return entry; } @@ -92,7 +92,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif public override ServiceObjectHolder GetObject(int id) { - var entry = _manager._entryManager.GetEntry(id); + EntryManager.Entry entry = _manager._entryManager.GetEntry(id); if (entry == null) { return null; @@ -116,7 +116,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif public override void RegisterObject(int id, ServiceObjectHolder obj) { - var entry = _manager._entryManager.GetEntry(id); + EntryManager.Entry entry = _manager._entryManager.GetEntry(id); DebugUtil.Assert(entry != null); lock (_manager._entryOwnerLock) @@ -133,7 +133,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif { for (int i = 0; i < outIds.Length; i++) { - var entry = _manager._entryManager.AllocateEntry(); + EntryManager.Entry entry = _manager._entryManager.AllocateEntry(); if (entry == null) { return SfResult.OutOfDomainEntries; @@ -149,7 +149,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif public override ServiceObjectHolder UnregisterObject(int id) { - var entry = _manager._entryManager.GetEntry(id); + EntryManager.Entry entry = _manager._entryManager.GetEntry(id); if (entry == null) { return null; @@ -186,7 +186,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif { for (int i = 0; i < ids.Length; i++) { - var entry = _manager._entryManager.GetEntry(ids[i]); + EntryManager.Entry entry = _manager._entryManager.GetEntry(ids[i]); DebugUtil.Assert(entry != null); DebugUtil.Assert(entry.Owner == null); @@ -197,7 +197,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif public void Dispose() { - foreach (var entry in _entries) + foreach (EntryManager.Entry entry in _entries) { if (entry.Obj.ServiceObject is IDisposable disposableObj) { @@ -230,7 +230,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif return null; } - var domain = new Domain(this); + Domain domain = new Domain(this); _domains.Add(domain); return domain; } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServiceDispatchTableBase.cs b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServiceDispatchTableBase.cs index 2625a4c3e..f2292feff 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServiceDispatchTableBase.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Cmif/ServiceDispatchTableBase.cs @@ -35,9 +35,9 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif ReadOnlySpan inMessageRawData = inRawData[Unsafe.SizeOf()..]; uint commandId = inHeader.CommandId; - var outHeader = Span.Empty; + Span outHeader = Span.Empty; - if (!entries.TryGetValue((int)commandId, out var commandHandler)) + if (!entries.TryGetValue((int)commandId, out CommandHandler commandHandler)) { if (HorizonStatic.Options.IgnoreMissingServices) { @@ -87,7 +87,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Cmif private static void PrepareForStubReply(scoped ref ServiceDispatchContext context, out Span outRawData) { - var response = HipcMessage.WriteResponse(context.OutMessageBuffer, 0, 0x20 / sizeof(uint), 0, 0); + HipcMessageData response = HipcMessage.WriteResponse(context.OutMessageBuffer, 0, 0x20 / sizeof(uint), 0, 0); outRawData = MemoryMarshal.Cast(response.DataWords); } } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/CommandHandler.cs b/src/Ryujinx.Horizon/Sdk/Sf/CommandHandler.cs index d0efe0d4b..3dcf4a263 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/CommandHandler.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/CommandHandler.cs @@ -37,7 +37,7 @@ namespace Ryujinx.Horizon.Sdk.Sf context.Processor.SetImplementationProcessor(_processor); } - var runtimeMetadata = context.Processor.GetRuntimeMetadata(); + ServerMessageRuntimeMetadata runtimeMetadata = context.Processor.GetRuntimeMetadata(); Result result = context.Processor.PrepareForProcess(ref context, runtimeMetadata); return result.IsFailure ? result : _invoke(ref context, _processor, runtimeMetadata, inRawData, ref outHeader); diff --git a/src/Ryujinx.Horizon/Sdk/Sf/CommandSerialization.cs b/src/Ryujinx.Horizon/Sdk/Sf/CommandSerialization.cs index 7f5284648..53bbe56f9 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/CommandSerialization.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/CommandSerialization.cs @@ -27,7 +27,7 @@ namespace Ryujinx.Horizon.Sdk.Sf public static ref T GetRef(PointerAndSize bufferRange) where T : unmanaged { - var writableRegion = GetWritableRegion(bufferRange); + WritableRegion writableRegion = GetWritableRegion(bufferRange); return ref MemoryMarshal.Cast(writableRegion.Memory.Span)[0]; } diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/Api.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/Api.cs index 5f3f67061..4c8dacb8f 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/Api.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/Api.cs @@ -35,7 +35,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc handles[0] = sessionHandle; - var tlsSpan = HorizonStatic.AddressSpace.GetSpan(HorizonStatic.ThreadContext.TlsAddress, TlsMessageBufferSize); + ReadOnlySpan tlsSpan = HorizonStatic.AddressSpace.GetSpan(HorizonStatic.ThreadContext.TlsAddress, TlsMessageBufferSize); if (messageBuffer == tlsSpan) { @@ -56,7 +56,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc private static Result ReplyImpl(int sessionHandle, ReadOnlySpan messageBuffer) { - var tlsSpan = HorizonStatic.AddressSpace.GetSpan(HorizonStatic.ThreadContext.TlsAddress, TlsMessageBufferSize); + ReadOnlySpan tlsSpan = HorizonStatic.AddressSpace.GetSpan(HorizonStatic.ThreadContext.TlsAddress, TlsMessageBufferSize); if (messageBuffer == tlsSpan) { diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcManager.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcManager.cs index 4f0bbb014..953f9e755 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcManager.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/HipcManager.cs @@ -20,7 +20,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc { objectId = 0; - var domain = _manager.Domain.AllocateDomainServiceObject(); + DomainServiceObject domain = _manager.Domain.AllocateDomainServiceObject(); if (domain == null) { return HipcResult.OutOfDomains; @@ -66,7 +66,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc return HipcResult.TargetNotDomain; } - var obj = domain.GetObject(objectId); + ServiceObjectHolder obj = domain.GetObject(objectId); if (obj == null) { return HipcResult.DomainObjectNotFound; @@ -100,7 +100,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc { clientHandle = 0; - var clone = _session.ServiceObjectHolder.Clone(); + ServiceObjectHolder clone = _session.ServiceObjectHolder.Clone(); if (clone == null) { return HipcResult.DomainObjectNotFound; diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerManagerBase.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerManagerBase.cs index 31ca264e3..669dc5ee3 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerManagerBase.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerManagerBase.cs @@ -2,6 +2,7 @@ using Ryujinx.Horizon.Common; using Ryujinx.Horizon.Sdk.OsTypes; using Ryujinx.Horizon.Sdk.Sf.Cmif; using Ryujinx.Horizon.Sdk.Sm; +using Ryujinx.Memory; using System; using System.Linq; using System.Threading; @@ -257,14 +258,14 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc ServerSession session = (ServerSession)holder; - using var tlsMessage = HorizonStatic.AddressSpace.GetWritableRegion(HorizonStatic.ThreadContext.TlsAddress, Api.TlsMessageBufferSize); + using WritableRegion tlsMessage = HorizonStatic.AddressSpace.GetWritableRegion(HorizonStatic.ThreadContext.TlsAddress, Api.TlsMessageBufferSize); Result result; if (_canDeferInvokeRequest) { // If the request is deferred, we save the message on a temporary buffer to process it later. - using var savedMessage = HorizonStatic.AddressSpace.GetWritableRegion(session.SavedMessage.Address, (int)session.SavedMessage.Size); + using WritableRegion savedMessage = HorizonStatic.AddressSpace.GetWritableRegion(session.SavedMessage.Address, (int)session.SavedMessage.Size); DebugUtil.Assert(tlsMessage.Memory.Length == savedMessage.Memory.Length); diff --git a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerSessionManager.cs b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerSessionManager.cs index bd5a48444..f902768cc 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerSessionManager.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/Hipc/ServerSessionManager.cs @@ -186,7 +186,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc { CommandType commandType = GetCmifCommandType(inMessage); - using var _ = new ScopedInlineContextChange(GetInlineContext(commandType, inMessage)); + using ScopedInlineContextChange _ = new ScopedInlineContextChange(GetInlineContext(commandType, inMessage)); return commandType switch { @@ -282,7 +282,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc return HipcResult.InvalidRequestSize; } - var dispatchCtx = new ServiceDispatchContext + ServiceDispatchContext dispatchCtx = new ServiceDispatchContext { ServiceObject = objectHolder.ServiceObject, Manager = this, @@ -312,7 +312,7 @@ namespace Ryujinx.Horizon.Sdk.Sf.Hipc result = Api.Reply(session.SessionHandle, outMessage); - ref var handlesToClose = ref dispatchCtx.HandlesToClose; + ref HandlesToClose handlesToClose = ref dispatchCtx.HandlesToClose; for (int i = 0; i < handlesToClose.Count; i++) { diff --git a/src/Ryujinx.Horizon/Sdk/Sf/HipcCommandProcessor.cs b/src/Ryujinx.Horizon/Sdk/Sf/HipcCommandProcessor.cs index dc34f791a..b553115eb 100644 --- a/src/Ryujinx.Horizon/Sdk/Sf/HipcCommandProcessor.cs +++ b/src/Ryujinx.Horizon/Sdk/Sf/HipcCommandProcessor.cs @@ -46,7 +46,7 @@ namespace Ryujinx.Horizon.Sdk.Sf switch (argInfo.Type) { case CommandArgType.Buffer: - var flags = argInfo.BufferFlags; + HipcBufferFlags flags = argInfo.BufferFlags; if (flags.HasFlag(HipcBufferFlags.In)) { @@ -146,7 +146,7 @@ namespace Ryujinx.Horizon.Sdk.Sf continue; } - var flags = _args[i].BufferFlags; + HipcBufferFlags flags = _args[i].BufferFlags; bool isMapAlias; if (flags.HasFlag(HipcBufferFlags.MapAlias)) @@ -159,7 +159,7 @@ namespace Ryujinx.Horizon.Sdk.Sf } else /* if (flags.HasFlag(HipcBufferFlags.HipcAutoSelect)) */ { - var descriptor = flags.HasFlag(HipcBufferFlags.In) + HipcBufferDescriptor descriptor = flags.HasFlag(HipcBufferFlags.In) ? context.Request.Data.SendBuffers[sendMapAliasIndex] : context.Request.Data.ReceiveBuffers[recvMapAliasIndex]; @@ -170,7 +170,7 @@ namespace Ryujinx.Horizon.Sdk.Sf if (isMapAlias) { - var descriptor = flags.HasFlag(HipcBufferFlags.In) + HipcBufferDescriptor descriptor = flags.HasFlag(HipcBufferFlags.In) ? context.Request.Data.SendBuffers[sendMapAliasIndex++] : context.Request.Data.ReceiveBuffers[recvMapAliasIndex++]; @@ -185,7 +185,7 @@ namespace Ryujinx.Horizon.Sdk.Sf { if (flags.HasFlag(HipcBufferFlags.In)) { - var descriptor = context.Request.Data.SendStatics[sendPointerIndex++]; + HipcStaticDescriptor descriptor = context.Request.Data.SendStatics[sendPointerIndex++]; ulong address = descriptor.Address; ulong size = descriptor.Size; @@ -206,8 +206,8 @@ namespace Ryujinx.Horizon.Sdk.Sf } else { - var data = MemoryMarshal.Cast(context.Request.Data.DataWordsPadded); - var recvPointerSizes = MemoryMarshal.Cast(data[runtimeMetadata.UnfixedOutPointerSizeOffset..]); + Span data = MemoryMarshal.Cast(context.Request.Data.DataWordsPadded); + Span recvPointerSizes = MemoryMarshal.Cast(data[runtimeMetadata.UnfixedOutPointerSizeOffset..]); size = recvPointerSizes[unfixedRecvPointerIndex++]; } @@ -257,13 +257,13 @@ namespace Ryujinx.Horizon.Sdk.Sf continue; } - var flags = _args[i].BufferFlags; + HipcBufferFlags flags = _args[i].BufferFlags; if (!flags.HasFlag(HipcBufferFlags.Out)) { continue; } - var buffer = _bufferRanges[i]; + PointerAndSize buffer = _bufferRanges[i]; if (flags.HasFlag(HipcBufferFlags.Pointer)) { @@ -303,7 +303,7 @@ namespace Ryujinx.Horizon.Sdk.Sf public override Result PrepareForProcess(ref ServiceDispatchContext context, ServerMessageRuntimeMetadata runtimeMetadata) { - ref var meta = ref context.Request.Meta; + ref HipcMetadata meta = ref context.Request.Meta; bool requestValid = true; requestValid &= meta.SendPid == _hasInProcessIdHolder; requestValid &= meta.SendStaticsCount == _inPointerBuffersCount; @@ -346,7 +346,7 @@ namespace Ryujinx.Horizon.Sdk.Sf } int index = inObjectIndex++; - var inObject = inObjects[index]; + ServiceObjectHolder inObject = inObjects[index]; objects[index] = inObject?.ServiceObject; } @@ -362,7 +362,7 @@ namespace Ryujinx.Horizon.Sdk.Sf public override HipcMessageData PrepareForReply(scoped ref ServiceDispatchContext context, out Span outRawData, ServerMessageRuntimeMetadata runtimeMetadata) { int rawDataSize = OutRawDataSize + runtimeMetadata.OutHeadersSize; - var response = HipcMessage.WriteResponse( + HipcMessageData response = HipcMessage.WriteResponse( context.OutMessageBuffer, _outPointerBuffersCount, (BitUtils.AlignUp(rawDataSize, 4) + 0x10) / sizeof(uint), @@ -376,7 +376,7 @@ namespace Ryujinx.Horizon.Sdk.Sf public override void PrepareForErrorReply(scoped ref ServiceDispatchContext context, out Span outRawData, ServerMessageRuntimeMetadata runtimeMetadata) { int rawDataSize = runtimeMetadata.OutHeadersSize; - var response = HipcMessage.WriteResponse( + HipcMessageData response = HipcMessage.WriteResponse( context.OutMessageBuffer, 0, (BitUtils.AlignUp(rawDataSize, 4) + 0x10) / sizeof(uint), diff --git a/src/Ryujinx.Horizon/Sm/Impl/ServiceManager.cs b/src/Ryujinx.Horizon/Sm/Impl/ServiceManager.cs index 177cc0d3d..c13b85c4c 100644 --- a/src/Ryujinx.Horizon/Sm/Impl/ServiceManager.cs +++ b/src/Ryujinx.Horizon/Sm/Impl/ServiceManager.cs @@ -120,7 +120,7 @@ namespace Ryujinx.Horizon.Sm.Impl return SmResult.NotRegistered; } - ref var serviceInfo = ref _services[serviceIndex]; + ref ServiceInfo serviceInfo = ref _services[serviceIndex]; if (serviceInfo.OwnerProcessId != processId) { return SmResult.NotAllowed; From 93539e7d45caae8dae3c86a756bd77b2e526200d Mon Sep 17 00:00:00 2001 From: Evan Husted Date: Sat, 25 Jan 2025 14:14:40 -0600 Subject: [PATCH 18/19] misc: chore: Use explicit types in GAL --- .../Multithreading/ThreadedPipeline.cs | 2 +- .../Multithreading/ThreadedRenderer.cs | 14 +++++++------- src/Ryujinx.Graphics.GAL/ResourceLayout.cs | 2 +- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/Ryujinx.Graphics.GAL/Multithreading/ThreadedPipeline.cs b/src/Ryujinx.Graphics.GAL/Multithreading/ThreadedPipeline.cs index deec36648..c999ad789 100644 --- a/src/Ryujinx.Graphics.GAL/Multithreading/ThreadedPipeline.cs +++ b/src/Ryujinx.Graphics.GAL/Multithreading/ThreadedPipeline.cs @@ -359,7 +359,7 @@ namespace Ryujinx.Graphics.GAL.Multithreading public bool TryHostConditionalRendering(ICounterEvent value, ulong compare, bool isEqual) { - var evt = value as ThreadedCounterEvent; + ThreadedCounterEvent evt = value as ThreadedCounterEvent; if (evt != null) { if (compare == 0 && evt.Type == CounterType.SamplesPassed && evt.ClearCounter) diff --git a/src/Ryujinx.Graphics.GAL/Multithreading/ThreadedRenderer.cs b/src/Ryujinx.Graphics.GAL/Multithreading/ThreadedRenderer.cs index 6375d290c..676cbe8fc 100644 --- a/src/Ryujinx.Graphics.GAL/Multithreading/ThreadedRenderer.cs +++ b/src/Ryujinx.Graphics.GAL/Multithreading/ThreadedRenderer.cs @@ -294,7 +294,7 @@ namespace Ryujinx.Graphics.GAL.Multithreading public IImageArray CreateImageArray(int size, bool isBuffer) { - var imageArray = new ThreadedImageArray(this); + ThreadedImageArray imageArray = new(this); New().Set(Ref(imageArray), size, isBuffer); QueueCommand(); @@ -303,7 +303,7 @@ namespace Ryujinx.Graphics.GAL.Multithreading public IProgram CreateProgram(ShaderSource[] shaders, ShaderInfo info) { - var program = new ThreadedProgram(this); + ThreadedProgram program = new(this); SourceProgramRequest request = new(program, shaders, info); @@ -319,7 +319,7 @@ namespace Ryujinx.Graphics.GAL.Multithreading public ISampler CreateSampler(SamplerCreateInfo info) { - var sampler = new ThreadedSampler(this); + ThreadedSampler sampler = new(this); New().Set(Ref(sampler), info); QueueCommand(); @@ -337,7 +337,7 @@ namespace Ryujinx.Graphics.GAL.Multithreading { if (IsGpuThread()) { - var texture = new ThreadedTexture(this, info); + ThreadedTexture texture = new ThreadedTexture(this, info); New().Set(Ref(texture), info); QueueCommand(); @@ -345,7 +345,7 @@ namespace Ryujinx.Graphics.GAL.Multithreading } else { - var texture = new ThreadedTexture(this, info) + ThreadedTexture texture = new ThreadedTexture(this, info) { Base = _baseRenderer.CreateTexture(info), }; @@ -355,7 +355,7 @@ namespace Ryujinx.Graphics.GAL.Multithreading } public ITextureArray CreateTextureArray(int size, bool isBuffer) { - var textureArray = new ThreadedTextureArray(this); + ThreadedTextureArray textureArray = new ThreadedTextureArray(this); New().Set(Ref(textureArray), size, isBuffer); QueueCommand(); @@ -414,7 +414,7 @@ namespace Ryujinx.Graphics.GAL.Multithreading public IProgram LoadProgramBinary(byte[] programBinary, bool hasFragmentShader, ShaderInfo info) { - var program = new ThreadedProgram(this); + ThreadedProgram program = new ThreadedProgram(this); BinaryProgramRequest request = new(program, programBinary, hasFragmentShader, info); Programs.Add(request); diff --git a/src/Ryujinx.Graphics.GAL/ResourceLayout.cs b/src/Ryujinx.Graphics.GAL/ResourceLayout.cs index b7464ee12..c91eed3d2 100644 --- a/src/Ryujinx.Graphics.GAL/ResourceLayout.cs +++ b/src/Ryujinx.Graphics.GAL/ResourceLayout.cs @@ -126,7 +126,7 @@ namespace Ryujinx.Graphics.GAL if (Descriptors != null) { - foreach (var descriptor in Descriptors) + foreach (ResourceDescriptor descriptor in Descriptors) { hasher.Add(descriptor); } From 250acab7a7c5562451eba80b1c1a04b6883e184c Mon Sep 17 00:00:00 2001 From: Evan Husted Date: Sat, 25 Jan 2025 14:15:47 -0600 Subject: [PATCH 19/19] misc: chore: Use explicit types in Tests projects --- src/Ryujinx.Common/Configuration/DirtyHack.cs | 3 +- .../SequenceReaderExtensionsTests.cs | 42 +++++++++--------- src/Ryujinx.Tests/Cpu/CpuTest32.cs | 2 +- src/Ryujinx.Tests/Cpu/CpuTestSimdCvt32.cs | 4 +- src/Ryujinx.Tests/Cpu/CpuTestSimdMemory32.cs | 18 ++++---- src/Ryujinx.Tests/Cpu/CpuTestSimdMov32.cs | 3 +- src/Ryujinx.Tests/Cpu/EnvironmentTests.cs | 2 +- src/Ryujinx.Tests/Memory/PartialUnmaps.cs | 43 ++++++++++--------- 8 files changed, 60 insertions(+), 57 deletions(-) diff --git a/src/Ryujinx.Common/Configuration/DirtyHack.cs b/src/Ryujinx.Common/Configuration/DirtyHack.cs index 6564f8567..3959c0a99 100644 --- a/src/Ryujinx.Common/Configuration/DirtyHack.cs +++ b/src/Ryujinx.Common/Configuration/DirtyHack.cs @@ -24,7 +24,8 @@ namespace Ryujinx.Common.Configuration public static EnabledDirtyHack Unpack(ulong packedHack) { uint[] unpackedFields = packedHack.UnpackBitFields(PackedFormat); - if (unpackedFields is not [var hack, var value]) + // ReSharper disable once PatternAlwaysMatches + if (unpackedFields is not [uint hack, uint value]) throw new Exception("The unpack operation on the integer resulted in an invalid unpacked result."); return new EnabledDirtyHack((DirtyHack)hack, (int)value); diff --git a/src/Ryujinx.Tests/Common/Extensions/SequenceReaderExtensionsTests.cs b/src/Ryujinx.Tests/Common/Extensions/SequenceReaderExtensionsTests.cs index c0127530a..de81ec303 100644 --- a/src/Ryujinx.Tests/Common/Extensions/SequenceReaderExtensionsTests.cs +++ b/src/Ryujinx.Tests/Common/Extensions/SequenceReaderExtensionsTests.cs @@ -23,9 +23,9 @@ namespace Ryujinx.Tests.Common.Extensions ReadOnlySequence sequence = CreateSegmentedByteSequence(originalStructs, maxSegmentSize ?? Unsafe.SizeOf()); - var sequenceReader = new SequenceReader(sequence); + SequenceReader sequenceReader = new SequenceReader(sequence); - foreach (var original in originalStructs) + foreach (MyUnmanagedStruct original in originalStructs) { // Act ref readonly MyUnmanagedStruct read = ref sequenceReader.GetRefOrRefToCopy(out _); @@ -43,12 +43,12 @@ namespace Ryujinx.Tests.Common.Extensions ReadOnlySequence sequence = CreateSegmentedByteSequence(originalStructs, 3); - var sequenceReader = new SequenceReader(sequence); + SequenceReader sequenceReader = new SequenceReader(sequence); - foreach (var original in originalStructs) + foreach (MyUnmanagedStruct original in originalStructs) { // Act - ref readonly MyUnmanagedStruct read = ref sequenceReader.GetRefOrRefToCopy(out var copy); + ref readonly MyUnmanagedStruct read = ref sequenceReader.GetRefOrRefToCopy(out MyUnmanagedStruct copy); // Assert MyUnmanagedStruct.Assert(Assert.AreEqual, original, read); @@ -64,12 +64,12 @@ namespace Ryujinx.Tests.Common.Extensions ReadOnlySequence sequence = CreateSegmentedByteSequence(originalStructs, int.MaxValue); - var sequenceReader = new SequenceReader(sequence); + SequenceReader sequenceReader = new SequenceReader(sequence); - foreach (var original in originalStructs) + foreach (MyUnmanagedStruct original in originalStructs) { // Act - ref readonly MyUnmanagedStruct read = ref sequenceReader.GetRefOrRefToCopy(out var copy); + ref readonly MyUnmanagedStruct read = ref sequenceReader.GetRefOrRefToCopy(out MyUnmanagedStruct copy); // Assert MyUnmanagedStruct.Assert(Assert.AreEqual, original, read); @@ -88,7 +88,7 @@ namespace Ryujinx.Tests.Common.Extensions // Act/Assert Assert.Throws(() => { - var sequenceReader = new SequenceReader(sequence); + SequenceReader sequenceReader = new SequenceReader(sequence); sequenceReader.Advance(1); @@ -106,7 +106,7 @@ namespace Ryujinx.Tests.Common.Extensions BinaryPrimitives.WriteInt32LittleEndian(buffer.AsSpan(), TestValue); - var sequenceReader = new SequenceReader(new ReadOnlySequence(buffer)); + SequenceReader sequenceReader = new SequenceReader(new ReadOnlySequence(buffer)); // Act sequenceReader.ReadLittleEndian(out int roundTrippedValue); @@ -125,7 +125,7 @@ namespace Ryujinx.Tests.Common.Extensions BinaryPrimitives.WriteInt32BigEndian(buffer.AsSpan(), TestValue); - var sequenceReader = new SequenceReader(new ReadOnlySequence(buffer)); + SequenceReader sequenceReader = new SequenceReader(new ReadOnlySequence(buffer)); // Act sequenceReader.ReadLittleEndian(out int roundTrippedValue); @@ -147,7 +147,7 @@ namespace Ryujinx.Tests.Common.Extensions // Act/Assert Assert.Throws(() => { - var sequenceReader = new SequenceReader(new ReadOnlySequence(buffer)); + SequenceReader sequenceReader = new SequenceReader(new ReadOnlySequence(buffer)); sequenceReader.Advance(1); sequenceReader.ReadLittleEndian(out int roundTrippedValue); @@ -173,7 +173,7 @@ namespace Ryujinx.Tests.Common.Extensions // Act/Assert Assert.Throws(() => { - var sequenceReader = new SequenceReader(sequence); + SequenceReader sequenceReader = new SequenceReader(sequence); sequenceReader.Advance(1); @@ -200,7 +200,7 @@ namespace Ryujinx.Tests.Common.Extensions Assert.Throws(() => { - var sequenceReader = new SequenceReader(sequence); + SequenceReader sequenceReader = new SequenceReader(sequence); sequenceReader.SetConsumed(MyUnmanagedStruct.SizeOf * StructCount + 1); }); @@ -213,9 +213,9 @@ namespace Ryujinx.Tests.Common.Extensions ReadOnlySequence sequence = CreateSegmentedByteSequence(originalStructs, maxSegmentLength); - var sequenceReader = new SequenceReader(sequence); + SequenceReader sequenceReader = new SequenceReader(sequence); - foreach (var original in originalStructs) + foreach (MyUnmanagedStruct original in originalStructs) { // Act sequenceReader.ReadUnmanaged(out MyUnmanagedStruct read); @@ -232,7 +232,7 @@ namespace Ryujinx.Tests.Common.Extensions ReadOnlySequence sequence = CreateSegmentedByteSequence(originalStructs, maxSegmentLength); - var sequenceReader = new SequenceReader(sequence); + SequenceReader sequenceReader = new SequenceReader(sequence); static void SetConsumedAndAssert(scoped ref SequenceReader sequenceReader, long consumed) { @@ -283,7 +283,7 @@ namespace Ryujinx.Tests.Common.Extensions const int BaseInt32Value = 0x1234abcd; const short BaseInt16Value = 0x5678; - var result = new MyUnmanagedStruct + MyUnmanagedStruct result = new MyUnmanagedStruct { BehaviourSize = BaseInt32Value ^ rng.Next(), MemoryPoolsSize = BaseInt32Value ^ rng.Next(), @@ -320,7 +320,7 @@ namespace Ryujinx.Tests.Common.Extensions private static IEnumerable EnumerateNewUnmanagedStructs() { - var rng = new Random(0); + Random rng = new Random(0); while (true) { @@ -331,7 +331,7 @@ namespace Ryujinx.Tests.Common.Extensions private static ReadOnlySequence CreateSegmentedByteSequence(T[] array, int maxSegmentLength) where T : unmanaged { byte[] arrayBytes = MemoryMarshal.AsBytes(array.AsSpan()).ToArray(); - var memory = new Memory(arrayBytes); + Memory memory = new Memory(arrayBytes); int index = 0; BytesReadOnlySequenceSegment first = null, last = null; @@ -339,7 +339,7 @@ namespace Ryujinx.Tests.Common.Extensions while (index < memory.Length) { int nextSegmentLength = Math.Min(maxSegmentLength, memory.Length - index); - var nextSegment = memory.Slice(index, nextSegmentLength); + Memory nextSegment = memory.Slice(index, nextSegmentLength); if (first == null) { diff --git a/src/Ryujinx.Tests/Cpu/CpuTest32.cs b/src/Ryujinx.Tests/Cpu/CpuTest32.cs index 6a690834f..81ed9bcc9 100644 --- a/src/Ryujinx.Tests/Cpu/CpuTest32.cs +++ b/src/Ryujinx.Tests/Cpu/CpuTest32.cs @@ -296,7 +296,7 @@ namespace Ryujinx.Tests.Cpu FinalRegs = test.FinalRegs, }); - foreach (var (address, value) in test.MemoryDelta) + foreach ((ulong address, ushort value) in test.MemoryDelta) { testMem[address - DataBaseAddress + 0] = (byte)(value >> 0); testMem[address - DataBaseAddress + 1] = (byte)(value >> 8); diff --git a/src/Ryujinx.Tests/Cpu/CpuTestSimdCvt32.cs b/src/Ryujinx.Tests/Cpu/CpuTestSimdCvt32.cs index ba201a480..8768d6bd6 100644 --- a/src/Ryujinx.Tests/Cpu/CpuTestSimdCvt32.cs +++ b/src/Ryujinx.Tests/Cpu/CpuTestSimdCvt32.cs @@ -465,7 +465,7 @@ namespace Ryujinx.Tests.Cpu opcode |= (fixImm & 0x3f) << 16; - var v0 = new V128((uint)s0, (uint)s1, (uint)s2, (uint)s3); + V128 v0 = new V128((uint)s0, (uint)s1, (uint)s2, (uint)s3); SingleOpcode(opcode, v0: v0); @@ -505,7 +505,7 @@ namespace Ryujinx.Tests.Cpu opcode |= (fixImm & 0x3f) << 16; - var v0 = new V128(s0, s1, s2, s3); + V128 v0 = new V128(s0, s1, s2, s3); SingleOpcode(opcode, v0: v0); diff --git a/src/Ryujinx.Tests/Cpu/CpuTestSimdMemory32.cs b/src/Ryujinx.Tests/Cpu/CpuTestSimdMemory32.cs index d59e963b5..441b09c29 100644 --- a/src/Ryujinx.Tests/Cpu/CpuTestSimdMemory32.cs +++ b/src/Ryujinx.Tests/Cpu/CpuTestSimdMemory32.cs @@ -44,7 +44,7 @@ namespace Ryujinx.Tests.Cpu [Range(0u, 3u)] uint n, [Values(0x0u)] uint offset) { - var data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); + byte[] data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); SetWorkingMemory(0, data); uint opcode = 0xf4a00000u; // VLD1.8 {D0[0]}, [R0], R0 @@ -74,7 +74,7 @@ namespace Ryujinx.Tests.Cpu [Values] bool t, [Values(0x0u)] uint offset) { - var data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); + byte[] data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); SetWorkingMemory(0, data); uint opcode = 0xf4a00c00u; // VLD1.8 {D0[0]}, [R0], R0 @@ -103,7 +103,7 @@ namespace Ryujinx.Tests.Cpu [Range(0u, 10u)] uint mode, [Values(0x0u)] uint offset) { - var data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); + byte[] data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); SetWorkingMemory(0, data); uint opcode = 0xf4200000u; // VLD4.8 {D0, D1, D2, D3}, [R0], R0 @@ -133,7 +133,7 @@ namespace Ryujinx.Tests.Cpu [Range(0u, 3u)] uint n, [Values(0x0u)] uint offset) { - var data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); + byte[] data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); SetWorkingMemory(0, data); (V128 vec1, V128 vec2, V128 vec3, V128 vec4) = GenerateTestVectors(); @@ -164,7 +164,7 @@ namespace Ryujinx.Tests.Cpu [Range(0u, 10u)] uint mode, [Values(0x0u)] uint offset) { - var data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); + byte[] data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); SetWorkingMemory(0, data); (V128 vec1, V128 vec2, V128 vec3, V128 vec4) = GenerateTestVectors(); @@ -194,7 +194,7 @@ namespace Ryujinx.Tests.Cpu [Values(0x1u, 0x32u)] uint regs, [Values] bool single) { - var data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); + byte[] data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); SetWorkingMemory(0, data); uint opcode = 0xec100a00u; // VST4.8 {D0, D1, D2, D3}, [R0], R0 @@ -246,7 +246,7 @@ namespace Ryujinx.Tests.Cpu [Values(0x0u)] uint imm, [Values] bool sub) { - var data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); + byte[] data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); SetWorkingMemory(0, data); uint opcode = 0xed900a00u; // VLDR.32 S0, [R0, #0] @@ -281,7 +281,7 @@ namespace Ryujinx.Tests.Cpu [Values(0x0u)] uint imm, [Values] bool sub) { - var data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); + byte[] data = GenerateVectorSequence((int)MemoryBlock.GetPageSize()); SetWorkingMemory(0, data); uint opcode = 0xed800a00u; // VSTR.32 S0, [R0, #0] @@ -331,7 +331,7 @@ namespace Ryujinx.Tests.Cpu data[i] = i + (i / 9f); } - var result = new byte[length]; + byte[] result = new byte[length]; Buffer.BlockCopy(data, 0, result, 0, result.Length); return result; } diff --git a/src/Ryujinx.Tests/Cpu/CpuTestSimdMov32.cs b/src/Ryujinx.Tests/Cpu/CpuTestSimdMov32.cs index 85f77fff1..5cc993e5e 100644 --- a/src/Ryujinx.Tests/Cpu/CpuTestSimdMov32.cs +++ b/src/Ryujinx.Tests/Cpu/CpuTestSimdMov32.cs @@ -2,6 +2,7 @@ using ARMeilleure.State; using NUnit.Framework; +using NUnit.Framework.Internal; namespace Ryujinx.Tests.Cpu { @@ -467,7 +468,7 @@ namespace Ryujinx.Tests.Cpu opcode |= (vn & 0xf) << 16; opcode |= (length & 0x3) << 8; - var rnd = TestContext.CurrentContext.Random; + Randomizer rnd = TestContext.CurrentContext.Random; V128 v2 = new(TestContext.CurrentContext.Random.NextULong(), TestContext.CurrentContext.Random.NextULong()); V128 v3 = new(TestContext.CurrentContext.Random.NextULong(), TestContext.CurrentContext.Random.NextULong()); V128 v4 = new(TestContext.CurrentContext.Random.NextULong(), TestContext.CurrentContext.Random.NextULong()); diff --git a/src/Ryujinx.Tests/Cpu/EnvironmentTests.cs b/src/Ryujinx.Tests/Cpu/EnvironmentTests.cs index 43c84c193..da4997e26 100644 --- a/src/Ryujinx.Tests/Cpu/EnvironmentTests.cs +++ b/src/Ryujinx.Tests/Cpu/EnvironmentTests.cs @@ -53,7 +53,7 @@ namespace Ryujinx.Tests.Cpu bool methodCalled = false; bool isFz = false; - var method = TranslatorTestMethods.GenerateFpFlagsPInvokeTest(); + TranslatorTestMethods.FpFlagsPInvokeTest method = TranslatorTestMethods.GenerateFpFlagsPInvokeTest(); // This method sets flush-to-zero and then calls the managed method. // Before and after setting the flags, it ensures subnormal addition works as expected. diff --git a/src/Ryujinx.Tests/Memory/PartialUnmaps.cs b/src/Ryujinx.Tests/Memory/PartialUnmaps.cs index 3e5b47423..d120a39e1 100644 --- a/src/Ryujinx.Tests/Memory/PartialUnmaps.cs +++ b/src/Ryujinx.Tests/Memory/PartialUnmaps.cs @@ -3,6 +3,7 @@ using ARMeilleure.Memory; using ARMeilleure.Signal; using ARMeilleure.Translation; using NUnit.Framework; +using Ryujinx.Common.Memory; using Ryujinx.Common.Memory.PartialUnmaps; using Ryujinx.Cpu; using Ryujinx.Cpu.Jit; @@ -26,11 +27,11 @@ namespace Ryujinx.Tests.Memory { MemoryAllocationFlags asFlags = MemoryAllocationFlags.Reserve | MemoryAllocationFlags.ViewCompatible; - var addressSpace = new MemoryBlock(asSize, asFlags); - var addressSpaceMirror = new MemoryBlock(asSize, asFlags); + MemoryBlock addressSpace = new MemoryBlock(asSize, asFlags); + MemoryBlock addressSpaceMirror = new MemoryBlock(asSize, asFlags); - var tracking = new MemoryTracking(new MockVirtualMemoryManager(asSize, 0x1000), 0x1000); - var exceptionHandler = new MemoryEhMeilleure(addressSpace, addressSpaceMirror, tracking); + MemoryTracking tracking = new MemoryTracking(new MockVirtualMemoryManager(asSize, 0x1000), 0x1000); + MemoryEhMeilleure exceptionHandler = new MemoryEhMeilleure(addressSpace, addressSpaceMirror, tracking); return (addressSpace, addressSpaceMirror, exceptionHandler); } @@ -39,7 +40,7 @@ namespace Ryujinx.Tests.Memory { int count = 0; - ref var ids = ref state.LocalCounts.ThreadIds; + ref Array20 ids = ref state.LocalCounts.ThreadIds; for (int i = 0; i < ids.Length; i++) { @@ -71,13 +72,13 @@ namespace Ryujinx.Tests.Memory ulong vaSize = 0x100000; // The first 0x100000 is mapped to start. It is replaced from the center with the 0x200000 mapping. - var backing = new MemoryBlock(vaSize * 2, MemoryAllocationFlags.Mirrorable); + MemoryBlock backing = new MemoryBlock(vaSize * 2, MemoryAllocationFlags.Mirrorable); (MemoryBlock unusedMainMemory, MemoryBlock memory, MemoryEhMeilleure exceptionHandler) = GetVirtual(vaSize * 2); EnsureTranslator(); - ref var state = ref PartialUnmapState.GetRef(); + ref PartialUnmapState state = ref PartialUnmapState.GetRef(); Thread testThread = null; bool shouldAccess = true; @@ -216,17 +217,17 @@ namespace Ryujinx.Tests.Memory ulong vaSize = 0x100000; // The first 0x100000 is mapped to start. It is replaced from the center with the 0x200000 mapping. - var backing = new MemoryBlock(vaSize * 2, MemoryAllocationFlags.Mirrorable); + MemoryBlock backing = new MemoryBlock(vaSize * 2, MemoryAllocationFlags.Mirrorable); (MemoryBlock mainMemory, MemoryBlock unusedMirror, MemoryEhMeilleure exceptionHandler) = GetVirtual(vaSize * 2); EnsureTranslator(); - ref var state = ref PartialUnmapState.GetRef(); + ref PartialUnmapState state = ref PartialUnmapState.GetRef(); // Create some state to be used for managing the native writing loop. int stateSize = Unsafe.SizeOf(); - var statePtr = Marshal.AllocHGlobal(stateSize); + IntPtr statePtr = Marshal.AllocHGlobal(stateSize); Unsafe.InitBlockUnaligned((void*)statePtr, 0, (uint)stateSize); ref NativeWriteLoopState writeLoopState = ref Unsafe.AsRef((void*)statePtr); @@ -241,7 +242,7 @@ namespace Ryujinx.Tests.Memory // Create a large mapping. mainMemory.MapView(backing, 0, 0, vaSize); - var writeFunc = TestMethods.GenerateDebugNativeWriteLoop(); + TestMethods.DebugNativeWriteLoop writeFunc = TestMethods.GenerateDebugNativeWriteLoop(); nint writePtr = mainMemory.GetPointer(vaSize - 0x1000, 4); Thread testThread = new(() => @@ -292,10 +293,10 @@ namespace Ryujinx.Tests.Memory public void ThreadLocalMap() { PartialUnmapState.Reset(); - ref var state = ref PartialUnmapState.GetRef(); + ref PartialUnmapState state = ref PartialUnmapState.GetRef(); bool running = true; - var testThread = new Thread(() => + Thread testThread = new Thread(() => { PartialUnmapState.GetRef().RetryFromAccessViolation(); while (running) @@ -331,11 +332,11 @@ namespace Ryujinx.Tests.Memory PartialUnmapState.Reset(); - ref var state = ref PartialUnmapState.GetRef(); + ref PartialUnmapState state = ref PartialUnmapState.GetRef(); fixed (void* localMap = &state.LocalCounts) { - var getOrReserve = TestMethods.GenerateDebugThreadLocalMapGetOrReserve((nint)localMap); + TestMethods.DebugThreadLocalMapGetOrReserve getOrReserve = TestMethods.GenerateDebugThreadLocalMapGetOrReserve((nint)localMap); for (int i = 0; i < ThreadLocalMap.MapSize; i++) { @@ -375,8 +376,8 @@ namespace Ryujinx.Tests.Memory [Test] public void NativeReaderWriterLock() { - var rwLock = new NativeReaderWriterLock(); - var threads = new List(); + NativeReaderWriterLock rwLock = new NativeReaderWriterLock(); + List threads = new List(); int value = 0; @@ -386,7 +387,7 @@ namespace Ryujinx.Tests.Memory for (int i = 0; i < 5; i++) { - var readThread = new Thread(() => + Thread readThread = new Thread(() => { int count = 0; while (running) @@ -423,7 +424,7 @@ namespace Ryujinx.Tests.Memory for (int i = 0; i < 2; i++) { - var writeThread = new Thread(() => + Thread writeThread = new Thread(() => { int count = 0; while (running) @@ -453,7 +454,7 @@ namespace Ryujinx.Tests.Memory threads.Add(writeThread); } - foreach (var thread in threads) + foreach (Thread thread in threads) { thread.Start(); } @@ -462,7 +463,7 @@ namespace Ryujinx.Tests.Memory running = false; - foreach (var thread in threads) + foreach (Thread thread in threads) { thread.Join(); }