-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathVeldridRenderer.cs
442 lines (364 loc) · 17.6 KB
/
VeldridRenderer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using OpenWheels.Rendering;
using Veldrid;
namespace OpenWheels.Veldrid
{
/// <summary>
/// <see cref="IRenderer"/> implementation that uses Veldrid to render.
/// </summary>
public class VeldridRenderer : IRenderer, IDisposable
{
public GraphicsDevice GraphicsDevice { get; }
private TextureStorage<Texture> _textureStorage;
private TextureView[] _textureViews;
private ResourceSet[] _textureResourceSets;
private Lazy<ResourceSet>[] _samplerResourceSets;
private Sampler _linearClamp;
private Sampler _pointClamp;
private Sampler _anisotropicClamp;
private CommandList _commandList;
private DeviceBuffer _vertexBuffer;
private DeviceBuffer _indexBuffer;
private Shader _vertexShader;
private Shader _fragmentShader;
private ShaderSetDescription _shaderSet;
private ResourceLayout _wvpLayout;
private ResourceLayout _textureLayout;
private ResourceLayout _samplerLayout;
private ResourceLayout[] _resourceLayouts;
private ResourceSet _wvpSet;
private DeviceBuffer _wvpBuffer;
private Dictionary<OutputDescription, Pipeline> _pipelines;
private bool _disposed;
private Framebuffer _currentTarget;
/// <summary>
/// Create a new renderer.
/// </summary>
/// <param name="graphicsDevice">The <see cref="global::Veldrid.GraphicsDevice"/> to render with.</param>
/// <exception cref="ArgumentNullException">If <paramref name="graphicsDevice"/> is <c>null</c>.</exception>
public VeldridRenderer(GraphicsDevice graphicsDevice, TextureStorage<Texture> textureStorage)
{
if (graphicsDevice == null)
throw new ArgumentNullException(nameof(graphicsDevice));
GraphicsDevice = graphicsDevice;
_currentTarget = GraphicsDevice.SwapchainFramebuffer;
CreateResources();
_pipelines = new Dictionary<OutputDescription, Pipeline>();
_textureStorage = textureStorage;
_textureViews = new TextureView[32];
_textureResourceSets = new ResourceSet[32];
// We lazily create and cache texture views and resource sets when required.
// When a texture is destroyed the matching cached values are destroyed as well.
_textureStorage.TextureDestroyed += (s, a) => RemoveTextureResourceSet(a.TextureId);
}
private void CreateResources()
{
var rf = GraphicsDevice.ResourceFactory;
_commandList = rf.CreateCommandList();
var vertexLayout = new VertexLayoutDescription(
new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3),
new VertexElementDescription("Color", VertexElementSemantic.Color, VertexElementFormat.Byte4_Norm),
new VertexElementDescription("TextureCoordinate", VertexElementSemantic.TextureCoordinate,
VertexElementFormat.Float2));
_vertexShader = VeldridHelper.LoadShader(rf, "SpriteShader", ShaderStages.Vertex, "VS");
_fragmentShader = VeldridHelper.LoadShader(rf, "SpriteShader", ShaderStages.Fragment, "FS");
_shaderSet = new ShaderSetDescription(
new[] {vertexLayout},
new[] {_vertexShader, _fragmentShader});
_wvpLayout = rf.CreateResourceLayout(new ResourceLayoutDescription(
new ResourceLayoutElementDescription("Wvp", ResourceKind.UniformBuffer, ShaderStages.Vertex)));
_textureLayout = rf.CreateResourceLayout(new ResourceLayoutDescription(
new ResourceLayoutElementDescription("Input", ResourceKind.TextureReadOnly, ShaderStages.Fragment)));
_samplerLayout = rf.CreateResourceLayout(new ResourceLayoutDescription(
new ResourceLayoutElementDescription("Sampler", ResourceKind.Sampler, ShaderStages.Fragment)));
CreateSamplerResourceSets();
_resourceLayouts = new[] {_wvpLayout, _textureLayout, _samplerLayout};
_wvpBuffer = rf.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));
UpdateWvp();
_wvpSet = rf.CreateResourceSet(new ResourceSetDescription(_wvpLayout, _wvpBuffer));
}
private void CreateSamplerResourceSets()
{
_samplerResourceSets = new Lazy<ResourceSet>[6];
// Linear Clamp
_samplerResourceSets[0] = new Lazy<ResourceSet>(() =>
{
var linearClampDescr = SamplerDescription.Linear;
linearClampDescr.AddressModeU = SamplerAddressMode.Clamp;
linearClampDescr.AddressModeV = SamplerAddressMode.Clamp;
linearClampDescr.AddressModeW = SamplerAddressMode.Clamp;
_linearClamp = GraphicsDevice.ResourceFactory.CreateSampler(linearClampDescr);
var resourceSetDescr = new ResourceSetDescription(_samplerLayout, _linearClamp);
return GraphicsDevice.ResourceFactory.CreateResourceSet(ref resourceSetDescr);
}, false);
// Linear Wrap
_samplerResourceSets[1] = new Lazy<ResourceSet>(() =>
{
var resourceSetDescr = new ResourceSetDescription(_samplerLayout, GraphicsDevice.LinearSampler);
return GraphicsDevice.ResourceFactory.CreateResourceSet(ref resourceSetDescr);
}, false);
// Point Clamp
_samplerResourceSets[2] = new Lazy<ResourceSet>(() =>
{
var pointClampDescr = SamplerDescription.Point;
pointClampDescr.AddressModeU = SamplerAddressMode.Clamp;
pointClampDescr.AddressModeV = SamplerAddressMode.Clamp;
pointClampDescr.AddressModeW = SamplerAddressMode.Clamp;
_pointClamp = GraphicsDevice.ResourceFactory.CreateSampler(pointClampDescr);
var resourceSetDescr = new ResourceSetDescription(_samplerLayout, _pointClamp);
return GraphicsDevice.ResourceFactory.CreateResourceSet(ref resourceSetDescr);
}, false);
// Point Wrap
_samplerResourceSets[3] = new Lazy<ResourceSet>(() =>
{
var resourceSetDescr = new ResourceSetDescription(_samplerLayout, GraphicsDevice.PointSampler);
return GraphicsDevice.ResourceFactory.CreateResourceSet(ref resourceSetDescr);
}, false);
// Anisotropic Clamp
_samplerResourceSets[4] = new Lazy<ResourceSet>(() =>
{
var anisoClampDescr = SamplerDescription.Aniso4x;
anisoClampDescr.AddressModeU = SamplerAddressMode.Clamp;
anisoClampDescr.AddressModeV = SamplerAddressMode.Clamp;
anisoClampDescr.AddressModeW = SamplerAddressMode.Clamp;
_anisotropicClamp = GraphicsDevice.ResourceFactory.CreateSampler(anisoClampDescr);
var resourceSetDescr = new ResourceSetDescription(_samplerLayout, _anisotropicClamp);
return GraphicsDevice.ResourceFactory.CreateResourceSet(ref resourceSetDescr);
}, false);
// Anisotropic Wrap
_samplerResourceSets[5] = new Lazy<ResourceSet>(() =>
{
var resourceSetDescr = new ResourceSetDescription(_samplerLayout, GraphicsDevice.Aniso4xSampler);
return GraphicsDevice.ResourceFactory.CreateResourceSet(ref resourceSetDescr);
}, false);
}
/// <summary>
/// Set the render target to the swapchain framebuffer of the <see cref="GraphicsDevice"/>.
/// </summary>
/// <seealso cref="global::Veldrid.GraphicsDevice.SwapchainFramebuffer"/>
public void SetTarget()
{
SetTarget(GraphicsDevice.SwapchainFramebuffer);
}
/// <summary>
/// Set the render target.
/// </summary>
/// <param name="target">The framebuffer to render to.</param>
/// <exception cref="ArgumentNullException">If <paramref name="target"/> is <c>null</c>.</exception>
public void SetTarget(Framebuffer target)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
_currentTarget = target;
}
/// <summary>
/// Update the transformation matrix so coordinates match pixel coordinates on the
/// currently active <see cref="Framebuffer"/>. Call this after changing the render
/// target with <see cref="SetTarget"/> or when the active <see cref="Framebuffer"/> is resized.
/// </summary>
public void UpdateWvp()
{
UpdateWvp((int) _currentTarget.Width, (int) _currentTarget.Height);
}
private void UpdateWvp(int width, int height)
{
var wvp = Matrix4x4.CreateOrthographicOffCenter(0, width, height, 0, 0, 1);
GraphicsDevice.UpdateBuffer(_wvpBuffer, 0, ref wvp);
}
/// <summary>
/// Clear the background.
/// </summary>
/// <param name="color">Color to set the background to.</param>
public void Clear(Color color)
{
if (_disposed)
throw new ObjectDisposedException("Can't use renderer after it has been disposed.");
_commandList.Begin();
_commandList.SetFramebuffer(_currentTarget);
var c = new RgbaFloat(color.R / 255f, color.G / 255f, color.B / 255f, color.A / 255f);
_commandList.ClearColorTarget(0, c);
_commandList.End();
GraphicsDevice.SubmitCommands(_commandList);
}
/// <inheritdoc />
public void BeginRender(Vertex[] vertexBuffer, int[] indexBuffer, int vertexCount, int indexCount)
{
if (_disposed)
throw new ObjectDisposedException("Can't use renderer after it has been disposed.");
EnsureVertexBufferSize(vertexBuffer.Length);
EnsureIndexBufferSize(indexBuffer.Length);
GraphicsDevice.UpdateBuffer(_vertexBuffer, 0, ref vertexBuffer[0], (uint) (vertexCount * Vertex.SizeInBytes));
GraphicsDevice.UpdateBuffer(_indexBuffer, 0, ref indexBuffer[0], (uint) (indexCount * sizeof(int)));
// Begin() must be called before commands can be issued.
_commandList.Begin();
_commandList.SetFramebuffer(_currentTarget);
var outputDescr = _currentTarget.OutputDescription;
if (!_pipelines.TryGetValue(outputDescr, out var pipeline))
pipeline = AddPipeline(outputDescr);
_commandList.SetPipeline(pipeline);
_commandList.SetVertexBuffer(0, _vertexBuffer);
_commandList.SetIndexBuffer(_indexBuffer, IndexFormat.UInt32);
}
private void EnsureVertexBufferSize(int vertexCount)
=> EnsureBufferSize(ref _vertexBuffer, (uint)vertexCount * Vertex.SizeInBytes, BufferUsage.VertexBuffer);
private void EnsureIndexBufferSize(int indexCount)
=> EnsureBufferSize(ref _indexBuffer, (uint)indexCount * sizeof(int), BufferUsage.IndexBuffer);
private void EnsureBufferSize(ref DeviceBuffer buffer, uint requiredSize, BufferUsage usage)
{
if (buffer != null && buffer.SizeInBytes < requiredSize)
{
GraphicsDevice.DisposeWhenIdle(buffer);
buffer = null;
}
if (buffer == null)
{
var descr = new BufferDescription(requiredSize, usage);
buffer = GraphicsDevice.ResourceFactory.CreateBuffer(ref descr);
}
}
/// <inheritdoc />
public void DrawBatch(GraphicsState state, int startIndex, int indexCount, object batchUserData)
{
var sampler = GetSamplerResourceSet(state.SamplerState);
var texSet = GetTextureResourceSet(state.Texture);
_commandList.SetGraphicsResourceSet(0, _wvpSet);
_commandList.SetGraphicsResourceSet(1, texSet);
_commandList.SetGraphicsResourceSet(2, sampler);
// Issue a Draw command for a single instance with 4 indices.
_commandList.DrawIndexed(
indexCount: (uint) indexCount,
instanceCount: 1,
indexStart: (uint) startIndex,
vertexOffset: 0,
instanceStart: 0);
}
/// <summary>
/// Lazily creates texture resource sets.
/// </summary>
private ResourceSet GetTextureResourceSet(int id)
{
var tex = _textureStorage.GetTexture(id);
if (id >= _textureResourceSets.Length)
{
GrowResourceSets();
}
if (_textureResourceSets[id] == null)
{
_textureViews[id] = GraphicsDevice.ResourceFactory.CreateTextureView(tex);
_textureResourceSets[id] = GraphicsDevice.ResourceFactory.CreateResourceSet(new ResourceSetDescription(
_textureLayout,
_textureViews[id]));
}
return _textureResourceSets[id];
}
private void GrowResourceSets()
{
Array.Resize(ref _textureViews, _textureViews.Length * 2);
Array.Resize(ref _textureResourceSets, _textureResourceSets.Length * 2);
}
private void RemoveTextureResourceSet(int id)
{
if (id < _textureResourceSets.Length && _textureResourceSets[id] != null)
{
_textureViews[id].Dispose();
_textureViews[id] = null;
_textureResourceSets[id].Dispose();
_textureResourceSets[id] = null;
}
}
private ResourceSet GetSamplerResourceSet(SamplerState samplerState)
{
return _samplerResourceSets[(int) samplerState].Value;
}
/// <inheritdoc />
public void EndRender()
{
// End() must be called before commands can be submitted for execution.
_commandList.End();
GraphicsDevice.SubmitCommands(_commandList);
}
private Pipeline AddPipeline(in OutputDescription outputDescr)
{
var gpd = new GraphicsPipelineDescription();
gpd.BlendState = BlendStateDescription.SingleAlphaBlend;
gpd.DepthStencilState = DepthStencilStateDescription.Disabled;
gpd.RasterizerState = new RasterizerStateDescription(FaceCullMode.None, PolygonFillMode.Solid,
FrontFace.Clockwise, true, false);
gpd.PrimitiveTopology = PrimitiveTopology.TriangleList;
gpd.ShaderSet = _shaderSet;
gpd.ResourceLayouts = _resourceLayouts;
gpd.Outputs = outputDescr;
var pipeline = GraphicsDevice.ResourceFactory.CreateGraphicsPipeline(gpd);
_pipelines[outputDescr] = pipeline;
return pipeline;
}
public void Dispose()
{
if (_disposed)
return;
foreach (var pipeline in _pipelines.Values)
pipeline.Dispose();
foreach (var t in _textureResourceSets)
t?.Dispose();
foreach (var t in _textureViews)
t?.Dispose();
_textureLayout.Dispose();
_wvpSet.Dispose();
_wvpBuffer.Dispose();
_wvpLayout.Dispose();
foreach (var s in _samplerResourceSets)
{
if (s.IsValueCreated)
s.Value.Dispose();
}
_linearClamp?.Dispose();
_pointClamp?.Dispose();
_anisotropicClamp?.Dispose();
_samplerLayout.Dispose();
_vertexShader.Dispose();
_fragmentShader.Dispose();
_commandList.Dispose();
_vertexBuffer?.Dispose();
_indexBuffer?.Dispose();
_disposed = true;
}
}
internal static class VeldridHelper
{
public static Stream OpenEmbeddedAssetStream(string name, Type t) => t.Assembly.GetManifestResourceStream(name);
public static Shader LoadShader(ResourceFactory factory, string set, ShaderStages stage, string entryPoint)
{
string name = $"{set}-{stage.ToString().ToLower()}.{GetExtension(factory.BackendType)}";
return factory.CreateShader(new ShaderDescription(stage, ReadEmbeddedAssetBytes(name), entryPoint));
}
public static byte[] ReadEmbeddedAssetBytes(string name)
{
using (Stream stream = OpenEmbeddedAssetStream(name, typeof(VeldridHelper)))
{
var info = typeof(VeldridHelper).Assembly.GetManifestResourceInfo(name);
byte[] bytes = new byte[stream.Length];
using (MemoryStream ms = new MemoryStream(bytes))
{
stream.CopyTo(ms);
return bytes;
}
}
}
private static string GetExtension(GraphicsBackend backendType)
{
return (backendType == GraphicsBackend.Direct3D11)
? "hlsl.bytes"
: (backendType == GraphicsBackend.Vulkan)
? "450.glsl.spv"
: (backendType == GraphicsBackend.Metal)
? "ios.metallib"
: (backendType == GraphicsBackend.OpenGL)
? "330.glsl"
: "300.glsles";
}
}
}