Updated D3D12Renderer for testing.

This commit is contained in:
2025-11-11 16:10:17 +09:00
parent 56f73e774b
commit fb003da26a
7 changed files with 107 additions and 87 deletions

View File

@@ -18,7 +18,8 @@ public readonly struct Handle<T>
public static Handle<T> Invalid => new(-1, -1); public static Handle<T> Invalid => new(-1, -1);
public bool IsValid => this != Invalid; public readonly bool IsValid => this != Invalid;
public readonly bool IsNotValid => this == Invalid;
public readonly override int GetHashCode() public readonly override int GetHashCode()
{ {
@@ -63,7 +64,8 @@ public readonly struct Identifier<T>
public static Identifier<T> Invalid => new(-1); public static Identifier<T> Invalid => new(-1);
public bool IsValid => this != Invalid; public readonly bool IsValid => this != Invalid;
public readonly bool IsNotValid => this == Invalid;
public readonly override int GetHashCode() public readonly override int GetHashCode()
{ {

View File

@@ -26,6 +26,7 @@ internal unsafe class D3D12GraphicsEngine : IGraphicsEngine
public IPipelineLibrary PipelineLibrary => _pipelineLibrary; public IPipelineLibrary PipelineLibrary => _pipelineLibrary;
public IResourceDatabase ResourceDatabase => _resourceDatabase; public IResourceDatabase ResourceDatabase => _resourceDatabase;
public IResourceAllocator ResourceAllocator => _resourceAllocator; public IResourceAllocator ResourceAllocator => _resourceAllocator;
public ICommandBuffer CopyCommandBuffer => _copyCommandBuffer;
public D3D12GraphicsEngine(IRenderSystem renderSystem) public D3D12GraphicsEngine(IRenderSystem renderSystem)
{ {

View File

@@ -3,6 +3,7 @@ using Ghost.Graphics.D3D12.Utilities;
using Ghost.Graphics.RHI; using Ghost.Graphics.RHI;
using Misaki.HighPerformance.Mathematics; using Misaki.HighPerformance.Mathematics;
using Ghost.Graphics.Core; using Ghost.Graphics.Core;
using Ghost.Graphics.RenderPasses;
namespace Ghost.Graphics.D3D12; namespace Ghost.Graphics.D3D12;
@@ -16,7 +17,7 @@ internal unsafe class D3D12Renderer : IRenderer
public ICommandBuffer commandBuffer; public ICommandBuffer commandBuffer;
public ulong fenceValue; public ulong fenceValue;
public FrameResource(IGraphicsEngine graphicsEngine) public FrameResource(D3D12GraphicsEngine graphicsEngine)
{ {
commandBuffer = graphicsEngine.CreateCommandBuffer(); commandBuffer = graphicsEngine.CreateCommandBuffer();
fenceValue = 0; fenceValue = 0;
@@ -28,33 +29,37 @@ internal unsafe class D3D12Renderer : IRenderer
} }
} }
private readonly ICommandQueue _commandQueue; private readonly D3D12GraphicsEngine _graphicsEngine;
private readonly D3D12CommandQueue _commandQueue;
private readonly FrameResource[] _frameResources; private readonly FrameResource[] _frameResources;
private uint _frameIndex; private uint _frameIndex;
private readonly IResourceAllocator _resourceAllocator; private readonly D3D12ResourceAllocator _resourceAllocator;
private readonly D3D12ResourceDatabase _resourceDatabase; private readonly D3D12ResourceDatabase _resourceDatabase;
private Handle<Texture> _customRenderTarget; // User-provided render target private Handle<Texture> _renderTarget;
private Handle<Texture> _offScreenRenderTarget; // Off-screen target for swap chain
private ISwapChain? _swapChain; private ISwapChain? _swapChain;
private readonly Lock _lock = new(); private readonly Lock _lock = new();
private uint2 _currentSize; private uint2 _currentSize;
private uint _pendingWidth; private uint2 _pendingSize;
private uint _pendingHeight;
private bool _resizeRequested; private bool _resizeRequested;
private bool _disposed; private bool _disposed;
// NOTE: Testing only.
private readonly MeshRenderPass _pass;
public uint2 Size => _currentSize; public uint2 Size => _currentSize;
// TODO: Add render passes support // TODO: Add render passes support
// private ImmutableArray<IRenderPass> _renderPasses; // private ImmutableArray<IRenderPass> _renderPasses;
public D3D12Renderer(IGraphicsEngine graphicsEngine, IResourceAllocator resourceAllocator, D3D12ResourceDatabase resourceDatabase) public D3D12Renderer(D3D12GraphicsEngine graphicsEngine, D3D12ResourceAllocator resourceAllocator, D3D12ResourceDatabase resourceDatabase)
{ {
_commandQueue = graphicsEngine.Device.GraphicsQueue; _graphicsEngine = graphicsEngine;
_commandQueue = (D3D12CommandQueue)graphicsEngine.Device.GraphicsQueue;
_resourceAllocator = resourceAllocator; _resourceAllocator = resourceAllocator;
_resourceDatabase = resourceDatabase; _resourceDatabase = resourceDatabase;
@@ -65,8 +70,11 @@ internal unsafe class D3D12Renderer : IRenderer
_frameResources[i] = new FrameResource(graphicsEngine); _frameResources[i] = new FrameResource(graphicsEngine);
} }
_customRenderTarget = Handle<Texture>.Invalid; _renderTarget = Handle<Texture>.Invalid;
_offScreenRenderTarget = Handle<Texture>.Invalid;
// NOTE: Testing only.
_pass = new();
} }
~D3D12Renderer() ~D3D12Renderer()
@@ -74,42 +82,46 @@ internal unsafe class D3D12Renderer : IRenderer
Dispose(); Dispose();
} }
private void CreateOffScreenRenderTarget(uint width, uint height)
{
var desc = RenderTargetDesc.Color(width, height, 1, TextureFormat.R8G8B8A8_UNorm);
_renderTarget = _resourceAllocator.CreateRenderTarget(in desc);
}
public void SetRenderTarget(Handle<Texture> renderTarget) public void SetRenderTarget(Handle<Texture> renderTarget)
{ {
_customRenderTarget = renderTarget;
_swapChain = null; _swapChain = null;
// Clean up off-screen target when switching to render target mode _resourceDatabase.ReleaseResource(_renderTarget.AsResource());
_resourceDatabase.ReleaseResource(_offScreenRenderTarget.AsResource()); _renderTarget = renderTarget;
_offScreenRenderTarget = Handle<Texture>.Invalid;
} }
public void SetSwapChain(ISwapChain? swapChain) public void SetSwapChain(ISwapChain? swapChain)
{ {
_swapChain = swapChain;
_customRenderTarget = Handle<Texture>.Invalid;
if (_swapChain != null) if (_swapChain != null)
{ {
CreateOrUpdateOffScreenRenderTarget(_swapChain.Width, _swapChain.Height); _resourceDatabase.ReleaseResource(_renderTarget.AsResource());
} }
else
if (swapChain != null)
{ {
_resourceDatabase.ReleaseResource(_offScreenRenderTarget.AsResource()); CreateOffScreenRenderTarget(swapChain.Width, swapChain.Height);
_offScreenRenderTarget = Handle<Texture>.Invalid;
} }
_swapChain = swapChain;
} }
public void RequestResize(uint width, uint height) public void RequestResize(uint2 newSize )
{ {
lock (_lock) lock (_lock)
{ {
if (_pendingWidth == width && _pendingHeight == height) if (math.all(_pendingSize == newSize))
{
return; return;
}
_resizeRequested = true; _resizeRequested = true;
_pendingWidth = width; _pendingSize = newSize;
_pendingHeight = height;
} }
} }
@@ -120,11 +132,10 @@ internal unsafe class D3D12Renderer : IRenderer
return; return;
} }
uint newWidth, newHeight; uint2 newSize;
lock (_lock) lock (_lock)
{ {
newWidth = _pendingWidth; newSize = _pendingSize;
newHeight = _pendingHeight;
_resizeRequested = false; _resizeRequested = false;
} }
@@ -132,13 +143,14 @@ internal unsafe class D3D12Renderer : IRenderer
WaitIdle(); WaitIdle();
// Resize swap chain if present // Resize swap chain if present
_swapChain?.Resize(newWidth, newHeight); _swapChain?.Resize(newSize.x, newSize.y);
_currentSize = new uint2(newWidth, newHeight); _currentSize = newSize;
// Update off-screen render target size // Update off-screen render target size
if (_swapChain != null) if (_swapChain != null)
{ {
CreateOrUpdateOffScreenRenderTarget(newWidth, newHeight); _resourceDatabase.ReleaseResource(_renderTarget.AsResource());
CreateOffScreenRenderTarget(newSize.x, newSize.y);
} }
} }
@@ -154,32 +166,32 @@ internal unsafe class D3D12Renderer : IRenderer
_commandQueue.WaitForValue(frame.fenceValue); _commandQueue.WaitForValue(frame.fenceValue);
} }
frame.commandBuffer.Begin(); if (_renderTarget.IsValid)
if (_customRenderTarget.IsValid)
{ {
// Render target mode: render directly to custom target frame.commandBuffer.Begin();
RenderScene(_customRenderTarget, frame.commandBuffer);
// NOTE: Temperary solution: render directly to the swap chain back buffer if available.
var rt = _swapChain?.GetCurrentBackBuffer() ?? _renderTarget;
RenderScene(rt, frame.commandBuffer);
// if (_swapChain != null)
// {
// var backBufferRT = _swapChain.GetCurrentBackBuffer();
// BlitToDestination(_renderTarget, backBufferRT, frame.commandBuffer);
// }
frame.commandBuffer.End();
_commandQueue.Submit(frame.commandBuffer);
_swapChain?.Present();
} }
else if (_swapChain != null && _offScreenRenderTarget.IsValid)
{
// Swap chain mode: render to off-screen, then blit to back buffer
var backBufferRT = _swapChain.GetCurrentBackBuffer();
// For testing, we render directly to the back buffer
RenderScene(backBufferRT, frame.commandBuffer);
//BlitToDestination(_offScreenRenderTarget, backBufferRT, frame.CommandBuffer);
}
frame.commandBuffer.End();
_commandQueue.Submit(frame.commandBuffer);
_swapChain?.Present();
frame.fenceValue = _commandQueue.Signal(_frameIndex); frame.fenceValue = _commandQueue.Signal(_frameIndex);
_frameIndex++; _frameIndex++;
} }
// TODO: A proper render graph integration.
private void RenderScene(Handle<Texture> target, ICommandBuffer cmd) private void RenderScene(Handle<Texture> target, ICommandBuffer cmd)
{ {
var clearColor = new Color128 { r = 1.0f, g = 0.0f, b = 1.0f, a = 1.0f }; var clearColor = new Color128 { r = 1.0f, g = 0.0f, b = 1.0f, a = 1.0f };
@@ -206,16 +218,19 @@ internal unsafe class D3D12Renderer : IRenderer
cmd.SetViewport(viewport); cmd.SetViewport(viewport);
cmd.SetScissorRect(scissor); cmd.SetScissorRect(scissor);
// TODO: Execute render passes // NOTE: Testing only.
// foreach (var pass in _renderPasses) var ctx = new RenderingContext(_graphicsEngine, cmd, _graphicsEngine.CopyCommandBuffer, null!);
// { if (_frameIndex == 0)
// pass.Execute(cmd); {
// } _pass.Initialize(ref ctx);
}
_pass.Execute(ref ctx);
cmd.EndRenderPass(); cmd.EndRenderPass();
} }
private void BlitToDestination(Handle<Texture> source, Handle<Texture> destination, ICommandBuffer cmd) private void BlitToSwapChain(Handle<Texture> source, Handle<Texture> destination, ICommandBuffer cmd)
{ {
// Handle swap chain back buffer transitions if needed // Handle swap chain back buffer transitions if needed
if (_swapChain != null) if (_swapChain != null)
@@ -231,7 +246,6 @@ internal unsafe class D3D12Renderer : IRenderer
// This is a placeholder - in D3D12, you would typically: // This is a placeholder - in D3D12, you would typically:
// 1. Set render target to the destination // 1. Set render target to the destination
// 2. Use a full-screen quad/triangle with a shader that samples from the source // 2. Use a full-screen quad/triangle with a shader that samples from the source
// 3. Apply post-processing effects (tone mapping, gamma correction, etc.)
// Handle swap chain back buffer transitions if needed // Handle swap chain back buffer transitions if needed
if (_swapChain != null) if (_swapChain != null)
@@ -241,17 +255,6 @@ internal unsafe class D3D12Renderer : IRenderer
} }
} }
private void CreateOrUpdateOffScreenRenderTarget(uint width, uint height)
{
if (_offScreenRenderTarget.IsValid)
{
_resourceAllocator.ReleaseResource(_offScreenRenderTarget.AsResource());
}
var desc = RenderTargetDesc.Color(width, height, 1, TextureFormat.R8G8B8A8_UNorm);
_offScreenRenderTarget = _resourceAllocator.CreateRenderTarget(in desc);
}
public void WaitIdle() public void WaitIdle()
{ {
// Wait for all frame resources to complete // Wait for all frame resources to complete
@@ -273,14 +276,21 @@ internal unsafe class D3D12Renderer : IRenderer
WaitIdle(); WaitIdle();
// NOTE: Testing only.
_pass.Cleanup(_resourceDatabase);
// If using a swap chain, release the off-screen render target.
// Otherwise, the render target is managed externally.
if (_swapChain != null)
{
_resourceDatabase.ReleaseResource(_renderTarget.AsResource());
}
foreach (ref var frame in _frameResources.AsSpan()) foreach (ref var frame in _frameResources.AsSpan())
{ {
frame.Dispose(); frame.Dispose();
} }
_resourceDatabase.ReleaseResource(_customRenderTarget.AsResource());
_resourceDatabase.ReleaseResource(_offScreenRenderTarget.AsResource());
_disposed = true; _disposed = true;
GC.SuppressFinalize(this); GC.SuppressFinalize(this);

View File

@@ -165,6 +165,12 @@ internal class D3D12ResourceDatabase : IResourceDatabase, IDisposable
return handle; return handle;
} }
public bool HasResource(Handle<GPUResource> handle)
{
ObjectDisposedException.ThrowIf(_disposed, this);
return _resources.Contain(handle.id, handle.generation);
}
public ref ResourceRecord GetResourceInfo(Handle<GPUResource> handle) public ref ResourceRecord GetResourceInfo(Handle<GPUResource> handle)
{ {
ObjectDisposedException.ThrowIf(_disposed, this); ObjectDisposedException.ThrowIf(_disposed, this);

View File

@@ -1,5 +1,6 @@
using Ghost.Core; using Ghost.Core;
using Ghost.Core.Utilities; using Ghost.Core.Utilities;
using Ghost.Graphics.Core;
using Ghost.Graphics.Contracts; using Ghost.Graphics.Contracts;
using Ghost.Graphics.D3D12.Utilities; using Ghost.Graphics.D3D12.Utilities;
using Ghost.Graphics.RHI; using Ghost.Graphics.RHI;
@@ -11,8 +12,6 @@ using TerraFX.Interop.Windows;
using static TerraFX.Aliases.DXGI_Alias; using static TerraFX.Aliases.DXGI_Alias;
using Ghost.Graphics.Core;
namespace Ghost.Graphics.D3D12; namespace Ghost.Graphics.D3D12;
/// <summary> /// <summary>
@@ -120,7 +119,7 @@ internal unsafe class D3D12SwapChain : ISwapChain
_swapChain.Get()->GetBuffer(i, backBuffer.IID(), backBuffer.PPV()); _swapChain.Get()->GetBuffer(i, backBuffer.IID(), backBuffer.PPV());
backBuffer.Get()->SetName($"SwapChain_BackBuffer_{i}"); backBuffer.Get()->SetName($"SwapChain_BackBuffer_{i}");
_backBuffers[i] = _resourceDatabase.ImportExternalResource(backBuffer, ResourceState.Present).AsTexture(); _backBuffers[i] = _resourceDatabase.ImportExternalResource(backBuffer.Move(), ResourceState.Present).AsTexture();
} }
} }
@@ -135,10 +134,7 @@ internal unsafe class D3D12SwapChain : ISwapChain
var presentFlags = 0u; var presentFlags = 0u;
var syncInterval = vsync ? 1u : 0u; var syncInterval = vsync ? 1u : 0u;
if (_swapChain.Get()->Present(syncInterval, presentFlags).FAILED) ThrowIfFailed(_swapChain.Get()->Present(syncInterval, presentFlags));
{
throw new InvalidOperationException("Failed to present swap chain.");
}
} }
public void Resize(uint width, uint height) public void Resize(uint width, uint height)

