More code refactoring, removed all legacy code

このコミットが含まれているのは:
Sergio Pedri committed 2019-09-19 15:08:34 +02:00
1 親 47ca3adf0c
コミット 7c3c642fad
6ファイル変更
+30 -239

検索条件に一致するファイルはありません

-80
ファイルの表示
@@ -1,80 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Numerics;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics.Buffers.Abstract;
namespace ComputeSharp.Graphics.Buffers.Extensions
{
/// <summary>
/// A <see langword="class"/> with extension methods for the <see cref="GraphicsDevice"/> type to allocate generic resources
/// </summary>
internal static class GraphicsResourceExtensions
{
/// <summary>
/// Allocates a new constant buffer with the specified generic values
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer</param>
/// <param name="data">The input <see cref="object"/> sequence to copy to the allocated buffer</param>
/// <returns>A constant <see cref="ConstantBuffer{T}"/> instance (as a <see cref="GraphicsResource"/>) with the input data</returns>
[Pure]
public static GraphicsResource AllocateConstantBufferFromReflectedValues(this GraphicsDevice device, IReadOnlyList<object> data)
{
Span<Vector4> temporarySpan = stackalloc Vector4[data.Count];
ref byte r0 = ref Unsafe.As<Vector4, byte>(ref temporarySpan.GetPinnableReference());
int offset = 0;
// Local method to write a value in the temporary buffer
void WriteValue<T>(T value, ref byte target) where T : unmanaged
{
int size = Unsafe.SizeOf<T>();
if (offset % 16 > 16 - size) offset += 16 - offset % 16;
Unsafe.As<byte, T>(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.Count; j++)
{
switch (data[j])
{
case bool b:
uint ub = default;
Unsafe.As<uint, bool>(ref ub) = b;
WriteValue(ub, ref r0);
break;
case Bool2 b2: WriteValue(b2, ref r0); break;
case Bool3 b3: WriteValue(b3, ref r0); break;
case Bool4 b4: WriteValue(b4, ref r0); break;
case int i: WriteValue(i, ref r0); break;
case Int2 i2: WriteValue(i2, ref r0); break;
case Int3 i3: WriteValue(i3, ref r0); break;
case Int4 i4: WriteValue(i4, ref r0); break;
case uint u: WriteValue(u, ref r0); break;
case UInt2 ui2: WriteValue(ui2, ref r0); break;
case UInt3 ui3: WriteValue(ui3, ref r0); break;
case UInt4 ui4: WriteValue(ui4, ref r0); break;
case float f: WriteValue(f, ref r0); break;
case Float2 f2: WriteValue(f2, ref r0); break;
case Float3 f3: WriteValue(f3, ref r0); break;
case Float4 f4: WriteValue(f4, 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;
case double d: WriteValue(d, ref r0); break;
case Double2 d2: WriteValue(d2, ref r0); break;
case Double3 d3: WriteValue(d3, ref r0); break;
case Double4 d4: WriteValue(d4, ref r0); break;
default: throw new InvalidOperationException($"Invalid item of type {data[j].GetType()}");
}
}
// Create the array to return
ConstantBuffer<Vector4> buffer = new ConstantBuffer<Vector4>(device, data.Count);
buffer.SetData(temporarySpan);
return buffer;
}
}
}
-108
ファイルの表示
@@ -1,108 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
namespace ComputeSharp.Shaders.Translation.Models
{
internal sealed partial class ReadableMember
{
/// <summary>
/// The mapping of members to getter delegates
/// </summary>
private static readonly Dictionary<string, Getter> GettersMapping = new Dictionary<string, Getter>();
/// <summary>
/// The local <see cref="Getter"/> instance, if already loaded
/// </summary>
private Getter? _Getter;
/// <summary>
/// Ensures the dynamic accessor for the current instance is loaded and ready to use
/// </summary>
public void PreloadAccessor()
{
if (_Getter == null)
{
/* If the local delegate is available, use it and save the dictionary
* access entirely. If it's not, try to get the delegate from the dictionary
* first. This can save unnecessary overhead if a delegate for the same member has
* already been built, eg. if it belongs to a captured field that is used by two different
* shaders in the same closure. Once the getter is built, cache it and invoke it */
if (GettersMapping.TryGetValue(Id, out Getter getter)) _Getter = getter;
else
{
_Getter = getter = BuildDynamicGetter();
GettersMapping.Add(Id, getter);
}
}
}
/// <summary>
/// Returns the value of the wrapped member for the current instance
/// </summary>
/// <param name="instance">The target instance to use to read the value from</param>
/// <remarks>This method doesn't ensure that the accessor is available</remarks>
/// <exception cref="NullReferenceException">The dynamic accessor is not available</exception>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public object DangerousGetValue(object? instance) => _Getter!(instance);
/// <summary>
/// Returns the value of the wrapped member for the current instance
/// </summary>
/// <param name="instance">The target instance to use to read the value from</param>
[Pure]
public object GetValue(object? instance)
{
PreloadAccessor();
return _Getter!(instance);
}
/// <summary>
/// A <see langword="delegate"/> that represents a getter for a specific member
/// </summary>
/// <param name="obj">The source object to get the member from</param>
/// <returns>The value of the member, upcast to <see cref="object"/></returns>
private delegate object Getter(object? obj);
/// <summary>
/// Gets or sets the list of parent members to access the current one from the root instance
/// </summary>
public IReadOnlyList<ReadableMember>? Parents { get; set; }
/// <summary>
/// Builds a dynamic IL method to retrieve the value of the current member
/// </summary>
[Pure]
private Getter BuildDynamicGetter()
{
return DynamicMethod<Getter>.New(il =>
{
// Info for hierarchical access
ReadableMember[] hierarchy = (Parents ?? Array.Empty<ReadableMember>()).Concat(new[] { this }).ToArray();
// Load the argument (the object instance) and cast it to the right type, if needed
if (!IsStatic)
{
il.Emit(OpCodes.Ldarg_0);
il.EmitCastOrUnbox(hierarchy[0].DeclaringType);
}
// Unroll the member access
foreach (ReadableMember member in hierarchy)
{
il.EmitReadMember(member);
}
// Box the value, if needed
if (MemberType.IsValueType) il.Emit(OpCodes.Box, MemberType);
// Return the member value from the top of the evaluation stack
il.Emit(OpCodes.Ret);
});
}
}
}
+23 -7
ファイルの表示
@@ -1,4 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Reflection;
namespace ComputeSharp.Shaders.Translation.Models
@@ -6,13 +8,8 @@ namespace ComputeSharp.Shaders.Translation.Models
/// <summary>
/// A <see langword="class"/> that wraps a readable member of another <see langword="class"/> and provides access to it
/// </summary>
internal sealed partial class ReadableMember
internal sealed class ReadableMember
{
/// <summary>
/// The id of the current member
/// </summary>
private readonly string Id;
/// <summary>
/// The <see cref="MemberInfo"/> object wrapped by the current instance
/// </summary>
@@ -25,7 +22,6 @@ namespace ComputeSharp.Shaders.Translation.Models
private ReadableMember(MemberInfo memberInfo)
{
// General properties
Id = $"{memberInfo.DeclaringType.FullName}{Type.Delimiter}{memberInfo.Name}";
Member = memberInfo;
Name = memberInfo.Name;
DeclaringType = memberInfo.DeclaringType;
@@ -66,6 +62,26 @@ namespace ComputeSharp.Shaders.Translation.Models
/// </summary>
public Type MemberType { get; }
/// <summary>
/// Gets or sets the list of parent members to access the current one from the root instance
/// </summary>
public IReadOnlyList<ReadableMember>? Parents { get; set; }
/// <summary>
/// Returns the value of the wrapped member for the current instance
/// </summary>
/// <param name="instance">The target instance to use to read the value from</param>
[Pure]
public object GetValue(object? instance)
{
return Member switch
{
FieldInfo field => field.GetValue(instance),
PropertyInfo property => property.GetValue(instance),
_ => throw new InvalidOperationException("Field and property can't both be null at the same time")
};
}
/// <summary>
/// Converts a <see cref="FieldInfo"/> object into a <see cref="ReadableMember"/> instance
/// </summary>
+7 -1
ファイルの表示
@@ -51,6 +51,13 @@ namespace ComputeSharp.Shaders.Translation
[Pure]
public DispatchData GetDispatchData(Action<ThreadIds> action, int x, int y, int z)
{
/* Create the data loader instance, if not available already.
* This will also initialize the other local fields in the shader
* loader class, which are used to rent the buffers used to store
* the captured resources and variables. This is why this call
* has to be the first one in this method, it must NOT be moved */
DispatchDataLoader loader = _DispatchDataLoader ??= BuildDispatchDataLoader();
// Resources and variables buffers
GraphicsResource[] resources = ArrayPool<GraphicsResource>.Shared.Rent(_ResourcesCount);
byte[] variables = ArrayPool<byte>.Shared.Rent(_VariablesByteSize);
@@ -63,7 +70,6 @@ namespace ComputeSharp.Shaders.Translation
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 2) = z;
// Invoke the dynamic method to extract the captured data
DispatchDataLoader loader = _DispatchDataLoader ??= BuildDispatchDataLoader();
loader(action.Target, ref r0, ref r1);
return new DispatchData(resources, _ResourcesCount, variables, _VariablesByteSize);
-8
ファイルの表示
@@ -223,14 +223,6 @@ namespace ComputeSharp.Shaders.Translation
// Captured static delegates with a return type
LoadStaticMethodSource(fieldName, func.Method);
}
/* Build the dynamic IL accessor for the current member, if one is
* not available already. This is done during while the shader is
* being loaded and not just when needed because the internal cache
* system for the accessors is not thread safe. Preloading the accessor here
* leverages the external lock around the shader loading, ensuring
* that no race conditions occur when accessing the cached mapping */
memberInfo.PreloadAccessor();
}
/// <summary>
-35
ファイルの表示
@@ -1,35 +0,0 @@
using System;
using System.Numerics;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics.Buffers.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ComputeSharp.Tests.Internals
{
[TestClass]
[TestCategory("Buffers")]
public class BufferTests
{
[TestMethod]
public void ConstantBufferGetSetFromGenericValues()
{
object[] values = { 7, 3.14, Vector2.UnitX, 3.14f, new Vector4(7.14f, 7.15f, 7.77f, 2.55f) };
using ConstantBuffer<Vector4> buffer = (ConstantBuffer<Vector4>)Gpu.Default.AllocateConstantBufferFromReflectedValues(values);
Vector4[] data = buffer.GetData();
ref byte r0 = ref Unsafe.As<Vector4, byte>(ref data[0]);
int i = Unsafe.As<byte, int>(ref Unsafe.Add(ref r0, 0)); // 0 -> 3, sizeof(int) == 4
double d = Unsafe.As<byte, double>(ref Unsafe.Add(ref r0, 4)); // 4 -> 11, sizeof(double) == 8
Vector2 v2 = Unsafe.As<byte, Vector2>(ref Unsafe.Add(ref r0, 16)); // 16 -> 23, sizeof(Vector2) == 8
float f = Unsafe.As<byte, float>(ref Unsafe.Add(ref r0, 24)); // 24 -> 27, sizeof(float) == 4
Vector4 v4 = Unsafe.As<byte, Vector4>(ref Unsafe.Add(ref r0, 32)); // 32 -> 47, sizeof(Vector4) == 16
Assert.IsTrue((int)values[0] == i);
Assert.IsTrue(Math.Abs((double)values[1] - d) < 0.0001);
Assert.IsTrue((Vector2)values[2] == v2);
Assert.IsTrue(MathF.Abs((float)values[3] - f) < 0.0001);
Assert.IsTrue((Vector4)values[4] == v4);
}
}
}