using System.Collections.Concurrent;
using System.Reflection;
namespace Brutal.VulkanApi.Abstractions;
///
/// Controls how (s)byte or (u)short types are mapped to shader-compatible types.
///
public enum Behavior
{
///
/// Small integer types should map to a 32-bit integer type, potentially signed.
///
///
///
/// - sbyte will map to int
/// - sbyte3 will map to ivec3
/// - byte will map to uint
/// - byte3 will map to uvec3
///
///
None,
///
/// Small integer types should map to a normalized floating point range, potentially signed.
///
///
///
/// - sbyte components will be mapped onto a [-1.0f - 1.0f] floating point range
/// - byte components will be mapped onto a [0.0f - 1.0f] floating point range
///
///
Normalize,
///
/// Small integer types should convert directly to a 32-bit floating point value, maintaining the original value.
///
///
///
/// - byte components will be mapped to a [0.0f - 255.0f] floating point range
/// - sbyte components will be mapped to a [-128.0f - 127.0f] floating point range
///
///
Scale,
}
///
/// Controls how (s)byte or (u)short types are mapped to shader-compatible types.
///
[AttributeUsage(AttributeTargets.Field)]
public class FixedPointConversionAttribute(Behavior mode) : Attribute
{
public Behavior Mode = mode;
}
///
/// Overrides the that reflection assigns to a
/// field - e.g. a packed uint color field annotated
/// [VertexFormat(VkFormat.R8G8B8A8UNorm)] instead of the default R32UInt.
/// The field's natural size still determines the offset advance, so the override's format
/// must be the same size as the field.
///
[AttributeUsage(AttributeTargets.Field)]
public class VertexFormatAttribute(VkFormat format) : Attribute
{
public VkFormat Format = format;
}
///
/// A builder for PipelineVertexInputStateCreateInfo
///
public class VertexInput
{
// csharpier-ignore
private static readonly Dictionary FormatMap =
new()
{
[typeof(sbyte)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R8SInt,
NormalizedFormat = VkFormat.R8SNorm,
ScaledFormat = VkFormat.R8SScaled,
LayoutCount = 1
}
),
[typeof(sbyte2)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R8G8SInt,
NormalizedFormat = VkFormat.R8G8SNorm,
ScaledFormat = VkFormat.R8G8SScaled,
LayoutCount = 1
}
),
[typeof(sbyte3)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R8G8B8SInt,
NormalizedFormat = VkFormat.R8G8B8SNorm,
ScaledFormat = VkFormat.R8G8B8SScaled,
LayoutCount = 1
}
),
[typeof(sbyte4)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R8G8B8A8SInt,
NormalizedFormat = VkFormat.R8G8B8A8SNorm,
ScaledFormat = VkFormat.R8G8B8A8SScaled,
LayoutCount = 1
}
),
[typeof(byte)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R8UInt,
NormalizedFormat = VkFormat.R8UNorm,
ScaledFormat = VkFormat.R8UScaled,
LayoutCount = 1
}
),
[typeof(byte2)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R8G8UInt,
NormalizedFormat = VkFormat.R8G8UNorm,
ScaledFormat = VkFormat.R8G8UScaled,
LayoutCount = 1
}
),
[typeof(byte3)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R8G8B8UInt,
NormalizedFormat = VkFormat.R8G8B8UNorm,
ScaledFormat = VkFormat.R8G8B8UScaled,
LayoutCount = 1
}
),
[typeof(byte4)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R8G8B8A8UInt,
NormalizedFormat = VkFormat.R8G8B8A8UNorm,
ScaledFormat = VkFormat.R8G8B8A8UScaled,
LayoutCount = 1
}
),
[typeof(short)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R16SInt,
NormalizedFormat = VkFormat.R16SNorm,
ScaledFormat = VkFormat.R16SScaled,
LayoutCount = 1
}
),
[typeof(short2)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R16G16SInt,
NormalizedFormat = VkFormat.R16G16SNorm,
ScaledFormat = VkFormat.R16G16SScaled,
LayoutCount = 1
}
),
[typeof(short3)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R16G16B16SInt,
NormalizedFormat = VkFormat.R16G16B16SNorm,
ScaledFormat = VkFormat.R16G16B16SScaled,
LayoutCount = 1
}
),
[typeof(short4)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R16G16B16A16SInt,
NormalizedFormat = VkFormat.R16G16B16A16SNorm,
ScaledFormat = VkFormat.R16G16B16A16SScaled,
LayoutCount = 1
}
),
[typeof(ushort)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R16UInt,
NormalizedFormat = VkFormat.R16UNorm,
ScaledFormat = VkFormat.R16UScaled,
LayoutCount = 1
}
),
[typeof(ushort2)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R16G16UInt,
NormalizedFormat = VkFormat.R16G16UNorm,
ScaledFormat = VkFormat.R16G16UScaled,
LayoutCount = 1
}
),
[typeof(ushort3)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R16G16B16UInt,
NormalizedFormat = VkFormat.R16G16B16UNorm,
ScaledFormat = VkFormat.R16G16B16UScaled,
LayoutCount = 1
}
),
[typeof(ushort4)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R16G16B16A16UInt,
NormalizedFormat = VkFormat.R16G16B16A16UNorm,
ScaledFormat = VkFormat.R16G16B16A16UScaled,
LayoutCount = 1
}
),
[typeof(int)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R32SInt,
NormalizedFormat = VkFormat.Undefined,
ScaledFormat = VkFormat.Undefined,
LayoutCount = 1
}
),
[typeof(int2)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R32G32SInt,
NormalizedFormat = VkFormat.Undefined,
ScaledFormat = VkFormat.Undefined,
LayoutCount = 1
}
),
[typeof(int3)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R32G32B32SInt,
NormalizedFormat = VkFormat.Undefined,
ScaledFormat = VkFormat.Undefined,
LayoutCount = 1
}
),
[typeof(int4)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R32G32B32A32SInt,
NormalizedFormat = VkFormat.Undefined,
ScaledFormat = VkFormat.Undefined,
LayoutCount = 1
}
),
[typeof(uint)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R32UInt,
NormalizedFormat = VkFormat.Undefined,
ScaledFormat = VkFormat.Undefined,
LayoutCount = 1
}
),
[typeof(uint2)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R32G32UInt,
NormalizedFormat = VkFormat.Undefined,
ScaledFormat = VkFormat.Undefined,
LayoutCount = 1
}
),
[typeof(uint3)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R32G32B32UInt,
NormalizedFormat = VkFormat.Undefined,
ScaledFormat = VkFormat.Undefined,
LayoutCount = 1
}
),
[typeof(uint4)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R32G32B32A32UInt,
NormalizedFormat = VkFormat.Undefined,
ScaledFormat = VkFormat.Undefined,
LayoutCount = 1
}
),
[typeof(float)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R32SFloat,
NormalizedFormat = VkFormat.Undefined,
ScaledFormat = VkFormat.Undefined,
LayoutCount = 1
}
),
[typeof(float2)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R32G32SFloat,
NormalizedFormat = VkFormat.Undefined,
ScaledFormat = VkFormat.Undefined,
LayoutCount = 1
}
),
[typeof(float3)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R32G32B32SFloat,
NormalizedFormat = VkFormat.Undefined,
ScaledFormat = VkFormat.Undefined,
LayoutCount = 1
}
),
[typeof(float4)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R32G32B32A32SFloat,
NormalizedFormat = VkFormat.Undefined,
ScaledFormat = VkFormat.Undefined,
LayoutCount = 1
}
),
[typeof(float4x4)] = AttributeInfo.Make(
new CreateAttributeInfo
{
DefaultFormat = VkFormat.R32G32B32A32SFloat,
NormalizedFormat = VkFormat.Undefined,
ScaledFormat = VkFormat.Undefined,
LayoutCount = 4
}
)
};
///
/// Error codes for vertex input validation
///
public enum Error
{
///
/// Vertex input is valid
///
Ok,
///
/// A binding has been declared more than once
///
DuplicateBinding,
///
/// An attribute has been declared more than once to a single location
///
DuplicateLocation,
///
/// An attribute's offset exceeds the stride of the binding
///
OffsetExceedsStride,
///
/// An attribute references a binding that has not been declared
///
AttributeReferencesNonExistentBinding,
///
/// A binding has a stride of zero
///
BindingHasZeroStride,
}
///
/// The list of bindings that can be used by the vertex input
///
public NativeList Bindings;
///
/// The list of attributes that can be used by the vertex input across all bindings
///
public NativeList Attributes;
private PtrOwner _createInfo = new(
new VkPipelineVertexInputStateCreateInfo { }
);
///
/// The list of attributes that can be used by the vertex input across all bindings
///
PtrOwner GetCreateInfo()
{
_createInfo.Value = _createInfo.Value with
{
VertexBindingDescriptions = Bindings.Ptr,
VertexAttributeDescriptions = Attributes.Ptr,
VertexBindingDescriptionCount = Bindings.Count,
VertexAttributeDescriptionCount = Attributes.Count,
};
return _createInfo;
}
///
/// Construct a new VertexInput builder
///
/// Preallocate with this many bindings
/// Preallocate with this many attributes
public VertexInput(int bindingCapacity, int attributeCapacity)
{
Bindings = new NativeList(bindingCapacity);
Attributes = new NativeList(attributeCapacity);
}
///
/// Construct with a complete input layout structure
///
public VertexInput(
Span bindings,
Span attributes
)
{
Bindings = new NativeList(bindings);
Attributes = new NativeList(attributes);
}
///
/// Reset for reuse
///
public void Reset()
{
Bindings.Count = 0;
Attributes.Count = 0;
}
///
/// Clone this vertex input
///
public VertexInput Clone()
{
return new VertexInput(Bindings.AsSpan(), Attributes.AsSpan());
}
///
/// Implicit cast to the PipelineVertexInputStateCreateInfo structure
///
public static unsafe implicit operator VkPipelineVertexInputStateCreateInfo*(VertexInput inValue) =>
inValue.GetCreateInfo();
///
/// Add a binding to the vertex input
///
/// The buffer slot
/// The size of one vertex
/// Whether this binding will be per vertex or per instance
/// The builder
public VertexInput AddBinding(int binding, ByteSize stride, VkVertexInputRate vertexInputRate)
{
return AddBinding(
new VkVertexInputBindingDescription
{
Binding = binding,
Stride = stride,
InputRate = vertexInputRate,
}
);
}
///
/// Add a binding to the vertex input, inferring the stride from the templated type
///
/// The buffer slot
/// Whether this binding will be per vertex or per instance
/// The type of the vertex
/// The builder
public VertexInput AddBinding(int binding, VkVertexInputRate vertexInputRate)
{
if (FormatMap.TryGetValue(typeof(T), out var typeInfo))
{
return AddBinding(binding, typeInfo.GetTotalSize(Behavior.None), vertexInputRate);
}
var size = 0;
foreach (var field in GetFieldLayout(typeof(T)))
size += (int)field.Info.GetTotalSize(field.Mode);
return AddBinding(binding, ByteSize.Of(size), vertexInputRate);
}
///
/// Add a binding to the vertex input
///
/// The buffer slot
/// The builder
public VertexInput AddBinding(VkVertexInputBindingDescription binding)
{
Bindings.Add(binding);
return this;
}
///
/// Add an attribute to the vertex input for a given binding
///
/// The index of this attribute
/// The buffer slot this attribute will be read from
/// The format of the attribute
/// The offset into the buffer to find this attribute
/// The builder
public VertexInput AddAttribute(int location, int binding, VkFormat format, ByteSize offset)
{
return AddAttribute(
new VkVertexInputAttributeDescription
{
Location = location,
Binding = binding,
Format = format,
Offset = offset,
}
);
}
///
/// Add an attribute to the vertex input for a given binding
///
/// The index of this attribute
/// The buffer slot this attribute will be read from
/// The offset into the buffer to find this attribute
/// The behaviour of the attribute
/// The builder
public VertexInput AddAttribute(int location, int binding, ByteSize offset, Behavior mode)
{
var info = FormatMap[typeof(T)];
var format = info.GetFormat(mode);
for (var j = 0; j < info.Num; ++j)
{
AddAttribute(location, binding, format, offset);
offset += info.GetBehaviourStride(mode);
location += 1;
}
return this;
}
///
/// Add an attribute to the vertex input
///
/// The attibute to add
/// The builder
public VertexInput AddAttribute(VkVertexInputAttributeDescription attribute)
{
Attributes.Add(attribute);
return this;
}
///
/// Create a new binding containing a single attribute for the templated type
///
/// The index
/// The buffer slot
/// Whether this binding will be per vertex or per instance
/// The behaviour of certain formats
/// The type of the vertex
public VertexInput AddAttributeBinding(
int location,
int binding,
VkVertexInputRate vertexInputRate,
Behavior mode = Behavior.None
)
{
return AddBinding(binding, vertexInputRate).AddAttribute(location, binding, ByteSize.Zero, mode);
}
///
/// Create a new binding and add attributes for the templated type
///
/// The starting index
/// The buffer slot
/// Whether this binding will be per vertex or per instance
/// The type of the vertex
public VertexInput AddBindingWithAttributes(int firstLocation, int binding, VkVertexInputRate vertexInputRate)
{
return AddBinding(binding, vertexInputRate).AddAttributes(firstLocation, binding, ByteSize.Zero);
}
///
/// Add attributes for the templated type, for some existing binding
///
/// The starting index
/// The buffer slot
/// The starting byte offset
/// The type of the vertex
public VertexInput AddAttributes(int firstLocation, int binding, ByteSize firstOffset)
{
var location = firstLocation;
var offset = firstOffset;
foreach (var field in GetFieldLayout(typeof(T)))
{
var info = field.Info;
var format = field.FormatOverride != VkFormat.Undefined ? field.FormatOverride : info.GetFormat(field.Mode);
for (var j = 0; j < info.Num; ++j)
{
AddAttribute(location, binding, format, offset);
offset += info.GetBehaviourStride(field.Mode);
location += 1;
}
}
return this;
}
///
/// Cached per-type field layout so reflection runs once per vertex type instead of on every call.
///
private readonly record struct FieldLayout(AttributeInfo Info, Behavior Mode, VkFormat FormatOverride);
private static readonly ConcurrentDictionary LayoutCache = new();
private static FieldLayout[] GetFieldLayout(Type type)
{
return LayoutCache.GetOrAdd(
type,
static t =>
{
var fields = t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
var layout = new FieldLayout[fields.Length];
for (var i = 0; i < fields.Length; i++)
{
var info = FormatMap[fields[i].FieldType];
var mode =
(
Attribute.GetCustomAttribute(fields[i], typeof(FixedPointConversionAttribute))
as FixedPointConversionAttribute
)?.Mode ?? Behavior.None;
var formatOverride =
(
Attribute.GetCustomAttribute(fields[i], typeof(VertexFormatAttribute))
as VertexFormatAttribute
)?.Format ?? VkFormat.Undefined;
layout[i] = new FieldLayout(info, mode, formatOverride);
}
return layout;
}
);
}
///
/// Build a complete single-binding vertex input for :
/// binding 0 at per-vertex rate, attributes reflected from the type's fields starting at location 0.
///
public static VertexInput For()
{
return new VertexInput(1, Count(typeof(TVertex))).AddBindingWithAttributes(
0,
0,
VkVertexInputRate.Vertex
);
}
///
/// Build a complete two-binding vertex input: on binding 0 at
/// per-vertex rate starting at location 0, and on binding 1 at
/// per-instance rate, with its locations continuing after the vertex attributes.
///
public static VertexInput For()
{
var vertexAttributeCount = Count(typeof(TVertex));
return new VertexInput(2, vertexAttributeCount + Count(typeof(TInstance)))
.AddBindingWithAttributes(0, 0, VkVertexInputRate.Vertex)
.AddBindingWithAttributes(vertexAttributeCount, 1, VkVertexInputRate.Instance);
}
///
/// Test that the vertex input is valid
///
///
public Error Test()
{
for (var i = 0; i < Bindings.Count; ++i)
{
if (Bindings[i].Stride == 0)
return Error.BindingHasZeroStride;
for (var j = 0; j < Bindings.Count; ++j)
{
if (i == j)
continue;
if (Bindings[i].Binding == Bindings[j].Binding)
return Error.DuplicateBinding;
}
}
for (var i = 0; i < Attributes.Count; ++i)
{
for (var j = 0; j < Attributes.Count; ++j)
{
if (i == j)
continue;
if (Attributes[i].Location == Attributes[j].Location)
return Error.DuplicateLocation;
}
var foundBinding = false;
for (var j = 0; j < Bindings.Count; j++)
{
if (Attributes[i].Binding == Bindings[j].Binding)
{
foundBinding = true;
if (Attributes[i].Offset >= Bindings[j].Stride)
return Error.OffsetExceedsStride;
break;
}
}
if (!foundBinding)
return Error.AttributeReferencesNonExistentBinding;
}
return Error.Ok;
}
public struct CreateAttributeInfo()
{
public required int LayoutCount = 1;
public required VkFormat DefaultFormat;
public required VkFormat NormalizedFormat = VkFormat.Undefined;
public required VkFormat ScaledFormat = VkFormat.Undefined;
}
public class AttributeInfo(CreateAttributeInfo info, ByteSize inStride)
{
public readonly int Num = info.LayoutCount;
// Stride with default behaviour
public readonly ByteSize Stride = inStride;
public ByteSize GetBehaviourStride(Behavior mode) => mode == Behavior.None ? Stride : ByteSize.Of();
public ByteSize GetTotalSize(Behavior mode) => GetBehaviourStride(mode) * Num;
public VkFormat GetFormat(Behavior mode)
{
var format = GetFormatInternal(mode);
if (format == VkFormat.Undefined)
throw new InvalidOperationException($"Format {mode} not supported for this type!");
return format;
}
private VkFormat GetFormatInternal(Behavior mode)
{
return mode switch
{
Behavior.None => info.DefaultFormat,
Behavior.Normalize => info.NormalizedFormat,
Behavior.Scale => info.ScaledFormat,
_ => throw new ArgumentOutOfRangeException(nameof(mode), mode, null),
};
}
public static AttributeInfo Make(CreateAttributeInfo info)
where T : unmanaged
{
var size = ByteSize.Of();
return new AttributeInfo(info, size);
}
}
// Binary-compat shim for assemblies compiled against the old params Type[] signature
public static int Count(params Type[] types) => Count((ReadOnlySpan)types);
///
/// Count the number of rendering attributes for the given type(s).
///
///
/// Counts every instance field (public and non-public) exactly as and
/// lay them out, via the shared field-layout cache. Static fields are
/// not counted. This differs from the historical behaviour, which counted public fields including
/// static ones; the two are now consistent so a count always matches the emitted binding.
///
public static int Count(params ReadOnlySpan types)
{
var count = 0;
foreach (var type in types)
foreach (var field in GetFieldLayout(type))
count += field.Info.Num;
return count;
}
///
/// Check the validity of the vertex input structure
///
///
public VertexInput Check()
{
var error = Test();
if (error != Error.Ok)
throw new InvalidOperationException($"Invalid vertex input: {error}");
return this;
}
}