acdream/src/AcDream.App/Rendering/Gpu/Vk/VulkanPhysicalDeviceSelection.cs
Erik e8a4c1af3f feat(render): Campaign V slice V5 - Vulkan bring-up, dark
Instance, physical-device selection, logical device, queues, swapchain, and the
three-layer capability gate, behind ACDREAM_RENDER_BACKEND=vulkan. Nothing of
the game renders through it. OpenGL stays the default and the only live backend
until V10, and with the variable unset or set to gl the GL path executes not one
new statement.

The shape of the slice. Plan §4.11 asks the Vulkan gate to mirror the GL one
exactly - passive record, active probes, an Evaluate producing operator-facing
sentences, NotSupportedException into Program.cs's exit-code-4 contract, and an
atomic JSON report. The harder question was where to put the seam, because a
capability gate is precisely the code you cannot exercise on the machine that
already passes it: this box has one discrete GPU, so device ranking, the split-
queue path, an sRGB-only surface, a minimised window and a device missing
descriptorBindingVariableDescriptorCount are all unreachable by running the
client. So every decision the gate makes is a pure function over plain records,
and the Silk interop layer only has to be right about which Vulkan field feeds
which property. VulkanPhysicalDeviceSelection ranks candidates,
VulkanExtensionSelection does the required-versus-optional set arithmetic,
VulkanSwapchainConfigurationFactory chooses format, present mode, image count,
extent, usage, transform and composite alpha, VulkanSwapchainRecreationPolicy
classifies every acquire and present result, and
VulkanCapabilityRequirements.Evaluate turns a captured record into failure
sentences. All of it is unit-tested with no driver, no device and no window.

This commit is the integration of that work onto the post-revert tree. The V5
branch was written on b064668b, before V4c/V4d were reverted, so GameWindow.cs
had to be merged rather than taken: the file here is eb2ba4e5's GameWindow plus
V5's fifteen-line backend branch, and it keeps _terrainModernShader, which the
revert restored and which the V5 branch never had. Every other file is byte-
identical to the branch - git diff e1ef4313 over Rendering/Gpu/Vk,
tests/.../Gpu/Vk and RenderBackendKind.cs is empty, no BOM was introduced, and
CRLF is uniform across all seventeen files.

Gate results, recorded verbatim.

Release build: succeeded, 0 warnings, 0 errors.

App tests, Release: Failed 0, Passed 3981, Skipped 3, Total 3984 - the 3,866
baseline plus V5's 115 new tests, exactly.

Offline pixel gate against eb2ba4e5: PASS world-offline.png, differing fraction
1.06534090909091E-05, which is 6 differing pixels out of the 563,200 compared
after the top 280 sky rows are masked. §5.1's re-measured same-commit control
band is 15-23 pixels at fraction <= 4.1e-05, so this sits below the noise floor
rather than merely inside it - the expected result for a slice that adds no
statement to the GL path.

Vulkan check (a), ACDREAM_RENDER_BACKEND=vulkan on the RX 9070 XT with an
automation artifact directory:

  vulkan: capability gate passed (Windows, AMD Radeon RX 9070 XT, Vulkan
  1.4.349, vendor 0x1002, device 0x7550, driver 2.0.395 (raw 0x0080018B));
  swapchain B8G8R8A8Unorm/PresentModeImmediateKhr 1280x720 x3
  vulkan: device selection - automatic: 'AMD Radeon RX 9070 XT' (DiscreteGpu,
  15.92 GiB device-local) ranked first of 2 enumerated device(s).
  [world-gate] screenshot-complete name=vulkan-bringup path=...
  artifacts\vk-bringup\vulkan-bringup.png size=1280x720
  vulkan: presented 64609 clear-colour frame(s); shutting down.

Exit code 0 on CloseMainWindow. The PNG is 5,238 bytes, 1280x720, and uniformly
RGBA(11,19,39,255) - exactly ClearColor [0.043, 0.075, 0.153, 1] scaled to
UNORM. Orientation is right-side-up by construction rather than by inspection,
which a uniform clear could not show: VulkanBackbufferSwizzle.ToGlOriginRgba
writes source row y into destination row height-1-y precisely because
FrameScreenshotController flips again on the way to the PNG, so the two
cancel. That double-flip is unit-tested.

Vulkan check (b), ACDREAM_VULKAN_FORCE_UNSUPPORTED=timelineSemaphore:

  [ERR] acdream's Vulkan renderer is unsupported by the selected device.
  Platform: win-x64, Windows, AMD Radeon RX 9070 XT (DiscreteGpu), Vulkan
  1.4.349, vendor 0x1002, device 0x7550, driver 2.0.395 (raw 0x0080018B)
   - timelineSemaphore is required; the frame serial is the semaphore value.
  Full capability report: ...\diagnostics\graphical-capabilities-vulkan.json

