Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions docs/d3d12x-shim.md
Original file line number Diff line number Diff line change
Expand Up @@ -721,11 +721,15 @@ viewport indices stay the corner's) and emits a strip of two triangles with the
| Compile one geometry shader per distinct output signature into `<translated>/rect-gs/gs_<hash>.dxil` | `fivestar shader rect-gs <translated>` (2,191 vertex programs, 211 shaders) |
| Keep each created pipeline's description and programs | `RectanglePipelines.Remember` (pipeline factory) |
| Record the pipeline (slot 25), the console topology (slot 20); clear on Reset | `RectangleDraws`, state at wrapper +0xF00 |
| First draw under topology 17: build the variant once (by the same hash), bind it | `RectangleDraws.BeforeDraw` (slots 12, 13) |
| First draw under topology 17: queue the variant's build on the pipeline build threads (urgent, within the compile budget) and skip the draw; once built, bind it after any depth-twin copy (which binds the game's pipeline again); a build that throws is reported once and leaves triangles | `RectangleDraws.Building` (skip), `RectangleDraws.BeforeDraw` (bind; slots 12, 13), `RectanglePipelines.Variant` |
| Another topology: bind the game's pipeline again | slot 20 |

A pipeline with a mesh or geometry stage, or without its `rect-gs` file, has no variant: its rectangle-list draws
stay triangles (warned once). The log counts expanded draws every 4,096.
stay triangles (warned once). The log counts expanded draws every 4,096, with the draws skipped while a variant
built. The variant of a tiled-lighting pipeline is a full compile of its pixel program: built on the drawing game
thread, one held a frame's job for over 25 s while eight other compiles ran, and the game's hang watchdog ended a run
in the opening cutscene.

### Debug layer

