Merge pull request #515 from Sergio0694/dev/uwp-tests

Add ComputeSharp.D2D1.Uwp unit tests
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2023-04-26 09:46:48 -07:00
コミット 50c60ec544
29ファイル変更
+1420 -19

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

+29 -3
ファイルの表示
@@ -71,7 +71,7 @@ jobs:
path: artifacts\*.nupkg
if-no-files-found: error
# Run all unit tests referencing the ComputeSharp project directly
# Run all unit tests referencing the ComputeSharp projects directly
run-tests:
needs: [build-solution]
strategy:
@@ -122,6 +122,32 @@ jobs:
- name: Run ComputeSharp.D2D1.Tests.AssemblyLevelAttributes
run: dotnet test tests\ComputeSharp.D2D1.Tests.AssemblyLevelAttributes\ComputeSharp.D2D1.Tests.AssemblyLevelAttributes.csproj -c Release -f ${{matrix.framework}} -v n -l "console;verbosity=detailed"
# Run all UWP tests (separately, as they need VS Test)
run-tests-uwp:
needs: [build-solution]
strategy:
matrix:
configuration: [Debug, Release]
runs-on: windows-2022
steps:
- name: Git checkout
uses: actions/checkout@v3
- name: Add msbuild to PATH
uses: microsoft/[email protected]
# Build the D2D1 UWP unit tests (need to restore and build separately for it to build correctly)
- name: Build ComputeSharp.D2D1.Uwp.Tests
run: >
msbuild tests\ComputeSharp.D2D1.Uwp.Tests\ComputeSharp.D2D1.Uwp.Tests.csproj -t:restore /p:Configuration=${{matrix.configuration}} /p:Platform=x64;
msbuild tests\ComputeSharp.D2D1.Uwp.Tests\ComputeSharp.D2D1.Uwp.Tests.csproj -t:build /p:Configuration=${{matrix.configuration}} /p:Platform=x64
# Run the D2D1 UWP unit tests with VS Test (need to use vswhere to find the VS Test runner)
- name: Run ComputeSharp.D2D1.Uwp.Tests
run: >
$vs_path = vswhere -latest -products * -requires Microsoft.VisualStudio.Workload.ManagedDesktop -requiresAny -property installationPath;
$vstest_path = join-path $vs_path 'Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe';
& $vstest_path /Platform:x64 /framework:frameworkuap10 tests\ComputeSharp.D2D1.Uwp.Tests\bin\x64\${{matrix.configuration}}\ComputeSharp.D2D1.Uwp.Tests.build.appxrecipe
# Run all the local samples to ensure they build and run with no errors
run-samples:
needs: [build-solution]
@@ -255,7 +281,7 @@ jobs:
# Publish the packages to GitHub packages
publish-nightlies-github:
needs: [run-tests, run-samples, run-samples-aot, verify-packages]
needs: [run-tests, run-tests-uwp, run-samples, run-samples-aot, verify-packages]
runs-on: windows-2022
if: ${{github.event_name == 'push'}}
steps:
@@ -267,7 +293,7 @@ jobs:
# Publish the packages to Azure DevOps
publish-nightlies-azure-devops:
needs: [run-tests, run-samples, run-samples-aot, verify-packages]
needs: [run-tests, run-tests-uwp, run-samples, run-samples-aot, verify-packages]
runs-on: windows-2022
if: ${{github.event_name == 'push'}}
steps:
+23
ファイルの表示
@@ -150,6 +150,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Assets", "Assets", "{345F62
assets\icon_highres.png = assets\icon_highres.png
EndProjectSection
EndProject
Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "ComputeSharp.D2D1.UI.Tests", "tests\ComputeSharp.D2D1.UI.Tests\ComputeSharp.D2D1.UI.Tests.shproj", "{346AEB10-A4EA-427E-8578-F60915DB3053}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.D2D1.Uwp.Tests", "tests\ComputeSharp.D2D1.Uwp.Tests\ComputeSharp.D2D1.Uwp.Tests.csproj", "{4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
@@ -414,6 +418,18 @@ Global
{9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}.Release|ARM64.Build.0 = Release|ARM64
{9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}.Release|x64.ActiveCfg = Release|x64
{9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}.Release|x64.Build.0 = Release|x64
{4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}.Debug|ARM64.ActiveCfg = Debug|ARM64
{4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}.Debug|ARM64.Build.0 = Debug|ARM64
{4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}.Debug|ARM64.Deploy.0 = Debug|ARM64
{4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}.Debug|x64.ActiveCfg = Debug|x64
{4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}.Debug|x64.Build.0 = Debug|x64
{4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}.Debug|x64.Deploy.0 = Debug|x64
{4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}.Release|ARM64.ActiveCfg = Release|ARM64
{4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}.Release|ARM64.Build.0 = Release|ARM64
{4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}.Release|ARM64.Deploy.0 = Release|ARM64
{4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}.Release|x64.ActiveCfg = Release|x64
{4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}.Release|x64.Build.0 = Release|x64
{4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}.Release|x64.Deploy.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -451,6 +467,8 @@ Global
{568E7009-5C13-4153-9C94-0AC7A3E6883C} = {1A9C4108-F61A-4ABE-B5CF-F524521EAE2D}
{B54B6DCA-6EAB-46A8-83D3-15154659F47F} = {1A9C4108-F61A-4ABE-B5CF-F524521EAE2D}
{9EA5AE9D-C39A-4F43-B03E-0A848EA2558A} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1}
{346AEB10-A4EA-427E-8578-F60915DB3053} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7}
{4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4664C5E3-0340-4E22-BCFD-98AAEDF5F2DC}
@@ -464,6 +482,11 @@ Global
src\TerraFX.Interop.Windows.Dynamic\TerraFX.Interop.Windows.Dynamic.projitems*{158f984d-cd96-4062-bd02-2268946031a0}*SharedItemsImports = 13
samples\ComputeSharp.SwapChain.Shaders.D2D1.Shared\ComputeSharp.SwapChain.Shaders.D2D1.Shared.projitems*{209c95a3-fa53-431b-b688-3299ca6c29d2}*SharedItemsImports = 5
src\TerraFX.Interop.Windows\TerraFX.Interop.Windows.projitems*{314eb353-e7e3-4146-8111-685cc83ec1de}*SharedItemsImports = 5
tests\ComputeSharp.D2D1.UI.Tests\ComputeSharp.D2D1.UI.Tests.projitems*{346aeb10-a4ea-427e-8578-f60915db3053}*SharedItemsImports = 13
samples\ComputeSharp.SwapChain.Shaders.D2D1.Shared\ComputeSharp.SwapChain.Shaders.D2D1.Shared.projitems*{4d4bb2f6-5653-4db5-a8dd-90d58d8fe4d3}*SharedItemsImports = 4
src\ComputeSharp.NetStandard\ComputeSharp.NetStandard.projitems*{4d4bb2f6-5653-4db5-a8dd-90d58d8fe4d3}*SharedItemsImports = 4
src\TerraFX.Interop.Windows.D2D1\TerraFX.Interop.Windows.D2D1.projitems*{4d4bb2f6-5653-4db5-a8dd-90d58d8fe4d3}*SharedItemsImports = 4
tests\ComputeSharp.D2D1.UI.Tests\ComputeSharp.D2D1.UI.Tests.projitems*{4d4bb2f6-5653-4db5-a8dd-90d58d8fe4d3}*SharedItemsImports = 4
src\TerraFX.Interop.Windows.D2D1\TerraFX.Interop.Windows.D2D1.projitems*{4d7d9ba8-a821-4b1c-9ee2-cbcf5849906e}*SharedItemsImports = 5
src\TerraFX.Interop.Windows\TerraFX.Interop.Windows.projitems*{514ff00e-bbf0-4d55-a47c-eeeb6208adce}*SharedItemsImports = 13
src\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems*{51d5a422-d3a5-4c4d-8a6d-a048940bf279}*SharedItemsImports = 13
+5 -7
ファイルの表示
@@ -124,14 +124,12 @@ public abstract partial class CanvasEffect : ICanvasImage, ICanvasImageInterop.I
this.canvasImage?.Dispose();
this.canvasImage = null;
this.isInvalidated = false;
}
else
{
// Otherwise, just mark the internal state as not being valid anymore. The next
// time the image is requested, the effect graph will be configured if needed.
this.isInvalidated = true;
}
// For both invalidation types, always mark the internal state as not being valid anymore.
// The next time the image is requested, the effect graph will be configured if needed.
// This matches the default value for the field (which is needed for the first realization).
this.isInvalidated = true;
}
}
+2 -2
ファイルの表示
@@ -124,7 +124,7 @@ unsafe partial class PixelShaderEffect<T>
{
*wrapper = null;
return E.E_INVALIDARG;
return D2DERR.D2DERR_WRONG_FACTORY;
}
}
@@ -139,7 +139,7 @@ unsafe partial class PixelShaderEffect<T>
// Register the new wrapper for the input resource. This has to be done manually in this
// case, as the effect is not being realized through the usual path from GetD2DImage.
ResourceManager.RegisterWrapper((IUnknown*)resource, this);
ResourceManager.RegisterWrapper((IUnknown*)resource, @this);
// Unwrap the PixelShaderEffect<T> and return its CCW to the caller
RcwMarshaller.GetNativeObject(@this, wrapper);
+5 -1
ファイルの表示
@@ -1,3 +1,4 @@
using System;
using ComputeSharp.D2D1.Interop;
#if WINDOWS_UWP
using ComputeSharp.D2D1.Uwp.Extensions;
@@ -92,6 +93,9 @@ unsafe partial class PixelShaderEffect<T>
}
else
{
// If the effect is not realized, manually ensure the transform isn't null
default(ArgumentNullException).ThrowIfNull(value);
this.transformMapper = value;
}
}
@@ -196,7 +200,7 @@ unsafe partial class PixelShaderEffect<T>
};
// Map from D2D1_BUFFER_PRECISION to CanvasBufferPrecision, and return null for D2D1_BUFFER_PRECISION_UNKNOWN
return this.d2D1BufferPrecision switch
return d2D1BufferPrecision switch
{
D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_8BPC_UNORM => CanvasBufferPrecision.Precision8UIntNormalized,
D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_8BPC_UNORM_SRGB => CanvasBufferPrecision.Precision8UIntNormalizedSrgb,
+22 -4
ファイルの表示
@@ -1,6 +1,12 @@
using System;
using ComputeSharp.Interop;
using System.Runtime.CompilerServices;
#if WINDOWS_UWP
using ComputeSharp.D2D1.Uwp.Helpers;
#else
using ComputeSharp.D2D1.WinUI.Helpers;
#endif
using TerraFX.Interop.Windows;
#if WINDOWS_UWP
namespace ComputeSharp.D2D1.Uwp;
@@ -41,15 +47,27 @@ partial class PixelShaderEffect<T>
}
/// <inheritdoc/>
void IReferenceTrackedObject.DangerousOnDispose()
unsafe void IReferenceTrackedObject.DangerousOnDispose()
{
// When the effect is disposed, we also unregister it from the resource manager cache. This
// is analogous to what is done when manually unrealizing the effect (eg. when using a new
// device. Without this call, the resource manager would keep registered effects alive for
// the entire process duration, even if their original wrappers are gone (ie. collected).
if (this.d2D1Effect.Get() is not null)
{
ResourceManager.UnregisterWrapper((IUnknown*)this.d2D1Effect.Get());
}
// Release the native D2D objects that were set during realization
this.canvasDevice.Dispose();
this.d2D1RealizationDevice.Dispose();
this.d2D1Effect.Dispose();
// Also release all native resources for the used sources.
// The transform mapper and resource texture managers don't
// need to be disposed, as those could be shared between effects.
// Also release all native resources for the used sources. The transform mapper and
// resource texture managers don't need to be disposed, as those could be shared
// between effects. Note that SourceReference.Dispose() will only release the native
// resources (ie. D2D images and effects), but it will not also dispose the managed
// wrappers (ie. IGraphicsEffectSource objects), as those can be shared as well.
for (int i = 0; i < Sources.Count; i++)
{
Sources.Storage[i].Dispose();
+5 -2
ファイルの表示
@@ -7,12 +7,15 @@ namespace TerraFX.Interop.DirectX;
internal static partial class D2DERR
{
[NativeTypeName("#define D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES _HRESULT_TYPEDEF_(0x88990026L)")]
public const int D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES = unchecked((int)(0x88990026));
[NativeTypeName("#define D2DERR_WRONG_FACTORY _HRESULT_TYPEDEF_(0x88990012L)")]
public const int D2DERR_WRONG_FACTORY = unchecked((int)(0x88990012));
[NativeTypeName("#define D2DERR_CYCLIC_GRAPH _HRESULT_TYPEDEF_(0x88990020L)")]
public const int D2DERR_CYCLIC_GRAPH = unchecked((int)(0x88990020));
[NativeTypeName("#define D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES _HRESULT_TYPEDEF_(0x88990026L)")]
public const int D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES = unchecked((int)(0x88990026));
[NativeTypeName("#define D2DERR_EFFECT_IS_NOT_REGISTERED _HRESULT_TYPEDEF_(0x88990028L)")]
public const int D2DERR_EFFECT_IS_NOT_REGISTERED = unchecked((int)(0x88990028));
}
+121
ファイルの表示
@@ -0,0 +1,121 @@
using ComputeSharp.D2D1.Uwp;
using Microsoft.Graphics.Canvas;
using Microsoft.VisualStudio.TestTools.UnitTesting;
#nullable enable
namespace ComputeSharp.D2D1.UI.Tests;
[TestClass]
[TestCategory("CanvasEffect")]
public partial class CanvasEffectTests
{
[TestMethod]
public unsafe void CanvasEffect_IsRealizedAndInvalidatedCorrectly()
{
EffectWithNoInputs effect = new();
try
{
using (CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f))
using (CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession())
{
drawingSession.DrawImage(effect);
}
Assert.AreEqual(effect.NumberOfBuildEffectGraphCalls, 1);
Assert.AreEqual(effect.NumberOfConfigureEffectGraphCalls, 1);
Assert.AreEqual(effect.NumberOfDisposeCalls, 0);
effect.Value = 42;
using (CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f))
using (CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession())
{
drawingSession.DrawImage(effect);
}
Assert.AreEqual(effect.NumberOfBuildEffectGraphCalls, 1);
Assert.AreEqual(effect.NumberOfConfigureEffectGraphCalls, 2);
Assert.AreEqual(effect.NumberOfDisposeCalls, 0);
effect.ValueWithReload = 123;
using (CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f))
using (CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession())
{
drawingSession.DrawImage(effect);
}
Assert.AreEqual(effect.NumberOfBuildEffectGraphCalls, 2);
Assert.AreEqual(effect.NumberOfConfigureEffectGraphCalls, 3);
Assert.AreEqual(effect.NumberOfDisposeCalls, 0);
}
finally
{
effect.Dispose();
Assert.AreEqual(effect.NumberOfDisposeCalls, 1);
}
}
private sealed class EffectWithNoInputs : CanvasEffect
{
private PixelShaderEffect<ShaderWithNoInputs>? effect;
private int value;
public int Value
{
get => this.value;
set => SetAndInvalidateEffectGraph(ref this.value, value);
}
public int ValueWithReload
{
get => this.value;
set => SetAndInvalidateEffectGraph(ref this.value, value, InvalidationType.Creation);
}
public int NumberOfBuildEffectGraphCalls { get; private set; }
public int NumberOfConfigureEffectGraphCalls { get; private set; }
public int NumberOfDisposeCalls { get; private set; }
protected override ICanvasImage BuildEffectGraph()
{
NumberOfBuildEffectGraphCalls++;
return this.effect = new PixelShaderEffect<ShaderWithNoInputs>();
}
protected override void ConfigureEffectGraph()
{
NumberOfConfigureEffectGraphCalls++;
this.effect!.ConstantBuffer = new ShaderWithNoInputs(this.value);
}
protected override void Dispose(bool disposing)
{
NumberOfDisposeCalls++;
base.Dispose(disposing);
this.effect?.Dispose();
}
}
[D2DInputCount(0)]
[AutoConstructor]
private partial struct ShaderWithNoInputs : ID2D1PixelShader
{
public int Value;
public float4 Execute()
{
return default;
}
}
}
+18
ファイルの表示
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<MSBuildAllProjects Condition="'$(MSBuildVersion)' == '' Or '$(MSBuildVersion)' &lt; '16.0'">$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
<HasSharedItems>true</HasSharedItems>
<SharedGUID>346aeb10-a4ea-427e-8578-f60915db3053</SharedGUID>
</PropertyGroup>
<PropertyGroup Label="Configuration">
<Import_RootNamespace>ComputeSharp.D2D1.UI.Tests</Import_RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)Helpers\Win2DHelper.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\TolerantImageComparer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CanvasEffectTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)PixelShaderEffectTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ShadersTests.cs" />
</ItemGroup>
</Project>
+13
ファイルの表示
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Label="Globals">
<ProjectGuid>346aeb10-a4ea-427e-8578-f60915db3053</ProjectGuid>
<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" />
<PropertyGroup />
<Import Project="ComputeSharp.D2D1.UI.Tests.projitems" Label="Shared" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" />
</Project>
+117
ファイルの表示
@@ -0,0 +1,117 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Runtime.CompilerServices;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Graphics.Canvas;
using Color = Windows.UI.Color;
namespace ComputeSharp.D2D1.UI.Tests.Helpers;
/// <summary>
/// An tolerant image comparer type, inspired from <see href="https://github.com/SixLabors/ImageSharp">ImageSharp</see>.
/// </summary>
internal static class TolerantImageComparer
{
/// <summary>
/// Asserts that two images are equal.
/// </summary>
/// <param name="expected">The reference image.</param>
/// <param name="actual">The expected image.</param>
/// <param name="threshold">The allowed difference threshold for the normalized delta.</param>
public static void AssertEqual(CanvasBitmap expected, CanvasBitmap actual, float threshold)
{
if (expected.SizeInPixels.Width != actual.SizeInPixels.Width ||
expected.SizeInPixels.Height != actual.SizeInPixels.Height)
{
Assert.Fail($"The input images have different sizes: {expected.SizeInPixels} and {actual.SizeInPixels}");
}
Color[] expectedColors = expected.GetPixelColors();
Color[] actualColors = actual.GetPixelColors();
float totalDifference = 0F;
List<PixelDifference> differences = new(20);
for (int i = 0; i < expectedColors.Length; i++)
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static int GetManhattanDistanceInRgbaSpace(ref Color a, ref Color b)
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static int Diff(ushort a, ushort b) => Math.Abs(a - b);
return Diff(a.R, b.R) + Diff(a.G, b.G) + Diff(a.B, b.B) + Diff(a.A, b.A);
}
int d = GetManhattanDistanceInRgbaSpace(ref expectedColors[i], ref actualColors[i]);
if (d > 0)
{
if (differences.Count < 20)
{
int offsetY = (int)(i / expected.SizeInPixels.Width);
int offsetX = (int)(i % expected.SizeInPixels.Width);
PixelDifference diff = new(new Point(offsetX, offsetY), expectedColors[i], actualColors[i]);
differences.Add(diff);
}
totalDifference += d;
}
}
float normalizedDifference = totalDifference / (actual.SizeInPixels.Width * (float)actual.SizeInPixels.Height);
normalizedDifference /= 4F * 65535F;
if (normalizedDifference > threshold)
{
StringBuilder builder = new();
_ = builder.AppendLine($"The input images don't match. Normalized delta: {normalizedDifference}%");
_ = builder.AppendLine($"First {differences.Count} pixel deltas:");
foreach (PixelDifference delta in differences)
{
_ = builder.AppendLine(delta.ToString());
}
Assert.Fail(builder.ToString());
}
}
/// <summary>
/// A simple model repressenting info about a difference between two pixels.
/// </summary>
private readonly struct PixelDifference
{
public PixelDifference(Point position, Color expected, Color actual)
{
this.Position = position;
this.RedDifference = actual.R - expected.R;
this.GreenDifference = actual.G - expected.G;
this.BlueDifference = actual.B - expected.B;
this.AlphaDifference = actual.A - expected.A;
}
public readonly Point Position;
public readonly int RedDifference;
public readonly int GreenDifference;
public readonly int BlueDifference;
public readonly int AlphaDifference;
/// <inheritdoc/>
public override string ToString()
{
return $"[delta({this.RedDifference},{this.GreenDifference},{this.BlueDifference},{this.AlphaDifference}) @ ({this.Position.X},{this.Position.Y})]";
}
}
}
+119
ファイルの表示
@@ -0,0 +1,119 @@
using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
using Microsoft.Graphics.Canvas;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
#nullable enable
namespace ComputeSharp.D2D1.UI.Tests.Helpers;
/// <summary>
/// A helper type to marshal managed objects in unit tests.
/// </summary>
internal static class Win2DHelper
{
/// <summary>
/// Gets the managed wrapper for a given <see cref="ID2D1Image"/> object.
/// </summary>
/// <param name="d2D1Image">The input <see cref="ID2D1Image"/> object to get a wrapper for.</param>
/// <param name="canvasDevice">The realization <see cref="CanvasDevice"/> instance to use.</param>
/// <returns>The resulting managed wrapper for <paramref name="d2D1Image"/>.</returns>
public static unsafe object GetOrCreate(ID2D1Image* d2D1Image, CanvasDevice? canvasDevice = null)
{
IActivationFactory activationFactory = WindowsRuntimeMarshal.GetActivationFactory(typeof(CanvasDevice));
using ComPtr<IUnknown> activationFactoryUnknown = default;
activationFactoryUnknown.Attach((IUnknown*)Marshal.GetIUnknownForObject(activationFactory));
using ComPtr<IUnknown> canvasFactoryNativeUnknown = default;
Guid uuidOfCanvasFactoryNativeUnknown = new("695C440D-04B3-4EDD-BFD9-63E51E9F7202");
//Get the ICanvasFactoryNative object
int hresult = activationFactoryUnknown.CopyTo(&uuidOfCanvasFactoryNativeUnknown, (void**)canvasFactoryNativeUnknown.GetAddressOf());
Marshal.ThrowExceptionForHR(hresult);
using ComPtr<IUnknown> canvasDeviceUnknown = default;
if (canvasDevice is not null)
{
canvasDeviceUnknown.Attach((IUnknown*)Marshal.GetIUnknownForObject(canvasDevice));
}
using ComPtr<IUnknown> canvasDeviceInterfaceUnknown = default;
if (canvasDevice is not null)
{
Guid uuidOfCanvasDeviceInterface = new("A27F0B5D-EC2C-4D4F-948F-0AA1E95E33E6");
// Get the ICanvasDevice object (as an IUnknown* as well)
hresult = canvasDeviceUnknown.CopyTo(&uuidOfCanvasDeviceInterface, (void**)canvasDeviceInterfaceUnknown.GetAddressOf());
}
using ComPtr<IUnknown> wrapperUnknown = default;
// Invoke GetOrCreate to get the inspectable wrapper
hresult = ((delegate* unmanaged[Stdcall]<IUnknown*, IUnknown*, IUnknown*, float, IUnknown**, int>)(*(void***)canvasFactoryNativeUnknown.Get())[6])(
canvasFactoryNativeUnknown.Get(),
canvasDeviceInterfaceUnknown.Get(),
(IUnknown*)d2D1Image,
0,
wrapperUnknown.GetAddressOf());
Marshal.ThrowExceptionForHR(hresult);
// Get or create a managed object for the native object
return Marshal.GetObjectForIUnknown((IntPtr)wrapperUnknown.Get());
}
/// <summary>
/// Gets the D2D image from a given <see cref="ICanvasImage"/> object.
/// </summary>
/// <param name="canvasImage">The input <see cref="ICanvasImage"/> object.</param>
/// <param name="canvasDevice">The realization <see cref="CanvasDevice"/> instance to use.</param>
/// <param name="d2D1Image">The resulting <see cref="ID2D1Image"/> object.</param>
public static unsafe void GetD2DImage(ICanvasImage canvasImage, CanvasDevice canvasDevice, ID2D1Image** d2D1Image)
{
using ComPtr<IUnknown> effectUnknown = default;
effectUnknown.Attach((IUnknown*)Marshal.GetIUnknownForObject(canvasImage));
using ComPtr<IUnknown> canvasImageInteropUnknown = default;
Guid uuidOfCanvasImageInterop = new("E042D1F7-F9AD-4479-A713-67627EA31863");
// Get the ICanvasImageInterop object (as an IUnknown*)
int hresult = effectUnknown.CopyTo(&uuidOfCanvasImageInterop, (void**)canvasImageInteropUnknown.GetAddressOf());
Marshal.ThrowExceptionForHR(hresult);
using ComPtr<IUnknown> canvasDeviceUnknown = default;
canvasDeviceUnknown.Attach((IUnknown*)Marshal.GetIUnknownForObject(canvasDevice));
using ComPtr<IUnknown> canvasDeviceInterfaceUnknown = default;
Guid uuidOfCanvasDeviceInterface = new("A27F0B5D-EC2C-4D4F-948F-0AA1E95E33E6");
// Get the ICanvasDevice object (as an IUnknown* as well)
hresult = canvasDeviceUnknown.CopyTo(&uuidOfCanvasDeviceInterface, (void**)canvasDeviceInterfaceUnknown.GetAddressOf());
Marshal.ThrowExceptionForHR(hresult);
// Invoke GetD2DImage (passing NEVER_INSERT_DPI_COMPENSATION | MINIMAL_REALIZATION | ALLOW_NULL_EFFECT_INPUTS)
hresult = ((delegate* unmanaged[Stdcall]<IUnknown*, IUnknown*, IUnknown*, uint, float, float*, ID2D1Image**, int>)(*(void***)canvasImageInteropUnknown.Get())[4])(
canvasImageInteropUnknown.Get(),
canvasDeviceInterfaceUnknown.Get(),
null,
4 | 8 | 16,
0,
null,
d2D1Image);
Marshal.ThrowExceptionForHR(hresult);
}
}
+514
ファイルの表示
@@ -0,0 +1,514 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.D2D1.Interop;
using ComputeSharp.D2D1.UI.Tests.Helpers;
using ComputeSharp.D2D1.Uwp;
using Microsoft.Graphics.Canvas;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
namespace ComputeSharp.D2D1.UI.Tests;
[TestClass]
[TestCategory("PixelShaderEffect<T>")]
public partial class PixelShaderEffectTests
{
[TestMethod]
public unsafe void ConstantBuffer_IsInitiallySetToDefault()
{
using PixelShaderEffect<ShaderWithSomeProperties> effect = new();
ShaderWithSomeProperties shader = effect.ConstantBuffer;
ShaderWithSomeProperties defaultShader = default;
ReadOnlySpan<byte> actual = new(&shader, sizeof(ShaderWithSomeProperties));
ReadOnlySpan<byte> expected = new(&defaultShader, sizeof(ShaderWithSomeProperties));
// The default constant buffer is set to 0, and it can be retrieved correctly
Assert.IsTrue(actual.SequenceEqual(expected));
}
[TestMethod]
public unsafe void ConstantBuffer_RoundTripsCorrectly()
{
ShaderWithSomeProperties shader = new(
A: 3.14f,
B: 123456,
C: new int2(111, -222),
D: new uint2x2(8888, 123456, 98765, 192837465),
E: new float2(-3.14f, 6.28f));
using PixelShaderEffect<ShaderWithSomeProperties> effect = new() { ConstantBuffer = shader };
ShaderWithSomeProperties roundTripShader = effect.ConstantBuffer;
ReadOnlySpan<byte> expected = new(&shader, sizeof(ShaderWithSomeProperties));
ReadOnlySpan<byte> actual = new(&roundTripShader, sizeof(ShaderWithSomeProperties));
// The resulting constant buffer matches the source, when the effect is not realized
Assert.IsTrue(actual.SequenceEqual(expected));
// Draw the effect, to force realization
using (CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f))
using (CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession())
{
drawingSession.DrawImage(effect);
}
roundTripShader = effect.ConstantBuffer;
actual = new(&roundTripShader, sizeof(ShaderWithSomeProperties));
// The shader also matches when retrieving it through the realized effect
Assert.IsTrue(actual.SequenceEqual(expected));
// Draw the effect on a different device (this forces it to unrealize and re-realize).
// This also acts as a unit test for the device changed logic, since that's used here.
using (CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f))
using (CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession())
{
drawingSession.DrawImage(effect);
}
roundTripShader = effect.ConstantBuffer;
actual = new(&roundTripShader, sizeof(ShaderWithSomeProperties));
// The shader also matches when retrieving it through the realized effect
Assert.IsTrue(actual.SequenceEqual(expected));
}
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void SourcesOutOfRange_ThrowsArgumentOutOfRangeException()
{
using PixelShaderEffect<ShaderWith0Inputs> effect0 = new();
_ = Assert.ThrowsException<ArgumentOutOfRangeException>(() => effect0.Sources[0] = null);
_ = Assert.ThrowsException<ArgumentOutOfRangeException>(() => effect0.Sources[1] = null);
using PixelShaderEffect<ShaderWith1Input> effect1 = new();
effect1.Sources[0] = null;
_ = Assert.ThrowsException<ArgumentOutOfRangeException>(() => effect1.Sources[1] = null);
_ = Assert.ThrowsException<ArgumentOutOfRangeException>(() => effect1.Sources[2] = null);
using PixelShaderEffect<ShaderWith1Input> effect2 = new();
effect2.Sources[0] = null;
effect2.Sources[1] = null;
_ = Assert.ThrowsException<ArgumentOutOfRangeException>(() => effect2.Sources[2] = null);
_ = Assert.ThrowsException<ArgumentOutOfRangeException>(() => effect2.Sources[3] = null);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void NullTransformMapper_UnrealizedEffect_ThrowsArgumentNullException()
{
using PixelShaderEffect<ShaderWith0Inputs> effect = new();
effect.TransformMapper = null!;
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void NullTransformMapper_RealizedEffect_ThrowsArgumentNullException()
{
using PixelShaderEffect<ShaderWith0Inputs> effect = new();
using (CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f))
using (CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession())
{
drawingSession.DrawImage(effect);
}
effect.TransformMapper = null!;
}
[TestMethod]
[ExpectedException(typeof(Exception), AllowDerivedTypes = true)]
public unsafe void GraphCycle_IsDetectedCorrectly()
{
using PixelShaderEffect<ShaderWith0Inputs> effect1 = new();
using PixelShaderEffect<ShaderWith2Inputs> effect2 = new();
using PixelShaderEffect<ShaderWith1Input> effect3 = new();
using PixelShaderEffect<ShaderWith1Input> effect4 = new();
using PixelShaderEffect<ShaderWith2Inputs> effect5 = new();
using PixelShaderEffect<ShaderWith2Inputs> effect6 = new();
using PixelShaderEffect<ShaderWith0Inputs> effect7 = new();
// Build a graph with a cycle in it:
//
// ┌───┐ ┌───┐ ┌───┐
// │ 1 ├──►│ 2 ├──►│ 3 ├──────────┐
// └───┘ └───┘ └───┘ ▼
// ┌───┐ ┌───┐ ▲ │ ┌───┐ ┌───┐
// │ 7 ├──►│ 6 ├─┘ └─►│ 4 ├──►│ 5 │
// └───┘ └───┘ └───┘ └───┘
// ▲ │
// └─────────────────┘
//
// The cycle is 4 -> 6 -> 2 -> 3 -> 4.
effect2.Sources[0] = effect1;
effect2.Sources[1] = effect6;
effect3.Sources[0] = effect2;
effect4.Sources[0] = effect3;
effect5.Sources[0] = effect3;
effect5.Sources[1] = effect4;
effect6.Sources[0] = effect4;
effect6.Sources[1] = effect7;
using ComPtr<ID2D1Image> d2D1Image = default;
// Realize the effect for it to detect a graph cycle. We specifically don't want to draw
// the effect, because in that case we'd still get an exception from D2D, even if the
// effect from ComputeSharp failed to detect a graph cycle. We want to make sure the
// detection and subsequent error is coming from our wrapper, not from D2D's logic.
Win2DHelper.GetD2DImage(effect5, new CanvasDevice(), d2D1Image.GetAddressOf());
}
[TestMethod]
public unsafe void Interop_EffectPropertiesAreForwardedCorrectly()
{
ShaderWithSomePropertiesAndInputs shader = new(-1234567);
using PixelShaderEffect<ShaderWith0Inputs> effect0 = new();
using PixelShaderEffect<ShaderWithSomePropertiesAndInputs> effect1 = new()
{
ConstantBuffer = shader,
CacheOutput = true,
BufferPrecision = CanvasBufferPrecision.Precision32Float,
Sources = { [0] = effect0 }
};
CanvasDevice canvasDevice = new();
using ComPtr<ID2D1Image> d2D1Image = default;
// Realize the effect and get the D2D effect (this will also apply all local properties)
Win2DHelper.GetD2DImage(effect1, canvasDevice, d2D1Image.GetAddressOf());
using ComPtr<ID2D1Effect> d2D1Effect = default;
Marshal.ThrowExceptionForHR(d2D1Image.CopyTo(d2D1Effect.GetAddressOf()));
int constantBufferDataSize = D2D1PixelShader.GetConstantBufferSize<ShaderWithSomePropertiesAndInputs>();
byte* constantBufferData = stackalloc byte[constantBufferDataSize];
int hresult = d2D1Effect.Get()->GetValue(
index: D2D1PixelShaderEffectProperty.ConstantBuffer,
type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_BLOB,
data: constantBufferData,
dataSize: (uint)constantBufferDataSize);
Marshal.ThrowExceptionForHR(hresult);
ReadOnlyMemory<byte> expectedConstantBufferData = D2D1PixelShader.GetConstantBuffer(in shader);
Assert.IsTrue(expectedConstantBufferData.Span.SequenceEqual(new ReadOnlySpan<byte>(constantBufferData, constantBufferDataSize)));
int cacheOutput;
hresult = d2D1Effect.Get()->GetValue(
index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_CACHED,
type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_BOOL,
data: (byte*)&cacheOutput,
dataSize: sizeof(int));
Marshal.ThrowExceptionForHR(hresult);
Assert.AreEqual(1, cacheOutput);
D2D1_BUFFER_PRECISION d2D1BufferPrecision;
hresult = d2D1Effect.Get()->GetValue(
index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_PRECISION,
type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_UNKNOWN,
data: (byte*)&d2D1BufferPrecision,
dataSize: sizeof(D2D1_BUFFER_PRECISION));
Marshal.ThrowExceptionForHR(hresult);
Assert.AreEqual(D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_32BPC_FLOAT, d2D1BufferPrecision);
using ComPtr<ID2D1Image> d2D1Image1 = default;
using ComPtr<ID2D1Image> d2D1Image2 = default;
Win2DHelper.GetD2DImage(effect0, canvasDevice, d2D1Image1.GetAddressOf());
d2D1Effect.Get()->GetInput(0, d2D1Image2.GetAddressOf());
using ComPtr<IUnknown> d2D1Image1Unknown = default;
using ComPtr<IUnknown> d2D1Image2Unknown = default;
Marshal.ThrowExceptionForHR(d2D1Image1.CopyTo(d2D1Image1Unknown.GetAddressOf()));
Marshal.ThrowExceptionForHR(d2D1Image2.CopyTo(d2D1Image2Unknown.GetAddressOf()));
// The image from the effect input should be the same retrieved from the original source wrapper
Assert.IsTrue(d2D1Image1Unknown.Get() == d2D1Image2Unknown.Get());
}
[TestMethod]
public unsafe void Interop_EffectPropertiesAreUpdatedFromNativeEffectCorrectly()
{
ShaderWithSomePropertiesAndInputs shader = new(-1234567);
using PixelShaderEffect<ShaderWith0Inputs> effect0 = new();
using PixelShaderEffect<ShaderWithSomePropertiesAndInputs> effect1 = new();
CanvasDevice canvasDevice = new();
using ComPtr<ID2D1Image> d2D1Image0 = default;
using ComPtr<ID2D1Image> d2D1Image1 = default;
// Realize the effects and get the D2D effects
Win2DHelper.GetD2DImage(effect0, canvasDevice, d2D1Image0.GetAddressOf());
Win2DHelper.GetD2DImage(effect1, canvasDevice, d2D1Image1.GetAddressOf());
using ComPtr<ID2D1Effect> d2D1Effect = default;
Marshal.ThrowExceptionForHR(d2D1Image1.CopyTo(d2D1Effect.GetAddressOf()));
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), in shader);
int cacheOutput = 1;
int hresult = d2D1Effect.Get()->SetValue(
index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_CACHED,
type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_BOOL,
data: (byte*)&cacheOutput,
dataSize: sizeof(int));
Marshal.ThrowExceptionForHR(hresult);
Assert.AreEqual(1, cacheOutput);
D2D1_BUFFER_PRECISION d2D1BufferPrecision = D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_32BPC_FLOAT;
hresult = d2D1Effect.Get()->SetValue(
index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_PRECISION,
type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_UNKNOWN,
data: (byte*)&d2D1BufferPrecision,
dataSize: sizeof(D2D1_BUFFER_PRECISION));
Marshal.ThrowExceptionForHR(hresult);
d2D1Effect.Get()->SetInput(0, d2D1Image0.Get());
Assert.AreEqual(shader.Number, effect1.ConstantBuffer.Number);
Assert.IsTrue(effect1.CacheOutput);
Assert.AreEqual(CanvasBufferPrecision.Precision32Float, effect1.BufferPrecision);
Assert.AreSame(effect0, effect1.Sources[0]);
}
[TestMethod]
public unsafe void Interop_IsWrapperRegisteredCorrectly()
{
using PixelShaderEffect<ShaderWith0Inputs> effect = new();
using ComPtr<ID2D1Image> d2D1Image = default;
Win2DHelper.GetD2DImage(effect, new CanvasDevice(), d2D1Image.GetAddressOf());
object wrapper = Win2DHelper.GetOrCreate(d2D1Image.Get());
Assert.AreSame(effect, wrapper);
}
[TestMethod]
public unsafe void Interop_IsWrapperUnregisteredCorrectly_FromExplicitDispose()
{
using ComPtr<ID2D1Image> d2D1Image = default;
PixelShaderEffect<ShaderWith0Inputs> effect = new();
CanvasDevice canvasDevice = new();
try
{
Win2DHelper.GetD2DImage(effect, canvasDevice, d2D1Image.GetAddressOf());
}
finally
{
effect.Dispose();
}
object wrapper = Win2DHelper.GetOrCreate(d2D1Image.Get(), canvasDevice);
Assert.IsTrue(wrapper is PixelShaderEffect<ShaderWith0Inputs>);
Assert.AreNotSame(effect, wrapper);
// Ensure the new wrapper is disposed as well
using PixelShaderEffect<ShaderWith0Inputs> _ = (PixelShaderEffect<ShaderWith0Inputs>)wrapper;
}
[TestMethod]
[ExpectedException(typeof(Exception), AllowDerivedTypes = true)]
public unsafe void Interop_IsWrapperUnregisteredCorrectly_FromExplicitDispose_FailsWithNoDevice()
{
using ComPtr<ID2D1Image> d2D1Image = default;
using (PixelShaderEffect<ShaderWith0Inputs> effect = new())
{
Win2DHelper.GetD2DImage(effect, new CanvasDevice(), d2D1Image.GetAddressOf());
}
_ = Win2DHelper.GetOrCreate(d2D1Image.Get());
}
[TestMethod]
[ExpectedException(typeof(Exception), AllowDerivedTypes = true)]
public unsafe void Interop_IsWrapperUnregisteredCorrectly_FromFinalizer_FailsWithNoDevice()
{
using ComPtr<ID2D1Image> d2D1Image = default;
[MethodImpl(MethodImplOptions.NoInlining)]
static void Test(ID2D1Image** d2D1Image)
{
PixelShaderEffect<ShaderWith0Inputs> effect = new();
Win2DHelper.GetD2DImage(effect, new CanvasDevice(), d2D1Image);
}
Test(d2D1Image.GetAddressOf());
GC.Collect();
GC.WaitForPendingFinalizers();
_ = Win2DHelper.GetOrCreate(d2D1Image.Get());
}
[TestMethod]
public unsafe void Interop_IsWrapperFactoryRegisteredCorrectlyAndWorking()
{
using PixelShaderEffect<ShaderWith0Inputs> effect = new();
CanvasDevice canvasDevice1 = new();
CanvasDevice canvasDevice2 = new();
using ComPtr<ID2D1Image> d2D1Image1 = default;
using ComPtr<ID2D1Image> d2D1Image2 = default;
Win2DHelper.GetD2DImage(effect, canvasDevice1, d2D1Image1.GetAddressOf());
Win2DHelper.GetD2DImage(effect, canvasDevice2, d2D1Image2.GetAddressOf());
// The first resource is orphaned, so a new wrapper will be created
object wrapper1 = Win2DHelper.GetOrCreate(d2D1Image1.Get(), canvasDevice1);
Assert.IsTrue(wrapper1 is PixelShaderEffect<ShaderWith0Inputs>);
Assert.AreNotSame(wrapper1, effect);
// Property dispose the new wrapper as well
using PixelShaderEffect<ShaderWith0Inputs> _ = (PixelShaderEffect<ShaderWith0Inputs>)wrapper1;
// Getting the same wrapper again should return the newly created one
object wrapper1FromCache = Win2DHelper.GetOrCreate(d2D1Image1.Get(), canvasDevice1);
Assert.AreSame(wrapper1, wrapper1FromCache);
using ComPtr<ID2D1Image> d2D1Image1FromNewWrapper = default;
// Get the realized image from the newly created wrapper
Win2DHelper.GetD2DImage((ICanvasImage)wrapper1, canvasDevice1, d2D1Image1FromNewWrapper.GetAddressOf());
using ComPtr<IUnknown> d2D1Image1Unknown = default;
using ComPtr<IUnknown> d2D1Image1FromNewWrapperUnknown = default;
Marshal.ThrowExceptionForHR(d2D1Image1.CopyTo(d2D1Image1Unknown.GetAddressOf()));
Marshal.ThrowExceptionForHR(d2D1Image1FromNewWrapper.CopyTo(d2D1Image1FromNewWrapperUnknown.GetAddressOf()));
// The retrieved image should be the same one the new wrapper was created from
Assert.IsTrue(d2D1Image1Unknown.Get() == d2D1Image1FromNewWrapperUnknown.Get());
// The second resource is currently registered, so it returns the local wrapper
object wrapper2 = Win2DHelper.GetOrCreate(d2D1Image2.Get());
Assert.AreSame(effect, wrapper2);
}
[TestMethod]
public unsafe void Interop_WrapperFactoryDetectsMismatchedDevices()
{
using PixelShaderEffect<ShaderWith0Inputs> effect = new();
CanvasDevice canvasDevice1 = new();
CanvasDevice canvasDevice2 = new();
using ComPtr<ID2D1Image> d2D1Image1 = default;
using ComPtr<ID2D1Image> d2D1Image2 = default;
Win2DHelper.GetD2DImage(effect, canvasDevice1, d2D1Image1.GetAddressOf());
Win2DHelper.GetD2DImage(effect, canvasDevice2, d2D1Image2.GetAddressOf());
// The factory should detect we're passing an incompatible device for the resource
try
{
_ = Win2DHelper.GetOrCreate(d2D1Image1.Get(), canvasDevice2);
Assert.Fail();
}
catch (Exception e)
{
Assert.AreEqual(e.HResult, D2DERR.D2DERR_WRONG_FACTORY);
}
}
[D2DInputCount(0)]
[AutoConstructor]
private partial struct ShaderWithSomeProperties : ID2D1PixelShader
{
public float A;
public int B;
public int2 C;
public uint2x2 D;
public float2 E;
public float4 Execute()
{
return default;
}
}
[D2DInputCount(1)]
[AutoConstructor]
private partial struct ShaderWithSomePropertiesAndInputs : ID2D1PixelShader
{
public int Number;
public float4 Execute()
{
return D2D.GetInput(0);
}
}
[D2DInputCount(0)]
private partial struct ShaderWith0Inputs : ID2D1PixelShader
{
public float4 Execute()
{
return default;
}
}
[D2DInputCount(1)]
[D2DInputSimple(0)]
private partial struct ShaderWith1Input : ID2D1PixelShader
{
public float4 Execute()
{
return D2D.GetInput(0);
}
}
[D2DInputCount(2)]
[D2DInputSimple(0)]
[D2DInputSimple(1)]
private partial struct ShaderWith2Inputs : ID2D1PixelShader
{
public float4 Execute()
{
return D2D.GetInput(0) + D2D.GetInput(1);
}
}
}
+144
ファイルの表示
@@ -0,0 +1,144 @@
using System;
using System.IO;
using System.Threading.Tasks;
using ComputeSharp.D2D1.UI.Tests.Helpers;
using ComputeSharp.D2D1.Uwp;
using ComputeSharp.SwapChain.Shaders.D2D1;
using Microsoft.Graphics.Canvas;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Windows.Storage;
using Windows.UI;
#nullable enable
namespace ComputeSharp.D2D1.UI.Tests;
[TestClass]
[TestCategory("Shaders")]
public class ShadersTests
{
[TestMethod]
[DataRow(WrapperType.PixelShaderEffect)]
[DataRow(WrapperType.CanvasEffect)]
public async Task HelloWorld(WrapperType wrapperType)
{
await RunTestAsync<HelloWorld>(wrapperType);
}
[TestMethod]
[DataRow(WrapperType.PixelShaderEffect)]
[DataRow(WrapperType.CanvasEffect)]
public async Task ColorfulInfinity(WrapperType wrapperType)
{
await RunTestAsync<ColorfulInfinity>(wrapperType);
}
[TestMethod]
[DataRow(WrapperType.PixelShaderEffect)]
[DataRow(WrapperType.CanvasEffect)]
public async Task FractalTiling(WrapperType wrapperType)
{
await RunTestAsync<FractalTiling>(wrapperType);
}
[TestMethod]
[DataRow(WrapperType.PixelShaderEffect)]
[DataRow(WrapperType.CanvasEffect)]
public async Task MengerJourney(WrapperType wrapperType)
{
await RunTestAsync<MengerJourney>(wrapperType, 0.000011f);
}
[TestMethod]
[DataRow(WrapperType.PixelShaderEffect)]
[DataRow(WrapperType.CanvasEffect)]
public async Task Octagrams(WrapperType wrapperType)
{
await RunTestAsync<Octagrams>(wrapperType);
}
[TestMethod]
[DataRow(WrapperType.PixelShaderEffect)]
[DataRow(WrapperType.CanvasEffect)]
public async Task ProteanClouds(WrapperType wrapperType)
{
await RunTestAsync<ProteanClouds>(wrapperType);
}
[TestMethod]
[DataRow(WrapperType.PixelShaderEffect)]
[DataRow(WrapperType.CanvasEffect)]
public async Task TerracedHills(WrapperType wrapperType)
{
await RunTestAsync<TerracedHills>(wrapperType, 0.000026f);
}
private static async Task RunTestAsync<T>(WrapperType wrapperType, float threshold = 0.00001f)
where T : unmanaged, ID2D1PixelShader
{
T shader = (T)Activator.CreateInstance(typeof(T), 0f, new int2(1280, 720))!;
// Either create the effect directly, or a canvas effect
using ICanvasImage canvasImage = wrapperType switch
{
WrapperType.PixelShaderEffect => new PixelShaderEffect<T>() { ConstantBuffer = shader },
_ => new TestCanvasEffect<T> { ConstantBuffer = shader }
};
Color[] pixelColors;
using CanvasDevice canvasDevice = new();
// Compute the resulting image
using (CanvasRenderTarget renderTarget = new(canvasDevice, 1280, 720, 96.0f))
{
// Draw the shader on the render target
using (CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession())
{
drawingSession.DrawImage(canvasImage);
}
// Get the BGRA32 pixel data from the render target
pixelColors = renderTarget.GetPixelColors();
}
StorageFile imageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri($"ms-appx:///Assets/Shaders/{typeof(T).Name}.png"));
// Retrieve the expected image
using Stream stream = await imageFile.OpenStreamForReadAsync();
using CanvasBitmap expected = await CanvasBitmap.LoadAsync(canvasDevice, stream.AsRandomAccessStream());
using CanvasBitmap actual = CanvasBitmap.CreateFromColors(canvasDevice, pixelColors, 1280, 720);
TolerantImageComparer.AssertEqual(expected, actual, threshold);
}
private sealed class TestCanvasEffect<T> : CanvasEffect
where T : unmanaged, ID2D1PixelShader
{
private PixelShaderEffect<T>? effect;
private T constantBuffer;
public T ConstantBuffer
{
get => this.constantBuffer;
set => SetAndInvalidateEffectGraph(ref this.constantBuffer, value);
}
protected override ICanvasImage BuildEffectGraph()
{
return this.effect = new PixelShaderEffect<T>();
}
protected override void ConfigureEffectGraph()
{
this.effect!.ConstantBuffer = this.constantBuffer;
}
}
public enum WrapperType
{
PixelShaderEffect,
CanvasEffect
}
}
バイナリファイルは表示されません。

