diff --git a/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs b/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs
index 7ab8bb98..2c596832 100644
--- a/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs
+++ b/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs
@@ -3,7 +3,9 @@ using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
+using System.Numerics;
using System.Reflection;
+using System.Runtime.CompilerServices;
using ComputeSharp.Graphics.Buffers.Abstract;
namespace ComputeSharp.Graphics.Buffers.Extensions
@@ -56,5 +58,51 @@ namespace ComputeSharp.Graphics.Buffers.Extensions
return buffer;
}
+
+ ///
+ /// Allocates a new constant buffer with the specified generic values
+ ///
+ /// The instance to use to allocate the buffer
+ /// The input array to copy to the allocated buffer
+ /// A constant instance (as a ) with the input data
+ [Pure]
+ public static GraphicsResource AllocateConstantBufferFromReflectedValues(this GraphicsDevice device, object[] data)
+ {
+ Span temporarySpan = stackalloc Vector4[data.Length];
+ ref byte r0 = ref Unsafe.As(ref temporarySpan.GetPinnableReference());
+ int offset = 0;
+
+ // Local method to write a value in the temporary buffer
+ void WriteValue(T value, ref byte target) where T : unmanaged
+ {
+ int size = Unsafe.SizeOf();
+ if (offset % 16 > 16 - size) offset += 16 - offset % 16;
+ Unsafe.As(ref Unsafe.Add(ref target, offset)) = value;
+ offset += size;
+ }
+
+ // Iterate on the input values and write them with the proper padding
+ for (int j = 0; j < data.Length; j++)
+ {
+ switch (data[j])
+ {
+ case bool b: WriteValue(b, ref r0); break;
+ case int i: WriteValue(i, ref r0); break;
+ case uint u: WriteValue(u, ref r0); break;
+ case float f: WriteValue(f, ref r0); break;
+ case double d: WriteValue(d, ref r0); break;
+ case Vector2 v2: WriteValue(v2, ref r0); break;
+ case Vector3 v3: WriteValue(v3, ref r0); break;
+ case Vector4 v4: WriteValue(v4, ref r0); break;
+ default: throw new InvalidOperationException($"Invalid item of type {data[j].GetType()}");
+ }
+ }
+
+ // Create the array to return
+ ConstantBuffer buffer = new ConstantBuffer(device, data.Length);
+ buffer.SetData(temporarySpan);
+
+ return buffer;
+ }
}
}