Skip to content

Commit 6ea5405

Browse files
authored
feat(graphics): add shader assets and graphics pipeline cache (#71)
1 parent 0801dba commit 6ea5405

25 files changed

Lines changed: 1540 additions & 3 deletions
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
namespace kajarlabs.Framework.Graphics.Rendering;
2+
3+
/// <summary>
4+
/// Immutable key identifying a cached graphics pipeline state configuration.
5+
/// </summary>
6+
internal sealed class GpuGraphicsPipelineKey : IEquatable<GpuGraphicsPipelineKey>
7+
{
8+
public GpuGraphicsPipelineKey(
9+
GpuShaderDescriptor vertexShader,
10+
GpuShaderDescriptor fragmentShader,
11+
GpuVertexLayout vertexLayout,
12+
BlendingParameters blending,
13+
GpuPrimitiveTopology topology,
14+
GpuTextureFormat colorTargetFormat)
15+
{
16+
ArgumentNullException.ThrowIfNull(vertexShader);
17+
ArgumentNullException.ThrowIfNull(fragmentShader);
18+
ArgumentNullException.ThrowIfNull(vertexLayout);
19+
20+
if (vertexShader.Stage != GpuShaderStage.Vertex)
21+
throw new ArgumentException("Vertex shader descriptor must have stage Vertex.", nameof(vertexShader));
22+
23+
if (fragmentShader.Stage != GpuShaderStage.Fragment)
24+
throw new ArgumentException("Fragment shader descriptor must have stage Fragment.", nameof(fragmentShader));
25+
26+
if (colorTargetFormat == GpuTextureFormat.INVALID)
27+
throw new ArgumentException("Color target format must be valid.", nameof(colorTargetFormat));
28+
29+
VertexShader = vertexShader;
30+
FragmentShader = fragmentShader;
31+
VertexLayout = vertexLayout;
32+
Blending = blending;
33+
Topology = topology;
34+
ColorTargetFormat = colorTargetFormat;
35+
}
36+
37+
public GpuShaderDescriptor VertexShader { get; }
38+
39+
public GpuShaderDescriptor FragmentShader { get; }
40+
41+
public GpuVertexLayout VertexLayout { get; }
42+
43+
public BlendingParameters Blending { get; }
44+
45+
public GpuPrimitiveTopology Topology { get; }
46+
47+
public GpuTextureFormat ColorTargetFormat { get; }
48+
49+
public static bool operator ==(GpuGraphicsPipelineKey? left, GpuGraphicsPipelineKey? right) => Equals(left, right);
50+
51+
public static bool operator !=(GpuGraphicsPipelineKey? left, GpuGraphicsPipelineKey? right) => !Equals(left, right);
52+
53+
public bool Equals(GpuGraphicsPipelineKey? other)
54+
{
55+
if (ReferenceEquals(this, other))
56+
return true;
57+
58+
if (other is null)
59+
return false;
60+
61+
return ReferenceEquals(VertexShader, other.VertexShader)
62+
&& ReferenceEquals(FragmentShader, other.FragmentShader)
63+
&& VertexLayout.Equals(other.VertexLayout)
64+
&& Blending.Equals(other.Blending)
65+
&& Topology == other.Topology
66+
&& ColorTargetFormat == other.ColorTargetFormat;
67+
}
68+
69+
public override bool Equals(object? obj) => obj is GpuGraphicsPipelineKey other && Equals(other);
70+
71+
public override int GetHashCode()
72+
=> HashCode.Combine(VertexShader, FragmentShader, VertexLayout, Blending, Topology, ColorTargetFormat);
73+
}
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
namespace kajarlabs.Framework.Graphics.Rendering;
2+
3+
/// <summary>
4+
/// Caches compiled shader objects and <c>SDL_GPUGraphicsPipeline</c> handles keyed by immutable pipeline state.
5+
/// </summary>
6+
internal sealed class GpuPipelineCache : IDisposable
7+
{
8+
private readonly IGpuBackend backend;
9+
private readonly nint device;
10+
private readonly GpuShaderFormats supportedFormats;
11+
private readonly Lock cacheLock = new();
12+
private readonly Dictionary<(GpuShaderDescriptor Descriptor, GpuShaderFormats Format), nint> shaders = new();
13+
private readonly Dictionary<GpuGraphicsPipelineKey, nint> pipelines = new();
14+
private bool disposed;
15+
16+
public GpuPipelineCache(IGpuBackend backend, nint device, GpuShaderFormats supportedFormats)
17+
{
18+
ArgumentNullException.ThrowIfNull(backend);
19+
20+
if (device == nint.Zero)
21+
throw new ArgumentException("GPU device handle must not be zero.", nameof(device));
22+
23+
this.backend = backend;
24+
this.device = device;
25+
this.supportedFormats = supportedFormats;
26+
}
27+
28+
internal int CachedShaderCount
29+
{
30+
get
31+
{
32+
lock (cacheLock)
33+
return shaders.Count;
34+
}
35+
}
36+
37+
internal int CachedPipelineCount
38+
{
39+
get
40+
{
41+
lock (cacheLock)
42+
return pipelines.Count;
43+
}
44+
}
45+
46+
public nint GetOrCreatePipeline(GpuGraphicsPipelineKey key)
47+
{
48+
ArgumentNullException.ThrowIfNull(key);
49+
50+
lock (cacheLock)
51+
{
52+
ObjectDisposedException.ThrowIf(disposed, this);
53+
54+
if (pipelines.TryGetValue(key, out var existingPipeline))
55+
return existingPipeline;
56+
57+
var vertexShader = getOrCreateShaderLocked(key.VertexShader);
58+
var fragmentShader = getOrCreateShaderLocked(key.FragmentShader);
59+
60+
var pipelineDescription = new GpuGraphicsPipelineDescription(
61+
vertexShader,
62+
fragmentShader,
63+
key.VertexLayout,
64+
key.Blending,
65+
key.Topology,
66+
key.ColorTargetFormat);
67+
68+
var createdPipeline = backend.CreateGraphicsPipeline(device, in pipelineDescription);
69+
70+
if (createdPipeline == nint.Zero)
71+
{
72+
throw new InvalidOperationException(
73+
$"Failed to create SDL_GPUGraphicsPipeline for shaders '{key.VertexShader.Name}' / '{key.FragmentShader.Name}'.");
74+
}
75+
76+
pipelines[key] = createdPipeline;
77+
return createdPipeline;
78+
}
79+
}
80+
81+
public void Dispose()
82+
{
83+
nint[] pipelinesToRelease;
84+
nint[] shadersToRelease;
85+
86+
lock (cacheLock)
87+
{
88+
if (disposed)
89+
return;
90+
91+
disposed = true;
92+
pipelinesToRelease = [.. pipelines.Values];
93+
shadersToRelease = [.. shaders.Values];
94+
pipelines.Clear();
95+
shaders.Clear();
96+
}
97+
98+
foreach (var pipeline in pipelinesToRelease)
99+
backend.ReleaseGraphicsPipeline(device, pipeline);
100+
101+
foreach (var shader in shadersToRelease)
102+
backend.ReleaseShader(device, shader);
103+
}
104+
105+
private nint getOrCreateShaderLocked(GpuShaderDescriptor descriptor)
106+
{
107+
var variant = descriptor.SelectVariant(supportedFormats);
108+
var shaderKey = (descriptor, variant.Format);
109+
110+
if (shaders.TryGetValue(shaderKey, out var existingShader))
111+
return existingShader;
112+
113+
var bytecode = variant.LoadBytecode();
114+
var description = new GpuShaderCreateDescription(
115+
descriptor.Stage,
116+
variant.Format,
117+
variant.Entrypoint,
118+
bytecode,
119+
descriptor.NumSamplers,
120+
descriptor.NumStorageTextures,
121+
descriptor.NumStorageBuffers,
122+
descriptor.NumUniformBuffers);
123+
124+
var createdShader = backend.CreateShader(device, in description);
125+
126+
if (createdShader == nint.Zero)
127+
throw new InvalidOperationException($"Failed to create SDL_GPUShader '{descriptor.Name}' ({variant.Format}).");
128+
129+
shaders[shaderKey] = createdShader;
130+
return createdShader;
131+
}
132+
}

‎libs/framework/Graphics/Rendering/GpuTypes.cs‎

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
using System.Runtime.InteropServices;
2+
using kajarlabs.Framework.Graphics.Rendering.Vertices;
3+
14
namespace kajarlabs.Framework.Graphics.Rendering;
25

36
[Flags]
@@ -61,3 +64,128 @@ internal readonly record struct GpuOffscreenFrame(
6164
nint ColorTargetTexture,
6265
int Width,
6366
int Height);
67+
68+
internal enum GpuShaderStage
69+
{
70+
Vertex = 0,
71+
Fragment = 1,
72+
}
73+
74+
internal enum GpuPrimitiveTopology
75+
{
76+
TriangleList = 0,
77+
TriangleStrip = 1,
78+
LineList = 2,
79+
LineStrip = 3,
80+
PointList = 4,
81+
}
82+
83+
internal enum GpuVertexInputRate
84+
{
85+
Vertex = 0,
86+
Instance = 1,
87+
}
88+
89+
internal enum GpuVertexElementFormat
90+
{
91+
Float = 0,
92+
Float2 = 1,
93+
Float3 = 2,
94+
Float4 = 3,
95+
}
96+
97+
internal readonly record struct GpuVertexBufferBinding(
98+
uint Slot,
99+
uint Pitch,
100+
GpuVertexInputRate InputRate = GpuVertexInputRate.Vertex,
101+
uint InstanceStepRate = 0);
102+
103+
internal readonly record struct GpuVertexAttributeDescription(
104+
uint Location,
105+
uint BufferSlot,
106+
GpuVertexElementFormat Format,
107+
uint Offset);
108+
109+
internal sealed class GpuVertexLayout : IEquatable<GpuVertexLayout>
110+
{
111+
public static readonly GpuVertexLayout TEXTURED_VERTEX_2D = new(
112+
[new GpuVertexBufferBinding(0, (uint)Marshal.SizeOf<TexturedVertex2D>())],
113+
[
114+
new GpuVertexAttributeDescription(0, 0, GpuVertexElementFormat.Float2, 0),
115+
new GpuVertexAttributeDescription(1, 0, GpuVertexElementFormat.Float2, 8),
116+
new GpuVertexAttributeDescription(2, 0, GpuVertexElementFormat.Float4, 16),
117+
]);
118+
119+
private readonly GpuVertexBufferBinding[] bufferBindings;
120+
private readonly GpuVertexAttributeDescription[] attributes;
121+
private readonly int cachedHashCode;
122+
123+
public GpuVertexLayout(
124+
ReadOnlySpan<GpuVertexBufferBinding> bufferBindings,
125+
ReadOnlySpan<GpuVertexAttributeDescription> attributes)
126+
{
127+
this.bufferBindings = bufferBindings.ToArray();
128+
this.attributes = attributes.ToArray();
129+
cachedHashCode = computeHashCode(this.bufferBindings, this.attributes);
130+
}
131+
132+
public ReadOnlySpan<GpuVertexBufferBinding> BufferBindings => bufferBindings;
133+
134+
public ReadOnlySpan<GpuVertexAttributeDescription> Attributes => attributes;
135+
136+
public static bool operator ==(GpuVertexLayout? left, GpuVertexLayout? right) => Equals(left, right);
137+
138+
public static bool operator !=(GpuVertexLayout? left, GpuVertexLayout? right) => !Equals(left, right);
139+
140+
public bool Equals(GpuVertexLayout? other)
141+
{
142+
if (ReferenceEquals(this, other))
143+
return true;
144+
145+
if (other is null || cachedHashCode != other.cachedHashCode)
146+
return false;
147+
148+
return bufferBindings.AsSpan().SequenceEqual(other.bufferBindings)
149+
&& attributes.AsSpan().SequenceEqual(other.attributes);
150+
}
151+
152+
public override bool Equals(object? obj) => obj is GpuVertexLayout other && Equals(other);
153+
154+
public override int GetHashCode() => cachedHashCode;
155+
156+
private static int computeHashCode(
157+
ReadOnlySpan<GpuVertexBufferBinding> bindings,
158+
ReadOnlySpan<GpuVertexAttributeDescription> attrs)
159+
{
160+
var hash = new HashCode();
161+
hash.Add(bindings.Length);
162+
163+
foreach (var binding in bindings)
164+
hash.Add(binding);
165+
166+
hash.Add(attrs.Length);
167+
168+
foreach (var attr in attrs)
169+
hash.Add(attr);
170+
171+
return hash.ToHashCode();
172+
}
173+
}
174+
175+
internal readonly record struct GpuShaderCreateDescription(
176+
GpuShaderStage Stage,
177+
GpuShaderFormats Format,
178+
string Entrypoint,
179+
ReadOnlyMemory<byte> Bytecode,
180+
uint NumSamplers,
181+
uint NumStorageTextures,
182+
uint NumStorageBuffers,
183+
uint NumUniformBuffers);
184+
185+
internal readonly record struct GpuGraphicsPipelineDescription(
186+
nint VertexShader,
187+
nint FragmentShader,
188+
GpuVertexLayout VertexLayout,
189+
BlendingParameters Blending,
190+
GpuPrimitiveTopology Topology,
191+
GpuTextureFormat ColorTargetFormat);

‎libs/framework/Graphics/Rendering/IGpuBackend.cs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,14 @@ bool SetSwapchainParameters(
3838

3939
void ReleaseTexture(nint device, nint texture);
4040

41+
nint CreateShader(nint device, in GpuShaderCreateDescription description);
42+
43+
void ReleaseShader(nint device, nint shader);
44+
45+
nint CreateGraphicsPipeline(nint device, in GpuGraphicsPipelineDescription description);
46+
47+
void ReleaseGraphicsPipeline(nint device, nint pipeline);
48+
4149
nint AcquireCommandBuffer(nint device);
4250

4351
bool SubmitCommandBuffer(nint commandBuffer);

0 commit comments

Comments
 (0)