diff --git a/src/DirectX12GameEngine.Shaders/ShaderLoader.cs b/src/DirectX12GameEngine.Shaders/ShaderLoader.cs new file mode 100644 index 00000000..2d6b130c --- /dev/null +++ b/src/DirectX12GameEngine.Shaders/ShaderLoader.cs @@ -0,0 +1,105 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using System.Linq; +using System.Reflection; +using DirectX12GameEngine.Shaders.Mappings; +using DirectX12GameEngine.Shaders.Primitives; +using DirectX12GameEngine.Shaders.Renderer.Models.Abstract; +using DirectX12GameEngine.Shaders.Renderer.Models.Fields; + +namespace DirectX12GameEngine.Shaders +{ + /// + /// A responsible for loading and processing instances + /// + public sealed class ShaderLoader + { + /// + /// The that represents the shader to load + /// + private readonly Action Action; + + /// + /// The closure for the field + /// + private readonly Type ShaderType; + + /// + /// The closure instance for the field + /// + private readonly object ShaderInstance; + + /// + /// The sequence of fields in the targeted closure + /// + private readonly IReadOnlyList ShaderFields; + + /// + /// Creates a new with the specified parameters + /// + /// The to use to build the shader + private ShaderLoader(Action action) + { + Action = action; + ShaderType = action.Method.DeclaringType ?? throw new InvalidOperationException("Invalid closure type"); + ShaderInstance = action.Target; + ShaderFields = ShaderType.GetFields().ToArray(); + } + + private readonly List _FieldsInfo = new List(); + + /// + /// Gets the collection of items for the shader fields + /// + public IReadOnlyList FieldsInfo => _FieldsInfo; + + /// + /// Loads and processes an input + /// + /// The to use to build the shader + /// A new instance representing the input shader + [Pure] + public static ShaderLoader Load(Action action) + { + ShaderLoader @this = new ShaderLoader(action); + + @this.LoadFieldsInfo(); + + return @this; + } + + /// + /// Loads the fields info for the current shader being loaded + /// + private void LoadFieldsInfo() + { + if (FieldsInfo.Count > 0) throw new InvalidOperationException("Shader fields already loaded"); + + int readWriteBuffersCount = 0; + + foreach (FieldInfo fieldInfo in ShaderFields) + { + Type fieldType = fieldInfo.FieldType; + string fieldName = fieldInfo.Name; + object fieldValue = fieldInfo.GetValue(ShaderInstance); + FieldInfoBase processedFieldInfo; + + // Read write buffer + if (HlslKnownTypes.IsReadWriteBufferType(fieldType)) + { + processedFieldInfo = new ReadWriteBufferFieldInfo(fieldType.Name, fieldName, readWriteBuffersCount++); + } + else if (HlslKnownTypes.IsKnownScalarType(fieldType)) + { + // Static scalar field + string typeName = HlslKnownTypes.GetMappedName(fieldType); + processedFieldInfo = new StaticScalarFieldInfo(typeName, fieldName, fieldValue); + } + else throw new NotSupportedException($"Unsupported field of type {fieldType.FullName}"); + + _FieldsInfo.Add(processedFieldInfo); + } + } + } +}