`--d3d12-debug` turns on the D3D12 debug layer before the device is created (`--d3d12-gpu-validation` adds
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,12 @@ public static void DrawInstanced(XboxObject* self, uint vertices, uint instances
return;
}

// A rectangle-list draw whose variant still builds is skipped; the variant is bound after CopyTwin.
if (ShimContext.Runtime.D3D12X.Rectangles.Building(self))
{
return;
}

if (DepthTwins.Any)
{
CopyTwin(self);
Expand Down Expand Up @@ -372,6 +378,12 @@ public static void DrawIndexedInstanced(XboxObject* self, uint indices, uint ins
return;
}

// A rectangle-list draw whose variant still builds is skipped; the variant is bound after CopyTwin.
if (ShimContext.Runtime.D3D12X.Rectangles.Building(self))
{
return;
}

if (DepthTwins.Any)
{
CopyTwin(self);
Expand Down
108 changes: 94 additions & 14 deletions src/FiveStar.Loader/Shims/D3D12X/Pipelines/RectanglePipelines.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ namespace FiveStar.Loader.Shims.D3D12X.Pipelines;
/// <summary>
/// The rectangle-list variant of each graphics pipeline (docs/d3d12x-shim.md, Rectangle lists): the same pipeline with
/// the geometry shader of its vertex program's output signature added, read from <c>rect-gs/</c> of the translate
/// output (<c>fivestar shader rect-gs</c>; never compiled here). A variant is built on the first rectangle-list draw with
/// output (<c>fivestar shader rect-gs</c>; never compiled here). A variant is built off the game's threads, started by the first rectangle-list draw with
/// its pipeline; 0 stands for a pipeline that has none (mesh or geometry stage, no shader file, creation failed).
/// </summary>
internal sealed unsafe class RectanglePipelines
Expand All @@ -23,22 +23,29 @@ internal sealed unsafe class RectanglePipelines
/// <summary>Leading D3D12_RASTERIZER_DESC and D3D12_DEPTH_STENCIL_DESC1 bytes a trace shows (fill, cull; depth enable, write mask, function).</summary>
private const int StateTraceBytes = 12;

/// <summary>What <see cref="Variant"/> returns while the variant builds: its draws are skipped meanwhile.</summary>
public const nint Pending = -1;

private readonly nint _device2;
private readonly nint _rootSignature;
private readonly string _folder;
private readonly IProgramLibrary _programs;
private readonly OnceLog _warnings;
private readonly PipelineBuildQueue _builds;
private readonly ConcurrentDictionary<nint, RectangleRecipe> _recipes = new();
private readonly ConcurrentDictionary<nint, nint> _variants = new();
private readonly ConcurrentDictionary<nint, VariantBuild> _building = new();
private readonly ConcurrentDictionary<string, byte[]?> _shaders = new(StringComparer.Ordinal);

/// <param name="device2">A desktop ID3D12Device2 (the caller keeps it alive).</param>
/// <param name="rootSignature">The root signature of translated programs.</param>
/// <param name="folder">The compiled geometry shaders (<c>&lt;translated&gt;/rect-gs</c>).</param>
/// <param name="programs">Where a variant's programs are read again by name.</param>
/// <param name="warnings">Where missing shaders and failures are reported, once each.</param>
public RectanglePipelines(nint device2, nint rootSignature, string folder, IProgramLibrary programs, OnceLog warnings)
/// <param name="builds">The build threads that create the variants, as urgent creations (a draw waits for each).</param>
public RectanglePipelines(nint device2, nint rootSignature, string folder, IProgramLibrary programs, OnceLog warnings, PipelineBuildQueue builds)
{
_builds = builds;
_device2 = device2;
_rootSignature = rootSignature;
_folder = folder;
Expand Down Expand Up @@ -103,7 +110,12 @@ public static bool Derived(string name)
return $"{programs}; inputs [{inputs}]; targets [{string.Join(", ", description.RenderTargetFormats)}] depth {description.DepthStencilFormat}; blend {blend}; raster {raster}; depth state {depth}; sample mask 0x{description.SampleMask:x}, samples {description.SampleCount}.{description.SampleQuality}, raster all {Convert.ToHexString(description.Rasterizer)}";
}

/// <summary>The variant of a desktop pipeline, built on the first call; 0 when it has none.</summary>
/// <summary>
/// The variant of a desktop pipeline; 0 when it has none; <see cref="Pending"/> while it builds. The first call queues
/// the build on the pipeline build threads (urgent) and never waits for it: the variant of a tiled-lighting pipeline
/// is a full compile of its pixel program, and built on the drawing game thread it held a frame's job for over 25 s,
/// until the game's hang watchdog ended the run in the opening cutscene.
/// </summary>
[HotPath]
public nint Variant(nint pipeline)
{
Expand All @@ -112,29 +124,86 @@ public nint Variant(nint pipeline)
return variant;
}

return Create(pipeline);
if (_building.ContainsKey(pipeline))
{
return Pending;
}

return Start(pipeline);
}

private nint Create(nint pipeline)
/// <summary>The first call for a pipeline: 0 without a recipe, otherwise its build queued and <see cref="Pending"/>.</summary>
private nint Start(nint pipeline)
{
nint variant = 0;
if (!_recipes.TryGetValue(pipeline, out var recipe))
{
_variants.TryAdd(pipeline, 0);

return _variants[pipeline];
}

if (_recipes.TryGetValue(pipeline, out var recipe))
var build = new VariantBuild(recipe);

if (!_building.TryAdd(pipeline, build))
{
variant = Build(recipe);
return Pending;
}

if (_variants.TryAdd(pipeline, variant))
// A build that finished between the caller's two lookups left its variant: no second build.
if (_variants.TryGetValue(pipeline, out var built))
{
return variant;
_building.TryRemove(new KeyValuePair<nint, VariantBuild>(pipeline, build));
build.Done.Set();

return built;
}

if (variant != 0)
_builds.Queue(() => Finish(pipeline, build), urgent: true);

return Pending;
}

/// <summary>Waits until the variant of <paramref name="pipeline"/> is no longer building; false on timeout.</summary>
public bool WaitBuilt(nint pipeline, TimeSpan timeout)
{
return !_building.TryGetValue(pipeline, out var build) || build.Done.Wait(timeout);
}

/// <summary>
/// On a build thread: builds the variant within the compile budget, then keeps it unless the pipeline was remembered
/// again since. A failure keeps 0 (drawn as triangles) and is reported once; an exception would end the build thread.
/// </summary>
private PipelineResult Finish(nint pipeline, VariantBuild build)
{
nint variant = 0;
nint kept = 0;

try
{
DesktopDevice.Release(variant);
variant = Build(build.Recipe);
}
catch (Exception exception)
{
_warnings.Warn($"rect-throw-{build.Recipe.Vertex}", $"[d3d12_xs] rectangle-list pipeline for {build.Recipe.Vertex}: {exception.GetType().Name}: {exception.Message}; drawn as triangles");
}
finally
{
if (_recipes.TryGetValue(pipeline, out var current) && ReferenceEquals(current, build.Recipe) && _variants.TryAdd(pipeline, variant))
{
kept = variant;
variant = 0;
}

return _variants[pipeline];
if (variant != 0)
{
DesktopDevice.Release(variant);
}

_building.TryRemove(new KeyValuePair<nint, VariantBuild>(pipeline, build));
build.Done.Set();
}

return new PipelineResult(HResult.Ok, kept);
}

private nint Build(RectangleRecipe recipe)
Expand Down Expand Up @@ -166,7 +235,18 @@ private nint Build(RectangleRecipe recipe)
programs.Add(TranslatedProgram.Of(vertex.Name, HardwareStage.Geometry, shader));
var iid = DesktopDevice.PipelineStateIid;
nint variant = 0;
var hr = DesktopPipelineBuilder.Graphics(_device2, _rootSignature, recipe.Description, programs, &iid, &variant);
long shaderBytes = programs.Sum(program => (long)program.Dxil.Length);
int hr;
CompileBudget.Enter(shaderBytes);

try
{
hr = DesktopPipelineBuilder.Graphics(_device2, _rootSignature, recipe.Description, programs, &iid, &variant);
}
finally
{
CompileBudget.Exit(shaderBytes);
}

if (HResult.Failed(hr))
{
Expand Down
12 changes: 12 additions & 0 deletions src/FiveStar.Loader/Shims/D3D12X/Pipelines/VariantBuild.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Copyright (c) 2026 Five Star Recomp contributors.
// SPDX-License-Identifier: GPL-3.0-or-later

namespace FiveStar.Loader.Shims.D3D12X.Pipelines;

/// <summary>A rectangle-list variant being built (<see cref="RectanglePipelines"/>): its recipe, and set once it is done.</summary>
internal sealed class VariantBuild(RectangleRecipe recipe)
{
public RectangleRecipe Recipe { get; } = recipe;

public ManualResetEventSlim Done { get; } = new();
}
40 changes: 36 additions & 4 deletions src/FiveStar.Loader/Shims/D3D12X/RectangleDraws.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ namespace FiveStar.Loader.Shims.D3D12X;
/// Draws under the console rectangle list (topology 17; docs/d3d12x-shim.md, Rectangle lists). The topology itself
/// becomes a triangle list; a draw under it binds the rectangle-list variant of the list's pipeline
/// (<see cref="RectanglePipelines"/>), whose geometry shader adds each rectangle's fourth corner. The variant stays
/// bound until the game sets another pipeline or topology. Without a variant the draw covers half of each rectangle.
/// bound until the game sets another pipeline or topology. While the variant builds the draw is skipped; without one it
/// covers half of each rectangle.
/// </summary>
internal sealed unsafe class RectangleDraws
{
Expand All @@ -24,6 +25,7 @@ internal sealed unsafe class RectangleDraws
private readonly LoaderLog _log;
private long _expanded;
private long _triangles;
private long _pending;

public RectangleDraws(LoaderLog log)
{
Expand All @@ -39,6 +41,9 @@ public RectangleDraws(LoaderLog log)
/// <summary>Rectangle-list draws drawn as triangles, for want of a variant.</summary>
public long AsTriangles => Interlocked.Read(ref _triangles);

/// <summary>Rectangle-list draws skipped while their variant was building.</summary>
public long WhileBuilding => Interlocked.Read(ref _pending);

public void Attach(RectanglePipelines pipelines)
{
Pipelines = pipelines;
Expand Down Expand Up @@ -76,7 +81,33 @@ public void Reset(XboxObject* list, nint pipeline)
state->Pipeline = pipeline;
}

/// <summary>Before a draw: under the rectangle list, binds the variant and counts the draw.</summary>
/// <summary>
/// First thing before a draw: true when it is to be skipped, since it is under the rectangle list and the variant of
/// its pipeline is still building (off the game's threads; the first call starts the build). The variant is bound
/// later, by <see cref="BeforeDraw"/>, after anything that binds the game's pipeline again (a depth-twin copy).
/// </summary>
[HotPath]
public bool Building(XboxObject* list)
{
var state = RectangleListState.Of(list);
var pipelines = Pipelines;

if (state->Topology != PrimitiveTopologies.RectangleList || state->VariantBound != 0 || pipelines is null || state->Pipeline == 0)
{
return false;
}

if (pipelines.Variant(state->Pipeline) != RectanglePipelines.Pending)
{
return false;
}

Interlocked.Increment(ref _pending);

return true;
}

/// <summary>Right before a draw: under the rectangle list, binds the variant and counts the draw.</summary>
[HotPath]
public void BeforeDraw(XboxObject* list)
{
Expand Down Expand Up @@ -120,7 +151,8 @@ private void BindVariant(XboxObject* list, RectangleListState* state)

nint variant = pipelines.Variant(state->Pipeline);

if (variant != 0)
// Pending only if the pipeline was remembered again since Building: the draw then covers half of each rectangle.
if (variant != 0 && variant != RectanglePipelines.Pending)
{
Bind(list, variant);
state->VariantBound = 1;
Expand All @@ -141,6 +173,6 @@ private void Warn(nint pipeline)

private void Report()
{
_log.Info($" [d3d12_xs] rectangle lists: {Expanded} draws expanded, {AsTriangles} drawn as triangles");
_log.Info($" [d3d12_xs] rectangle lists: {Expanded} draws expanded, {AsTriangles} drawn as triangles, {WhileBuilding} skipped while their variant built");
}
}
4 changes: 2 additions & 2 deletions src/FiveStar.Loader/Shims/D3D12X/XboxDeviceFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -307,8 +307,6 @@ private void CreatePipelines(nint inner)
WaitForProgramIndex();
var onDemand = _pipelineFolders.OnDemand?.Open(_programIndex!, programs!, translated, device2, warnings, _log);
IProgramLibrary library = onDemand ?? (IProgramLibrary)TranslatedProgramLibrary.Open(_programIndex!, translated!, device2, warnings, _log);
var rectangles = new RectanglePipelines(device2, root, RectangleFolder(translated), library, warnings) { Compiler = _pipelineFolders.OnDemand?.RectangleCompiler };
Rectangles.Attach(rectangles);

// Builds start only while the machine has the memory; heavy ones on their own thread (docs/d3d12x-pipelines.md#stand-ins).
// The queues keep only the machine's reserves: each compile's own need is the compile budget's to count. Counting
Expand All @@ -318,6 +316,8 @@ private void CreatePipelines(nint inner)
var heavyBuilds = new PipelineBuildQueue(1, _ => WarmMemoryGuard.RoomForHeavyBuild(0));
builds.Start();
heavyBuilds.Start();
var rectangles = new RectanglePipelines(device2, root, RectangleFolder(translated), library, warnings, builds) { Compiler = _pipelineFolders.OnDemand?.RectangleCompiler };
Rectangles.Attach(rectangles);
var standIns = new StandInPipelines(PipelineSlots.CreationBudget, builds, heavyBuilds, warnings);

var cache = OpenCache(device2);
Expand Down
Loading
Loading