変更後

幅:  |  高さ:  |  サイズ: 1.4 KiB

バイナリファイルは表示されません。

変更後

幅:  |  高さ:  |  サイズ: 7.5 KiB

バイナリファイルは表示されません。

変更後

幅:  |  高さ:  |  サイズ: 2.9 KiB

バイナリファイルは表示されません。

変更後

幅:  |  高さ:  |  サイズ: 1.6 KiB

バイナリファイルは表示されません。

変更後

幅:  |  高さ:  |  サイズ: 1.2 KiB

バイナリファイルは表示されません。

変更後

幅:  |  高さ:  |  サイズ: 1.4 KiB

バイナリファイルは表示されません。

変更後

幅:  |  高さ:  |  サイズ: 3.1 KiB

+160
ファイルの表示
@@ -0,0 +1,160 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x64</Platform>
<ProjectGuid>{4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}</ProjectGuid>
<OutputType>AppContainerExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ComputeSharp.D2D1.Uwp.Tests</RootNamespace>
<AssemblyName>ComputeSharp.D2D1.Uwp.Tests</AssemblyName>
<DefaultLanguage>en-US</DefaultLanguage>
<TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
<TargetPlatformVersion>10.0.22621.0</TargetPlatformVersion>
<TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>
<MinimumVisualStudioVersion>14</MinimumVisualStudioVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<UnitTestPlatformVersion Condition="'$(UnitTestPlatformVersion)' == ''">$(VisualStudioVersion)</UnitTestPlatformVersion>
<AppxPackageSigningEnabled>false</AppxPackageSigningEnabled>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|ARM64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\ARM64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<NoWarn>$(NoWarn);2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>ARM64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|ARM64'">
<OutputPath>bin\ARM64\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>$(NoWarn);2008</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>ARM64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<NoWarn>$(NoWarn);2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>$(NoWarn);2008</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup>
<RestoreProjectStyle>PackageReference</RestoreProjectStyle>
</PropertyGroup>
<ItemGroup>
<SDKReference Include="TestPlatform.Universal, Version=$(UnitTestPlatformVersion)" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="UnitTestApp.xaml.cs">
<DependentUpon>UnitTestApp.xaml</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="UnitTestApp.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
</ItemGroup>
<ItemGroup>
<AppxManifest Include="Package.appxmanifest">
<SubType>Designer</SubType>
</AppxManifest>
</ItemGroup>
<ItemGroup>
<Content Include="..\ComputeSharp.Tests\Assets\ColorfulInfinity.png">
<Link>Assets\Shaders\ColorfulInfinity.png</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="..\ComputeSharp.Tests\Assets\FractalTiling.png">
<Link>Assets\Shaders\FractalTiling.png</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="..\ComputeSharp.Tests\Assets\HelloWorld.png">
<Link>Assets\Shaders\HelloWorld.png</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="..\ComputeSharp.Tests\Assets\MengerJourney.png">
<Link>Assets\Shaders\MengerJourney.png</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="..\ComputeSharp.Tests\Assets\Octagrams.png">
<Link>Assets\Shaders\Octagrams.png</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="..\ComputeSharp.Tests\Assets\ProteanClouds.png">
<Link>Assets\Shaders\ProteanClouds.png</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="..\ComputeSharp.Tests\Assets\TerracedHills.png">
<Link>Assets\Shaders\TerracedHills.png</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="Properties\Default.rd.xml" />
<Content Include="Assets\LockScreenLogo.scale-200.png" />
<Content Include="Assets\SplashScreen.scale-200.png" />
<Content Include="Assets\Square150x150Logo.scale-200.png" />
<Content Include="Assets\Square44x44Logo.scale-200.png" />
<Content Include="Assets\Square44x44Logo.targetsize-24_altform-unplated.png" />
<Content Include="Assets\StoreLogo.png" />
<Content Include="Assets\Wide310x150Logo.scale-200.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform">
<Version>6.2.14</Version>
</PackageReference>
<PackageReference Include="MSTest.TestAdapter">
<Version>2.2.7</Version>
</PackageReference>
<PackageReference Include="MSTest.TestFramework">
<Version>2.2.7</Version>
</PackageReference>
<PackageReference Include="PolySharp">
<Version>1.13.1</Version>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\ComputeSharp.Core.SourceGenerators\ComputeSharp.Core.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
<ProjectReference Include="..\..\src\ComputeSharp.Core\ComputeSharp.Core.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.D2D1.SourceGenerators\ComputeSharp.D2D1.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
<ProjectReference Include="..\..\src\ComputeSharp.D2D1.Uwp\ComputeSharp.D2D1.Uwp.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.D2D1\ComputeSharp.D2D1.csproj" />
</ItemGroup>
<Import Project="..\ComputeSharp.D2D1.UI.Tests\ComputeSharp.D2D1.UI.Tests.projitems" Label="Shared" />
<Import Project="..\..\samples\ComputeSharp.SwapChain.Shaders.D2D1.Shared\ComputeSharp.SwapChain.Shaders.D2D1.Shared.projitems" Label="Shared" />
<Import Project="..\..\src\TerraFX.Interop.Windows.D2D1\TerraFX.Interop.Windows.D2D1.projitems" Label="Shared" />
<Import Project="..\..\src\ComputeSharp.NetStandard\ComputeSharp.NetStandard.projitems" Label="Shared" />
<PropertyGroup Condition=" '$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' &lt; '14.0' ">
<VisualStudioVersion>14.0</VisualStudioVersion>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets" />
</Project>
+44
ファイルの表示
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="utf-8"?>
<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
IgnorableNamespaces="uap mp">
<Identity Name="683f5570-5e7b-4565-aee0-7caf424526f1"
Publisher="CN=sergiopedri"
Version="1.0.0.0" />
<mp:PhoneIdentity PhoneProductId="683f5570-5e7b-4565-aee0-7caf424526f1" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
<Properties>
<DisplayName>ComputeSharp.D2D1.Uwp.Tests</DisplayName>
<PublisherDisplayName>sergiopedri</PublisherDisplayName>
<Logo>Assets\StoreLogo.png</Logo>
</Properties>
<Dependencies>
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0" />
</Dependencies>
<Resources>
<Resource Language="x-generate" />
</Resources>
<Applications>
<Application
Id="vstest.executionengine.universal.App"
Executable="$targetnametoken$.exe"
EntryPoint="ComputeSharp.D2D1.Uwp.Tests.App" >
<uap:VisualElements
AppListEntry="none"
DisplayName="ComputeSharp.D2D1.Uwp.Tests"
Square150x150Logo="Assets\Square150x150Logo.png"
Square44x44Logo="Assets\Square44x44Logo.png"
Description="ComputeSharp.D2D1.Uwp.Tests"
BackgroundColor="transparent">
<uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png"/>
<uap:SplashScreen Image="Assets\SplashScreen.png" />
</uap:VisualElements>
</Application>
</Applications>
</Package>
+16
ファイルの表示
@@ -0,0 +1,16 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("ComputeSharp.D2D1.Uwp.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ComputeSharp.D2D1.Uwp.Tests")]
[assembly: AssemblyCopyright("Copyright © 2023")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyMetadata("TargetPlatform","UAP")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)]
+22
ファイルの表示
@@ -0,0 +1,22 @@
<!--
This file contains Runtime Directives used by .NET Native. The defaults here are suitable for most
developers. However, you can modify these parameters to modify the behavior of the .NET Native
optimizer.
Runtime Directives are documented at https://go.microsoft.com/fwlink/?LinkID=391919
To fully enable reflection for App1.MyClass and all of its public/private members
<Type Name="App1.MyClass" Dynamic="Required All"/>
To enable dynamic creation of the specific instantiation of AppClass<T> over System.Int32
<TypeInstantiation Name="App1.AppClass" Arguments="System.Int32" Activate="Required Public" />
Using the Namespace directive to apply reflection policy to all the types in a particular namespace
<Namespace Name="DataClasses.ViewModels" Serialize="All" />
-->
<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
<Application>
<Assembly Name="*Application*" Dynamic="Required All" />
</Application>
</Directives>
+4
ファイルの表示
@@ -0,0 +1,4 @@
<Application
x:Class="ComputeSharp.D2D1.Uwp.Tests.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" />
+31
ファイルの表示
@@ -0,0 +1,31 @@
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace ComputeSharp.D2D1.Uwp.Tests;
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
public sealed partial class App : Application
{
/// <summary>
/// Creates a new <see cref="App"/> instance.
/// </summary>
public App()
{
InitializeComponent();
}
/// <inheritdoc/>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
Window.Current.Content ??= new Frame();
Microsoft.VisualStudio.TestPlatform.TestExecutor.UnitTestClient.CreateDefaultUI();
Window.Current.Activate();
Microsoft.VisualStudio.TestPlatform.TestExecutor.UnitTestClient.Run(e.Arguments);
}
}
+3
ファイルの表示
@@ -85,6 +85,7 @@ internal static class TolerantImageComparer
if (differences.Count < 20)
{
PixelDifference diff = new(new Point(x, y), aBuffer[x], bBuffer[x]);
differences.Add(diff);
}
@@ -94,11 +95,13 @@ internal static class TolerantImageComparer
}
float normalizedDifference = totalDifference / (actual.Width * (float)actual.Height);
normalizedDifference /= 4F * 65535F;
if (normalizedDifference > threshold)
{
StringBuilder builder = new();
_ = builder.AppendLine($"The input images don't match. Normalized delta: {normalizedDifference}%");
_ = builder.AppendLine($"First {differences.Count} pixel deltas:");
+3
ファイルの表示
@@ -6,6 +6,9 @@
<!-- Test projects never need to be packaged -->
<IsPackable>false</IsPackable>
<!-- Ignore warnings for public fields (TerraFX polyfills) -->
<NoWarn>$(NoWarn);CS0649</NoWarn>
<!-- Unit tests don't need public XML docs -->
<NoWarn>$(NoWarn);CS1591</NoWarn>