diff --git a/StarterNG.Tests/GraphicsCardsTests.cs b/StarterNG.Tests/GraphicsCardsTests.cs index f793054..6ba2fce 100644 --- a/StarterNG.Tests/GraphicsCardsTests.cs +++ b/StarterNG.Tests/GraphicsCardsTests.cs @@ -99,6 +99,83 @@ public class GraphicsCardsTests Assert.Equal(new[] { "AMD Radeon RX 6700 XT", "AMD Radeon 780M" }, cards.Select(card => card.Name)); } + private static GraphicsCards WindowsReader(IReadOnlyList? dxgi, params GraphicsCard[] registry) => + new(new InMemoryFileSystem(), new FakeEnvironment().AsWindows(), new LinuxGpus(new InMemoryFileSystem(), new FakeEnvironment()), + () => Array.Empty(), () => dxgi, () => registry); + + private static DxgiAdapter Adapter(string name, uint vendor, long memory, uint flags = 0) => + new(name, vendor, (ulong)memory, flags); + + [Fact] + public void Windows_takes_the_cards_dxgi_lists_and_the_discrete_one_first() + { + var reader = WindowsReader( + new[] { Adapter("AMD Radeon(TM) Graphics", 0x1002, GiB / 2), Adapter("NVIDIA GeForce RTX 3060", 0x10DE, 12 * GiB) }, + new GraphicsCard("AMD Radeon(TM) Graphics", GiB / 2)); + + var cards = reader.List(); + + Assert.Equal(new[] { "NVIDIA GeForce RTX 3060", "AMD Radeon(TM) Graphics" }, cards.Select(card => card.Name)); + Assert.Equal(12, cards[0].MemoryGb); + } + + [Fact] + public void Software_adapters_are_no_cards() + { + var cards = DxgiAdapters.Cards(new[] + { + Adapter("Microsoft Basic Render Driver", 0x1414, 0, flags: 2), + Adapter("Microsoft Remote Display Adapter", 0x1414, 0), + Adapter("Some software rasterizer", 0x1234, 0, flags: 2), + Adapter("NVIDIA GeForce RTX 5060 Laptop GPU", 0x10DE, 8546942976) + }); + + Assert.Equal("NVIDIA GeForce RTX 5060 Laptop GPU", Assert.Single(cards).Name); + } + + [Fact] + public void A_card_dxgi_lists_twice_is_shown_once() + { + var cards = DxgiAdapters.Cards(new[] + { + Adapter("AMD Radeon 780M Graphics", 0x1002, GiB / 2), + Adapter("AMD Radeon 780M Graphics ", 0x1002, GiB / 2) + }); + + Assert.Equal("AMD Radeon 780M Graphics", Assert.Single(cards).Name); + } + + [Fact] + public void The_registry_answers_when_dxgi_cannot_be_asked() + { + var card = Assert.Single(WindowsReader(null, new GraphicsCard("NVIDIA GeForce RTX 3060", 12 * GiB)).List()); + + Assert.Equal("NVIDIA GeForce RTX 3060", card.Name); + } + + [Fact] + public void The_registry_answers_when_dxgi_lists_only_software() + { + var reader = WindowsReader(new[] { Adapter("Microsoft Basic Render Driver", 0x1414, 0, flags: 2) }, + new GraphicsCard("AMD Radeon(TM) Graphics", GiB / 2)); + + Assert.Equal("AMD Radeon(TM) Graphics", Assert.Single(reader.List()).Name); + } + + [Fact] + public void Dxgi_answers_on_this_machine() + { + if (!OperatingSystem.IsWindows()) + return; + + // Every Windows lists at least the Basic Render Driver, so an answer means the calls work. + var adapters = DxgiAdapters.Read(); + + Assert.NotNull(adapters); + Assert.NotEmpty(adapters); + Assert.All(adapters, adapter => Assert.False(string.IsNullOrWhiteSpace(adapter.Description))); + } + [Fact] public void There_are_no_cards_on_a_mac() { diff --git a/StarterNG/Infrastructure/DxgiAdapters.cs b/StarterNG/Infrastructure/DxgiAdapters.cs new file mode 100644 index 0000000..978c636 --- /dev/null +++ b/StarterNG/Infrastructure/DxgiAdapters.cs @@ -0,0 +1,114 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using StarterNG.Domain.Settings; + +namespace StarterNG.Infrastructure; + +/// An adapter as DXGI describes it (DXGI_ADAPTER_DESC1). +/// The card's own memory; for a card in a processor, the share the firmware sets aside. +public sealed record DxgiAdapter(string Description, uint VendorId, ulong DedicatedVideoMemory, uint Flags); + +/// +/// The graphics cards of a Windows machine as DXGI lists them: the adapters Windows +/// draws with, whose drivers the simulator's OpenGL runs on too. The registry's list of +/// video devices is what each driver chose to write there, and some leave their card out of it. +/// +public static unsafe class DxgiAdapters +{ + private const uint MicrosoftVendor = 0x1414; + private const uint SoftwareFlag = 2; // DXGI_ADAPTER_FLAG_SOFTWARE + private const int NotFound = unchecked((int)0x887A0002); // DXGI_ERROR_NOT_FOUND + private const int MostAdapters = 64; + + private static readonly Guid FactoryInterface = new("770aae78-f26f-4dba-a829-253c83d1b387"); // IDXGIFactory1 + + /// The cards among the adapters: not the Microsoft Basic Render Driver or any other software one. + public static IReadOnlyList Cards(IEnumerable adapters) => + adapters + .Where(adapter => (adapter.Flags & SoftwareFlag) == 0 && adapter.VendorId != MicrosoftVendor) + .Select(adapter => new GraphicsCard(adapter.Description.Trim(), (long)adapter.DedicatedVideoMemory)) + .Where(card => card.Name.Length > 0) + // Two of the same card tell no more than one, as in the registry's list. + .DistinctBy(card => card.Name) + .ToList(); + + /// Every adapter DXGI lists, software ones too; null when DXGI could not be asked. + [SupportedOSPlatform("windows")] + public static IReadOnlyList? Read() + { + IntPtr factory; + try + { + Guid iid = FactoryInterface; + if (CreateDXGIFactory1(&iid, &factory) < 0 || factory == IntPtr.Zero) + return null; + } + catch (Exception e) when (e is DllNotFoundException or EntryPointNotFoundException) + { + return null; + } + + try + { + // IDXGIFactory1::EnumAdapters1, after IUnknown's 3, IDXGIObject's 4 and IDXGIFactory's 5. + var enumAdapters1 = (delegate* unmanaged[Stdcall])Method(factory, 12); + var adapters = new List(); + for (uint i = 0; i < MostAdapters; i++) + { + IntPtr adapter; + int result = enumAdapters1(factory, i, &adapter); + if (result == NotFound) + break; + if (result < 0 || adapter == IntPtr.Zero) + return null; + + try + { + // IDXGIAdapter1::GetDesc1, after IUnknown's 3, IDXGIObject's 4 and IDXGIAdapter's 3. + var getDesc1 = (delegate* unmanaged[Stdcall])Method(adapter, 10); + AdapterDesc1 desc; + if (getDesc1(adapter, &desc) >= 0) + adapters.Add(new DxgiAdapter(new string(desc.Description), desc.VendorId, + desc.DedicatedVideoMemory, desc.Flags)); + } + finally + { + Release(adapter); + } + } + + return adapters; + } + finally + { + Release(factory); + } + } + + private static void* Method(IntPtr instance, int slot) => (*(void***)instance)[slot]; + + private static void Release(IntPtr instance) => + ((delegate* unmanaged[Stdcall])Method(instance, 2))(instance); + + [DllImport("dxgi.dll", ExactSpelling = true)] + private static extern int CreateDXGIFactory1(Guid* riid, IntPtr* factory); + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct AdapterDesc1 + { + public fixed char Description[128]; + public uint VendorId; + public uint DeviceId; + public uint SubSysId; + public uint Revision; + public nuint DedicatedVideoMemory; + public nuint DedicatedSystemMemory; + public nuint SharedSystemMemory; + public uint AdapterLuidLow; + public int AdapterLuidHigh; + public uint Flags; + } +} diff --git a/StarterNG/Infrastructure/GraphicsCards.cs b/StarterNG/Infrastructure/GraphicsCards.cs index a357586..47e0390 100644 --- a/StarterNG/Infrastructure/GraphicsCards.cs +++ b/StarterNG/Infrastructure/GraphicsCards.cs @@ -30,14 +30,20 @@ public sealed class GraphicsCards private readonly IEnvironment _environment; private readonly LinuxGpus _gpus; private readonly Func> _nvidiaSmi; + private readonly Func?> _dxgi; + private readonly Func> _registry; public GraphicsCards(IFileSystem files, IEnvironment environment, LinuxGpus gpus, - Func>? nvidiaSmi = null) + Func>? nvidiaSmi = null, + Func?>? dxgi = null, + Func>? registry = null) { _files = files; _environment = environment; _gpus = gpus; _nvidiaSmi = nvidiaSmi ?? AskNvidiaSmi; + _dxgi = dxgi ?? AskDxgi; + _registry = registry ?? ReadRegistry; } /// Takes a while on Linux, where the PCI list is read: not for the UI thread. @@ -46,15 +52,34 @@ public sealed class GraphicsCards IEnumerable cards = Array.Empty(); if (_environment.IsLinux) cards = FromLinux(); - else if (_environment.IsWindows && OperatingSystem.IsWindows()) - cards = FromRegistry(); + else if (_environment.IsWindows) + cards = FromWindows(); // A program goes to the discrete card, on Windows by its own request. return cards.OrderBy(card => card.SharedMemory).ThenByDescending(card => card.MemoryBytes).ToList(); } + /// + /// DXGI's list, the adapters the simulator's OpenGL runs on. The registry's list of + /// video devices only when DXGI cannot be asked or lists no card: there each driver + /// writes what it chooses, and some leave their card out (an RTX 3060 beside a Ryzen's + /// Radeon was missing from it). + /// + private IReadOnlyList FromWindows() + { + var adapters = _dxgi(); + var cards = adapters is null ? Array.Empty() : DxgiAdapters.Cards(adapters); + return cards.Count > 0 ? cards : _registry(); + } + + private static IReadOnlyList? AskDxgi() => + OperatingSystem.IsWindows() ? DxgiAdapters.Read() : null; + + private static IReadOnlyList ReadRegistry() => + OperatingSystem.IsWindows() ? FromRegistry() : Array.Empty(); + [SupportedOSPlatform("windows")] - private static IEnumerable FromRegistry() + private static IReadOnlyList FromRegistry() { try { diff --git a/StarterNG/StarterNG.csproj b/StarterNG/StarterNG.csproj index aeb91b0..34f3ed9 100644 --- a/StarterNG/StarterNG.csproj +++ b/StarterNG/StarterNG.csproj @@ -7,6 +7,8 @@ net10.0 enable true + + true app.manifest Assets\starter.ico true