Exit code 4. The report records ForcedUnsupportedFeature timelineSemaphore,
TimelineSemaphore false against an otherwise complete feature set, and the
matching SupportFailures sentence, so the injected rejection is distinguishable
from a genuinely absent feature. Both enumerated devices, all five surface
formats, all four present modes and a clean FunctionProbe with no failures are
recorded beside it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-28 07:11:50 +02:00

232 lines
9 KiB
C#

using System.Globalization;
using Silk.NET.Vulkan;
namespace AcDream.App.Rendering.Gpu.Vk;
/// <summary>The chosen device plus the sentence explaining why, which the report records verbatim.</summary>
internal sealed record VulkanPhysicalDeviceChoice(
VulkanPhysicalDeviceCandidate Device,
string Reason);
/// <summary>
/// Campaign V slice V5, plan §4.11: "discrete &gt; integrated &gt; virtual &gt;
/// CPU, tie-broken by largest device-local heap, with an
/// <c>ACDREAM_VULKAN_DEVICE</c> override recorded in the report."
///
/// Pure ranking over <see cref="VulkanPhysicalDeviceCandidate"/> values so the
/// policy is unit-tested without enumerating a real instance — which matters
/// because this machine has exactly one GPU and the ordering it exercises is
/// therefore never the interesting case.
/// </summary>
internal static class VulkanPhysicalDeviceSelection
{
/// <summary>
/// Preference rank; lower is better. Vulkan's <see cref="PhysicalDeviceType"/>
/// numbering is Other(0) &lt; Integrated(1) &lt; Discrete(2) &lt; Virtual(3)
/// &lt; Cpu(4), which is neither our order nor a monotone one, so it is
/// mapped explicitly rather than compared numerically.
/// </summary>
internal static int PreferenceRank(PhysicalDeviceType type) => type switch
{
PhysicalDeviceType.DiscreteGpu => 0,
PhysicalDeviceType.IntegratedGpu => 1,
PhysicalDeviceType.VirtualGpu => 2,
PhysicalDeviceType.Cpu => 3,
_ => 4,
};
/// <summary>
/// Choose a device.
///
/// <para><paramref name="deviceOverride"/> is an enumeration index when it is
/// entirely decimal digits, and a case-insensitive device-name substring
/// otherwise. The split is exact rather than "try index, then fall back to
/// substring" because a bare digit is a substring of most real device names —
/// <c>7</c> occurs in "AMD Radeon RX 9070 XT" — so a fall-through would make
/// an out-of-range index quietly select a device by coincidence. A name that
/// genuinely contains digits ("RX 7900 XTX") still matches, because it is not
/// digits alone.</para>
///
/// <para>An override that matches nothing falls back to the automatic choice
/// and says so in the reason: refusing to start over a stale environment
/// variable is worse than starting on the right GPU anyway.</para>
/// </summary>
internal static VulkanPhysicalDeviceChoice? Choose(
IReadOnlyList<VulkanPhysicalDeviceCandidate> candidates,
string? deviceOverride)
{
ArgumentNullException.ThrowIfNull(candidates);
if (candidates.Count == 0)
return null;
if (!string.IsNullOrWhiteSpace(deviceOverride))
{
string trimmed = deviceOverride.Trim();
if (IsDecimalIndex(trimmed))
{
int index = int.Parse(trimmed, NumberStyles.None, CultureInfo.InvariantCulture);
VulkanPhysicalDeviceCandidate? byIndex =
candidates.FirstOrDefault(candidate => candidate.Index == index);
if (byIndex is not null)
{
return new VulkanPhysicalDeviceChoice(
byIndex,
$"ACDREAM_VULKAN_DEVICE={trimmed} selected device index {index}.");
}
}
else
{
VulkanPhysicalDeviceCandidate? byName = candidates.FirstOrDefault(
candidate => candidate.DeviceName.Contains(
trimmed,
StringComparison.OrdinalIgnoreCase));
if (byName is not null)
{
return new VulkanPhysicalDeviceChoice(
byName,
$"ACDREAM_VULKAN_DEVICE={trimmed} matched device name '{byName.DeviceName}'.");
}
}
VulkanPhysicalDeviceCandidate automatic = Rank(candidates);
return new VulkanPhysicalDeviceChoice(
automatic,
$"ACDREAM_VULKAN_DEVICE={trimmed} matched no enumerated device; " +
$"fell back to the automatic choice '{automatic.DeviceName}' " +
$"({automatic.DeviceType}, {Gib(automatic.DeviceLocalHeapBytes)} device-local).");
}
VulkanPhysicalDeviceCandidate chosen = Rank(candidates);
return new VulkanPhysicalDeviceChoice(
chosen,
$"automatic: '{chosen.DeviceName}' ({chosen.DeviceType}, " +
$"{Gib(chosen.DeviceLocalHeapBytes)} device-local) ranked first of " +
$"{candidates.Count} enumerated device(s).");
}
/// <summary>
/// Deterministic ordering: type preference, then largest device-local heap,
/// then enumeration index. The final index tie-break exists so two identical
/// GPUs always produce the same choice across launches.
/// </summary>
internal static VulkanPhysicalDeviceCandidate Rank(
IReadOnlyList<VulkanPhysicalDeviceCandidate> candidates)
{
ArgumentNullException.ThrowIfNull(candidates);
if (candidates.Count == 0)
throw new ArgumentException("At least one candidate is required.", nameof(candidates));
VulkanPhysicalDeviceCandidate best = candidates[0];
for (int i = 1; i < candidates.Count; i++)
{
if (Compare(candidates[i], best) < 0)
best = candidates[i];
}
return best;
}
/// <summary>Negative when <paramref name="left"/> is the better device.</summary>
internal static int Compare(
VulkanPhysicalDeviceCandidate left,
VulkanPhysicalDeviceCandidate right)
{
ArgumentNullException.ThrowIfNull(left);
ArgumentNullException.ThrowIfNull(right);
int byType = PreferenceRank(left.DeviceType).CompareTo(PreferenceRank(right.DeviceType));
if (byType != 0)
return byType;
int byHeap = right.DeviceLocalHeapBytes.CompareTo(left.DeviceLocalHeapBytes);
return byHeap != 0 ? byHeap : left.Index.CompareTo(right.Index);
}
/// <summary>An index override is decimal digits and nothing else.</summary>
internal static bool IsDecimalIndex(string value)
{
if (string.IsNullOrEmpty(value))
return false;
foreach (char character in value)
{
if (character is < '0' or > '9')
return false;
}
return true;
}
private static string Gib(ulong bytes)
=> (bytes / (1024d * 1024d * 1024d)).ToString("0.##", CultureInfo.InvariantCulture) + " GiB";
}
/// <summary>
/// Which queue family carries graphics and which carries present. Slice V5 uses
/// one graphics+present queue with transfers riding it (plan §4.8); a device
/// whose present-capable family is separate is still supported, and the
/// swapchain then declares concurrent sharing.
/// </summary>
internal sealed record VulkanQueueFamilyChoice(
uint GraphicsFamily,
uint PresentFamily)
{
/// <summary>True when one queue serves both, which is the case on every GPU we target.</summary>
internal bool IsUnified => GraphicsFamily == PresentFamily;
}
/// <summary>One enumerated queue family, reduced to the two facts the selector needs.</summary>
internal readonly record struct VulkanQueueFamilyCandidate(
uint Index,
bool SupportsGraphics,
bool SupportsPresent);
/// <summary>
/// Pure queue-family selection. Prefers a single family that does both, because
/// that removes the concurrent-sharing declaration and the ownership transfers
/// that would otherwise be needed on every swapchain image.
/// </summary>
internal static class VulkanQueueFamilySelection
{
internal static VulkanQueueFamilyChoice? Choose(
IReadOnlyList<VulkanQueueFamilyCandidate> families)
{
ArgumentNullException.ThrowIfNull(families);
foreach (VulkanQueueFamilyCandidate family in families)
{
if (family.SupportsGraphics && family.SupportsPresent)
return new VulkanQueueFamilyChoice(family.Index, family.Index);
}
uint? graphics = null;
uint? present = null;
foreach (VulkanQueueFamilyCandidate family in families)
{
if (graphics is null && family.SupportsGraphics)
graphics = family.Index;
if (present is null && family.SupportsPresent)
present = family.Index;
}
return graphics is { } g && present is { } p
? new VulkanQueueFamilyChoice(g, p)
: null;
}
/// <summary>
/// The headless variant used by the offscreen capability probe, which has no
/// surface and therefore no present requirement.
/// </summary>
internal static uint? ChooseGraphicsOnly(
IReadOnlyList<VulkanQueueFamilyCandidate> families)
{
ArgumentNullException.ThrowIfNull(families);
foreach (VulkanQueueFamilyCandidate family in families)
{
if (family.SupportsGraphics)
return family.Index;
}
return null;
}
}