View File

@@ -39,9 +39,8 @@ public interface IRenderer : IDisposable
/// <summary> /// <summary>
/// Requests a resize operation /// Requests a resize operation
/// </summary> /// </summary>
/// <param name="width">New width</param> /// <param name="newSize">New size</param>
/// <param name="height">New height</param> public void RequestResize(uint2 newSize);
public void RequestResize(uint width, uint height);
/// <summary> /// <summary>
/// Waits for the GPU to complete all work /// Waits for the GPU to complete all work

View File

@@ -25,17 +25,23 @@ public interface IResourceDatabase
where T : unmanaged; where T : unmanaged;
*/ */
/// <summary>
/// Checks if a resource with the specified handle exists in the database.
/// </summary>
/// <param name="handle">The handle of the resource to check for existence.</param>
bool HasResource(Handle<GPUResource> handle);
/// <summary> /// <summary>
/// Retrieves the current state of the specified resource. /// Retrieves the current state of the specified resource.
/// </summary> /// </summary>
/// <param name="handle">The handle that uniquely identifies the resource whose state is to be retrieved. Must not be null.</param> /// <param name="handle">The handle that uniquely identifies the resource whose state is to be retrieved.</param>
/// <returns>A ResourceState value representing the current state of the resource associated with the specified handle.</returns> /// <returns>A ResourceState value representing the current state of the resource associated with the specified handle.</returns>
ResourceState GetResourceState(Handle<GPUResource> handle); ResourceState GetResourceState(Handle<GPUResource> handle);
/// <summary> /// <summary>
/// Sets the state of the specified resource handle to the given value. /// Sets the state of the specified resource handle to the given value.
/// </summary> /// </summary>
/// <param name="handle">The handle that identifies the resource whose state will be updated. Cannot be null.</param> /// <param name="handle">The handle that identifies the resource whose state will be updated.</param>
/// <param name="state">The new state to assign to the resource represented by <paramref name="handle"/>.</param> /// <param name="state">The new state to assign to the resource represented by <paramref name="handle"/>.</param>
void SetResourceState(Handle<GPUResource> handle, ResourceState state); void SetResourceState(Handle<GPUResource> handle, ResourceState state);
@@ -163,4 +169,4 @@ public interface IResourceDatabase
/// <param name="passKey">The unique identifier of the shader pass to retrieve.</param> /// <param name="passKey">The unique identifier of the shader pass to retrieve.</param>
/// <returns>The <see cref="ShaderPass"/> corresponding to the specified identifier, or null if no matching shader pass is found.</returns> /// <returns>The <see cref="ShaderPass"/> corresponding to the specified identifier, or null if no matching shader pass is found.</returns>
ShaderPass GetShaderPass(ShaderPassKey passKey); ShaderPass GetShaderPass(ShaderPassKey passKey);
} }