using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Reflection; using ComputeSharp.Graphics.Buffers.Abstract; namespace ComputeSharp.Graphics.Buffers.Extensions { /// /// A with extension methods for the type to allocate generic resources /// internal static class GraphicsResourceExtensions { /// /// The that maps types to the necessary data to create buffers, for quick lookup /// private static readonly Dictionary TypeMapping = new Dictionary(); /// /// Allocates a new constant buffer with the specified generic value /// /// The instance to use to allocate the buffer /// The input to copy to the allocated buffer /// A constant instance (as a ) with the input data [Pure] public static GraphicsResource AllocateConstantBufferFromReflectedSingleValue(this GraphicsDevice device, object data) { Type dataType = data.GetType(); if (!TypeMapping.TryGetValue(dataType, out var info)) { // Get the generic buffer constructor Type bufferType = typeof(ConstantBuffer<>).MakeGenericType(dataType); info.Constructor = bufferType.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic).First(); // Create the reusable array Type arrayType = dataType.MakeArrayType(); ConstructorInfo[] arrayConstructors = arrayType.GetConstructors(BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.Instance | BindingFlags.OptionalParamBinding); info.Array = (IList)arrayConstructors[0].Invoke(new object[] { 1 }); // Set the input data to the new buffer info.Setter = bufferType.GetMethod(nameof(HlslBuffer.SetData), new[] { arrayType }); // Cache for later reuse TypeMapping.Add(dataType, info); } // Create the buffer and set the content GraphicsResource buffer = (GraphicsResource)info.Constructor.Invoke(new object[] { device, 1 }); info.Array[0] = data; info.Setter.Invoke(buffer, new object[] { info.Array }); return buffer; } } }