From d084d7bc247628afcea36a800541edce6cb30f6e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 01:46:15 +0200 Subject: [PATCH 01/25] Removed unnecessary code --- .../AsyncDictionary.cs | 62 ------------------ .../DisposableExtensions.cs | 13 ---- src/DirectX12GameEngine.Core/ICollector.cs | 10 --- src/DirectX12GameEngine.Core/IIdentifiable.cs | 9 --- .../QuaternionExtensions.cs | 63 ------------------- .../GraphicsDevice.cs | 10 +-- 6 files changed, 1 insertion(+), 166 deletions(-) delete mode 100644 src/DirectX12GameEngine.Core/AsyncDictionary.cs delete mode 100644 src/DirectX12GameEngine.Core/DisposableExtensions.cs delete mode 100644 src/DirectX12GameEngine.Core/ICollector.cs delete mode 100644 src/DirectX12GameEngine.Core/IIdentifiable.cs delete mode 100644 src/DirectX12GameEngine.Core/QuaternionExtensions.cs diff --git a/src/DirectX12GameEngine.Core/AsyncDictionary.cs b/src/DirectX12GameEngine.Core/AsyncDictionary.cs deleted file mode 100644 index 4a872a70..00000000 --- a/src/DirectX12GameEngine.Core/AsyncDictionary.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; - -namespace DirectX12GameEngine.Core -{ - public class AsyncDictionary - { - private readonly Dictionary dictionary = new Dictionary(); - - public event EventHandler> ItemAdded; - - public void Add(TKey key, TValue value) - { - dictionary.Add(key, value); - ItemAdded?.Invoke(this, new DictionaryChangedEventArgs(key, value)); - } - - public bool ContainsKey(TKey key) => dictionary.ContainsKey(key); - - public bool ContainsValue(TValue value) => dictionary.ContainsValue(value); - - public async Task GetValueAsync(TKey key) - { - if (!dictionary.TryGetValue(key, out TValue value)) - { - TaskCompletionSource tcs = new TaskCompletionSource(); - - void OnItemAdded(object s, DictionaryChangedEventArgs e) - { - if (e.Item.Key.Equals(key)) - { - tcs.TrySetResult(e.Item.Value); - } - } - - ItemAdded += OnItemAdded; - value = await tcs.Task; - ItemAdded -= OnItemAdded; - } - - return value; - } - - public Task this[TKey key] => GetValueAsync(key); - } - - public class DictionaryChangedEventArgs : EventArgs - { - public DictionaryChangedEventArgs(TKey key, TValue value) - : this(new KeyValuePair(key, value)) - { - } - - public DictionaryChangedEventArgs(KeyValuePair item) - { - Item = item; - } - - public KeyValuePair Item { get; } - } -} diff --git a/src/DirectX12GameEngine.Core/DisposableExtensions.cs b/src/DirectX12GameEngine.Core/DisposableExtensions.cs deleted file mode 100644 index 2f1f8e49..00000000 --- a/src/DirectX12GameEngine.Core/DisposableExtensions.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; - -namespace DirectX12GameEngine.Core -{ - public static class DisposableExtensions - { - public static T DisposeBy(this T item, ICollector collector) where T : IDisposable - { - collector.Disposables.Add(item); - return item; - } - } -} diff --git a/src/DirectX12GameEngine.Core/ICollector.cs b/src/DirectX12GameEngine.Core/ICollector.cs deleted file mode 100644 index 5c5bebc3..00000000 --- a/src/DirectX12GameEngine.Core/ICollector.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace DirectX12GameEngine.Core -{ - public interface ICollector - { - ICollection Disposables { get; } - } -} diff --git a/src/DirectX12GameEngine.Core/IIdentifiable.cs b/src/DirectX12GameEngine.Core/IIdentifiable.cs deleted file mode 100644 index 3e327b71..00000000 --- a/src/DirectX12GameEngine.Core/IIdentifiable.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; - -namespace DirectX12GameEngine.Core -{ - public interface IIdentifiable - { - Guid Id { get; set; } - } -} diff --git a/src/DirectX12GameEngine.Core/QuaternionExtensions.cs b/src/DirectX12GameEngine.Core/QuaternionExtensions.cs deleted file mode 100644 index e20430f6..00000000 --- a/src/DirectX12GameEngine.Core/QuaternionExtensions.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System; -using System.Numerics; - -namespace DirectX12GameEngine.Core -{ - public static class QuaternionExtensions - { - public static Vector3 ToEuler(in Quaternion rotation) - { - Vector3 rotationEuler; - - float xx = rotation.X * rotation.X; - float yy = rotation.Y * rotation.Y; - float zz = rotation.Z * rotation.Z; - float xy = rotation.X * rotation.Y; - float zw = rotation.Z * rotation.W; - float zx = rotation.Z * rotation.X; - float yw = rotation.Y * rotation.W; - float yz = rotation.Y * rotation.Z; - float xw = rotation.X * rotation.W; - - rotationEuler.Y = (float)Math.Asin(2.0f * (yw - zx)); - double test = Math.Cos(rotationEuler.Y); - - if (test > 1e-6f) - { - rotationEuler.Z = (float)Math.Atan2(2.0f * (xy + zw), 1.0f - (2.0f * (yy + zz))); - rotationEuler.X = (float)Math.Atan2(2.0f * (yz + xw), 1.0f - (2.0f * (yy + xx))); - } - else - { - rotationEuler.Z = (float)Math.Atan2(2.0f * (zw - xy), 2.0f * (zx + yw)); - rotationEuler.X = 0.0f; - } - - return rotationEuler; - } - - public static Quaternion ToQuaternion(in Vector3 value) - { - Quaternion rotation; - - var halfAngles = value * 0.5f; - - var fSinX = (float)Math.Sin(halfAngles.X); - var fCosX = (float)Math.Cos(halfAngles.X); - var fSinY = (float)Math.Sin(halfAngles.Y); - var fCosY = (float)Math.Cos(halfAngles.Y); - var fSinZ = (float)Math.Sin(halfAngles.Z); - var fCosZ = (float)Math.Cos(halfAngles.Z); - - var fCosXY = fCosX * fCosY; - var fSinXY = fSinX * fSinY; - - rotation.X = fSinX * fCosY * fCosZ - fSinZ * fSinY * fCosX; - rotation.Y = fSinY * fCosX * fCosZ + fSinZ * fSinX * fCosY; - rotation.Z = fSinZ * fCosXY - fSinXY * fCosZ; - rotation.W = fCosZ * fCosXY + fSinXY * fSinZ; - - return rotation; - } - } -} diff --git a/src/DirectX12GameEngine.Graphics/GraphicsDevice.cs b/src/DirectX12GameEngine.Graphics/GraphicsDevice.cs index 1a30ff15..31752402 100644 --- a/src/DirectX12GameEngine.Graphics/GraphicsDevice.cs +++ b/src/DirectX12GameEngine.Graphics/GraphicsDevice.cs @@ -2,13 +2,12 @@ using System.Collections.Generic; using System.Linq; using System.Threading; -using DirectX12GameEngine.Core; using SharpDX.Direct3D; using SharpDX.Direct3D12; namespace DirectX12GameEngine.Graphics { - public sealed class GraphicsDevice : IDisposable, ICollector + public sealed class GraphicsDevice : IDisposable { private readonly AutoResetEvent fenceEvent = new AutoResetEvent(false); private SharpDX.Direct3D11.Device? nativeDirect3D11Device; @@ -53,8 +52,6 @@ namespace DirectX12GameEngine.Graphics public CommandList CopyCommandList { get; } - public ICollection Disposables { get; } = new List(); - public FeatureLevel FeatureLevel { get; } public GraphicsPresenter? Presenter { get; set; } @@ -163,11 +160,6 @@ namespace DirectX12GameEngine.Graphics NativeDirectFence.Dispose(); NativeDirectFence.Dispose(); - foreach (IDisposable disposable in Disposables) - { - disposable.Dispose(); - } - nativeDirect3D11Device?.Dispose(); NativeDevice.Dispose(); From ef6f153f382ec4b990597feb96ac2b95a3a6d669 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 01:46:23 +0200 Subject: [PATCH 02/25] Added missing documentation --- src/DirectX12GameEngine.Core/MemoryHelper.cs | 32 +++++++++++--------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/src/DirectX12GameEngine.Core/MemoryHelper.cs b/src/DirectX12GameEngine.Core/MemoryHelper.cs index 4fef2426..908799e0 100644 --- a/src/DirectX12GameEngine.Core/MemoryHelper.cs +++ b/src/DirectX12GameEngine.Core/MemoryHelper.cs @@ -3,31 +3,33 @@ using System.Runtime.CompilerServices; namespace DirectX12GameEngine.Core { + /// + /// A with some helper methods to copy data between memory areas + /// public static class MemoryHelper { - public static unsafe void Copy(IntPtr source, IntPtr destination, int sizeInBytesToCopy) - { - Copy(new Span(source.ToPointer(), sizeInBytesToCopy), destination); - } - + /// + /// Copies the content of a to the area pointed by an input value + /// + /// The type of values in the input + /// The source to read + /// The for the destination memory area + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe void Copy(Span source, IntPtr destination) where T : unmanaged { source.CopyTo(new Span(destination.ToPointer(), source.Length)); } + /// + /// Copies a memory area pointed by an value to a target + /// + /// The type of values to read + /// The that indicates the memory area to read from + /// The destination to write + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe void Copy(IntPtr source, Span destination) where T : unmanaged { new Span(source.ToPointer(), destination.Length).CopyTo(destination); } - - public static unsafe void Copy(in T source, IntPtr destination) where T : unmanaged - { - Unsafe.Copy(destination.ToPointer(), ref Unsafe.AsRef(source)); - } - - public static unsafe void Copy(IntPtr source, ref T destination) where T : unmanaged - { - Unsafe.Copy(ref destination, source.ToPointer()); - } } } From 73c8b2d3e6b6c61d2afe5bc63c758d4baf901f7f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 01:46:34 +0200 Subject: [PATCH 03/25] Extension methods refactored --- .../Extensions/PointExtensions.cs | 27 ++++++++ .../Extensions/RectExtensions.cs | 29 +++++++++ .../Extensions/SizeExtensions.cs | 29 +++++++++ .../WindowsRuntimeExtensions.cs | 64 ------------------- 4 files changed, 85 insertions(+), 64 deletions(-) create mode 100644 src/DirectX12GameEngine.Core/Extensions/PointExtensions.cs create mode 100644 src/DirectX12GameEngine.Core/Extensions/RectExtensions.cs create mode 100644 src/DirectX12GameEngine.Core/Extensions/SizeExtensions.cs delete mode 100644 src/DirectX12GameEngine.Core/WindowsRuntimeExtensions.cs diff --git a/src/DirectX12GameEngine.Core/Extensions/PointExtensions.cs b/src/DirectX12GameEngine.Core/Extensions/PointExtensions.cs new file mode 100644 index 00000000..4c636790 --- /dev/null +++ b/src/DirectX12GameEngine.Core/Extensions/PointExtensions.cs @@ -0,0 +1,27 @@ +using System.Diagnostics.Contracts; +using System.Numerics; + +namespace Windows.Foundation +{ + /// + /// A with some extension methods for the type + /// + public static class PointExtensions + { + /// + /// Converts a value to a + /// + /// The input to convert + /// A value representing the input + [Pure] + public static Vector2 ToVector2(this in Point value) => new Vector2((float)value.X, (float)value.Y); + + /// + /// Converts a value to a + /// + /// The input to convert + /// A value representing the input + [Pure] + public static Point ToPoint(this in Vector2 value) => new Point(value.X, value.Y); + } +} diff --git a/src/DirectX12GameEngine.Core/Extensions/RectExtensions.cs b/src/DirectX12GameEngine.Core/Extensions/RectExtensions.cs new file mode 100644 index 00000000..55956a6e --- /dev/null +++ b/src/DirectX12GameEngine.Core/Extensions/RectExtensions.cs @@ -0,0 +1,29 @@ +using System.Diagnostics.Contracts; +using System.Numerics; + +namespace Windows.Foundation +{ + /// + /// A with some extension methods for the type + /// + public static class RectExtensions + { + /// + /// Converts a value to a + /// + /// The input to convert + /// A value representing the input + /// The input is read in the following order: , , , + [Pure] + public static Vector4 ToVector2(this in Rect value) => new Vector4((float)value.Left, (float)value.Top, (float)value.Right, (float)value.Bottom); + + /// + /// Converts a value to a + /// + /// The input to convert + /// A value representing the input + /// The input is assigned in the following order: , , , + [Pure] + public static Rect ToPoint(this in Vector4 value) => new Rect(value.X, value.Y, value.Z, value.W); + } +} \ No newline at end of file diff --git a/src/DirectX12GameEngine.Core/Extensions/SizeExtensions.cs b/src/DirectX12GameEngine.Core/Extensions/SizeExtensions.cs new file mode 100644 index 00000000..f8871206 --- /dev/null +++ b/src/DirectX12GameEngine.Core/Extensions/SizeExtensions.cs @@ -0,0 +1,29 @@ +using System.Diagnostics.Contracts; +using System.Numerics; + +namespace Windows.Foundation +{ + /// + /// A with some extension methods for the type + /// + public static class SizeExtensions + { + /// + /// Converts a value to a + /// + /// The input to convert + /// A value representing the input + /// The input is read in the following order: , + [Pure] + public static Vector2 ToVector2(this in Size value) => new Vector2((float)value.Width, (float)value.Height); + + /// + /// Converts a value to a + /// + /// The input to convert + /// A value representing the input + /// The input is assigned in the following order: , + [Pure] + public static Size ToPoint(this in Vector2 value) => new Size(value.X, value.Y); + } +} \ No newline at end of file diff --git a/src/DirectX12GameEngine.Core/WindowsRuntimeExtensions.cs b/src/DirectX12GameEngine.Core/WindowsRuntimeExtensions.cs deleted file mode 100644 index 787b5040..00000000 --- a/src/DirectX12GameEngine.Core/WindowsRuntimeExtensions.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System.Numerics; -using Windows.Foundation; - -namespace DirectX12GameEngine.Core -{ - public static class PointExtensions - { - public static Vector2 ToVector2(this in Point value) - { - return new Vector2((float)value.X, (float)value.Y); - } - - public static Point ToPoint(this in Vector2 value) - { - return new Point(value.X, value.Y); - } - - public static System.Drawing.PointF ToPointF(this in Point value) - { - return new System.Drawing.PointF((float)value.X, (float)value.Y); - } - - public static Point ToPoint(this in System.Drawing.PointF value) - { - return new Point(value.X, value.Y); - } - } - - public static class RectangleExtensions - { - public static System.Drawing.RectangleF ToRectangleF(this in Rect value) - { - return new System.Drawing.RectangleF((float)value.X, (float)value.Y, (float)value.Width, (float)value.Height); - } - - public static Rect ToRect(this in System.Drawing.RectangleF value) - { - return new Rect(value.X, value.Y, value.Width, value.Height); - } - } - - public static class SizeExtensions - { - public static Vector2 ToVector2(this in Size value) - { - return new Vector2((float)value.Width, (float)value.Height); - } - - public static Size ToSize(this in Vector2 value) - { - return new Size(value.X, value.Y); - } - - public static System.Drawing.SizeF ToSizeF(this in Size value) - { - return new System.Drawing.SizeF((float)value.Width, (float)value.Height); - } - - public static Size ToSize(this in System.Drawing.SizeF value) - { - return new Size(value.Width, value.Height); - } - } -} From 198e01ce5064ae4a2bf55650c49ae0f3d9edced5 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 01:51:33 +0200 Subject: [PATCH 04/25] Removed unnecessary texture classes --- .../CommandList.cs | 111 --------- .../GraphicsPresenter.cs | 17 -- .../ImageDescription.cs | 2 - .../PipelineState.cs | 12 - .../SwapChainGraphicsPresenter.cs | 30 --- src/DirectX12GameEngine.Graphics/Texture.cs | 223 ------------------ .../TextureDescription.cs | 73 ------ .../TextureDimension.cs | 10 - .../TextureFlags.cs | 14 -- 9 files changed, 492 deletions(-) delete mode 100644 src/DirectX12GameEngine.Graphics/Texture.cs delete mode 100644 src/DirectX12GameEngine.Graphics/TextureDescription.cs delete mode 100644 src/DirectX12GameEngine.Graphics/TextureDimension.cs delete mode 100644 src/DirectX12GameEngine.Graphics/TextureFlags.cs diff --git a/src/DirectX12GameEngine.Graphics/CommandList.cs b/src/DirectX12GameEngine.Graphics/CommandList.cs index 843bbf88..bcc34d45 100644 --- a/src/DirectX12GameEngine.Graphics/CommandList.cs +++ b/src/DirectX12GameEngine.Graphics/CommandList.cs @@ -28,62 +28,14 @@ namespace DirectX12GameEngine.Graphics public CommandListType CommandListType { get; } - public Texture? DepthStencilBuffer { get; private set; } - public GraphicsDevice GraphicsDevice { get; } - public Texture[] RenderTargets { get; private set; } = Array.Empty(); - public RawRectangle[] ScissorRectangles { get; private set; } = Array.Empty(); public RawViewportF[] Viewports { get; private set; } = Array.Empty(); public PrimitiveTopology PrimitiveTopology { set => currentCommandList.NativeCommandList.PrimitiveTopology = value; } - public void BeginRenderPass() - { - BeginRenderPass(DepthStencilBuffer, RenderTargets); - } - - public void BeginRenderPass(Texture? depthStencilView, params Texture[] renderTargetViews) - { - RenderPassRenderTargetDescription[] renderPassRenderTargetDescriptions = new RenderPassRenderTargetDescription[renderTargetViews.Length]; - - RenderPassBeginningAccess renderPassBeginningAccessPreserve = new RenderPassBeginningAccess { Type = RenderPassBeginningAccessType.Preserve }; - RenderPassEndingAccess renderPassEndingAccessPreserve = new RenderPassEndingAccess { Type = RenderPassEndingAccessType.Preserve }; - - for (int i = 0; i < renderTargetViews.Length; i++) - { - RenderPassRenderTargetDescription renderPassRenderTargetDescription = new RenderPassRenderTargetDescription - { - BeginningAccess = renderPassBeginningAccessPreserve, - EndingAccess = renderPassEndingAccessPreserve, - CpuDescriptor = renderTargetViews[i].NativeCpuDescriptorHandle - }; - - renderPassRenderTargetDescriptions[i] = renderPassRenderTargetDescription; - } - - RenderPassBeginningAccess renderPassBeginningAccessNoAccess = new RenderPassBeginningAccess { Type = RenderPassBeginningAccessType.NoAccess }; - RenderPassEndingAccess renderPassEndingAccessNoAccess = new RenderPassEndingAccess { Type = RenderPassEndingAccessType.NoAccess }; - - RenderPassDepthStencilDescription? renderPassDepthStencilDescription = null; - - if (depthStencilView != null) - { - renderPassDepthStencilDescription = new RenderPassDepthStencilDescription - { - DepthBeginningAccess = renderPassBeginningAccessNoAccess, - DepthEndingAccess = renderPassEndingAccessNoAccess, - StencilBeginningAccess = renderPassBeginningAccessNoAccess, - StencilEndingAccess = renderPassEndingAccessNoAccess, - CpuDescriptor = depthStencilView.NativeCpuDescriptorHandle, - }; - } - - BeginRenderPass(renderTargetViews.Length, renderPassRenderTargetDescriptions, renderPassDepthStencilDescription, RenderPassFlags.None); - } - public void BeginRenderPass(int numRenderTargets, RenderPassRenderTargetDescription[] renderTargetsRef, RenderPassDepthStencilDescription? depthStencilRef, RenderPassFlags flags) { using GraphicsCommandList4 commandList = currentCommandList.NativeCommandList.QueryInterface(); @@ -96,42 +48,6 @@ namespace DirectX12GameEngine.Graphics commandList.EndRenderPass(); } - public void Clear(Texture depthStencilBuffer, ClearFlags clearFlags, float depth = 1, byte stencil = 0) - { - currentCommandList.NativeCommandList.ClearDepthStencilView(depthStencilBuffer.NativeCpuDescriptorHandle, (SharpDX.Direct3D12.ClearFlags)clearFlags, depth, stencil); - } - - public unsafe void Clear(Texture renderTarget, Vector4 color) - { - currentCommandList.NativeCommandList.ClearRenderTargetView(renderTarget.NativeCpuDescriptorHandle, *(RawColor4*)&color); - } - - public void ClearState() - { - Array.Clear(Viewports, 0, Viewports.Length); - Array.Clear(ScissorRectangles, 0, ScissorRectangles.Length); - - Texture? depthStencilBuffer = GraphicsDevice.Presenter?.DepthStencilBuffer; - Texture? backBuffer = GraphicsDevice.Presenter?.BackBuffer; - - if (backBuffer != null) - { - SetRenderTargets(depthStencilBuffer, backBuffer); - SetViewports(new RawViewportF { X = 0, Y = 0, Width = backBuffer.Width, Height = backBuffer.Height, MaxDepth = 1.0f }); - SetScissorRectangles(new RawRectangle { Right = backBuffer.Width, Bottom = backBuffer.Height }); - } - else if (depthStencilBuffer != null) - { - SetRenderTargets(depthStencilBuffer); - SetViewports(new RawViewportF { X = 0, Y = 0, Width = depthStencilBuffer.Width, Height = depthStencilBuffer.Height, MaxDepth = 1.0f }); - SetScissorRectangles(new RawRectangle { Right = depthStencilBuffer.Width, Bottom = depthStencilBuffer.Height }); - } - else - { - SetRenderTargets(null); - } - } - public CompiledCommandList Close() { //foreach (var renderTarget in RenderTargets) @@ -297,33 +213,6 @@ namespace DirectX12GameEngine.Graphics currentCommandList.NativeCommandList.PipelineState = pipelineState.NativePipelineState; } - public void SetRenderTargets(Texture? depthStencilView, params Texture[] renderTargetViews) - { - DepthStencilBuffer = depthStencilView; - - if (renderTargetViews.Length > MaxRenderTargetCount) - { - throw new ArgumentOutOfRangeException(nameof(renderTargetViews), renderTargetViews.Length, $"The maximum number of render targets is {MaxRenderTargetCount}."); - } - - if (RenderTargets.Length != renderTargetViews.Length) - { - RenderTargets = new Texture[renderTargetViews.Length]; - } - - renderTargetViews.CopyTo(RenderTargets, 0); - - CpuDescriptorHandle[] renderTargetDescriptors = new CpuDescriptorHandle[renderTargetViews.Length]; - - for (int i = 0; i < renderTargetViews.Length; i++) - { - //ResourceBarrierTransition(renderTargetViews[i], ResourceStates.Present, ResourceStates.RenderTarget); - renderTargetDescriptors[i] = renderTargetViews[i].NativeCpuDescriptorHandle; - } - - currentCommandList.NativeCommandList.SetRenderTargets(renderTargetDescriptors, depthStencilView?.NativeCpuDescriptorHandle); - } - public void SetScissorRectangles(params RawRectangle[] scissorRectangles) { if (scissorRectangles.Length > MaxViewportAndScissorRectangleCount) diff --git a/src/DirectX12GameEngine.Graphics/GraphicsPresenter.cs b/src/DirectX12GameEngine.Graphics/GraphicsPresenter.cs index 3edf4fd1..8db786ce 100644 --- a/src/DirectX12GameEngine.Graphics/GraphicsPresenter.cs +++ b/src/DirectX12GameEngine.Graphics/GraphicsPresenter.cs @@ -8,27 +8,20 @@ namespace DirectX12GameEngine.Graphics { GraphicsDevice = device; PresentationParameters = presentationParameters; - - DepthStencilBuffer = CreateDepthStencilBuffer(); } - public abstract Texture BackBuffer { get; } - public GraphicsDevice GraphicsDevice { get; } public abstract object NativePresenter { get; } public PresentationParameters PresentationParameters { get; } - public Texture DepthStencilBuffer { get; protected set; } - public virtual void BeginDraw(CommandList commandList) { } public virtual void Dispose() { - DepthStencilBuffer.Dispose(); } public abstract void Present(); @@ -39,18 +32,8 @@ namespace DirectX12GameEngine.Graphics PresentationParameters.BackBufferHeight = height; ResizeBackBuffer(width, height); - ResizeDepthStencilBuffer(width, height); - } - - protected virtual Texture CreateDepthStencilBuffer() - { - return Texture.New2D(GraphicsDevice, - PresentationParameters.BackBufferWidth, PresentationParameters.BackBufferHeight, PresentationParameters.DepthStencilFormat, - TextureFlags.DepthStencil, 1, PresentationParameters.Stereo ? 2 : 1); } protected abstract void ResizeBackBuffer(int width, int height); - - protected abstract void ResizeDepthStencilBuffer(int width, int height); } } diff --git a/src/DirectX12GameEngine.Graphics/ImageDescription.cs b/src/DirectX12GameEngine.Graphics/ImageDescription.cs index 4575a9da..cf605e31 100644 --- a/src/DirectX12GameEngine.Graphics/ImageDescription.cs +++ b/src/DirectX12GameEngine.Graphics/ImageDescription.cs @@ -2,7 +2,6 @@ { public struct ImageDescription { - public TextureDimension Dimension; public int Width; @@ -20,7 +19,6 @@ { return new ImageDescription { - Dimension = TextureDimension.Texture2D, Width = width, Height = height, Depth = 1, diff --git a/src/DirectX12GameEngine.Graphics/PipelineState.cs b/src/DirectX12GameEngine.Graphics/PipelineState.cs index 692df0d9..79bcfd32 100644 --- a/src/DirectX12GameEngine.Graphics/PipelineState.cs +++ b/src/DirectX12GameEngine.Graphics/PipelineState.cs @@ -82,18 +82,6 @@ namespace DirectX12GameEngine.Graphics StreamOutput = new StreamOutputDescription() }; - Texture? depthStencilBuffer = device.CommandList.DepthStencilBuffer; - - if (depthStencilBuffer != null) - { - pipelineStateDescription.DepthStencilFormat = (Format)depthStencilBuffer.Description.Format; - } - - for (int i = 0; i < device.CommandList.RenderTargets.Length; i++) - { - pipelineStateDescription.RenderTargetFormats[i] = (Format)device.CommandList.RenderTargets[i].Description.Format; - } - return pipelineStateDescription; } } diff --git a/src/DirectX12GameEngine.Graphics/SwapChainGraphicsPresenter.cs b/src/DirectX12GameEngine.Graphics/SwapChainGraphicsPresenter.cs index 826f1387..8dc3198b 100644 --- a/src/DirectX12GameEngine.Graphics/SwapChainGraphicsPresenter.cs +++ b/src/DirectX12GameEngine.Graphics/SwapChainGraphicsPresenter.cs @@ -10,8 +10,6 @@ namespace DirectX12GameEngine.Graphics { protected const int BufferCount = 2; - private readonly Texture[] renderTargets = new Texture[BufferCount]; - public SwapChainGraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters, SwapChain3 swapChain) : base(device, presentationParameters) { @@ -22,12 +20,8 @@ namespace DirectX12GameEngine.Graphics GraphicsDevice.RenderTargetViewAllocator.Dispose(); GraphicsDevice.RenderTargetViewAllocator = new DescriptorAllocator(GraphicsDevice, DescriptorHeapType.RenderTargetView, descriptorCount: BufferCount); } - - CreateRenderTargets(); } - public override Texture BackBuffer => renderTargets[SwapChain.CurrentBackBufferIndex]; - public Matrix3x2 MatrixTransform { get => SwapChain.MatrixTransform.ToMatrix3x2(); set => SwapChain.MatrixTransform = value.ToMatrix3x2(); } public override object NativePresenter => SwapChain; @@ -38,11 +32,6 @@ namespace DirectX12GameEngine.Graphics { SwapChain.Dispose(); - foreach (Texture renderTarget in renderTargets) - { - renderTarget.Dispose(); - } - base.Dispose(); } @@ -53,28 +42,9 @@ namespace DirectX12GameEngine.Graphics protected override void ResizeBackBuffer(int width, int height) { - for (int i = 0; i < BufferCount; i++) - { - renderTargets[i].Dispose(); - } SwapChain.ResizeBuffers(BufferCount, width, height, (Format)PresentationParameters.BackBufferFormat, SwapChainFlags.None); - CreateRenderTargets(); - } - - protected override void ResizeDepthStencilBuffer(int width, int height) - { - DepthStencilBuffer.Dispose(); - DepthStencilBuffer = CreateDepthStencilBuffer(); - } - - private void CreateRenderTargets() - { - for (int i = 0; i < BufferCount; i++) - { - renderTargets[i] = new Texture(GraphicsDevice).InitializeFrom(SwapChain.GetBackBuffer(i)); - } } } diff --git a/src/DirectX12GameEngine.Graphics/Texture.cs b/src/DirectX12GameEngine.Graphics/Texture.cs deleted file mode 100644 index 3879ce41..00000000 --- a/src/DirectX12GameEngine.Graphics/Texture.cs +++ /dev/null @@ -1,223 +0,0 @@ -using System; -using System.IO; -using System.Runtime.CompilerServices; -using System.Threading.Tasks; -using SharpDX.Direct3D12; -using SharpDX.DXGI; - -using Resource = SharpDX.Direct3D12.Resource; - -namespace DirectX12GameEngine.Graphics -{ - public sealed class Texture : GraphicsResource - { - public Texture() - { - } - - internal Texture(GraphicsDevice device) : base(device) - { - } - - public TextureDescription Description { get; private set; } - - public int Width => Description.Width; - - public int Height => Description.Height; - - public static async Task LoadAsync(GraphicsDevice device, string filePath) - { - using FileStream stream = File.OpenRead(filePath); - return await LoadAsync(device, stream); - } - - public static async Task LoadAsync(GraphicsDevice device, Stream stream) - { - using Image image = await Image.LoadAsync(stream); - return New2D(device, image.Data.Span, image.Width, image.Height, image.Description.Format); ; - } - - public static Texture New(GraphicsDevice device, TextureDescription description) - { - return new Texture(device).InitializeFrom(description); - } - - public static Texture New2D(GraphicsDevice device, int width, int height, PixelFormat format, TextureFlags textureFlags = TextureFlags.ShaderResource, int mipCount = 1, int arraySize = 1, int multisampleCount = 1, GraphicsHeapType heapType = GraphicsHeapType.Default) - { - return New(device, TextureDescription.New2D(width, height, format, textureFlags, mipCount, arraySize, multisampleCount, heapType)); - } - - public static Texture New2D(GraphicsDevice device, Span data, int width, int height, PixelFormat format, TextureFlags textureFlags = TextureFlags.ShaderResource, int mipCount = 1, int arraySize = 1, int multisampleCount = 1, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged - { - Texture texture = New2D(device, width, height, format, textureFlags, mipCount, arraySize, multisampleCount, heapType); - texture.Recreate(data); - - return texture; - } - - public unsafe void Recreate(Span data) where T : unmanaged - { - Resource uploadResource = GraphicsDevice.NativeDevice.CreateCommittedResource(new HeapProperties(CpuPageProperty.WriteBack, MemoryPool.L0), HeapFlags.None, NativeResource.Description, ResourceStates.CopyDestination); - using Texture textureUploadBuffer = new Texture(GraphicsDevice).InitializeFrom(uploadResource); - - fixed (T* pointer = data) - { - textureUploadBuffer.NativeResource.WriteToSubresource(0, null, (IntPtr)pointer, ((Format)Description.Format).SizeOfInBytes() * Width, data.Length * Unsafe.SizeOf()); - } - - using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); - - copyCommandList.CopyResource(textureUploadBuffer, this); - copyCommandList.Flush(true); - } - - public Texture InitializeFrom(TextureDescription description) - { - ResourceStates resourceStates = ResourceStates.Common; - - if (description.HeapType == GraphicsHeapType.Upload) - { - resourceStates = ResourceStates.GenericRead; - } - else if (description.HeapType == GraphicsHeapType.Readback) - { - resourceStates = ResourceStates.CopyDestination; - } - - NativeResource ??= GraphicsDevice.NativeDevice.CreateCommittedResource( - new HeapProperties((HeapType)description.HeapType), HeapFlags.None, - ConvertToNativeDescription(description), resourceStates); - - Description = description; - - (NativeCpuDescriptorHandle, NativeGpuDescriptorHandle) = description.Flags switch - { - TextureFlags.DepthStencil => CreateDepthStencilView(), - TextureFlags.RenderTarget => CreateRenderTargetView(), - TextureFlags.ShaderResource => CreateShaderResourceView(), - TextureFlags.UnorderedAccess => CreateUnorderedAccessView(), - _ => default - }; - - return this; - } - - internal Texture InitializeFrom(Resource resource) - { - NativeResource = resource; - - TextureDescription description = ConvertFromNativeDescription(resource.Description); - - return InitializeFrom(description); - } - - internal static ResourceFlags GetBindFlagsFromTextureFlags(TextureFlags flags) - { - ResourceFlags result = ResourceFlags.None; - - if (flags.HasFlag(TextureFlags.RenderTarget)) - { - result |= ResourceFlags.AllowRenderTarget; - } - - if (flags.HasFlag(TextureFlags.UnorderedAccess)) - { - result |= ResourceFlags.AllowUnorderedAccess; - //result |= ResourceFlags.AllowSimultaneousAccess; - } - - if (flags.HasFlag(TextureFlags.DepthStencil)) - { - result |= ResourceFlags.AllowDepthStencil; - - if (!flags.HasFlag(TextureFlags.ShaderResource)) - { - result |= ResourceFlags.DenyShaderResource; - } - } - - return result; - } - - private static TextureDescription ConvertFromNativeDescription(ResourceDescription description, bool isShaderResource = false) - { - TextureDescription textureDescription = new TextureDescription() - { - Dimension = TextureDimension.Texture2D, - Width = (int)description.Width, - Height = description.Height, - Depth = 1, - MultisampleCount = description.SampleDescription.Count, - Format = (PixelFormat)description.Format, - MipLevels = description.MipLevels, - HeapType = GraphicsHeapType.Default, - ArraySize = description.DepthOrArraySize, - Flags = TextureFlags.None - }; - - if (description.Flags.HasFlag(ResourceFlags.AllowRenderTarget)) - { - textureDescription.Flags |= TextureFlags.RenderTarget; - } - - if (description.Flags.HasFlag(ResourceFlags.AllowUnorderedAccess)) - { - textureDescription.Flags |= TextureFlags.UnorderedAccess; - } - - if (description.Flags.HasFlag(ResourceFlags.AllowDepthStencil)) - { - textureDescription.Flags |= TextureFlags.DepthStencil; - } - - if (!description.Flags.HasFlag(ResourceFlags.DenyShaderResource) && isShaderResource) - { - textureDescription.Flags |= TextureFlags.ShaderResource; - } - - return textureDescription; - } - - private static ResourceDescription ConvertToNativeDescription(TextureDescription description) - { - return description.Dimension switch - { - TextureDimension.Texture2D => ResourceDescription.Texture2D((Format)description.Format, description.Width, description.Height, (short)description.ArraySize, (short)description.MipLevels, description.MultisampleCount, 0, GetBindFlagsFromTextureFlags(description.Flags)), - _ => throw new NotSupportedException() - }; - } - - private (CpuDescriptorHandle, GpuDescriptorHandle) CreateDepthStencilView() - { - (CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.DepthStencilViewAllocator.Allocate(1); - GraphicsDevice.NativeDevice.CreateDepthStencilView(NativeResource, null, cpuHandle); - - return (cpuHandle, gpuHandle); - } - - private (CpuDescriptorHandle, GpuDescriptorHandle) CreateRenderTargetView() - { - (CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.RenderTargetViewAllocator.Allocate(1); - GraphicsDevice.NativeDevice.CreateRenderTargetView(NativeResource, null, cpuHandle); - - return (cpuHandle, gpuHandle); - } - - private (CpuDescriptorHandle, GpuDescriptorHandle) CreateShaderResourceView() - { - (CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate(1); - GraphicsDevice.NativeDevice.CreateShaderResourceView(NativeResource, null, cpuHandle); - - return (cpuHandle, gpuHandle); - } - - private (CpuDescriptorHandle, GpuDescriptorHandle) CreateUnorderedAccessView() - { - (CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate(1); - - GraphicsDevice.NativeDevice.CreateUnorderedAccessView(NativeResource, null, null, cpuHandle); - - return (cpuHandle, gpuHandle); - } - } -} diff --git a/src/DirectX12GameEngine.Graphics/TextureDescription.cs b/src/DirectX12GameEngine.Graphics/TextureDescription.cs deleted file mode 100644 index ba46f874..00000000 --- a/src/DirectX12GameEngine.Graphics/TextureDescription.cs +++ /dev/null @@ -1,73 +0,0 @@ -namespace DirectX12GameEngine.Graphics -{ - public struct TextureDescription - { - public TextureDimension Dimension; - - public int Width; - - public int Height; - - public int Depth; - - public int ArraySize; - - public int MipLevels; - - public PixelFormat Format; - - public int MultisampleCount; - - public GraphicsHeapType HeapType; - - public TextureFlags Flags; - - public static TextureDescription New2D(int width, int height, PixelFormat format, TextureFlags textureFlags = TextureFlags.ShaderResource, int mipCount = 1, int arraySize = 1, int multisampleCount = 1, GraphicsHeapType heapType = GraphicsHeapType.Default) - { - return new TextureDescription - { - Dimension = TextureDimension.Texture2D, - Width = width, - Height = height, - Depth = 1, - ArraySize = arraySize, - MultisampleCount = multisampleCount, - Flags = textureFlags, - Format = format, - MipLevels = mipCount, - HeapType = heapType, - }; - } - - public static implicit operator TextureDescription(ImageDescription description) - { - return new TextureDescription() - { - Dimension = description.Dimension, - Width = description.Width, - Height = description.Height, - Depth = description.Depth, - ArraySize = description.ArraySize, - MipLevels = description.MipLevels, - Format = description.Format, - Flags = TextureFlags.ShaderResource, - MultisampleCount = 1, - HeapType = GraphicsHeapType.Default - }; - } - - public static implicit operator ImageDescription(TextureDescription description) - { - return new ImageDescription() - { - Dimension = description.Dimension, - Width = description.Width, - Height = description.Height, - Depth = description.Depth, - ArraySize = description.ArraySize, - MipLevels = description.MipLevels, - Format = description.Format, - }; - } - } -} diff --git a/src/DirectX12GameEngine.Graphics/TextureDimension.cs b/src/DirectX12GameEngine.Graphics/TextureDimension.cs deleted file mode 100644 index b6f9a580..00000000 --- a/src/DirectX12GameEngine.Graphics/TextureDimension.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace DirectX12GameEngine.Graphics -{ - public enum TextureDimension - { - Texture1D, - Texture2D, - Texture3D, - TextureCube - } -} diff --git a/src/DirectX12GameEngine.Graphics/TextureFlags.cs b/src/DirectX12GameEngine.Graphics/TextureFlags.cs deleted file mode 100644 index 6cfa0070..00000000 --- a/src/DirectX12GameEngine.Graphics/TextureFlags.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; - -namespace DirectX12GameEngine.Graphics -{ - [Flags] - public enum TextureFlags - { - None = 0, - RenderTarget = 1, - DepthStencil = 2, - UnorderedAccess = 4, - ShaderResource = 8 - } -} From 8c7773e6cdf27f83bc9aaec4e35be78fc5935579 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 01:52:00 +0200 Subject: [PATCH 05/25] Removed image classes --- src/DirectX12GameEngine.Graphics/Image.cs | 61 ------------------- .../ImageDescription.cs | 31 ---------- 2 files changed, 92 deletions(-) delete mode 100644 src/DirectX12GameEngine.Graphics/Image.cs delete mode 100644 src/DirectX12GameEngine.Graphics/ImageDescription.cs diff --git a/src/DirectX12GameEngine.Graphics/Image.cs b/src/DirectX12GameEngine.Graphics/Image.cs deleted file mode 100644 index f598faa8..00000000 --- a/src/DirectX12GameEngine.Graphics/Image.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System; -using System.IO; -using System.Threading.Tasks; -using SharpDX.DXGI; -using Windows.Graphics.Imaging; - -namespace DirectX12GameEngine.Graphics -{ - public sealed class Image : IDisposable - { - public Memory Data { get; } - - public ImageDescription Description { get; } - - public int Width => Description.Width; - - public int Height => Description.Height; - - internal Image() - { - } - - internal Image(ImageDescription description, Memory data) - { - Description = description; - Data = data; - } - - public static async Task LoadAsync(string filePath) - { - using FileStream stream = File.OpenRead(filePath); - return await LoadAsync(stream); - } - - public static async Task LoadAsync(Stream stream) - { - BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream.AsRandomAccessStream()); - - PixelDataProvider pixelDataProvider = await decoder.GetPixelDataAsync( - decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, new BitmapTransform(), - ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage); - - byte[] imageBuffer = pixelDataProvider.DetachPixelData(); - - PixelFormat pixelFormat = decoder.BitmapPixelFormat switch - { - BitmapPixelFormat.Rgba8 => PixelFormat.R8G8B8A8_UNorm, - BitmapPixelFormat.Bgra8 => PixelFormat.B8G8R8A8_UNorm, - _ => throw new NotSupportedException("This format is not supported.") - }; - - ImageDescription description = ImageDescription.New2D((int)decoder.PixelWidth, (int)decoder.OrientedPixelHeight, pixelFormat); - - return new Image(description, imageBuffer); - } - - public void Dispose() - { - } - } -} diff --git a/src/DirectX12GameEngine.Graphics/ImageDescription.cs b/src/DirectX12GameEngine.Graphics/ImageDescription.cs deleted file mode 100644 index cf605e31..00000000 --- a/src/DirectX12GameEngine.Graphics/ImageDescription.cs +++ /dev/null @@ -1,31 +0,0 @@ -namespace DirectX12GameEngine.Graphics -{ - public struct ImageDescription - { - - public int Width; - - public int Height; - - public int Depth; - - public int ArraySize; - - public int MipLevels; - - public PixelFormat Format; - - public static ImageDescription New2D(int width, int height, PixelFormat format, int mipCount = 1, int arraySize = 1) - { - return new ImageDescription - { - Width = width, - Height = height, - Depth = 1, - ArraySize = arraySize, - Format = format, - MipLevels = mipCount, - }; - } - } -} From 5c07022eecc67b231a3cd96c2afbae4b8af27bfc Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 01:53:50 +0200 Subject: [PATCH 06/25] Removed more presentation classes --- .../Buffer.Index.cs | 19 --- .../CoreWindowSwapChainGraphicsPresenter.cs | 41 ------ .../GraphicsDevice.cs | 2 - .../GraphicsPresenter.cs | 39 ------ .../HwndSwapChainGraphicsPresenter.cs | 38 ------ .../PixelFormat.cs | 125 ------------------ .../PresentationParameters.cs | 37 ------ .../SwapChainGraphicsPresenter.cs | 63 --------- .../WindowHandle.cs | 14 -- .../XamlSwapChainGraphicsPresenter.cs | 63 --------- 10 files changed, 441 deletions(-) delete mode 100644 src/DirectX12GameEngine.Graphics/CoreWindowSwapChainGraphicsPresenter.cs delete mode 100644 src/DirectX12GameEngine.Graphics/GraphicsPresenter.cs delete mode 100644 src/DirectX12GameEngine.Graphics/HwndSwapChainGraphicsPresenter.cs delete mode 100644 src/DirectX12GameEngine.Graphics/PixelFormat.cs delete mode 100644 src/DirectX12GameEngine.Graphics/PresentationParameters.cs delete mode 100644 src/DirectX12GameEngine.Graphics/SwapChainGraphicsPresenter.cs delete mode 100644 src/DirectX12GameEngine.Graphics/WindowHandle.cs delete mode 100644 src/DirectX12GameEngine.Graphics/XamlSwapChainGraphicsPresenter.cs diff --git a/src/DirectX12GameEngine.Graphics/Buffer.Index.cs b/src/DirectX12GameEngine.Graphics/Buffer.Index.cs index 6c4be0bf..398811fd 100644 --- a/src/DirectX12GameEngine.Graphics/Buffer.Index.cs +++ b/src/DirectX12GameEngine.Graphics/Buffer.Index.cs @@ -22,25 +22,6 @@ namespace DirectX12GameEngine.Graphics { return Buffer.New(device, data, BufferFlags.IndexBuffer, heapType); } - - public static IndexBufferView CreateIndexBufferView(Buffer indexBuffer, PixelFormat format, int size) - { - switch (format) - { - case PixelFormat.R16_UInt: - case PixelFormat.R32_UInt: - break; - default: - throw new NotSupportedException("Index buffer type must be ushort or uint"); - } - - return new IndexBufferView - { - BufferLocation = indexBuffer.NativeResource.GPUVirtualAddress, - Format = (Format)format, - SizeInBytes = size - }; - } } } } diff --git a/src/DirectX12GameEngine.Graphics/CoreWindowSwapChainGraphicsPresenter.cs b/src/DirectX12GameEngine.Graphics/CoreWindowSwapChainGraphicsPresenter.cs deleted file mode 100644 index e52d61f2..00000000 --- a/src/DirectX12GameEngine.Graphics/CoreWindowSwapChainGraphicsPresenter.cs +++ /dev/null @@ -1,41 +0,0 @@ -using SharpDX; -using SharpDX.DXGI; -using Windows.UI.Core; - -namespace DirectX12GameEngine.Graphics -{ - public class CoreWindowSwapChainGraphicsPresenter : SwapChainGraphicsPresenter - { - private readonly CoreWindow coreWindow; - - public CoreWindowSwapChainGraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters, CoreWindow coreWindow) - : base(device, presentationParameters, CreateSwapChain(device, presentationParameters, coreWindow)) - { - this.coreWindow = coreWindow; - } - - private static SwapChain3 CreateSwapChain(GraphicsDevice device, PresentationParameters presentationParameters, CoreWindow coreWindow) - { - SwapChainDescription1 swapChainDescription = new SwapChainDescription1 - { - Width = presentationParameters.BackBufferWidth, - Height = presentationParameters.BackBufferHeight, - SampleDescription = new SampleDescription(1, 0), - Stereo = presentationParameters.Stereo, - Usage = Usage.RenderTargetOutput, - BufferCount = BufferCount, - Scaling = Scaling.Stretch, - SwapEffect = SwapEffect.FlipSequential, - Format = (Format)presentationParameters.BackBufferFormat, - Flags = SwapChainFlags.None, - AlphaMode = AlphaMode.Unspecified - }; - - using Factory4 factory = new Factory4(); - using ComObject window = new ComObject(coreWindow); - using SwapChain1 tempSwapChain = new SwapChain1(factory, device.NativeDirectCommandQueue, window, ref swapChainDescription); - - return tempSwapChain.QueryInterface(); - } - } -} diff --git a/src/DirectX12GameEngine.Graphics/GraphicsDevice.cs b/src/DirectX12GameEngine.Graphics/GraphicsDevice.cs index 31752402..a5f67e05 100644 --- a/src/DirectX12GameEngine.Graphics/GraphicsDevice.cs +++ b/src/DirectX12GameEngine.Graphics/GraphicsDevice.cs @@ -54,8 +54,6 @@ namespace DirectX12GameEngine.Graphics public FeatureLevel FeatureLevel { get; } - public GraphicsPresenter? Presenter { get; set; } - internal Device NativeDevice { get; } internal SharpDX.Direct3D11.Device NativeDirect3D11Device => NativeDirect3D11Device ?? (nativeDirect3D11Device = SharpDX.Direct3D11.Device.CreateFromDirect3D12( diff --git a/src/DirectX12GameEngine.Graphics/GraphicsPresenter.cs b/src/DirectX12GameEngine.Graphics/GraphicsPresenter.cs deleted file mode 100644 index 8db786ce..00000000 --- a/src/DirectX12GameEngine.Graphics/GraphicsPresenter.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; - -namespace DirectX12GameEngine.Graphics -{ - public abstract class GraphicsPresenter : IDisposable - { - protected GraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters) - { - GraphicsDevice = device; - PresentationParameters = presentationParameters; - } - - public GraphicsDevice GraphicsDevice { get; } - - public abstract object NativePresenter { get; } - - public PresentationParameters PresentationParameters { get; } - - public virtual void BeginDraw(CommandList commandList) - { - } - - public virtual void Dispose() - { - } - - public abstract void Present(); - - public void Resize(int width, int height) - { - PresentationParameters.BackBufferWidth = width; - PresentationParameters.BackBufferHeight = height; - - ResizeBackBuffer(width, height); - } - - protected abstract void ResizeBackBuffer(int width, int height); - } -} diff --git a/src/DirectX12GameEngine.Graphics/HwndSwapChainGraphicsPresenter.cs b/src/DirectX12GameEngine.Graphics/HwndSwapChainGraphicsPresenter.cs deleted file mode 100644 index a441d3cb..00000000 --- a/src/DirectX12GameEngine.Graphics/HwndSwapChainGraphicsPresenter.cs +++ /dev/null @@ -1,38 +0,0 @@ -using SharpDX.DXGI; - -namespace DirectX12GameEngine.Graphics -{ - public class HwndSwapChainGraphicsPresenter : SwapChainGraphicsPresenter - { - private readonly WindowHandle windowHandle; - - public HwndSwapChainGraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters, WindowHandle windowHandle) - : base(device, presentationParameters, CreateSwapChain(device, presentationParameters, windowHandle)) - { - this.windowHandle = windowHandle; - } - - private static SwapChain3 CreateSwapChain(GraphicsDevice device, PresentationParameters presentationParameters, WindowHandle windowHandle) - { - SwapChainDescription1 swapChainDescription = new SwapChainDescription1 - { - Width = presentationParameters.BackBufferWidth, - Height = presentationParameters.BackBufferHeight, - SampleDescription = new SampleDescription(1, 0), - Stereo = presentationParameters.Stereo, - Usage = Usage.RenderTargetOutput, - BufferCount = BufferCount, - Scaling = Scaling.Stretch, - SwapEffect = SwapEffect.FlipSequential, - Format = (Format)presentationParameters.BackBufferFormat, - Flags = SwapChainFlags.None, - AlphaMode = AlphaMode.Unspecified - }; - - using Factory4 factory = new Factory4(); - using SwapChain1 tempSwapChain = new SwapChain1(factory, device.NativeDirectCommandQueue, windowHandle.Handle, ref swapChainDescription); - - return tempSwapChain.QueryInterface(); - } - } -} diff --git a/src/DirectX12GameEngine.Graphics/PixelFormat.cs b/src/DirectX12GameEngine.Graphics/PixelFormat.cs deleted file mode 100644 index e0e88a21..00000000 --- a/src/DirectX12GameEngine.Graphics/PixelFormat.cs +++ /dev/null @@ -1,125 +0,0 @@ -namespace DirectX12GameEngine.Graphics -{ - public enum PixelFormat - { - Unknown = 0, - R32G32B32A32_Typeless = 1, - R32G32B32A32_Float = 2, - R32G32B32A32_UInt = 3, - R32G32B32A32_SInt = 4, - R32G32B32_Typeless = 5, - R32G32B32_Float = 6, - R32G32B32_UInt = 7, - R32G32B32_SInt = 8, - R16G16B16A16_Typeless = 9, - R16G16B16A16_Float = 10, - R16G16B16A16_UNorm = 11, - R16G16B16A16_UInt = 12, - R16G16B16A16_SNorm = 13, - R16G16B16A16_SInt = 14, - R32G32_Typeless = 15, - R32G32_Float = 16, - R32G32_UInt = 17, - R32G32_SInt = 18, - R32G8X24_Typeless = 19, - D32_Float_S8X24_UInt = 20, - R32_Float_X8X24_Typeless = 21, - X32_Typeless_G8X24_UInt = 22, - R10G10B10A2_Typeless = 23, - R10G10B10A2_UNorm = 24, - R10G10B10A2_UInt = 25, - R11G11B10_Float = 26, - R8G8B8A8_Typeless = 27, - R8G8B8A8_UNorm = 28, - R8G8B8A8_UNorm_SRgb = 29, - R8G8B8A8_UInt = 30, - R8G8B8A8_SNorm = 31, - R8G8B8A8_SInt = 32, - R16G16_Typeless = 33, - R16G16_Float = 34, - R16G16_UNorm = 35, - R16G16_UInt = 36, - R16G16_SNorm = 37, - R16G16_SInt = 38, - R32_Typeless = 39, - D32_Float = 40, - R32_Float = 41, - R32_UInt = 42, - R32_SInt = 43, - R24G8_Typeless = 44, - D24_UNorm_S8_UInt = 45, - R24_UNorm_X8_Typeless = 46, - X24_Typeless_G8_UInt = 47, - R8G8_Typeless = 48, - R8G8_UNorm = 49, - R8G8_UInt = 50, - R8G8_SNorm = 51, - R8G8_SInt = 52, - R16_Typeless = 53, - R16_Float = 54, - D16_UNorm = 55, - R16_UNorm = 56, - R16_UInt = 57, - R16_SNorm = 58, - R16_SInt = 59, - R8_Typeless = 60, - R8_UNorm = 61, - R8_UInt = 62, - R8_SNorm = 63, - R8_SInt = 64, - A8_UNorm = 65, - R1_UNorm = 66, - R9G9B9E5_Sharedexp = 67, - R8G8_B8G8_UNorm = 68, - G8R8_G8B8_UNorm = 69, - BC1_Typeless = 70, - BC1_UNorm = 71, - BC1_UNorm_SRgb = 72, - BC2_Typeless = 73, - BC2_UNorm = 74, - BC2_UNorm_SRgb = 75, - BC3_Typeless = 76, - BC3_UNorm = 77, - BC3_UNorm_SRgb = 78, - BC4_Typeless = 79, - BC4_UNorm = 80, - BC4_SNorm = 81, - BC5_Typeless = 82, - BC5_UNorm = 83, - BC5_SNorm = 84, - B5G6R5_UNorm = 85, - B5G5R5A1_UNorm = 86, - B8G8R8A8_UNorm = 87, - B8G8R8X8_UNorm = 88, - R10G10B10_Xr_Bias_A2_UNorm = 89, - B8G8R8A8_Typeless = 90, - B8G8R8A8_UNorm_SRgb = 91, - B8G8R8X8_Typeless = 92, - B8G8R8X8_UNorm_SRgb = 93, - BC6H_Typeless = 94, - BC6H_Uf16 = 95, - BC6H_Sf16 = 96, - BC7_Typeless = 97, - BC7_UNorm = 98, - BC7_UNorm_SRgb = 99, - AYUV = 100, - Y410 = 101, - Y416 = 102, - NV12 = 103, - P010 = 104, - P016 = 105, - Opaque420 = 106, - YUY2 = 107, - Y210 = 108, - Y216 = 109, - NV11 = 110, - AI44 = 111, - IA44 = 112, - P8 = 113, - A8P8 = 114, - B4G4R4A4_UNorm = 115, - P208 = 130, - V208 = 131, - V408 = 132 - } -} diff --git a/src/DirectX12GameEngine.Graphics/PresentationParameters.cs b/src/DirectX12GameEngine.Graphics/PresentationParameters.cs deleted file mode 100644 index b5ca8801..00000000 --- a/src/DirectX12GameEngine.Graphics/PresentationParameters.cs +++ /dev/null @@ -1,37 +0,0 @@ -using SharpDX.DXGI; - -namespace DirectX12GameEngine.Graphics -{ - public class PresentationParameters - { - public PresentationParameters() - { - } - - public PresentationParameters(int backBufferWidth, int backBufferHeight) - : this(backBufferWidth, backBufferHeight, PixelFormat.B8G8R8A8_UNorm) - { - } - - public PresentationParameters(int backBufferWidth, int backBufferHeight, PixelFormat backBufferFomat) - { - BackBufferWidth = backBufferWidth; - BackBufferHeight = backBufferHeight; - BackBufferFormat = backBufferFomat; - } - - public int BackBufferWidth { get; set; } - - public int BackBufferHeight { get; set; } - - public PixelFormat BackBufferFormat { get; set; } = PixelFormat.B8G8R8A8_UNorm; - - public PixelFormat DepthStencilFormat { get; set; } = PixelFormat.D32_Float; - - public PresentParameters PresentParameters { get; set; } - - public bool Stereo { get; set; } - - public int SyncInterval { get; set; } = 1; - } -} diff --git a/src/DirectX12GameEngine.Graphics/SwapChainGraphicsPresenter.cs b/src/DirectX12GameEngine.Graphics/SwapChainGraphicsPresenter.cs deleted file mode 100644 index 8dc3198b..00000000 --- a/src/DirectX12GameEngine.Graphics/SwapChainGraphicsPresenter.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System.Numerics; -using SharpDX.Direct3D12; -using SharpDX.DXGI; - -using Resource = SharpDX.Direct3D12.Resource; - -namespace DirectX12GameEngine.Graphics -{ - public class SwapChainGraphicsPresenter : GraphicsPresenter - { - protected const int BufferCount = 2; - - public SwapChainGraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters, SwapChain3 swapChain) - : base(device, presentationParameters) - { - SwapChain = swapChain; - - if (GraphicsDevice.RenderTargetViewAllocator.DescriptorHeap.Description.DescriptorCount != BufferCount) - { - GraphicsDevice.RenderTargetViewAllocator.Dispose(); - GraphicsDevice.RenderTargetViewAllocator = new DescriptorAllocator(GraphicsDevice, DescriptorHeapType.RenderTargetView, descriptorCount: BufferCount); - } - } - - public Matrix3x2 MatrixTransform { get => SwapChain.MatrixTransform.ToMatrix3x2(); set => SwapChain.MatrixTransform = value.ToMatrix3x2(); } - - public override object NativePresenter => SwapChain; - - protected SwapChain3 SwapChain { get; } - - public override void Dispose() - { - SwapChain.Dispose(); - - base.Dispose(); - } - - public override void Present() - { - SwapChain.Present(PresentationParameters.SyncInterval, PresentFlags.None, PresentationParameters.PresentParameters); - } - - protected override void ResizeBackBuffer(int width, int height) - { - - SwapChain.ResizeBuffers(BufferCount, width, height, (Format)PresentationParameters.BackBufferFormat, SwapChainFlags.None); - - } - } - - internal static class MatrixExtensions - { - public static unsafe SharpDX.Mathematics.Interop.RawMatrix3x2 ToMatrix3x2(this Matrix3x2 value) - { - return *(SharpDX.Mathematics.Interop.RawMatrix3x2*)&value; - } - - public static unsafe Matrix3x2 ToMatrix3x2(this SharpDX.Mathematics.Interop.RawMatrix3x2 value) - { - return *(Matrix3x2*)&value; - } - } -} diff --git a/src/DirectX12GameEngine.Graphics/WindowHandle.cs b/src/DirectX12GameEngine.Graphics/WindowHandle.cs deleted file mode 100644 index 15fa43d6..00000000 --- a/src/DirectX12GameEngine.Graphics/WindowHandle.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; - -namespace DirectX12GameEngine.Graphics -{ - public class WindowHandle - { - public WindowHandle(IntPtr handle) - { - Handle = handle; - } - - public IntPtr Handle { get; } - } -} diff --git a/src/DirectX12GameEngine.Graphics/XamlSwapChainGraphicsPresenter.cs b/src/DirectX12GameEngine.Graphics/XamlSwapChainGraphicsPresenter.cs deleted file mode 100644 index 75850567..00000000 --- a/src/DirectX12GameEngine.Graphics/XamlSwapChainGraphicsPresenter.cs +++ /dev/null @@ -1,63 +0,0 @@ -using SharpDX; -using SharpDX.DXGI; -using Windows.UI.Xaml.Controls; - -namespace DirectX12GameEngine.Graphics -{ - public class XamlSwapChainGraphicsPresenter : SwapChainGraphicsPresenter - { - private readonly SwapChainPanel swapChainPanel; - - public XamlSwapChainGraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters, SwapChainPanel swapChainPanel) - : base(device, presentationParameters, CreateSwapChain(device, presentationParameters, swapChainPanel)) - { - this.swapChainPanel = swapChainPanel; - } - - protected override void ResizeBackBuffer(int width, int height) - { - MatrixTransform = new System.Numerics.Matrix3x2 - { - M11 = 1.0f / swapChainPanel.CompositionScaleX, - M22 = 1.0f / swapChainPanel.CompositionScaleY - }; - - base.ResizeBackBuffer(width, height); - } - - private static SwapChain3 CreateSwapChain(GraphicsDevice device, PresentationParameters presentationParameters, SwapChainPanel swapChainPanel) - { - SwapChainDescription1 swapChainDescription = new SwapChainDescription1 - { - Width = presentationParameters.BackBufferWidth, - Height = presentationParameters.BackBufferHeight, - SampleDescription = new SampleDescription(1, 0), - Stereo = presentationParameters.Stereo, - Usage = Usage.RenderTargetOutput, - BufferCount = BufferCount, - Scaling = Scaling.Stretch, - SwapEffect = SwapEffect.FlipSequential, - Format = (Format)presentationParameters.BackBufferFormat, - Flags = SwapChainFlags.None, - AlphaMode = AlphaMode.Unspecified - }; - - swapChainDescription.AlphaMode = AlphaMode.Premultiplied; - - using Factory4 factory = new Factory4(); - using ISwapChainPanelNative nativePanel = ComObject.As(swapChainPanel); - using SwapChain1 tempSwapChain = new SwapChain1(factory, device.NativeDirectCommandQueue, ref swapChainDescription); - - SwapChain3 swapChain = tempSwapChain.QueryInterface(); - nativePanel.SwapChain = swapChain; - - swapChain.MatrixTransform = new SharpDX.Mathematics.Interop.RawMatrix3x2 - { - M11 = 1.0f / swapChainPanel.CompositionScaleX, - M22 = 1.0f / swapChainPanel.CompositionScaleY - }; - - return swapChain; - } - } -} From 5a3ebc3338803700ff93ea25960caa024e3c5261 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 02:04:57 +0200 Subject: [PATCH 07/25] PipelineState class simplified --- .../CommandList.cs | 9 +- .../PipelineState.cs | 99 +++++-------------- 2 files changed, 24 insertions(+), 84 deletions(-) diff --git a/src/DirectX12GameEngine.Graphics/CommandList.cs b/src/DirectX12GameEngine.Graphics/CommandList.cs index bcc34d45..7a0b407b 100644 --- a/src/DirectX12GameEngine.Graphics/CommandList.cs +++ b/src/DirectX12GameEngine.Graphics/CommandList.cs @@ -201,14 +201,7 @@ namespace DirectX12GameEngine.Graphics public void SetPipelineState(PipelineState pipelineState) { - if (pipelineState.IsCompute) - { - SetComputeRootSignature(pipelineState.RootSignature); - } - else - { - SetGraphicsRootSignature(pipelineState.RootSignature); - } + SetComputeRootSignature(pipelineState.RootSignature); currentCommandList.NativeCommandList.PipelineState = pipelineState.NativePipelineState; } diff --git a/src/DirectX12GameEngine.Graphics/PipelineState.cs b/src/DirectX12GameEngine.Graphics/PipelineState.cs index 79bcfd32..c74c8967 100644 --- a/src/DirectX12GameEngine.Graphics/PipelineState.cs +++ b/src/DirectX12GameEngine.Graphics/PipelineState.cs @@ -1,88 +1,35 @@ -using SharpDX.Direct3D; -using SharpDX.Direct3D12; -using SharpDX.DXGI; +using SharpDX.Direct3D12; namespace DirectX12GameEngine.Graphics { - public sealed class PipelineState + /// + /// A representing a custom pipeline state for a compute operation + /// + public sealed class PipelineState : ComputePipelineStateDescription { - public PipelineState(GraphicsDevice device, ComputePipelineStateDescription pipelineStateDescription) - { - IsCompute = true; - RootSignature = pipelineStateDescription.RootSignaturePointer; - NativePipelineState = device.NativeDevice.CreateComputePipelineState(pipelineStateDescription); - } - + /// + /// Creates a new instance with the specified parameters + /// + /// The to use + /// The value for the current shader + /// The bytecode for the compute shader to run public PipelineState(GraphicsDevice device, RootSignature rootSignature, ShaderBytecode computeShader) - : this(device, CreateComputePipelineStateDescription(rootSignature, computeShader)) - { - } - - public PipelineState(GraphicsDevice device, GraphicsPipelineStateDescription pipelineStateDescription) - { - IsCompute = false; - RootSignature = pipelineStateDescription.RootSignature; - NativePipelineState = device.NativeDevice.CreateGraphicsPipelineState(pipelineStateDescription); - } - - public PipelineState(GraphicsDevice device, InputElement[] inputElements, RootSignature rootSignature, ShaderBytecode vertexShader, ShaderBytecode pixelShader, ShaderBytecode hullShader = default, ShaderBytecode domainShader = default, ShaderBytecode geometryShader = default, RasterizerStateDescription? rasterizerStateDescription = null) - : this(device, CreateGraphicsPipelineStateDescription(device, inputElements, rootSignature, vertexShader, pixelShader, hullShader, domainShader, geometryShader, rasterizerStateDescription)) { + RootSignaturePointer = rootSignature; + ComputeShader = computeShader; + RootSignature = RootSignaturePointer; + + NativePipelineState = device.NativeDevice.CreateComputePipelineState(this); } + /// + /// Gets the value for the current shader + /// public RootSignature RootSignature { get; } - internal bool IsCompute { get; } - - internal SharpDX.Direct3D12.PipelineState NativePipelineState { get; } - - private static ComputePipelineStateDescription CreateComputePipelineStateDescription(RootSignature rootSignature, ShaderBytecode computeShader) - { - return new ComputePipelineStateDescription - { - RootSignaturePointer = rootSignature, - ComputeShader = computeShader - }; - } - - private static GraphicsPipelineStateDescription CreateGraphicsPipelineStateDescription(GraphicsDevice device, InputElement[] inputElements, RootSignature rootSignature, ShaderBytecode vertexShader, ShaderBytecode pixelShader, ShaderBytecode hullShader, ShaderBytecode domainShader, ShaderBytecode geometryShader, RasterizerStateDescription? rasterizerStateDescription) - { - RasterizerStateDescription rasterizerDescription = rasterizerStateDescription ?? RasterizerStateDescription.Default(); - rasterizerDescription.IsFrontCounterClockwise = true; - rasterizerDescription.CullMode = CullMode.None; - - BlendStateDescription blendStateDescription = BlendStateDescription.Default(); - RenderTargetBlendDescription[] renderTargetDescriptions = blendStateDescription.RenderTarget; - - for (int i = 0; i < renderTargetDescriptions.Length; i++) - { - renderTargetDescriptions[i].IsBlendEnabled = true; - renderTargetDescriptions[i].SourceBlend = BlendOption.SourceAlpha; - renderTargetDescriptions[i].DestinationBlend = BlendOption.InverseSourceAlpha; - } - - DepthStencilStateDescription depthStencilStateDescription = DepthStencilStateDescription.Default(); - - GraphicsPipelineStateDescription pipelineStateDescription = new GraphicsPipelineStateDescription - { - InputLayout = new InputLayoutDescription(inputElements), - RootSignature = rootSignature, - VertexShader = vertexShader, - PixelShader = pixelShader, - HullShader = hullShader, - DomainShader = domainShader, - GeometryShader = geometryShader, - RasterizerState = rasterizerDescription, - BlendState = blendStateDescription, - DepthStencilState = depthStencilStateDescription, - SampleMask = int.MaxValue, - PrimitiveTopologyType = PrimitiveTopologyType.Triangle, - RenderTargetCount = 1, - SampleDescription = new SampleDescription(1, 0), - StreamOutput = new StreamOutputDescription() - }; - - return pipelineStateDescription; - } + /// + /// Gets the instance for the current object + /// + public SharpDX.Direct3D12.PipelineState NativePipelineState { get; } } } From 321deb22c3085fa811779a6045e9298bdf82671e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 02:06:31 +0200 Subject: [PATCH 08/25] Removed unused Direct3DInterop class --- .../Direct3DInterop.cs | 70 ------------------- 1 file changed, 70 deletions(-) delete mode 100644 src/DirectX12GameEngine.Graphics/Direct3DInterop.cs diff --git a/src/DirectX12GameEngine.Graphics/Direct3DInterop.cs b/src/DirectX12GameEngine.Graphics/Direct3DInterop.cs deleted file mode 100644 index a0f50b62..00000000 --- a/src/DirectX12GameEngine.Graphics/Direct3DInterop.cs +++ /dev/null @@ -1,70 +0,0 @@ -using SharpDX; -using SharpDX.DXGI; -using System; -using System.Runtime.InteropServices; -using Windows.Graphics.DirectX.Direct3D11; - -namespace DirectX12GameEngine.Graphics -{ - internal static class Direct3DInterop - { - private static readonly Guid ID3D11Resource = new Guid("DC8E63F3-D12B-4952-B47B-5E45026A862D"); - - [ComImport] - [Guid("A9B3D012-3DF2-4EE3-B8D1-8695F457D3C1")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - [ComVisible(true)] - private interface IDirect3DDxgiInterfaceAccess : IDisposable - { - IntPtr GetInterface([In] ref Guid iid); - } - - internal static IDirect3DDevice CreateDirect3DDevice(Device dxgiDevice) - { - Result result = CreateDirect3D11DeviceFromDXGIDevice(dxgiDevice.NativePointer, out IntPtr graphicsDevice); - - if (result.Failure) throw new InvalidOperationException(result.Code.ToString()); - - IDirect3DDevice d3DInteropDevice = (IDirect3DDevice)Marshal.GetObjectForIUnknown(graphicsDevice); - Marshal.Release(graphicsDevice); - - return d3DInteropDevice; - } - - internal static IDirect3DSurface CreateDirect3DSurface(Surface dxgiSurface) - { - Result result = CreateDirect3D11SurfaceFromDXGISurface(dxgiSurface.NativePointer, out IntPtr graphicsSurface); - - if (result.Failure) throw new InvalidOperationException(result.Code.ToString()); - - IDirect3DSurface d3DSurface = (IDirect3DSurface)Marshal.GetObjectForIUnknown(graphicsSurface); - Marshal.Release(graphicsSurface); - - return d3DSurface; - } - - internal static Device CreateDXGIDevice(IDirect3DDevice direct3DDevice) - { - IDirect3DDxgiInterfaceAccess dxgiDeviceInterfaceAccess = (IDirect3DDxgiInterfaceAccess)direct3DDevice; - IntPtr device = dxgiDeviceInterfaceAccess.GetInterface(ID3D11Resource); - - return new Device(device); - } - - internal static Surface CreateDXGISurface(IDirect3DSurface direct3DSurface) - { - IDirect3DDxgiInterfaceAccess dxgiSurfaceInterfaceAccess = (IDirect3DDxgiInterfaceAccess)direct3DSurface; - IntPtr surface = dxgiSurfaceInterfaceAccess.GetInterface(ID3D11Resource); - - return new Surface(surface); - } - - [DllImport("d3d11.dll", EntryPoint = "CreateDirect3D11DeviceFromDXGIDevice", - SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] - private static extern Result CreateDirect3D11DeviceFromDXGIDevice(IntPtr dxgiDevice, out IntPtr graphicsDevice); - - [DllImport("d3d11.dll", EntryPoint = "CreateDirect3D11SurfaceFromDXGISurface", - SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] - private static extern Result CreateDirect3D11SurfaceFromDXGISurface(IntPtr dxgiSurface, out IntPtr graphicsSurface); - } -} From 072b16f2e27df4c1ae734249c67a5e5a0fb19bb6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 02:10:50 +0200 Subject: [PATCH 09/25] Removed unnecessary code from the GraphicsDevice class --- .../GraphicsDevice.cs | 67 ------------------- 1 file changed, 67 deletions(-) diff --git a/src/DirectX12GameEngine.Graphics/GraphicsDevice.cs b/src/DirectX12GameEngine.Graphics/GraphicsDevice.cs index a5f67e05..ed11f4c7 100644 --- a/src/DirectX12GameEngine.Graphics/GraphicsDevice.cs +++ b/src/DirectX12GameEngine.Graphics/GraphicsDevice.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; using System.Threading; using SharpDX.Direct3D; using SharpDX.Direct3D12; @@ -91,48 +89,11 @@ namespace DirectX12GameEngine.Graphics internal long NextDirectFenceValue { get; private set; } = 1; - public void CopyDescriptors(int numDestDescriptorRanges, CpuDescriptorHandle[] destDescriptorRangeStartsRef, int[] destDescriptorRangeSizesRef, int numSrcDescriptorRanges, CpuDescriptorHandle[] srcDescriptorRangeStartsRef, int[] srcDescriptorRangeSizesRef, DescriptorHeapType descriptorHeapsType) - { - NativeDevice.CopyDescriptors(numDestDescriptorRanges, destDescriptorRangeStartsRef, destDescriptorRangeSizesRef, numSrcDescriptorRanges, srcDescriptorRangeStartsRef, srcDescriptorRangeSizesRef, descriptorHeapsType); - } - - public (CpuDescriptorHandle, GpuDescriptorHandle) CopyDescriptorsToOneDescriptorHandle(IEnumerable resources) - { - return CopyDescriptorsToOneDescriptorHandle(resources.Select(t => t.NativeCpuDescriptorHandle).ToArray()); - } - - public (CpuDescriptorHandle, GpuDescriptorHandle) CopyDescriptorsToOneDescriptorHandle(CpuDescriptorHandle[] descriptors) - { - if (descriptors.Length == 0) return default; - - int[] srcDescriptorRangeStarts = new int[descriptors.Length]; - //Array.Fill(srcDescriptorRangeStarts, 1); - - for (int i = 0; i < srcDescriptorRangeStarts.Length; i++) - { - srcDescriptorRangeStarts[i] = 1; - } - - var (cpuDescriptorHandle, gpuDescriptorHandle) = ShaderResourceViewAllocator.Allocate(descriptors.Length); - - CopyDescriptors( - 1, new[] { cpuDescriptorHandle }, new[] { descriptors.Length }, - descriptors.Length, descriptors, srcDescriptorRangeStarts, - DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); - - return (cpuDescriptorHandle, gpuDescriptorHandle); - } - public RootSignature CreateRootSignature(RootSignatureDescription rootSignatureDescription) { return NativeDevice.CreateRootSignature(rootSignatureDescription.Serialize()); } - public RootSignature CreateRootSignature(byte[] bytecode) - { - return NativeDevice.CreateRootSignature(bytecode); - } - public void Dispose() { NativeDirectCommandQueue.Signal(NativeDirectFence, NextDirectFenceValue); @@ -248,32 +209,4 @@ namespace DirectX12GameEngine.Graphics } } } - - internal class D3DXUtilities - { - public const int ComponentMappingMask = 0x7; - - public const int ComponentMappingShift = 3; - - public const int ComponentMappingAlwaysSetBitAvoidingZeromemMistakes = 1 << (ComponentMappingShift * 4); - - public static int ComponentMapping(int src0, int src1, int src2, int src3) - { - return ((src0) & ComponentMappingMask) - | (((src1) & ComponentMappingMask) << ComponentMappingShift) - | (((src2) & ComponentMappingMask) << (ComponentMappingShift * 2)) - | (((src3) & ComponentMappingMask) << (ComponentMappingShift * 3)) - | ComponentMappingAlwaysSetBitAvoidingZeromemMistakes; - } - - public static int DefaultComponentMapping() - { - return ComponentMapping(0, 1, 2, 3); - } - - public static int ComponentMapping(int ComponentToExtract, int Mapping) - { - return (Mapping >> (ComponentMappingShift * ComponentToExtract)) & ComponentMappingMask; - } - } } From 8e041638db2fe0f1365d938e15c6b34b7dee874c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 02:16:58 +0200 Subject: [PATCH 10/25] More code refactoring --- src/DirectX12ComputeShaderSample/Program.cs | 2 +- .../CommandList.cs | 91 ------------------- .../GraphicsDevice.cs | 17 +--- 3 files changed, 4 insertions(+), 106 deletions(-) diff --git a/src/DirectX12ComputeShaderSample/Program.cs b/src/DirectX12ComputeShaderSample/Program.cs index 07b57fba..b34ecd8c 100644 --- a/src/DirectX12ComputeShaderSample/Program.cs +++ b/src/DirectX12ComputeShaderSample/Program.cs @@ -37,7 +37,7 @@ namespace DirectX12ComputeShaderSample // Create graphics device and pipeline state - using GraphicsDevice device = new GraphicsDevice(SharpDX.Direct3D.FeatureLevel.Level_12_1, true); + using GraphicsDevice device = new GraphicsDevice(true); SharpDX.Direct3D12.RootParameter[] rootParameters = new SharpDX.Direct3D12.RootParameter[] { diff --git a/src/DirectX12GameEngine.Graphics/CommandList.cs b/src/DirectX12GameEngine.Graphics/CommandList.cs index 7a0b407b..cc7c597a 100644 --- a/src/DirectX12GameEngine.Graphics/CommandList.cs +++ b/src/DirectX12GameEngine.Graphics/CommandList.cs @@ -1,16 +1,10 @@ using System; -using System.Numerics; -using SharpDX.Direct3D; using SharpDX.Direct3D12; -using SharpDX.Mathematics.Interop; namespace DirectX12GameEngine.Graphics { public sealed class CommandList : IDisposable { - private const int MaxRenderTargetCount = 8; - private const int MaxViewportAndScissorRectangleCount = 16; - private readonly CompiledCommandList currentCommandList; public CommandList(GraphicsDevice device, CommandListType commandListType) @@ -30,24 +24,6 @@ namespace DirectX12GameEngine.Graphics public GraphicsDevice GraphicsDevice { get; } - public RawRectangle[] ScissorRectangles { get; private set; } = Array.Empty(); - - public RawViewportF[] Viewports { get; private set; } = Array.Empty(); - - public PrimitiveTopology PrimitiveTopology { set => currentCommandList.NativeCommandList.PrimitiveTopology = value; } - - public void BeginRenderPass(int numRenderTargets, RenderPassRenderTargetDescription[] renderTargetsRef, RenderPassDepthStencilDescription? depthStencilRef, RenderPassFlags flags) - { - using GraphicsCommandList4 commandList = currentCommandList.NativeCommandList.QueryInterface(); - commandList.BeginRenderPass(numRenderTargets, renderTargetsRef, depthStencilRef, flags); - } - - public void EndRenderPass() - { - using GraphicsCommandList4 commandList = currentCommandList.NativeCommandList.QueryInterface(); - commandList.EndRenderPass(); - } - public CompiledCommandList Close() { //foreach (var renderTarget in RenderTargets) @@ -70,11 +46,6 @@ namespace DirectX12GameEngine.Graphics currentCommandList.NativeCommandList.CopyResource(destination.NativeResource, source.NativeResource); } - public void CopyTextureRegion(TextureCopyLocation source, TextureCopyLocation destination) - { - currentCommandList.NativeCommandList.CopyTextureRegion(destination, 0, 0, 0, source, null); - } - public void Dispatch(int threadGroupCountX, int threadGroupCountY, int threadGroupCountZ) { currentCommandList.NativeCommandList.Dispatch(threadGroupCountX, threadGroupCountY, threadGroupCountZ); @@ -103,24 +74,6 @@ namespace DirectX12GameEngine.Graphics currentCommandList.NativeCommandList.Dispose(); } - public void DrawIndexedInstanced(int indexCountPerInstance, int instanceCount, int startIndexLocation = 0, int baseVertexLocation = 0, int startInstanceLocation = 0) - { - currentCommandList.NativeCommandList.DrawIndexedInstanced(indexCountPerInstance, instanceCount, startIndexLocation, baseVertexLocation, startInstanceLocation); - } - - public void DrawInstanced(int vertexCountPerInstance, int instanceCount, int startVertexLocation = 0, int startInstanceLocation = 0) - { - currentCommandList.NativeCommandList.DrawInstanced(vertexCountPerInstance, instanceCount, startVertexLocation, startInstanceLocation); - } - - public void ExecuteBundle(CompiledCommandList commandList) - { - if (currentCommandList != commandList && commandList.Builder.CommandListType == CommandListType.Bundle) - { - currentCommandList.NativeCommandList.ExecuteBundle(commandList.NativeCommandList); - } - } - public void Flush(bool wait = false) { GraphicsDevice.ExecuteCommandLists(wait, Close()); @@ -194,11 +147,6 @@ namespace DirectX12GameEngine.Graphics currentCommandList.NativeCommandList.SetComputeRootUnorderedAccessView(rootParameterIndex, resource.NativeResource.GPUVirtualAddress); } - public void SetIndexBuffer(IndexBufferView? indexBufferView) - { - currentCommandList.NativeCommandList.SetIndexBuffer(indexBufferView); - } - public void SetPipelineState(PipelineState pipelineState) { SetComputeRootSignature(pipelineState.RootSignature); @@ -206,45 +154,6 @@ namespace DirectX12GameEngine.Graphics currentCommandList.NativeCommandList.PipelineState = pipelineState.NativePipelineState; } - public void SetScissorRectangles(params RawRectangle[] scissorRectangles) - { - if (scissorRectangles.Length > MaxViewportAndScissorRectangleCount) - { - throw new ArgumentOutOfRangeException(nameof(scissorRectangles), scissorRectangles.Length, $"The maximum number of scissor rectangles is {MaxViewportAndScissorRectangleCount}."); - } - - if (ScissorRectangles.Length != scissorRectangles.Length) - { - ScissorRectangles = new RawRectangle[scissorRectangles.Length]; - } - - scissorRectangles.CopyTo(ScissorRectangles, 0); - - currentCommandList.NativeCommandList.SetScissorRectangles(scissorRectangles); - } - - public void SetVertexBuffers(int startSlot, params VertexBufferView[] vertexBufferViews) - { - currentCommandList.NativeCommandList.SetVertexBuffers(startSlot, vertexBufferViews); - } - - public void SetViewports(params RawViewportF[] viewports) - { - if (viewports.Length > MaxViewportAndScissorRectangleCount) - { - throw new ArgumentOutOfRangeException(nameof(viewports), viewports.Length, $"The maximum number of viewporst is {MaxViewportAndScissorRectangleCount}."); - } - - if (Viewports.Length != viewports.Length) - { - Viewports = new RawViewportF[viewports.Length]; - } - - viewports.CopyTo(Viewports, 0); - - currentCommandList.NativeCommandList.SetViewports(viewports); - } - private CommandAllocator GetCommandAllocator() => CommandListType switch { CommandListType.Bundle => GraphicsDevice.BundleAllocatorPool.GetCommandAllocator(), diff --git a/src/DirectX12GameEngine.Graphics/GraphicsDevice.cs b/src/DirectX12GameEngine.Graphics/GraphicsDevice.cs index ed11f4c7..42be36df 100644 --- a/src/DirectX12GameEngine.Graphics/GraphicsDevice.cs +++ b/src/DirectX12GameEngine.Graphics/GraphicsDevice.cs @@ -8,18 +8,12 @@ namespace DirectX12GameEngine.Graphics public sealed class GraphicsDevice : IDisposable { private readonly AutoResetEvent fenceEvent = new AutoResetEvent(false); - private SharpDX.Direct3D11.Device? nativeDirect3D11Device; - public GraphicsDevice(FeatureLevel minFeatureLevel = FeatureLevel.Level_11_0, bool enableDebugLayer = false) + public GraphicsDevice(bool enableDebugLayer = false) { #if DEBUG - if (enableDebugLayer) - { - DebugInterface.Get().EnableDebugLayer(); - } + if (enableDebugLayer) DebugInterface.Get().EnableDebugLayer(); #endif - FeatureLevel = minFeatureLevel < FeatureLevel.Level_11_0 ? FeatureLevel.Level_11_0 : minFeatureLevel; - NativeDevice = new Device(null, FeatureLevel); NativeComputeCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Compute)); @@ -50,13 +44,10 @@ namespace DirectX12GameEngine.Graphics public CommandList CopyCommandList { get; } - public FeatureLevel FeatureLevel { get; } + public const FeatureLevel FeatureLevel = SharpDX.Direct3D.FeatureLevel.Level_12_1; internal Device NativeDevice { get; } - internal SharpDX.Direct3D11.Device NativeDirect3D11Device => NativeDirect3D11Device ?? (nativeDirect3D11Device = SharpDX.Direct3D11.Device.CreateFromDirect3D12( - NativeDevice, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport, null, null, NativeDirectCommandQueue)); - internal DescriptorAllocator DepthStencilViewAllocator { get; set; } internal DescriptorAllocator RenderTargetViewAllocator { get; set; } @@ -119,8 +110,6 @@ namespace DirectX12GameEngine.Graphics NativeDirectFence.Dispose(); NativeDirectFence.Dispose(); - nativeDirect3D11Device?.Dispose(); - NativeDevice.Dispose(); } From 79605702c833e4f097fd537e712699dad6144b29 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 02:24:54 +0200 Subject: [PATCH 11/25] GraphicsResource class refactored --- src/DirectX12GameEngine.Graphics/Buffer.cs | 5 +- .../CommandList.cs | 1 + .../GraphicsResource.cs | 54 -------------- .../Primitives/Abstract/GraphicsResource.cs | 70 +++++++++++++++++++ 4 files changed, 72 insertions(+), 58 deletions(-) delete mode 100644 src/DirectX12GameEngine.Graphics/GraphicsResource.cs create mode 100644 src/DirectX12GameEngine.Graphics/Primitives/Abstract/GraphicsResource.cs diff --git a/src/DirectX12GameEngine.Graphics/Buffer.cs b/src/DirectX12GameEngine.Graphics/Buffer.cs index 8fe4b741..8b9ee87b 100644 --- a/src/DirectX12GameEngine.Graphics/Buffer.cs +++ b/src/DirectX12GameEngine.Graphics/Buffer.cs @@ -1,16 +1,13 @@ using System; using System.Runtime.CompilerServices; using DirectX12GameEngine.Core; +using DirectX12GameEngine.Graphics.Primitives.Abstract; using SharpDX.Direct3D12; namespace DirectX12GameEngine.Graphics { public partial class Buffer : GraphicsResource { - public Buffer() - { - } - protected Buffer(GraphicsDevice device) : base(device) { } diff --git a/src/DirectX12GameEngine.Graphics/CommandList.cs b/src/DirectX12GameEngine.Graphics/CommandList.cs index cc7c597a..699ea89b 100644 --- a/src/DirectX12GameEngine.Graphics/CommandList.cs +++ b/src/DirectX12GameEngine.Graphics/CommandList.cs @@ -1,4 +1,5 @@ using System; +using DirectX12GameEngine.Graphics.Primitives.Abstract; using SharpDX.Direct3D12; namespace DirectX12GameEngine.Graphics diff --git a/src/DirectX12GameEngine.Graphics/GraphicsResource.cs b/src/DirectX12GameEngine.Graphics/GraphicsResource.cs deleted file mode 100644 index 3ea86e7c..00000000 --- a/src/DirectX12GameEngine.Graphics/GraphicsResource.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System; -using SharpDX.Direct3D12; - -namespace DirectX12GameEngine.Graphics -{ - public abstract class GraphicsResource : IDisposable - { - protected GraphicsResource() - { - } - - protected GraphicsResource(GraphicsDevice device) - { - AttachToGraphicsDevice(device); - } - -#nullable disable - public GraphicsDevice GraphicsDevice { get; private set; } -#nullable restore - - public IntPtr MappedResource { get; private set; } - -#nullable disable - protected internal Resource NativeResource { get; set; } -#nullable restore - - protected internal CpuDescriptorHandle NativeCpuDescriptorHandle { get; protected set; } - - protected internal GpuDescriptorHandle NativeGpuDescriptorHandle { get; protected set; } - - public void AttachToGraphicsDevice(GraphicsDevice device) - { - GraphicsDevice = device; - } - - public virtual void Dispose() - { - NativeResource.Dispose(); - } - - public IntPtr Map(int subresource) - { - IntPtr mappedResource = NativeResource.Map(subresource); - MappedResource = mappedResource; - return mappedResource; - } - - public void Unmap(int subresource) - { - NativeResource.Unmap(subresource); - MappedResource = IntPtr.Zero; - } - } -} diff --git a/src/DirectX12GameEngine.Graphics/Primitives/Abstract/GraphicsResource.cs b/src/DirectX12GameEngine.Graphics/Primitives/Abstract/GraphicsResource.cs new file mode 100644 index 00000000..61a0d1eb --- /dev/null +++ b/src/DirectX12GameEngine.Graphics/Primitives/Abstract/GraphicsResource.cs @@ -0,0 +1,70 @@ +using System; +using SharpDX.Direct3D12; + +namespace DirectX12GameEngine.Graphics.Primitives.Abstract +{ + /// + /// An abstract that represents a graphics resource object + /// + public abstract class GraphicsResource : IDisposable + { + /// + /// Creates a new instance with the specified parameters + /// + /// The associated with the current instance + protected GraphicsResource(GraphicsDevice device) + { + GraphicsDevice = device; + } + + /// + /// Gets the associated with the current instance + /// + public GraphicsDevice GraphicsDevice { get; } + + /// + /// Gets the associated to the currently mapped resource + /// + public IntPtr MappedResource { get; private set; } + + /// + /// Gets the object currently mapped + /// + protected internal Resource? NativeResource { get; set; } + + /// + /// Gets the instance for the current resource + /// + protected internal CpuDescriptorHandle NativeCpuDescriptorHandle { get; protected set; } + + /// + /// Gets the instance for the current resource + /// + protected internal GpuDescriptorHandle NativeGpuDescriptorHandle { get; protected set; } + + /// + /// Maps the current resource to a specified subresource + /// + /// The index of the target subresource to map + /// An for the newly mapped resource + public IntPtr Map(int subresource) + { + IntPtr mappedResource = NativeResource?.Map(subresource) ?? throw new InvalidOperationException("Missing resource"); + MappedResource = mappedResource; + return mappedResource; + } + + /// + /// Unmaps a subresource specified by a given index + /// + /// The index of the subresource to unmap + public void Unmap(int subresource) + { + NativeResource?.Unmap(subresource); + MappedResource = IntPtr.Zero; + } + + /// + public virtual void Dispose() => NativeResource?.Dispose(); + } +} From c0f261e5e1c100a40cd0e70f8f9cf14ea2b4b53e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 02:27:22 +0200 Subject: [PATCH 12/25] Buffer classes moved --- src/DirectX12ComputeShaderSample/Program.cs | 4 +-- .../Buffer.Index.cs | 27 ------------------- .../Abstract/GraphicsResource.cs | 2 +- .../{ => Buffers}/Buffer.Constant.cs | 2 +- .../{ => Buffers}/Buffer.UnorderedAccess.cs | 10 +++---- .../{ => Buffers}/Buffer.Vertex.cs | 14 +++++----- .../{ => Buffers}/Buffer.cs | 16 +++++------ .../CommandList.cs | 2 +- 8 files changed, 25 insertions(+), 52 deletions(-) delete mode 100644 src/DirectX12GameEngine.Graphics/Buffer.Index.cs rename src/DirectX12GameEngine.Graphics/{Primitives => Buffers}/Abstract/GraphicsResource.cs (97%) rename src/DirectX12GameEngine.Graphics/{ => Buffers}/Buffer.Constant.cs (95%) rename src/DirectX12GameEngine.Graphics/{ => Buffers}/Buffer.UnorderedAccess.cs (52%) rename src/DirectX12GameEngine.Graphics/{ => Buffers}/Buffer.Vertex.cs (65%) rename src/DirectX12GameEngine.Graphics/{ => Buffers}/Buffer.cs (92%) diff --git a/src/DirectX12ComputeShaderSample/Program.cs b/src/DirectX12ComputeShaderSample/Program.cs index b34ecd8c..67e0e101 100644 --- a/src/DirectX12ComputeShaderSample/Program.cs +++ b/src/DirectX12ComputeShaderSample/Program.cs @@ -3,8 +3,8 @@ using DirectX12GameEngine.Shaders; using DirectX12GameEngine.Shaders.Numerics; using System; using System.Linq; - -using Buffer = DirectX12GameEngine.Graphics.Buffer; +using DirectX12GameEngine.Graphics.Buffers; +using Buffer = DirectX12GameEngine.Graphics.Buffers.Buffer; namespace DirectX12ComputeShaderSample { diff --git a/src/DirectX12GameEngine.Graphics/Buffer.Index.cs b/src/DirectX12GameEngine.Graphics/Buffer.Index.cs deleted file mode 100644 index 398811fd..00000000 --- a/src/DirectX12GameEngine.Graphics/Buffer.Index.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using SharpDX.Direct3D12; -using SharpDX.DXGI; - -namespace DirectX12GameEngine.Graphics -{ - public partial class Buffer - { - public static class Index - { - public static unsafe Buffer New(GraphicsDevice device, int size, GraphicsHeapType heapType = GraphicsHeapType.Default) - { - return Buffer.New(device, size, BufferFlags.IndexBuffer, heapType); - } - - public static unsafe Buffer New(GraphicsDevice device, in T data, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged - { - return Buffer.New(device, data, BufferFlags.IndexBuffer, heapType); - } - - public static unsafe Buffer New(GraphicsDevice device, Span data, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged - { - return Buffer.New(device, data, BufferFlags.IndexBuffer, heapType); - } - } - } -} diff --git a/src/DirectX12GameEngine.Graphics/Primitives/Abstract/GraphicsResource.cs b/src/DirectX12GameEngine.Graphics/Buffers/Abstract/GraphicsResource.cs similarity index 97% rename from src/DirectX12GameEngine.Graphics/Primitives/Abstract/GraphicsResource.cs rename to src/DirectX12GameEngine.Graphics/Buffers/Abstract/GraphicsResource.cs index 61a0d1eb..1ffa6721 100644 --- a/src/DirectX12GameEngine.Graphics/Primitives/Abstract/GraphicsResource.cs +++ b/src/DirectX12GameEngine.Graphics/Buffers/Abstract/GraphicsResource.cs @@ -1,7 +1,7 @@ using System; using SharpDX.Direct3D12; -namespace DirectX12GameEngine.Graphics.Primitives.Abstract +namespace DirectX12GameEngine.Graphics.Buffers.Abstract { /// /// An abstract that represents a graphics resource object diff --git a/src/DirectX12GameEngine.Graphics/Buffer.Constant.cs b/src/DirectX12GameEngine.Graphics/Buffers/Buffer.Constant.cs similarity index 95% rename from src/DirectX12GameEngine.Graphics/Buffer.Constant.cs rename to src/DirectX12GameEngine.Graphics/Buffers/Buffer.Constant.cs index 13365b9a..7745734e 100644 --- a/src/DirectX12GameEngine.Graphics/Buffer.Constant.cs +++ b/src/DirectX12GameEngine.Graphics/Buffers/Buffer.Constant.cs @@ -1,6 +1,6 @@ using System; -namespace DirectX12GameEngine.Graphics +namespace DirectX12GameEngine.Graphics.Buffers { public partial class Buffer { diff --git a/src/DirectX12GameEngine.Graphics/Buffer.UnorderedAccess.cs b/src/DirectX12GameEngine.Graphics/Buffers/Buffer.UnorderedAccess.cs similarity index 52% rename from src/DirectX12GameEngine.Graphics/Buffer.UnorderedAccess.cs rename to src/DirectX12GameEngine.Graphics/Buffers/Buffer.UnorderedAccess.cs index 8fd99873..20ec576d 100644 --- a/src/DirectX12GameEngine.Graphics/Buffer.UnorderedAccess.cs +++ b/src/DirectX12GameEngine.Graphics/Buffers/Buffer.UnorderedAccess.cs @@ -1,24 +1,24 @@ using System; -namespace DirectX12GameEngine.Graphics +namespace DirectX12GameEngine.Graphics.Buffers { public partial class Buffer { public static class UnorderedAccess { - public static unsafe Buffer New(GraphicsDevice device, int size, GraphicsHeapType heapType = GraphicsHeapType.Default) + public static unsafe Buffers.Buffer New(GraphicsDevice device, int size, GraphicsHeapType heapType = GraphicsHeapType.Default) { - return Buffer.New(device, size, BufferFlags.UnorderedAccess, heapType); + return Buffers.Buffer.New(device, size, BufferFlags.UnorderedAccess, heapType); } public static unsafe Buffer New(GraphicsDevice device, in T data, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged { - return Buffer.New(device, data, BufferFlags.UnorderedAccess, heapType); + return Buffers.Buffer.New(device, data, BufferFlags.UnorderedAccess, heapType); } public static unsafe Buffer New(GraphicsDevice device, Span data, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged { - return Buffer.New(device, data, BufferFlags.UnorderedAccess, heapType); + return Buffers.Buffer.New(device, data, BufferFlags.UnorderedAccess, heapType); } } } diff --git a/src/DirectX12GameEngine.Graphics/Buffer.Vertex.cs b/src/DirectX12GameEngine.Graphics/Buffers/Buffer.Vertex.cs similarity index 65% rename from src/DirectX12GameEngine.Graphics/Buffer.Vertex.cs rename to src/DirectX12GameEngine.Graphics/Buffers/Buffer.Vertex.cs index 6fd0b84b..b78b5338 100644 --- a/src/DirectX12GameEngine.Graphics/Buffer.Vertex.cs +++ b/src/DirectX12GameEngine.Graphics/Buffers/Buffer.Vertex.cs @@ -2,28 +2,28 @@ using System.Runtime.CompilerServices; using SharpDX.Direct3D12; -namespace DirectX12GameEngine.Graphics +namespace DirectX12GameEngine.Graphics.Buffers { public partial class Buffer { public static class Vertex { - public static unsafe Buffer New(GraphicsDevice device, int size, GraphicsHeapType heapType = GraphicsHeapType.Default) + public static unsafe Buffers.Buffer New(GraphicsDevice device, int size, GraphicsHeapType heapType = GraphicsHeapType.Default) { - return Buffer.New(device, size, BufferFlags.VertexBuffer, heapType); + return Buffers.Buffer.New(device, size, BufferFlags.VertexBuffer, heapType); } public static unsafe Buffer New(GraphicsDevice device, in T data, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged { - return Buffer.New(device, data, BufferFlags.VertexBuffer, heapType); + return Buffers.Buffer.New(device, data, BufferFlags.VertexBuffer, heapType); } public static unsafe Buffer New(GraphicsDevice device, Span data, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged { - return Buffer.New(device, data, BufferFlags.VertexBuffer, heapType); + return Buffers.Buffer.New(device, data, BufferFlags.VertexBuffer, heapType); } - public static VertexBufferView CreateVertexBufferView(Buffer vertexBuffer, int size, int stride) + public static VertexBufferView CreateVertexBufferView(Buffers.Buffer vertexBuffer, int size, int stride) { return new VertexBufferView { @@ -33,7 +33,7 @@ namespace DirectX12GameEngine.Graphics }; } - public static unsafe VertexBufferView CreateVertexBufferView(Buffer vertexBuffer, int size) where T : unmanaged + public static unsafe VertexBufferView CreateVertexBufferView(Buffers.Buffer vertexBuffer, int size) where T : unmanaged { return CreateVertexBufferView(vertexBuffer, size, Unsafe.SizeOf()); } diff --git a/src/DirectX12GameEngine.Graphics/Buffer.cs b/src/DirectX12GameEngine.Graphics/Buffers/Buffer.cs similarity index 92% rename from src/DirectX12GameEngine.Graphics/Buffer.cs rename to src/DirectX12GameEngine.Graphics/Buffers/Buffer.cs index 8b9ee87b..aecaa8e8 100644 --- a/src/DirectX12GameEngine.Graphics/Buffer.cs +++ b/src/DirectX12GameEngine.Graphics/Buffers/Buffer.cs @@ -1,10 +1,10 @@ using System; using System.Runtime.CompilerServices; using DirectX12GameEngine.Core; -using DirectX12GameEngine.Graphics.Primitives.Abstract; +using DirectX12GameEngine.Graphics.Buffers.Abstract; using SharpDX.Direct3D12; -namespace DirectX12GameEngine.Graphics +namespace DirectX12GameEngine.Graphics.Buffers { public partial class Buffer : GraphicsResource { @@ -84,7 +84,7 @@ namespace DirectX12GameEngine.Graphics } } - public Buffer ToReadback() + public Buffers.Buffer ToReadback() { BufferDescription description = Description; description.HeapType = GraphicsHeapType.Readback; @@ -93,12 +93,12 @@ namespace DirectX12GameEngine.Graphics return New(GraphicsDevice, description); } - public static Buffer New(GraphicsDevice device, BufferDescription description) + public static Buffers.Buffer New(GraphicsDevice device, BufferDescription description) { - return new Buffer(device).InitializeFrom(description); + return new Buffers.Buffer(device).InitializeFrom(description); } - public static Buffer New(GraphicsDevice device, int size, BufferFlags bufferFlags, GraphicsHeapType heapType = GraphicsHeapType.Default) + public static Buffers.Buffer New(GraphicsDevice device, int size, BufferFlags bufferFlags, GraphicsHeapType heapType = GraphicsHeapType.Default) { return New(device, new BufferDescription(size, bufferFlags, heapType)); } @@ -126,7 +126,7 @@ namespace DirectX12GameEngine.Graphics return buffer; } - protected internal Buffer InitializeFrom(BufferDescription description) + protected internal Buffers.Buffer InitializeFrom(BufferDescription description) { ResourceStates resourceStates = ResourceStates.Common; @@ -215,7 +215,7 @@ namespace DirectX12GameEngine.Graphics } } - public class Buffer : Buffer where T : unmanaged + public class Buffer : Buffers.Buffer where T : unmanaged { protected internal Buffer(GraphicsDevice device, int size, BufferFlags bufferFlags, GraphicsHeapType heapType = GraphicsHeapType.Default) : base(device) { diff --git a/src/DirectX12GameEngine.Graphics/CommandList.cs b/src/DirectX12GameEngine.Graphics/CommandList.cs index 699ea89b..341aa967 100644 --- a/src/DirectX12GameEngine.Graphics/CommandList.cs +++ b/src/DirectX12GameEngine.Graphics/CommandList.cs @@ -1,5 +1,5 @@ using System; -using DirectX12GameEngine.Graphics.Primitives.Abstract; +using DirectX12GameEngine.Graphics.Buffers.Abstract; using SharpDX.Direct3D12; namespace DirectX12GameEngine.Graphics From ffcb53c46075277dc452565b1172acf2f9f31671 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 02:34:42 +0200 Subject: [PATCH 13/25] Removed unnecessary vertex buffer --- .../Buffers/Buffer.Vertex.cs | 42 ------------------- 1 file changed, 42 deletions(-) delete mode 100644 src/DirectX12GameEngine.Graphics/Buffers/Buffer.Vertex.cs diff --git a/src/DirectX12GameEngine.Graphics/Buffers/Buffer.Vertex.cs b/src/DirectX12GameEngine.Graphics/Buffers/Buffer.Vertex.cs deleted file mode 100644 index b78b5338..00000000 --- a/src/DirectX12GameEngine.Graphics/Buffers/Buffer.Vertex.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System; -using System.Runtime.CompilerServices; -using SharpDX.Direct3D12; - -namespace DirectX12GameEngine.Graphics.Buffers -{ - public partial class Buffer - { - public static class Vertex - { - public static unsafe Buffers.Buffer New(GraphicsDevice device, int size, GraphicsHeapType heapType = GraphicsHeapType.Default) - { - return Buffers.Buffer.New(device, size, BufferFlags.VertexBuffer, heapType); - } - - public static unsafe Buffer New(GraphicsDevice device, in T data, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged - { - return Buffers.Buffer.New(device, data, BufferFlags.VertexBuffer, heapType); - } - - public static unsafe Buffer New(GraphicsDevice device, Span data, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged - { - return Buffers.Buffer.New(device, data, BufferFlags.VertexBuffer, heapType); - } - - public static VertexBufferView CreateVertexBufferView(Buffers.Buffer vertexBuffer, int size, int stride) - { - return new VertexBufferView - { - BufferLocation = vertexBuffer.NativeResource.GPUVirtualAddress, - StrideInBytes = stride, - SizeInBytes = size - }; - } - - public static unsafe VertexBufferView CreateVertexBufferView(Buffers.Buffer vertexBuffer, int size) where T : unmanaged - { - return CreateVertexBufferView(vertexBuffer, size, Unsafe.SizeOf()); - } - } - } -} From 3f866f192858eaf938307e9f9d27696eb52aece6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 02:36:14 +0200 Subject: [PATCH 14/25] Minor code refactoring --- src/DirectX12GameEngine.Core/{ => Helpers}/MemoryHelper.cs | 2 +- src/DirectX12GameEngine.Graphics/Buffers/Buffer.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename src/DirectX12GameEngine.Core/{ => Helpers}/MemoryHelper.cs (97%) diff --git a/src/DirectX12GameEngine.Core/MemoryHelper.cs b/src/DirectX12GameEngine.Core/Helpers/MemoryHelper.cs similarity index 97% rename from src/DirectX12GameEngine.Core/MemoryHelper.cs rename to src/DirectX12GameEngine.Core/Helpers/MemoryHelper.cs index 908799e0..559eabee 100644 --- a/src/DirectX12GameEngine.Core/MemoryHelper.cs +++ b/src/DirectX12GameEngine.Core/Helpers/MemoryHelper.cs @@ -1,7 +1,7 @@ using System; using System.Runtime.CompilerServices; -namespace DirectX12GameEngine.Core +namespace DirectX12GameEngine.Core.Helpers { /// /// A with some helper methods to copy data between memory areas diff --git a/src/DirectX12GameEngine.Graphics/Buffers/Buffer.cs b/src/DirectX12GameEngine.Graphics/Buffers/Buffer.cs index aecaa8e8..db4052e0 100644 --- a/src/DirectX12GameEngine.Graphics/Buffers/Buffer.cs +++ b/src/DirectX12GameEngine.Graphics/Buffers/Buffer.cs @@ -1,6 +1,6 @@ using System; using System.Runtime.CompilerServices; -using DirectX12GameEngine.Core; +using DirectX12GameEngine.Core.Helpers; using DirectX12GameEngine.Graphics.Buffers.Abstract; using SharpDX.Direct3D12; From 3f0bad2d79fa5d727ff07124b9d36cf4ef33e9c9 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 02:47:45 +0200 Subject: [PATCH 15/25] Removed duplicate CommandListType enum --- src/DirectX12ComputeShaderSample/Program.cs | 3 +++ src/DirectX12GameEngine.Graphics/CommandListType.cs | 13 ------------- 2 files changed, 3 insertions(+), 13 deletions(-) delete mode 100644 src/DirectX12GameEngine.Graphics/CommandListType.cs diff --git a/src/DirectX12ComputeShaderSample/Program.cs b/src/DirectX12ComputeShaderSample/Program.cs index 67e0e101..28de6038 100644 --- a/src/DirectX12ComputeShaderSample/Program.cs +++ b/src/DirectX12ComputeShaderSample/Program.cs @@ -4,7 +4,10 @@ using DirectX12GameEngine.Shaders.Numerics; using System; using System.Linq; using DirectX12GameEngine.Graphics.Buffers; +using SharpDX.Direct3D12; using Buffer = DirectX12GameEngine.Graphics.Buffers.Buffer; +using CommandList = DirectX12GameEngine.Graphics.CommandList; +using PipelineState = DirectX12GameEngine.Graphics.PipelineState; namespace DirectX12ComputeShaderSample { diff --git a/src/DirectX12GameEngine.Graphics/CommandListType.cs b/src/DirectX12GameEngine.Graphics/CommandListType.cs deleted file mode 100644 index f8bbc3b7..00000000 --- a/src/DirectX12GameEngine.Graphics/CommandListType.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -namespace DirectX12GameEngine.Graphics -{ - public enum CommandListType - { - Direct, - Bundle, - Compute, - Copy, - VideoDecode, - VideoProcess - } -} From f3e66111a4d58b67c615dbddf21b267fa0398c04 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 02:54:56 +0200 Subject: [PATCH 16/25] Sample program switched to lambda expression --- src/DirectX12ComputeShaderSample/Program.cs | 75 +++++++++------------ 1 file changed, 33 insertions(+), 42 deletions(-) diff --git a/src/DirectX12ComputeShaderSample/Program.cs b/src/DirectX12ComputeShaderSample/Program.cs index 28de6038..00bfe9cb 100644 --- a/src/DirectX12ComputeShaderSample/Program.cs +++ b/src/DirectX12ComputeShaderSample/Program.cs @@ -11,57 +11,17 @@ using PipelineState = DirectX12GameEngine.Graphics.PipelineState; namespace DirectX12ComputeShaderSample { - public class MyComputeShader - { - [ConstantBufferResource] public uint Width; - - [ShaderResource] public RWBufferResource Data; - - [ShaderMethod] - [Shader("compute")] - [NumThreads(5, 5, 1)] - public void CSMain([SystemDispatchThreadIdSemantic] UInt3 id) - { - Data[id.X + id.Y * Width] *= 2; - } - } - public class Program { private static void Main() { - // Generate computer shader - - MyComputeShader myComputeShader = new MyComputeShader(); - ShaderGenerator shaderGenerator = new ShaderGenerator(myComputeShader); - ShaderGenerationResult result = shaderGenerator.GenerateShader(); - - byte[] shaderBytecode = ShaderCompiler.CompileShader(result.ShaderSource, SharpDX.D3DCompiler.ShaderVersion.ComputeShader, result.ComputeShader); - - // Create graphics device and pipeline state - + // Create the graphics device using GraphicsDevice device = new GraphicsDevice(true); - SharpDX.Direct3D12.RootParameter[] rootParameters = new SharpDX.Direct3D12.RootParameter[] - { - new SharpDX.Direct3D12.RootParameter(SharpDX.Direct3D12.ShaderVisibility.All, - new SharpDX.Direct3D12.RootConstants(0, 0, 1)), - new SharpDX.Direct3D12.RootParameter(SharpDX.Direct3D12.ShaderVisibility.All, - new SharpDX.Direct3D12.DescriptorRange(SharpDX.Direct3D12.DescriptorRangeType.UnorderedAccessView, 1, 0)) - }; - - var rootSignatureDescription = new SharpDX.Direct3D12.RootSignatureDescription(SharpDX.Direct3D12.RootSignatureFlags.None, rootParameters); - var rootSignature = device.CreateRootSignature(rootSignatureDescription); - - PipelineState pipelineState = new PipelineState(device, rootSignature, shaderBytecode); - - // Create graphics buffer - + // Create the graphics buffer int width = 10; int height = 10; - float[] array = new float[width * height]; - for (int i = 0; i < array.Length; i++) { array[i] = i + 1; @@ -69,6 +29,37 @@ namespace DirectX12ComputeShaderSample using Buffer gpuBuffer = Buffer.UnorderedAccess.New(device, array.AsSpan()); + // Variables for closure + var data = new RWBufferResource(); + uint Width = (uint)width; + + // Shader body + Action action = id => + { + data[id.X + id.Y * Width] *= 2; + }; + + // Generate computer shader + ShaderGenerator shaderGenerator = new ShaderGenerator(action); + ShaderGenerationResult result = shaderGenerator.GenerateShaderForLambda(); + + byte[] shaderBytecode = ShaderCompiler.CompileShader(result.ShaderSource, SharpDX.D3DCompiler.ShaderVersion.ComputeShader, result.ComputeShader); + + // Create the pipeline state + + RootParameter[] rootParameters = + { + new RootParameter(ShaderVisibility.All, new RootConstants(0, 0, 1)), + new RootParameter(ShaderVisibility.All, new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, 0)) + }; + + var rootSignatureDescription = new RootSignatureDescription(RootSignatureFlags.None, rootParameters); + var rootSignature = device.CreateRootSignature(rootSignatureDescription); + + PipelineState pipelineState = new PipelineState(device, rootSignature, shaderBytecode); + + + // Execute computer shader using (CommandList commandList = new CommandList(device, CommandListType.Compute)) From 839b8765e4871a6767b085a58e9c7fec2558e276 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 02:57:35 +0200 Subject: [PATCH 17/25] Switched sample constant parameter to buffer --- src/DirectX12ComputeShaderSample/Program.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/DirectX12ComputeShaderSample/Program.cs b/src/DirectX12ComputeShaderSample/Program.cs index 00bfe9cb..e14c1d8e 100644 --- a/src/DirectX12ComputeShaderSample/Program.cs +++ b/src/DirectX12ComputeShaderSample/Program.cs @@ -28,10 +28,11 @@ namespace DirectX12ComputeShaderSample } using Buffer gpuBuffer = Buffer.UnorderedAccess.New(device, array.AsSpan()); + using Buffer widthBuffer = Buffer.Constant.New(device, (uint)width); // Variables for closure - var data = new RWBufferResource(); uint Width = (uint)width; + var data = new RWBufferResource(); // Shader body Action action = id => @@ -49,7 +50,7 @@ namespace DirectX12ComputeShaderSample RootParameter[] rootParameters = { - new RootParameter(ShaderVisibility.All, new RootConstants(0, 0, 1)), + new RootParameter(ShaderVisibility.All, new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, 0)), new RootParameter(ShaderVisibility.All, new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, 0)) }; @@ -66,7 +67,7 @@ namespace DirectX12ComputeShaderSample { commandList.SetPipelineState(pipelineState); - commandList.SetComputeRoot32BitConstant(0, width, 0); + commandList.SetComputeRootDescriptorTable(0, widthBuffer); commandList.SetComputeRootDescriptorTable(1, gpuBuffer); commandList.Dispatch(2, 2, 1); From a5249a05619bc1866b3569037bd29d92e02f9010 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 03:16:12 +0200 Subject: [PATCH 18/25] Initial setup for the RWBufferResource class --- src/DirectX12ComputeShaderSample/Program.cs | 2 +- .../DirectX12GameEngine.Shaders.csproj | 1 + .../ShaderCompiler.cs | 5 ----- .../ShaderResource.cs | 16 +++++++++++++++- 4 files changed, 17 insertions(+), 7 deletions(-) diff --git a/src/DirectX12ComputeShaderSample/Program.cs b/src/DirectX12ComputeShaderSample/Program.cs index e14c1d8e..b0e0d92b 100644 --- a/src/DirectX12ComputeShaderSample/Program.cs +++ b/src/DirectX12ComputeShaderSample/Program.cs @@ -32,7 +32,7 @@ namespace DirectX12ComputeShaderSample // Variables for closure uint Width = (uint)width; - var data = new RWBufferResource(); + var data = gpuBuffer.GetGpuResource(); // Shader body Action action = id => diff --git a/src/DirectX12GameEngine.Shaders/DirectX12GameEngine.Shaders.csproj b/src/DirectX12GameEngine.Shaders/DirectX12GameEngine.Shaders.csproj index 398b8a35..581e66ea 100644 --- a/src/DirectX12GameEngine.Shaders/DirectX12GameEngine.Shaders.csproj +++ b/src/DirectX12GameEngine.Shaders/DirectX12GameEngine.Shaders.csproj @@ -18,6 +18,7 @@ + diff --git a/src/DirectX12GameEngine.Shaders/ShaderCompiler.cs b/src/DirectX12GameEngine.Shaders/ShaderCompiler.cs index fabf5f62..c5a4dedb 100644 --- a/src/DirectX12GameEngine.Shaders/ShaderCompiler.cs +++ b/src/DirectX12GameEngine.Shaders/ShaderCompiler.cs @@ -42,11 +42,6 @@ namespace DirectX12GameEngine.Shaders } } - public static byte[] CompileShaderLegacy(string shaderSource, ShaderVersion? version = null, string? entryPoint = null) - { - return ShaderBytecode.Compile(shaderSource, entryPoint ?? GetDefaultEntryPoint(version), $"{GetShaderProfile(version)}_5_1", ShaderFlags.PackMatrixRowMajor); - } - public static unsafe byte[] GetBytesFromBlob(IDxcBlob blob) { byte* pMem = (byte*)blob.GetBufferPointer(); diff --git a/src/DirectX12GameEngine.Shaders/ShaderResource.cs b/src/DirectX12GameEngine.Shaders/ShaderResource.cs index 6619bfc5..c1be3cde 100644 --- a/src/DirectX12GameEngine.Shaders/ShaderResource.cs +++ b/src/DirectX12GameEngine.Shaders/ShaderResource.cs @@ -1,5 +1,7 @@ using System; using System.Numerics; +using DirectX12GameEngine.Graphics.Buffers; +using Buffer = System.Buffer; namespace DirectX12GameEngine.Shaders { @@ -40,11 +42,23 @@ namespace DirectX12GameEngine.Shaders } [UnorderedAccessViewResource] - public class RWBufferResource : ShaderResource + public sealed class RWBufferResource : ShaderResource where T : unmanaged { + internal RWBufferResource(Buffer buffer) => Buffer = buffer; + + public Buffer Buffer { get; } + public T this[uint index] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } } + public static class RWBufferResourceExtensions + { + public static RWBufferResource GetGpuResource(this Buffer buffer) where T : unmanaged + { + return new RWBufferResource(buffer); + } + } + [UnorderedAccessViewResource] public class RWTexture2DResource : ShaderResource where T : unmanaged { From 9c2ef49e09f35bc8f53682bb82a0dc3bbac5980e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 10:53:10 +0200 Subject: [PATCH 19/25] Removed unnecessary code --- .../ShaderGenerationResult.cs | 41 +--------- .../ShaderGenerator.cs | 74 +------------------ 2 files changed, 4 insertions(+), 111 deletions(-) diff --git a/src/DirectX12GameEngine.Shaders/ShaderGenerationResult.cs b/src/DirectX12GameEngine.Shaders/ShaderGenerationResult.cs index 0eeccecb..84cb358a 100644 --- a/src/DirectX12GameEngine.Shaders/ShaderGenerationResult.cs +++ b/src/DirectX12GameEngine.Shaders/ShaderGenerationResult.cs @@ -5,49 +5,14 @@ namespace DirectX12GameEngine.Shaders { public class ShaderGenerationResult { - public ShaderGenerationResult(string shaderSource) + public ShaderGenerationResult(string shaderSource, string computeShader) { ShaderSource = shaderSource; + ComputeShader = computeShader; } public string ShaderSource { get; } - public string? ComputeShader { get; set; } - - public string? VertexShader { get; set; } - - public string? PixelShader { get; set; } - - public string? HullShader { get; set; } - - public string? DomainShader { get; set; } - - public string? GeometryShader { get; set; } - - public string? RayGenerationShader { get; set; } - - public string? IntersectionShader { get; set; } - - public string? AnyHitShader { get; set; } - - public string? ClosestHitShader { get; set; } - - public string? MissShader { get; set; } - - public string? CallableShader { get; set; } - - internal void SetShader(string shaderName, string methodName) - { - foreach (PropertyInfo propertyInfo in GetType().GetProperties()) - { - if (shaderName == propertyInfo.Name.Replace("Shader", "").ToLower()) - { - propertyInfo.SetValue(this, methodName); - return; - } - } - - throw new NotSupportedException("Attribute 'Shader' must have one of these values: compute, vertex, pixel, hull, domain, geometry, raygeneration, intersection, anyhit, closesthit, miss, callable."); - } + public string ComputeShader { get; set; } } } diff --git a/src/DirectX12GameEngine.Shaders/ShaderGenerator.cs b/src/DirectX12GameEngine.Shaders/ShaderGenerator.cs index c94f3599..69d8561a 100644 --- a/src/DirectX12GameEngine.Shaders/ShaderGenerator.cs +++ b/src/DirectX12GameEngine.Shaders/ShaderGenerator.cs @@ -92,64 +92,6 @@ namespace DirectX12GameEngine.Shaders CollectStructure(type, null); } - public ShaderGenerationResult GenerateShader() - { - if (result != null) return result; - - Type shaderType = shader.GetType(); - - var memberInfos = shaderType.GetMembersInTypeHierarchyInOrder(bindingAttr).Where(m => m.IsDefined(typeof(ShaderResourceAttribute))); - - // Collecting stage - - foreach (MemberInfo memberInfo in memberInfos) - { - Type? memberType = memberInfo.GetMemberType(shader); - - if (memberType != null) - { - CollectStructure(memberType, memberInfo.GetMemberValue(shader)); - } - - ShaderResourceAttribute? resourceType = memberInfo.GetResourceAttribute(memberType); - - if (resourceType is ShaderMethodAttribute && memberInfo is MethodInfo methodInfo) - { - CollectTopLevelMethod(methodInfo); - } - } - - // Writing stage - - foreach (ShaderTypeDefinition type in collectedTypes) - { - WriteStructure(type.Type, type.Instance); - } - - foreach (MemberInfo memberInfo in memberInfos) - { - Type? memberType = memberInfo.GetMemberType(shader); - ShaderResourceAttribute? resourceType = memberInfo.GetResourceAttribute(memberType); - - if (resourceType is ShaderMethodAttribute && memberInfo is MethodInfo methodInfo) - { - WriteTopLevelMethod(methodInfo); - } - else if (memberType != null && resourceType != null) - { - WriteResource(memberInfo, memberType, resourceType); - } - } - - stringWriter.GetStringBuilder().TrimEnd(); - writer.WriteLine(); - - result = new ShaderGenerationResult(stringWriter.ToString()); - GetEntryPoints(result, shaderType, bindingAttr); - - return result; - } - public ShaderGenerationResult GenerateShaderForLambda() { if (result != null) return result; @@ -194,21 +136,7 @@ namespace DirectX12GameEngine.Shaders stringWriter.GetStringBuilder().TrimEnd(); writer.WriteLine(); - result = new ShaderGenerationResult(stringWriter.ToString()); - //GetEntryPoints(result, shaderType, bindingAttr); - - result.SetShader("compute", "Foo" /* action.Method.Name */); - - return result; - } - - public static ShaderGenerationResult GetEntryPoints(ShaderGenerationResult result, Type shaderType, BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance) - { - foreach (MethodInfo shaderMethodInfo in shaderType.GetMethods(bindingAttr).Where(m => m.IsDefined(typeof(ShaderAttribute)))) - { - ShaderAttribute shaderAttribute = shaderMethodInfo.GetCustomAttribute(); - result.SetShader(shaderAttribute.Name, shaderMethodInfo.Name); - } + result = new ShaderGenerationResult(stringWriter.ToString(), "Foo"); /* action.Method.Name */ return result; } From f87105b23cf57e55014aa9dd1034b2bb157421ad Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 12:05:14 +0200 Subject: [PATCH 20/25] Removed unnecessary code --- src/DirectX12GameEngine.Shaders/ShaderBase.cs | 64 ------------------- .../ShaderCompiler.cs | 24 +------ 2 files changed, 1 insertion(+), 87 deletions(-) delete mode 100644 src/DirectX12GameEngine.Shaders/ShaderBase.cs diff --git a/src/DirectX12GameEngine.Shaders/ShaderBase.cs b/src/DirectX12GameEngine.Shaders/ShaderBase.cs deleted file mode 100644 index 05c6cf60..00000000 --- a/src/DirectX12GameEngine.Shaders/ShaderBase.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System.Numerics; - -namespace DirectX12GameEngine.Shaders -{ - public abstract class ShaderBase - { - [ShaderMethod] - [Shader("vertex")] - public virtual VSOutput VSMain(VSInput input) - { - return default; - } - - [ShaderMethod] - [Shader("pixel")] - public virtual PSOutput PSMain(PSInput input) - { - return default; - } - } - - public struct VSInput - { - [ShaderResource] [PositionSemantic] public Vector3 Position; - [ShaderResource] [NormalSemantic] public Vector3 Normal; - [ShaderResource] [TangentSemantic] public Vector4 Tangent; - [ShaderResource] [TextureCoordinateSemantic] public Vector2 TexCoord; - - [ShaderResource] [SystemInstanceIdSemantic] public uint InstanceId; - } - - public struct VSOutput - { - [ShaderResource] [PositionSemantic] public Vector4 PositionWS; - [ShaderResource] [NormalSemantic(0)] public Vector3 Normal; - [ShaderResource] [NormalSemantic(1)] public Vector3 NormalWS; - [ShaderResource] [TangentSemantic] public Vector4 Tangent; - [ShaderResource] [TextureCoordinateSemantic] public Vector2 TexCoord; - - [ShaderResource] [SystemPositionSemantic] public Vector4 ShadingPosition; - [ShaderResource] [SystemInstanceIdSemantic] public uint InstanceId; - [ShaderResource] [SystemRenderTargetArrayIndexSemantic] public uint TargetId; - } - - public struct PSInput - { - [ShaderResource] [PositionSemantic] public Vector4 PositionWS; - [ShaderResource] [NormalSemantic(0)] public Vector3 Normal; - [ShaderResource] [NormalSemantic(1)] public Vector3 NormalWS; - [ShaderResource] [TangentSemantic] public Vector4 Tangent; - [ShaderResource] [TextureCoordinateSemantic] public Vector2 TexCoord; - - [ShaderResource] [SystemPositionSemantic] public Vector4 ShadingPosition; - [ShaderResource] [SystemInstanceIdSemantic] public uint InstanceId; - [ShaderResource] [SystemRenderTargetArrayIndexSemantic] public uint TargetId; - - [ShaderResource] [SystemIsFrontFaceSemantic] public bool IsFrontFace; - } - - public struct PSOutput - { - [ShaderResource] [SystemTargetSemantic] public Vector4 ColorTarget; - } -} diff --git a/src/DirectX12GameEngine.Shaders/ShaderCompiler.cs b/src/DirectX12GameEngine.Shaders/ShaderCompiler.cs index c5a4dedb..ffe9aba0 100644 --- a/src/DirectX12GameEngine.Shaders/ShaderCompiler.cs +++ b/src/DirectX12GameEngine.Shaders/ShaderCompiler.cs @@ -26,7 +26,7 @@ namespace DirectX12GameEngine.Shaders const uint CP_UTF16 = 1200; IDxcBlobEncoding sourceBlob = library.CreateBlobWithEncodingOnHeapCopy(shaderSource, (uint)(shaderSource.Length * 2), CP_UTF16); - IDxcOperationResult result = compiler.Compile(sourceBlob, filePath, entryPoint ?? GetDefaultEntryPoint(version), $"{GetShaderProfile(version)}_6_1", new[] { "-Zpr" }, 1, null, 0, library.CreateIncludeHandler()); + IDxcOperationResult result = compiler.Compile(sourceBlob, filePath, entryPoint ?? "CSMain", "cs_6_1", new[] { "-Zpr" }, 1, null, 0, library.CreateIncludeHandler()); if (result.GetStatus() == 0) { @@ -64,27 +64,5 @@ namespace DirectX12GameEngine.Shaders blob = library.GetBlobAstUf16(blob); return new string(blob.GetBufferPointer(), 0, (int)(blob.GetBufferSize() / 2)); } - - private static string GetDefaultEntryPoint(ShaderVersion? version) => version switch - { - ShaderVersion.ComputeShader => "CSMain", - ShaderVersion.VertexShader => "VSMain", - ShaderVersion.PixelShader => "PSMain", - ShaderVersion.HullShader => "HSMain", - ShaderVersion.DomainShader => "DSMain", - ShaderVersion.GeometryShader => "GSMain", - _ => "" - }; - - private static string GetShaderProfile(ShaderVersion? version) => version switch - { - ShaderVersion.ComputeShader => "cs", - ShaderVersion.VertexShader => "vs", - ShaderVersion.PixelShader => "ps", - ShaderVersion.HullShader => "hs", - ShaderVersion.DomainShader => "ds", - ShaderVersion.GeometryShader => "gs", - _ => "lib" - }; } } From c3365e52530b57eb90e9a574903280b6a96d7d34 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 13:05:56 +0200 Subject: [PATCH 21/25] Early support for HLSL static variables --- src/DirectX12ComputeShaderSample/Program.cs | 9 +++------ src/DirectX12GameEngine.Shaders/ShaderGenerator.cs | 10 +++++++++- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/DirectX12ComputeShaderSample/Program.cs b/src/DirectX12ComputeShaderSample/Program.cs index b0e0d92b..8835bd21 100644 --- a/src/DirectX12ComputeShaderSample/Program.cs +++ b/src/DirectX12ComputeShaderSample/Program.cs @@ -28,16 +28,15 @@ namespace DirectX12ComputeShaderSample } using Buffer gpuBuffer = Buffer.UnorderedAccess.New(device, array.AsSpan()); - using Buffer widthBuffer = Buffer.Constant.New(device, (uint)width); // Variables for closure - uint Width = (uint)width; + uint size = (uint)width; var data = gpuBuffer.GetGpuResource(); // Shader body Action action = id => { - data[id.X + id.Y * Width] *= 2; + data[id.X + id.Y * size] *= 2; }; // Generate computer shader @@ -50,7 +49,6 @@ namespace DirectX12ComputeShaderSample RootParameter[] rootParameters = { - new RootParameter(ShaderVisibility.All, new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, 0)), new RootParameter(ShaderVisibility.All, new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, 0)) }; @@ -67,8 +65,7 @@ namespace DirectX12ComputeShaderSample { commandList.SetPipelineState(pipelineState); - commandList.SetComputeRootDescriptorTable(0, widthBuffer); - commandList.SetComputeRootDescriptorTable(1, gpuBuffer); + commandList.SetComputeRootDescriptorTable(0, gpuBuffer); commandList.Dispatch(2, 2, 1); commandList.Flush(true); diff --git a/src/DirectX12GameEngine.Shaders/ShaderGenerator.cs b/src/DirectX12GameEngine.Shaders/ShaderGenerator.cs index 69d8561a..64bc09c9 100644 --- a/src/DirectX12GameEngine.Shaders/ShaderGenerator.cs +++ b/src/DirectX12GameEngine.Shaders/ShaderGenerator.cs @@ -125,7 +125,8 @@ namespace DirectX12GameEngine.Shaders if (memberType.IsGenericType && memberType.GetGenericTypeDefinition() == typeof(RWBufferResource<>)) WriteUnorderedAccessView(fieldInfo, memberType, bindingTracker.UnorderedAccessView++); - else WriteConstantBuffer(fieldInfo, memberType, bindingTracker.ConstantBuffer++); + //else WriteConstantBuffer(fieldInfo, memberType, bindingTracker.ConstantBuffer++); + else WriteStaticVariable(fieldInfo, memberType, fieldInfo.GetValue(shaderInstance)); } // Write the actual shader body @@ -333,6 +334,13 @@ namespace DirectX12GameEngine.Shaders } } + private void WriteStaticVariable(MemberInfo memberInfo, Type memberType, object value) + { + writer.Write($"static {HlslKnownTypes.GetMappedName(memberType)} {memberInfo.Name}"); + writer.Write($" = {value};"); + writer.WriteLine(); + } + private void WriteConstantBuffer(MemberInfo memberInfo, Type memberType, int binding) { int arrayCount = memberType.IsArray ? 2 : 0; From 43d961f7c39690bf55444ff616c71960582d8328 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 13:08:15 +0200 Subject: [PATCH 22/25] Removed unnecessary NuGet packages --- .../DirectX12GameEngine.Graphics.csproj | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/DirectX12GameEngine.Graphics/DirectX12GameEngine.Graphics.csproj b/src/DirectX12GameEngine.Graphics/DirectX12GameEngine.Graphics.csproj index 87aeaf38..e2b2653d 100644 --- a/src/DirectX12GameEngine.Graphics/DirectX12GameEngine.Graphics.csproj +++ b/src/DirectX12GameEngine.Graphics/DirectX12GameEngine.Graphics.csproj @@ -8,8 +8,6 @@ - - From b92356d02512a99efcc2459b668ea082fa6224a9 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 13:32:55 +0200 Subject: [PATCH 23/25] Added dynamic root parameters and buffers parsing --- .../ShaderGenerator.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/DirectX12GameEngine.Shaders/ShaderGenerator.cs b/src/DirectX12GameEngine.Shaders/ShaderGenerator.cs index 64bc09c9..0aa9f330 100644 --- a/src/DirectX12GameEngine.Shaders/ShaderGenerator.cs +++ b/src/DirectX12GameEngine.Shaders/ShaderGenerator.cs @@ -7,12 +7,14 @@ using System.Numerics; using System.Reflection; using System.Reflection.Metadata; using System.Text.RegularExpressions; +using DirectX12GameEngine.Graphics.Buffers.Abstract; using DirectX12GameEngine.Shaders.Numerics; using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.CSharp; using ICSharpCode.Decompiler.Metadata; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; +using SharpDX.Direct3D12; using Vector2 = System.Numerics.Vector2; using Vector4 = System.Numerics.Vector4; @@ -92,6 +94,10 @@ namespace DirectX12GameEngine.Shaders CollectStructure(type, null); } + public RootParameter[] RootParameters { get; private set; } + + public IReadOnlyList ReadWriteBuffers { get; private set; } + public ShaderGenerationResult GenerateShaderForLambda() { if (result != null) return result; @@ -119,15 +125,26 @@ namespace DirectX12GameEngine.Shaders } // Write the fields, assuming that all buffers are unordered access views, and the other fields are constant buffers + var parameters = new List(); + var rwbuffers = new List(); foreach (FieldInfo fieldInfo in fields) { Type? memberType = fieldInfo.FieldType; if (memberType.IsGenericType && memberType.GetGenericTypeDefinition() == typeof(RWBufferResource<>)) + { + var range = new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, bindingTracker.UnorderedAccessView); + parameters.Add(range); + var buffer = fieldInfo.GetValue(shaderInstance); + var resource = (GraphicsResource)memberType.GetProperty(nameof(RWBufferResource.Buffer)).GetValue(buffer); + rwbuffers.Add(resource); WriteUnorderedAccessView(fieldInfo, memberType, bindingTracker.UnorderedAccessView++); + } //else WriteConstantBuffer(fieldInfo, memberType, bindingTracker.ConstantBuffer++); else WriteStaticVariable(fieldInfo, memberType, fieldInfo.GetValue(shaderInstance)); } + RootParameters = parameters.Select(range => new RootParameter(ShaderVisibility.All, range)).ToArray(); + ReadWriteBuffers = rwbuffers; // Write the actual shader body writer.WriteLine("[Shader(\"compute\")]"); From 518a02d17dcf8cb6994b34b67117aade043fda76 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 13:35:22 +0200 Subject: [PATCH 24/25] Added initial version of GPU extensions --- src/DirectX12ComputeShaderSample/Gpu.cs | 50 +++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/DirectX12ComputeShaderSample/Gpu.cs diff --git a/src/DirectX12ComputeShaderSample/Gpu.cs b/src/DirectX12ComputeShaderSample/Gpu.cs new file mode 100644 index 00000000..7e122ace --- /dev/null +++ b/src/DirectX12ComputeShaderSample/Gpu.cs @@ -0,0 +1,50 @@ +using System; +using System.Linq; +using DirectX12GameEngine.Graphics; +using DirectX12GameEngine.Shaders; +using DirectX12GameEngine.Shaders.Numerics; +using SharpDX.D3DCompiler; +using SharpDX.Direct3D12; +using CommandList = DirectX12GameEngine.Graphics.CommandList; +using PipelineState = DirectX12GameEngine.Graphics.PipelineState; + +namespace DirectX12ComputeShaderSample +{ + public static class Gpu + { + private static GraphicsDevice _Default; + + public static GraphicsDevice Default => _Default ??= new GraphicsDevice(true); + } + + public static class GraphicsDeviceExtensions + { + public static void For(this GraphicsDevice device, int n, Action shader) + { + // Generate the compute shadr + ShaderGenerator shaderGenerator = new ShaderGenerator(shader); + ShaderGenerationResult result = shaderGenerator.GenerateShaderForLambda(); + + byte[] shaderBytecode = ShaderCompiler.CompileShader(result.ShaderSource, ShaderVersion.ComputeShader, result.ComputeShader); + + // Create the root signature for the pipeline and the pipeline state + RootSignatureDescription rootSignatureDescription = new RootSignatureDescription(RootSignatureFlags.None, shaderGenerator.RootParameters); + RootSignature rootSignature = device.CreateRootSignature(rootSignatureDescription); + PipelineState pipelineState = new PipelineState(device, rootSignature, shaderBytecode); + + // Create the commands list + using CommandList commandList = new CommandList(device, CommandListType.Compute); + commandList.SetPipelineState(pipelineState); + + // Load the captured buffers + foreach (var item in shaderGenerator.ReadWriteBuffers.Select((r, i) => (Resource: r, Index: i))) + { + commandList.SetComputeRootDescriptorTable(item.Index, item.Resource); + } + + // Dispatch and wait for completion + commandList.Dispatch(2, 2, 1); + commandList.Flush(true); + } + } +} From 37bfb7db4b47df89e8a165a7d0b3e654ead1c97f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 13:35:28 +0200 Subject: [PATCH 25/25] Updated code sample --- src/DirectX12ComputeShaderSample/Program.cs | 44 ++------------------- 1 file changed, 4 insertions(+), 40 deletions(-) diff --git a/src/DirectX12ComputeShaderSample/Program.cs b/src/DirectX12ComputeShaderSample/Program.cs index 8835bd21..33ffa741 100644 --- a/src/DirectX12ComputeShaderSample/Program.cs +++ b/src/DirectX12ComputeShaderSample/Program.cs @@ -1,13 +1,9 @@ -using DirectX12GameEngine.Graphics; -using DirectX12GameEngine.Shaders; +using DirectX12GameEngine.Shaders; using DirectX12GameEngine.Shaders.Numerics; using System; using System.Linq; using DirectX12GameEngine.Graphics.Buffers; -using SharpDX.Direct3D12; using Buffer = DirectX12GameEngine.Graphics.Buffers.Buffer; -using CommandList = DirectX12GameEngine.Graphics.CommandList; -using PipelineState = DirectX12GameEngine.Graphics.PipelineState; namespace DirectX12ComputeShaderSample { @@ -15,9 +11,6 @@ namespace DirectX12ComputeShaderSample { private static void Main() { - // Create the graphics device - using GraphicsDevice device = new GraphicsDevice(true); - // Create the graphics buffer int width = 10; int height = 10; @@ -27,7 +20,7 @@ namespace DirectX12ComputeShaderSample array[i] = i + 1; } - using Buffer gpuBuffer = Buffer.UnorderedAccess.New(device, array.AsSpan()); + using Buffer gpuBuffer = Buffer.UnorderedAccess.New(Gpu.Default, array.AsSpan()); // Variables for closure uint size = (uint)width; @@ -39,37 +32,8 @@ namespace DirectX12ComputeShaderSample data[id.X + id.Y * size] *= 2; }; - // Generate computer shader - ShaderGenerator shaderGenerator = new ShaderGenerator(action); - ShaderGenerationResult result = shaderGenerator.GenerateShaderForLambda(); - - byte[] shaderBytecode = ShaderCompiler.CompileShader(result.ShaderSource, SharpDX.D3DCompiler.ShaderVersion.ComputeShader, result.ComputeShader); - - // Create the pipeline state - - RootParameter[] rootParameters = - { - new RootParameter(ShaderVisibility.All, new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, 0)) - }; - - var rootSignatureDescription = new RootSignatureDescription(RootSignatureFlags.None, rootParameters); - var rootSignature = device.CreateRootSignature(rootSignatureDescription); - - PipelineState pipelineState = new PipelineState(device, rootSignature, shaderBytecode); - - - - // Execute computer shader - - using (CommandList commandList = new CommandList(device, CommandListType.Compute)) - { - commandList.SetPipelineState(pipelineState); - - commandList.SetComputeRootDescriptorTable(0, gpuBuffer); - - commandList.Dispatch(2, 2, 1); - commandList.Flush(true); - } + // Run the shader + Gpu.Default.For(100, action); // Print matrix