Refactor: variant-aware shader/material pipeline overhaul
Major architectural update to graphics/material/shader system: - Introduced strongly-typed key structs (Key64/Key128) for passes, variants, and pipelines; removed legacy key types. - Implemented robust hashing and key generation utilities for efficient variant and pipeline lookup/caching. - Shader compiler now compiles/caches all keyword variants using new key system; includes handled as lists. - Switched to push constant root signature for per-draw data; updated HLSL and C# codegen accordingly. - Refactored Material, Shader, and Pass data structures for cache efficiency and variant support. - Pipeline library and PSO management now use 128-bit keys and variant-specific caching. - Replaced WorldNode with SceneNode in editor/scene graph; introduced ComponentManager for archetype/query management. - Migrated math utilities to Misaki.HighPerformance.Mathematics; updated editor controls. - Updated all HLSL and codegen for new buffer/push constant layouts and macros. - Misc: project reference cleanup, D3D12 Work Graph support, doc updates, and code modernization.
This commit is contained in:
@@ -66,14 +66,6 @@ internal sealed partial class DxcShaderCompiler
|
||||
argsArray.Add(define);
|
||||
}
|
||||
|
||||
// HACK: Currently DXC does not support force include, we have to use GENERATED_CODE_PATH define as a workaround.
|
||||
// User must to write '#include GENERATED_CODE_PATH' in their shader code manually.
|
||||
if (File.Exists(config.include))
|
||||
{
|
||||
argsArray.Add("-D");
|
||||
argsArray.Add($"GENERATED_CODE_PATH={'"' + config.include.Replace("\\", "/") + '"'}");
|
||||
}
|
||||
|
||||
if (!config.options.HasFlag(CompilerOption.KeepDebugInfo))
|
||||
{
|
||||
argsArray.Add("-Qstrip_debug");
|
||||
@@ -97,6 +89,27 @@ internal sealed partial class DxcShaderCompiler
|
||||
return argsArray;
|
||||
}
|
||||
|
||||
private static Result<string, ErrorStatus> GetFinalShaderCode(string shaderPath, ReadOnlySpan<string> includes)
|
||||
{
|
||||
if (!File.Exists(shaderPath))
|
||||
{
|
||||
return ErrorStatus.NotFound;
|
||||
}
|
||||
|
||||
var shaderCode = File.ReadAllText(shaderPath);
|
||||
|
||||
var sb = new System.Text.StringBuilder();
|
||||
foreach (var includePath in includes)
|
||||
{
|
||||
sb.AppendLine($"#include \"{includePath}\"");
|
||||
}
|
||||
|
||||
sb.AppendLine($"#line {includes.Length + 1} \"{shaderPath}\"");
|
||||
sb.AppendLine(shaderCode);
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static ShaderInputType ToInputType(D3D_SHADER_INPUT_TYPE type)
|
||||
{
|
||||
return type switch
|
||||
@@ -121,7 +134,7 @@ internal sealed unsafe partial class DxcShaderCompiler : IShaderCompiler
|
||||
private UniquePtr<IDxcUtils> _utils;
|
||||
// NOTE: This is just a temporary cache for compiled shader code. We will implement a proper disk cache later.
|
||||
// TODO: This should be shader variant specific cache instead of pass specific.
|
||||
private readonly Dictionary<ShaderPassKey, GraphicsCompiledResult> _compiledResults;
|
||||
private readonly Dictionary<Key64<ShaderVariant>, GraphicsCompiledResult> _compiledResults;
|
||||
|
||||
private bool _disposed;
|
||||
|
||||
@@ -139,7 +152,7 @@ internal sealed unsafe partial class DxcShaderCompiler : IShaderCompiler
|
||||
_compiler.Attach(pCompiler);
|
||||
_utils.Attach(pUtils);
|
||||
|
||||
_compiledResults = new Dictionary<ShaderPassKey, GraphicsCompiledResult>();
|
||||
_compiledResults = new Dictionary<Key64<ShaderVariant>, GraphicsCompiledResult>();
|
||||
}
|
||||
|
||||
~DxcShaderCompiler()
|
||||
@@ -194,41 +207,41 @@ internal sealed unsafe partial class DxcShaderCompiler : IShaderCompiler
|
||||
switch (bindDesc.Type)
|
||||
{
|
||||
case D3D_SHADER_INPUT_TYPE.D3D_SIT_CBUFFER:
|
||||
{
|
||||
var cbuffer = pReflection->GetConstantBufferByName(bindDesc.Name);
|
||||
D3D12_SHADER_BUFFER_DESC cbufferDesc;
|
||||
ThrowIfFailed(cbuffer->GetDesc(&cbufferDesc));
|
||||
|
||||
var variables = new List<CBufferPropertyInfo>((int)cbufferDesc.Variables);
|
||||
|
||||
// Now we iterate all variables for *every* cbuffer, not just b3
|
||||
for (uint j = 0; j < cbufferDesc.Variables; j++)
|
||||
{
|
||||
var variable = cbuffer->GetVariableByIndex(j);
|
||||
D3D12_SHADER_VARIABLE_DESC varDesc;
|
||||
variable->GetDesc(&varDesc);
|
||||
var cbuffer = pReflection->GetConstantBufferByName(bindDesc.Name);
|
||||
D3D12_SHADER_BUFFER_DESC cbufferDesc;
|
||||
ThrowIfFailed(cbuffer->GetDesc(&cbufferDesc));
|
||||
|
||||
var variableName = Marshal.PtrToStringUTF8((IntPtr)varDesc.Name);
|
||||
if (variableName == null)
|
||||
var variables = new List<CBufferPropertyInfo>((int)cbufferDesc.Variables);
|
||||
|
||||
// Now we iterate all variables for *every* cbuffer, not just b3
|
||||
for (uint j = 0; j < cbufferDesc.Variables; j++)
|
||||
{
|
||||
continue;
|
||||
var variable = cbuffer->GetVariableByIndex(j);
|
||||
D3D12_SHADER_VARIABLE_DESC varDesc;
|
||||
variable->GetDesc(&varDesc);
|
||||
|
||||
var variableName = Marshal.PtrToStringUTF8((IntPtr)varDesc.Name);
|
||||
if (variableName == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
variables.Add(new CBufferPropertyInfo
|
||||
{
|
||||
Name = variableName,
|
||||
StartOffset = varDesc.StartOffset,
|
||||
Size = varDesc.Size
|
||||
});
|
||||
}
|
||||
|
||||
variables.Add(new CBufferPropertyInfo
|
||||
{
|
||||
Name = variableName,
|
||||
StartOffset = varDesc.StartOffset,
|
||||
Size = varDesc.Size
|
||||
});
|
||||
info.Size = cbufferDesc.Size;
|
||||
info.Properties = variables;
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
info.Size = cbufferDesc.Size;
|
||||
info.Properties = variables;
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
// NOTE: Currently we do not support resource bindings yet, everything access through bindless heaps.
|
||||
// NOTE: Currently we do not support resource bindings yet, everything access through bindless heaps.
|
||||
}
|
||||
|
||||
reflectionData.ResourcesBindings.Add(info);
|
||||
@@ -252,12 +265,24 @@ internal sealed unsafe partial class DxcShaderCompiler : IShaderCompiler
|
||||
ThrowIfFailed(_utils.Get()->CreateDefaultIncludeHandler(includeHandler.GetAddressOf()));
|
||||
|
||||
// Create source blob
|
||||
fixed (char* pPath = config.shaderPath)
|
||||
// fixed (char* pPath = config.shaderPath)
|
||||
// {
|
||||
// if (_utils.Get()->LoadFile(pPath, null, sourceBlob.GetAddressOf()).FAILED)
|
||||
// {
|
||||
// return Result.Failure($"Failed to load shader file: {config.shaderPath}");
|
||||
// }
|
||||
// }
|
||||
var finalShaderCodeResult = GetFinalShaderCode(config.shaderPath, config.includes);
|
||||
if (finalShaderCodeResult.IsFailure)
|
||||
{
|
||||
if (_utils.Get()->LoadFile(pPath, null, sourceBlob.GetAddressOf()).FAILED)
|
||||
{
|
||||
return Result.Failure($"Failed to load shader file: {config.shaderPath}");
|
||||
}
|
||||
return Result.Failure(finalShaderCodeResult.Error);
|
||||
}
|
||||
|
||||
var finalShaderCode = finalShaderCodeResult.Value;
|
||||
fixed (byte* pCode = System.Text.Encoding.UTF8.GetBytes(finalShaderCode))
|
||||
{
|
||||
var sizeInBytes = System.Text.Encoding.UTF8.GetByteCount(finalShaderCode);
|
||||
ThrowIfFailed(_utils.Get()->CreateBlobFromPinned(pCode, (uint)sizeInBytes, DXC_CP_UTF8, sourceBlob.GetAddressOf()));
|
||||
}
|
||||
|
||||
var argsArray = GetCompilerArguments(in config);
|
||||
@@ -342,11 +367,11 @@ internal sealed unsafe partial class DxcShaderCompiler : IShaderCompiler
|
||||
|
||||
// TODO: This should be shader variant specific compile instead of pass specific.
|
||||
// TODO: Build final shader code in memory before compiling.
|
||||
public Result<GraphicsCompiledResult> CompilePass(IPassDescriptor descriptor, ref readonly ShaderCompilationConfig additionalConfig, string? generatedCodePath)
|
||||
public Result<GraphicsCompiledResult> CompilePass(IPassDescriptor descriptor, ref readonly ShaderCompilationConfig additionalConfig, Key64<ShaderVariant> key)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
|
||||
if (descriptor is not FullPassDescriptor fullDescriptor)
|
||||
if (descriptor is not PassDescriptor fullDescriptor)
|
||||
{
|
||||
return Result.Failure("FullPassDescriptor expected.");
|
||||
}
|
||||
@@ -361,7 +386,7 @@ internal sealed unsafe partial class DxcShaderCompiler : IShaderCompiler
|
||||
var config = new ShaderCompilationConfig
|
||||
{
|
||||
defines = fullDefines.AsSpan(),
|
||||
include = generatedCodePath,
|
||||
includes = fullDescriptor.includes.AsSpan(),
|
||||
shaderPath = tsEntry.shader,
|
||||
entryPoint = tsEntry.entry,
|
||||
stage = ShaderStage.TaskShader,
|
||||
@@ -386,7 +411,7 @@ internal sealed unsafe partial class DxcShaderCompiler : IShaderCompiler
|
||||
var config = new ShaderCompilationConfig
|
||||
{
|
||||
defines = fullDefines.AsSpan(),
|
||||
include = generatedCodePath,
|
||||
includes = fullDescriptor.includes.AsSpan(),
|
||||
shaderPath = msEntry.shader,
|
||||
entryPoint = msEntry.entry,
|
||||
stage = ShaderStage.MeshShader,
|
||||
@@ -415,7 +440,7 @@ internal sealed unsafe partial class DxcShaderCompiler : IShaderCompiler
|
||||
var config = new ShaderCompilationConfig
|
||||
{
|
||||
defines = fullDefines.AsSpan(),
|
||||
include = generatedCodePath,
|
||||
includes = fullDescriptor.includes.AsSpan(),
|
||||
shaderPath = psEntry.shader,
|
||||
entryPoint = psEntry.entry,
|
||||
stage = ShaderStage.PixelShader,
|
||||
@@ -444,11 +469,11 @@ internal sealed unsafe partial class DxcShaderCompiler : IShaderCompiler
|
||||
psResult = psResult,
|
||||
};
|
||||
|
||||
_compiledResults[new ShaderPassKey(fullDescriptor.Identifier)] = compiled;
|
||||
_compiledResults[key] = compiled;
|
||||
return compiled;
|
||||
}
|
||||
|
||||
public Result<GraphicsCompiledResult, ErrorStatus> LoadCompiledCache(ShaderPassKey key)
|
||||
public Result<GraphicsCompiledResult, ErrorStatus> LoadCompiledCache(Key64<ShaderVariant> key)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
|
||||
|
||||
@@ -1,47 +1,20 @@
|
||||
using System.Runtime.Intrinsics;
|
||||
|
||||
using TerraFX.Interop.Windows;
|
||||
using ElementType = uint;
|
||||
|
||||
namespace Ghost.Graphics.Core;
|
||||
|
||||
public unsafe struct LocalKeywordSet
|
||||
{
|
||||
public struct ReadOnly
|
||||
{
|
||||
private LocalKeywordSet _set;
|
||||
|
||||
internal ReadOnly(LocalKeywordSet set)
|
||||
{
|
||||
_set = set;
|
||||
}
|
||||
|
||||
public bool IsKeywordEnabled(int id)
|
||||
{
|
||||
return _set.IsKeywordEnabled(id);
|
||||
}
|
||||
|
||||
public static ReadOnly operator |(in ReadOnly a, in ReadOnly b)
|
||||
{
|
||||
var resultSet = a._set | b._set;
|
||||
return new ReadOnly(resultSet);
|
||||
}
|
||||
|
||||
public static ReadOnly operator &(in ReadOnly a, in ReadOnly b)
|
||||
{
|
||||
var resultSet = a._set & b._set;
|
||||
return new ReadOnly(resultSet);
|
||||
}
|
||||
}
|
||||
|
||||
private const int _DATA_ARRAY_LENGTH = 4; // 4 * 32 = 128 bits
|
||||
private const int _SIZE_OF_ELEMENT = sizeof(ElementType);
|
||||
private const int _BITS_PER_ELEMENT = sizeof(ElementType) * 8;
|
||||
|
||||
private fixed ElementType _data[_DATA_ARRAY_LENGTH];
|
||||
|
||||
public void SetKeyword(int localIndex, bool enabled)
|
||||
{
|
||||
var index = localIndex / _SIZE_OF_ELEMENT;
|
||||
var bit = localIndex % _SIZE_OF_ELEMENT;
|
||||
var index = localIndex / _BITS_PER_ELEMENT;
|
||||
var bit = localIndex % _BITS_PER_ELEMENT;
|
||||
if (enabled)
|
||||
{
|
||||
_data[index] |= (uint)(1 << bit);
|
||||
@@ -54,8 +27,8 @@ public unsafe struct LocalKeywordSet
|
||||
|
||||
public bool IsKeywordEnabled(int localIndex)
|
||||
{
|
||||
var index = localIndex / _SIZE_OF_ELEMENT;
|
||||
var bit = localIndex % _SIZE_OF_ELEMENT;
|
||||
var index = localIndex / _BITS_PER_ELEMENT;
|
||||
var bit = localIndex % _BITS_PER_ELEMENT;
|
||||
return (_data[index] & (uint)(1 << bit)) != 0;
|
||||
}
|
||||
|
||||
@@ -67,11 +40,31 @@ public unsafe struct LocalKeywordSet
|
||||
}
|
||||
}
|
||||
|
||||
public readonly ReadOnly AsReadOnly()
|
||||
public ulong GetHash64()
|
||||
{
|
||||
return new ReadOnly(this);
|
||||
ulong hash = 14695981039346656037ul; // FNV offset basis
|
||||
|
||||
for (var i = 0; i < _DATA_ARRAY_LENGTH; i++)
|
||||
{
|
||||
hash ^= _data[i];
|
||||
hash *= 1099511628211ul; // FNV prime
|
||||
}
|
||||
|
||||
return hash;
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
var hash = 17;
|
||||
for (var i = 0; i < _DATA_ARRAY_LENGTH; i++)
|
||||
{
|
||||
hash = hash * 31 + _data[i].GetHashCode();
|
||||
}
|
||||
|
||||
return hash;
|
||||
}
|
||||
|
||||
|
||||
public static LocalKeywordSet operator |(in LocalKeywordSet a, in LocalKeywordSet b)
|
||||
{
|
||||
var result = default(LocalKeywordSet);
|
||||
@@ -83,10 +76,11 @@ public unsafe struct LocalKeywordSet
|
||||
{
|
||||
for (var i = 0; i < _DATA_ARRAY_LENGTH; i += Vector128<ElementType>.Count)
|
||||
{
|
||||
var vecA = Vector128.LoadUnsafe(ref *pDataA, (uint)(i * _SIZE_OF_ELEMENT));
|
||||
var vecB = Vector128.LoadUnsafe(ref *pDataB, (uint)(i * _SIZE_OF_ELEMENT));
|
||||
var elementOffset = (nuint)i;
|
||||
var vecA = Vector128.LoadUnsafe(ref *pDataA, elementOffset);
|
||||
var vecB = Vector128.LoadUnsafe(ref *pDataB, elementOffset);
|
||||
var vecResult = Vector128.BitwiseOr(vecA, vecB);
|
||||
vecResult.StoreUnsafe(ref result._data[0], (uint)(i * _SIZE_OF_ELEMENT));
|
||||
vecResult.StoreUnsafe(ref result._data[0], elementOffset);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -112,10 +106,11 @@ public unsafe struct LocalKeywordSet
|
||||
{
|
||||
for (var i = 0; i < _DATA_ARRAY_LENGTH; i += Vector128<ElementType>.Count)
|
||||
{
|
||||
var vecA = Vector128.LoadUnsafe(ref *pDataA, (uint)(i * _SIZE_OF_ELEMENT));
|
||||
var vecB = Vector128.LoadUnsafe(ref *pDataB, (uint)(i * _SIZE_OF_ELEMENT));
|
||||
var elementOffset = (nuint)i;
|
||||
var vecA = Vector128.LoadUnsafe(ref *pDataA, elementOffset);
|
||||
var vecB = Vector128.LoadUnsafe(ref *pDataB, elementOffset);
|
||||
var vecResult = Vector128.BitwiseAnd(vecA, vecB);
|
||||
vecResult.StoreUnsafe(ref result._data[0], (uint)(i * _SIZE_OF_ELEMENT));
|
||||
vecResult.StoreUnsafe(ref result._data[0], elementOffset);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,33 +7,22 @@ using System.Runtime.CompilerServices;
|
||||
|
||||
namespace Ghost.Graphics.Core;
|
||||
|
||||
#if false
|
||||
public struct VariantMask
|
||||
{
|
||||
private ulong _mask;
|
||||
}
|
||||
#endif
|
||||
|
||||
internal struct CBufferCache : IResourceReleasable
|
||||
{
|
||||
private UnsafeArray<byte> _cpuData;
|
||||
private Handle<GraphicsBuffer> _gpuResource;
|
||||
private uint _size;
|
||||
private uint _alignedSize;
|
||||
|
||||
public readonly UnsafeArray<byte> CpuData => _cpuData;
|
||||
public readonly Handle<GraphicsBuffer> GpuResource => _gpuResource;
|
||||
public readonly uint Size => _size;
|
||||
public readonly uint AlignedSize => _alignedSize;
|
||||
|
||||
public readonly bool IsCreated => _size != 0 && _gpuResource.IsValid && _cpuData.IsCreated;
|
||||
|
||||
public CBufferCache(Handle<GraphicsBuffer> buffer, uint bufferSize)
|
||||
{
|
||||
_size = bufferSize;
|
||||
_alignedSize = (bufferSize + 255u) & ~255u;
|
||||
|
||||
_cpuData = new UnsafeArray<byte>((int)AlignedSize, Allocator.Persistent);
|
||||
_cpuData = new UnsafeArray<byte>((int)bufferSize, Allocator.Persistent);
|
||||
_gpuResource = buffer;
|
||||
}
|
||||
|
||||
@@ -50,27 +39,24 @@ internal struct CBufferCache : IResourceReleasable
|
||||
_gpuResource = Handle<GraphicsBuffer>.Invalid;
|
||||
|
||||
_size = 0;
|
||||
_alignedSize = 0;
|
||||
}
|
||||
}
|
||||
|
||||
public struct Material : IResourceReleasable, IHandleType
|
||||
public struct Material : IResourceReleasable
|
||||
{
|
||||
private struct PipelineOverride
|
||||
{
|
||||
public ShaderPassKey shaderPass;
|
||||
public Key64<ShaderPass> shaderPass;
|
||||
public PipelineState options;
|
||||
public MaterialPipelineKey pipelineKey;
|
||||
}
|
||||
|
||||
private Identifier<Shader> _shader;
|
||||
private CBufferCache _cBufferCache;
|
||||
private UnsafeArray<PipelineOverride> _passPipelineOverride;
|
||||
private LocalKeywordSet _keywordMask;
|
||||
|
||||
private bool _isDirty;
|
||||
|
||||
internal readonly CBufferCache CBufferCache => _cBufferCache;
|
||||
internal CBufferCache _cBufferCache;
|
||||
internal LocalKeywordSet _keywordMask;
|
||||
|
||||
|
||||
public readonly Identifier<Shader> Shader => _shader;
|
||||
public readonly bool IsDirty => _isDirty;
|
||||
@@ -81,12 +67,6 @@ public struct Material : IResourceReleasable, IHandleType
|
||||
_isDirty = true;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal readonly MaterialPipelineKey GetPassPipelineKey(int passIndex)
|
||||
{
|
||||
return _passPipelineOverride[passIndex].pipelineKey;
|
||||
}
|
||||
|
||||
public ErrorStatus SetShader(Identifier<Shader> shaderId, IResourceAllocator allocator, IResourceDatabase database)
|
||||
{
|
||||
if (!shaderId.IsValid)
|
||||
@@ -117,9 +97,8 @@ public struct Material : IResourceReleasable, IHandleType
|
||||
ref var pass = ref shader.GetPassReference(i);
|
||||
_passPipelineOverride[i] = new PipelineOverride
|
||||
{
|
||||
shaderPass = pass.Identifier,
|
||||
shaderPass = pass.Key,
|
||||
options = pass.DeafaultState,
|
||||
pipelineKey = new MaterialPipelineKey(pass.Identifier, pass.DeafaultState),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -128,7 +107,7 @@ public struct Material : IResourceReleasable, IHandleType
|
||||
var desc = new BufferDesc
|
||||
{
|
||||
Size = shader.CBufferSize,
|
||||
Usage = BufferUsage.Constant,
|
||||
Usage = BufferUsage.Raw | BufferUsage.ShaderResource,
|
||||
MemoryType = ResourceMemoryType.Default,
|
||||
};
|
||||
|
||||
@@ -202,7 +181,6 @@ public struct Material : IResourceReleasable, IHandleType
|
||||
{
|
||||
ref var pipelineOverride = ref _passPipelineOverride[passIndex];
|
||||
pipelineOverride.options = options;
|
||||
pipelineOverride.pipelineKey = new MaterialPipelineKey(pipelineOverride.shaderPass, options);
|
||||
SetDirty();
|
||||
}
|
||||
|
||||
@@ -223,16 +201,27 @@ public struct Material : IResourceReleasable, IHandleType
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public readonly bool IsKeywordEnabled(int keywordId)
|
||||
public readonly bool IsKeywordEnabled(IResourceDatabase resourceDatabase, int keywordId)
|
||||
{
|
||||
return _keywordMask.IsKeywordEnabled(keywordId);
|
||||
ref var shader = ref resourceDatabase.GetShaderReference(_shader);
|
||||
var localIndex = shader.GetLocalKeywordIndex(keywordId);
|
||||
if (localIndex == -1)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return _keywordMask.IsKeywordEnabled(localIndex);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public readonly void UploadData(ICommandBuffer cmb)
|
||||
public readonly void UploadData(ICommandBuffer cmb, bool pixelOnlyResource = true)
|
||||
{
|
||||
cmb.UploadBuffer(_cBufferCache.GpuResource, _cBufferCache.CpuData.AsSpan());
|
||||
cmb.ResourceBarrier(_cBufferCache.GpuResource.AsResource(), ResourceState.VertexAndConstantBuffer);
|
||||
|
||||
var state = pixelOnlyResource
|
||||
? ResourceState.PixelShaderResource
|
||||
: ResourceState.NonPixelShaderResource | ResourceState.PixelShaderResource;
|
||||
cmb.ResourceBarrier(_cBufferCache.GpuResource.AsResource(), state);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
|
||||
@@ -9,7 +9,7 @@ using Misaki.HighPerformance.Mathematics.Geometry;
|
||||
|
||||
namespace Ghost.Graphics.Core;
|
||||
|
||||
public struct Mesh : IResourceReleasable, IHandleType
|
||||
public struct Mesh : IResourceReleasable
|
||||
{
|
||||
private UnsafeList<Vertex> _vertices;
|
||||
private UnsafeList<uint> _indices;
|
||||
|
||||
@@ -64,6 +64,8 @@ public readonly unsafe ref struct RenderingContext
|
||||
if (staticMesh)
|
||||
{
|
||||
meshData.ReleaseCpuResources();
|
||||
_directCmd.ResourceBarrier(vertexHandle, ResourceState.NonPixelShaderResource);
|
||||
_directCmd.ResourceBarrier(indexHandle, ResourceState.NonPixelShaderResource);
|
||||
}
|
||||
|
||||
return mesh;
|
||||
@@ -91,7 +93,7 @@ public readonly unsafe ref struct RenderingContext
|
||||
{
|
||||
ref var meshRef = ref ResourceDatabase.GetMeshReference(mesh);
|
||||
|
||||
_directCmd.ResourceBarrier(meshRef.VertexBuffer.AsResource(),ResourceState.CopyDest);
|
||||
_directCmd.ResourceBarrier(meshRef.VertexBuffer.AsResource(), ResourceState.CopyDest);
|
||||
_directCmd.ResourceBarrier(meshRef.IndexBuffer.AsResource(), ResourceState.CopyDest);
|
||||
|
||||
_directCmd.UploadBuffer(meshRef.VertexBuffer, meshRef.Vertices.AsSpan());
|
||||
@@ -122,7 +124,7 @@ public readonly unsafe ref struct RenderingContext
|
||||
|
||||
_directCmd.ResourceBarrier(bufferHandle, ResourceState.CopyDest);
|
||||
_directCmd.UploadBuffer(meshData.ObjectDataBuffer, [data]);
|
||||
_directCmd.ResourceBarrier(bufferHandle, ResourceState.VertexAndConstantBuffer);
|
||||
_directCmd.ResourceBarrier(bufferHandle, ResourceState.NonPixelShaderResource | ResourceState.PixelShaderResource);
|
||||
}
|
||||
|
||||
public Handle<Texture> CreateTexture<T>(ref readonly TextureDesc desc, ReadOnlySpan<T> data, bool tempResource = false)
|
||||
@@ -176,14 +178,20 @@ public readonly unsafe ref struct RenderingContext
|
||||
throw new InvalidOperationException("Shader pass not found in the material's shader.");
|
||||
}
|
||||
|
||||
var passPipelineKey = new PassPipelineKey([TextureFormat.B8G8R8A8_UNorm], TextureFormat.Unknown);
|
||||
var materialPipelineKey = materialRef.GetPassPipelineKey(passIndex);
|
||||
var pipelineKey = GraphicsPipelineKey.Combine(materialPipelineKey, passPipelineKey);
|
||||
ref var pass = ref shader.GetPassReference(passIndex);
|
||||
|
||||
var passPipelineHash = new PassPipelineHash([TextureFormat.B8G8R8A8_UNorm], TextureFormat.Unknown);
|
||||
var materialPipeline = materialRef.GetPassPipelineOverride(passIndex);
|
||||
|
||||
// Mask out the keywords that are not used in this pass.
|
||||
var variantMask = materialRef._keywordMask & pass.KeywordIDs;
|
||||
var shaderVariantKey = RHIUtility.CreateShaderVariantKey(pass.Key, in variantMask);
|
||||
|
||||
var pipelineKey = RHIUtility.CreateGraphicsPipelineKey(shaderVariantKey, materialPipeline, passPipelineHash);
|
||||
|
||||
if (!_engine.PipelineLibrary.HasPipeline(pipelineKey))
|
||||
{
|
||||
var pass = shader.GetPassReference(passIndex);
|
||||
var r = _engine.ShaderCompiler.LoadCompiledCache(pass.Identifier);
|
||||
var r = _engine.ShaderCompiler.LoadCompiledCache(shaderVariantKey);
|
||||
if (r.IsFailure)
|
||||
{
|
||||
throw new InvalidOperationException("Failed to load compiled shader cache for pipeline state object creation.");
|
||||
@@ -191,7 +199,7 @@ public readonly unsafe ref struct RenderingContext
|
||||
|
||||
var psoDes = new GraphicsPSODescriptor
|
||||
{
|
||||
PassId = pass.Identifier,
|
||||
VariantKey = shaderVariantKey,
|
||||
PipelineOption = materialRef.GetPassPipelineOverride(passIndex),
|
||||
|
||||
RtvFormats = [TextureFormat.B8G8R8A8_UNorm],
|
||||
@@ -203,14 +211,15 @@ public readonly unsafe ref struct RenderingContext
|
||||
}
|
||||
|
||||
_directCmd.SetPipelineState(pipelineKey);
|
||||
_directCmd.SetConstantBufferView(RootSignatureLayout.PER_OBJECT_BUFFER_SLOT, meshRef.ObjectDataBuffer);
|
||||
|
||||
// NOTE: We use fixed root signature layout for bindless rendering.
|
||||
var cache = materialRef.CBufferCache;
|
||||
if (cache.IsCreated)
|
||||
var data = new PushConstantsData
|
||||
{
|
||||
_directCmd.SetConstantBufferView(RootSignatureLayout.PER_MATERIAL_BUFFER_SLOT, cache.GpuResource);
|
||||
}
|
||||
objectIndex = _engine.ResourceDatabase.GetBindlessIndex(meshRef.ObjectDataBuffer.AsResource()).GetValueOrThrow(),
|
||||
materialIndex = _engine.ResourceDatabase.GetBindlessIndex(materialRef._cBufferCache.GpuResource.AsResource()).GetValueOrThrow(),
|
||||
};
|
||||
|
||||
var pushConstantSpan = new ReadOnlySpan<uint>(&data, sizeof(PushConstantsData) / sizeof(uint));
|
||||
_directCmd.SetGraphicsRoot32Constants(RootSignatureLayout.PUSH_CONSTANT_SLOT, pushConstantSpan);
|
||||
|
||||
var threadGroupCountX = ((uint)meshRef.IndexCount + numThreadsX - 1) / numThreadsX;
|
||||
_directCmd.DispatchMesh(threadGroupCountX, 1, 1);
|
||||
|
||||
@@ -2,11 +2,11 @@ using Ghost.Core;
|
||||
|
||||
namespace Ghost.Graphics.Core;
|
||||
|
||||
public readonly struct GPUResource : IHandleType;
|
||||
public readonly struct Texture : IHandleType;
|
||||
public readonly struct GraphicsBuffer : IHandleType;
|
||||
public readonly struct GPUResource;
|
||||
public readonly struct Texture;
|
||||
public readonly struct GraphicsBuffer;
|
||||
|
||||
public readonly struct Sampler : IIdentifierType;
|
||||
public readonly struct Sampler;
|
||||
|
||||
public static class ResourceHandleExtensions
|
||||
{
|
||||
|
||||
@@ -28,23 +28,42 @@ namespace Ghost.Graphics.Core;
|
||||
/// </summary>
|
||||
public static class RootSignatureLayout
|
||||
{
|
||||
public const int GLOBAL_BUFFER_SLOT = 0;
|
||||
public const int PER_VIEW_BUFFER_SLOT = 1;
|
||||
public const int PER_OBJECT_BUFFER_SLOT = 2;
|
||||
public const int PER_MATERIAL_BUFFER_SLOT = 3;
|
||||
// public const int GLOBAL_BUFFER_SLOT = 0;
|
||||
// public const int PER_VIEW_BUFFER_SLOT = 1;
|
||||
// public const int PER_OBJECT_BUFFER_SLOT = 2;
|
||||
// public const int PER_MATERIAL_BUFFER_SLOT = 3;
|
||||
|
||||
public const int TEXTURE_HEAP_SLOT = 0;
|
||||
public const int SAMPLER_HEAP_SLOT = 0;
|
||||
// public const int TEXTURE_HEAP_SLOT = 0;
|
||||
// public const int SAMPLER_HEAP_SLOT = 0;
|
||||
|
||||
public const int ROOT_PARAMETER_COUNT =
|
||||
#if USE_TRADITIONAL_BINDLESS
|
||||
6
|
||||
#else
|
||||
4
|
||||
#endif
|
||||
;
|
||||
public const int PUSH_CONSTANT_SLOT = 0;
|
||||
|
||||
public const int ROOT_PARAMETER_COUNT = 1;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, Size = 16)]
|
||||
public struct PushConstantsData
|
||||
{
|
||||
public uint globalIndex;
|
||||
public uint viewIndex;
|
||||
public uint objectIndex;
|
||||
public uint materialIndex;
|
||||
}
|
||||
|
||||
// The size should be 176 bytes (16-byte aligned)
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1)]
|
||||
public struct PerViewData
|
||||
{
|
||||
public float4x4 viewMatrix;
|
||||
public float4x4 projectionMatrix;
|
||||
public float3 cameraPosition;
|
||||
public float nearClip;
|
||||
public float3 cameraDirection;
|
||||
public float farClip;
|
||||
public float4 screenSize; // xy: size, zw: 1/size
|
||||
};
|
||||
|
||||
// The size should be 96 bytes (16-byte aligned)
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1)]
|
||||
public struct PerObjectData
|
||||
{
|
||||
@@ -53,4 +72,4 @@ public struct PerObjectData
|
||||
public uint vertexBuffer;
|
||||
public float3 worldBoundsMax;
|
||||
public uint indexBuffer;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -9,7 +9,7 @@ namespace Ghost.Graphics.Core;
|
||||
|
||||
public readonly struct ShaderPass
|
||||
{
|
||||
public ShaderPassKey Identifier
|
||||
public Key64<ShaderPass> Key
|
||||
{
|
||||
get; init;
|
||||
}
|
||||
@@ -19,7 +19,7 @@ public readonly struct ShaderPass
|
||||
get; init;
|
||||
}
|
||||
|
||||
public LocalKeywordSet.ReadOnly KeywordIDs
|
||||
public LocalKeywordSet KeywordIDs
|
||||
{
|
||||
get; init;
|
||||
}
|
||||
@@ -89,7 +89,7 @@ public partial struct Shader
|
||||
/// <summary>
|
||||
/// A representation of a GPU shader, including all the passes it contains.
|
||||
/// </summary>
|
||||
public partial struct Shader : IResourceReleasable, IIdentifierType
|
||||
public partial struct Shader : IResourceReleasable
|
||||
{
|
||||
private readonly uint _cbufferSize;
|
||||
private UnsafeArray<ShaderPass> _shaderPasses;
|
||||
@@ -111,18 +111,18 @@ public partial struct Shader : IResourceReleasable, IIdentifierType
|
||||
var pass = descriptor.passes[i];
|
||||
|
||||
// TODO: Handle inherited passes
|
||||
if (pass is not FullPassDescriptor fullPass)
|
||||
if (pass is not PassDescriptor fullPass)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var passKey = new ShaderPassKey(pass.Identifier);
|
||||
var passKey = RHIUtility.CreateShaderPassKey(pass.Identifier);
|
||||
var keywords = default(LocalKeywordSet);
|
||||
|
||||
if (fullPass.keywords != null && fullPass.keywords.Count > 0)
|
||||
{
|
||||
var localKeywordIndex = 0;
|
||||
|
||||
|
||||
for (var j = 0; j < fullPass.keywords.Count; j++)
|
||||
{
|
||||
var group = fullPass.keywords[j];
|
||||
@@ -149,9 +149,9 @@ public partial struct Shader : IResourceReleasable, IIdentifierType
|
||||
|
||||
_shaderPasses[i] = new ShaderPass
|
||||
{
|
||||
Identifier = passKey,
|
||||
Key = passKey,
|
||||
DeafaultState = fullPass.localPipeline,
|
||||
KeywordIDs = keywords.AsReadOnly(),
|
||||
KeywordIDs = keywords,
|
||||
};
|
||||
|
||||
_passIDToLocal[GetPassID(pass.Name)] = (ushort)i;
|
||||
@@ -207,6 +207,7 @@ public partial struct Shader : IResourceReleasable, IIdentifierType
|
||||
|
||||
void IResourceReleasable.ReleaseResource(IResourceDatabase database)
|
||||
{
|
||||
_keywordIDToLocal.Dispose();
|
||||
_shaderPasses.Dispose();
|
||||
_passIDToLocal.Dispose();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user