参照されないプロジェクトを削除しビルド構成を整理
検索条件に一致するファイルはありません
@@ -1,16 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MSTest" Version="3.8.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.Core\ComputeSharp.Core.csproj" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.Core.SourceGenerators\ComputeSharp.Core.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.D2D1\ComputeSharp.D2D1.csproj" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.D2D1.SourceGenerators\ComputeSharp.D2D1.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,193 +0,0 @@
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeSharp.D2D1.Interop;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests.AssemblyLevelAttributes;
|
||||
|
||||
[TestClass]
|
||||
public partial class D2D1PixelShaderTests
|
||||
{
|
||||
[TestMethod]
|
||||
public unsafe void ShaderWithAssemblyLevelAttributes()
|
||||
{
|
||||
ReadOnlyMemory<byte> bytecode = D2D1PixelShader.LoadBytecode<ShaderWithNoCompileAttributes>();
|
||||
|
||||
// Verify the shader was precompiled
|
||||
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager<byte>? manager));
|
||||
Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
|
||||
|
||||
// Compile with the same assembly level options
|
||||
bytecode = D2D1PixelShader.LoadBytecode<ShaderWithNoCompileAttributes>(
|
||||
shaderProfile: D2D1ShaderProfile.PixelShader41,
|
||||
compileOptions: D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2 | D2D1CompileOptions.PartialPrecision);
|
||||
|
||||
// Verify the same bytecode is returned
|
||||
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
|
||||
Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
|
||||
|
||||
// Incorrect profile
|
||||
bytecode = D2D1PixelShader.LoadBytecode<ShaderWithNoCompileAttributes>(D2D1ShaderProfile.PixelShader50);
|
||||
|
||||
Assert.IsFalse(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager<byte>? _));
|
||||
Assert.IsTrue(MemoryMarshal.TryGetArray(bytecode, out ArraySegment<byte> segment));
|
||||
Assert.AreEqual(0, segment.Offset);
|
||||
Assert.IsTrue(segment.Count > 0);
|
||||
|
||||
// Incorrect options
|
||||
bytecode = D2D1PixelShader.LoadBytecode<ShaderWithNoCompileAttributes>(D2D1CompileOptions.Default);
|
||||
|
||||
Assert.IsFalse(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager<byte>? _));
|
||||
Assert.IsTrue(MemoryMarshal.TryGetArray(bytecode, out segment));
|
||||
Assert.AreEqual(0, segment.Offset);
|
||||
Assert.IsTrue(segment.Count > 0);
|
||||
}
|
||||
|
||||
[D2DInputCount(3)]
|
||||
[D2DInputSimple(0)]
|
||||
[D2DInputSimple(1)]
|
||||
[D2DInputSimple(2)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct ShaderWithNoCompileAttributes : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
float4 dst = D2D.GetInput(0);
|
||||
float4 src = D2D.GetInput(1);
|
||||
float4 srcMask = D2D.GetInput(2);
|
||||
float4 result = ((1 - srcMask) * dst) + (srcMask * src);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void ShaderWithAssemblyLevelAttributesAndOverriddenProfile()
|
||||
{
|
||||
ReadOnlyMemory<byte> bytecode = D2D1PixelShader.LoadBytecode<ShaderWithOverriddenProfile>();
|
||||
|
||||
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager<byte>? manager));
|
||||
Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
|
||||
|
||||
// Try to recompile with the correct combined options
|
||||
bytecode = D2D1PixelShader.LoadBytecode<ShaderWithOverriddenProfile>(
|
||||
shaderProfile: D2D1ShaderProfile.PixelShader50,
|
||||
compileOptions: D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2 | D2D1CompileOptions.PartialPrecision);
|
||||
|
||||
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
|
||||
Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
|
||||
|
||||
// Incorrect profile (overridden profile)
|
||||
bytecode = D2D1PixelShader.LoadBytecode<ShaderWithOverriddenProfile>(
|
||||
shaderProfile: D2D1ShaderProfile.PixelShader41,
|
||||
compileOptions: D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2 | D2D1CompileOptions.PartialPrecision);
|
||||
|
||||
Assert.IsFalse(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager<byte>? _));
|
||||
Assert.IsTrue(MemoryMarshal.TryGetArray(bytecode, out ArraySegment<byte> segment));
|
||||
Assert.AreEqual(0, segment.Offset);
|
||||
Assert.IsTrue(segment.Count > 0);
|
||||
}
|
||||
|
||||
[D2DInputCount(3)]
|
||||
[D2DInputSimple(0)]
|
||||
[D2DInputSimple(1)]
|
||||
[D2DInputSimple(2)]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct ShaderWithOverriddenProfile : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
float4 dst = D2D.GetInput(0);
|
||||
float4 src = D2D.GetInput(1);
|
||||
float4 srcMask = D2D.GetInput(2);
|
||||
float4 result = ((1 - srcMask) * dst) + (srcMask * src);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void ShaderWithAssemblyLevelAttributesAndOverriddenOptions()
|
||||
{
|
||||
ReadOnlyMemory<byte> bytecode = D2D1PixelShader.LoadBytecode<ShaderWithOverriddenOptions>();
|
||||
|
||||
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager<byte>? manager));
|
||||
Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
|
||||
|
||||
// Try to recompile with the correct combined options
|
||||
bytecode = D2D1PixelShader.LoadBytecode<ShaderWithOverriddenOptions>(
|
||||
shaderProfile: D2D1ShaderProfile.PixelShader41,
|
||||
compileOptions: D2D1CompileOptions.Debug | D2D1CompileOptions.AvoidFlowControl | D2D1CompileOptions.PartialPrecision);
|
||||
|
||||
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
|
||||
Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
|
||||
|
||||
// Incorrect profile (overridden compile options)
|
||||
bytecode = D2D1PixelShader.LoadBytecode<ShaderWithOverriddenOptions>(
|
||||
shaderProfile: D2D1ShaderProfile.PixelShader41,
|
||||
compileOptions: D2D1CompileOptions.Default);
|
||||
|
||||
Assert.IsFalse(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager<byte>? _));
|
||||
Assert.IsTrue(MemoryMarshal.TryGetArray(bytecode, out ArraySegment<byte> segment));
|
||||
Assert.AreEqual(0, segment.Offset);
|
||||
Assert.IsTrue(segment.Count > 0);
|
||||
}
|
||||
|
||||
[D2DInputCount(3)]
|
||||
[D2DInputSimple(0)]
|
||||
[D2DInputSimple(1)]
|
||||
[D2DInputSimple(2)]
|
||||
[D2DCompileOptions(D2D1CompileOptions.Debug | D2D1CompileOptions.AvoidFlowControl | D2D1CompileOptions.PartialPrecision)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct ShaderWithOverriddenOptions : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
float4 dst = D2D.GetInput(0);
|
||||
float4 src = D2D.GetInput(1);
|
||||
float4 srcMask = D2D.GetInput(2);
|
||||
float4 result = ((1 - srcMask) * dst) + (srcMask * src);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void ShaderWithAssemblyLevelAttributesAndEverythingOverridden()
|
||||
{
|
||||
ReadOnlyMemory<byte> bytecode = D2D1PixelShader.LoadBytecode<ShaderWithOverriddenProfileAndOptions>();
|
||||
|
||||
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager<byte>? manager));
|
||||
Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
|
||||
|
||||
// Try to get the new bytecode
|
||||
bytecode = D2D1PixelShader.LoadBytecode<ShaderWithOverriddenProfileAndOptions>(
|
||||
shaderProfile: D2D1ShaderProfile.PixelShader50,
|
||||
compileOptions: D2D1CompileOptions.Debug | D2D1CompileOptions.AvoidFlowControl | D2D1CompileOptions.PartialPrecision);
|
||||
|
||||
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
|
||||
Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
|
||||
}
|
||||
|
||||
[D2DInputCount(3)]
|
||||
[D2DInputSimple(0)]
|
||||
[D2DInputSimple(1)]
|
||||
[D2DInputSimple(2)]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DCompileOptions(D2D1CompileOptions.Debug | D2D1CompileOptions.AvoidFlowControl | D2D1CompileOptions.PartialPrecision)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct ShaderWithOverriddenProfileAndOptions : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
float4 dst = D2D.GetInput(0);
|
||||
float4 src = D2D.GetInput(1);
|
||||
float4 srcMask = D2D.GetInput(2);
|
||||
float4 result = ((1 - srcMask) * dst) + (srcMask * src);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
[assembly: D2DShaderProfile(D2D1ShaderProfile.PixelShader41)]
|
||||
[assembly: D2DCompileOptions(D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2 | D2D1CompileOptions.PartialPrecision)]
|
||||
@@ -1,37 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<DefineConstants>$(DefineConstants);D2D1_TESTS</DefineConstants>
|
||||
|
||||
<!--
|
||||
Temporarily suppress warnings about packages with security vulnerabilities coming from
|
||||
transitive dependencies of the 'Microsoft.CodeAnalysis.CSharp' testing packages. This
|
||||
can be removed once new stable releases of those packages are shipped. We don't want
|
||||
to add a new more recent top-level dependency to guard against binary breaking changes.
|
||||
-->
|
||||
<NoWarn>$(NoWarn);NU1903</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Basic.Reference.Assemblies.Net80" Version="1.8.0" />
|
||||
<PackageReference Include="MSTest" Version="3.8.3" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Analyzer.Testing" Version="1.1.2" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.CodeFix.Testing" Version="1.1.2" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.12.0" />
|
||||
|
||||
<!-- Top-level override to fix address security vulnerability warnings -->
|
||||
<PackageReference Include="System.Formats.Asn1" Version="9.0.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.Core\ComputeSharp.Core.csproj" Aliases="Core" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.D2D1\ComputeSharp.D2D1.csproj" Aliases="D2D1" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.D2D1.CodeFixers\ComputeSharp.D2D1.CodeFixers.csproj" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.D2D1.SourceGenerators\ComputeSharp.D2D1.SourceGenerators.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\ComputeSharp.Tests.SourceGenerators\Helpers\CSharpAnalyzerTest{TAnalyzer}.cs" Link="Helpers\CSharpAnalyzerTest{TAnalyzer}.cs" />
|
||||
<Compile Include="..\ComputeSharp.Tests.SourceGenerators\Helpers\CSharpGeneratorTest{TGenerator}.cs" Link="Helpers\CSharpGeneratorTest{TGenerator}.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,64 +0,0 @@
|
||||
using ComputeSharp.D2D1.SourceGenerators;
|
||||
using ComputeSharp.Tests.SourceGenerators.Helpers;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests.SourceGenerators;
|
||||
|
||||
[TestClass]
|
||||
public class Test_D2DPixelShaderDescriptorGenerator_Diagnostics
|
||||
{
|
||||
[TestMethod]
|
||||
public void MissingD2DRequiresDoublePrecisionSupportAttribute()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp;
|
||||
using ComputeSharp.D2D1;
|
||||
using float4 = global::ComputeSharp.Float4;
|
||||
|
||||
namespace MyNamespace;
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct MyShader : ID2D1PixelShader
|
||||
{
|
||||
private readonly float time;
|
||||
|
||||
public float4 Execute()
|
||||
{
|
||||
return (float)(time * 2.0);
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
CSharpGeneratorTest<D2DPixelShaderDescriptorGenerator>.VerifyDiagnostics(source, "CMPSD2D0080");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UnnecessaryD2DRequiresDoublePrecisionSupportAttribute()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp;
|
||||
using ComputeSharp.D2D1;
|
||||
using float4 = global::ComputeSharp.Float4;
|
||||
|
||||
namespace MyNamespace;
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DRequiresDoublePrecisionSupport]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct MyShader : ID2D1PixelShader
|
||||
{
|
||||
private readonly float time;
|
||||
|
||||
public float4 Execute()
|
||||
{
|
||||
return (float)(time * 2.0f);
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
CSharpGeneratorTest<D2DPixelShaderDescriptorGenerator>.VerifyDiagnostics(source, "CMPSD2D0081");
|
||||
}
|
||||
}
|
||||
@@ -1,202 +0,0 @@
|
||||
using ComputeSharp.D2D1.SourceGenerators;
|
||||
using ComputeSharp.Tests.SourceGenerators.Helpers;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests.SourceGenerators;
|
||||
|
||||
[TestClass]
|
||||
public class Test_D2DPixelShaderDescriptorGenerator_Incrementality
|
||||
{
|
||||
[TestMethod]
|
||||
public void ModifiedStatement_ModifiesOutput()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp;
|
||||
using ComputeSharp.D2D1;
|
||||
using float4 = global::ComputeSharp.Float4;
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct MyShader : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
const string updatedSource = """
|
||||
using ComputeSharp;
|
||||
using ComputeSharp.D2D1;
|
||||
using float4 = global::ComputeSharp.Float4;
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct MyShader : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
// Some dummy comment
|
||||
return 42;
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
CSharpGeneratorTest<D2DPixelShaderDescriptorGenerator>.VerifyIncrementalSteps(
|
||||
source,
|
||||
updatedSource,
|
||||
executeReason: IncrementalStepRunReason.Modified,
|
||||
diagnosticsReason: null,
|
||||
outputReason: IncrementalStepRunReason.Modified,
|
||||
diagnosticsSourceReason: null,
|
||||
sourceReason: IncrementalStepRunReason.Modified);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AddedComment_DoesNotModifyOutput()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp;
|
||||
using ComputeSharp.D2D1;
|
||||
using float4 = global::ComputeSharp.Float4;
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct MyShader : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
const string updatedSource = """
|
||||
using ComputeSharp;
|
||||
using ComputeSharp.D2D1;
|
||||
using float4 = global::ComputeSharp.Float4;
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct MyShader : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
// Some dummy comment
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
CSharpGeneratorTest<D2DPixelShaderDescriptorGenerator>.VerifyIncrementalSteps(
|
||||
source,
|
||||
updatedSource,
|
||||
executeReason: IncrementalStepRunReason.Unchanged,
|
||||
diagnosticsReason: null,
|
||||
outputReason: IncrementalStepRunReason.Cached,
|
||||
diagnosticsSourceReason: null,
|
||||
sourceReason: IncrementalStepRunReason.Cached);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AddedRequiresDoublePrecisionSupport_DoesNotModifyOutput()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp;
|
||||
using ComputeSharp.D2D1;
|
||||
using float4 = global::ComputeSharp.Float4;
|
||||
using double4 = global::ComputeSharp.Double4;
|
||||
|
||||
[D2DInputCount(1)]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct MyShader(double factor) : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
return (float4)((double4)D2D.GetInput(0) * factor);
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
const string updatedSource = """
|
||||
using ComputeSharp;
|
||||
using ComputeSharp.D2D1;
|
||||
using float4 = global::ComputeSharp.Float4;
|
||||
using double4 = global::ComputeSharp.Double4;
|
||||
|
||||
[D2DInputCount(1)]
|
||||
[D2DRequiresDoublePrecisionSupport]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct MyShader(double factor) : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
return (float4)((double4)D2D.GetInput(0) * factor);
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
CSharpGeneratorTest<D2DPixelShaderDescriptorGenerator>.VerifyIncrementalSteps(
|
||||
source,
|
||||
updatedSource,
|
||||
executeReason: IncrementalStepRunReason.Modified,
|
||||
diagnosticsReason: IncrementalStepRunReason.Modified,
|
||||
outputReason: IncrementalStepRunReason.Unchanged,
|
||||
diagnosticsSourceReason: IncrementalStepRunReason.Removed,
|
||||
sourceReason: IncrementalStepRunReason.Cached);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void RemovedRequiresDoublePrecisionSupport_DoesNotModifyOutputAndProducesDiagnostics()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp;
|
||||
using ComputeSharp.D2D1;
|
||||
using float4 = global::ComputeSharp.Float4;
|
||||
using double4 = global::ComputeSharp.Double4;
|
||||
|
||||
[D2DInputCount(1)]
|
||||
[D2DRequiresDoublePrecisionSupport]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct MyShader(double factor) : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
return (float4)((double4)D2D.GetInput(0) * factor);
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
const string updatedSource = """
|
||||
using ComputeSharp;
|
||||
using ComputeSharp.D2D1;
|
||||
using float4 = global::ComputeSharp.Float4;
|
||||
using double4 = global::ComputeSharp.Double4;
|
||||
|
||||
[D2DInputCount(1)]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct MyShader(double factor) : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
return (float4)((double4)D2D.GetInput(0) * factor);
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
CSharpGeneratorTest<D2DPixelShaderDescriptorGenerator>.VerifyIncrementalSteps(
|
||||
source,
|
||||
updatedSource,
|
||||
executeReason: IncrementalStepRunReason.Modified,
|
||||
diagnosticsReason: IncrementalStepRunReason.Modified,
|
||||
outputReason: IncrementalStepRunReason.Unchanged,
|
||||
diagnosticsSourceReason: IncrementalStepRunReason.New,
|
||||
sourceReason: IncrementalStepRunReason.Cached);
|
||||
}
|
||||
}
|
||||
@@ -1,267 +0,0 @@
|
||||
using System.Threading.Tasks;
|
||||
using ComputeSharp.D2D1.SourceGenerators;
|
||||
using ComputeSharp.Tests.SourceGenerators.Helpers;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests.SourceGenerators;
|
||||
|
||||
[TestClass]
|
||||
public class Test_D2DPixelShaderSourceGenerator_Analyzers
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task InvalidD2DPixelShaderSourceMethodReturnType_ReadOnlySpanOfByte_DoesNotWarn()
|
||||
{
|
||||
const string source = """"
|
||||
using System;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
public partial class MyClass
|
||||
{
|
||||
[D2DPixelShaderSource("""
|
||||
#define D2D_INPUT_COUNT 0
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
""")]
|
||||
public static partial ReadOnlySpan<byte> InvertEffect();
|
||||
|
||||
public static partial ReadOnlySpan<byte> InvertEffect() => default;
|
||||
}
|
||||
"""";
|
||||
|
||||
await CSharpAnalyzerTest<InvalidD2DPixelShaderSourceMethodReturnTypeAnalyzer>.VerifyAnalyzerAsync(source);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("TimeSpan")]
|
||||
[DataRow("ReadOnlyMemory<byte>")]
|
||||
[DataRow("ReadOnlySpan<int>")]
|
||||
[DataRow("string")]
|
||||
[DataRow("object")]
|
||||
[DataRow("byte")]
|
||||
[DataRow("dynamic")]
|
||||
[DataRow("byte*")]
|
||||
public async Task InvalidD2DPixelShaderSourceMethodReturnType_InvalidType_Warns(string returnType)
|
||||
{
|
||||
string source = $$""""
|
||||
using System;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
public unsafe partial class MyClass
|
||||
{
|
||||
[D2DPixelShaderSource("""
|
||||
#define D2D_INPUT_COUNT 0
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
""")]
|
||||
public static partial {{returnType}} {|CMPSD2D0057:InvertEffect|}();
|
||||
|
||||
public static partial {{returnType}} InvertEffect() => default;
|
||||
}
|
||||
"""";
|
||||
|
||||
await CSharpAnalyzerTest<InvalidD2DPixelShaderSourceMethodReturnTypeAnalyzer>.VerifyAnalyzerAsync(source);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task MissingShaderProfileForD2DPixelShaderSource_ShaderProfileOnMethod_DoesNotWarn()
|
||||
{
|
||||
const string source = """"
|
||||
using System;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
public partial class MyClass
|
||||
{
|
||||
[D2DPixelShaderSource("""
|
||||
#define D2D_INPUT_COUNT 0
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
""")]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
public static partial ReadOnlySpan<byte> InvertEffect();
|
||||
|
||||
public static partial ReadOnlySpan<byte> InvertEffect() => default;
|
||||
}
|
||||
"""";
|
||||
|
||||
await CSharpAnalyzerTest<MissingD2DShaderProfileOnD2DPixelShaderSourceMethodAnalyzer>.VerifyAnalyzerAsync(source);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task MissingShaderProfileForD2DPixelShaderSource_ShaderProfileOnAssembly_DoesNotWarn()
|
||||
{
|
||||
const string source = """"
|
||||
using System;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
[assembly: D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
|
||||
public partial class MyClass
|
||||
{
|
||||
[D2DPixelShaderSource("""
|
||||
#define D2D_INPUT_COUNT 0
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
""")]
|
||||
public static partial ReadOnlySpan<byte> InvertEffect();
|
||||
|
||||
public static partial ReadOnlySpan<byte> InvertEffect() => default;
|
||||
}
|
||||
"""";
|
||||
|
||||
await CSharpAnalyzerTest<MissingD2DShaderProfileOnD2DPixelShaderSourceMethodAnalyzer>.VerifyAnalyzerAsync(source);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task MissingShaderProfileForD2DPixelShaderSource_MissingShaderProfile_Warns()
|
||||
{
|
||||
const string source = """"
|
||||
using System;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
public partial class MyClass
|
||||
{
|
||||
[D2DPixelShaderSource("""
|
||||
#define D2D_INPUT_COUNT 0
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
""")]
|
||||
public static partial ReadOnlySpan<byte> {|CMPSD2D0055:InvertEffect|}();
|
||||
|
||||
public static partial ReadOnlySpan<byte> InvertEffect() => default;
|
||||
}
|
||||
"""";
|
||||
|
||||
await CSharpAnalyzerTest<MissingD2DShaderProfileOnD2DPixelShaderSourceMethodAnalyzer>.VerifyAnalyzerAsync(source);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task MissingCompileOptionsForD2DPixelShaderSource_CompileOptionsOnMethod_DoesNotWarn()
|
||||
{
|
||||
const string source = """"
|
||||
using System;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
public partial class MyClass
|
||||
{
|
||||
[D2DPixelShaderSource("""
|
||||
#define D2D_INPUT_COUNT 0
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
""")]
|
||||
[D2DCompileOptions(D2D1CompileOptions.OptimizationLevel0)]
|
||||
public static partial ReadOnlySpan<byte> InvertEffect();
|
||||
|
||||
public static partial ReadOnlySpan<byte> InvertEffect() => default;
|
||||
}
|
||||
"""";
|
||||
|
||||
await CSharpAnalyzerTest<MissingD2DCompileOptionsOnD2DPixelShaderSourceMethodAnalyzer>.VerifyAnalyzerAsync(source);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task MissingCompileOptionsForD2DPixelShaderSource_CompileOptionsOnAssembly_DoesNotWarn()
|
||||
{
|
||||
const string source = """"
|
||||
using System;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
[assembly: D2DCompileOptions(D2D1CompileOptions.OptimizationLevel0)]
|
||||
|
||||
public partial class MyClass
|
||||
{
|
||||
[D2DPixelShaderSource("""
|
||||
#define D2D_INPUT_COUNT 0
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
""")]
|
||||
public static partial ReadOnlySpan<byte> InvertEffect();
|
||||
|
||||
public static partial ReadOnlySpan<byte> InvertEffect() => default;
|
||||
}
|
||||
"""";
|
||||
|
||||
await CSharpAnalyzerTest<MissingD2DCompileOptionsOnD2DPixelShaderSourceMethodAnalyzer>.VerifyAnalyzerAsync(source);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task MissingCompileOptionsForD2DPixelShaderSource_MissingCompileOptions_Warns()
|
||||
{
|
||||
const string source = """"
|
||||
using System;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
public partial class MyClass
|
||||
{
|
||||
[D2DPixelShaderSource("""
|
||||
#define D2D_INPUT_COUNT 0
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
""")]
|
||||
public static partial ReadOnlySpan<byte> {|CMPSD2D0056:InvertEffect|}();
|
||||
|
||||
public static partial ReadOnlySpan<byte> InvertEffect() => default;
|
||||
}
|
||||
"""";
|
||||
|
||||
await CSharpAnalyzerTest<MissingD2DCompileOptionsOnD2DPixelShaderSourceMethodAnalyzer>.VerifyAnalyzerAsync(source);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task InvalidD2DPixelShaderSource_NullArgument_Warns()
|
||||
{
|
||||
const string source = """
|
||||
using System;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
public partial class MyClass
|
||||
{
|
||||
[D2DPixelShaderSource(null)]
|
||||
public static partial ReadOnlySpan<byte> {|CMPSD2D0052:InvertEffect|}();
|
||||
|
||||
public static partial ReadOnlySpan<byte> InvertEffect() => default;
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<InvalidD2DPixelShaderSourceAttributeUseAnalyzer>.VerifyAnalyzerAsync(source);
|
||||
}
|
||||
}
|
||||
@@ -1,275 +0,0 @@
|
||||
using ComputeSharp.D2D1.SourceGenerators;
|
||||
using ComputeSharp.Tests.SourceGenerators.Helpers;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests.SourceGenerators;
|
||||
|
||||
[TestClass]
|
||||
public class Test_D2DPixelShaderSourceGenerator_Incrementality
|
||||
{
|
||||
[TestMethod]
|
||||
public void ModifiedOptions_ModifiesOutput()
|
||||
{
|
||||
const string source = """"
|
||||
using System;
|
||||
using ComputeSharp;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
partial class C
|
||||
{
|
||||
[D2DPixelShaderSource("""
|
||||
#define D2D_INPUT_COUNT 1
|
||||
#define D2D_INPUT0_SIMPLE
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
float4 color = D2DGetInput(0);
|
||||
float3 rgb = saturate(1.0 - color.rgb);
|
||||
return float4(rgb, 1);
|
||||
}
|
||||
""")]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DCompileOptions(D2D1CompileOptions.OptimizationLevel0)]
|
||||
static partial ReadOnlySpan<byte> MyShader();
|
||||
}
|
||||
"""";
|
||||
|
||||
const string updatedSource = """"
|
||||
using System;
|
||||
using ComputeSharp;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
partial class C
|
||||
{
|
||||
[D2DPixelShaderSource("""
|
||||
#define D2D_INPUT_COUNT 1
|
||||
#define D2D_INPUT0_SIMPLE
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
float4 color = D2DGetInput(0);
|
||||
float3 rgb = saturate(1.0 - color.rgb);
|
||||
return float4(rgb, 1);
|
||||
}
|
||||
""")]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DCompileOptions(D2D1CompileOptions.OptimizationLevel1)]
|
||||
static partial ReadOnlySpan<byte> MyShader();
|
||||
}
|
||||
"""";
|
||||
|
||||
CSharpGeneratorTest<D2DPixelShaderSourceGenerator>.VerifyIncrementalSteps(
|
||||
source,
|
||||
updatedSource,
|
||||
executeReason: IncrementalStepRunReason.Modified,
|
||||
diagnosticsReason: null,
|
||||
outputReason: IncrementalStepRunReason.Modified,
|
||||
diagnosticsSourceReason: null,
|
||||
sourceReason: IncrementalStepRunReason.Modified);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AddedLeadingTrivia_DoesNotModifyOutput()
|
||||
{
|
||||
const string source = """"
|
||||
using System;
|
||||
using ComputeSharp;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
partial class C
|
||||
{
|
||||
[D2DPixelShaderSource("""
|
||||
#define D2D_INPUT_COUNT 1
|
||||
#define D2D_INPUT0_SIMPLE
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
float4 color = D2DGetInput(0);
|
||||
float3 rgb = saturate(1.0 - color.rgb);
|
||||
return float4(rgb, 1);
|
||||
}
|
||||
""")]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DCompileOptions(D2D1CompileOptions.OptimizationLevel0)]
|
||||
static partial ReadOnlySpan<byte> MyShader();
|
||||
}
|
||||
"""";
|
||||
|
||||
const string updatedSource = """"
|
||||
using System;
|
||||
using ComputeSharp;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
// Useless comment
|
||||
partial class C
|
||||
{
|
||||
// Useless method
|
||||
public static int AddOne(int x) => x + 1;
|
||||
|
||||
// Hello
|
||||
[D2DPixelShaderSource("""
|
||||
#define D2D_INPUT_COUNT 1
|
||||
#define D2D_INPUT0_SIMPLE
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
float4 color = D2DGetInput(0);
|
||||
float3 rgb = saturate(1.0 - color.rgb);
|
||||
return float4(rgb, 1);
|
||||
}
|
||||
""")]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DCompileOptions(D2D1CompileOptions.OptimizationLevel0)]
|
||||
static partial ReadOnlySpan<byte> MyShader();
|
||||
}
|
||||
"""";
|
||||
|
||||
CSharpGeneratorTest<D2DPixelShaderSourceGenerator>.VerifyIncrementalSteps(
|
||||
source,
|
||||
updatedSource,
|
||||
executeReason: IncrementalStepRunReason.Unchanged,
|
||||
diagnosticsReason: null,
|
||||
outputReason: IncrementalStepRunReason.Cached,
|
||||
diagnosticsSourceReason: null,
|
||||
sourceReason: IncrementalStepRunReason.Cached);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AddedCompileError_ModifiesOutputAndProducesDiagnostics()
|
||||
{
|
||||
const string source = """"
|
||||
using System;
|
||||
using ComputeSharp;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
partial class C
|
||||
{
|
||||
[D2DPixelShaderSource("""
|
||||
#define D2D_INPUT_COUNT 1
|
||||
#define D2D_INPUT0_SIMPLE
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
float4 color = D2DGetInput(0);
|
||||
float3 rgb = saturate(1.0 - color.rgb);
|
||||
return float4(rgb, 1);
|
||||
}
|
||||
""")]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DCompileOptions(D2D1CompileOptions.OptimizationLevel0)]
|
||||
static partial ReadOnlySpan<byte> MyShader();
|
||||
}
|
||||
"""";
|
||||
|
||||
const string updatedSource = """"
|
||||
using System;
|
||||
using ComputeSharp;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
partial class C
|
||||
{
|
||||
[D2DPixelShaderSource("""
|
||||
#define D2D_INPUT_COUNT 0
|
||||
#define D2D_INPUT0_SIMPLE
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
float4 color = D2DGetInput(0);
|
||||
float3 rgb = saturate(1.0 - color.rgb);
|
||||
return float4(rgb, 1);
|
||||
}
|
||||
""")]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DCompileOptions(D2D1CompileOptions.OptimizationLevel0)]
|
||||
static partial ReadOnlySpan<byte> MyShader();
|
||||
}
|
||||
"""";
|
||||
|
||||
CSharpGeneratorTest<D2DPixelShaderSourceGenerator>.VerifyIncrementalSteps(
|
||||
source,
|
||||
updatedSource,
|
||||
executeReason: IncrementalStepRunReason.Modified,
|
||||
diagnosticsReason: IncrementalStepRunReason.Modified,
|
||||
outputReason: IncrementalStepRunReason.Modified,
|
||||
diagnosticsSourceReason: IncrementalStepRunReason.New,
|
||||
sourceReason: IncrementalStepRunReason.Modified);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void FixedCompileError_ModifiesOutputAndRemovesDiagnostics()
|
||||
{
|
||||
const string source = """"
|
||||
using System;
|
||||
using ComputeSharp;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
partial class C
|
||||
{
|
||||
[D2DPixelShaderSource("""
|
||||
#define D2D_INPUT_COUNT 0
|
||||
#define D2D_INPUT0_SIMPLE
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
float4 color = D2DGetInput(0);
|
||||
float3 rgb = saturate(1.0 - color.rgb);
|
||||
return float4(rgb, 1);
|
||||
}
|
||||
""")]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DCompileOptions(D2D1CompileOptions.OptimizationLevel0)]
|
||||
static partial ReadOnlySpan<byte> MyShader();
|
||||
}
|
||||
"""";
|
||||
|
||||
const string updatedSource = """"
|
||||
using System;
|
||||
using ComputeSharp;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
partial class C
|
||||
{
|
||||
[D2DPixelShaderSource("""
|
||||
#define D2D_INPUT_COUNT 1
|
||||
#define D2D_INPUT0_SIMPLE
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
float4 color = D2DGetInput(0);
|
||||
float3 rgb = saturate(1.0 - color.rgb);
|
||||
return float4(rgb, 1);
|
||||
}
|
||||
""")]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DCompileOptions(D2D1CompileOptions.OptimizationLevel0)]
|
||||
static partial ReadOnlySpan<byte> MyShader();
|
||||
}
|
||||
"""";
|
||||
|
||||
CSharpGeneratorTest<D2DPixelShaderSourceGenerator>.VerifyIncrementalSteps(
|
||||
source,
|
||||
updatedSource,
|
||||
executeReason: IncrementalStepRunReason.Modified,
|
||||
diagnosticsReason: IncrementalStepRunReason.Modified,
|
||||
outputReason: IncrementalStepRunReason.Modified,
|
||||
diagnosticsSourceReason: IncrementalStepRunReason.Removed,
|
||||
sourceReason: IncrementalStepRunReason.Modified);
|
||||
}
|
||||
}
|
||||
@@ -1,361 +0,0 @@
|
||||
extern alias Core;
|
||||
extern alias D2D1;
|
||||
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.CodeAnalysis.Testing;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using CSharpCodeFixTest = Microsoft.CodeAnalysis.CSharp.Testing.CSharpCodeFixTest<
|
||||
ComputeSharp.D2D1.SourceGenerators.MissingPixelShaderDescriptorOnPixelShaderAnalyzer,
|
||||
ComputeSharp.D2D1.CodeFixers.MissingPixelShaderDescriptorOnPixelShaderCodeFixer,
|
||||
Microsoft.CodeAnalysis.Testing.DefaultVerifier>;
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests.SourceGenerators;
|
||||
|
||||
[TestClass]
|
||||
public class Test_MissingPixelShaderDescriptorOnPixelShaderCodeFixer
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task FileContainsComputeSharpD2D1UsingDirective()
|
||||
{
|
||||
string original = """
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
partial struct {|CMPSD2D0065:MyShader|} : ID2D1PixelShader
|
||||
{
|
||||
public ComputeSharp.Float4 Execute() => 0;
|
||||
}
|
||||
""";
|
||||
|
||||
string @fixed = """
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
partial struct MyShader : ID2D1PixelShader
|
||||
{
|
||||
public ComputeSharp.Float4 Execute() => 0;
|
||||
}
|
||||
""";
|
||||
|
||||
CSharpCodeFixTest test = new()
|
||||
{
|
||||
TestCode = original,
|
||||
FixedCode = @fixed,
|
||||
ReferenceAssemblies = ReferenceAssemblies.Net.Net80
|
||||
};
|
||||
|
||||
test.TestState.AdditionalReferences.Add(typeof(Core::ComputeSharp.Float4).Assembly);
|
||||
test.TestState.AdditionalReferences.Add(typeof(D2D1::ComputeSharp.D2D1.ID2D1PixelShader).Assembly);
|
||||
test.TestState.AnalyzerConfigFiles.Add(("/.editorconfig", "[*]\nend_of_line = lf"));
|
||||
|
||||
await test.RunAsync();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task FileContainsComputeSharpD2D1UsingDirective_MultipleOccurrences()
|
||||
{
|
||||
string original = """
|
||||
using System;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
partial struct {|CMPSD2D0065:MyShader1|} : ID2D1PixelShader
|
||||
{
|
||||
public ComputeSharp.Float4 Execute() => 0;
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[TestAttribute]
|
||||
partial struct {|CMPSD2D0065:MyShader2|} : ID2D1PixelShader
|
||||
{
|
||||
public ComputeSharp.Float4 Execute() => 0;
|
||||
}
|
||||
|
||||
public class TestAttribute : Attribute
|
||||
{
|
||||
}
|
||||
""";
|
||||
|
||||
string @fixed = """
|
||||
using System;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
partial struct MyShader1 : ID2D1PixelShader
|
||||
{
|
||||
public ComputeSharp.Float4 Execute() => 0;
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
[TestAttribute]
|
||||
partial struct MyShader2 : ID2D1PixelShader
|
||||
{
|
||||
public ComputeSharp.Float4 Execute() => 0;
|
||||
}
|
||||
|
||||
public class TestAttribute : Attribute
|
||||
{
|
||||
}
|
||||
""";
|
||||
|
||||
CSharpCodeFixTest test = new()
|
||||
{
|
||||
TestCode = original,
|
||||
FixedCode = @fixed,
|
||||
ReferenceAssemblies = ReferenceAssemblies.Net.Net80
|
||||
};
|
||||
|
||||
test.TestState.AdditionalReferences.Add(typeof(Core::ComputeSharp.Float4).Assembly);
|
||||
test.TestState.AdditionalReferences.Add(typeof(D2D1::ComputeSharp.D2D1.ID2D1PixelShader).Assembly);
|
||||
test.TestState.AnalyzerConfigFiles.Add(("/.editorconfig", "[*]\nend_of_line = lf"));
|
||||
|
||||
await test.RunAsync();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task FileDoesNotContainComputeSharpD2D1UsingDirective()
|
||||
{
|
||||
string original = """
|
||||
partial struct {|CMPSD2D0065:MyShader|} : ComputeSharp.D2D1.ID2D1PixelShader
|
||||
{
|
||||
public ComputeSharp.Float4 Execute() => 0;
|
||||
}
|
||||
""";
|
||||
|
||||
string @fixed = """
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
partial struct MyShader : ComputeSharp.D2D1.ID2D1PixelShader
|
||||
{
|
||||
public ComputeSharp.Float4 Execute() => 0;
|
||||
}
|
||||
""";
|
||||
|
||||
CSharpCodeFixTest test = new()
|
||||
{
|
||||
TestCode = original,
|
||||
FixedCode = @fixed,
|
||||
ReferenceAssemblies = ReferenceAssemblies.Net.Net80
|
||||
};
|
||||
|
||||
test.TestState.AdditionalReferences.Add(typeof(Core::ComputeSharp.Float4).Assembly);
|
||||
test.TestState.AdditionalReferences.Add(typeof(D2D1::ComputeSharp.D2D1.ID2D1PixelShader).Assembly);
|
||||
test.TestState.AnalyzerConfigFiles.Add(("/.editorconfig", "[*]\nend_of_line = lf"));
|
||||
|
||||
await test.RunAsync();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task FileDoesNotContainComputeSharpD2D1UsingDirective_MultipleOccurrences()
|
||||
{
|
||||
string original = """
|
||||
using System;
|
||||
|
||||
partial struct {|CMPSD2D0065:MyShader1|} : ComputeSharp.D2D1.ID2D1PixelShader
|
||||
{
|
||||
public ComputeSharp.Float4 Execute() => 0;
|
||||
}
|
||||
|
||||
[TestAttribute]
|
||||
partial struct {|CMPSD2D0065:MyShader2|} : ComputeSharp.D2D1.ID2D1PixelShader
|
||||
{
|
||||
public ComputeSharp.Float4 Execute() => 0;
|
||||
}
|
||||
|
||||
public class TestAttribute : Attribute
|
||||
{
|
||||
}
|
||||
""";
|
||||
|
||||
string @fixed = """
|
||||
using System;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
partial struct MyShader1 : ComputeSharp.D2D1.ID2D1PixelShader
|
||||
{
|
||||
public ComputeSharp.Float4 Execute() => 0;
|
||||
}
|
||||
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
[TestAttribute]
|
||||
partial struct MyShader2 : ComputeSharp.D2D1.ID2D1PixelShader
|
||||
{
|
||||
public ComputeSharp.Float4 Execute() => 0;
|
||||
}
|
||||
|
||||
public class TestAttribute : Attribute
|
||||
{
|
||||
}
|
||||
""";
|
||||
|
||||
CSharpCodeFixTest test = new()
|
||||
{
|
||||
TestCode = original,
|
||||
FixedCode = @fixed,
|
||||
ReferenceAssemblies = ReferenceAssemblies.Net.Net80
|
||||
};
|
||||
|
||||
test.TestState.AdditionalReferences.Add(typeof(Core::ComputeSharp.Float4).Assembly);
|
||||
test.TestState.AdditionalReferences.Add(typeof(D2D1::ComputeSharp.D2D1.ID2D1PixelShader).Assembly);
|
||||
test.TestState.AnalyzerConfigFiles.Add(("/.editorconfig", "[*]\nend_of_line = lf"));
|
||||
|
||||
await test.RunAsync();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task InsertsAttributeAfterAllOtherD2DAttributes()
|
||||
{
|
||||
string original = """
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
[D2DInputCount(1)]
|
||||
[D2DInputSimple(0)]
|
||||
partial struct {|CMPSD2D0065:MyShader|} : ID2D1PixelShader
|
||||
{
|
||||
public ComputeSharp.Float4 Execute() => 0;
|
||||
}
|
||||
""";
|
||||
|
||||
string @fixed = """
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
[D2DInputCount(1)]
|
||||
[D2DInputSimple(0)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
partial struct MyShader : ID2D1PixelShader
|
||||
{
|
||||
public ComputeSharp.Float4 Execute() => 0;
|
||||
}
|
||||
""";
|
||||
|
||||
CSharpCodeFixTest test = new()
|
||||
{
|
||||
TestCode = original,
|
||||
FixedCode = @fixed,
|
||||
ReferenceAssemblies = ReferenceAssemblies.Net.Net80
|
||||
};
|
||||
|
||||
test.TestState.AdditionalReferences.Add(typeof(Core::ComputeSharp.Float4).Assembly);
|
||||
test.TestState.AdditionalReferences.Add(typeof(D2D1::ComputeSharp.D2D1.ID2D1PixelShader).Assembly);
|
||||
test.TestState.AnalyzerConfigFiles.Add(("/.editorconfig", "[*]\nend_of_line = lf"));
|
||||
|
||||
await test.RunAsync();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task InsertsAttributeAfterAllOtherD2DAttributes_WithOtherNonD2DAttribute()
|
||||
{
|
||||
string original = """
|
||||
using System;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
[D2DInputCount(1)]
|
||||
[D2DInputSimple(0)]
|
||||
[Test]
|
||||
partial struct {|CMPSD2D0065:MyShader|} : ID2D1PixelShader
|
||||
{
|
||||
public ComputeSharp.Float4 Execute() => 0;
|
||||
}
|
||||
|
||||
public class TestAttribute : Attribute
|
||||
{
|
||||
}
|
||||
""";
|
||||
|
||||
string @fixed = """
|
||||
using System;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
[D2DInputCount(1)]
|
||||
[D2DInputSimple(0)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
[Test]
|
||||
partial struct MyShader : ID2D1PixelShader
|
||||
{
|
||||
public ComputeSharp.Float4 Execute() => 0;
|
||||
}
|
||||
|
||||
public class TestAttribute : Attribute
|
||||
{
|
||||
}
|
||||
""";
|
||||
|
||||
CSharpCodeFixTest test = new()
|
||||
{
|
||||
TestCode = original,
|
||||
FixedCode = @fixed,
|
||||
ReferenceAssemblies = ReferenceAssemblies.Net.Net80
|
||||
};
|
||||
|
||||
test.TestState.AdditionalReferences.Add(typeof(Core::ComputeSharp.Float4).Assembly);
|
||||
test.TestState.AdditionalReferences.Add(typeof(D2D1::ComputeSharp.D2D1.ID2D1PixelShader).Assembly);
|
||||
test.TestState.AnalyzerConfigFiles.Add(("/.editorconfig", "[*]\nend_of_line = lf"));
|
||||
|
||||
await test.RunAsync();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task InsertsAttributeAfterAllOtherD2DAttributes_WithFakeAttributes()
|
||||
{
|
||||
string original = """
|
||||
using System;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
[D2DInputCount(2)]
|
||||
[D2DInputSimple(0)]
|
||||
[ComputeSharp.D2D1.D2DInputSimple(1)]
|
||||
[D2DFake]
|
||||
[Test]
|
||||
partial struct {|CMPSD2D0065:MyShader|} : ID2D1PixelShader
|
||||
{
|
||||
public ComputeSharp.Float4 Execute() => 0;
|
||||
}
|
||||
|
||||
public class TestAttribute : Attribute
|
||||
{
|
||||
}
|
||||
|
||||
public class D2DFakeAttribute : Attribute
|
||||
{
|
||||
}
|
||||
""";
|
||||
|
||||
string @fixed = """
|
||||
using System;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
[D2DInputCount(2)]
|
||||
[D2DInputSimple(0)]
|
||||
[ComputeSharp.D2D1.D2DInputSimple(1)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
[D2DFake]
|
||||
[Test]
|
||||
partial struct {|CMPSD2D0065:MyShader|} : ID2D1PixelShader
|
||||
{
|
||||
public ComputeSharp.Float4 Execute() => 0;
|
||||
}
|
||||
|
||||
public class TestAttribute : Attribute
|
||||
{
|
||||
}
|
||||
|
||||
public class D2DFakeAttribute : Attribute
|
||||
{
|
||||
}
|
||||
""";
|
||||
|
||||
CSharpCodeFixTest test = new()
|
||||
{
|
||||
TestCode = original,
|
||||
FixedCode = @fixed,
|
||||
ReferenceAssemblies = ReferenceAssemblies.Net.Net80
|
||||
};
|
||||
|
||||
test.TestState.AdditionalReferences.Add(typeof(Core::ComputeSharp.Float4).Assembly);
|
||||
test.TestState.AdditionalReferences.Add(typeof(D2D1::ComputeSharp.D2D1.ID2D1PixelShader).Assembly);
|
||||
test.TestState.AnalyzerConfigFiles.Add(("/.editorconfig", "[*]\nend_of_line = lf"));
|
||||
|
||||
await test.RunAsync();
|
||||
}
|
||||
}
|
||||
|
変更前 幅: | 高さ: | サイズ: 2.5 MiB |
|
変更前 幅: | 高さ: | サイズ: 123 B |
|
変更前 幅: | 高さ: | サイズ: 1.7 MiB |
|
変更前 幅: | 高さ: | サイズ: 1.1 MiB |
|
変更前 幅: | 高さ: | サイズ: 2.0 MiB |
|
変更前 幅: | 高さ: | サイズ: 88 KiB |
|
変更前 幅: | 高さ: | サイズ: 1.6 MiB |
|
変更前 幅: | 高さ: | サイズ: 2.0 MiB |
|
変更前 幅: | 高さ: | サイズ: 919 KiB |
|
変更前 幅: | 高さ: | サイズ: 1.7 MiB |
|
変更前 幅: | 高さ: | サイズ: 410 KiB |
|
変更前 幅: | 高さ: | サイズ: 444 KiB |
|
変更前 幅: | 高さ: | サイズ: 328 KiB |
|
変更前 幅: | 高さ: | サイズ: 1.5 MiB |
|
変更前 幅: | 高さ: | サイズ: 414 KiB |
@@ -1,104 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\ComputeSharp.Tests\Helpers\TolerantImageComparer.cs" Link="Helpers\ComputeSharp.Tests\TolerantImageComparer.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoConstructor" Version="5.6.0" PrivateAssets="all" />
|
||||
<PackageReference Include="MSTest" Version="3.8.3" />
|
||||
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.11" />
|
||||
<PackageReference Include="TerraFX.Interop.Windows" Version="10.0.26100.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.Core\ComputeSharp.Core.csproj" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.Core.SourceGenerators\ComputeSharp.Core.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.D2D1\ComputeSharp.D2D1.csproj" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.D2D1.CodeFixers\ComputeSharp.D2D1.CodeFixers.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.D2D1.SourceGenerators\ComputeSharp.D2D1.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\samples\ComputeSharp.ImageProcessing\Primitives\Complex64.cs" Link="Imaging\Primitives\Complex64.cs" />
|
||||
<Compile Include="..\..\samples\ComputeSharp.ImageProcessing\Primitives\ComplexVector4.cs" Link="Imaging\Primitives\ComplexVector4.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="Assets\Landscape.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Landscape_CheckerboardClip.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Landscape_Inverted.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Landscape_Pixelate.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Wallpaper0.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Wallpaper1.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\WallpapersStack.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\ZonePlate.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Include="..\ComputeSharp.Tests\Assets\CityWith1920x1280Resizing.png" Link="Assets\City.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Include="..\ComputeSharp.Tests\Assets\ColorfulInfinity.png" Link="Assets\ColorfulInfinity.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Include="..\ComputeSharp.Tests\Assets\ExtrudedTruchetPattern.png" Link="Assets\ExtrudedTruchetPattern.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Include="..\ComputeSharp.Tests\Assets\FractalTiling.png" Link="Assets\FractalTiling.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Include="..\ComputeSharp.Tests\Assets\HelloWorld.png" Link="Assets\HelloWorld.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Include="..\ComputeSharp.Tests\Assets\MengerJourney.png" Link="Assets\MengerJourney.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Include="..\ComputeSharp.Tests\Assets\Octagrams.png" Link="Assets\Octagrams.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Include="..\ComputeSharp.Tests\Assets\ProteanClouds.png" Link="Assets\ProteanClouds.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\PyramidPattern.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\TriangleGridContouring.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\TwoTiledTruchet.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\ContouredLayers.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Include="Assets\TerracedHills.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\RadialFadeOut.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Green32x32.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Include="..\..\samples\ComputeSharp.SwapChain\Textures\RustyMetal.png" Link="Assets\Textures\RustyMetal.png" CopyToOutputDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
|
||||
<Import Project="..\..\samples\ComputeSharp.SwapChain.Shaders.D2D1\ComputeSharp.SwapChain.Shaders.D2D1.projitems" Label="Shared" />
|
||||
</Project>
|
||||
@@ -1,241 +0,0 @@
|
||||
using System;
|
||||
using ComputeSharp.D2D1.Interop;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests;
|
||||
|
||||
[TestClass]
|
||||
public partial class D2D1EffectRegistrationDataTests
|
||||
{
|
||||
[TestMethod]
|
||||
public unsafe void EffectRegistrationData_Validate()
|
||||
{
|
||||
ReadOnlyMemory<byte> blob = D2D1PixelShaderEffect.GetRegistrationBlob<TestRegistrationBlobShader>(out Guid effectId);
|
||||
D2D1EffectRegistrationData.V1 data = D2D1EffectRegistrationData.V1.Load(blob);
|
||||
|
||||
Assert.AreEqual(Guid.Parse("8AA3BDF3-5EC8-34D9-CFBC-97A2B4068FFD"), effectId);
|
||||
Assert.AreEqual(effectId, data.ClassId);
|
||||
Assert.AreEqual(2, data.NumberOfInputs);
|
||||
Assert.IsTrue(data.EffectFactory is not null);
|
||||
Assert.AreEqual(2, data.PropertyBindings.Length);
|
||||
Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ConstantBuffer), data.PropertyBindings.Span[0].PropertyName);
|
||||
Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.TransformMapper), data.PropertyBindings.Span[1].PropertyName);
|
||||
|
||||
foreach (ref readonly D2D1PropertyBinding propertyBinding in data.PropertyBindings.Span)
|
||||
{
|
||||
Assert.IsTrue(propertyBinding.SetFunction is not null);
|
||||
Assert.IsTrue(propertyBinding.GetFunction is not null);
|
||||
}
|
||||
|
||||
Assert.AreEqual("""
|
||||
<?xml version='1.0'?>
|
||||
<Effect>
|
||||
<Property name='DisplayName' type='string' value=''/>
|
||||
<Property name='Description' type='string' value=''/>
|
||||
<Property name='Category' type='string' value=''/>
|
||||
<Property name='Author' type='string' value=''/>
|
||||
<Inputs>
|
||||
<Input name='Source0'/>
|
||||
<Input name='Source1'/>
|
||||
</Inputs>
|
||||
<Property name='ConstantBuffer' type='blob'>
|
||||
<Property name='DisplayName' type='string' value='ConstantBuffer'/>
|
||||
</Property>
|
||||
<Property name='TransformMapper' type='iunknown'>
|
||||
<Property name='DisplayName' type='string' value='TransformMapper'/>
|
||||
</Property>
|
||||
</Effect>
|
||||
""", data.PropertyXml);
|
||||
}
|
||||
|
||||
[D2DInputCount(2)]
|
||||
[D2DRequiresScenePosition]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct TestRegistrationBlobShader : ID2D1PixelShader
|
||||
{
|
||||
private readonly float a;
|
||||
|
||||
public float4 Execute()
|
||||
{
|
||||
return this.a;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void EffectRegistrationData_WithCustomMetadata_Validate()
|
||||
{
|
||||
ReadOnlyMemory<byte> blob = D2D1PixelShaderEffect.GetRegistrationBlob<TestRegistrationBlobWithCustomMetadataShader>(out Guid effectId);
|
||||
D2D1EffectRegistrationData.V1 data = D2D1EffectRegistrationData.V1.Load(blob);
|
||||
|
||||
Assert.AreEqual(Guid.Parse("ABF58390-91D2-4F58-AA2B-22D0F6AC069C"), effectId);
|
||||
Assert.AreEqual("""
|
||||
<?xml version='1.0'?>
|
||||
<Effect>
|
||||
<Property name='DisplayName' type='string' value='EffectWithCustomMetadata'/>
|
||||
<Property name='Description' type='string' value='A test effect with some custom metadata'/>
|
||||
<Property name='Category' type='string' value='Test effects'/>
|
||||
<Property name='Author' type='string' value='Bob Ross'/>
|
||||
<Inputs>
|
||||
<Input name='Source0'/>
|
||||
<Input name='Source1'/>
|
||||
</Inputs>
|
||||
<Property name='ConstantBuffer' type='blob'>
|
||||
<Property name='DisplayName' type='string' value='ConstantBuffer'/>
|
||||
</Property>
|
||||
<Property name='TransformMapper' type='iunknown'>
|
||||
<Property name='DisplayName' type='string' value='TransformMapper'/>
|
||||
</Property>
|
||||
</Effect>
|
||||
""", data.PropertyXml);
|
||||
}
|
||||
|
||||
[D2DInputCount(2)]
|
||||
[D2DEffectId("ABF58390-91D2-4F58-AA2B-22D0F6AC069C")]
|
||||
[D2DEffectDisplayName("EffectWithCustomMetadata")]
|
||||
[D2DEffectDescription("A test effect with some custom metadata")]
|
||||
[D2DEffectCategory("Test effects")]
|
||||
[D2DEffectAuthor("Bob Ross")]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct TestRegistrationBlobWithCustomMetadataShader : ID2D1PixelShader
|
||||
{
|
||||
private readonly float a;
|
||||
|
||||
public float4 Execute()
|
||||
{
|
||||
return this.a;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void EffectRegistrationData_WithResourceTextures_Validate()
|
||||
{
|
||||
ReadOnlyMemory<byte> blob = D2D1PixelShaderEffect.GetRegistrationBlob<TestRegistrationBlobWithResourceTextures>(out _);
|
||||
D2D1EffectRegistrationData.V1 data = D2D1EffectRegistrationData.V1.Load(blob);
|
||||
|
||||
Assert.IsTrue(data.EffectFactory is not null);
|
||||
Assert.AreEqual(14, data.PropertyBindings.Length);
|
||||
Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ConstantBuffer), data.PropertyBindings.Span[0].PropertyName);
|
||||
Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.TransformMapper), data.PropertyBindings.Span[1].PropertyName);
|
||||
Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager0), data.PropertyBindings.Span[2].PropertyName);
|
||||
Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager1), data.PropertyBindings.Span[3].PropertyName);
|
||||
Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager2), data.PropertyBindings.Span[4].PropertyName);
|
||||
Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager3), data.PropertyBindings.Span[5].PropertyName);
|
||||
Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager4), data.PropertyBindings.Span[6].PropertyName);
|
||||
Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager5), data.PropertyBindings.Span[7].PropertyName);
|
||||
Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager6), data.PropertyBindings.Span[8].PropertyName);
|
||||
Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager7), data.PropertyBindings.Span[9].PropertyName);
|
||||
Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager8), data.PropertyBindings.Span[10].PropertyName);
|
||||
Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager9), data.PropertyBindings.Span[11].PropertyName);
|
||||
Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager10), data.PropertyBindings.Span[12].PropertyName);
|
||||
Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager11), data.PropertyBindings.Span[13].PropertyName);
|
||||
|
||||
foreach (ref readonly D2D1PropertyBinding propertyBinding in data.PropertyBindings.Span)
|
||||
{
|
||||
Assert.IsTrue(propertyBinding.SetFunction is not null);
|
||||
Assert.IsTrue(propertyBinding.GetFunction is not null);
|
||||
}
|
||||
|
||||
Assert.AreEqual("""
|
||||
<?xml version='1.0'?>
|
||||
<Effect>
|
||||
<Property name='DisplayName' type='string' value=''/>
|
||||
<Property name='Description' type='string' value=''/>
|
||||
<Property name='Category' type='string' value=''/>
|
||||
<Property name='Author' type='string' value=''/>
|
||||
<Inputs>
|
||||
</Inputs>
|
||||
<Property name='ConstantBuffer' type='blob'>
|
||||
<Property name='DisplayName' type='string' value='ConstantBuffer'/>
|
||||
</Property>
|
||||
<Property name='TransformMapper' type='iunknown'>
|
||||
<Property name='DisplayName' type='string' value='TransformMapper'/>
|
||||
</Property>
|
||||
<Property name='ResourceTextureManager0' type='iunknown'>
|
||||
<Property name='DisplayName' type='string' value='ResourceTextureManager0'/>
|
||||
</Property>
|
||||
<Property name='ResourceTextureManager1' type='iunknown'>
|
||||
<Property name='DisplayName' type='string' value='ResourceTextureManager1'/>
|
||||
</Property>
|
||||
<Property name='ResourceTextureManager2' type='iunknown'>
|
||||
<Property name='DisplayName' type='string' value='ResourceTextureManager2'/>
|
||||
</Property>
|
||||
<Property name='ResourceTextureManager3' type='iunknown'>
|
||||
<Property name='DisplayName' type='string' value='ResourceTextureManager3'/>
|
||||
</Property>
|
||||
<Property name='ResourceTextureManager4' type='iunknown'>
|
||||
<Property name='DisplayName' type='string' value='ResourceTextureManager4'/>
|
||||
</Property>
|
||||
<Property name='ResourceTextureManager5' type='iunknown'>
|
||||
<Property name='DisplayName' type='string' value='ResourceTextureManager5'/>
|
||||
</Property>
|
||||
<Property name='ResourceTextureManager6' type='iunknown'>
|
||||
<Property name='DisplayName' type='string' value='ResourceTextureManager6'/>
|
||||
</Property>
|
||||
<Property name='ResourceTextureManager7' type='iunknown'>
|
||||
<Property name='DisplayName' type='string' value='ResourceTextureManager7'/>
|
||||
</Property>
|
||||
<Property name='ResourceTextureManager8' type='iunknown'>
|
||||
<Property name='DisplayName' type='string' value='ResourceTextureManager8'/>
|
||||
</Property>
|
||||
<Property name='ResourceTextureManager9' type='iunknown'>
|
||||
<Property name='DisplayName' type='string' value='ResourceTextureManager9'/>
|
||||
</Property>
|
||||
<Property name='ResourceTextureManager10' type='iunknown'>
|
||||
<Property name='DisplayName' type='string' value='ResourceTextureManager10'/>
|
||||
</Property>
|
||||
<Property name='ResourceTextureManager11' type='iunknown'>
|
||||
<Property name='DisplayName' type='string' value='ResourceTextureManager11'/>
|
||||
</Property>
|
||||
</Effect>
|
||||
""", data.PropertyXml);
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct TestRegistrationBlobWithResourceTextures : ID2D1PixelShader
|
||||
{
|
||||
[D2DResourceTextureIndex(0)]
|
||||
public readonly D2D1ResourceTexture1D<float> t0;
|
||||
|
||||
[D2DResourceTextureIndex(1)]
|
||||
public readonly D2D1ResourceTexture1D<float> t1;
|
||||
|
||||
[D2DResourceTextureIndex(2)]
|
||||
public readonly D2D1ResourceTexture1D<float> t2;
|
||||
|
||||
[D2DResourceTextureIndex(3)]
|
||||
public readonly D2D1ResourceTexture1D<float> t3;
|
||||
|
||||
[D2DResourceTextureIndex(4)]
|
||||
public readonly D2D1ResourceTexture1D<float> t4;
|
||||
|
||||
[D2DResourceTextureIndex(5)]
|
||||
public readonly D2D1ResourceTexture1D<float> t5;
|
||||
|
||||
[D2DResourceTextureIndex(6)]
|
||||
public readonly D2D1ResourceTexture1D<float> t6;
|
||||
|
||||
[D2DResourceTextureIndex(7)]
|
||||
public readonly D2D1ResourceTexture1D<float> t7;
|
||||
|
||||
[D2DResourceTextureIndex(8)]
|
||||
public readonly D2D1ResourceTexture1D<float> t8;
|
||||
|
||||
[D2DResourceTextureIndex(9)]
|
||||
public readonly D2D1ResourceTexture1D<float> t9;
|
||||
|
||||
[D2DResourceTextureIndex(10)]
|
||||
public readonly D2D1ResourceTexture1D<float> t10;
|
||||
|
||||
[D2DResourceTextureIndex(11)]
|
||||
public readonly D2D1ResourceTexture1D<float> t11;
|
||||
|
||||
public float4 Execute()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,296 +0,0 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using ComputeSharp.D2D1;
|
||||
using ComputeSharp.D2D1.Interop;
|
||||
using ComputeSharp.D2D1.Tests.Effects;
|
||||
using ComputeSharp.D2D1.Tests.Helpers;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using TerraFX.Interop.DirectX;
|
||||
using TerraFX.Interop.Windows;
|
||||
|
||||
[assembly: D2DEnableRuntimeCompilation]
|
||||
|
||||
#pragma warning disable IDE0022, IDE0044
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests;
|
||||
|
||||
[TestClass]
|
||||
public partial class D2D1PixelShaderEffectTests
|
||||
{
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)]
|
||||
public unsafe void RegisterForD2D1Factory1_NullD2D1Factory1()
|
||||
{
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<InvertEffect>(null, out _);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)]
|
||||
public unsafe void RegisterForD2D1Factory1_WithTransformMapperFactory_NullD2D1Factory1()
|
||||
{
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<PixelateEffect>(null, out _);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)]
|
||||
public unsafe void CreateFromD2D1DeviceContext_NullD2D1DeviceContext()
|
||||
{
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<InvertEffect>(null, (void**)1);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)]
|
||||
public unsafe void CreateFromD2D1DeviceContext_NullD2D1Effect()
|
||||
{
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<InvertEffect>((void*)1, null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)]
|
||||
public unsafe void SetConstantBufferForD2D1Effect_NullD2D1Effect()
|
||||
{
|
||||
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect<InvertEffect>(null, default);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)]
|
||||
public unsafe void SetResourceTextureManagerForD2D1Effect_NullD2D1Effect()
|
||||
{
|
||||
D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(null, (void*)1, 0);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)]
|
||||
public unsafe void SetResourceTextureManagerForD2D1Effect_NullD2D1ResourceTextureManager()
|
||||
{
|
||||
D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect((void*)1, (void*)null, 0);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)]
|
||||
public unsafe void SetResourceTextureManagerForD2D1Effect_RCW_NullD2D1Effect()
|
||||
{
|
||||
D2D1ResourceTextureManager resourceTextureManager = new(
|
||||
extents: [64],
|
||||
bufferPrecision: D2D1BufferPrecision.UInt8Normalized,
|
||||
channelDepth: D2D1ChannelDepth.One,
|
||||
filter: D2D1Filter.MinLinearMagMipPoint,
|
||||
extendModes: [D2D1ExtendMode.Clamp]);
|
||||
|
||||
D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(null, resourceTextureManager, 0);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)]
|
||||
public unsafe void SetResourceTextureManagerForD2D1Effect_RCW_NullD2D1ResourceTextureManager()
|
||||
{
|
||||
D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect((void*)1, (D2D1ResourceTextureManager)null!, 0);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)]
|
||||
public unsafe void SetTransformMapperForD2D1Effect_RCW_NullD2D1Effect()
|
||||
{
|
||||
D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(null, (void*)1);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)]
|
||||
public unsafe void SetTransformMapperForD2D1Effect_RCW_NullD2D1ResourceTextureManager()
|
||||
{
|
||||
D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect((void*)1, (D2D1DrawTransformMapper<NullConstantBufferShader>)null!);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(Win32Exception))]
|
||||
public unsafe void NullConstantBuffer_DrawImageFails()
|
||||
{
|
||||
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2();
|
||||
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
|
||||
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
|
||||
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<NullConstantBufferShader>(d2D1Factory2.Get(), out _);
|
||||
|
||||
using ComPtr<ID2D1Effect> d2D1Effect = default;
|
||||
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<NullConstantBufferShader>(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf());
|
||||
|
||||
using ComPtr<ID2D1Bitmap> d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), 128, 128);
|
||||
|
||||
D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get());
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DRequiresScenePosition]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct NullConstantBufferShader : ID2D1PixelShader
|
||||
{
|
||||
private readonly float dummy;
|
||||
|
||||
public float4 Execute()
|
||||
{
|
||||
return this.dummy;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void GetValueSize_ConstantBuffer()
|
||||
{
|
||||
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2();
|
||||
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
|
||||
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
|
||||
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<ConstantBufferSizeTestShader>(d2D1Factory2.Get(), out _);
|
||||
|
||||
using ComPtr<ID2D1Effect> d2D1Effect = default;
|
||||
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<ConstantBufferSizeTestShader>(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf());
|
||||
|
||||
uint size = d2D1Effect.Get()->GetValueSize(D2D1PixelShaderEffectProperty.ConstantBuffer);
|
||||
|
||||
Assert.AreEqual(D2D1PixelShader.GetConstantBufferSize<ConstantBufferSizeTestShader>(), (int)size);
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DRequiresScenePosition]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct ConstantBufferSizeTestShader : ID2D1PixelShader
|
||||
{
|
||||
private readonly float a;
|
||||
private readonly float b;
|
||||
private readonly float3 c;
|
||||
private readonly int d;
|
||||
private readonly int e;
|
||||
|
||||
public float4 Execute()
|
||||
{
|
||||
return this.a + this.b + this.c.X + this.d + this.e;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void DefaultEffectId_MatchesValue()
|
||||
{
|
||||
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2();
|
||||
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
|
||||
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
|
||||
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<ShaderWithDefaultEffectId>(d2D1Factory2.Get(), out Guid effectId);
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<ShaderWithDefaultEffectId2>(d2D1Factory2.Get(), out Guid effectId2);
|
||||
|
||||
// Ensure that the dynamically generated GUIDs are deterministic and stable
|
||||
Assert.AreEqual(Guid.Parse("F5287184-0EC7-0BC6-3942-8BFB70E77C4B"), effectId);
|
||||
Assert.AreEqual(Guid.Parse("96310279-E716-D336-5097-BE516792CBF0"), effectId2);
|
||||
|
||||
Assert.AreEqual(D2D1PixelShaderEffect.GetEffectId<ShaderWithDefaultEffectId>(), effectId);
|
||||
Assert.AreEqual(D2D1PixelShaderEffect.GetEffectId<ShaderWithDefaultEffectId2>(), effectId2);
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal partial struct ShaderWithDefaultEffectId : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal partial struct ShaderWithDefaultEffectId2 : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void ExplicitEffectId_MatchesValue()
|
||||
{
|
||||
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2();
|
||||
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
|
||||
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
|
||||
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<ShaderWithExplicitEffectId>(d2D1Factory2.Get(), out Guid effectId);
|
||||
|
||||
Assert.AreEqual(Guid.Parse("8E1F7F49-EF0D-4242-8912-08ADA36AB4EC"), effectId);
|
||||
Assert.AreEqual(D2D1PixelShaderEffect.GetEffectId<ShaderWithExplicitEffectId>(), effectId);
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DEffectId("8E1F7F49-EF0D-4242-8912-08ADA36AB4EC")]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal partial struct ShaderWithExplicitEffectId : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void DefaultEffectMetadata_MatchesValue()
|
||||
{
|
||||
Assert.AreEqual(D2D1PixelShaderEffect.GetEffectDisplayName<ShaderWithDefaultEffectDisplayName>(), null);
|
||||
Assert.AreEqual(D2D1PixelShaderEffect.GetEffectDisplayName<ShaderWithDefaultEffectDisplayName>(), null);
|
||||
Assert.AreEqual(D2D1PixelShaderEffect.GetEffectDisplayName<ShaderWithDefaultEffectDisplayName>(), null);
|
||||
Assert.AreEqual(D2D1PixelShaderEffect.GetEffectDisplayName<ShaderWithDefaultEffectDisplayName>(), null);
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal partial struct ShaderWithDefaultEffectDisplayName : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void ExplicitEffectMetadata1_MatchesValue()
|
||||
{
|
||||
Assert.AreEqual(D2D1PixelShaderEffect.GetEffectDisplayName<ShaderWithExplicitEffectDisplayName1>(), "Fancy blur");
|
||||
Assert.AreEqual(D2D1PixelShaderEffect.GetEffectDescription<ShaderWithExplicitEffectDisplayName1>(), null);
|
||||
Assert.AreEqual(D2D1PixelShaderEffect.GetEffectCategory<ShaderWithExplicitEffectDisplayName1>(), null);
|
||||
Assert.AreEqual(D2D1PixelShaderEffect.GetEffectAuthor<ShaderWithExplicitEffectDisplayName1>(), null);
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DEffectDisplayName("Fancy blur")]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal partial struct ShaderWithExplicitEffectDisplayName1 : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void ExplicitEffectMetadata2_MatchesValue()
|
||||
{
|
||||
Assert.AreEqual(D2D1PixelShaderEffect.GetEffectDisplayName<ShaderWithExplicitEffectDisplayName2>(), "Fancy"<");
|
||||
Assert.AreEqual(D2D1PixelShaderEffect.GetEffectDescription<ShaderWithExplicitEffectDisplayName2>(), "A test effect with some custom metadata");
|
||||
Assert.AreEqual(D2D1PixelShaderEffect.GetEffectCategory<ShaderWithExplicitEffectDisplayName2>(), "Test effects!");
|
||||
Assert.AreEqual(D2D1PixelShaderEffect.GetEffectAuthor<ShaderWithExplicitEffectDisplayName2>(), "Bob Ross");
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DEffectDisplayName("F\r\na\nncy\"<")]
|
||||
[D2DEffectDescription("A test effect with \nsome custom metadata")]
|
||||
[D2DEffectCategory("Test effects!")]
|
||||
[D2DEffectAuthor("Bob \r\nRoss")]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal partial struct ShaderWithExplicitEffectDisplayName2 : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
using ComputeSharp.D2D1.Interop;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests;
|
||||
|
||||
[TestClass]
|
||||
public partial class D2D1ReflectionServicesTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void GetShaderInfo()
|
||||
{
|
||||
D2D1ShaderInfo shaderInfo = D2D1ReflectionServices.GetShaderInfo<ReflectedShader>();
|
||||
|
||||
Assert.IsNotNull(shaderInfo);
|
||||
Assert.AreEqual(10u, shaderInfo.BoundResourceCount);
|
||||
Assert.AreEqual(5u, shaderInfo.DeclarationCount);
|
||||
Assert.IsFalse(shaderInfo.RequiresDoublePrecisionSupport);
|
||||
Assert.AreEqual(D3DFeatureLevel.FeatureLevel10_1, shaderInfo.MinimumFeatureLevel);
|
||||
Assert.IsNotNull(shaderInfo.CompilerVersion);
|
||||
|
||||
Assert.AreEqual("""
|
||||
#define D2D_INPUT_COUNT 3
|
||||
#define D2D_INPUT0_SIMPLE
|
||||
#define D2D_INPUT1_SIMPLE
|
||||
#define D2D_INPUT2_COMPLEX
|
||||
#define D2D_REQUIRES_SCENE_POSITION
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
float2 offset;
|
||||
|
||||
Texture1D<float> __reserved__buffer : register(t3);
|
||||
SamplerState __sampler____reserved__buffer : register(s3);
|
||||
|
||||
Texture2D<float4> __reserved__texture : register(t4);
|
||||
SamplerState __sampler____reserved__texture : register(s4);
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
int2 xy = (int2)D2DGetScenePosition().xy;
|
||||
float4 input0 = D2DGetInput(0);
|
||||
float4 input1 = D2DGetInput(1);
|
||||
float4 input2 = D2DSampleInputAtPosition(2, xy + offset);
|
||||
float value3 = __reserved__buffer[0];
|
||||
float4 value4 = __reserved__texture.Sample(__sampler____reserved__texture, float2(0, asfloat(1056964608U)));
|
||||
return input0 + input1 + input2 + value3 + value4;
|
||||
}
|
||||
""", shaderInfo.HlslSource);
|
||||
|
||||
CollectionAssert.AreEqual(D2D1PixelShader.LoadBytecode<ReflectedShader>().ToArray(), shaderInfo.HlslBytecode.ToArray());
|
||||
}
|
||||
|
||||
[D2DInputCount(3)]
|
||||
[D2DInputSimple(0)]
|
||||
[D2DInputSimple(1)]
|
||||
[D2DInputComplex(2)]
|
||||
[D2DRequiresScenePosition]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader41)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct ReflectedShader : ID2D1PixelShader
|
||||
{
|
||||
private readonly float2 offset;
|
||||
|
||||
[D2DResourceTextureIndex(3)]
|
||||
private readonly D2D1ResourceTexture1D<float> buffer;
|
||||
|
||||
[D2DResourceTextureIndex(4)]
|
||||
private readonly D2D1ResourceTexture2D<float4> texture;
|
||||
|
||||
public float4 Execute()
|
||||
{
|
||||
int2 xy = (int2)D2D.GetScenePosition().XY;
|
||||
|
||||
float4 input0 = D2D.GetInput(0);
|
||||
float4 input1 = D2D.GetInput(1);
|
||||
float4 input2 = D2D.SampleInputAtPosition(2, xy + this.offset);
|
||||
|
||||
float value3 = this.buffer[0];
|
||||
float4 value4 = this.texture.Sample(0, 0.5f);
|
||||
|
||||
return input0 + input1 + input2 + value3 + value4;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void GetShaderInfoWithDoublePrecisionFeature()
|
||||
{
|
||||
D2D1ShaderInfo shaderInfo = D2D1ReflectionServices.GetShaderInfo<ReflectedShaderWithDoubleOperations>();
|
||||
|
||||
Assert.IsNotNull(shaderInfo);
|
||||
Assert.AreEqual(3u, shaderInfo.BoundResourceCount);
|
||||
Assert.AreEqual(1u, shaderInfo.ConstantBufferCount);
|
||||
Assert.AreEqual(2u, shaderInfo.DeclarationCount);
|
||||
Assert.IsTrue(shaderInfo.RequiresDoublePrecisionSupport);
|
||||
Assert.AreEqual(D3DFeatureLevel.FeatureLevel11_0, shaderInfo.MinimumFeatureLevel);
|
||||
Assert.IsNotNull(shaderInfo.CompilerVersion);
|
||||
|
||||
Assert.AreEqual("""
|
||||
#define D2D_INPUT_COUNT 1
|
||||
#define D2D_INPUT0_SIMPLE
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
double amount;
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
return (float4)(D2DGetInput(0) + (double4)amount);
|
||||
}
|
||||
""", shaderInfo.HlslSource);
|
||||
|
||||
CollectionAssert.AreEqual(D2D1PixelShader.LoadBytecode<ReflectedShaderWithDoubleOperations>().ToArray(), shaderInfo.HlslBytecode.ToArray());
|
||||
}
|
||||
|
||||
[D2DInputCount(1)]
|
||||
[D2DInputSimple(0)]
|
||||
[D2DRequiresDoublePrecisionSupport]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct ReflectedShaderWithDoubleOperations : ID2D1PixelShader
|
||||
{
|
||||
private readonly double amount;
|
||||
|
||||
public float4 Execute()
|
||||
{
|
||||
return (float4)(D2D.GetInput(0) + (double4)this.amount);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,945 +0,0 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Threading;
|
||||
using ComputeSharp.D2D1.Interop;
|
||||
using ComputeSharp.D2D1.Tests.Helpers;
|
||||
using ComputeSharp.Tests.Helpers;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
using TerraFX.Interop.DirectX;
|
||||
using TerraFX.Interop.Windows;
|
||||
|
||||
#pragma warning disable CS0649, IDE0044
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests;
|
||||
|
||||
[TestClass]
|
||||
public partial class D2D1ResourceTextureManagerTests
|
||||
{
|
||||
[TestMethod]
|
||||
public unsafe void VerifyInterfaces()
|
||||
{
|
||||
using ComPtr<IUnknown> resourceTextureManager = default;
|
||||
|
||||
D2D1ResourceTextureManager.Create((void**)resourceTextureManager.GetAddressOf());
|
||||
|
||||
Assert.IsTrue(resourceTextureManager.Get() is not null);
|
||||
|
||||
_ = resourceTextureManager.Get()->AddRef();
|
||||
|
||||
Assert.AreEqual(1u, resourceTextureManager.Get()->Release());
|
||||
|
||||
using ComPtr<IUnknown> unknown = default;
|
||||
using ComPtr<IUnknown> resourceTextureManager2 = default;
|
||||
using ComPtr<IUnknown> resourceTextureManagerInternal = default;
|
||||
|
||||
Guid uuidOfIUnknown = typeof(IUnknown).GUID;
|
||||
Guid uuidOfResourceTextureManager = new("3C4FC7E4-A419-46CA-B5F6-66EB4FF18D64");
|
||||
Guid uuidOfResourceTextureManagerInternal = new("5CBB1024-8EA1-4689-81BF-8AD190B5EF5D");
|
||||
|
||||
// The object implements IUnknown and the two resource texture manager interfaces
|
||||
Assert.AreEqual(0, (int)resourceTextureManager.AsIID(&uuidOfIUnknown, &unknown));
|
||||
Assert.AreEqual(0, (int)resourceTextureManager.AsIID(&uuidOfResourceTextureManager, &resourceTextureManager2));
|
||||
Assert.AreEqual(0, (int)resourceTextureManager.AsIID(&uuidOfResourceTextureManagerInternal, &resourceTextureManagerInternal));
|
||||
|
||||
Assert.IsTrue(unknown.Get() is not null);
|
||||
Assert.IsTrue(resourceTextureManager2.Get() is not null);
|
||||
Assert.IsTrue(resourceTextureManagerInternal.Get() is not null);
|
||||
|
||||
using ComPtr<IUnknown> garbage = default;
|
||||
|
||||
Guid uuidOfGarbage = Guid.NewGuid();
|
||||
|
||||
// Any other random QueryInterface should fail
|
||||
Assert.AreEqual(E.E_NOINTERFACE, (int)resourceTextureManager.AsIID(&uuidOfGarbage, &garbage));
|
||||
|
||||
Assert.IsTrue(garbage.Get() is null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void VerifyInterfaces_RCW()
|
||||
{
|
||||
D2D1ResourceTextureManager resourceTextureManager = new(
|
||||
extents: [64],
|
||||
bufferPrecision: D2D1BufferPrecision.UInt8Normalized,
|
||||
channelDepth: D2D1ChannelDepth.Four,
|
||||
filter: D2D1Filter.MinLinearMagMipPoint,
|
||||
extendModes: [D2D1ExtendMode.Clamp]);
|
||||
|
||||
using ComPtr<IUnknown> unknown = default;
|
||||
using ComPtr<IUnknown> resourceTextureManager2 = default;
|
||||
using ComPtr<IUnknown> resourceTextureManagerInternal = default;
|
||||
|
||||
Guid uuidOfIUnknown = typeof(IUnknown).GUID;
|
||||
Guid uuidOfResourceTextureManager = new("3C4FC7E4-A419-46CA-B5F6-66EB4FF18D64");
|
||||
Guid uuidOfResourceTextureManagerInternal = new("5CBB1024-8EA1-4689-81BF-8AD190B5EF5D");
|
||||
|
||||
// The object implements IUnknown and the two resource texture manager interfaces
|
||||
Assert.AreEqual(CustomQueryInterfaceResult.Handled, ((ICustomQueryInterface)resourceTextureManager).GetInterface(ref uuidOfIUnknown, out *(IntPtr*)unknown.GetAddressOf()));
|
||||
Assert.AreEqual(CustomQueryInterfaceResult.Handled, ((ICustomQueryInterface)resourceTextureManager).GetInterface(ref uuidOfResourceTextureManager, out *(IntPtr*)resourceTextureManager2.GetAddressOf()));
|
||||
Assert.AreEqual(CustomQueryInterfaceResult.Handled, ((ICustomQueryInterface)resourceTextureManager).GetInterface(ref uuidOfResourceTextureManagerInternal, out *(IntPtr*)resourceTextureManagerInternal.GetAddressOf()));
|
||||
|
||||
Assert.IsTrue(unknown.Get() is not null);
|
||||
Assert.IsTrue(resourceTextureManager2.Get() is not null);
|
||||
Assert.IsTrue(resourceTextureManagerInternal.Get() is not null);
|
||||
|
||||
using ComPtr<IUnknown> garbage = default;
|
||||
|
||||
Guid uuidOfGarbage = Guid.NewGuid();
|
||||
|
||||
// Any other random QueryInterface should fail
|
||||
Assert.AreEqual(CustomQueryInterfaceResult.Failed, ((ICustomQueryInterface)resourceTextureManager).GetInterface(ref uuidOfGarbage, out *(IntPtr*)garbage.GetAddressOf()));
|
||||
|
||||
Assert.IsTrue(garbage.Get() is null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void VerifyReferenceCounting()
|
||||
{
|
||||
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2();
|
||||
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
|
||||
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
|
||||
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<DummyShaderWithResourceTexture>(d2D1Factory2.Get(), out _);
|
||||
|
||||
using ComPtr<IUnknown> resourceTextureManager = default;
|
||||
|
||||
D2D1ResourceTextureManager.Create((void**)resourceTextureManager.GetAddressOf());
|
||||
|
||||
_ = resourceTextureManager.Get()->AddRef();
|
||||
|
||||
// Right after creation, the manager has only 1 ref count
|
||||
Assert.AreEqual(1u, resourceTextureManager.Get()->Release());
|
||||
|
||||
using (ComPtr<ID2D1Effect> d2D1Effect = default)
|
||||
{
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<DummyShaderWithResourceTexture>(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf());
|
||||
|
||||
D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(d2D1Effect.Get(), resourceTextureManager.Get(), 0);
|
||||
|
||||
_ = resourceTextureManager.Get()->AddRef();
|
||||
|
||||
// After setting a manager to an effect, the manager also has a reference
|
||||
Assert.AreEqual(2u, resourceTextureManager.Get()->Release());
|
||||
|
||||
D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(d2D1Effect.Get(), resourceTextureManager.Get(), 0);
|
||||
|
||||
_ = resourceTextureManager.Get()->AddRef();
|
||||
|
||||
// Adding the same manager again doesn't increment ref count
|
||||
Assert.AreEqual(2u, resourceTextureManager.Get()->Release());
|
||||
}
|
||||
|
||||
_ = resourceTextureManager.Get()->AddRef();
|
||||
|
||||
// If the effect is released, that extra manager reference is also released
|
||||
Assert.AreEqual(1u, resourceTextureManager.Get()->Release());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(Win32Exception))]
|
||||
public unsafe void SingleThreadedFactory_AssigningRCWManagerFails()
|
||||
{
|
||||
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2(singleThreaded: true);
|
||||
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
|
||||
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
|
||||
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<DummyShaderWithResourceTexture>(d2D1Factory2.Get(), out _);
|
||||
|
||||
D2D1ResourceTextureManager resourceTextureManager = new(
|
||||
extents: [128, 128],
|
||||
bufferPrecision: D2D1BufferPrecision.UInt8Normalized,
|
||||
channelDepth: D2D1ChannelDepth.Four,
|
||||
filter: D2D1Filter.MinMagMipPoint,
|
||||
extendModes: [D2D1ExtendMode.Clamp, D2D1ExtendMode.Clamp],
|
||||
data: [],
|
||||
strides: []);
|
||||
|
||||
using ComPtr<ID2D1Effect> d2D1Effect = default;
|
||||
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<DummyShaderWithResourceTexture>(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf());
|
||||
|
||||
D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(d2D1Effect.Get(), resourceTextureManager, 0);
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DRequiresScenePosition]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct DummyShaderWithResourceTexture : ID2D1PixelShader
|
||||
{
|
||||
[D2DResourceTextureIndex(0)]
|
||||
private readonly D2D1ResourceTexture2D<float4> source;
|
||||
|
||||
public float4 Execute()
|
||||
{
|
||||
int2 xy = (int2)D2D.GetScenePosition().XY;
|
||||
|
||||
return this.source[xy];
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void LoadPixelsFromResourceTexture2D_CreateAfterGettingEffectContext()
|
||||
{
|
||||
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2();
|
||||
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
|
||||
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
|
||||
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<IndexFrom2DResourceTextureShader>(d2D1Factory2.Get(), out _);
|
||||
|
||||
using ComPtr<ID2D1Effect> d2D1Effect = default;
|
||||
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<IndexFrom2DResourceTextureShader>(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf());
|
||||
|
||||
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), default(IndexFrom2DResourceTextureShader));
|
||||
|
||||
using ComPtr<IUnknown> resourceTextureManager = default;
|
||||
|
||||
D2D1ResourceTextureManager.Create((void**)resourceTextureManager.GetAddressOf());
|
||||
|
||||
D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(d2D1Effect.Get(), resourceTextureManager.Get(), 0);
|
||||
|
||||
string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!;
|
||||
string expectedPath = Path.Combine(assemblyPath, "Assets", "Landscape.png");
|
||||
|
||||
using Image<Rgba32> expected = Image.Load<Rgba32>(expectedPath);
|
||||
|
||||
if (!expected.DangerousTryGetSinglePixelMemory(out Memory<Rgba32> pixels))
|
||||
{
|
||||
Assert.Inconclusive();
|
||||
}
|
||||
|
||||
D2D1ResourceTextureManager.Initialize(
|
||||
resourceTextureManager: resourceTextureManager.Get(),
|
||||
resourceId: Guid.NewGuid(),
|
||||
extents: [(uint)expected.Width, (uint)expected.Height],
|
||||
bufferPrecision: D2D1BufferPrecision.UInt8Normalized,
|
||||
channelDepth: D2D1ChannelDepth.Four,
|
||||
filter: D2D1Filter.MinMagMipPoint,
|
||||
extendModes: [D2D1ExtendMode.Clamp, D2D1ExtendMode.Clamp],
|
||||
data: MemoryMarshal.AsBytes(pixels.Span),
|
||||
strides: [(uint)(sizeof(Rgba32) * expected.Width)]);
|
||||
|
||||
using ComPtr<ID2D1Bitmap> d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), (uint)expected.Width, (uint)expected.Height);
|
||||
|
||||
D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get());
|
||||
|
||||
using ComPtr<ID2D1Bitmap1> d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect);
|
||||
|
||||
string destinationPath = Path.Combine(assemblyPath, "temp", "IndexedFromResourceTexture2D_After.png");
|
||||
|
||||
_ = Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!);
|
||||
|
||||
ImageHelper.SaveBitmapToFile(destinationPath, (uint)expected.Width, (uint)expected.Height, d2D1MappedRect.pitch, d2D1MappedRect.bits);
|
||||
|
||||
TolerantImageComparer.AssertEqual(destinationPath, expectedPath, 0.00001f);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(1)]
|
||||
[DataRow(2)]
|
||||
public unsafe void LoadPixelsFromResourceTexture2D_CreateBeforeGettingEffectContext(int drawCount)
|
||||
{
|
||||
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2();
|
||||
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
|
||||
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
|
||||
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<IndexFrom2DResourceTextureShader>(d2D1Factory2.Get(), out _);
|
||||
|
||||
using ComPtr<ID2D1Effect> d2D1Effect = default;
|
||||
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<IndexFrom2DResourceTextureShader>(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf());
|
||||
|
||||
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), default(IndexFrom2DResourceTextureShader));
|
||||
|
||||
using ComPtr<IUnknown> resourceTextureManager = default;
|
||||
|
||||
D2D1ResourceTextureManager.Create((void**)resourceTextureManager.GetAddressOf());
|
||||
|
||||
string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!;
|
||||
string expectedPath = Path.Combine(assemblyPath, "Assets", "Landscape.png");
|
||||
|
||||
using Image<Rgba32> expected = Image.Load<Rgba32>(expectedPath);
|
||||
|
||||
if (!expected.DangerousTryGetSinglePixelMemory(out Memory<Rgba32> pixels))
|
||||
{
|
||||
Assert.Inconclusive();
|
||||
}
|
||||
|
||||
using ComPtr<ID2D1Bitmap> d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), (uint)expected.Width, (uint)expected.Height);
|
||||
|
||||
D2D1ResourceTextureManager.Initialize(
|
||||
resourceTextureManager: resourceTextureManager.Get(),
|
||||
resourceId: Guid.NewGuid(),
|
||||
extents: [(uint)expected.Width, (uint)expected.Height],
|
||||
bufferPrecision: D2D1BufferPrecision.UInt8Normalized,
|
||||
channelDepth: D2D1ChannelDepth.Four,
|
||||
filter: D2D1Filter.MinMagMipPoint,
|
||||
extendModes: [D2D1ExtendMode.Clamp, D2D1ExtendMode.Clamp],
|
||||
data: MemoryMarshal.AsBytes(pixels.Span),
|
||||
strides: [(uint)(sizeof(Rgba32) * expected.Width)]);
|
||||
|
||||
for (int i = 0; i < drawCount; i++)
|
||||
{
|
||||
// We need to reassign the resource texture manager before each draw, so the D2D runtime can see
|
||||
// some effect property has changed, and it will call PrepareForRender. That's where the resource
|
||||
// texture will be retrieved. When drawCount is more than 1, this test is used to validate that
|
||||
// getting the resource texture multiple times from the same manager also works correctly.
|
||||
D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(d2D1Effect.Get(), resourceTextureManager.Get(), 0);
|
||||
|
||||
D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get());
|
||||
}
|
||||
|
||||
using ComPtr<ID2D1Bitmap1> d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect);
|
||||
|
||||
string destinationPath = Path.Combine(assemblyPath, "temp", $"IndexedFromResourceTexture2D_Before_Draw{drawCount}.png");
|
||||
|
||||
_ = Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!);
|
||||
|
||||
ImageHelper.SaveBitmapToFile(destinationPath, (uint)expected.Width, (uint)expected.Height, d2D1MappedRect.pitch, d2D1MappedRect.bits);
|
||||
|
||||
TolerantImageComparer.AssertEqual(destinationPath, expectedPath, 0.00001f);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void LoadPixelsFromResourceTexture2D_CreateBeforeGettingEffectContext_RCW()
|
||||
{
|
||||
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2();
|
||||
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
|
||||
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
|
||||
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<IndexFrom2DResourceTextureShader>(d2D1Factory2.Get(), out _);
|
||||
|
||||
using ComPtr<ID2D1Effect> d2D1Effect = default;
|
||||
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<IndexFrom2DResourceTextureShader>(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf());
|
||||
|
||||
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), default(IndexFrom2DResourceTextureShader));
|
||||
|
||||
string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!;
|
||||
string expectedPath = Path.Combine(assemblyPath, "Assets", "Landscape.png");
|
||||
|
||||
using Image<Rgba32> expected = Image.Load<Rgba32>(expectedPath);
|
||||
|
||||
if (!expected.DangerousTryGetSinglePixelMemory(out Memory<Rgba32> pixels))
|
||||
{
|
||||
Assert.Inconclusive();
|
||||
}
|
||||
|
||||
D2D1ResourceTextureManager resourceTextureManager = new(
|
||||
resourceId: Guid.NewGuid(),
|
||||
extents: [(uint)expected.Width, (uint)expected.Height],
|
||||
bufferPrecision: D2D1BufferPrecision.UInt8Normalized,
|
||||
channelDepth: D2D1ChannelDepth.Four,
|
||||
filter: D2D1Filter.MinMagMipPoint,
|
||||
extendModes: [D2D1ExtendMode.Clamp, D2D1ExtendMode.Clamp],
|
||||
data: MemoryMarshal.AsBytes(pixels.Span),
|
||||
strides: [(uint)(sizeof(Rgba32) * expected.Width)]);
|
||||
|
||||
using ComPtr<IUnknown> unknown = default;
|
||||
|
||||
Guid uuidOfIUnknown = typeof(IUnknown).GUID;
|
||||
|
||||
Assert.AreEqual(CustomQueryInterfaceResult.Handled, ((ICustomQueryInterface)resourceTextureManager).GetInterface(ref uuidOfIUnknown, out *(IntPtr*)unknown.GetAddressOf()));
|
||||
|
||||
D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(d2D1Effect.Get(), unknown.Get(), 0);
|
||||
|
||||
using ComPtr<ID2D1Bitmap> d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), (uint)expected.Width, (uint)expected.Height);
|
||||
|
||||
D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get());
|
||||
|
||||
using ComPtr<ID2D1Bitmap1> d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect);
|
||||
|
||||
string destinationPath = Path.Combine(assemblyPath, "temp", "IndexedFromResourceTexture2D_Before.png");
|
||||
|
||||
_ = Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!);
|
||||
|
||||
ImageHelper.SaveBitmapToFile(destinationPath, (uint)expected.Width, (uint)expected.Height, d2D1MappedRect.pitch, d2D1MappedRect.bits);
|
||||
|
||||
TolerantImageComparer.AssertEqual(destinationPath, expectedPath, 0.00001f);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void LoadPixelsFromResourceTexture2D_AlternatingResourceTextureManagers()
|
||||
{
|
||||
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2();
|
||||
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
|
||||
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
|
||||
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<IndexFrom2DResourceTextureShader>(d2D1Factory2.Get(), out _);
|
||||
|
||||
string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!;
|
||||
string wallpaper0Path = Path.Combine(assemblyPath, "Assets", "Wallpaper0.png");
|
||||
string wallpaper1Path = Path.Combine(assemblyPath, "Assets", "Wallpaper1.png");
|
||||
|
||||
using Image<Rgba32> expected0 = Image.Load<Rgba32>(wallpaper0Path);
|
||||
using Image<Rgba32> expected1 = Image.Load<Rgba32>(wallpaper1Path);
|
||||
|
||||
Memory<Rgba32> pixels0 = Memory<Rgba32>.Empty;
|
||||
Memory<Rgba32> pixels1 = Memory<Rgba32>.Empty;
|
||||
|
||||
if (!expected0.DangerousTryGetSinglePixelMemory(out pixels0) ||
|
||||
!expected1.DangerousTryGetSinglePixelMemory(out pixels1))
|
||||
{
|
||||
Assert.Inconclusive();
|
||||
}
|
||||
|
||||
using ComPtr<IUnknown> resourceTextureManager0 = default;
|
||||
using ComPtr<IUnknown> resourceTextureManager1 = default;
|
||||
|
||||
D2D1ResourceTextureManager.Create((void**)resourceTextureManager0.GetAddressOf());
|
||||
D2D1ResourceTextureManager.Create((void**)resourceTextureManager1.GetAddressOf());
|
||||
|
||||
D2D1ResourceTextureManager.Initialize(
|
||||
resourceTextureManager: resourceTextureManager0.Get(),
|
||||
resourceId: Guid.NewGuid(),
|
||||
extents: [(uint)expected0.Width, (uint)expected0.Height],
|
||||
bufferPrecision: D2D1BufferPrecision.UInt8Normalized,
|
||||
channelDepth: D2D1ChannelDepth.Four,
|
||||
filter: D2D1Filter.MinMagMipPoint,
|
||||
extendModes: [D2D1ExtendMode.Clamp, D2D1ExtendMode.Clamp],
|
||||
data: MemoryMarshal.AsBytes(pixels0.Span),
|
||||
strides: [(uint)(sizeof(Rgba32) * expected0.Width)]);
|
||||
|
||||
D2D1ResourceTextureManager.Initialize(
|
||||
resourceTextureManager: resourceTextureManager1.Get(),
|
||||
resourceId: Guid.NewGuid(),
|
||||
extents: [(uint)expected0.Width, (uint)expected0.Height],
|
||||
bufferPrecision: D2D1BufferPrecision.UInt8Normalized,
|
||||
channelDepth: D2D1ChannelDepth.Four,
|
||||
filter: D2D1Filter.MinMagMipPoint,
|
||||
extendModes: [D2D1ExtendMode.Clamp, D2D1ExtendMode.Clamp],
|
||||
data: MemoryMarshal.AsBytes(pixels1.Span),
|
||||
strides: [(uint)(sizeof(Rgba32) * expected0.Width)]);
|
||||
|
||||
using (ComPtr<ID2D1Effect> d2D1Effect = default)
|
||||
{
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<IndexFrom2DResourceTextureShader>(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf());
|
||||
|
||||
using ComPtr<ID2D1Bitmap> d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), (uint)expected0.Width, (uint)expected0.Height);
|
||||
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
ref readonly ComPtr<IUnknown> resourceTextureManager = ref i % 2 == 0
|
||||
? ref resourceTextureManager0
|
||||
: ref resourceTextureManager1;
|
||||
|
||||
D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(d2D1Effect.Get(), resourceTextureManager.Get(), 0);
|
||||
|
||||
D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get());
|
||||
|
||||
using ComPtr<ID2D1Bitmap1> d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect);
|
||||
|
||||
string destinationPath = Path.Combine(assemblyPath, "temp", $"LoadPixelsFromResourceTexture2D_Alternating{i}.png");
|
||||
|
||||
_ = Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!);
|
||||
|
||||
ImageHelper.SaveBitmapToFile(destinationPath, (uint)expected0.Width, (uint)expected0.Height, d2D1MappedRect.pitch, d2D1MappedRect.bits);
|
||||
|
||||
string expectedPath = i % 2 == 0 ? wallpaper0Path : wallpaper1Path;
|
||||
|
||||
TolerantImageComparer.AssertEqual(destinationPath, expectedPath, 0.00001f);
|
||||
}
|
||||
}
|
||||
|
||||
_ = resourceTextureManager0.Get()->AddRef();
|
||||
|
||||
Assert.AreEqual(1u, resourceTextureManager0.Get()->Release());
|
||||
|
||||
_ = resourceTextureManager1.Get()->AddRef();
|
||||
|
||||
Assert.AreEqual(1u, resourceTextureManager1.Get()->Release());
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DRequiresScenePosition]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct IndexFrom2DResourceTextureShader : ID2D1PixelShader
|
||||
{
|
||||
[D2DResourceTextureIndex(0)]
|
||||
private readonly D2D1ResourceTexture2D<float4> source;
|
||||
|
||||
public float4 Execute()
|
||||
{
|
||||
int2 xy = (int2)D2D.GetScenePosition().XY;
|
||||
|
||||
return this.source[xy];
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void LoadPixelsFromResourceTexture3D()
|
||||
{
|
||||
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2();
|
||||
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
|
||||
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
|
||||
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<IndexFrom3DResourceTextureShader>(d2D1Factory2.Get(), out _);
|
||||
|
||||
using ComPtr<ID2D1Effect> d2D1Effect = default;
|
||||
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<IndexFrom3DResourceTextureShader>(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf());
|
||||
|
||||
string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!;
|
||||
string expectedPath = Path.Combine(assemblyPath, "Assets", "WallpapersStack.png");
|
||||
|
||||
using Image<Rgba32> expected = Image.Load<Rgba32>(expectedPath);
|
||||
|
||||
if (!expected.DangerousTryGetSinglePixelMemory(out Memory<Rgba32> pixels))
|
||||
{
|
||||
Assert.Inconclusive();
|
||||
}
|
||||
|
||||
IndexFrom3DResourceTextureShader shader = new(expected.Height / 4);
|
||||
|
||||
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), in shader);
|
||||
|
||||
using ComPtr<IUnknown> resourceTextureManager = default;
|
||||
|
||||
D2D1ResourceTextureManager.Create((void**)resourceTextureManager.GetAddressOf());
|
||||
|
||||
D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(d2D1Effect.Get(), resourceTextureManager.Get(), 0);
|
||||
|
||||
D2D1ResourceTextureManager.Initialize(
|
||||
resourceTextureManager: resourceTextureManager.Get(),
|
||||
resourceId: Guid.NewGuid(),
|
||||
extents: [(uint)expected.Width, (uint)(expected.Height / 4), 4u],
|
||||
bufferPrecision: D2D1BufferPrecision.UInt8Normalized,
|
||||
channelDepth: D2D1ChannelDepth.Four,
|
||||
filter: D2D1Filter.MinMagMipPoint,
|
||||
extendModes: [D2D1ExtendMode.Clamp, D2D1ExtendMode.Clamp, D2D1ExtendMode.Clamp],
|
||||
data: MemoryMarshal.AsBytes(pixels.Span),
|
||||
strides: [(uint)(sizeof(Rgba32) * expected.Width), (uint)(sizeof(Rgba32) * expected.Width * (expected.Height / 4))]);
|
||||
|
||||
using ComPtr<ID2D1Bitmap> d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), (uint)expected.Width, (uint)expected.Height);
|
||||
|
||||
D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get());
|
||||
|
||||
using ComPtr<ID2D1Bitmap1> d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect);
|
||||
|
||||
string destinationPath = Path.Combine(assemblyPath, "temp", "IndexedFromResourceTexture3D.png");
|
||||
|
||||
_ = Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!);
|
||||
|
||||
ImageHelper.SaveBitmapToFile(destinationPath, (uint)expected.Width, (uint)expected.Height, d2D1MappedRect.pitch, d2D1MappedRect.bits);
|
||||
|
||||
TolerantImageComparer.AssertEqual(destinationPath, expectedPath, 0.00001f);
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DRequiresScenePosition]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct IndexFrom3DResourceTextureShader(float height) : ID2D1PixelShader
|
||||
{
|
||||
[D2DResourceTextureIndex(0)]
|
||||
private readonly D2D1ResourceTexture3D<float4> source;
|
||||
|
||||
public float4 Execute()
|
||||
{
|
||||
int2 xy = (int2)D2D.GetScenePosition().XY;
|
||||
|
||||
int x = xy.X;
|
||||
int y = (int)((uint)xy.Y % (uint)height);
|
||||
int z = (int)((uint)xy.Y / (uint)height);
|
||||
|
||||
return this.source[x, y, z];
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(128, 0, 26)]
|
||||
[DataRow(128, 0, 67)]
|
||||
[DataRow(128, 0, 128)]
|
||||
[DataRow(128, 32, 64)]
|
||||
[DataRow(1024, 311, 489)]
|
||||
[DataRow(1024, 907, 117)]
|
||||
public unsafe void UpdateResourceTexture1D(int width, int startOffset, int updateLength)
|
||||
{
|
||||
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2();
|
||||
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
|
||||
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
|
||||
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<CopyFromResourceTexture1DShader>(d2D1Factory2.Get(), out _);
|
||||
|
||||
using ComPtr<ID2D1Effect> d2D1Effect = default;
|
||||
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<CopyFromResourceTexture1DShader>(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf());
|
||||
|
||||
CopyFromResourceTexture1DShader shader = new();
|
||||
|
||||
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), in shader);
|
||||
|
||||
byte[] texture = new byte[width];
|
||||
|
||||
D2D1ResourceTextureManager resourceTextureManager = new(
|
||||
extents: [(uint)width],
|
||||
bufferPrecision: D2D1BufferPrecision.UInt8Normalized,
|
||||
channelDepth: D2D1ChannelDepth.One,
|
||||
filter: D2D1Filter.MinMagMipPoint,
|
||||
extendModes: [D2D1ExtendMode.Clamp],
|
||||
data: texture,
|
||||
strides: null);
|
||||
|
||||
byte[] data = new byte[updateLength];
|
||||
|
||||
RandomNumberGenerator.Create().GetBytes(data);
|
||||
|
||||
resourceTextureManager.Update(
|
||||
minimumExtents: [(uint)startOffset],
|
||||
maximimumExtents: [(uint)(startOffset + updateLength)],
|
||||
strides: [],
|
||||
data: data);
|
||||
|
||||
data.CopyTo(texture.AsSpan(startOffset));
|
||||
|
||||
D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(d2D1Effect.Get(), resourceTextureManager, 0);
|
||||
|
||||
using ComPtr<ID2D1Bitmap> d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), (uint)width, 1);
|
||||
|
||||
D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get());
|
||||
|
||||
using ComPtr<ID2D1Bitmap1> d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect);
|
||||
|
||||
byte[] resultingBytes = new byte[width];
|
||||
int i = 0;
|
||||
|
||||
foreach (Bgra32 pixel in new ReadOnlySpan<Bgra32>(d2D1MappedRect.bits, width))
|
||||
{
|
||||
resultingBytes[i++] = pixel.B;
|
||||
}
|
||||
|
||||
Assert.IsTrue(texture.AsSpan().SequenceEqual(resultingBytes));
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DRequiresScenePosition]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct CopyFromResourceTexture1DShader : ID2D1PixelShader
|
||||
{
|
||||
[D2DResourceTextureIndex(0)]
|
||||
private readonly D2D1ResourceTexture1D<float> source;
|
||||
|
||||
public float4 Execute()
|
||||
{
|
||||
int2 xy = (int2)D2D.GetScenePosition().XY;
|
||||
|
||||
return this.source[xy.X];
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(64, 64, 0, 0, 64, 64)]
|
||||
[DataRow(64, 64, 32, 32, 32, 32)]
|
||||
[DataRow(64, 64, 12, 33, 43, 22)]
|
||||
[DataRow(512, 768, 245, 111, 255, 461)]
|
||||
[DataRow(1024, 2048, 11, 899, 512, 342)]
|
||||
public unsafe void UpdateResourceTexture2D(
|
||||
int width,
|
||||
int height,
|
||||
int startOffsetX,
|
||||
int startOffsetY,
|
||||
int updateLengthX,
|
||||
int updateLengthY)
|
||||
{
|
||||
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2();
|
||||
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
|
||||
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
|
||||
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<CopyFromResourceTexture2DShader>(d2D1Factory2.Get(), out _);
|
||||
|
||||
using ComPtr<ID2D1Effect> d2D1Effect = default;
|
||||
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<CopyFromResourceTexture2DShader>(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf());
|
||||
|
||||
CopyFromResourceTexture2DShader shader = new();
|
||||
|
||||
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), in shader);
|
||||
|
||||
byte[] texture = new byte[width * height];
|
||||
|
||||
D2D1ResourceTextureManager resourceTextureManager = new(
|
||||
extents: [(uint)width, (uint)height],
|
||||
bufferPrecision: D2D1BufferPrecision.UInt8Normalized,
|
||||
channelDepth: D2D1ChannelDepth.One,
|
||||
filter: D2D1Filter.MinMagMipPoint,
|
||||
extendModes: [D2D1ExtendMode.Clamp, D2D1ExtendMode.Clamp],
|
||||
data: texture,
|
||||
strides: [(uint)width]);
|
||||
|
||||
byte[] data = new byte[updateLengthX * updateLengthY];
|
||||
|
||||
RandomNumberGenerator.Create().GetBytes(data);
|
||||
|
||||
resourceTextureManager.Update(
|
||||
minimumExtents: [(uint)startOffsetX, (uint)startOffsetY],
|
||||
maximimumExtents: [(uint)(startOffsetX + updateLengthX), (uint)(startOffsetY + updateLengthY)],
|
||||
strides: [(uint)updateLengthX],
|
||||
data: data);
|
||||
|
||||
for (int y = 0; y < updateLengthY; y++)
|
||||
{
|
||||
ReadOnlySpan<byte> source = data.AsSpan(y * updateLengthX, updateLengthX);
|
||||
Span<byte> destination = texture.AsSpan((startOffsetY * width) + (y * width) + startOffsetX, updateLengthX);
|
||||
|
||||
source.CopyTo(destination);
|
||||
}
|
||||
|
||||
D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(d2D1Effect.Get(), resourceTextureManager, 0);
|
||||
|
||||
using ComPtr<ID2D1Bitmap> d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), (uint)width, (uint)height);
|
||||
|
||||
D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get());
|
||||
|
||||
using ComPtr<ID2D1Bitmap1> d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect);
|
||||
|
||||
byte[] resultingBytes = new byte[width * height];
|
||||
int i = 0;
|
||||
|
||||
for (int y = 0; y < height; y++)
|
||||
{
|
||||
foreach (Bgra32 pixel in new ReadOnlySpan<Bgra32>(d2D1MappedRect.bits + (d2D1MappedRect.pitch * y), width))
|
||||
{
|
||||
resultingBytes[i++] = pixel.B;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsTrue(texture.AsSpan().SequenceEqual(resultingBytes));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void UpdateResourceTexture2D_ConcurrentAccess_DoesNotDeadlock()
|
||||
{
|
||||
const int width = 4096;
|
||||
const int height = 4096;
|
||||
|
||||
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2();
|
||||
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
|
||||
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
|
||||
using ComPtr<ID2D1Bitmap> d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), width, height);
|
||||
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<CopyFromResourceTexture2DShader>(d2D1Factory2.Get(), out _);
|
||||
|
||||
using ComPtr<ID2D1Effect> d2D1Effect = default;
|
||||
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<CopyFromResourceTexture2DShader>(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf());
|
||||
|
||||
CopyFromResourceTexture2DShader shader = new();
|
||||
|
||||
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), in shader);
|
||||
|
||||
byte[] texture = new byte[width * height];
|
||||
|
||||
D2D1ResourceTextureManager resourceTextureManager = new(
|
||||
extents: [width, height],
|
||||
bufferPrecision: D2D1BufferPrecision.UInt8Normalized,
|
||||
channelDepth: D2D1ChannelDepth.One,
|
||||
filter: D2D1Filter.MinMagMipPoint,
|
||||
extendModes: [D2D1ExtendMode.Clamp, D2D1ExtendMode.Clamp],
|
||||
data: texture,
|
||||
strides: [width]);
|
||||
|
||||
D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(d2D1Effect.Get(), resourceTextureManager, 0);
|
||||
|
||||
CancellationTokenSource cancellationTokenSource = new(TimeSpan.FromSeconds(20));
|
||||
|
||||
// Thread As are constantly updating the resource texture
|
||||
void UpdateResourceTexture()
|
||||
{
|
||||
ReadOnlySpan<uint> minimumExtents = [0, 0];
|
||||
ReadOnlySpan<uint> maximumExtents = [width, height];
|
||||
ReadOnlySpan<uint> strides = [width];
|
||||
|
||||
while (!cancellationTokenSource.IsCancellationRequested)
|
||||
{
|
||||
resourceTextureManager.Update(
|
||||
minimumExtents: minimumExtents,
|
||||
maximimumExtents: maximumExtents,
|
||||
strides: strides,
|
||||
data: texture);
|
||||
}
|
||||
}
|
||||
|
||||
// Thread Bs are constantly drawing on the target bitmap
|
||||
void Draw()
|
||||
{
|
||||
while (!cancellationTokenSource.IsCancellationRequested)
|
||||
{
|
||||
D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get());
|
||||
}
|
||||
}
|
||||
|
||||
Thread threadA = new(UpdateResourceTexture);
|
||||
Thread threadB = new(Draw);
|
||||
|
||||
threadA.Start();
|
||||
threadB.Start();
|
||||
|
||||
threadA.Join();
|
||||
threadB.Join();
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DRequiresScenePosition]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct CopyFromResourceTexture2DShader : ID2D1PixelShader
|
||||
{
|
||||
[D2DResourceTextureIndex(0)]
|
||||
private readonly D2D1ResourceTexture2D<float> source;
|
||||
|
||||
public float4 Execute()
|
||||
{
|
||||
int2 xy = (int2)D2D.GetScenePosition().XY;
|
||||
|
||||
return this.source[xy];
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(64, 64, 3, 0, 0, 0, 64, 64, 3)]
|
||||
[DataRow(64, 64, 3, 10, 22, 1, 44, 33, 1)]
|
||||
[DataRow(64, 64, 3, 10, 22, 1, 44, 33, 2)]
|
||||
[DataRow(64, 64, 3, 10, 22, 0, 44, 33, 2)]
|
||||
[DataRow(512, 512, 6, 245, 0, 2, 188, 1, 4)]
|
||||
[DataRow(512, 512, 6, 245, 0, 2, 188, 467, 3)]
|
||||
[DataRow(512, 512, 6, 245, 113, 1, 256, 322, 2)]
|
||||
public unsafe void UpdateResourceTexture3D(
|
||||
int width,
|
||||
int height,
|
||||
int depth,
|
||||
int startOffsetX,
|
||||
int startOffsetY,
|
||||
int startOffsetZ,
|
||||
int updateLengthX,
|
||||
int updateLengthY,
|
||||
int updateLengthZ)
|
||||
{
|
||||
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2();
|
||||
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
|
||||
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
|
||||
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<CopyFromResourceTexture3DShader>(d2D1Factory2.Get(), out _);
|
||||
|
||||
using ComPtr<ID2D1Effect> d2D1Effect = default;
|
||||
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<CopyFromResourceTexture3DShader>(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf());
|
||||
|
||||
CopyFromResourceTexture3DShader shader = new(height);
|
||||
|
||||
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), in shader);
|
||||
|
||||
byte[] texture = new byte[width * height * depth];
|
||||
|
||||
D2D1ResourceTextureManager resourceTextureManager = new(
|
||||
extents: [(uint)width, (uint)height, (uint)depth],
|
||||
bufferPrecision: D2D1BufferPrecision.UInt8Normalized,
|
||||
channelDepth: D2D1ChannelDepth.One,
|
||||
filter: D2D1Filter.MinMagMipPoint,
|
||||
extendModes: [D2D1ExtendMode.Clamp, D2D1ExtendMode.Clamp, D2D1ExtendMode.Clamp],
|
||||
data: texture,
|
||||
strides: [(uint)width, (uint)(width * height)]);
|
||||
|
||||
byte[] data = new byte[updateLengthX * updateLengthY * updateLengthZ];
|
||||
|
||||
RandomNumberGenerator.Create().GetBytes(data);
|
||||
|
||||
resourceTextureManager.Update(
|
||||
minimumExtents: [(uint)startOffsetX, (uint)startOffsetY, (uint)startOffsetZ],
|
||||
maximimumExtents: [(uint)(startOffsetX + updateLengthX), (uint)(startOffsetY + updateLengthY), (uint)(startOffsetZ + updateLengthZ)],
|
||||
strides: [(uint)updateLengthX, (uint)(updateLengthX * updateLengthY)],
|
||||
data: data);
|
||||
|
||||
for (int z = 0; z < updateLengthZ; z++)
|
||||
{
|
||||
for (int y = 0; y < updateLengthY; y++)
|
||||
{
|
||||
ReadOnlySpan<byte> source = data.AsSpan((z * updateLengthX * updateLengthY) + (y * updateLengthX), updateLengthX);
|
||||
Span<byte> destination = texture.AsSpan(((startOffsetZ + z) * width * height) + ((startOffsetY + y) * width) + startOffsetX, updateLengthX);
|
||||
|
||||
source.CopyTo(destination);
|
||||
}
|
||||
}
|
||||
|
||||
D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(d2D1Effect.Get(), resourceTextureManager, 0);
|
||||
|
||||
using ComPtr<ID2D1Bitmap> d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), (uint)width, (uint)(height * depth));
|
||||
|
||||
D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get());
|
||||
|
||||
using ComPtr<ID2D1Bitmap1> d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect);
|
||||
|
||||
byte[] resultingBytes = new byte[width * height * depth];
|
||||
int i = 0;
|
||||
|
||||
for (int y = 0; y < height * depth; y++)
|
||||
{
|
||||
foreach (Bgra32 pixel in new ReadOnlySpan<Bgra32>(d2D1MappedRect.bits + (d2D1MappedRect.pitch * y), width))
|
||||
{
|
||||
resultingBytes[i++] = pixel.B;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsTrue(texture.AsSpan().SequenceEqual(resultingBytes));
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DRequiresScenePosition]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct CopyFromResourceTexture3DShader(float height) : ID2D1PixelShader
|
||||
{
|
||||
[D2DResourceTextureIndex(0)]
|
||||
private readonly D2D1ResourceTexture3D<float> source;
|
||||
|
||||
public float4 Execute()
|
||||
{
|
||||
int2 xy = (int2)D2D.GetScenePosition().XY;
|
||||
|
||||
int x = xy.X;
|
||||
int y = (int)((uint)xy.Y % (uint)height);
|
||||
int z = (int)((uint)xy.Y / (uint)height);
|
||||
|
||||
return this.source[x, y, z];
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(Win32Exception))]
|
||||
public unsafe void NullResourceTexture_DrawImageFails()
|
||||
{
|
||||
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2();
|
||||
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
|
||||
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
|
||||
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<NullResourceTextureShader>(d2D1Factory2.Get(), out _);
|
||||
|
||||
using ComPtr<ID2D1Effect> d2D1Effect = default;
|
||||
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<NullResourceTextureShader>(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf());
|
||||
|
||||
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), default(NullResourceTextureShader));
|
||||
|
||||
using ComPtr<ID2D1Bitmap> d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), 128, 128);
|
||||
|
||||
D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get());
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DRequiresScenePosition]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct NullResourceTextureShader : ID2D1PixelShader
|
||||
{
|
||||
[D2DResourceTextureIndex(0)]
|
||||
private readonly D2D1ResourceTexture2D<float4> source;
|
||||
|
||||
public float4 Execute()
|
||||
{
|
||||
return this.source[0, 0];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
namespace ComputeSharp.D2D1.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// A test class for the diagnostic suppressor for D2D1 resource texture fields being left uninitialized.
|
||||
/// </summary>
|
||||
internal sealed partial class D2D1ResourceTextureUninitializedFieldDiagnosticSuppressorTests
|
||||
{
|
||||
[D2DInputCount(0)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
public readonly partial struct MyShader : ID2D1PixelShader
|
||||
{
|
||||
// This test just needs to validate the project builds fine with this shader.
|
||||
// If the diagnostic suppressor wasn't working, it'd fail to build because
|
||||
// Roslyn would emit a CS0649 warning, which would be treated as an error.
|
||||
[D2DResourceTextureIndex(0)]
|
||||
private readonly D2D1ResourceTexture1D<float4> texture;
|
||||
|
||||
public float4 Execute()
|
||||
{
|
||||
return this.texture[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,318 +0,0 @@
|
||||
using System;
|
||||
using ComputeSharp.D2D1.Interop;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests;
|
||||
|
||||
[TestClass]
|
||||
public partial class D2D1ShaderCompilerTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void CompileInvertEffectWithDefaultOptions()
|
||||
{
|
||||
const string source = """
|
||||
#define D2D_INPUT_COUNT 1
|
||||
#define D2D_INPUT0_SIMPLE
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(PSMain)
|
||||
{
|
||||
float4 color = D2DGetInput(0);
|
||||
float3 rgb = saturate(1.0 - color.rgb);
|
||||
return float4(rgb, 1);
|
||||
}
|
||||
""";
|
||||
|
||||
ReadOnlyMemory<byte> bytecode = D2D1ShaderCompiler.Compile(
|
||||
source.AsSpan(),
|
||||
"PSMain".AsSpan(),
|
||||
D2D1ShaderProfile.PixelShader40Level93,
|
||||
D2D1CompileOptions.Default);
|
||||
|
||||
Assert.IsTrue(bytecode.Length > 0);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CompileInvertEffectWithDefaultOptions_Utf8()
|
||||
{
|
||||
ReadOnlySpan<byte> sourceUtf8 = """
|
||||
#define D2D_INPUT_COUNT 1
|
||||
#define D2D_INPUT0_SIMPLE
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(PSMain)
|
||||
{
|
||||
float4 color = D2DGetInput(0);
|
||||
float3 rgb = saturate(1.0 - color.rgb);
|
||||
return float4(rgb, 1);
|
||||
}
|
||||
"""u8;
|
||||
|
||||
ReadOnlyMemory<byte> bytecode = D2D1ShaderCompiler.Compile(
|
||||
sourceUtf8,
|
||||
"PSMain"u8,
|
||||
D2D1ShaderProfile.PixelShader40Level93,
|
||||
D2D1CompileOptions.Default);
|
||||
|
||||
Assert.IsTrue(bytecode.Length > 0);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CompileInvertEffectWithDefaultOptionsAndLinking()
|
||||
{
|
||||
const string source = """
|
||||
#define D2D_INPUT_COUNT 1
|
||||
#define D2D_INPUT0_SIMPLE
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(PSMain)
|
||||
{
|
||||
float4 color = D2DGetInput(0);
|
||||
float3 rgb = saturate(1.0 - color.rgb);
|
||||
return float4(rgb, 1);
|
||||
}
|
||||
""";
|
||||
|
||||
ReadOnlyMemory<byte> bytecode = D2D1ShaderCompiler.Compile(
|
||||
source.AsSpan(),
|
||||
"PSMain".AsSpan(),
|
||||
D2D1ShaderProfile.PixelShader40Level93,
|
||||
D2D1CompileOptions.Default & ~D2D1CompileOptions.EnableLinking);
|
||||
|
||||
ReadOnlyMemory<byte> bytecodeWithLinking = D2D1ShaderCompiler.Compile(
|
||||
source.AsSpan(),
|
||||
"PSMain".AsSpan(),
|
||||
D2D1ShaderProfile.PixelShader40Level93,
|
||||
D2D1CompileOptions.Default);
|
||||
|
||||
Assert.IsTrue(bytecode.Length > 800);
|
||||
Assert.IsTrue(bytecodeWithLinking.Length > 1600);
|
||||
Assert.IsTrue(bytecodeWithLinking.Length > bytecode.Length);
|
||||
Assert.IsTrue((bytecodeWithLinking.Length - bytecode.Length) > 800);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CompileInvertEffectWithDefaultOptionsAndOptimizeForSize()
|
||||
{
|
||||
const string source = """
|
||||
#define D2D_INPUT_COUNT 1
|
||||
#define D2D_INPUT0_SIMPLE
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(PSMain)
|
||||
{
|
||||
float4 color = D2DGetInput(0);
|
||||
float3 rgb = saturate(1.0 - color.rgb);
|
||||
return float4(rgb, 1);
|
||||
}
|
||||
""";
|
||||
|
||||
ReadOnlyMemory<byte> bytecode = D2D1ShaderCompiler.Compile(
|
||||
source.AsSpan(),
|
||||
"PSMain".AsSpan(),
|
||||
D2D1ShaderProfile.PixelShader40Level93,
|
||||
D2D1CompileOptions.Default);
|
||||
|
||||
ReadOnlyMemory<byte> bytecodeWithOptimizeForSize = D2D1ShaderCompiler.Compile(
|
||||
source.AsSpan(),
|
||||
"PSMain".AsSpan(),
|
||||
D2D1ShaderProfile.PixelShader40Level93,
|
||||
D2D1CompileOptions.OptimizeForSize);
|
||||
|
||||
Assert.IsTrue(bytecode.Length > 1800);
|
||||
Assert.IsTrue(bytecodeWithOptimizeForSize.Length < 600);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CompileInvertEffectWithDefaultOptionsAndStripReflectionData()
|
||||
{
|
||||
const string source = """
|
||||
#define D2D_INPUT_COUNT 1
|
||||
#define D2D_INPUT0_SIMPLE
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(PSMain)
|
||||
{
|
||||
float4 color = D2DGetInput(0);
|
||||
float3 rgb = saturate(1.0 - color.rgb);
|
||||
return float4(rgb, 1);
|
||||
}
|
||||
""";
|
||||
|
||||
ReadOnlyMemory<byte> bytecode = D2D1ShaderCompiler.Compile(
|
||||
source.AsSpan(),
|
||||
"PSMain".AsSpan(),
|
||||
D2D1ShaderProfile.PixelShader40Level93,
|
||||
D2D1CompileOptions.Default);
|
||||
|
||||
ReadOnlyMemory<byte> bytecodeWithStripReflectionData = D2D1ShaderCompiler.Compile(
|
||||
source.AsSpan(),
|
||||
"PSMain".AsSpan(),
|
||||
D2D1ShaderProfile.PixelShader40Level93,
|
||||
D2D1CompileOptions.Default | D2D1CompileOptions.StripReflectionData);
|
||||
|
||||
Assert.IsTrue(bytecode.Length > 800);
|
||||
Assert.IsTrue(bytecodeWithStripReflectionData.Length > 500);
|
||||
Assert.IsTrue(bytecode.Length > bytecodeWithStripReflectionData.Length);
|
||||
Assert.IsTrue((bytecode.Length - bytecodeWithStripReflectionData.Length) > 200);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FxcCompilationException))]
|
||||
public void CompileInvertEffectWithInvalidEntryPoint()
|
||||
{
|
||||
const string source = """
|
||||
#define D2D_INPUT_COUNT 1
|
||||
#define D2D_INPUT0_SIMPLE
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(PSMain)
|
||||
{
|
||||
float4 color = D2DGetInput(0);
|
||||
float3 rgb = saturate(1.0 - color.rgb);
|
||||
return float4(rgb, 1);
|
||||
}
|
||||
""";
|
||||
|
||||
_ = D2D1ShaderCompiler.Compile(
|
||||
source.AsSpan(),
|
||||
"Execute".AsSpan(),
|
||||
D2D1ShaderProfile.PixelShader40Level93,
|
||||
D2D1CompileOptions.Default);
|
||||
|
||||
Assert.Fail();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FxcCompilationException))]
|
||||
public void CompileInvertEffectWithErrors()
|
||||
{
|
||||
const string source = """
|
||||
#define D2D_INPUT_COUNT 1
|
||||
#define D2D_INPUT0_SIMPLE
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(PSMain)
|
||||
{
|
||||
float4 color = D2DGetInput(99);
|
||||
float3 rgb2 = saturate(1.0 - color.rgb);
|
||||
return float4(rgb, 1, 4.0);
|
||||
}
|
||||
""";
|
||||
|
||||
_ = D2D1ShaderCompiler.Compile(
|
||||
source.AsSpan(),
|
||||
"PSMain".AsSpan(),
|
||||
D2D1ShaderProfile.PixelShader40Level93,
|
||||
D2D1CompileOptions.Default);
|
||||
|
||||
Assert.Fail();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CompilePixelateEffectWithDefaultOptions()
|
||||
{
|
||||
const string source = """
|
||||
#define D2D_INPUT_COUNT 1
|
||||
#define D2D_INPUT0_COMPLEX
|
||||
#define D2D_REQUIRES_SCENE_POSITION
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
struct ComputeSharp_D2D1_Tests_Effects_PixelateEffect_Shader_Constants
|
||||
{
|
||||
int inputWidth;
|
||||
int inputHeight;
|
||||
int cellSize;
|
||||
};
|
||||
|
||||
ComputeSharp_D2D1_Tests_Effects_PixelateEffect_Shader_Constants constants;
|
||||
|
||||
D2D_PS_ENTRY(PSMain)
|
||||
{
|
||||
float2 scenePos = D2DGetScenePosition().xy;
|
||||
uint x = (uint)floor(scenePos.x);
|
||||
uint y = (uint)floor(scenePos.y);
|
||||
int cellX = (int)floor(x / constants.cellSize);
|
||||
int cellY = (int)floor(y / constants.cellSize);
|
||||
int x0 = cellX * constants.cellSize;
|
||||
int y0 = cellY * constants.cellSize;
|
||||
int x1 = min(constants.inputWidth, x0 + constants.cellSize) - 1;
|
||||
int y1 = min(constants.inputHeight, y0 + constants.cellSize) - 1;
|
||||
float4 sample0 = D2DSampleInputAtPosition(0, int2(x0, y0));
|
||||
float4 sample1 = D2DSampleInputAtPosition(0, int2(x1, y0));
|
||||
float4 sample2 = D2DSampleInputAtPosition(0, int2(x0, y1));
|
||||
float4 sample3 = D2DSampleInputAtPosition(0, int2(x1, y1));
|
||||
float4 color = (sample0 + sample1 + sample2 + sample3) / 4;
|
||||
return color;
|
||||
}
|
||||
""";
|
||||
|
||||
ReadOnlyMemory<byte> bytecode = D2D1ShaderCompiler.Compile(
|
||||
source.AsSpan(),
|
||||
"PSMain".AsSpan(),
|
||||
D2D1ShaderProfile.PixelShader40,
|
||||
D2D1CompileOptions.Default);
|
||||
|
||||
Assert.IsTrue(bytecode.Length > 0);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FxcCompilationException))]
|
||||
public void CompileShaderWithWarning()
|
||||
{
|
||||
const string source = """
|
||||
#define D2D_INPUT_COUNT 0
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
int a;
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
return a / 4;
|
||||
}
|
||||
""";
|
||||
|
||||
_ = D2D1ShaderCompiler.Compile(
|
||||
source.AsSpan(),
|
||||
"Execute".AsSpan(),
|
||||
D2D1ShaderProfile.PixelShader40,
|
||||
D2D1CompileOptions.Default);
|
||||
|
||||
Assert.Fail();
|
||||
}
|
||||
|
||||
// See https://github.com/Sergio0694/ComputeSharp/issues/647
|
||||
[TestMethod]
|
||||
public void CompileShaderWithWarning_Suppressed()
|
||||
{
|
||||
const string source = """
|
||||
#define D2D_INPUT_COUNT 0
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
int a;
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
return a / 4;
|
||||
}
|
||||
""";
|
||||
|
||||
ReadOnlyMemory<byte> bytecode = D2D1ShaderCompiler.Compile(
|
||||
source.AsSpan(),
|
||||
"Execute".AsSpan(),
|
||||
D2D1ShaderProfile.PixelShader40,
|
||||
D2D1CompileOptions.Default & ~D2D1CompileOptions.WarningsAreErrors);
|
||||
|
||||
Assert.IsTrue(bytecode.Length > 0);
|
||||
}
|
||||
}
|
||||
@@ -1,324 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeSharp.D2D1.Interop;
|
||||
using ComputeSharp.D2D1.Tests.Helpers;
|
||||
using ComputeSharp.SwapChain.Shaders.D2D1;
|
||||
using ComputeSharp.Tests.Helpers;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using TerraFX.Interop.DirectX;
|
||||
using TerraFX.Interop.Windows;
|
||||
using Rectangle = System.Drawing.Rectangle;
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests;
|
||||
|
||||
[TestClass]
|
||||
public partial class D2D1TransformMapperTests
|
||||
{
|
||||
[TestMethod]
|
||||
public unsafe void VerifyInterfaces()
|
||||
{
|
||||
D2D1DrawTransformMapper<HelloWorld> transformMapper = D2D1DrawTransformMapper<HelloWorld>.Inflate(4);
|
||||
|
||||
using ComPtr<IUnknown> unknown = default;
|
||||
using ComPtr<IUnknown> transformMapper2 = default;
|
||||
using ComPtr<IUnknown> transformMapperInternal = default;
|
||||
|
||||
Guid uuidOfIUnknown = typeof(IUnknown).GUID;
|
||||
Guid uuidOfTransformMapper = new("02E6D48D-B892-4FBC-AA54-119203BAB802");
|
||||
Guid uuidOfTransformMapperInternal = new("C5D8FC65-FB86-4C2D-9EF5-95AEC639C952");
|
||||
|
||||
// The object implements IUnknown and the transform mapper interfaces
|
||||
Assert.AreEqual(CustomQueryInterfaceResult.Handled, ((ICustomQueryInterface)transformMapper).GetInterface(ref uuidOfIUnknown, out *(IntPtr*)unknown.GetAddressOf()));
|
||||
Assert.AreEqual(CustomQueryInterfaceResult.Handled, ((ICustomQueryInterface)transformMapper).GetInterface(ref uuidOfTransformMapper, out *(IntPtr*)transformMapper2.GetAddressOf()));
|
||||
Assert.AreEqual(CustomQueryInterfaceResult.Handled, ((ICustomQueryInterface)transformMapper).GetInterface(ref uuidOfTransformMapperInternal, out *(IntPtr*)transformMapperInternal.GetAddressOf()));
|
||||
|
||||
Assert.IsTrue(unknown.Get() is not null);
|
||||
Assert.IsTrue(transformMapper2.Get() is not null);
|
||||
Assert.IsTrue(transformMapperInternal.Get() is not null);
|
||||
|
||||
using ComPtr<IUnknown> garbage = default;
|
||||
|
||||
Guid uuidOfGarbage = Guid.NewGuid();
|
||||
|
||||
// Any other random QueryInterface should fail
|
||||
Assert.AreEqual(CustomQueryInterfaceResult.Failed, ((ICustomQueryInterface)transformMapper).GetInterface(ref uuidOfGarbage, out *(IntPtr*)garbage.GetAddressOf()));
|
||||
|
||||
Assert.IsTrue(garbage.Get() is null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void VerifyReferenceCounting()
|
||||
{
|
||||
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2();
|
||||
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
|
||||
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
|
||||
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<DummyShader>(d2D1Factory2.Get(), out _);
|
||||
|
||||
D2D1DrawTransformMapper<HelloWorld> transformMapper = D2D1DrawTransformMapper<HelloWorld>.Inflate(4);
|
||||
|
||||
using ComPtr<IUnknown> transformMapper2 = default;
|
||||
|
||||
Guid uuidOfTransformMapper = new("02E6D48D-B892-4FBC-AA54-119203BAB802");
|
||||
|
||||
Assert.AreEqual(CustomQueryInterfaceResult.Handled, ((ICustomQueryInterface)transformMapper).GetInterface(ref uuidOfTransformMapper, out *(IntPtr*)transformMapper2.GetAddressOf()));
|
||||
|
||||
_ = transformMapper2.Get()->AddRef();
|
||||
|
||||
// Right after creation, the transform mapper has only 2 ref count (one is the managed object, one is this ComPtr<T>)
|
||||
Assert.AreEqual(2u, transformMapper2.Get()->Release());
|
||||
|
||||
using (ComPtr<ID2D1Effect> d2D1Effect = default)
|
||||
{
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<DummyShader>(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf());
|
||||
|
||||
D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(d2D1Effect.Get(), transformMapper);
|
||||
|
||||
_ = transformMapper2.Get()->AddRef();
|
||||
|
||||
// After setting a transform mapper to an effect, the count raises to 3
|
||||
Assert.AreEqual(3u, transformMapper2.Get()->Release());
|
||||
|
||||
D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(d2D1Effect.Get(), transformMapper);
|
||||
|
||||
_ = transformMapper2.Get()->AddRef();
|
||||
|
||||
// Adding the same transform mapper again doesn't increment ref count
|
||||
Assert.AreEqual(3u, transformMapper2.Get()->Release());
|
||||
}
|
||||
|
||||
_ = transformMapper2.Get()->AddRef();
|
||||
|
||||
// If the effect is released, that extra manager reference is also released
|
||||
Assert.AreEqual(2u, transformMapper2.Get()->Release());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void VerifyManagedWrapperRetrieval()
|
||||
{
|
||||
D2D1DrawTransformMapper<HelloWorld> transformMapper = D2D1DrawTransformMapper<HelloWorld>.Inflate(4);
|
||||
|
||||
using ComPtr<IUnknown> unknown = default;
|
||||
using ComPtr<IUnknown> transformMapperInternal = default;
|
||||
|
||||
Guid uuidOfIUnknown = typeof(IUnknown).GUID;
|
||||
Guid uuidOfTransformMapperInternal = new("C5D8FC65-FB86-4C2D-9EF5-95AEC639C952");
|
||||
|
||||
Assert.AreEqual(CustomQueryInterfaceResult.Handled, ((ICustomQueryInterface)transformMapper).GetInterface(ref uuidOfIUnknown, out *(IntPtr*)unknown.GetAddressOf()));
|
||||
|
||||
Assert.IsTrue(unknown.Get() is not null);
|
||||
|
||||
HRESULT hresult = unknown.CopyTo(&uuidOfTransformMapperInternal, (void**)transformMapperInternal.GetAddressOf());
|
||||
|
||||
Assert.AreEqual((int)hresult, S.S_OK);
|
||||
Assert.IsTrue(transformMapperInternal.Get() is not null);
|
||||
|
||||
IntPtr handlePtr;
|
||||
|
||||
// Invoke GetManagedWrapperHandle
|
||||
hresult = ((delegate* unmanaged[MemberFunction]<IUnknown*, void**, int>)(*(void***)transformMapperInternal.Get())[3])(
|
||||
transformMapperInternal.Get(),
|
||||
(void**)&handlePtr);
|
||||
|
||||
Assert.AreEqual((int)hresult, S.S_OK);
|
||||
|
||||
GCHandle handle = GCHandle.FromIntPtr(handlePtr);
|
||||
|
||||
Assert.IsNotNull(handle.Target);
|
||||
Assert.AreSame(handle.Target, transformMapper);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void VerifyReferenceTrackingWithManagedWrapper()
|
||||
{
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
static void GetTransformMapperUnknownAndGCHandle(
|
||||
IUnknown** transformMapperUnknown,
|
||||
out GCHandle transformMapperHandle)
|
||||
{
|
||||
D2D1DrawTransformMapper<HelloWorld> transformMapper = D2D1DrawTransformMapper<HelloWorld>.Inflate(4);
|
||||
|
||||
Guid uuidOfTransformMapper = new("02E6D48D-B892-4FBC-AA54-119203BAB802");
|
||||
|
||||
Assert.AreEqual(CustomQueryInterfaceResult.Handled, ((ICustomQueryInterface)transformMapper).GetInterface(ref uuidOfTransformMapper, out *(IntPtr*)transformMapperUnknown));
|
||||
|
||||
transformMapperHandle = GCHandle.Alloc(transformMapper, GCHandleType.Weak);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
static void Test(out GCHandle transformMapperHandle)
|
||||
{
|
||||
using ComPtr<IUnknown> transformMapperUnknown = default;
|
||||
|
||||
GetTransformMapperUnknownAndGCHandle(transformMapperUnknown.GetAddressOf(), out transformMapperHandle);
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
static void Test(GCHandle transformMapperHandle)
|
||||
{
|
||||
// Sanity check: the wrapper is alive right now
|
||||
Assert.IsNotNull(transformMapperHandle.Target);
|
||||
}
|
||||
|
||||
Test(transformMapperHandle);
|
||||
|
||||
GC.Collect();
|
||||
GC.WaitForPendingFinalizers();
|
||||
|
||||
// The wrapper is still alive, as the CCW is rooting it
|
||||
Assert.IsNotNull(transformMapperHandle.Target);
|
||||
}
|
||||
|
||||
GCHandle transformMapperHandle = default;
|
||||
|
||||
try
|
||||
{
|
||||
Test(out transformMapperHandle);
|
||||
|
||||
GC.Collect();
|
||||
GC.WaitForPendingFinalizers();
|
||||
|
||||
// The wrapper is gone, as the CCW has been released
|
||||
Assert.IsNull(transformMapperHandle.Target);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (transformMapperHandle.IsAllocated)
|
||||
{
|
||||
transformMapperHandle.Free();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal partial struct DummyShader : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
return default;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public unsafe void UpdateConstantBufferFromTransformMapper()
|
||||
{
|
||||
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2();
|
||||
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
|
||||
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
|
||||
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<ShaderWithDispatchArea>(d2D1Factory2.Get(), out _);
|
||||
|
||||
using ComPtr<ID2D1Effect> d2D1Effect = default;
|
||||
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<ShaderWithDispatchArea>(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf());
|
||||
|
||||
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), new ShaderWithDispatchArea(111, 222));
|
||||
|
||||
DispatchAreaTransformMapper transformMapper = new() { ExpectedWidth = 111, ExpectedHeight = 222 };
|
||||
|
||||
D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(d2D1Effect.Get(), transformMapper);
|
||||
|
||||
string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!;
|
||||
string sourcePath = Path.Combine(assemblyPath, "Assets", "Landscape.png");
|
||||
string expectedPath = Path.Combine(assemblyPath, "Assets", "RadialFadeOut.png");
|
||||
|
||||
ReadOnlyMemory<byte> pixels = ImageHelper.LoadBitmapFromFile(sourcePath, out uint width, out uint height);
|
||||
|
||||
using ComPtr<ID2D1Bitmap> d2D1BitmapSource = D2D1Helper.CreateD2D1BitmapAndSetAsSource(d2D1DeviceContext.Get(), pixels, width, height, d2D1Effect.Get());
|
||||
using ComPtr<ID2D1Bitmap> d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), width, height);
|
||||
|
||||
D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get());
|
||||
|
||||
using ComPtr<ID2D1Bitmap1> d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect);
|
||||
|
||||
string destinationPath = Path.Combine(assemblyPath, "temp", $"{nameof(UpdateConstantBufferFromTransformMapper)}.png");
|
||||
|
||||
_ = Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!);
|
||||
|
||||
ImageHelper.SaveBitmapToFile(destinationPath, width, height, d2D1MappedRect.pitch, d2D1MappedRect.bits);
|
||||
|
||||
TolerantImageComparer.AssertEqual(destinationPath, expectedPath, 0.00001f);
|
||||
}
|
||||
|
||||
private sealed class DispatchAreaTransformMapper : D2D1DrawTransformMapper<ShaderWithDispatchArea>
|
||||
{
|
||||
public int ExpectedWidth;
|
||||
public int ExpectedHeight;
|
||||
|
||||
public override void MapInputsToOutput(
|
||||
D2D1DrawInfoUpdateContext<ShaderWithDispatchArea> drawInfoUpdateContext,
|
||||
ReadOnlySpan<Rectangle> inputs,
|
||||
ReadOnlySpan<Rectangle> opaqueInputs,
|
||||
out Rectangle output,
|
||||
out Rectangle opaqueOutput)
|
||||
{
|
||||
ShaderWithDispatchArea shader = drawInfoUpdateContext.GetConstantBuffer();
|
||||
|
||||
Assert.AreEqual(shader.Width, this.ExpectedWidth);
|
||||
Assert.AreEqual(shader.Height, this.ExpectedHeight);
|
||||
|
||||
shader = new ShaderWithDispatchArea(inputs[0].Width, inputs[0].Height);
|
||||
|
||||
drawInfoUpdateContext.SetConstantBuffer(in shader);
|
||||
|
||||
output = inputs[0];
|
||||
opaqueOutput = Rectangle.Empty;
|
||||
}
|
||||
|
||||
public override void MapInvalidOutput(int inputIndex, in Rectangle invalidInput, out Rectangle invalidOutput)
|
||||
{
|
||||
invalidOutput = invalidInput;
|
||||
}
|
||||
|
||||
public override void MapOutputToInputs(in Rectangle output, Span<Rectangle> inputs)
|
||||
{
|
||||
inputs.Fill(output);
|
||||
}
|
||||
}
|
||||
|
||||
[D2DInputCount(1)]
|
||||
[D2DInputSimple(0)]
|
||||
[D2DRequiresScenePosition]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct ShaderWithDispatchArea : ID2D1PixelShader
|
||||
{
|
||||
public readonly int Width;
|
||||
public readonly int Height;
|
||||
|
||||
public float4 Execute()
|
||||
{
|
||||
// Get the current integer coordinate and input color
|
||||
int2 xy = (int2)D2D.GetScenePosition().XY;
|
||||
float4 color = D2D.GetInput(0);
|
||||
|
||||
// Calculate the center and size of the largest circle centered in the image
|
||||
float2 center = new((uint)this.Width / 2, (uint)this.Height / 2);
|
||||
int diameter = Hlsl.Min(this.Width, this.Height);
|
||||
int radius = (int)((uint)diameter / 2);
|
||||
|
||||
// Calculate the distance from the center, to adjust the fade out
|
||||
float distance = Hlsl.Distance(xy, center);
|
||||
float falloff = radius / 2u;
|
||||
float alpha = 0;
|
||||
|
||||
// If the pixel is close enough, keep it fully visible
|
||||
if (distance <= falloff)
|
||||
{
|
||||
alpha = 1;
|
||||
}
|
||||
else if (distance <= radius)
|
||||
{
|
||||
// Otherwise, linearly fade it out until the outer radius is reached
|
||||
float delta = radius - distance;
|
||||
|
||||
alpha = delta / falloff;
|
||||
}
|
||||
|
||||
return new(color.RGB, alpha);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
using System;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests;
|
||||
|
||||
[TestClass]
|
||||
public partial class D2DPixelShaderSourceTests
|
||||
{
|
||||
[D2DPixelShaderSource("""
|
||||
#define D2D_INPUT_COUNT 1
|
||||
#define D2D_INPUT0_SIMPLE
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
float4 color = D2DGetInput(0);
|
||||
float3 rgb = saturate(1.0 - color.rgb);
|
||||
return float4(rgb, 1);
|
||||
}
|
||||
""")]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DCompileOptions(D2D1CompileOptions.OptimizationLevel0)]
|
||||
private static partial ReadOnlySpan<byte> InvertEffect();
|
||||
|
||||
[TestMethod]
|
||||
public void VerifyInvertEffectBytecode()
|
||||
{
|
||||
ReadOnlySpan<byte> bytecode = InvertEffect();
|
||||
|
||||
Assert.IsTrue(bytecode.Length > 0);
|
||||
}
|
||||
}
|
||||
@@ -1,625 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.IO;
|
||||
using System.Numerics;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeSharp.D2D1.Interop;
|
||||
using ComputeSharp.D2D1.Tests.Extensions;
|
||||
using ComputeSharp.D2D1.Tests.Helpers;
|
||||
using SixLabors.ImageSharp;
|
||||
using TerraFX.Interop.DirectX;
|
||||
using TerraFX.Interop.Windows;
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests.Effects;
|
||||
|
||||
/// <summary>
|
||||
/// A bokeh blur effect, using linearly separable convolutions in the complex space for better efficiency.
|
||||
/// </summary>
|
||||
public sealed partial class BokehBlurEffect
|
||||
{
|
||||
/// <summary>
|
||||
/// The mapping of initialized complex kernels and parameters, to speed up the initialization of new <see cref="BokehBlurEffect"/> instances.
|
||||
/// </summary>
|
||||
private static readonly ConcurrentDictionary<(int Radius, int ComponentsCount), (Vector4[] Parameters, float Scale, (float[] Real, float[] Imaginary)[] Kernels)> Cache = [];
|
||||
|
||||
/// <summary>
|
||||
/// The kernel scales to adjust the component values in each kernel.
|
||||
/// </summary>
|
||||
private static readonly float[] KernelScales = [1.4f, 1.2f, 1.2f, 1.2f, 1.2f, 1.2f];
|
||||
|
||||
/// <summary>
|
||||
/// The available bokeh blur kernel parameters.
|
||||
/// </summary>
|
||||
private static readonly Vector4[][] KernelComponents =
|
||||
[
|
||||
// 1 component
|
||||
[new Vector4(0.862325f, 1.624835f, 0.767583f, 1.862321f)],
|
||||
|
||||
// 2 components
|
||||
[
|
||||
new Vector4(0.886528f, 5.268909f, 0.411259f, -0.548794f),
|
||||
new Vector4(1.960518f, 1.558213f, 0.513282f, 4.56111f)
|
||||
],
|
||||
|
||||
// 3 components
|
||||
[
|
||||
new Vector4(2.17649f, 5.043495f, 1.621035f, -2.105439f),
|
||||
new Vector4(1.019306f, 9.027613f, -0.28086f, -0.162882f),
|
||||
new Vector4(2.81511f, 1.597273f, -0.366471f, 10.300301f)
|
||||
],
|
||||
|
||||
// 4 components
|
||||
[
|
||||
new Vector4(4.338459f, 1.553635f, -5.767909f, 46.164397f),
|
||||
new Vector4(3.839993f, 4.693183f, 9.795391f, -15.227561f),
|
||||
new Vector4(2.791880f, 8.178137f, -3.048324f, 0.302959f),
|
||||
new Vector4(1.342190f, 12.328289f, 0.010001f, 0.244650f)
|
||||
],
|
||||
|
||||
// 5 components
|
||||
[
|
||||
new Vector4(4.892608f, 1.685979f, -22.356787f, 85.91246f),
|
||||
new Vector4(4.71187f, 4.998496f, 35.918936f, -28.875618f),
|
||||
new Vector4(4.052795f, 8.244168f, -13.212253f, -1.578428f),
|
||||
new Vector4(2.929212f, 11.900859f, 0.507991f, 1.816328f),
|
||||
new Vector4(1.512961f, 16.116382f, 0.138051f, -0.01f)
|
||||
],
|
||||
|
||||
// 6 components
|
||||
[
|
||||
new Vector4(5.143778f, 2.079813f, -82.326596f, 111.231024f),
|
||||
new Vector4(5.612426f, 6.153387f, 113.878661f, 58.004879f),
|
||||
new Vector4(5.982921f, 9.802895f, 39.479083f, -162.028887f),
|
||||
new Vector4(6.505167f, 11.059237f, -71.286026f, 95.027069f),
|
||||
new Vector4(3.869579f, 14.81052f, 1.405746f, -3.704914f),
|
||||
new Vector4(2.201904f, 19.032909f, -0.152784f, -0.107988f)
|
||||
]
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// The kernel radius.
|
||||
/// </summary>
|
||||
private readonly int radius;
|
||||
|
||||
/// <summary>
|
||||
/// The maximum size of the kernel in either direction.
|
||||
/// </summary>
|
||||
private readonly int kernelSize;
|
||||
|
||||
/// <summary>
|
||||
/// The number of components to use when applying the bokeh blur.
|
||||
/// </summary>
|
||||
private readonly int componentsCount;
|
||||
|
||||
/// <summary>
|
||||
/// The kernel parameters to use for the current instance (a: X, b: Y, A: Z, B: W)
|
||||
/// </summary>
|
||||
private readonly Vector4[] kernelParameters;
|
||||
|
||||
/// <summary>
|
||||
/// The kernel components for the current instance.
|
||||
/// </summary>
|
||||
private readonly (float[] Real, float[] Imaginary)[] kernels;
|
||||
|
||||
/// <summary>
|
||||
/// The scaling factor for kernel values.
|
||||
/// </summary>
|
||||
private readonly float kernelsScale;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BokehBlurEffect"/> class.
|
||||
/// </summary>
|
||||
/// <param name="radius">The size of the area to sample.</param>
|
||||
/// <param name="componentsCount">The number of components to use to approximate the original 2D bokeh blur convolution kernel.</param>
|
||||
public BokehBlurEffect(int radius, int componentsCount)
|
||||
{
|
||||
this.radius = radius;
|
||||
this.kernelSize = (this.radius * 2) + 1;
|
||||
this.componentsCount = componentsCount;
|
||||
|
||||
// Reuse the initialized values from the cache, if possible
|
||||
(int radius, int componentsCount) parameters = (this.radius, this.componentsCount);
|
||||
|
||||
if (Cache.TryGetValue(parameters, out (Vector4[] Parameters, float Scale, (float[] Real, float[] Imaginary)[] Kernels) info))
|
||||
{
|
||||
this.kernelParameters = info.Parameters;
|
||||
this.kernelsScale = info.Scale;
|
||||
this.kernels = info.Kernels;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Initialize the complex kernels and parameters with the current arguments
|
||||
(this.kernelParameters, this.kernelsScale) = GetParameters();
|
||||
|
||||
Complex64[][] kernels = CreateComplexKernels();
|
||||
|
||||
NormalizeKernels(kernels, this.kernelParameters);
|
||||
|
||||
this.kernels = ConvertKernelsToStructureOfArrays(kernels);
|
||||
|
||||
// Store them in the cache for future use
|
||||
_ = Cache.TryAdd(parameters, (this.kernelParameters, this.kernelsScale, this.kernels));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the kernel parameters and scaling factor for the current count value in the current instance.
|
||||
/// </summary>
|
||||
private (Vector4[] Parameters, float Scale) GetParameters()
|
||||
{
|
||||
// Prepare the kernel components
|
||||
int index = Math.Max(0, Math.Min(this.componentsCount - 1, KernelComponents.Length));
|
||||
|
||||
return (KernelComponents[index], KernelScales[index]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the collection of complex 1D kernels with the specified parameters.
|
||||
/// </summary>
|
||||
private Complex64[][] CreateComplexKernels()
|
||||
{
|
||||
Complex64[][] kernels = new Complex64[this.kernelParameters.Length][];
|
||||
ref Vector4 baseRef = ref MemoryMarshal.GetReference(this.kernelParameters.AsSpan());
|
||||
|
||||
for (int i = 0; i < this.kernelParameters.Length; i++)
|
||||
{
|
||||
ref Vector4 paramsRef = ref Unsafe.Add(ref baseRef, i);
|
||||
|
||||
kernels[i] = CreateComplex1DKernel(paramsRef.X, paramsRef.Y);
|
||||
}
|
||||
|
||||
return kernels;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a complex 1D kernel with the specified parameters.
|
||||
/// </summary>
|
||||
/// <param name="a">The exponential parameter for each complex component.</param>
|
||||
/// <param name="b">The angle component for each complex component.</param>
|
||||
private Complex64[] CreateComplex1DKernel(float a, float b)
|
||||
{
|
||||
Complex64[] kernel = new Complex64[this.kernelSize];
|
||||
ref Complex64 baseRef = ref MemoryMarshal.GetReference(kernel.AsSpan());
|
||||
int r = this.radius;
|
||||
int n = -r;
|
||||
|
||||
for (int i = 0; i < this.kernelSize; i++, n++)
|
||||
{
|
||||
// Incrementally compute the range values
|
||||
float value = n * this.kernelsScale * (1f / r);
|
||||
|
||||
value *= value;
|
||||
|
||||
// Fill in the complex kernel values
|
||||
Unsafe.Add(ref baseRef, i) = new Complex64(
|
||||
(float)(Math.Exp(-a * value) * Math.Cos(b * value)),
|
||||
(float)(Math.Exp(-a * value) * Math.Sin(b * value)));
|
||||
}
|
||||
|
||||
return kernel;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Normalizes the kernels with respect to A * real + B * imaginary.
|
||||
/// </summary>
|
||||
/// <param name="kernels">The input kernels to normalize.</param>
|
||||
/// <param name="kernelParameters">The kernel parameters to use to normalize the kernels.</param>
|
||||
private static void NormalizeKernels(Complex64[][] kernels, Vector4[] kernelParameters)
|
||||
{
|
||||
// Calculate the complex weighted sum
|
||||
float total = 0;
|
||||
Span<Complex64[]> kernelsSpan = kernels.AsSpan();
|
||||
ref Complex64[] baseKernelsRef = ref MemoryMarshal.GetReference(kernelsSpan);
|
||||
ref Vector4 baseParamsRef = ref MemoryMarshal.GetReference(kernelParameters.AsSpan());
|
||||
|
||||
for (int i = 0; i < kernelParameters.Length; i++)
|
||||
{
|
||||
ref Complex64[] kernelRef = ref Unsafe.Add(ref baseKernelsRef, i);
|
||||
int length = kernelRef.Length;
|
||||
ref Complex64 valueRef = ref kernelRef[0];
|
||||
ref Vector4 paramsRef = ref Unsafe.Add(ref baseParamsRef, i);
|
||||
|
||||
for (int j = 0; j < length; j++)
|
||||
{
|
||||
for (int k = 0; k < length; k++)
|
||||
{
|
||||
ref Complex64 jRef = ref Unsafe.Add(ref valueRef, j);
|
||||
ref Complex64 kRef = ref Unsafe.Add(ref valueRef, k);
|
||||
|
||||
total +=
|
||||
(paramsRef.Z * ((jRef.Real * kRef.Real) - (jRef.Imaginary * kRef.Imaginary)))
|
||||
+ (paramsRef.W * ((jRef.Real * kRef.Imaginary) + (jRef.Imaginary * kRef.Real)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Normalize the kernels
|
||||
float scalar = 1f / (float)Math.Sqrt(total);
|
||||
|
||||
for (int i = 0; i < kernelsSpan.Length; i++)
|
||||
{
|
||||
ref Complex64[] kernelsRef = ref Unsafe.Add(ref baseKernelsRef, i);
|
||||
int length = kernelsRef.Length;
|
||||
ref Complex64 valueRef = ref kernelsRef[0];
|
||||
|
||||
for (int j = 0; j < length; j++)
|
||||
{
|
||||
Unsafe.Add(ref valueRef, j) *= scalar;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts the kernels into structure of arrays.
|
||||
/// </summary>
|
||||
/// <param name="kernels">The input kernels to convert.</param>
|
||||
private static (float[] Real, float[] Imaginary)[] ConvertKernelsToStructureOfArrays(Complex64[][] kernels)
|
||||
{
|
||||
(float[] Real, float[] Imaginary)[] structureOfArrayKernels = new (float[] Real, float[] Imaginary)[kernels.Length];
|
||||
|
||||
for (int i = 0; i < kernels.Length; i++)
|
||||
{
|
||||
Complex64[] kernel = kernels[i];
|
||||
float[] real = new float[kernel.Length];
|
||||
float[] imaginary = new float[kernel.Length];
|
||||
|
||||
for (int j = 0; j < kernel.Length; j++)
|
||||
{
|
||||
real[j] = kernel[j].Real;
|
||||
imaginary[j] = kernel[j].Imaginary;
|
||||
}
|
||||
|
||||
structureOfArrayKernels[i] = (real, imaginary);
|
||||
}
|
||||
|
||||
return structureOfArrayKernels;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies the effect on an image loaded from a given path and writes the result to the output path.
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">The source path for the image to run the effect on.</param>
|
||||
/// <param name="destinationPath">The destination path for the result.</param>
|
||||
public unsafe void ApplyEffect(string sourcePath, string destinationPath)
|
||||
{
|
||||
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2();
|
||||
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
|
||||
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
|
||||
|
||||
D2D1_RENDERING_CONTROLS d2D1RenderingControls = default;
|
||||
|
||||
d2D1DeviceContext.Get()->GetRenderingControls(&d2D1RenderingControls);
|
||||
|
||||
// Set the buffer precision for the whole context to 32 bits per channel. This avoids
|
||||
// color banding issues due to intermediate buffers clamping to just 8 bits per channel.
|
||||
d2D1RenderingControls.bufferPrecision = D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_32BPC_FLOAT;
|
||||
|
||||
d2D1DeviceContext.Get()->SetRenderingControls(&d2D1RenderingControls);
|
||||
|
||||
// Register all necessary effects
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<VerticalConvolution.Shader>(d2D1Factory2.Get(), out _);
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<HorizontalConvolutionAndAccumulatePartials.Shader>(d2D1Factory2.Get(), out _);
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<GammaHighlight>(d2D1Factory2.Get(), out _);
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<InverseGammaHighlight>(d2D1Factory2.Get(), out _);
|
||||
|
||||
int numberOfComponents = this.kernelParameters.Length;
|
||||
|
||||
using ComPtr<ID2D1Effect> gammaExposureEffect = default;
|
||||
using ComPtr<ID2D1Effect> inverseGammaExposureEffect = default;
|
||||
using ComPtr<ID2D1Effect> compositeEffect = default;
|
||||
using ComPtr<ID2D1Effect> borderEffect = default;
|
||||
|
||||
Span<ComPtr<ID2D1Effect>> verticalConvolutionEffectsForReals = new ComPtr<ID2D1Effect>[numberOfComponents];
|
||||
Span<ComPtr<ID2D1Effect>> verticalConvolutionEffectsForImaginaries = new ComPtr<ID2D1Effect>[numberOfComponents];
|
||||
Span<ComPtr<ID2D1Effect>> horizontalConvolutionEffects = new ComPtr<ID2D1Effect>[numberOfComponents];
|
||||
|
||||
try
|
||||
{
|
||||
// Create an instance of each effect
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<GammaHighlight>(d2D1DeviceContext.Get(), (void**)gammaExposureEffect.GetAddressOf());
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<InverseGammaHighlight>(d2D1DeviceContext.Get(), (void**)inverseGammaExposureEffect.GetAddressOf());
|
||||
|
||||
for (int i = 0; i < numberOfComponents; i++)
|
||||
{
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<VerticalConvolution.Shader>(d2D1DeviceContext.Get(), (void**)verticalConvolutionEffectsForReals[i].GetAddressOf());
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<VerticalConvolution.Shader>(d2D1DeviceContext.Get(), (void**)verticalConvolutionEffectsForImaginaries[i].GetAddressOf());
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<HorizontalConvolutionAndAccumulatePartials.Shader>(d2D1DeviceContext.Get(), (void**)horizontalConvolutionEffects[i].GetAddressOf());
|
||||
|
||||
D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(verticalConvolutionEffectsForReals[i].Get(), VerticalConvolution.Transform);
|
||||
D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(verticalConvolutionEffectsForImaginaries[i].Get(), VerticalConvolution.Transform);
|
||||
D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(horizontalConvolutionEffects[i].Get(), HorizontalConvolutionAndAccumulatePartials.Transform);
|
||||
}
|
||||
|
||||
// Create the border effect to clamp the input image
|
||||
d2D1DeviceContext.Get()->CreateEffect(
|
||||
effectId: (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_D2D1Border)),
|
||||
effect: borderEffect.GetAddressOf()).Assert();
|
||||
|
||||
D2D1_BORDER_EDGE_MODE d2D1BorderEdgeMode = D2D1_BORDER_EDGE_MODE.D2D1_BORDER_EDGE_MODE_CLAMP;
|
||||
|
||||
// Set the border mode to clamp on both axes
|
||||
borderEffect.Get()->SetValue((uint)D2D1_BORDER_PROP.D2D1_BORDER_PROP_EDGE_MODE_X, (byte*)&d2D1BorderEdgeMode, sizeof(D2D1_BORDER_EDGE_MODE)).Assert();
|
||||
borderEffect.Get()->SetValue((uint)D2D1_BORDER_PROP.D2D1_BORDER_PROP_EDGE_MODE_Y, (byte*)&d2D1BorderEdgeMode, sizeof(D2D1_BORDER_EDGE_MODE)).Assert();
|
||||
|
||||
// If partials need to be summed, also create the composite effect
|
||||
if (numberOfComponents > 1)
|
||||
{
|
||||
d2D1DeviceContext.Get()->CreateEffect(
|
||||
effectId: (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_D2D1Composite)),
|
||||
effect: compositeEffect.GetAddressOf()).Assert();
|
||||
|
||||
D2D1_BUFFER_PRECISION d2D1BufferPrecision = D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_32BPC_FLOAT;
|
||||
|
||||
// Set the channel precision to 32 bits manually to avoid banding
|
||||
compositeEffect.Get()->SetValue(unchecked((uint)D2D1_PROPERTY.D2D1_PROPERTY_PRECISION), (byte*)&d2D1BufferPrecision, sizeof(D2D1_BUFFER_PRECISION)).Assert();
|
||||
|
||||
D2D1_COMPOSITE_MODE d2D1CompositeMode = D2D1_COMPOSITE_MODE.D2D1_COMPOSITE_MODE_PLUS;
|
||||
|
||||
// Set the mode to plus
|
||||
compositeEffect.Get()->SetValue((uint)D2D1_COMPOSITE_PROP.D2D1_COMPOSITE_PROP_MODE, (byte*)&d2D1CompositeMode, sizeof(D2D1_COMPOSITE_MODE)).Assert();
|
||||
}
|
||||
|
||||
ReadOnlyMemory<byte> pixels = ImageHelper.LoadBitmapFromFile(sourcePath, out uint width, out uint height);
|
||||
|
||||
// Load the source bitmap and create a destination bitmap
|
||||
using ComPtr<ID2D1Bitmap> d2D1BitmapSource = D2D1Helper.CreateD2D1BitmapAndSetAsSource(d2D1DeviceContext.Get(), pixels, width, height, gammaExposureEffect.Get());
|
||||
using ComPtr<ID2D1Bitmap> d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), width, height);
|
||||
|
||||
(D2D1ResourceTextureManager Reals, D2D1ResourceTextureManager Imaginaries)[] kernels = new (D2D1ResourceTextureManager, D2D1ResourceTextureManager)[numberOfComponents];
|
||||
uint kernelSize = (uint)this.kernelSize;
|
||||
|
||||
for (int i = 0; i < numberOfComponents; i++)
|
||||
{
|
||||
// Create the resource texture for the real kernel
|
||||
D2D1ResourceTextureManager kernelReals = new(
|
||||
extents: new Span<uint>(&kernelSize, 1),
|
||||
bufferPrecision: D2D1BufferPrecision.Float32,
|
||||
channelDepth: D2D1ChannelDepth.One,
|
||||
filter: D2D1Filter.MinMagMipPoint,
|
||||
extendModes: [D2D1ExtendMode.Clamp],
|
||||
data: MemoryMarshal.AsBytes(this.kernels[i].Real.AsSpan()),
|
||||
strides: []);
|
||||
|
||||
// Also create the one for the imaginary kernel
|
||||
D2D1ResourceTextureManager kernelImaginary = new(
|
||||
extents: new Span<uint>(&kernelSize, 1),
|
||||
bufferPrecision: D2D1BufferPrecision.Float32,
|
||||
channelDepth: D2D1ChannelDepth.One,
|
||||
filter: D2D1Filter.MinMagMipPoint,
|
||||
extendModes: [D2D1ExtendMode.Clamp],
|
||||
data: MemoryMarshal.AsBytes(this.kernels[i].Imaginary.AsSpan()),
|
||||
strides: []);
|
||||
|
||||
kernels[i] = (kernelReals, kernelImaginary);
|
||||
}
|
||||
|
||||
// Assign the resource textures
|
||||
for (int i = 0; i < numberOfComponents; i++)
|
||||
{
|
||||
D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(verticalConvolutionEffectsForReals[i].Get(), kernels[i].Reals, 0);
|
||||
D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(verticalConvolutionEffectsForImaginaries[i].Get(), kernels[i].Imaginaries, 0);
|
||||
D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(horizontalConvolutionEffects[i].Get(), kernels[i].Reals, 0);
|
||||
D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(horizontalConvolutionEffects[i].Get(), kernels[i].Imaginaries, 1);
|
||||
}
|
||||
|
||||
// Set the constant buffers
|
||||
for (int i = 0; i < numberOfComponents; i++)
|
||||
{
|
||||
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(verticalConvolutionEffectsForReals[i].Get(), new VerticalConvolution.Shader((int)kernelSize));
|
||||
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(verticalConvolutionEffectsForImaginaries[i].Get(), new VerticalConvolution.Shader((int)kernelSize));
|
||||
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(horizontalConvolutionEffects[i].Get(), new HorizontalConvolutionAndAccumulatePartials.Shader((int)kernelSize, this.kernelParameters[i].Z, this.kernelParameters[i].W));
|
||||
}
|
||||
|
||||
// Build the effect graph:
|
||||
//
|
||||
// [INPUT] ---> [BORDER] --> [GAMMA EXPOSURE] ---> [VERTICAL REAL] ----
|
||||
// \ \
|
||||
// -----> [VERTICAL IMAGINARY] ----> [HORIZONTAL] ---> [INVERSE GAMMA EXPOSURE] ---> [OUTPUT]
|
||||
borderEffect.Get()->SetInputEffect(0, gammaExposureEffect.Get());
|
||||
|
||||
for (int i = 0; i < numberOfComponents; i++)
|
||||
{
|
||||
verticalConvolutionEffectsForReals[i].Get()->SetInputEffect(0, borderEffect.Get());
|
||||
verticalConvolutionEffectsForImaginaries[i].Get()->SetInputEffect(0, borderEffect.Get());
|
||||
horizontalConvolutionEffects[i].Get()->SetInputEffect(0, verticalConvolutionEffectsForReals[i].Get());
|
||||
horizontalConvolutionEffects[i].Get()->SetInputEffect(1, verticalConvolutionEffectsForImaginaries[i].Get());
|
||||
}
|
||||
|
||||
// Connect to the output node
|
||||
if (numberOfComponents == 1)
|
||||
{
|
||||
inverseGammaExposureEffect.Get()->SetInputEffect(0, horizontalConvolutionEffects[0].Get());
|
||||
}
|
||||
else
|
||||
{
|
||||
_ = compositeEffect.Get()->SetInputCount((uint)numberOfComponents);
|
||||
|
||||
// Aggregate all partial results with the composite effect
|
||||
for (int i = 0; i < numberOfComponents; i++)
|
||||
{
|
||||
compositeEffect.Get()->SetInputEffect((uint)i, horizontalConvolutionEffects[i].Get());
|
||||
}
|
||||
|
||||
inverseGammaExposureEffect.Get()->SetInputEffect(0, compositeEffect.Get());
|
||||
}
|
||||
|
||||
d2D1DeviceContext.Get()->BeginDraw();
|
||||
|
||||
// Draw the final result
|
||||
d2D1DeviceContext.Get()->DrawImage(
|
||||
effect: inverseGammaExposureEffect.Get(),
|
||||
targetOffset: null,
|
||||
imageRectangle: null,
|
||||
interpolationMode: D2D1_INTERPOLATION_MODE.D2D1_INTERPOLATION_MODE_NEAREST_NEIGHBOR,
|
||||
compositeMode: D2D1_COMPOSITE_MODE.D2D1_COMPOSITE_MODE_SOURCE_COPY);
|
||||
|
||||
d2D1DeviceContext.Get()->EndDraw().Assert();
|
||||
|
||||
using ComPtr<ID2D1Bitmap1> d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect);
|
||||
|
||||
_ = Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!);
|
||||
|
||||
ImageHelper.SaveBitmapToFile(destinationPath, width, height, d2D1MappedRect.pitch, d2D1MappedRect.bits);
|
||||
}
|
||||
finally
|
||||
{
|
||||
for (int i = 0; i < numberOfComponents; i++)
|
||||
{
|
||||
verticalConvolutionEffectsForReals[i].Dispose();
|
||||
verticalConvolutionEffectsForImaginaries[i].Dispose();
|
||||
horizontalConvolutionEffects[i].Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The vertical convolution shader and transform.
|
||||
/// </summary>
|
||||
internal sealed partial class VerticalConvolution
|
||||
{
|
||||
/// <summary>
|
||||
/// The <see cref="D2D1DrawTransformMapper{T}"/> for the shader.
|
||||
/// </summary>
|
||||
public static D2D1DrawTransformMapper<Shader> Transform { get; } = D2D1DrawTransformMapper<Shader>.Inflate(static (in shader) => (0, shader.kernelLength, 0, shader.kernelLength));
|
||||
|
||||
/// <summary>
|
||||
/// Kernel for the vertical convolution pass for real or imaginary components.
|
||||
/// </summary>
|
||||
[D2DInputCount(1)]
|
||||
[D2DInputComplex(0)]
|
||||
[D2DInputDescription(0, D2D1Filter.MinMagMipPoint)]
|
||||
[D2DOutputBuffer(D2D1BufferPrecision.Float32, D2D1ChannelDepth.Four)]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DRequiresScenePosition]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
public readonly partial struct Shader(int kernelLength) : ID2D1PixelShader
|
||||
{
|
||||
public readonly int kernelLength = kernelLength;
|
||||
|
||||
[D2DResourceTextureIndex(1)]
|
||||
private readonly D2D1ResourceTexture1D<float> kernel;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public float4 Execute()
|
||||
{
|
||||
float4 result = float4.Zero;
|
||||
int length = this.kernelLength;
|
||||
int radiusY = length >> 1;
|
||||
|
||||
for (int i = 0; i < length; i++)
|
||||
{
|
||||
float4 color = D2D.SampleInputAtOffset(0, new float2(0, i - radiusY));
|
||||
float factor = this.kernel[i];
|
||||
|
||||
result += factor * color;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The horizontal convolutin and partial accumulation effect and transform.
|
||||
/// </summary>
|
||||
internal sealed partial class HorizontalConvolutionAndAccumulatePartials
|
||||
{
|
||||
/// <summary>
|
||||
/// The <see cref="D2D1DrawTransformMapper{T}"/> for the shader.
|
||||
/// </summary>
|
||||
public static D2D1DrawTransformMapper<Shader> Transform { get; } = D2D1DrawTransformMapper<Shader>.Inflate(static (in shader) => (shader.kernelLength, 0, shader.kernelLength, 0));
|
||||
|
||||
/// <summary>
|
||||
/// Kernel for the horizontal convolution pass.
|
||||
/// </summary>
|
||||
[D2DInputCount(2)]
|
||||
[D2DInputComplex(0)]
|
||||
[D2DInputComplex(1)]
|
||||
[D2DInputDescription(0, D2D1Filter.MinMagMipPoint)]
|
||||
[D2DInputDescription(1, D2D1Filter.MinMagMipPoint)]
|
||||
[D2DOutputBuffer(D2D1BufferPrecision.Float32, D2D1ChannelDepth.Four)]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DRequiresScenePosition]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
public readonly partial struct Shader(
|
||||
int kernelLength,
|
||||
float z,
|
||||
float w) : ID2D1PixelShader
|
||||
{
|
||||
public readonly int kernelLength = kernelLength;
|
||||
|
||||
[D2DResourceTextureIndex(2)]
|
||||
private readonly D2D1ResourceTexture1D<float> kernelReals;
|
||||
|
||||
[D2DResourceTextureIndex(3)]
|
||||
private readonly D2D1ResourceTexture1D<float> kernelImaginaries;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public float4 Execute()
|
||||
{
|
||||
int length = this.kernelLength;
|
||||
int radiusX = length >> 1;
|
||||
ComplexVector4 result = default;
|
||||
|
||||
for (int i = 0; i < length; i++)
|
||||
{
|
||||
float4 sourceReal = D2D.SampleInputAtOffset(0, new float2(i - radiusX, 0));
|
||||
float4 sourceImaginary = D2D.SampleInputAtOffset(1, new float2(i - radiusX, 0));
|
||||
float realFactor = this.kernelReals[i];
|
||||
float imaginaryFactor = this.kernelImaginaries[i];
|
||||
|
||||
result.Real += (realFactor * sourceReal) - (imaginaryFactor * sourceImaginary);
|
||||
result.Imaginary += (realFactor * sourceImaginary) + (imaginaryFactor * sourceReal);
|
||||
}
|
||||
|
||||
return result.WeightedSum(z, w);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Kernel for the gamma highlight pass.
|
||||
/// </summary>
|
||||
[D2DInputCount(1)]
|
||||
[D2DInputSimple(0)]
|
||||
[D2DInputDescription(0, D2D1Filter.MinMagMipPoint)]
|
||||
[D2DOutputBuffer(D2D1BufferPrecision.Float32, D2D1ChannelDepth.Four)]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct GammaHighlight : ID2D1PixelShader
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public float4 Execute()
|
||||
{
|
||||
float4 pixel = D2D.GetInput(0);
|
||||
|
||||
pixel.XYZ = pixel.XYZ * pixel.XYZ * pixel.XYZ;
|
||||
|
||||
return pixel;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Kernel for the inverse gamma highlight pass.
|
||||
/// </summary>
|
||||
[D2DInputCount(1)]
|
||||
[D2DInputSimple(0)]
|
||||
[D2DInputDescription(0, D2D1Filter.MinMagMipPoint)]
|
||||
[D2DOutputBuffer(D2D1BufferPrecision.Float32, D2D1ChannelDepth.Four)]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct InverseGammaHighlight : ID2D1PixelShader
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public float4 Execute()
|
||||
{
|
||||
float4 pixel = D2D.GetInput(0);
|
||||
|
||||
pixel = Hlsl.Clamp(pixel, 0, float.MaxValue);
|
||||
pixel.XYZ = Hlsl.Pow(pixel.XYZ, 1 / 3f);
|
||||
|
||||
return pixel;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
namespace ComputeSharp.D2D1.Tests.Effects;
|
||||
|
||||
[D2DInputCount(1)]
|
||||
[D2DInputSimple(0)]
|
||||
[D2DRequiresScenePosition]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
public readonly partial struct CheckerboardClipEffect(int cellSize) : ID2D1PixelShader
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public float4 Execute()
|
||||
{
|
||||
float2 position = D2D.GetScenePosition().XY;
|
||||
uint x = (uint)Hlsl.Floor(position.X);
|
||||
uint y = (uint)Hlsl.Floor(position.Y);
|
||||
|
||||
uint cellX = (uint)(int)Hlsl.Floor(x / cellSize);
|
||||
uint cellY = (uint)(int)Hlsl.Floor(y / cellSize);
|
||||
|
||||
if ((cellX % 2 == 0 && cellY % 2 == 0) ||
|
||||
(cellX % 2 == 1 && cellY % 2 == 1))
|
||||
{
|
||||
Hlsl.Clip(-1);
|
||||
}
|
||||
|
||||
return D2D.GetInput(0);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
namespace ComputeSharp.D2D1.Tests.Effects;
|
||||
|
||||
[D2DInputCount(1)]
|
||||
[D2DInputSimple(0)]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
public partial struct InvertEffect : ID2D1PixelShader
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public float4 Execute()
|
||||
{
|
||||
float4 color = D2D.GetInput(0);
|
||||
float3 rgb = Hlsl.Saturate(1.0f - color.RGB);
|
||||
|
||||
return new(rgb, 1);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
namespace ComputeSharp.D2D1.Tests.Effects;
|
||||
|
||||
[D2DInputCount(1)]
|
||||
[D2DInputSimple(0)]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
public readonly partial struct InvertWithThresholdEffect(float number) : ID2D1PixelShader
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public float4 Execute()
|
||||
{
|
||||
float4 color = D2D.GetInput(0);
|
||||
float3 rgb = Hlsl.Saturate(number - color.RGB);
|
||||
|
||||
return new(rgb, 1);
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
#pragma warning disable IDE0290, CA1822
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests.Effects;
|
||||
|
||||
public struct ColorWrapperUsingExternalType
|
||||
{
|
||||
private float4 value;
|
||||
|
||||
public ColorWrapperUsingExternalType(float4 value)
|
||||
{
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public readonly float4 Invert()
|
||||
{
|
||||
ColorProcessor processor = default;
|
||||
|
||||
return processor.Invert(this.value);
|
||||
}
|
||||
|
||||
public readonly float4 Invert(float4 value)
|
||||
{
|
||||
return new(Hlsl.Saturate(1.0f - value.RGB), 1);
|
||||
}
|
||||
}
|
||||
|
||||
public struct ColorProcessor
|
||||
{
|
||||
public readonly float4 Invert(float4 value)
|
||||
{
|
||||
ColorWrapperUsingExternalType dummy = default;
|
||||
|
||||
return dummy.Invert(value);
|
||||
}
|
||||
}
|
||||
|
||||
[D2DInputCount(1)]
|
||||
[D2DInputSimple(0)]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
public partial struct InvertWithUserTypeAndMutuallyInvokingMethods : ID2D1PixelShader
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public float4 Execute()
|
||||
{
|
||||
ColorWrapperUsingExternalType wrapper = new(D2D.GetInput(0));
|
||||
|
||||
return wrapper.Invert();
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
#pragma warning disable IDE0290
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests.Effects;
|
||||
|
||||
public struct ColorWrapper
|
||||
{
|
||||
private float4 value;
|
||||
|
||||
public ColorWrapper(float4 value)
|
||||
{
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public float4 Invert()
|
||||
{
|
||||
return new(Hlsl.Saturate(1.0f - this.value.RGB), 1);
|
||||
}
|
||||
}
|
||||
|
||||
[D2DInputCount(1)]
|
||||
[D2DInputSimple(0)]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
public partial struct InvertWithUserTypeWithConstructorEffect : ID2D1PixelShader
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public float4 Execute()
|
||||
{
|
||||
ColorWrapper wrapper = new(D2D.GetInput(0));
|
||||
|
||||
return wrapper.Invert();
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
namespace ComputeSharp.D2D1.Tests.Effects;
|
||||
|
||||
[D2DInputCount(1)]
|
||||
[D2DInputComplex(0)]
|
||||
[D2DRequiresScenePosition]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader40)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
[AutoConstructor]
|
||||
public readonly partial struct PixelateEffect : ID2D1PixelShader
|
||||
{
|
||||
[AutoConstructor]
|
||||
public readonly partial struct Constants
|
||||
{
|
||||
public readonly int inputWidth;
|
||||
public readonly int inputHeight;
|
||||
public readonly int cellSize;
|
||||
}
|
||||
|
||||
private readonly Constants constants;
|
||||
|
||||
public float4 Execute()
|
||||
{
|
||||
float2 scenePos = D2D.GetScenePosition().XY;
|
||||
uint x = (uint)Hlsl.Floor(scenePos.X);
|
||||
uint y = (uint)Hlsl.Floor(scenePos.Y);
|
||||
|
||||
int cellX = (int)Hlsl.Floor(x / this.constants.cellSize);
|
||||
int cellY = (int)Hlsl.Floor(y / this.constants.cellSize);
|
||||
|
||||
int x0 = cellX * this.constants.cellSize;
|
||||
int y0 = cellY * this.constants.cellSize;
|
||||
|
||||
int x1 = Hlsl.Min(this.constants.inputWidth, x0 + this.constants.cellSize) - 1;
|
||||
int y1 = Hlsl.Min(this.constants.inputHeight, y0 + this.constants.cellSize) - 1;
|
||||
|
||||
float4 sample0 = D2D.SampleInputAtPosition(0, new float2(x0 + 0.5f, y0 + 0.5f));
|
||||
float4 sample1 = D2D.SampleInputAtPosition(0, new float2(x1 + 0.5f, y0 + 0.5f));
|
||||
float4 sample2 = D2D.SampleInputAtPosition(0, new float2(x0 + 0.5f, y1 + 0.5f));
|
||||
float4 sample3 = D2D.SampleInputAtPosition(0, new float2(x1 + 0.5f, y1 + 0.5f));
|
||||
|
||||
float4 color = (sample0 + sample1 + sample2 + sample3) / 4;
|
||||
|
||||
return color;
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests.Effects;
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DRequiresScenePosition]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
public readonly partial struct ZonePlateEffect(
|
||||
int width,
|
||||
int height,
|
||||
float diameter) : ID2D1PixelShader
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public float4 Execute()
|
||||
{
|
||||
float2 scenePos = D2D.GetScenePosition().XY;
|
||||
|
||||
float xo = scenePos.X - (width >> 1);
|
||||
float yo = scenePos.Y - (height >> 1);
|
||||
|
||||
float rm = 0.5f * diameter;
|
||||
float km = 0.7f / diameter * MathF.PI;
|
||||
float w = rm / 10.0f;
|
||||
|
||||
float yd = yo * yo;
|
||||
float xd = xo * xo;
|
||||
float d = xd + yd;
|
||||
float v = 1.0f + ((1.0f + Hlsl.Tanh((rm - Hlsl.Sqrt(d)) / w)) * Hlsl.Sin(km * d) * 0.5f);
|
||||
|
||||
return new Float4(v, v, v, 1.0f);
|
||||
}
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using ComputeSharp.D2D1.Interop;
|
||||
using ComputeSharp.D2D1.Tests.Effects;
|
||||
using ComputeSharp.D2D1.Tests.Helpers;
|
||||
using ComputeSharp.Tests.Helpers;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
using SixLabors.ImageSharp.Processing;
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests;
|
||||
|
||||
[TestClass]
|
||||
public class EffectsTests
|
||||
{
|
||||
[AssemblyInitialize]
|
||||
public static void ConfigureImageSharp(TestContext _)
|
||||
{
|
||||
Configuration.Default.PreferContiguousImageBuffers = true;
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Invert()
|
||||
{
|
||||
D2D1TestRunner.RunAndCompareShader(new InvertEffect(), null, "Landscape.png", "Landscape_Inverted.png");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void InvertWithThreshold()
|
||||
{
|
||||
D2D1TestRunner.RunAndCompareShader(new InvertWithThresholdEffect(1), null, "Landscape.png", "Landscape_Inverted.png");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void InvertWithUserTypeWithConstructor()
|
||||
{
|
||||
D2D1TestRunner.RunAndCompareShader(new InvertWithUserTypeWithConstructorEffect(), null, "Landscape.png", "Landscape_Inverted.png");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void InvertWithUserTypeAndMutuallyInvokingMethods()
|
||||
{
|
||||
D2D1TestRunner.RunAndCompareShader(new InvertWithUserTypeAndMutuallyInvokingMethods(), null, "Landscape.png", "Landscape_Inverted.png");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Pixelate()
|
||||
{
|
||||
D2D1TestRunner.RunAndCompareShader(
|
||||
new PixelateEffect(new PixelateEffect.Constants(1280, 840, 16)),
|
||||
D2D1DrawTransformMapper<PixelateEffect>.Inflate(16),
|
||||
"Landscape.png",
|
||||
"Landscape_Pixelate.png");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ZonePlate()
|
||||
{
|
||||
D2D1TestRunner.RunAndCompareShader(new ZonePlateEffect(1280, 720, 800), 1280, 720, "ZonePlate.png");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CheckerboardClip()
|
||||
{
|
||||
D2D1TestRunner.RunAndCompareShader(new CheckerboardClipEffect(32), null, "Landscape.png", "Landscape_CheckerboardClip.png");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(8, 1, "Landscape")]
|
||||
[DataRow(32, 3, "Landscape")]
|
||||
[DataRow(80, 1, "City")]
|
||||
[DataRow(80, 2, "City")]
|
||||
public void BokehBlur(int radius, int numberOfComponents, string filename)
|
||||
{
|
||||
string assetsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets");
|
||||
string temporaryPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "temp");
|
||||
string sourcePath = Path.Combine(assetsPath, Path.ChangeExtension(filename, "png"));
|
||||
string destinationPathForCpu = Path.Combine(temporaryPath, Path.ChangeExtension($"{filename}_{radius}_{numberOfComponents}_cpu", "png"));
|
||||
string destinationPathForGpu = Path.Combine(temporaryPath, Path.ChangeExtension($"{filename}_{radius}_{numberOfComponents}_gpu", "png"));
|
||||
|
||||
_ = Directory.CreateDirectory(temporaryPath);
|
||||
|
||||
using Image<Rgba32> original = Image.Load<Rgba32>(sourcePath);
|
||||
using Image<Rgba32> cpu = original.Clone(c => c.BokehBlur(radius, numberOfComponents, 3));
|
||||
|
||||
cpu.SaveAsPng(destinationPathForCpu);
|
||||
|
||||
new BokehBlurEffect(radius, numberOfComponents).ApplyEffect(sourcePath, destinationPathForGpu);
|
||||
|
||||
TolerantImageComparer.AssertEqual(destinationPathForCpu, destinationPathForGpu, 0.00002f);
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using TerraFX.Interop.Windows;
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests.Extensions;
|
||||
|
||||
/// <summary>
|
||||
/// Helper methods for working with the <see cref="ComPtr{T}"/> type.
|
||||
/// </summary>
|
||||
/// <remarks>Trimmed down version of the same file in <c>ComputeSharp</c>.</remarks>
|
||||
internal static class ComPtrExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Moves the current <see cref="ComPtr{T}"/> instance and resets it without releasing the reference.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type to wrap in the current <see cref="ComPtr{T}"/> instance.</typeparam>
|
||||
/// <param name="ptr">The input <see cref="ComPtr{T}"/> instance to move.</param>
|
||||
/// <returns>The moved <see cref="ComPtr{T}"/> instance.</returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static ComPtr<T> Move<T>(this in ComPtr<T> ptr)
|
||||
where T : unmanaged, IUnknown.Interface
|
||||
{
|
||||
ComPtr<T> copy = default;
|
||||
|
||||
Unsafe.AsRef(in ptr).Swap(ref copy);
|
||||
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Runtime.CompilerServices;
|
||||
using TerraFX.Interop.Windows;
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests.Extensions;
|
||||
|
||||
/// <summary>
|
||||
/// Helper methods to efficiently throw exceptions.
|
||||
/// </summary>
|
||||
/// <remarks>Trimmed down version of the same file in <c>ComputeSharp</c>.</remarks>
|
||||
[DebuggerStepThrough]
|
||||
internal static class HRESULTExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Throws a <see cref="Win32Exception"/> if <paramref name="result"/> represents an error.
|
||||
/// </summary>
|
||||
/// <param name="result">The input <see cref="HRESULT"/> to check.</param>
|
||||
/// <exception cref="Win32Exception">Thrown if <paramref name="result"/> represents an error.</exception>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void Assert(this HRESULT result)
|
||||
{
|
||||
if ((int)result < 0)
|
||||
{
|
||||
ThrowWin32Exception(result);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Throws a <see cref="Win32Exception"/> if <paramref name="result"/> represents an error.
|
||||
/// </summary>
|
||||
/// <param name="result">The input <see cref="int"/> to check.</param>
|
||||
/// <exception cref="Win32Exception">Thrown if <paramref name="result"/> represents an error.</exception>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void Assert(this int result)
|
||||
{
|
||||
if (result < 0)
|
||||
{
|
||||
ThrowWin32Exception(result);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Throws a <see cref="Win32Exception"/>.
|
||||
/// </summary>
|
||||
/// <param name="result">The input return code.</param>
|
||||
[DoesNotReturn]
|
||||
private static void ThrowWin32Exception(int result)
|
||||
{
|
||||
throw new Win32Exception(result);
|
||||
}
|
||||
}
|
||||
@@ -1,242 +0,0 @@
|
||||
using System;
|
||||
using ComputeSharp.D2D1.Tests.Extensions;
|
||||
using TerraFX.Interop.DirectX;
|
||||
using TerraFX.Interop.Windows;
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that uses the D2D1 APIs to configure and run effects.
|
||||
/// </summary>
|
||||
internal static class D2D1Helper
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates an <see cref="ID2D1Factory2"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="singleThreaded">Indicates whether or not the factory should be created as single threaded.</param>
|
||||
/// <returns>A new <see cref="ID2D1Factory2"/> instance.</returns>
|
||||
public static unsafe ComPtr<ID2D1Factory2> CreateD2D1Factory2(bool singleThreaded = false)
|
||||
{
|
||||
using ComPtr<ID2D1Factory2> d2D1Factory2 = default;
|
||||
|
||||
D2D1_FACTORY_OPTIONS d2D1FactoryOptions = default;
|
||||
|
||||
// Create a Direct2D factory
|
||||
DirectX.D2D1CreateFactory(
|
||||
factoryType: singleThreaded ? D2D1_FACTORY_TYPE.D2D1_FACTORY_TYPE_SINGLE_THREADED : D2D1_FACTORY_TYPE.D2D1_FACTORY_TYPE_MULTI_THREADED,
|
||||
riid: Windows.__uuidof<ID2D1Factory2>(),
|
||||
pFactoryOptions: &d2D1FactoryOptions,
|
||||
ppIFactory: (void**)d2D1Factory2.GetAddressOf()).Assert();
|
||||
|
||||
return d2D1Factory2.Move();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an <see cref="ID2D1Device"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="d2D1Factory2">The input <see cref="ID2D1Factory2"/> instance to use to create the device.</param>
|
||||
/// <returns>A new <see cref="ID2D1Device"/> instance.</returns>
|
||||
public static unsafe ComPtr<ID2D1Device> CreateD2D1Device(ID2D1Factory2* d2D1Factory2)
|
||||
{
|
||||
using ComPtr<ID3D11Device> d3D11Device = default;
|
||||
|
||||
D3D_FEATURE_LEVEL* featureLevels = stackalloc[]
|
||||
{
|
||||
D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_11_1,
|
||||
D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_11_0,
|
||||
D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_10_1,
|
||||
D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_10_0,
|
||||
D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_9_3,
|
||||
D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_9_2,
|
||||
D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_9_1
|
||||
};
|
||||
D3D_FEATURE_LEVEL d3DFeatureLevel;
|
||||
|
||||
// Create the Direct3D 11 API device and context
|
||||
DirectX.D3D11CreateDevice(
|
||||
pAdapter: null,
|
||||
DriverType: D3D_DRIVER_TYPE.D3D_DRIVER_TYPE_HARDWARE,
|
||||
Software: HMODULE.NULL,
|
||||
Flags: (uint)D3D11_CREATE_DEVICE_FLAG.D3D11_CREATE_DEVICE_BGRA_SUPPORT,
|
||||
pFeatureLevels: featureLevels,
|
||||
FeatureLevels: 7,
|
||||
SDKVersion: D3D11.D3D11_SDK_VERSION,
|
||||
ppDevice: d3D11Device.GetAddressOf(),
|
||||
pFeatureLevel: &d3DFeatureLevel,
|
||||
ppImmediateContext: null).Assert();
|
||||
|
||||
using ComPtr<IDXGIDevice3> dxgiDevice3 = default;
|
||||
|
||||
// Get a DXGI device from the D3D11 device
|
||||
d3D11Device.CopyTo(dxgiDevice3.GetAddressOf()).Assert();
|
||||
|
||||
using ComPtr<ID2D1Device> d2D1Device = default;
|
||||
|
||||
// Create a D2D1 device
|
||||
_ = d2D1Factory2->CreateDevice(
|
||||
dxgiDevice: (IDXGIDevice*)dxgiDevice3.Get(),
|
||||
d2dDevice: d2D1Device.GetAddressOf());
|
||||
|
||||
return d2D1Device.Move();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an <see cref="ID2D1DeviceContext"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="d2D1Device">The input <see cref="ID2D1Device"/> instance to use to create the context.</param>
|
||||
/// <returns>A new <see cref="ID2D1DeviceContext"/> instance.</returns>
|
||||
public static unsafe ComPtr<ID2D1DeviceContext> CreateD2D1DeviceContext(ID2D1Device* d2D1Device)
|
||||
{
|
||||
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = default;
|
||||
|
||||
// Create a D2D1 device context
|
||||
d2D1Device->CreateDeviceContext(
|
||||
options: D2D1_DEVICE_CONTEXT_OPTIONS.D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
|
||||
deviceContext: d2D1DeviceContext.GetAddressOf()).Assert();
|
||||
|
||||
return d2D1DeviceContext.Move();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an <see cref="ID2D1Bitmap"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="d2D1DeviceContext">The input <see cref="ID2D1DeviceContext"/> instance to use to create the bitmap source.</param>
|
||||
/// <param name="pixels">The loaded pixel data.</param>
|
||||
/// <param name="width">The width of the bitmap.</param>
|
||||
/// <param name="height">The height of the bitmap.</param>
|
||||
/// <param name="d2D1Effect">The input <see cref="ID2D1Effect"/> to set the source for.</param>
|
||||
/// <returns>A new <see cref="ID2D1Bitmap"/> instance.</returns>
|
||||
public static unsafe ComPtr<ID2D1Bitmap> CreateD2D1BitmapAndSetAsSource(
|
||||
ID2D1DeviceContext* d2D1DeviceContext,
|
||||
ReadOnlyMemory<byte> pixels,
|
||||
uint width,
|
||||
uint height,
|
||||
ID2D1Effect* d2D1Effect)
|
||||
{
|
||||
using ComPtr<ID2D1Bitmap> d2D1BitmapSource = default;
|
||||
|
||||
D2D_SIZE_U d2DSize = new(width, height);
|
||||
|
||||
D2D1_BITMAP_PROPERTIES d2DBitmapProperties = default;
|
||||
d2DBitmapProperties.pixelFormat.format = DXGI_FORMAT.DXGI_FORMAT_B8G8R8A8_UNORM;
|
||||
d2DBitmapProperties.pixelFormat.alphaMode = D2D1_ALPHA_MODE.D2D1_ALPHA_MODE_PREMULTIPLIED;
|
||||
d2DBitmapProperties.dpiX = 96;
|
||||
d2DBitmapProperties.dpiY = 96;
|
||||
|
||||
fixed (byte* p = pixels.Span)
|
||||
{
|
||||
// Create a source D2D1 bitmap from the image data
|
||||
d2D1DeviceContext->CreateBitmap(
|
||||
size: d2DSize,
|
||||
srcData: p,
|
||||
pitch: width * 4,
|
||||
bitmapProperties: &d2DBitmapProperties,
|
||||
bitmap: d2D1BitmapSource.GetAddressOf()).Assert();
|
||||
}
|
||||
|
||||
d2D1Effect->SetInput(0, (ID2D1Image*)d2D1BitmapSource.Get());
|
||||
|
||||
return d2D1BitmapSource.Move();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an <see cref="ID2D1Bitmap"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="d2D1DeviceContext">The input <see cref="ID2D1DeviceContext"/> instance to use to create the bitmap source.</param>
|
||||
/// <param name="width">The width of the bitmap to create.</param>
|
||||
/// <param name="height">The height of the bitmap to create.</param>
|
||||
/// <returns>A new <see cref="ID2D1Bitmap"/> instance.</returns>
|
||||
public static unsafe ComPtr<ID2D1Bitmap> CreateD2D1BitmapAndSetAsTarget(ID2D1DeviceContext* d2D1DeviceContext, uint width, uint height)
|
||||
{
|
||||
D2D_SIZE_U d2DSize = new(width, height);
|
||||
|
||||
D2D1_BITMAP_PROPERTIES1 d2DBitmapProperties1Target = default;
|
||||
d2DBitmapProperties1Target.pixelFormat.format = DXGI_FORMAT.DXGI_FORMAT_B8G8R8A8_UNORM;
|
||||
d2DBitmapProperties1Target.pixelFormat.alphaMode = D2D1_ALPHA_MODE.D2D1_ALPHA_MODE_PREMULTIPLIED;
|
||||
d2DBitmapProperties1Target.bitmapOptions = D2D1_BITMAP_OPTIONS.D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS.D2D1_BITMAP_OPTIONS_CANNOT_DRAW;
|
||||
|
||||
using ComPtr<ID2D1Bitmap> d2D1Bitmap1Target = default;
|
||||
|
||||
// Create a target D2D1 bitmap
|
||||
d2D1DeviceContext->CreateBitmap(
|
||||
size: d2DSize,
|
||||
sourceData: null,
|
||||
pitch: 0,
|
||||
bitmapProperties: &d2DBitmapProperties1Target,
|
||||
bitmap: (ID2D1Bitmap1**)d2D1Bitmap1Target.GetAddressOf()).Assert();
|
||||
|
||||
d2D1DeviceContext->SetTarget((ID2D1Image*)d2D1Bitmap1Target.Get());
|
||||
|
||||
return d2D1Bitmap1Target.Move();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an <see cref="ID2D1Bitmap1"/> instance and copies data from a source bitmap.
|
||||
/// </summary>
|
||||
/// <param name="d2D1DeviceContext">The input <see cref="ID2D1DeviceContext"/> instance to use to create the bitmap.</param>
|
||||
/// <param name="d2D1Bitmap">The input <see cref="ID2D1Bitmap1"/> to read data from.</param>
|
||||
/// <param name="d2D1MappedRect">The resulting <see cref="D2D1_MAPPED_RECT"/> for the bitmap.</param>
|
||||
/// <returns>A new <see cref="ID2D1Bitmap1"/> instance.</returns>
|
||||
public static unsafe ComPtr<ID2D1Bitmap1> CreateD2D1Bitmap1Buffer(ID2D1DeviceContext* d2D1DeviceContext, ID2D1Bitmap* d2D1Bitmap, out D2D1_MAPPED_RECT d2D1MappedRect)
|
||||
{
|
||||
D2D_SIZE_U d2DSize = d2D1Bitmap->GetPixelSize();
|
||||
|
||||
D2D1_BITMAP_PROPERTIES1 d2DBitmapProperties1Buffer = default;
|
||||
d2DBitmapProperties1Buffer.pixelFormat.format = DXGI_FORMAT.DXGI_FORMAT_B8G8R8A8_UNORM;
|
||||
d2DBitmapProperties1Buffer.pixelFormat.alphaMode = D2D1_ALPHA_MODE.D2D1_ALPHA_MODE_PREMULTIPLIED;
|
||||
d2DBitmapProperties1Buffer.bitmapOptions = D2D1_BITMAP_OPTIONS.D2D1_BITMAP_OPTIONS_CPU_READ | D2D1_BITMAP_OPTIONS.D2D1_BITMAP_OPTIONS_CANNOT_DRAW;
|
||||
|
||||
using ComPtr<ID2D1Bitmap1> d2D1Bitmap1Buffer = default;
|
||||
|
||||
// Create a buffer D2D1 bitmap
|
||||
d2D1DeviceContext->CreateBitmap(
|
||||
size: d2DSize,
|
||||
sourceData: null,
|
||||
pitch: 0,
|
||||
bitmapProperties: &d2DBitmapProperties1Buffer,
|
||||
bitmap: d2D1Bitmap1Buffer.GetAddressOf()).Assert();
|
||||
|
||||
D2D_POINT_2U d2DPointDestination = default;
|
||||
D2D_RECT_U d2DRectSource = default;
|
||||
d2DRectSource.top = 0;
|
||||
d2DRectSource.left = 0;
|
||||
d2DRectSource.right = d2DSize.width;
|
||||
d2DRectSource.bottom = d2DSize.height;
|
||||
|
||||
// Copy the image from the target to the readback bitmap
|
||||
_ = d2D1Bitmap1Buffer.Get()->CopyFromBitmap(
|
||||
destPoint: &d2DPointDestination,
|
||||
bitmap: d2D1Bitmap,
|
||||
srcRect: &d2DRectSource);
|
||||
|
||||
fixed (D2D1_MAPPED_RECT* d2D1MappedRectPtr = &d2D1MappedRect)
|
||||
{
|
||||
// Map the buffer bitmap
|
||||
d2D1Bitmap1Buffer.Get()->Map(
|
||||
options: D2D1_MAP_OPTIONS.D2D1_MAP_OPTIONS_READ,
|
||||
mappedRect: d2D1MappedRectPtr).Assert();
|
||||
}
|
||||
|
||||
return d2D1Bitmap1Buffer.Move();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Draws a given effect onto a context.
|
||||
/// </summary>
|
||||
/// <param name="d2D1DeviceContext">The input <see cref="ID2D1DeviceContext"/> instance to use to draw the effect.</param>
|
||||
/// <param name="d2D1Effect">The input <see cref="ID2D1Effect"/> to draw.</param>
|
||||
public static unsafe void DrawEffect(ID2D1DeviceContext* d2D1DeviceContext, ID2D1Effect* d2D1Effect)
|
||||
{
|
||||
d2D1DeviceContext->BeginDraw();
|
||||
|
||||
// Draw the image with the effect
|
||||
d2D1DeviceContext->DrawImage(
|
||||
effect: d2D1Effect,
|
||||
targetOffset: null,
|
||||
imageRectangle: null,
|
||||
interpolationMode: D2D1_INTERPOLATION_MODE.D2D1_INTERPOLATION_MODE_NEAREST_NEIGHBOR,
|
||||
compositeMode: D2D1_COMPOSITE_MODE.D2D1_COMPOSITE_MODE_SOURCE_COPY);
|
||||
|
||||
d2D1DeviceContext->EndDraw().Assert();
|
||||
}
|
||||
}
|
||||
@@ -1,194 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using ComputeSharp.D2D1.Descriptors;
|
||||
using ComputeSharp.D2D1.Interop;
|
||||
using ComputeSharp.Tests.Helpers;
|
||||
using TerraFX.Interop.DirectX;
|
||||
using TerraFX.Interop.Windows;
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// A test helper for D2D1 pixel shaders.
|
||||
/// </summary>
|
||||
internal static class D2D1TestRunner
|
||||
{
|
||||
/// <summary>
|
||||
/// Executes a pixel shader and compares the expected results.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of pixel shader to run.</typeparam>
|
||||
/// <param name="transformMapper">A custom <see cref="D2D1DrawTransformMapper{T}"/> instance for the effect.</param>
|
||||
/// <param name="originalFileName">The name of the source image.</param>
|
||||
/// <param name="expectedFileName">The name of the expected result image.</param>
|
||||
/// <param name="destinationFileName">The name of the destination image to save results to.</param>
|
||||
/// <param name="shader">The shader to run.</param>
|
||||
/// <param name="threshold">The allowed difference threshold for the normalized delta.</param>
|
||||
public static void RunAndCompareShader<T>(
|
||||
in T shader,
|
||||
D2D1DrawTransformMapper<T>? transformMapper,
|
||||
string originalFileName,
|
||||
string expectedFileName,
|
||||
[CallerMemberName] string destinationFileName = "",
|
||||
float threshold = 0.00001f)
|
||||
where T : unmanaged, ID2D1PixelShader, ID2D1PixelShaderDescriptor<T>
|
||||
{
|
||||
string assetsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets");
|
||||
string temporaryPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "temp");
|
||||
|
||||
_ = Directory.CreateDirectory(temporaryPath);
|
||||
|
||||
string originalPath = Path.Combine(assetsPath, originalFileName);
|
||||
string expectedPath = Path.Combine(assetsPath, expectedFileName);
|
||||
string destinationPath = Path.Combine(temporaryPath, $"{destinationFileName}.png");
|
||||
|
||||
// Run the shader
|
||||
ExecutePixelShaderAndSaveToFile(
|
||||
in shader,
|
||||
transformMapper,
|
||||
originalPath,
|
||||
destinationPath);
|
||||
|
||||
// Compare the results
|
||||
TolerantImageComparer.AssertEqual(destinationPath, expectedPath, threshold);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes a pixel shader and compares the expected results.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of pixel shader to run.</typeparam>
|
||||
/// <param name="width">The resulting width.</param>
|
||||
/// <param name="height">The resulting height.</param>
|
||||
/// <param name="expectedFileName">The name of the expected result image.</param>
|
||||
/// <param name="destinationFileName">The name of the destination image to save results to.</param>
|
||||
/// <param name="shader">The shader to run.</param>
|
||||
/// <param name="threshold">The allowed difference threshold for the normalized delta.</param>
|
||||
/// <param name="resourceTextures">The additional resource textures to use to run the shader.</param>
|
||||
public static void RunAndCompareShader<T>(
|
||||
in T shader,
|
||||
int width,
|
||||
int height,
|
||||
string expectedFileName,
|
||||
[CallerMemberName] string destinationFileName = "",
|
||||
float threshold = 0.00001f,
|
||||
params (int Index, D2D1ResourceTextureManager ResourceTextureManager)[] resourceTextures)
|
||||
where T : unmanaged, ID2D1PixelShader, ID2D1PixelShaderDescriptor<T>
|
||||
{
|
||||
string assetsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets");
|
||||
string temporaryPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "temp");
|
||||
|
||||
_ = Directory.CreateDirectory(temporaryPath);
|
||||
|
||||
string expectedPath = Path.Combine(assetsPath, expectedFileName);
|
||||
string destinationPath = Path.Combine(temporaryPath, $"{destinationFileName}.png");
|
||||
|
||||
// Run the shader
|
||||
ExecutePixelShaderAndSaveToFile(
|
||||
in shader,
|
||||
null,
|
||||
width,
|
||||
height,
|
||||
destinationPath,
|
||||
resourceTextures);
|
||||
|
||||
// Compare the results
|
||||
TolerantImageComparer.AssertEqual(destinationPath, expectedPath, threshold);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes a pixel shader to produce an image.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The shader type to execute.</typeparam>
|
||||
/// <param name="shader">The shader to run.</param>
|
||||
/// <param name="transformMapper">A custom <see cref="D2D1DrawTransformMapper{T}"/> instance for the effect.</param>
|
||||
/// <param name="sourcePath">The source path for the image to run the shader on.</param>
|
||||
/// <param name="destinationPath">The destination path for the result.</param>
|
||||
private static unsafe void ExecutePixelShaderAndSaveToFile<T>(
|
||||
in T shader,
|
||||
D2D1DrawTransformMapper<T>? transformMapper,
|
||||
string sourcePath,
|
||||
string destinationPath)
|
||||
where T : unmanaged, ID2D1PixelShader, ID2D1PixelShaderDescriptor<T>
|
||||
{
|
||||
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2();
|
||||
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
|
||||
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
|
||||
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<T>(d2D1Factory2.Get(), out _);
|
||||
|
||||
using ComPtr<ID2D1Effect> d2D1Effect = default;
|
||||
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<T>(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf());
|
||||
|
||||
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), in shader);
|
||||
|
||||
if (transformMapper is not null)
|
||||
{
|
||||
D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(d2D1Effect.Get(), transformMapper);
|
||||
}
|
||||
|
||||
ReadOnlyMemory<byte> pixels = ImageHelper.LoadBitmapFromFile(sourcePath, out uint width, out uint height);
|
||||
|
||||
using ComPtr<ID2D1Bitmap> d2D1BitmapSource = D2D1Helper.CreateD2D1BitmapAndSetAsSource(d2D1DeviceContext.Get(), pixels, width, height, d2D1Effect.Get());
|
||||
using ComPtr<ID2D1Bitmap> d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), width, height);
|
||||
|
||||
D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get());
|
||||
|
||||
using ComPtr<ID2D1Bitmap1> d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect);
|
||||
|
||||
// Save the image
|
||||
ImageHelper.SaveBitmapToFile(destinationPath, width, height, d2D1MappedRect.pitch, d2D1MappedRect.bits);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes a pixel shader to produce an image.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The shader type to execute.</typeparam>
|
||||
/// <param name="shader">The shader to run.</param>
|
||||
/// <param name="width">The resulting width.</param>
|
||||
/// <param name="height">The resulting height.</param>
|
||||
/// <param name="transformMapper">A custom <see cref="D2D1DrawTransformMapper{T}"/> instance for the effect.</param>
|
||||
/// <param name="destinationPath">The destination path for the result.</param>
|
||||
/// <param name="resourceTextures">The additional resource textures to use to run the shader.</param>
|
||||
private static unsafe void ExecutePixelShaderAndSaveToFile<T>(
|
||||
in T shader,
|
||||
D2D1DrawTransformMapper<T>? transformMapper,
|
||||
int width,
|
||||
int height,
|
||||
string destinationPath,
|
||||
params (int Index, D2D1ResourceTextureManager ResourceTextureManager)[] resourceTextures)
|
||||
where T : unmanaged, ID2D1PixelShader, ID2D1PixelShaderDescriptor<T>
|
||||
{
|
||||
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2();
|
||||
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
|
||||
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
|
||||
|
||||
D2D1PixelShaderEffect.RegisterForD2D1Factory1<T>(d2D1Factory2.Get(), out _);
|
||||
|
||||
using ComPtr<ID2D1Effect> d2D1Effect = default;
|
||||
|
||||
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<T>(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf());
|
||||
|
||||
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), in shader);
|
||||
|
||||
if (transformMapper is not null)
|
||||
{
|
||||
D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(d2D1Effect.Get(), transformMapper);
|
||||
}
|
||||
|
||||
foreach ((int index, D2D1ResourceTextureManager resourceTextureManager) in resourceTextures)
|
||||
{
|
||||
D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(d2D1Effect.Get(), resourceTextureManager, index);
|
||||
}
|
||||
|
||||
using ComPtr<ID2D1Bitmap> d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), (uint)width, (uint)height);
|
||||
|
||||
D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get());
|
||||
|
||||
using ComPtr<ID2D1Bitmap1> d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect);
|
||||
|
||||
// Save the image
|
||||
ImageHelper.SaveBitmapToFile(destinationPath, (uint)width, (uint)height, d2D1MappedRect.pitch, d2D1MappedRect.bits);
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> with helpers to load and save images.
|
||||
/// </summary>
|
||||
internal static class ImageHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Loads a <see cref="ReadOnlyMemory{T}"/> instance from a given path.
|
||||
/// </summary>
|
||||
/// <param name="filename">The path to load the image from.</param>
|
||||
/// <param name="width">The resulting image width.</param>
|
||||
/// <param name="height">The resulting image height.</param>
|
||||
/// <returns>The resulting <see cref="ReadOnlyMemory{T}"/> instance.</returns>
|
||||
public static unsafe ReadOnlyMemory<byte> LoadBitmapFromFile(string filename, out uint width, out uint height)
|
||||
{
|
||||
using Image<Bgra32> image = Image.Load<Bgra32>(filename);
|
||||
|
||||
width = (uint)image.Width;
|
||||
height = (uint)image.Height;
|
||||
|
||||
if (!image.DangerousTryGetSinglePixelMemory(out Memory<Bgra32> memory))
|
||||
{
|
||||
Assert.Inconclusive();
|
||||
}
|
||||
|
||||
return MemoryMarshal.AsBytes(memory.Span).ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves a given image buffer to a target path.
|
||||
/// </summary>
|
||||
/// <param name="filename">The path to save the image to.</param>
|
||||
/// <param name="width">The image width.</param>
|
||||
/// <param name="height">The image height.</param>
|
||||
/// <param name="strideInBytes">The image stride in bytes.</param>
|
||||
/// <param name="buffer">The image pixel buffer.</param>
|
||||
public static unsafe void SaveBitmapToFile(string filename, uint width, uint height, uint strideInBytes, byte* buffer)
|
||||
{
|
||||
byte[] pixelData = ArrayPool<byte>.Shared.Rent((int)width * (int)height * sizeof(Bgra32));
|
||||
|
||||
for (int i = 0; i < (int)height; i++)
|
||||
{
|
||||
ReadOnlySpan<byte> source = new(buffer + (i * (int)strideInBytes), (int)width * sizeof(Bgra32));
|
||||
|
||||
source.CopyTo(pixelData.AsSpan(i * (int)width * sizeof(Bgra32)));
|
||||
}
|
||||
|
||||
using (Image<Bgra32> image = Image.WrapMemory<Bgra32>(pixelData, (int)width, (int)height))
|
||||
{
|
||||
image.Save(filename);
|
||||
}
|
||||
|
||||
ArrayPool<byte>.Shared.Return(pixelData);
|
||||
}
|
||||
}
|
||||
@@ -1,240 +0,0 @@
|
||||
using ComputeSharp.D2D1.Interop;
|
||||
using ComputeSharp.D2D1.Tests.Helpers;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
#pragma warning disable CA1822
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests;
|
||||
|
||||
[TestClass]
|
||||
public partial class ShaderRewriterTests
|
||||
{
|
||||
// See https://github.com/Sergio0694/ComputeSharp/issues/725
|
||||
[TestMethod]
|
||||
public void ShaderWithStructAndInstanceMethodUsingIt_IsRewrittenCorrectly()
|
||||
{
|
||||
D2D1ShaderInfo shaderInfo = D2D1ReflectionServices.GetShaderInfo<ClassWithShader.ShaderWithStructAndInstanceMethodUsingIt>();
|
||||
|
||||
Assert.AreEqual("""
|
||||
#define D2D_INPUT_COUNT 0
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
struct ComputeSharp_D2D1_Tests_ShaderRewriterTests_ClassWithShader_ShaderWithStructAndInstanceMethodUsingIt_Data
|
||||
{
|
||||
int value;
|
||||
};
|
||||
|
||||
void UseData(inout ComputeSharp_D2D1_Tests_ShaderRewriterTests_ClassWithShader_ShaderWithStructAndInstanceMethodUsingIt_Data data);
|
||||
|
||||
void UseData(inout ComputeSharp_D2D1_Tests_ShaderRewriterTests_ClassWithShader_ShaderWithStructAndInstanceMethodUsingIt_Data data)
|
||||
{
|
||||
++data.value;
|
||||
}
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
ComputeSharp_D2D1_Tests_ShaderRewriterTests_ClassWithShader_ShaderWithStructAndInstanceMethodUsingIt_Data data = (ComputeSharp_D2D1_Tests_ShaderRewriterTests_ClassWithShader_ShaderWithStructAndInstanceMethodUsingIt_Data)0;
|
||||
UseData(data);
|
||||
return float4(data.value, data.value, data.value, data.value);
|
||||
}
|
||||
""", shaderInfo.HlslSource);
|
||||
}
|
||||
|
||||
internal sealed partial class ClassWithShader
|
||||
{
|
||||
[D2DInputCount(0)]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct ShaderWithStructAndInstanceMethodUsingIt : ID2D1PixelShader
|
||||
{
|
||||
private struct Data
|
||||
{
|
||||
public int value;
|
||||
}
|
||||
|
||||
public float4 Execute()
|
||||
{
|
||||
Data data = default;
|
||||
|
||||
UseData(ref data);
|
||||
|
||||
return new float4(data.value, data.value, data.value, data.value);
|
||||
}
|
||||
|
||||
private void UseData(ref Data data)
|
||||
{
|
||||
++data.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// See https://github.com/Sergio0694/ComputeSharp/issues/735
|
||||
[TestMethod]
|
||||
public void KnownNamedIntrinsic_ConditionalSelect()
|
||||
{
|
||||
D2D1ShaderInfo shaderInfo = D2D1ReflectionServices.GetShaderInfo<KnownNamedIntrinsic_ConditionalSelectShader>();
|
||||
|
||||
Assert.AreEqual("""
|
||||
#define D2D_INPUT_COUNT 0
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
bool4 mask4 = bool4(true, false, true, true);
|
||||
float4 float4_1 = float4(1, 2, asfloat(1078523331U), 4);
|
||||
float4 float4_2 = float4(5, 6, 7, 8);
|
||||
float4 float4_r = (mask4 ? float4_1 : float4_2);
|
||||
bool1x3 mask1x3 = bool1x3((bool)true, (bool)true, (bool)false);
|
||||
int1x3 int1x3_1 = int1x3((int)1, (int)2, (int)3);
|
||||
int1x3 int1x3_2 = int1x3((int)4, (int)5, (int)6);
|
||||
int1x3 int1x3_r = (mask1x3 ? int1x3_1 : int1x3_2);
|
||||
bool2x4 mask2x4 = bool2x4((bool)true, (bool)true, (bool)false, (bool)true, (bool)false, (bool)false, (bool)false, (bool)true);
|
||||
uint2x4 uint2x4_1 = uint2x4((uint)1, (uint)2, (uint)3, (uint)4, (uint)5, (uint)6, (uint)7, (uint)8);
|
||||
uint2x4 uint2x4_2 = uint2x4((uint)111, (uint)222, (uint)333, (uint)444, (uint)555, (uint)666, (uint)777, (uint)888);
|
||||
uint2x4 uint2x4_r = (mask2x4 ? uint2x4_1 : uint2x4_2);
|
||||
float2x2 f2x2_r = mul((float2x4)uint2x4_r, float4x2((float2)float4_r.xy, (float2)float4_r.zw, (float2)float2(int1x3_r._m00, int1x3_r._m01), (float2)float2(int1x3_r._m02, asfloat(1065353216U))));
|
||||
return float4(f2x2_r._m00, f2x2_r._m01, f2x2_r._m10, f2x2_r._m11);
|
||||
}
|
||||
""", shaderInfo.HlslSource);
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct KnownNamedIntrinsic_ConditionalSelectShader : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
bool4 mask4 = new(true, false, true, true);
|
||||
float4 float4_1 = new(1, 2, 3.14f, 4);
|
||||
float4 float4_2 = new(5, 6, 7, 8);
|
||||
|
||||
float4 float4_r = Hlsl.Select(mask4, float4_1, float4_2);
|
||||
|
||||
bool1x3 mask1x3 = new(true, true, false);
|
||||
int1x3 int1x3_1 = new(1, 2, 3);
|
||||
int1x3 int1x3_2 = new(4, 5, 6);
|
||||
|
||||
int1x3 int1x3_r = Hlsl.Select(mask1x3, int1x3_1, int1x3_2);
|
||||
|
||||
bool2x4 mask2x4 = new(true, true, false, true, false, false, false, true);
|
||||
uint2x4 uint2x4_1 = new(1, 2, 3, 4, 5, 6, 7, 8);
|
||||
uint2x4 uint2x4_2 = new(111, 222, 333, 444, 555, 666, 777, 888);
|
||||
|
||||
uint2x4 uint2x4_r = Hlsl.Select(mask2x4, uint2x4_1, uint2x4_2);
|
||||
|
||||
float2x2 f2x2_r = (float2x4)uint2x4_r * new float4x2(float4_r.XY, float4_r.ZW, new float2(int1x3_r.M11, int1x3_r.M12), new float2(int1x3_r.M13, 1.0f));
|
||||
|
||||
return new(f2x2_r.M11, f2x2_r.M12, f2x2_r.M21, f2x2_r.M22);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void KnownNamedIntrinsic_AndOr()
|
||||
{
|
||||
D2D1ShaderInfo shaderInfo = D2D1ReflectionServices.GetShaderInfo<KnownNamedIntrinsic_AndOrShader>();
|
||||
|
||||
Assert.AreEqual("""
|
||||
#define D2D_INPUT_COUNT 0
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
bool4 mask4_1 = bool4(true, false, true, true);
|
||||
bool4 mask4_2 = bool4(true, false, true, true);
|
||||
bool4 mask4_r_and = (mask4_1 && mask4_2);
|
||||
bool4 mask4_r_or = (mask4_1 || mask4_2);
|
||||
bool2x3 mask2x3_1 = bool2x3((bool)true, (bool)false, (bool)true, (bool)true, (bool)false, (bool)false);
|
||||
bool2x3 mask2x3_2 = bool2x3((bool)true, (bool)false, (bool)true, (bool)true, (bool)true, (bool)true);
|
||||
bool2x3 mask2x3_r_and = (mask2x3_1 && mask2x3_2);
|
||||
bool2x3 mask2x3_r_or = (mask2x3_1 || mask2x3_2);
|
||||
return float4(mask4_r_and.x ? 1 : 0, mask4_r_or.y ? 1 : 0, mask2x3_r_and._m00 ? 1 : 0, mask2x3_r_or._m00 ? 1 : 0);
|
||||
}
|
||||
""", shaderInfo.HlslSource);
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct KnownNamedIntrinsic_AndOrShader : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
bool4 mask4_1 = new(true, false, true, true);
|
||||
bool4 mask4_2 = new(true, false, true, true);
|
||||
bool4 mask4_r_and = Hlsl.And(mask4_1, mask4_2);
|
||||
bool4 mask4_r_or = Hlsl.Or(mask4_1, mask4_2);
|
||||
|
||||
bool2x3 mask2x3_1 = new(true, false, true, true, false, false);
|
||||
bool2x3 mask2x3_2 = new(true, false, true, true, true, true);
|
||||
bool2x3 mask2x3_r_and = Hlsl.And(mask2x3_1, mask2x3_2);
|
||||
bool2x3 mask2x3_r_or = Hlsl.Or(mask2x3_1, mask2x3_2);
|
||||
|
||||
return new(
|
||||
mask4_r_and.X ? 1 : 0,
|
||||
mask4_r_or.Y ? 1 : 0,
|
||||
mask2x3_r_and.M11 ? 1 : 0,
|
||||
mask2x3_r_or.M11 ? 1 : 0);
|
||||
}
|
||||
}
|
||||
|
||||
// See https://github.com/Sergio0694/ComputeSharp/issues/780
|
||||
[TestMethod]
|
||||
public void ProblematicFloatLiteralValue_IsRewrittenCorrectly()
|
||||
{
|
||||
D2D1TestRunner.RunAndCompareShader(
|
||||
new ProblematicFloatLiteralValueShader(131072.65f),
|
||||
32,
|
||||
32,
|
||||
"Green32x32.png");
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DOutputBuffer(D2D1BufferPrecision.Float32)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct ProblematicFloatLiteralValueShader(float x) : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
if (x != 131072.65f)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
return new float4(0.0f, 1.0f, 0.0f, 1.0f);
|
||||
}
|
||||
}
|
||||
|
||||
// See https://github.com/Sergio0694/ComputeSharp/issues/855
|
||||
[TestMethod]
|
||||
public void ExplicitEntryPointMethodPixelShader_IsRewrittenCorrectly()
|
||||
{
|
||||
D2D1ShaderInfo shaderInfo = D2D1ReflectionServices.GetShaderInfo<ExplicitEntryPointMethodPixelShader>();
|
||||
|
||||
Assert.AreEqual("""
|
||||
#define D2D_INPUT_COUNT 0
|
||||
|
||||
#include "d2d1effecthelpers.hlsli"
|
||||
|
||||
D2D_PS_ENTRY(Execute)
|
||||
{
|
||||
return (float4)0;
|
||||
}
|
||||
""", shaderInfo.HlslSource);
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal readonly partial struct ExplicitEntryPointMethodPixelShader : ID2D1PixelShader
|
||||
{
|
||||
float4 ID2D1PixelShader.Execute()
|
||||
{
|
||||
return default;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeSharp.D2D1.Descriptors;
|
||||
using ComputeSharp.D2D1.Interop;
|
||||
using ComputeSharp.D2D1.Tests.Helpers;
|
||||
using ComputeSharp.SwapChain.Shaders.D2D1;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests;
|
||||
|
||||
[TestClass]
|
||||
public class ShadersTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void HelloWorld()
|
||||
{
|
||||
RunTest<HelloWorld>();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ColorfulInfinity()
|
||||
{
|
||||
RunTest<ColorfulInfinity>();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void FractalTiling()
|
||||
{
|
||||
RunTest<FractalTiling>();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void MengerJourney()
|
||||
{
|
||||
RunTest<MengerJourney>(0.000011f);
|
||||
}
|
||||
|
||||
// This test and the other 3 below are skipped because they do produce valid result,
|
||||
// but the resulting images are different than the ones used as reference, so they
|
||||
// cannot be compared. They can be uncommented once the reason why they are seemingly
|
||||
// being randomized and producing different outputs has been identified and resolved.
|
||||
[TestMethod]
|
||||
[Ignore]
|
||||
public void TwoTiledTruchet()
|
||||
{
|
||||
RunTest<TwoTiledTruchet>();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Octagrams()
|
||||
{
|
||||
RunTest<Octagrams>();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ProteanClouds()
|
||||
{
|
||||
RunTest<ProteanClouds>();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Ignore]
|
||||
public void PyramidPattern()
|
||||
{
|
||||
RunTest<PyramidPattern>();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Ignore]
|
||||
public void TriangleGridContouring()
|
||||
{
|
||||
RunTest<TriangleGridContouring>();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Ignore]
|
||||
public unsafe void ContouredLayers()
|
||||
{
|
||||
string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!;
|
||||
string expectedPath = Path.Combine(assemblyPath, "Assets", "Textures", "RustyMetal.png");
|
||||
|
||||
D2D1ResourceTextureManager resourceTextureManager;
|
||||
|
||||
using (Image<Rgba32> texture = Image.Load<Rgba32>(expectedPath))
|
||||
{
|
||||
if (!texture.DangerousTryGetSinglePixelMemory(out Memory<Rgba32> pixels))
|
||||
{
|
||||
Assert.Inconclusive();
|
||||
}
|
||||
|
||||
resourceTextureManager = new D2D1ResourceTextureManager(
|
||||
extents: [(uint)texture.Width, (uint)texture.Height],
|
||||
bufferPrecision: D2D1BufferPrecision.UInt8Normalized,
|
||||
channelDepth: D2D1ChannelDepth.Four,
|
||||
filter: D2D1Filter.MinMagMipLinear,
|
||||
extendModes: [D2D1ExtendMode.Mirror, D2D1ExtendMode.Mirror],
|
||||
data: MemoryMarshal.AsBytes(pixels.Span),
|
||||
strides: [(uint)(texture.Width * sizeof(Rgba32))]);
|
||||
}
|
||||
|
||||
ContouredLayers shader = new(0f, new int2(1280, 720));
|
||||
|
||||
D2D1TestRunner.RunAndCompareShader(in shader, 1280, 720, $"{nameof(ContouredLayers)}.png", nameof(ContouredLayers), resourceTextures: (0, resourceTextureManager));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TerracedHills()
|
||||
{
|
||||
RunTest<TerracedHills>(0.000027f);
|
||||
}
|
||||
|
||||
private static void RunTest<T>(float threshold = 0.00001f)
|
||||
where T : unmanaged, ID2D1PixelShader, ID2D1PixelShaderDescriptor<T>
|
||||
{
|
||||
T shader = (T)Activator.CreateInstance(typeof(T), 0f, new int2(1280, 720))!;
|
||||
|
||||
D2D1TestRunner.RunAndCompareShader(in shader, 1280, 720, $"{typeof(T).Name}.png", typeof(T).Name, threshold);
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
|
||||
<TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>
|
||||
<Platforms>x64;ARM64</Platforms>
|
||||
<RuntimeIdentifiers>win-x64;win-arm64</RuntimeIdentifiers>
|
||||
<DefineConstants>$(DefineConstants);D2D1_WINUI_TESTS</DefineConstants>
|
||||
|
||||
<!-- Temporary workaround, see notes in 'ComputeSharp.D2D1.Tests.SourceGenerators' -->
|
||||
<NoWarn>$(NoWarn);NU1902;NU1903</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Basic.Reference.Assemblies.Net80" Version="1.8.0" />
|
||||
<PackageReference Include="MSTest" Version="3.8.3" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Analyzer.Testing" Version="1.1.2" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.CodeFix.Testing" Version="1.1.2" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.12.0" />
|
||||
|
||||
<!-- Top-level overrides to fix address security vulnerability warnings -->
|
||||
<PackageReference Include="System.Formats.Asn1" Version="9.0.4" />
|
||||
<PackageReference Include="System.Private.Uri" Version="4.3.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.Core\ComputeSharp.Core.csproj" Aliases="Core" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.D2D1\ComputeSharp.D2D1.csproj" Aliases="D2D1" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.D2D1.WinUI\ComputeSharp.D2D1.WinUI.csproj" Aliases="D2D1_WinUI" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.D2D1.WinUI.CodeFixers\ComputeSharp.D2D1.WinUI.CodeFixers.csproj" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.D2D1.WinUI.SourceGenerators\ComputeSharp.D2D1.WinUI.SourceGenerators.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\ComputeSharp.Tests.SourceGenerators\Helpers\CSharpAnalyzerTest{TAnalyzer}.cs" Link="Helpers\CSharpAnalyzerTest{TAnalyzer}.cs" />
|
||||
<Compile Include="..\ComputeSharp.Tests.SourceGenerators\Helpers\CSharpGeneratorTest{TGenerator}.cs" Link="Helpers\CSharpGeneratorTest{TGenerator}.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,42 +0,0 @@
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using Microsoft.CodeAnalysis.Testing;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CodeFixes;
|
||||
using Microsoft.CodeAnalysis.CSharp.Testing;
|
||||
|
||||
#pragma warning disable IDE0290
|
||||
|
||||
namespace ComputeSharp.Tests.SourceGenerators.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// A custom <see cref="CSharpCodeFixTest{TAnalyzer, TCodeFix, TVerifier}"/> that uses a specific C# language version to parse code.
|
||||
/// </summary>
|
||||
/// <typeparam name="TAnalyzer">The type of the analyzer to produce diagnostics.</typeparam>
|
||||
/// <typeparam name="TCodeFixer">The type of code fix to test.</typeparam>
|
||||
internal sealed class CSharpCodeFixTest<TAnalyzer, TCodeFixer> : CSharpCodeFixTest<TAnalyzer, TCodeFixer, DefaultVerifier>
|
||||
where TAnalyzer : DiagnosticAnalyzer, new()
|
||||
where TCodeFixer : CodeFixProvider, new()
|
||||
{
|
||||
/// <summary>
|
||||
/// The C# language version to use to parse code.
|
||||
/// </summary>
|
||||
private readonly LanguageVersion languageVersion;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="CSharpCodeFixTest{TAnalyzer, TCodeFix}"/> instance with the specified parameters.
|
||||
/// </summary>
|
||||
/// <param name="languageVersion">The C# language version to use to parse code.</param>
|
||||
public CSharpCodeFixTest(LanguageVersion languageVersion)
|
||||
{
|
||||
this.languageVersion = languageVersion;
|
||||
|
||||
TestState.AnalyzerConfigFiles.Add(("/.editorconfig", "[*]\nend_of_line = lf"));
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override ParseOptions CreateParseOptions()
|
||||
{
|
||||
return new CSharpParseOptions(this.languageVersion, DocumentationMode.Diagnose);
|
||||
}
|
||||
}
|
||||
@@ -1,584 +0,0 @@
|
||||
using ComputeSharp.D2D1.WinUI.SourceGenerators;
|
||||
using ComputeSharp.Tests.SourceGenerators.Helpers;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
namespace ComputeSharp.D2D1.WinUI.Tests.SourceGenerators;
|
||||
|
||||
[TestClass]
|
||||
public class Test_CanvasEffectPropertyGenerator
|
||||
{
|
||||
[TestMethod]
|
||||
public void SingleProperty()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyNamespace;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial int Number { get; set; }
|
||||
}
|
||||
""";
|
||||
|
||||
const string result = """"
|
||||
// <auto-generated/>
|
||||
#pragma warning disable
|
||||
|
||||
namespace MyNamespace
|
||||
{
|
||||
/// <inheritdoc cref="MyEffect"/>
|
||||
partial class MyEffect
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
[global::System.Diagnostics.DebuggerNonUserCode]
|
||||
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
public partial int Number
|
||||
{
|
||||
get => field;
|
||||
set
|
||||
{
|
||||
if (global::System.Collections.Generic.EqualityComparer<int>.Default.Equals(field, value))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int oldValue = field;
|
||||
|
||||
OnNumberChanging(value);
|
||||
OnNumberChanging(oldValue, value);
|
||||
|
||||
field = value;
|
||||
|
||||
OnNumberChanged(value);
|
||||
OnNumberChanged(oldValue, value);
|
||||
|
||||
InvalidateEffectGraph(global::ComputeSharp.D2D1.WinUI.CanvasEffectInvalidationType.Update);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="Number"/> is changing.</summary>
|
||||
/// <param name="value">The new property value being set.</param>
|
||||
/// <remarks>This method is invoked right before the value of <see cref="Number"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnNumberChanging(int newValue);
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="Number"/> is changing.</summary>
|
||||
/// <param name="oldValue">The previous property value that is being replaced.</param>
|
||||
/// <param name="newValue">The new property value being set.</param>
|
||||
/// <remarks>This method is invoked right before the value of <see cref="Number"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnNumberChanging(int oldValue, int newValue);
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="Number"/> has just changed.</summary>
|
||||
/// <param name="value">The new property value that has been set.</param>
|
||||
/// <remarks>This method is invoked right after the value of <see cref="Number"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnNumberChanged(int newValue);
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="Number"/> has just changed.</summary>
|
||||
/// <param name="oldValue">The previous property value that has been replaced.</param>
|
||||
/// <param name="newValue">The new property value that has been set.</param>
|
||||
/// <remarks>This method is invoked right after the value of <see cref="Number"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnNumberChanged(int oldValue, int newValue);
|
||||
}
|
||||
}
|
||||
"""";
|
||||
|
||||
VerifyGeneratedDiagnostics(source, ("MyNamespace.MyEffect.g.cs", result));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SingleProperty_WithNullabilityAnnotations()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyNamespace;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial object? Instance { get; set; }
|
||||
}
|
||||
""";
|
||||
|
||||
const string result = """"
|
||||
// <auto-generated/>
|
||||
#pragma warning disable
|
||||
|
||||
namespace MyNamespace
|
||||
{
|
||||
/// <inheritdoc cref="MyEffect"/>
|
||||
partial class MyEffect
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
[global::System.Diagnostics.DebuggerNonUserCode]
|
||||
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
public partial object? Instance
|
||||
{
|
||||
get => field;
|
||||
set
|
||||
{
|
||||
if (global::System.Collections.Generic.EqualityComparer<object?>.Default.Equals(field, value))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
object? oldValue = field;
|
||||
|
||||
OnInstanceChanging(value);
|
||||
OnInstanceChanging(oldValue, value);
|
||||
|
||||
field = value;
|
||||
|
||||
OnInstanceChanged(value);
|
||||
OnInstanceChanged(oldValue, value);
|
||||
|
||||
InvalidateEffectGraph(global::ComputeSharp.D2D1.WinUI.CanvasEffectInvalidationType.Update);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="Instance"/> is changing.</summary>
|
||||
/// <param name="value">The new property value being set.</param>
|
||||
/// <remarks>This method is invoked right before the value of <see cref="Instance"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnInstanceChanging(object? newValue);
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="Instance"/> is changing.</summary>
|
||||
/// <param name="oldValue">The previous property value that is being replaced.</param>
|
||||
/// <param name="newValue">The new property value being set.</param>
|
||||
/// <remarks>This method is invoked right before the value of <see cref="Instance"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnInstanceChanging(object? oldValue, object? newValue);
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="Instance"/> has just changed.</summary>
|
||||
/// <param name="value">The new property value that has been set.</param>
|
||||
/// <remarks>This method is invoked right after the value of <see cref="Instance"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnInstanceChanged(object? newValue);
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="Instance"/> has just changed.</summary>
|
||||
/// <param name="oldValue">The previous property value that has been replaced.</param>
|
||||
/// <param name="newValue">The new property value that has been set.</param>
|
||||
/// <remarks>This method is invoked right after the value of <see cref="Instance"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnInstanceChanged(object? oldValue, object? newValue);
|
||||
}
|
||||
}
|
||||
"""";
|
||||
|
||||
VerifyGeneratedDiagnostics(source, ("MyNamespace.MyEffect.g.cs", result));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SingleProperty_WithNotNullableReferenceType()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyNamespace;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial object Instance { get; set; }
|
||||
}
|
||||
""";
|
||||
|
||||
const string result = """"
|
||||
// <auto-generated/>
|
||||
#pragma warning disable
|
||||
|
||||
namespace MyNamespace
|
||||
{
|
||||
/// <inheritdoc cref="MyEffect"/>
|
||||
partial class MyEffect
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
[global::System.Diagnostics.DebuggerNonUserCode]
|
||||
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
public partial object Instance
|
||||
{
|
||||
get => field;
|
||||
set
|
||||
{
|
||||
if (global::System.Collections.Generic.EqualityComparer<object?>.Default.Equals(field, value))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
object? oldValue = field;
|
||||
|
||||
OnInstanceChanging(value);
|
||||
OnInstanceChanging(oldValue, value);
|
||||
|
||||
field = value;
|
||||
|
||||
OnInstanceChanged(value);
|
||||
OnInstanceChanged(oldValue, value);
|
||||
|
||||
InvalidateEffectGraph(global::ComputeSharp.D2D1.WinUI.CanvasEffectInvalidationType.Update);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="Instance"/> is changing.</summary>
|
||||
/// <param name="value">The new property value being set.</param>
|
||||
/// <remarks>This method is invoked right before the value of <see cref="Instance"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnInstanceChanging(object newValue);
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="Instance"/> is changing.</summary>
|
||||
/// <param name="oldValue">The previous property value that is being replaced.</param>
|
||||
/// <param name="newValue">The new property value being set.</param>
|
||||
/// <remarks>This method is invoked right before the value of <see cref="Instance"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnInstanceChanging(object? oldValue, object newValue);
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="Instance"/> has just changed.</summary>
|
||||
/// <param name="value">The new property value that has been set.</param>
|
||||
/// <remarks>This method is invoked right after the value of <see cref="Instance"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnInstanceChanged(object newValue);
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="Instance"/> has just changed.</summary>
|
||||
/// <param name="oldValue">The previous property value that has been replaced.</param>
|
||||
/// <param name="newValue">The new property value that has been set.</param>
|
||||
/// <remarks>This method is invoked right after the value of <see cref="Instance"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnInstanceChanged(object? oldValue, object newValue);
|
||||
}
|
||||
}
|
||||
"""";
|
||||
|
||||
VerifyGeneratedDiagnostics(source, ("MyNamespace.MyEffect.g.cs", result));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SingleProperty_WithCustomAccessorVisibility()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyNamespace;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial int Number { get; private set; }
|
||||
}
|
||||
""";
|
||||
|
||||
const string result = """"
|
||||
// <auto-generated/>
|
||||
#pragma warning disable
|
||||
|
||||
namespace MyNamespace
|
||||
{
|
||||
/// <inheritdoc cref="MyEffect"/>
|
||||
partial class MyEffect
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
[global::System.Diagnostics.DebuggerNonUserCode]
|
||||
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
public partial int Number
|
||||
{
|
||||
get => field;
|
||||
private set
|
||||
{
|
||||
if (global::System.Collections.Generic.EqualityComparer<int>.Default.Equals(field, value))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int oldValue = field;
|
||||
|
||||
OnNumberChanging(value);
|
||||
OnNumberChanging(oldValue, value);
|
||||
|
||||
field = value;
|
||||
|
||||
OnNumberChanged(value);
|
||||
OnNumberChanged(oldValue, value);
|
||||
|
||||
InvalidateEffectGraph(global::ComputeSharp.D2D1.WinUI.CanvasEffectInvalidationType.Update);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="Number"/> is changing.</summary>
|
||||
/// <param name="value">The new property value being set.</param>
|
||||
/// <remarks>This method is invoked right before the value of <see cref="Number"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnNumberChanging(int newValue);
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="Number"/> is changing.</summary>
|
||||
/// <param name="oldValue">The previous property value that is being replaced.</param>
|
||||
/// <param name="newValue">The new property value being set.</param>
|
||||
/// <remarks>This method is invoked right before the value of <see cref="Number"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnNumberChanging(int oldValue, int newValue);
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="Number"/> has just changed.</summary>
|
||||
/// <param name="value">The new property value that has been set.</param>
|
||||
/// <remarks>This method is invoked right after the value of <see cref="Number"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnNumberChanged(int newValue);
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="Number"/> has just changed.</summary>
|
||||
/// <param name="oldValue">The previous property value that has been replaced.</param>
|
||||
/// <param name="newValue">The new property value that has been set.</param>
|
||||
/// <remarks>This method is invoked right after the value of <see cref="Number"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnNumberChanged(int oldValue, int newValue);
|
||||
}
|
||||
}
|
||||
"""";
|
||||
|
||||
VerifyGeneratedDiagnostics(source, ("MyNamespace.MyEffect.g.cs", result));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SingleProperty_Required()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyNamespace;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public required partial int Number { get; set; }
|
||||
}
|
||||
""";
|
||||
|
||||
const string result = """"
|
||||
// <auto-generated/>
|
||||
#pragma warning disable
|
||||
|
||||
namespace MyNamespace
|
||||
{
|
||||
/// <inheritdoc cref="MyEffect"/>
|
||||
partial class MyEffect
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
[global::System.Diagnostics.DebuggerNonUserCode]
|
||||
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
public required partial int Number
|
||||
{
|
||||
get => field;
|
||||
set
|
||||
{
|
||||
if (global::System.Collections.Generic.EqualityComparer<int>.Default.Equals(field, value))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int oldValue = field;
|
||||
|
||||
OnNumberChanging(value);
|
||||
OnNumberChanging(oldValue, value);
|
||||
|
||||
field = value;
|
||||
|
||||
OnNumberChanged(value);
|
||||
OnNumberChanged(oldValue, value);
|
||||
|
||||
InvalidateEffectGraph(global::ComputeSharp.D2D1.WinUI.CanvasEffectInvalidationType.Update);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="Number"/> is changing.</summary>
|
||||
/// <param name="value">The new property value being set.</param>
|
||||
/// <remarks>This method is invoked right before the value of <see cref="Number"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnNumberChanging(int newValue);
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="Number"/> is changing.</summary>
|
||||
/// <param name="oldValue">The previous property value that is being replaced.</param>
|
||||
/// <param name="newValue">The new property value being set.</param>
|
||||
/// <remarks>This method is invoked right before the value of <see cref="Number"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnNumberChanging(int oldValue, int newValue);
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="Number"/> has just changed.</summary>
|
||||
/// <param name="value">The new property value that has been set.</param>
|
||||
/// <remarks>This method is invoked right after the value of <see cref="Number"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnNumberChanged(int newValue);
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="Number"/> has just changed.</summary>
|
||||
/// <param name="oldValue">The previous property value that has been replaced.</param>
|
||||
/// <param name="newValue">The new property value that has been set.</param>
|
||||
/// <remarks>This method is invoked right after the value of <see cref="Number"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnNumberChanged(int oldValue, int newValue);
|
||||
}
|
||||
}
|
||||
"""";
|
||||
|
||||
VerifyGeneratedDiagnostics(source, ("MyNamespace.MyEffect.g.cs", result));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void MultipleProperties()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyNamespace;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial int X { get; set; }
|
||||
|
||||
[GeneratedCanvasEffectProperty(CanvasEffectInvalidationType.Creation)]
|
||||
public partial int Y { get; set; }
|
||||
}
|
||||
""";
|
||||
|
||||
const string result = """"
|
||||
// <auto-generated/>
|
||||
#pragma warning disable
|
||||
|
||||
namespace MyNamespace
|
||||
{
|
||||
/// <inheritdoc cref="MyEffect"/>
|
||||
partial class MyEffect
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
[global::System.Diagnostics.DebuggerNonUserCode]
|
||||
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
public partial int X
|
||||
{
|
||||
get => field;
|
||||
set
|
||||
{
|
||||
if (global::System.Collections.Generic.EqualityComparer<int>.Default.Equals(field, value))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int oldValue = field;
|
||||
|
||||
OnXChanging(value);
|
||||
OnXChanging(oldValue, value);
|
||||
|
||||
field = value;
|
||||
|
||||
OnXChanged(value);
|
||||
OnXChanged(oldValue, value);
|
||||
|
||||
InvalidateEffectGraph(global::ComputeSharp.D2D1.WinUI.CanvasEffectInvalidationType.Update);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
[global::System.Diagnostics.DebuggerNonUserCode]
|
||||
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
public partial int Y
|
||||
{
|
||||
get => field;
|
||||
set
|
||||
{
|
||||
if (global::System.Collections.Generic.EqualityComparer<int>.Default.Equals(field, value))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int oldValue = field;
|
||||
|
||||
OnYChanging(value);
|
||||
OnYChanging(oldValue, value);
|
||||
|
||||
field = value;
|
||||
|
||||
OnYChanged(value);
|
||||
OnYChanged(oldValue, value);
|
||||
|
||||
InvalidateEffectGraph(global::ComputeSharp.D2D1.WinUI.CanvasEffectInvalidationType.Creation);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="X"/> is changing.</summary>
|
||||
/// <param name="value">The new property value being set.</param>
|
||||
/// <remarks>This method is invoked right before the value of <see cref="X"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnXChanging(int newValue);
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="X"/> is changing.</summary>
|
||||
/// <param name="oldValue">The previous property value that is being replaced.</param>
|
||||
/// <param name="newValue">The new property value being set.</param>
|
||||
/// <remarks>This method is invoked right before the value of <see cref="X"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnXChanging(int oldValue, int newValue);
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="X"/> has just changed.</summary>
|
||||
/// <param name="value">The new property value that has been set.</param>
|
||||
/// <remarks>This method is invoked right after the value of <see cref="X"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnXChanged(int newValue);
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="X"/> has just changed.</summary>
|
||||
/// <param name="oldValue">The previous property value that has been replaced.</param>
|
||||
/// <param name="newValue">The new property value that has been set.</param>
|
||||
/// <remarks>This method is invoked right after the value of <see cref="X"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnXChanged(int oldValue, int newValue);
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="Y"/> is changing.</summary>
|
||||
/// <param name="value">The new property value being set.</param>
|
||||
/// <remarks>This method is invoked right before the value of <see cref="Y"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnYChanging(int newValue);
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="Y"/> is changing.</summary>
|
||||
/// <param name="oldValue">The previous property value that is being replaced.</param>
|
||||
/// <param name="newValue">The new property value being set.</param>
|
||||
/// <remarks>This method is invoked right before the value of <see cref="Y"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnYChanging(int oldValue, int newValue);
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="Y"/> has just changed.</summary>
|
||||
/// <param name="value">The new property value that has been set.</param>
|
||||
/// <remarks>This method is invoked right after the value of <see cref="Y"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnYChanged(int newValue);
|
||||
|
||||
/// <summary>Executes the logic for when <see cref="Y"/> has just changed.</summary>
|
||||
/// <param name="oldValue">The previous property value that has been replaced.</param>
|
||||
/// <param name="newValue">The new property value that has been set.</param>
|
||||
/// <remarks>This method is invoked right after the value of <see cref="Y"/> is changed.</remarks>
|
||||
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
|
||||
partial void OnYChanged(int oldValue, int newValue);
|
||||
}
|
||||
}
|
||||
"""";
|
||||
|
||||
VerifyGeneratedDiagnostics(source, ("MyNamespace.MyEffect.g.cs", result));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies the output of a source generator.
|
||||
/// </summary>
|
||||
/// <param name="source">The input source to process.</param>
|
||||
/// <param name="result">The expected source to be generated.</param>
|
||||
/// <returns>The task for the operation.</returns>
|
||||
private static void VerifyGeneratedDiagnostics(string source, (string Filename, string Source) result)
|
||||
{
|
||||
// We cannot run the analyzers on the input source, because they'd report unwanted dsiagnostics due to the
|
||||
// partial properties missing an implementation part. For this generator, we just test analyzers individually.
|
||||
CSharpGeneratorTest<CanvasEffectPropertyGenerator>.VerifySources(source, result, languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
}
|
||||
@@ -1,457 +0,0 @@
|
||||
using System.Threading.Tasks;
|
||||
using ComputeSharp.D2D1.WinUI.SourceGenerators;
|
||||
using ComputeSharp.Tests.SourceGenerators.Helpers;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
namespace ComputeSharp.D2D1.WinUI.Tests.SourceGenerators;
|
||||
|
||||
[TestClass]
|
||||
public class Test_CanvasEffectPropertyGenerator_Analyzers
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer_NoBaseType_Warns()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
public partial class MyEffect
|
||||
{
|
||||
[{|CMPSD2DWINUI0001:GeneratedCanvasEffectProperty|}]
|
||||
public partial int {|CS9248:Number|} { get; set; }
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer>.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer_ReadOnlyProperty_Warns()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
public partial class MyEffect
|
||||
{
|
||||
[{|CMPSD2DWINUI0002:GeneratedCanvasEffectProperty|}]
|
||||
public partial int {|CS9248:Number|} { get; }
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer>.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer_InitOnlyProperty_Warns()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[{|CMPSD2DWINUI0002:GeneratedCanvasEffectProperty|}]
|
||||
public partial int {|CS9248:Number|} { get; init; }
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer>.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer_StaticProperty_Warns()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[{|CMPSD2DWINUI0003:GeneratedCanvasEffectProperty|}]
|
||||
public static partial int {|CS9248:Number|} { get; set; }
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer>.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer_NotPartialProperty_Warns()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[{|CMPSD2DWINUI0004:GeneratedCanvasEffectProperty|}]
|
||||
public int Number { get; set; }
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer>.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer_PartialPropertyWithImplementation_Warns()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[{|CMPSD2DWINUI0004:GeneratedCanvasEffectProperty|}]
|
||||
public partial int Number { get; set; }
|
||||
|
||||
public partial int Number { get => 42; set { } }
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer>.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer_PartialPropertyWithImplementation_GeneratedByGenerator_DoesNotWarn()
|
||||
{
|
||||
const string source = """
|
||||
using System.CodeDom.Compiler;
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial int Number { get; set; }
|
||||
|
||||
[GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "1.0.0")]
|
||||
public partial int Number { get => 42; set { } }
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer>.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer_PartialPropertyImplementationPart_Warns()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
public partial int Number { get; set; }
|
||||
|
||||
[{|CMPSD2DWINUI0004:GeneratedCanvasEffectProperty|}]
|
||||
public partial int Number { get => 42; set { } }
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer>.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer_ReturnsByRef_Warns()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[{|CMPSD2DWINUI0005:GeneratedCanvasEffectProperty|}]
|
||||
public partial ref int {|CS9248:Number|} { get; {|CS8147:set|}; }
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer>.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer_ReturnsByRefReadonly_Warns()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[{|CMPSD2DWINUI0005:GeneratedCanvasEffectProperty|}]
|
||||
public partial ref readonly int {|CS9248:Number|} { get; {|CS8147:set|}; }
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer>.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer_ReturnsRefStructType_Warns()
|
||||
{
|
||||
const string source = """
|
||||
using System;
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[{|CMPSD2DWINUI0006:GeneratedCanvasEffectProperty|}]
|
||||
public partial Span<int> {|CS9248:Number|} { get; set; }
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer>.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task RequireCSharpLanguageVersionPreviewAnalyzer_LanguageVersionIsNotPreview_Warns()
|
||||
{
|
||||
const string source = """
|
||||
using System;
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[{|CMPSD2DWINUI0007:GeneratedCanvasEffectProperty|}]
|
||||
public int Number { get; set; }
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<RequireCSharpLanguageVersionPreviewAnalyzer>.VerifyAnalyzerAsync(source);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task RequireCSharpLanguageVersionPreviewAnalyzer_LanguageVersionIsPreview_DoesNotWarn()
|
||||
{
|
||||
const string source = """
|
||||
using System;
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public int Number { get; set; }
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<RequireCSharpLanguageVersionPreviewAnalyzer>.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer_NormalProperty_DoesNotWarn()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
public abstract partial class SampleCanvasEffect : CanvasEffect
|
||||
{
|
||||
public string Name { get; set; }
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer>.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer_SimilarProperty_NotObservableObject_DoesNotWarn()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
public abstract partial class SampleCanvasEffect : MyBaseCanvasEffect
|
||||
{
|
||||
public string Name
|
||||
{
|
||||
get => field;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
}
|
||||
|
||||
public abstract class MyBaseCanvasEffect
|
||||
{
|
||||
protected void SetPropertyAndInvalidateEffectGraph<T>(ref T location, T value, CanvasEffectInvalidationType invalidationType = CanvasEffectInvalidationType.Update)
|
||||
{
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer>.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer_NoGetter_DoesNotWarn()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
public abstract partial class SampleCanvasEffect : CanvasEffect
|
||||
{
|
||||
public string Name
|
||||
{
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer>.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer_NoSetter_DoesNotWarn()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
public abstract partial class SampleCanvasEffect : CanvasEffect
|
||||
{
|
||||
public string Name
|
||||
{
|
||||
get => field;
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer>.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer_OtherLocation_DoesNotWarn()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
public abstract partial class SampleCanvasEffect : CanvasEffect
|
||||
{
|
||||
public string Name
|
||||
{
|
||||
get => field;
|
||||
set
|
||||
{
|
||||
string test = field;
|
||||
|
||||
SetPropertyAndInvalidateEffectGraph(ref test, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer>.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer_OtherValue_DoesNotWarn()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
public abstract partial class SampleCanvasEffect : CanvasEffect
|
||||
{
|
||||
public string Name
|
||||
{
|
||||
get => field;
|
||||
set
|
||||
{
|
||||
string test = "Bob";
|
||||
|
||||
SetPropertyAndInvalidateEffectGraph(ref field, test);
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer>.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer_ValidProperty_WithGeneratedCanvasEffectProperty_DoesNotWarn()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
public abstract partial class SampleCanvasEffect : CanvasEffect
|
||||
{
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public string Name
|
||||
{
|
||||
get => field;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer>.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer_GetAccessorWithExpressionBody_DoesNotWarn()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
public abstract partial class SampleCanvasEffect : CanvasEffect
|
||||
{
|
||||
public string Name
|
||||
{
|
||||
get => "Hello world";
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer>.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer_ValidProperty_Warns()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
public abstract partial class SampleCanvasEffect : CanvasEffect
|
||||
{
|
||||
public string {|CMPSD2DWINUI0008:Name|}
|
||||
{
|
||||
get => field;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer>.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer_ValidProperty_WithModifiers_Warns()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
public abstract partial class SampleCanvasEffect : CanvasEffect
|
||||
{
|
||||
public new string {|CMPSD2DWINUI0008:Name|}
|
||||
{
|
||||
get => field;
|
||||
private set => SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer>.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer_ValidProperty_WithBlocks_Warns()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
public abstract partial class SampleCanvasEffect : CanvasEffect
|
||||
{
|
||||
public new string {|CMPSD2DWINUI0008:Name|}
|
||||
{
|
||||
get
|
||||
{
|
||||
return field;
|
||||
}
|
||||
private set
|
||||
{
|
||||
SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
await CSharpAnalyzerTest<UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer>.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
using ComputeSharp.D2D1.WinUI.SourceGenerators;
|
||||
using ComputeSharp.Tests.SourceGenerators.Helpers;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
namespace ComputeSharp.D2D1.WinUI.Tests.SourceGenerators;
|
||||
|
||||
[TestClass]
|
||||
public class Test_CanvasEffectPropertyGenerator_Incrementality
|
||||
{
|
||||
[TestMethod]
|
||||
public void ModifiedOptions_ModifiesOutput()
|
||||
{
|
||||
const string source = """"
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial int Number { get; set; }
|
||||
}
|
||||
"""";
|
||||
|
||||
const string updatedSource = """"
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[GeneratedCanvasEffectProperty(CanvasEffectInvalidationType.Creation)]
|
||||
public partial int Number { get; set; }
|
||||
}
|
||||
"""";
|
||||
|
||||
CSharpGeneratorTest<CanvasEffectPropertyGenerator>.VerifyIncrementalSteps(
|
||||
source,
|
||||
updatedSource,
|
||||
executeReason: IncrementalStepRunReason.Modified,
|
||||
diagnosticsReason: null,
|
||||
outputReason: IncrementalStepRunReason.Modified,
|
||||
diagnosticsSourceReason: null,
|
||||
sourceReason: IncrementalStepRunReason.Modified,
|
||||
languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AddedLeadingTrivia_DoesNotModifyOutput()
|
||||
{
|
||||
const string source = """"
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial int Number { get; set; }
|
||||
}
|
||||
"""";
|
||||
|
||||
const string updatedSource = """"
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
/// <summary>
|
||||
/// This is some property.
|
||||
/// </summary>
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial int Number { get; set; }
|
||||
}
|
||||
"""";
|
||||
|
||||
CSharpGeneratorTest<CanvasEffectPropertyGenerator>.VerifyIncrementalSteps(
|
||||
source,
|
||||
updatedSource,
|
||||
executeReason: IncrementalStepRunReason.Unchanged,
|
||||
diagnosticsReason: null,
|
||||
outputReason: IncrementalStepRunReason.Cached,
|
||||
diagnosticsSourceReason: null,
|
||||
sourceReason: IncrementalStepRunReason.Cached,
|
||||
languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AddedOtherMember_DoesNotModifyOutput()
|
||||
{
|
||||
const string source = """"
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial int Number { get; set; }
|
||||
}
|
||||
"""";
|
||||
|
||||
const string updatedSource = """"
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
public void Foo()
|
||||
{
|
||||
}
|
||||
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial int Number { get; set; }
|
||||
}
|
||||
"""";
|
||||
|
||||
CSharpGeneratorTest<CanvasEffectPropertyGenerator>.VerifyIncrementalSteps(
|
||||
source,
|
||||
updatedSource,
|
||||
executeReason: IncrementalStepRunReason.Unchanged,
|
||||
diagnosticsReason: null,
|
||||
outputReason: IncrementalStepRunReason.Cached,
|
||||
diagnosticsSourceReason: null,
|
||||
sourceReason: IncrementalStepRunReason.Cached,
|
||||
languageVersion: LanguageVersion.Preview);
|
||||
}
|
||||
}
|
||||
@@ -1,767 +0,0 @@
|
||||
extern alias Core;
|
||||
extern alias D2D1_WinUI;
|
||||
extern alias D2D1;
|
||||
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.Testing;
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using Windows.Foundation;
|
||||
using Windows.UI.ViewManagement;
|
||||
using CSharpCodeFixTest = ComputeSharp.Tests.SourceGenerators.Helpers.CSharpCodeFixTest<
|
||||
ComputeSharp.D2D1.WinUI.SourceGenerators.UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer,
|
||||
ComputeSharp.D2D1.WinUI.SourceGenerators.UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyCodeFixer>;
|
||||
|
||||
namespace ComputeSharp.D2D1.WinUI.Tests.SourceGenerators;
|
||||
|
||||
[TestClass]
|
||||
public class Test_UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyCodeFixer
|
||||
{
|
||||
[TestMethod]
|
||||
[DataRow("get;")]
|
||||
[DataRow("get => field;")]
|
||||
public async Task SimpleProperty_ImplicitInvalidationType(string getAccessor)
|
||||
{
|
||||
string original = $$"""
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyApp;
|
||||
|
||||
public abstract class MyEffect : CanvasEffect
|
||||
{
|
||||
public string? [|Name|]
|
||||
{
|
||||
{{getAccessor}}
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
const string @fixed = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyApp;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial string? {|CS9248:Name|} { get; set; }
|
||||
}
|
||||
""";
|
||||
|
||||
CSharpCodeFixTest test = new(LanguageVersion.Preview)
|
||||
{
|
||||
TestCode = original,
|
||||
FixedCode = @fixed,
|
||||
ReferenceAssemblies = ReferenceAssemblies.Net.Net80,
|
||||
TestState = { AdditionalReferences =
|
||||
{
|
||||
MetadataReference.CreateFromFile(typeof(Point).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(ApplicationView).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(Button).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(D2D1_WinUI::ComputeSharp.D2D1.WinUI.CanvasEffect).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(D2D1::ComputeSharp.D2D1.ID2D1PixelShader).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(Core::ComputeSharp.Float4).Assembly.Location)
|
||||
} }
|
||||
};
|
||||
|
||||
await test.RunAsync();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("get;")]
|
||||
[DataRow("get => field;")]
|
||||
public async Task SimpleProperty_InvalidationTypeUpdate(string getAccessor)
|
||||
{
|
||||
string original = $$"""
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyApp;
|
||||
|
||||
public abstract class MyEffect : CanvasEffect
|
||||
{
|
||||
public string? [|Name|]
|
||||
{
|
||||
{{getAccessor}}
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value, CanvasEffectInvalidationType.Update);
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
const string @fixed = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyApp;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial string? {|CS9248:Name|} { get; set; }
|
||||
}
|
||||
""";
|
||||
|
||||
CSharpCodeFixTest test = new(LanguageVersion.Preview)
|
||||
{
|
||||
TestCode = original,
|
||||
FixedCode = @fixed,
|
||||
ReferenceAssemblies = ReferenceAssemblies.Net.Net80,
|
||||
TestState = { AdditionalReferences =
|
||||
{
|
||||
MetadataReference.CreateFromFile(typeof(Point).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(ApplicationView).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(Button).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(D2D1_WinUI::ComputeSharp.D2D1.WinUI.CanvasEffect).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(D2D1::ComputeSharp.D2D1.ID2D1PixelShader).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(Core::ComputeSharp.Float4).Assembly.Location)
|
||||
} }
|
||||
};
|
||||
|
||||
await test.RunAsync();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("get;")]
|
||||
[DataRow("get => field;")]
|
||||
public async Task SimpleProperty_InvalidationTypeCreation(string getAccessor)
|
||||
{
|
||||
string original = $$"""
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyApp;
|
||||
|
||||
public abstract class MyEffect : CanvasEffect
|
||||
{
|
||||
public string? [|Name|]
|
||||
{
|
||||
{{getAccessor}}
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value, CanvasEffectInvalidationType.Creation);
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
const string @fixed = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyApp;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[GeneratedCanvasEffectProperty(CanvasEffectInvalidationType.Creation)]
|
||||
public partial string? {|CS9248:Name|} { get; set; }
|
||||
}
|
||||
""";
|
||||
|
||||
CSharpCodeFixTest test = new(LanguageVersion.Preview)
|
||||
{
|
||||
TestCode = original,
|
||||
FixedCode = @fixed,
|
||||
ReferenceAssemblies = ReferenceAssemblies.Net.Net80,
|
||||
TestState = { AdditionalReferences =
|
||||
{
|
||||
MetadataReference.CreateFromFile(typeof(Point).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(ApplicationView).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(Button).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(D2D1_WinUI::ComputeSharp.D2D1.WinUI.CanvasEffect).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(D2D1::ComputeSharp.D2D1.ID2D1PixelShader).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(Core::ComputeSharp.Float4).Assembly.Location)
|
||||
} }
|
||||
};
|
||||
|
||||
await test.RunAsync();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SimpleProperty_WithMissingUsingDirective()
|
||||
{
|
||||
const string original = """
|
||||
namespace MyApp;
|
||||
|
||||
public abstract class MyEffect : ComputeSharp.D2D1.WinUI.CanvasEffect
|
||||
{
|
||||
public string? [|Name|]
|
||||
{
|
||||
get;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
const string @fixed = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyApp;
|
||||
|
||||
public abstract partial class MyEffect : ComputeSharp.D2D1.WinUI.CanvasEffect
|
||||
{
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial string? {|CS9248:Name|} { get; set; }
|
||||
}
|
||||
""";
|
||||
|
||||
CSharpCodeFixTest test = new(LanguageVersion.Preview)
|
||||
{
|
||||
TestCode = original,
|
||||
FixedCode = @fixed,
|
||||
ReferenceAssemblies = ReferenceAssemblies.Net.Net80,
|
||||
TestState = { AdditionalReferences =
|
||||
{
|
||||
MetadataReference.CreateFromFile(typeof(Point).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(ApplicationView).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(Button).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(D2D1_WinUI::ComputeSharp.D2D1.WinUI.CanvasEffect).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(D2D1::ComputeSharp.D2D1.ID2D1PixelShader).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(Core::ComputeSharp.Float4).Assembly.Location)
|
||||
} }
|
||||
};
|
||||
|
||||
await test.RunAsync();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SimpleProperty_WithLeadingTrivia()
|
||||
{
|
||||
const string original = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyApp;
|
||||
|
||||
public abstract class MyEffect : CanvasEffect
|
||||
{
|
||||
/// <summary>
|
||||
/// This is a property.
|
||||
/// </summary>
|
||||
public string? [|Name|]
|
||||
{
|
||||
get;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
const string @fixed = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyApp;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
/// <summary>
|
||||
/// This is a property.
|
||||
/// </summary>
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial string? {|CS9248:Name|} { get; set; }
|
||||
}
|
||||
""";
|
||||
|
||||
CSharpCodeFixTest test = new(LanguageVersion.Preview)
|
||||
{
|
||||
TestCode = original,
|
||||
FixedCode = @fixed,
|
||||
ReferenceAssemblies = ReferenceAssemblies.Net.Net80,
|
||||
TestState = { AdditionalReferences =
|
||||
{
|
||||
MetadataReference.CreateFromFile(typeof(Point).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(ApplicationView).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(Button).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(D2D1_WinUI::ComputeSharp.D2D1.WinUI.CanvasEffect).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(D2D1::ComputeSharp.D2D1.ID2D1PixelShader).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(Core::ComputeSharp.Float4).Assembly.Location)
|
||||
} }
|
||||
};
|
||||
|
||||
await test.RunAsync();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SimpleProperty_WithLeadingTrivia_AndAttribute()
|
||||
{
|
||||
const string original = """
|
||||
using System;
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyApp;
|
||||
|
||||
public abstract class MyEffect : CanvasEffect
|
||||
{
|
||||
/// <summary>
|
||||
/// This is a property.
|
||||
/// </summary>
|
||||
[Test("Targeting property")]
|
||||
[field: Test("Targeting field")]
|
||||
public string? [|Name|]
|
||||
{
|
||||
get;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
}
|
||||
|
||||
public class TestAttribute(string text) : Attribute;
|
||||
""";
|
||||
|
||||
const string @fixed = """
|
||||
using System;
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyApp;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
/// <summary>
|
||||
/// This is a property.
|
||||
/// </summary>
|
||||
[GeneratedCanvasEffectProperty]
|
||||
[Test("Targeting property")]
|
||||
[field: Test("Targeting field")]
|
||||
public partial string? {|CS9248:Name|} { get; set; }
|
||||
}
|
||||
|
||||
public class TestAttribute(string text) : Attribute;
|
||||
""";
|
||||
|
||||
CSharpCodeFixTest test = new(LanguageVersion.Preview)
|
||||
{
|
||||
TestCode = original,
|
||||
FixedCode = @fixed,
|
||||
ReferenceAssemblies = ReferenceAssemblies.Net.Net80,
|
||||
TestState = { AdditionalReferences =
|
||||
{
|
||||
MetadataReference.CreateFromFile(typeof(Point).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(ApplicationView).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(Button).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(D2D1_WinUI::ComputeSharp.D2D1.WinUI.CanvasEffect).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(D2D1::ComputeSharp.D2D1.ID2D1PixelShader).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(Core::ComputeSharp.Float4).Assembly.Location)
|
||||
} }
|
||||
};
|
||||
|
||||
await test.RunAsync();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SimpleProperty_Multiple()
|
||||
{
|
||||
const string original = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyApp;
|
||||
|
||||
public abstract class MyEffect : CanvasEffect
|
||||
{
|
||||
public string? [|FirstName|]
|
||||
{
|
||||
get;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
|
||||
public string? [|LastName|]
|
||||
{
|
||||
get;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
const string @fixed = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyApp;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial string? {|CS9248:FirstName|} { get; set; }
|
||||
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial string? {|CS9248:LastName|} { get; set; }
|
||||
}
|
||||
""";
|
||||
|
||||
CSharpCodeFixTest test = new(LanguageVersion.Preview)
|
||||
{
|
||||
TestCode = original,
|
||||
FixedCode = @fixed,
|
||||
ReferenceAssemblies = ReferenceAssemblies.Net.Net80,
|
||||
TestState = { AdditionalReferences =
|
||||
{
|
||||
MetadataReference.CreateFromFile(typeof(Point).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(ApplicationView).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(Button).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(D2D1_WinUI::ComputeSharp.D2D1.WinUI.CanvasEffect).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(D2D1::ComputeSharp.D2D1.ID2D1PixelShader).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(Core::ComputeSharp.Float4).Assembly.Location)
|
||||
} }
|
||||
};
|
||||
|
||||
await test.RunAsync();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SimpleProperty_Multiple_OnlyTriggersOnFirstOne()
|
||||
{
|
||||
const string original = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyApp;
|
||||
|
||||
public abstract class MyEffect : CanvasEffect
|
||||
{
|
||||
public string? [|FirstName|]
|
||||
{
|
||||
get;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
|
||||
private string? lastName;
|
||||
|
||||
public string? LastName
|
||||
{
|
||||
get => this.lastName;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref this.lastName, value);
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
const string @fixed = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyApp;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial string? {|CS9248:FirstName|} { get; set; }
|
||||
|
||||
private string? lastName;
|
||||
|
||||
public string? LastName
|
||||
{
|
||||
get => this.lastName;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref this.lastName, value);
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
CSharpCodeFixTest test = new(LanguageVersion.Preview)
|
||||
{
|
||||
TestCode = original,
|
||||
FixedCode = @fixed,
|
||||
ReferenceAssemblies = ReferenceAssemblies.Net.Net80,
|
||||
TestState = { AdditionalReferences =
|
||||
{
|
||||
MetadataReference.CreateFromFile(typeof(Point).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(ApplicationView).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(Button).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(D2D1_WinUI::ComputeSharp.D2D1.WinUI.CanvasEffect).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(D2D1::ComputeSharp.D2D1.ID2D1PixelShader).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(Core::ComputeSharp.Float4).Assembly.Location)
|
||||
} }
|
||||
};
|
||||
|
||||
await test.RunAsync();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SimpleProperty_Multiple_OnlyTriggersOnSecondOne()
|
||||
{
|
||||
const string original = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyApp;
|
||||
|
||||
public abstract class MyEffect : CanvasEffect
|
||||
{
|
||||
private string? firstName;
|
||||
|
||||
public string? FirstName
|
||||
{
|
||||
get => this.firstName;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref this.firstName, value);
|
||||
}
|
||||
|
||||
public string? [|LastName|]
|
||||
{
|
||||
get;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
const string @fixed = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyApp;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
private string? firstName;
|
||||
|
||||
public string? FirstName
|
||||
{
|
||||
get => this.firstName;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref this.firstName, value);
|
||||
}
|
||||
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial string? {|CS9248:LastName|} { get; set; }
|
||||
}
|
||||
""";
|
||||
|
||||
CSharpCodeFixTest test = new(LanguageVersion.Preview)
|
||||
{
|
||||
TestCode = original,
|
||||
FixedCode = @fixed,
|
||||
ReferenceAssemblies = ReferenceAssemblies.Net.Net80,
|
||||
TestState = { AdditionalReferences =
|
||||
{
|
||||
MetadataReference.CreateFromFile(typeof(Point).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(ApplicationView).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(Button).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(D2D1_WinUI::ComputeSharp.D2D1.WinUI.CanvasEffect).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(D2D1::ComputeSharp.D2D1.ID2D1PixelShader).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(Core::ComputeSharp.Float4).Assembly.Location)
|
||||
} }
|
||||
};
|
||||
|
||||
await test.RunAsync();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SimpleProperty_WithinPartialType()
|
||||
{
|
||||
const string original = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyApp;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
public string? [|Name|]
|
||||
{
|
||||
get;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
const string @fixed = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyApp;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial string? {|CS9248:Name|} { get; set; }
|
||||
}
|
||||
""";
|
||||
|
||||
CSharpCodeFixTest test = new(LanguageVersion.Preview)
|
||||
{
|
||||
TestCode = original,
|
||||
FixedCode = @fixed,
|
||||
ReferenceAssemblies = ReferenceAssemblies.Net.Net80,
|
||||
TestState = { AdditionalReferences =
|
||||
{
|
||||
MetadataReference.CreateFromFile(typeof(Point).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(ApplicationView).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(Button).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(D2D1_WinUI::ComputeSharp.D2D1.WinUI.CanvasEffect).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(D2D1::ComputeSharp.D2D1.ID2D1PixelShader).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(Core::ComputeSharp.Float4).Assembly.Location)
|
||||
} }
|
||||
};
|
||||
|
||||
await test.RunAsync();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SimpleProperty_WithMissingUsingDirective_Multiple()
|
||||
{
|
||||
const string original = """
|
||||
namespace MyApp;
|
||||
|
||||
public abstract class MyEffect : ComputeSharp.D2D1.WinUI.CanvasEffect
|
||||
{
|
||||
public string? [|FirstName|]
|
||||
{
|
||||
get;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
|
||||
public string? [|LastName|]
|
||||
{
|
||||
get;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
const string @fixed = """
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyApp;
|
||||
|
||||
public abstract partial class MyEffect : ComputeSharp.D2D1.WinUI.CanvasEffect
|
||||
{
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial string? {|CS9248:FirstName|} { get; set; }
|
||||
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial string? {|CS9248:LastName|} { get; set; }
|
||||
}
|
||||
""";
|
||||
|
||||
CSharpCodeFixTest test = new(LanguageVersion.Preview)
|
||||
{
|
||||
TestCode = original,
|
||||
FixedCode = @fixed,
|
||||
ReferenceAssemblies = ReferenceAssemblies.Net.Net80,
|
||||
TestState = { AdditionalReferences =
|
||||
{
|
||||
MetadataReference.CreateFromFile(typeof(Point).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(ApplicationView).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(Button).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(D2D1_WinUI::ComputeSharp.D2D1.WinUI.CanvasEffect).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(D2D1::ComputeSharp.D2D1.ID2D1PixelShader).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(Core::ComputeSharp.Float4).Assembly.Location)
|
||||
} }
|
||||
};
|
||||
|
||||
await test.RunAsync();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SimpleProperty_Multiple_MixedScenario()
|
||||
{
|
||||
const string original = """
|
||||
using System;
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyApp;
|
||||
|
||||
public abstract class MyEffect : CanvasEffect
|
||||
{
|
||||
[Test("This is an attribute")]
|
||||
public string [|Prop1|]
|
||||
{
|
||||
get => field;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
|
||||
// Single comment
|
||||
public string [|Prop2|]
|
||||
{
|
||||
get => field;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is a property.
|
||||
/// </summary>
|
||||
public string [|Prop3|]
|
||||
{
|
||||
get => field;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is another property.
|
||||
/// </summary>
|
||||
[Test("Another attribute")]
|
||||
public string [|Prop4|]
|
||||
{
|
||||
get => field;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
|
||||
// Some other single comment
|
||||
[Test("Yet another attribute")]
|
||||
public string [|Prop5|]
|
||||
{
|
||||
get => field;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
|
||||
[Test("Attribute without trivia")]
|
||||
public string [|Prop6|]
|
||||
{
|
||||
get => field;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
|
||||
public string [|Prop7|]
|
||||
{
|
||||
get => field;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref field, value);
|
||||
}
|
||||
}
|
||||
|
||||
public class TestAttribute(string text) : Attribute;
|
||||
""";
|
||||
|
||||
const string @fixed = """
|
||||
using System;
|
||||
using ComputeSharp.D2D1.WinUI;
|
||||
|
||||
namespace MyApp;
|
||||
|
||||
public abstract partial class MyEffect : CanvasEffect
|
||||
{
|
||||
[GeneratedCanvasEffectProperty]
|
||||
[Test("This is an attribute")]
|
||||
public partial string {|CS9248:Prop1|} { get; set; }
|
||||
|
||||
// Single comment
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial string {|CS9248:Prop2|} { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// This is a property.
|
||||
/// </summary>
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial string {|CS9248:Prop3|} { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// This is another property.
|
||||
/// </summary>
|
||||
[GeneratedCanvasEffectProperty]
|
||||
[Test("Another attribute")]
|
||||
public partial string {|CS9248:Prop4|} { get; set; }
|
||||
|
||||
// Some other single comment
|
||||
[GeneratedCanvasEffectProperty]
|
||||
[Test("Yet another attribute")]
|
||||
public partial string {|CS9248:Prop5|} { get; set; }
|
||||
|
||||
[GeneratedCanvasEffectProperty]
|
||||
[Test("Attribute without trivia")]
|
||||
public partial string {|CS9248:Prop6|} { get; set; }
|
||||
|
||||
[GeneratedCanvasEffectProperty]
|
||||
public partial string {|CS9248:Prop7|} { get; set; }
|
||||
}
|
||||
|
||||
public class TestAttribute(string text) : Attribute;
|
||||
""";
|
||||
|
||||
CSharpCodeFixTest test = new(LanguageVersion.Preview)
|
||||
{
|
||||
TestCode = original,
|
||||
FixedCode = @fixed,
|
||||
ReferenceAssemblies = ReferenceAssemblies.Net.Net80,
|
||||
TestState = { AdditionalReferences =
|
||||
{
|
||||
MetadataReference.CreateFromFile(typeof(Point).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(ApplicationView).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(Button).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(D2D1_WinUI::ComputeSharp.D2D1.WinUI.CanvasEffect).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(D2D1::ComputeSharp.D2D1.ID2D1PixelShader).Assembly.Location),
|
||||
MetadataReference.CreateFromFile(typeof(Core::ComputeSharp.Float4).Assembly.Location)
|
||||
} }
|
||||
};
|
||||
|
||||
await test.RunAsync();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
<Application
|
||||
x:Class="ComputeSharp.D2D1.WinUI.Tests.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" />
|
||||
@@ -1,25 +0,0 @@
|
||||
using System;
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.VisualStudio.TestPlatform.TestExecutor;
|
||||
|
||||
namespace ComputeSharp.D2D1.WinUI.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Provides application-specific behavior to supplement the default Application class.
|
||||
/// </summary>
|
||||
public partial class App : Application
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="App"/> instance.
|
||||
/// </summary>
|
||||
public App()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override void OnLaunched(LaunchActivatedEventArgs args)
|
||||
{
|
||||
UnitTestClient.Run(Environment.CommandLine);
|
||||
}
|
||||
}
|
||||
|
変更前 幅: | 高さ: | サイズ: 432 B |
|
変更前 幅: | 高さ: | サイズ: 5.2 KiB |
|
変更前 幅: | 高さ: | サイズ: 1.7 KiB |
|
変更前 幅: | 高さ: | サイズ: 637 B |
|
変更前 幅: | 高さ: | サイズ: 283 B |
|
変更前 幅: | 高さ: | サイズ: 456 B |
|
変更前 幅: | 高さ: | サイズ: 2.0 KiB |
@@ -1,97 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
|
||||
<TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
<Platforms>x64;ARM64</Platforms>
|
||||
<RuntimeIdentifiers>win-x64;win-arm64</RuntimeIdentifiers>
|
||||
<PublishProfile>win-$(Platform).pubxml</PublishProfile>
|
||||
<UseWinUI>true</UseWinUI>
|
||||
<EnableMsixTooling>true</EnableMsixTooling>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
|
||||
<!-- Ignore some warnings about ambiguous cref attribute references (same as in ComputeSharp.D2D1.WinUI) -->
|
||||
<NoWarn>$(NoWarn);CS0419</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<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.D2D1.Tests\Assets\TerracedHills.png">
|
||||
<Link>Assets\Shaders\TerracedHills.png</Link>
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</Content>
|
||||
<Content Include="Assets\SplashScreen.scale-200.png" />
|
||||
<Content Include="Assets\LockScreenLogo.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="AutoConstructor" Version="5.6.0" PrivateAssets="all" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.13.0" ExcludeAssets="build" />
|
||||
<PackageReference Include="MSTest" Version="3.8.3" />
|
||||
<PackageReference Include="TerraFX.Interop.Windows" Version="10.0.26100.2" />
|
||||
<Manifest Include="$(ApplicationManifest)" />
|
||||
</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.WinUI\ComputeSharp.D2D1.WinUI.csproj" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.D2D1\ComputeSharp.D2D1.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Mark the project as a test project -->
|
||||
<ItemGroup>
|
||||
<ProjectCapability Include="TestContainer" />
|
||||
</ItemGroup>
|
||||
|
||||
<!--
|
||||
Defining the "Msix" ProjectCapability here allows the Single-project MSIX Packaging
|
||||
Tools extension to be activated for this project even if the Windows App SDK Nuget
|
||||
package has not yet been restored.
|
||||
-->
|
||||
<ItemGroup Condition="'$(DisableMsixProjectCapabilityAddedByProject)'!='true' and '$(EnableMsixTooling)'=='true'">
|
||||
<ProjectCapability Include="Msix" />
|
||||
</ItemGroup>
|
||||
|
||||
<!--
|
||||
Defining the "HasPackageAndPublishMenuAddedByProject" property here allows the Solution
|
||||
Explorer "Package and Publish" context menu entry to be enabled for this project even if
|
||||
the Windows App SDK Nuget package has not yet been restored.
|
||||
-->
|
||||
<PropertyGroup Condition="'$(DisableHasPackageAndPublishMenuAddedByProject)'!='true' and '$(EnableMsixTooling)'=='true'">
|
||||
<HasPackageAndPublishMenu>true</HasPackageAndPublishMenu>
|
||||
</PropertyGroup>
|
||||
<Import Project="..\..\samples\ComputeSharp.SwapChain.Shaders.D2D1\ComputeSharp.SwapChain.Shaders.D2D1.projitems" Label="Shared" />
|
||||
</Project>
|
||||
@@ -1,103 +0,0 @@
|
||||
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.WinUI.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(Point position, Color expected, Color actual)
|
||||
{
|
||||
private readonly int redDifference = actual.R - expected.R;
|
||||
private readonly int greenDifference = actual.G - expected.G;
|
||||
private readonly int blueDifference = actual.B - expected.B;
|
||||
private readonly int alphaDifference = actual.A - expected.A;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override string ToString()
|
||||
{
|
||||
return $"[delta({this.redDifference},{this.greenDifference},{this.blueDifference},{this.alphaDifference}) @ ({position.X},{position.Y})]";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Graphics.Canvas;
|
||||
using TerraFX.Interop.DirectX;
|
||||
using TerraFX.Interop.Windows;
|
||||
using WinRT;
|
||||
|
||||
namespace ComputeSharp.D2D1.WinUI.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)
|
||||
{
|
||||
using ComPtr<IUnknown> canvasFactoryNativeUnknown = default;
|
||||
|
||||
// Get the ICanvasFactoryNative object
|
||||
using (IObjectReference canvasDeviceActivationFactory = ActivationFactory.Get(
|
||||
typeName: "Microsoft.Graphics.Canvas.CanvasDevice",
|
||||
iid: new Guid("695C440D-04B3-4EDD-BFD9-63E51E9F7202")))
|
||||
{
|
||||
canvasFactoryNativeUnknown.Attach((IUnknown*)canvasDeviceActivationFactory.GetRef());
|
||||
}
|
||||
|
||||
using ComPtr<IUnknown> canvasDeviceUnknown = default;
|
||||
|
||||
if (canvasDevice is not null)
|
||||
{
|
||||
canvasDeviceUnknown.Attach((IUnknown*)MarshalInspectable<CanvasDevice>.FromManaged(canvasDevice));
|
||||
}
|
||||
|
||||
int hresult;
|
||||
|
||||
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());
|
||||
|
||||
Marshal.ThrowExceptionForHR(hresult);
|
||||
}
|
||||
|
||||
using ComPtr<IUnknown> wrapperUnknown = default;
|
||||
|
||||
// Invoke GetOrCreate to get the inspectable wrapper
|
||||
hresult = ((delegate* unmanaged[MemberFunction]<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 MarshalInspectable<object>.FromAbi((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*)MarshalInterface<ICanvasImage>.FromManaged(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*)MarshalInspectable<CanvasDevice>.FromManaged(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[MemberFunction]<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);
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
<?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:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
|
||||
IgnorableNamespaces="uap rescap">
|
||||
|
||||
<Identity
|
||||
Name="3ecd8bb1-0416-4109-9318-6964189ee35d"
|
||||
Publisher="CN=sergiopedri"
|
||||
Version="1.0.0.0" />
|
||||
|
||||
<Properties>
|
||||
<DisplayName>ComputeSharp.D2D1.WinUI.Tests</DisplayName>
|
||||
<PublisherDisplayName>sergiopedri</PublisherDisplayName>
|
||||
<Logo>Assets\StoreLogo.png</Logo>
|
||||
</Properties>
|
||||
|
||||
<Dependencies>
|
||||
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.17763.0" MaxVersionTested="10.0.22621.0" />
|
||||
<TargetDeviceFamily Name="Windows.Desktop" MinVersion="10.0.17763.0" MaxVersionTested="10.0.22621.0" />
|
||||
</Dependencies>
|
||||
|
||||
<Resources>
|
||||
<Resource Language="x-generate"/>
|
||||
</Resources>
|
||||
|
||||
<Applications>
|
||||
<Application
|
||||
Id="App"
|
||||
Executable="$targetnametoken$.exe"
|
||||
EntryPoint="$targetentrypoint$">
|
||||
<uap:VisualElements
|
||||
DisplayName="ComputeSharp.D2D1.WinUI.Tests"
|
||||
Description="ComputeSharp.D2D1.WinUI.Tests"
|
||||
BackgroundColor="transparent"
|
||||
Square150x150Logo="Assets\Square150x150Logo.png"
|
||||
Square44x44Logo="Assets\Square44x44Logo.png">
|
||||
<uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png" />
|
||||
<uap:SplashScreen Image="Assets\SplashScreen.png" />
|
||||
</uap:VisualElements>
|
||||
</Application>
|
||||
</Applications>
|
||||
|
||||
<Capabilities>
|
||||
<rescap:Capability Name="runFullTrust" />
|
||||
</Capabilities>
|
||||
</Package>
|
||||
@@ -1,14 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<PublishProtocol>FileSystem</PublishProtocol>
|
||||
<Platform>ARM64</Platform>
|
||||
<RuntimeIdentifier>win-arm64</RuntimeIdentifier>
|
||||
<PublishDir>bin\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\publish\</PublishDir>
|
||||
<SelfContained>true</SelfContained>
|
||||
<PublishSingleFile>false</PublishSingleFile>
|
||||
<PublishReadyToRun Condition="'$(Configuration)' == 'Debug'">false</PublishReadyToRun>
|
||||
<PublishReadyToRun Condition="'$(Configuration)' != 'Debug'">true</PublishReadyToRun>
|
||||
<PublishTrimmed>false</PublishTrimmed>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -1,14 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<PublishProtocol>FileSystem</PublishProtocol>
|
||||
<Platform>x64</Platform>
|
||||
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
|
||||
<PublishDir>bin\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\publish\</PublishDir>
|
||||
<SelfContained>true</SelfContained>
|
||||
<PublishSingleFile>false</PublishSingleFile>
|
||||
<PublishReadyToRun Condition="'$(Configuration)' == 'Debug'">false</PublishReadyToRun>
|
||||
<PublishReadyToRun Condition="'$(Configuration)' != 'Debug'">true</PublishReadyToRun>
|
||||
<PublishTrimmed>false</PublishTrimmed>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -1,10 +0,0 @@
|
||||
{
|
||||
"profiles": {
|
||||
"ComputeSharp.D2D1.WinUI.Tests (Package)": {
|
||||
"commandName": "MsixPackage"
|
||||
},
|
||||
"ComputeSharp.D2D1.WinUI.Tests (Unpackaged)": {
|
||||
"commandName": "Project"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,712 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Numerics;
|
||||
using System.Threading.Tasks;
|
||||
using ComputeSharp.D2D1.WinUI.Tests.Helpers;
|
||||
using ComputeSharp.SwapChain.Shaders.D2D1;
|
||||
using Microsoft.Graphics.Canvas;
|
||||
using Microsoft.Graphics.Canvas.Effects;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using TerraFX.Interop.Windows;
|
||||
using Windows.Foundation;
|
||||
using Windows.Storage;
|
||||
using Windows.UI;
|
||||
|
||||
namespace ComputeSharp.D2D1.WinUI.Tests;
|
||||
|
||||
[TestClass]
|
||||
public partial class CanvasEffectTests
|
||||
{
|
||||
[TestMethod]
|
||||
public 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);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public void CanvasEffect_EffectSettingNotRegisteredOutputNode()
|
||||
{
|
||||
EffectSettingNotRegisteredOutputNode effect = new();
|
||||
|
||||
try
|
||||
{
|
||||
using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f);
|
||||
using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession();
|
||||
|
||||
drawingSession.DrawImage(effect);
|
||||
}
|
||||
catch
|
||||
{
|
||||
Assert.IsTrue(effect.WasConfigureEffectGraphCalled);
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(Exception), AllowDerivedTypes = true)]
|
||||
public void CanvasEffect_EffectNotRegisteringAnOutputNode()
|
||||
{
|
||||
const int COR_E_INVALIDOPERATION = unchecked((int)0x80131509);
|
||||
|
||||
EffectNotRegisteringAnOutputNode effect = new();
|
||||
|
||||
try
|
||||
{
|
||||
using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f);
|
||||
using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession();
|
||||
|
||||
drawingSession.DrawImage(effect);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// Note: this test should ideally expect and catch an InvalidOperationException, as that's the exception
|
||||
// type thrown by CanvasEffect. But it seems that CsWinRT isn't correctly forwarding the exception type
|
||||
// in this case, and it ends up only throwing a COMException on the managed side. To work around this in
|
||||
// this test, we can just catch a generic Exception and manually verify that the HRESULT is a match.
|
||||
// See https://github.com/microsoft/CsWinRT/issues/1393 (and ideally update the test once that's fixed).
|
||||
Assert.AreEqual(COR_E_INVALIDOPERATION, e.HResult);
|
||||
Assert.IsTrue(effect.WasConfigureEffectGraphCalled);
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public void CanvasEffect_EffectRegisteringNodesMultipleTimes1()
|
||||
{
|
||||
EffectRegisteringNodesMultipleTimes1 effect = new();
|
||||
|
||||
using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f);
|
||||
using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession();
|
||||
|
||||
drawingSession.DrawImage(effect);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public void CanvasEffect_EffectRegisteringNodesMultipleTimes2()
|
||||
{
|
||||
EffectRegisteringNodesMultipleTimes2 effect = new();
|
||||
|
||||
using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f);
|
||||
using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession();
|
||||
|
||||
drawingSession.DrawImage(effect);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanvasEffect_EffectRegisteringNullObjects()
|
||||
{
|
||||
EffectRegisteringNullObjects effect = new();
|
||||
|
||||
using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f);
|
||||
using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession();
|
||||
|
||||
drawingSession.DrawImage(effect);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanvasEffect_EffectConfiguringGraphIncorrectly()
|
||||
{
|
||||
EffectConfiguringGraphIncorrectly effect = new();
|
||||
|
||||
using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f);
|
||||
using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession();
|
||||
|
||||
drawingSession.DrawImage(effect);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanvasEffect_EffectOnlyUsingAnonymousNodes()
|
||||
{
|
||||
EffectOnlyUsingAnonymousNodes effect = new();
|
||||
|
||||
using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f);
|
||||
using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession();
|
||||
|
||||
drawingSession.DrawImage(effect);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanvasEffect_EffectUsingEffectGraphInInvalidState()
|
||||
{
|
||||
EffectUsingEffectGraphInInvalidState effect = new();
|
||||
|
||||
using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f);
|
||||
using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession();
|
||||
|
||||
drawingSession.DrawImage(effect);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanvasEffect_PixelShaderSwitchEffect()
|
||||
{
|
||||
PixelShaderSwitchEffect effect = new();
|
||||
|
||||
async Task TestAsync(string shaderName)
|
||||
{
|
||||
Color[] pixelColors;
|
||||
|
||||
using CanvasDevice canvasDevice = new();
|
||||
|
||||
// Same logic as in the shader tests
|
||||
using (CanvasRenderTarget renderTarget = new(canvasDevice, 1280, 720, 96.0f))
|
||||
{
|
||||
using (CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession())
|
||||
{
|
||||
drawingSession.DrawImage(effect);
|
||||
}
|
||||
|
||||
pixelColors = renderTarget.GetPixelColors();
|
||||
}
|
||||
|
||||
StorageFile imageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri($"ms-appx:///Assets/Shaders/{shaderName}.png"));
|
||||
|
||||
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: 0.00001f);
|
||||
}
|
||||
|
||||
// Every time the effect is re-drawn, a different shader is set as the output node
|
||||
await TestAsync(nameof(HelloWorld));
|
||||
await TestAsync(nameof(ColorfulInfinity));
|
||||
await TestAsync(nameof(FractalTiling));
|
||||
await TestAsync(nameof(Octagrams));
|
||||
await TestAsync(nameof(ProteanClouds));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanvasEffect_EffectTestingDisposal()
|
||||
{
|
||||
EffectTestingDisposal effect = new();
|
||||
|
||||
using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f);
|
||||
using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession();
|
||||
|
||||
// Force creating the graph (the drawing fails because the effects are dummies)
|
||||
try
|
||||
{
|
||||
drawingSession.DrawImage(effect);
|
||||
}
|
||||
catch (Exception e) when (e.HResult == E.E_FAIL)
|
||||
{
|
||||
}
|
||||
|
||||
Assert.AreEqual(1, effect.Effects1.Count);
|
||||
Assert.AreEqual(1, effect.Effects2.Count);
|
||||
Assert.AreEqual(1, effect.Effects3.Count);
|
||||
Assert.AreEqual(0, effect.Effects1[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(0, effect.Effects2[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(0, effect.Effects3[0].NumberOfDisposeCalls);
|
||||
|
||||
effect.InvalidateCreation();
|
||||
|
||||
// Effects aren't disposed yet until we redraw
|
||||
Assert.AreEqual(1, effect.Effects1.Count);
|
||||
Assert.AreEqual(1, effect.Effects2.Count);
|
||||
Assert.AreEqual(1, effect.Effects3.Count);
|
||||
Assert.AreEqual(0, effect.Effects1[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(0, effect.Effects2[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(0, effect.Effects3[0].NumberOfDisposeCalls);
|
||||
|
||||
// Redraw, which builds a new effect graph and disposes the old one
|
||||
try
|
||||
{
|
||||
drawingSession.DrawImage(effect);
|
||||
}
|
||||
catch (Exception e) when (e.HResult == E.E_FAIL)
|
||||
{
|
||||
}
|
||||
|
||||
Assert.AreEqual(2, effect.Effects1.Count);
|
||||
Assert.AreEqual(2, effect.Effects2.Count);
|
||||
Assert.AreEqual(2, effect.Effects3.Count);
|
||||
Assert.AreEqual(1, effect.Effects1[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(1, effect.Effects2[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(1, effect.Effects3[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(0, effect.Effects1[1].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(0, effect.Effects2[1].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(0, effect.Effects3[1].NumberOfDisposeCalls);
|
||||
|
||||
// Redrawing now doesn't change anything
|
||||
try
|
||||
{
|
||||
drawingSession.DrawImage(effect);
|
||||
}
|
||||
catch (Exception e) when (e.HResult == E.E_FAIL)
|
||||
{
|
||||
}
|
||||
|
||||
Assert.AreEqual(2, effect.Effects1.Count);
|
||||
Assert.AreEqual(2, effect.Effects2.Count);
|
||||
Assert.AreEqual(2, effect.Effects3.Count);
|
||||
Assert.AreEqual(1, effect.Effects1[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(1, effect.Effects2[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(1, effect.Effects3[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(0, effect.Effects1[1].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(0, effect.Effects2[1].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(0, effect.Effects3[1].NumberOfDisposeCalls);
|
||||
|
||||
effect.InvalidateUpdate();
|
||||
|
||||
// Invalidating with update mode also doesn't do anything here
|
||||
Assert.AreEqual(2, effect.Effects1.Count);
|
||||
Assert.AreEqual(2, effect.Effects2.Count);
|
||||
Assert.AreEqual(2, effect.Effects3.Count);
|
||||
Assert.AreEqual(1, effect.Effects1[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(1, effect.Effects2[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(1, effect.Effects3[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(0, effect.Effects1[1].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(0, effect.Effects2[1].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(0, effect.Effects3[1].NumberOfDisposeCalls);
|
||||
|
||||
// Redraw, and also verify the disposal state wasn't changed
|
||||
try
|
||||
{
|
||||
drawingSession.DrawImage(effect);
|
||||
}
|
||||
catch (Exception e) when (e.HResult == E.E_FAIL)
|
||||
{
|
||||
}
|
||||
|
||||
Assert.AreEqual(2, effect.Effects1.Count);
|
||||
Assert.AreEqual(2, effect.Effects2.Count);
|
||||
Assert.AreEqual(2, effect.Effects3.Count);
|
||||
Assert.AreEqual(1, effect.Effects1[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(1, effect.Effects2[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(1, effect.Effects3[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(0, effect.Effects1[1].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(0, effect.Effects2[1].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(0, effect.Effects3[1].NumberOfDisposeCalls);
|
||||
|
||||
// Verify that invalidating with update after creation is ignored
|
||||
effect.InvalidateCreation();
|
||||
effect.InvalidateUpdate();
|
||||
|
||||
Assert.AreEqual(2, effect.Effects1.Count);
|
||||
Assert.AreEqual(2, effect.Effects2.Count);
|
||||
Assert.AreEqual(2, effect.Effects3.Count);
|
||||
Assert.AreEqual(1, effect.Effects1[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(1, effect.Effects2[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(1, effect.Effects3[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(0, effect.Effects1[1].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(0, effect.Effects2[1].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(0, effect.Effects3[1].NumberOfDisposeCalls);
|
||||
|
||||
// Redraw, disposing the old graph once again
|
||||
try
|
||||
{
|
||||
drawingSession.DrawImage(effect);
|
||||
}
|
||||
catch (Exception e) when (e.HResult == E.E_FAIL)
|
||||
{
|
||||
}
|
||||
|
||||
Assert.AreEqual(3, effect.Effects1.Count);
|
||||
Assert.AreEqual(3, effect.Effects2.Count);
|
||||
Assert.AreEqual(3, effect.Effects3.Count);
|
||||
Assert.AreEqual(1, effect.Effects1[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(1, effect.Effects2[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(1, effect.Effects3[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(1, effect.Effects1[1].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(1, effect.Effects2[1].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(1, effect.Effects3[1].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(0, effect.Effects1[2].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(0, effect.Effects2[2].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(0, effect.Effects3[2].NumberOfDisposeCalls);
|
||||
|
||||
// Finally dispose the effect
|
||||
effect.Dispose();
|
||||
|
||||
Assert.AreEqual(3, effect.Effects1.Count);
|
||||
Assert.AreEqual(3, effect.Effects2.Count);
|
||||
Assert.AreEqual(3, effect.Effects3.Count);
|
||||
Assert.AreEqual(1, effect.Effects1[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(1, effect.Effects2[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(1, effect.Effects3[0].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(1, effect.Effects1[1].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(1, effect.Effects2[1].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(1, effect.Effects3[1].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(1, effect.Effects1[2].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(1, effect.Effects2[2].NumberOfDisposeCalls);
|
||||
Assert.AreEqual(1, effect.Effects3[2].NumberOfDisposeCalls);
|
||||
}
|
||||
|
||||
private sealed class EffectWithNoInputs : CanvasEffect
|
||||
{
|
||||
private static readonly CanvasEffectNode<PixelShaderEffect<ShaderWithNoInputs>> Effect = new();
|
||||
|
||||
private int value;
|
||||
|
||||
public int Value
|
||||
{
|
||||
get => this.value;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref this.value, value);
|
||||
}
|
||||
|
||||
public int ValueWithReload
|
||||
{
|
||||
get => this.value;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref this.value, value, CanvasEffectInvalidationType.Creation);
|
||||
}
|
||||
|
||||
public int NumberOfBuildEffectGraphCalls { get; private set; }
|
||||
|
||||
public int NumberOfConfigureEffectGraphCalls { get; private set; }
|
||||
|
||||
public int NumberOfDisposeCalls { get; private set; }
|
||||
|
||||
protected override void BuildEffectGraph(CanvasEffectGraph effectGraph)
|
||||
{
|
||||
NumberOfBuildEffectGraphCalls++;
|
||||
|
||||
effectGraph.RegisterOutputNode(Effect, new PixelShaderEffect<ShaderWithNoInputs>());
|
||||
}
|
||||
|
||||
protected override void ConfigureEffectGraph(CanvasEffectGraph effectGraph)
|
||||
{
|
||||
NumberOfConfigureEffectGraphCalls++;
|
||||
|
||||
effectGraph.GetNode(Effect).ConstantBuffer = new ShaderWithNoInputs(this.value);
|
||||
|
||||
// Also test the non-generic overload
|
||||
Assert.IsTrue(effectGraph.GetNode((ICanvasEffectNode)Effect) is PixelShaderEffect<ShaderWithNoInputs>);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
NumberOfDisposeCalls++;
|
||||
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class EffectSettingNotRegisteredOutputNode : CanvasEffect
|
||||
{
|
||||
public bool WasConfigureEffectGraphCalled { get; private set; }
|
||||
|
||||
protected override void BuildEffectGraph(CanvasEffectGraph effectGraph)
|
||||
{
|
||||
effectGraph.RegisterOutputNode(new CanvasEffectNode<ColorSourceEffect>(), new ColorSourceEffect());
|
||||
effectGraph.RegisterOutputNode(new CanvasEffectNode<ColorSourceEffect>(), new ColorSourceEffect());
|
||||
}
|
||||
|
||||
protected override void ConfigureEffectGraph(CanvasEffectGraph effectGraph)
|
||||
{
|
||||
WasConfigureEffectGraphCalled = true;
|
||||
|
||||
effectGraph.SetOutputNode(new CanvasEffectNode<ColorSourceEffect>());
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class EffectNotRegisteringAnOutputNode : CanvasEffect
|
||||
{
|
||||
public bool WasConfigureEffectGraphCalled { get; private set; }
|
||||
|
||||
protected override void BuildEffectGraph(CanvasEffectGraph effectGraph)
|
||||
{
|
||||
effectGraph.RegisterNode(new ColorSourceEffect());
|
||||
effectGraph.RegisterNode(new CanvasEffectNode<ColorSourceEffect>(), new ColorSourceEffect());
|
||||
effectGraph.RegisterNode(new CanvasEffectNode<ColorSourceEffect>(), new ColorSourceEffect());
|
||||
}
|
||||
|
||||
protected override void ConfigureEffectGraph(CanvasEffectGraph effectGraph)
|
||||
{
|
||||
WasConfigureEffectGraphCalled = true;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class EffectRegisteringNodesMultipleTimes1 : CanvasEffect
|
||||
{
|
||||
protected override void BuildEffectGraph(CanvasEffectGraph effectGraph)
|
||||
{
|
||||
CanvasEffectNode<ColorSourceEffect> node = new();
|
||||
|
||||
effectGraph.RegisterNode(node, new ColorSourceEffect());
|
||||
effectGraph.RegisterOutputNode(node, new ColorSourceEffect());
|
||||
}
|
||||
|
||||
protected override void ConfigureEffectGraph(CanvasEffectGraph effectGraph)
|
||||
{
|
||||
Assert.Fail();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class EffectRegisteringNodesMultipleTimes2 : CanvasEffect
|
||||
{
|
||||
protected override void BuildEffectGraph(CanvasEffectGraph effectGraph)
|
||||
{
|
||||
CanvasEffectNode<ColorSourceEffect> node = new();
|
||||
|
||||
effectGraph.RegisterNode(node, new ColorSourceEffect());
|
||||
effectGraph.RegisterNode(node, new ColorSourceEffect());
|
||||
effectGraph.RegisterOutputNode(new CanvasEffectNode<ColorSourceEffect>(), new ColorSourceEffect());
|
||||
}
|
||||
|
||||
protected override void ConfigureEffectGraph(CanvasEffectGraph effectGraph)
|
||||
{
|
||||
Assert.Fail();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class EffectRegisteringNullObjects : CanvasEffect
|
||||
{
|
||||
protected override unsafe void BuildEffectGraph(CanvasEffectGraph effectGraph)
|
||||
{
|
||||
// Verify that if the effect graph is invalid, arguments are validated first
|
||||
_ = Assert.ThrowsException<ArgumentNullException>(() => default(CanvasEffectGraph).RegisterNode(null!));
|
||||
_ = Assert.ThrowsException<ArgumentNullException>(() => default(CanvasEffectGraph).RegisterNode(null!, new ColorSourceEffect()));
|
||||
_ = Assert.ThrowsException<ArgumentNullException>(() => default(CanvasEffectGraph).RegisterNode(new CanvasEffectNode<ColorSourceEffect>(), null!));
|
||||
_ = Assert.ThrowsException<ArgumentNullException>(() => default(CanvasEffectGraph).RegisterNode(null!, (ColorSourceEffect?)null!));
|
||||
_ = Assert.ThrowsException<ArgumentNullException>(() => default(CanvasEffectGraph).RegisterOutputNode(null!));
|
||||
_ = Assert.ThrowsException<ArgumentNullException>(() => default(CanvasEffectGraph).RegisterOutputNode(null!, new ColorSourceEffect()));
|
||||
_ = Assert.ThrowsException<ArgumentNullException>(() => default(CanvasEffectGraph).RegisterOutputNode(new CanvasEffectNode<ColorSourceEffect>(), null!));
|
||||
_ = Assert.ThrowsException<ArgumentNullException>(() => default(CanvasEffectGraph).RegisterOutputNode(null!, (ColorSourceEffect)null!));
|
||||
|
||||
void* ptr = &effectGraph;
|
||||
|
||||
_ = Assert.ThrowsException<ArgumentNullException>(() => (*(CanvasEffectGraph*)ptr).RegisterNode(null!));
|
||||
_ = Assert.ThrowsException<ArgumentNullException>(() => (*(CanvasEffectGraph*)ptr).RegisterNode(null!, new ColorSourceEffect()));
|
||||
_ = Assert.ThrowsException<ArgumentNullException>(() => (*(CanvasEffectGraph*)ptr).RegisterNode(new CanvasEffectNode<ColorSourceEffect>(), null!));
|
||||
_ = Assert.ThrowsException<ArgumentNullException>(() => (*(CanvasEffectGraph*)ptr).RegisterNode(null!, (ColorSourceEffect?)null!));
|
||||
_ = Assert.ThrowsException<ArgumentNullException>(() => (*(CanvasEffectGraph*)ptr).RegisterOutputNode(null!));
|
||||
_ = Assert.ThrowsException<ArgumentNullException>(() => (*(CanvasEffectGraph*)ptr).RegisterOutputNode(null!, new ColorSourceEffect()));
|
||||
_ = Assert.ThrowsException<ArgumentNullException>(() => (*(CanvasEffectGraph*)ptr).RegisterOutputNode(new CanvasEffectNode<ColorSourceEffect>(), null!));
|
||||
_ = Assert.ThrowsException<ArgumentNullException>(() => (*(CanvasEffectGraph*)ptr).RegisterOutputNode(null!, (ColorSourceEffect)null!));
|
||||
|
||||
effectGraph.RegisterOutputNode(new CanvasEffectNode<ColorSourceEffect>(), new ColorSourceEffect());
|
||||
}
|
||||
|
||||
protected override void ConfigureEffectGraph(CanvasEffectGraph effectGraph)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class EffectConfiguringGraphIncorrectly : CanvasEffect
|
||||
{
|
||||
private static readonly CanvasEffectNode<ColorSourceEffect> EffectNode1 = new();
|
||||
private static readonly CanvasEffectNode<ColorSourceEffect> EffectNode2 = new();
|
||||
private static readonly CanvasEffectNode<ColorSourceEffect> EffectNode3 = new();
|
||||
#pragma warning disable CA2213
|
||||
private readonly ColorSourceEffect effect1 = new();
|
||||
private readonly ColorSourceEffect effect2 = new();
|
||||
private readonly ColorSourceEffect effect3 = new();
|
||||
#pragma warning restore CA2213
|
||||
|
||||
protected override void BuildEffectGraph(CanvasEffectGraph effectGraph)
|
||||
{
|
||||
effectGraph.RegisterNode(EffectNode1, this.effect1);
|
||||
effectGraph.RegisterNode(EffectNode2, this.effect2);
|
||||
effectGraph.RegisterOutputNode(EffectNode3, this.effect3);
|
||||
}
|
||||
|
||||
protected override unsafe void ConfigureEffectGraph(CanvasEffectGraph effectGraph)
|
||||
{
|
||||
void* ptr = &effectGraph;
|
||||
|
||||
_ = Assert.ThrowsException<ArgumentNullException>(() => (*(CanvasEffectGraph*)ptr).GetNode((CanvasEffectNode<ColorSourceEffect>)null!));
|
||||
_ = Assert.ThrowsException<ArgumentException>(() => (*(CanvasEffectGraph*)ptr).GetNode(new CanvasEffectNode<ColorSourceEffect>()));
|
||||
_ = Assert.ThrowsException<InvalidOperationException>(() => (*(CanvasEffectGraph*)ptr).RegisterNode(new CanvasEffectNode<ColorSourceEffect>(), new ColorSourceEffect()));
|
||||
_ = Assert.ThrowsException<InvalidOperationException>(() => (*(CanvasEffectGraph*)ptr).RegisterOutputNode(new CanvasEffectNode<ColorSourceEffect>(), new ColorSourceEffect()));
|
||||
|
||||
Assert.AreSame(effectGraph.GetNode(EffectNode1), this.effect1);
|
||||
Assert.AreSame(effectGraph.GetNode(EffectNode2), this.effect2);
|
||||
Assert.AreSame(effectGraph.GetNode(EffectNode3), this.effect3);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class EffectOnlyUsingAnonymousNodes : CanvasEffect
|
||||
{
|
||||
protected override void BuildEffectGraph(CanvasEffectGraph effectGraph)
|
||||
{
|
||||
effectGraph.RegisterNode(new ColorSourceEffect());
|
||||
effectGraph.RegisterNode(new ColorSourceEffect());
|
||||
effectGraph.RegisterOutputNode(new ColorSourceEffect());
|
||||
}
|
||||
|
||||
protected override void ConfigureEffectGraph(CanvasEffectGraph effectGraph)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class EffectUsingEffectGraphInInvalidState : CanvasEffect
|
||||
{
|
||||
protected override void BuildEffectGraph(CanvasEffectGraph effectGraph)
|
||||
{
|
||||
_ = Assert.ThrowsException<InvalidOperationException>(() => default(CanvasEffectGraph).RegisterNode(new ColorSourceEffect()));
|
||||
_ = Assert.ThrowsException<InvalidOperationException>(() => default(CanvasEffectGraph).RegisterNode(new CanvasEffectNode<ColorSourceEffect>(), new ColorSourceEffect()));
|
||||
_ = Assert.ThrowsException<InvalidOperationException>(() => default(CanvasEffectGraph).RegisterOutputNode(new ColorSourceEffect()));
|
||||
_ = Assert.ThrowsException<InvalidOperationException>(() => default(CanvasEffectGraph).RegisterOutputNode(new CanvasEffectNode<ColorSourceEffect>(), new ColorSourceEffect()));
|
||||
|
||||
effectGraph.RegisterOutputNode(new CanvasEffectNode<ColorSourceEffect>(), new ColorSourceEffect());
|
||||
}
|
||||
|
||||
protected override void ConfigureEffectGraph(CanvasEffectGraph effectGraph)
|
||||
{
|
||||
_ = Assert.ThrowsException<InvalidOperationException>(() => default(CanvasEffectGraph).GetNode(new CanvasEffectNode<ColorSourceEffect>()));
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class PixelShaderSwitchEffect : CanvasEffect
|
||||
{
|
||||
private static readonly CanvasEffectNode<PixelShaderEffect<HelloWorld>> HelloWorldNode = new();
|
||||
private static readonly CanvasEffectNode<PixelShaderEffect<ColorfulInfinity>> ColorfulInfinityNode = new();
|
||||
private static readonly CanvasEffectNode<PixelShaderEffect<FractalTiling>> FractalTilingNode = new();
|
||||
private static readonly CanvasEffectNode<PixelShaderEffect<Octagrams>> OctagramsNode = new();
|
||||
private static readonly CanvasEffectNode<PixelShaderEffect<ProteanClouds>> ProteanCloudsNode = new();
|
||||
|
||||
private int step;
|
||||
|
||||
protected override void BuildEffectGraph(CanvasEffectGraph effectGraph)
|
||||
{
|
||||
effectGraph.RegisterNode(HelloWorldNode, new PixelShaderEffect<HelloWorld> { ConstantBuffer = new HelloWorld(0, new int2(1280, 720)) });
|
||||
effectGraph.RegisterNode(ColorfulInfinityNode, new PixelShaderEffect<ColorfulInfinity> { ConstantBuffer = new ColorfulInfinity(0, new int2(1280, 720)) });
|
||||
effectGraph.RegisterNode(FractalTilingNode, new PixelShaderEffect<FractalTiling> { ConstantBuffer = new FractalTiling(0, new int2(1280, 720)) });
|
||||
effectGraph.RegisterNode(OctagramsNode, new PixelShaderEffect<Octagrams> { ConstantBuffer = new Octagrams(0, new int2(1280, 720)) });
|
||||
effectGraph.RegisterNode(ProteanCloudsNode, new PixelShaderEffect<ProteanClouds> { ConstantBuffer = new ProteanClouds(0, new int2(1280, 720)) });
|
||||
effectGraph.SetOutputNode(HelloWorldNode);
|
||||
}
|
||||
|
||||
protected override void ConfigureEffectGraph(CanvasEffectGraph effectGraph)
|
||||
{
|
||||
switch (this.step++)
|
||||
{
|
||||
case 0: break;
|
||||
case 1:
|
||||
effectGraph.SetOutputNode(ColorfulInfinityNode);
|
||||
break;
|
||||
case 2:
|
||||
effectGraph.SetOutputNode(FractalTilingNode);
|
||||
break;
|
||||
case 3 or 4:
|
||||
// Test the overload which is non-generic, allowing ternary expressions too
|
||||
effectGraph.SetOutputNode(this.step == 4 ? OctagramsNode : ProteanCloudsNode);
|
||||
break;
|
||||
default:
|
||||
Assert.Fail();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class EffectTestingDisposal : CanvasEffect
|
||||
{
|
||||
private static readonly CanvasEffectNode<DummyCanvasImageTrackingDisposal> EffectNode1 = new();
|
||||
private static readonly CanvasEffectNode<DummyCanvasImageTrackingDisposal> EffectNode2 = new();
|
||||
private static readonly CanvasEffectNode<DummyCanvasImageTrackingDisposal> EffectNode3 = new();
|
||||
public readonly List<DummyCanvasImageTrackingDisposal> Effects1 = [];
|
||||
public readonly List<DummyCanvasImageTrackingDisposal> Effects2 = [];
|
||||
public readonly List<DummyCanvasImageTrackingDisposal> Effects3 = [];
|
||||
|
||||
public void InvalidateCreation()
|
||||
{
|
||||
InvalidateEffectGraph(CanvasEffectInvalidationType.Creation);
|
||||
}
|
||||
|
||||
public void InvalidateUpdate()
|
||||
{
|
||||
InvalidateEffectGraph(CanvasEffectInvalidationType.Update);
|
||||
}
|
||||
|
||||
protected override void BuildEffectGraph(CanvasEffectGraph effectGraph)
|
||||
{
|
||||
this.Effects1.Add(new DummyCanvasImageTrackingDisposal());
|
||||
this.Effects2.Add(new DummyCanvasImageTrackingDisposal());
|
||||
this.Effects3.Add(new DummyCanvasImageTrackingDisposal());
|
||||
|
||||
effectGraph.RegisterNode(EffectNode1, this.Effects1[^1]);
|
||||
effectGraph.RegisterNode(EffectNode2, this.Effects2[^1]);
|
||||
effectGraph.RegisterOutputNode(EffectNode3, this.Effects3[^1]);
|
||||
}
|
||||
|
||||
protected override void ConfigureEffectGraph(CanvasEffectGraph effectGraph)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class DummyCanvasImageTrackingDisposal : ICanvasImage
|
||||
{
|
||||
public int NumberOfDisposeCalls { get; private set; }
|
||||
|
||||
public Rect GetBounds(ICanvasResourceCreator resourceCreator)
|
||||
{
|
||||
Assert.Fail();
|
||||
|
||||
return default;
|
||||
}
|
||||
|
||||
public Rect GetBounds(ICanvasResourceCreator resourceCreator, Matrix3x2 transform)
|
||||
{
|
||||
Assert.Fail();
|
||||
|
||||
return default;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
NumberOfDisposeCalls++;
|
||||
}
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct ShaderWithNoInputs : ID2D1PixelShader
|
||||
{
|
||||
public readonly int Value;
|
||||
|
||||
public float4 Execute()
|
||||
{
|
||||
return default;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,521 +0,0 @@
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeSharp.D2D1;
|
||||
using ComputeSharp.D2D1.Interop;
|
||||
using ComputeSharp.D2D1.WinUI.Tests.Helpers;
|
||||
using Microsoft.Graphics.Canvas;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using TerraFX.Interop.DirectX;
|
||||
using TerraFX.Interop.Windows;
|
||||
|
||||
[assembly: D2DEnableRuntimeCompilation]
|
||||
|
||||
namespace ComputeSharp.D2D1.WinUI.Tests;
|
||||
|
||||
[TestClass]
|
||||
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: unchecked((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: unchecked((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: unchecked((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: unchecked((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)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct ShaderWithSomeProperties : ID2D1PixelShader
|
||||
{
|
||||
public readonly float A;
|
||||
public readonly int B;
|
||||
public readonly int2 C;
|
||||
public readonly uint2x2 D;
|
||||
public readonly float2 E;
|
||||
|
||||
public float4 Execute()
|
||||
{
|
||||
return default;
|
||||
}
|
||||
}
|
||||
|
||||
[D2DInputCount(1)]
|
||||
[D2DInputSimple(0)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct ShaderWithSomePropertiesAndInputs : ID2D1PixelShader
|
||||
{
|
||||
public readonly int Number;
|
||||
|
||||
public float4 Execute()
|
||||
{
|
||||
return D2D.GetInput(0);
|
||||
}
|
||||
}
|
||||
|
||||
[D2DInputCount(0)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal partial struct ShaderWith0Inputs : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
return default;
|
||||
}
|
||||
}
|
||||
|
||||
[D2DInputCount(1)]
|
||||
[D2DInputSimple(0)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal partial struct ShaderWith1Input : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
return D2D.GetInput(0);
|
||||
}
|
||||
}
|
||||
|
||||
[D2DInputCount(2)]
|
||||
[D2DInputSimple(0)]
|
||||
[D2DInputSimple(1)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
internal partial struct ShaderWith2Inputs : ID2D1PixelShader
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
return D2D.GetInput(0) + D2D.GetInput(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using ComputeSharp.D2D1.Descriptors;
|
||||
using ComputeSharp.D2D1.WinUI.Tests.Helpers;
|
||||
using ComputeSharp.SwapChain.Shaders.D2D1;
|
||||
using Microsoft.Graphics.Canvas;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using Windows.Storage;
|
||||
using Windows.UI;
|
||||
|
||||
namespace ComputeSharp.D2D1.WinUI.Tests;
|
||||
|
||||
[TestClass]
|
||||
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.000027f);
|
||||
}
|
||||
|
||||
private static async Task RunTestAsync<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(WrapperType wrapperType, float threshold = 0.00001f)
|
||||
where T : unmanaged, ID2D1PixelShader, ID2D1PixelShaderDescriptor<T>
|
||||
{
|
||||
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, ID2D1PixelShaderDescriptor<T>
|
||||
{
|
||||
private static readonly CanvasEffectNode<PixelShaderEffect<T>> Effect = new();
|
||||
|
||||
private T constantBuffer;
|
||||
|
||||
public T ConstantBuffer
|
||||
{
|
||||
get => this.constantBuffer;
|
||||
set => SetPropertyAndInvalidateEffectGraph(ref this.constantBuffer, value);
|
||||
}
|
||||
|
||||
protected override void BuildEffectGraph(CanvasEffectGraph effectGraph)
|
||||
{
|
||||
effectGraph.RegisterOutputNode(Effect, new PixelShaderEffect<T>());
|
||||
}
|
||||
|
||||
protected override void ConfigureEffectGraph(CanvasEffectGraph effectGraph)
|
||||
{
|
||||
effectGraph.GetNode(Effect).ConstantBuffer = this.constantBuffer;
|
||||
}
|
||||
}
|
||||
|
||||
public enum WrapperType
|
||||
{
|
||||
PixelShaderEffect,
|
||||
CanvasEffect
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<assemblyIdentity version="1.0.0.0" name="ComputeSharp.D2D1.WinUI.Tests.app"/>
|
||||
|
||||
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
|
||||
<application>
|
||||
<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />
|
||||
</application>
|
||||
</compatibility>
|
||||
|
||||
<application xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<windowsSettings>
|
||||
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/PM</dpiAware>
|
||||
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2, PerMonitor</dpiAwareness>
|
||||
</windowsSettings>
|
||||
</application>
|
||||
</assembly>
|
||||
@@ -1,19 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<EnableTrimAnalyzer>true</EnableTrimAnalyzer>
|
||||
<NoWarn>$(NoWarn);IL2026</NoWarn>
|
||||
<PublishAot Condition="'$(COMPUTESHARP_NUGET_TESTS_PUBLISH_AOT)' == 'true'">true</PublishAot>
|
||||
<RestoreSources>
|
||||
https://api.nuget.org/v3/index.json;
|
||||
..\..\artifacts;
|
||||
</RestoreSources>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ComputeSharp.Core" Version="$(PackageVersion)" />
|
||||
<PackageReference Include="ComputeSharp" Version="$(PackageVersion)" />
|
||||
<PackageReference Include="ComputeSharp.Dxc" Version="$(PackageVersion)" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,45 +0,0 @@
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Runtime.Versioning;
|
||||
using ComputeSharp;
|
||||
using ComputeSharp.Interop;
|
||||
|
||||
[assembly: SupportedOSPlatform("windows6.2")]
|
||||
|
||||
float[] array = [.. Enumerable.Range(1, 100)];
|
||||
|
||||
// Create the graphics buffer
|
||||
using ReadWriteBuffer<float> gpuBuffer = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(array);
|
||||
|
||||
// Run the shader
|
||||
GraphicsDevice.GetDefault().For(100, new MultiplyByTwo(gpuBuffer));
|
||||
|
||||
// Get the data back
|
||||
float[] result = gpuBuffer.ToArray();
|
||||
|
||||
// Validate results
|
||||
for (int i = 0; i < array.Length; i++)
|
||||
{
|
||||
Trace.Assert(result[i] == array[i] * 2);
|
||||
}
|
||||
|
||||
// Also get the shader info (this requires DXC to be present)
|
||||
ShaderInfo shaderInfo = ReflectionServices.GetShaderInfo<MultiplyByTwo>();
|
||||
|
||||
// Validate a couple properties as a sanity check
|
||||
Trace.Assert(shaderInfo.HlslSource is { Length: > 0 });
|
||||
Trace.Assert(shaderInfo.BoundResourceCount == 2);
|
||||
|
||||
/// <summary>
|
||||
/// A sample kernel that requires dynamic compilation, as it's not precompiled.
|
||||
/// </summary>
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct MultiplyByTwo(ReadWriteBuffer<float> buffer) : IComputeShader
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public void Execute()
|
||||
{
|
||||
buffer[ThreadIds.X] *= 2;
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<EnableTrimAnalyzer>true</EnableTrimAnalyzer>
|
||||
<NoWarn>$(NoWarn);IL2026</NoWarn>
|
||||
<PublishAot Condition="'$(COMPUTESHARP_NUGET_TESTS_PUBLISH_AOT)' == 'true'">true</PublishAot>
|
||||
<RestoreSources>
|
||||
https://api.nuget.org/v3/index.json;
|
||||
..\..\artifacts;
|
||||
</RestoreSources>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ComputeSharp.Core" Version="$(PackageVersion)" />
|
||||
<PackageReference Include="ComputeSharp" Version="$(PackageVersion)" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,37 +0,0 @@
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Runtime.Versioning;
|
||||
using ComputeSharp;
|
||||
|
||||
[assembly: SupportedOSPlatform("windows6.2")]
|
||||
|
||||
float[] array = [.. Enumerable.Range(1, 100)];
|
||||
|
||||
// Create the graphics buffer
|
||||
using ReadWriteBuffer<float> gpuBuffer = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(array);
|
||||
|
||||
// Run the shader
|
||||
GraphicsDevice.GetDefault().For(100, new MultiplyByTwo(gpuBuffer));
|
||||
|
||||
// Get the data back
|
||||
float[] result = gpuBuffer.ToArray();
|
||||
|
||||
// Validate results
|
||||
for (int i = 0; i < array.Length; i++)
|
||||
{
|
||||
Trace.Assert(result[i] == array[i] * 2);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A sample kernel that is precompiled.
|
||||
/// </summary>
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct MultiplyByTwo(ReadWriteBuffer<float> buffer) : IComputeShader
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public void Execute()
|
||||
{
|
||||
buffer[ThreadIds.X] *= 2;
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<EnableTrimAnalyzer>true</EnableTrimAnalyzer>
|
||||
<NoWarn>$(NoWarn);IL2026</NoWarn>
|
||||
<PublishAot Condition="'$(COMPUTESHARP_NUGET_TESTS_PUBLISH_AOT)' == 'true'">true</PublishAot>
|
||||
<RestoreSources>
|
||||
https://api.nuget.org/v3/index.json;
|
||||
..\..\artifacts;
|
||||
</RestoreSources>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ComputeSharp.Core" Version="$(PackageVersion)" />
|
||||
<PackageReference Include="ComputeSharp" Version="$(PackageVersion)" />
|
||||
<PackageReference Include="ComputeSharp.Pix" Version="$(PackageVersion)" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,43 +0,0 @@
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Runtime.Versioning;
|
||||
using ComputeSharp;
|
||||
|
||||
[assembly: SupportedOSPlatform("windows6.2")]
|
||||
|
||||
float[] array = [.. Enumerable.Range(1, 100)];
|
||||
|
||||
// Create the graphics buffer
|
||||
using ReadWriteBuffer<float> gpuBuffer = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(array);
|
||||
|
||||
// Run the shader
|
||||
using (ComputeContext context = GraphicsDevice.GetDefault().CreateComputeContext())
|
||||
{
|
||||
context.Log("Dispatching shader");
|
||||
context.BeginEvent("Dispatching event");
|
||||
context.For(100, new MultiplyByTwo(gpuBuffer));
|
||||
context.EndEvent();
|
||||
}
|
||||
|
||||
// Get the data back
|
||||
float[] result = gpuBuffer.ToArray();
|
||||
|
||||
// Validate results
|
||||
for (int i = 0; i < array.Length; i++)
|
||||
{
|
||||
Trace.Assert(result[i] == array[i] * 2);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A sample kernel that is precompiled.
|
||||
/// </summary>
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct MultiplyByTwo(ReadWriteBuffer<float> buffer) : IComputeShader
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public void Execute()
|
||||
{
|
||||
buffer[ThreadIds.X] *= 2;
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- Add a defined constant for D3D12MA, same as in the main test project -->
|
||||
<PropertyGroup Condition="'$(UseD3D12MemoryAllocator)' == 'true'">
|
||||
<DefineConstants>$(DefineConstants);USE_D3D12MA</DefineConstants>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoConstructor" Version="5.6.0" PrivateAssets="all" />
|
||||
<PackageReference Include="MSTest" Version="3.8.3" />
|
||||
<PackageReference Include="TerraFX.Interop.Windows" Version="10.0.26100.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.Core\ComputeSharp.Core.csproj" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.Core.SourceGenerators\ComputeSharp.Core.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.D3D12MemoryAllocator\ComputeSharp.D3D12MemoryAllocator.csproj" Condition="'$(UseD3D12MemoryAllocator)' == 'true'" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp\ComputeSharp.csproj" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\ComputeSharp.Tests\Attributes\AdditionalDataAttribute.cs" Link="Attributes\AdditionalDataAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp.Tests\Attributes\AdditionalResourceAttribute.cs" Link="Attributes\AdditionalResourceAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp.Tests\Attributes\AllDevicesAttribute.cs" Link="Attributes\AllDevicesAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp.Tests\Attributes\CombinatorialTestMethodAttribute.cs" Link="Attributes\CombinatorialTestMethodAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp.Tests\Attributes\DataAttribute.cs" Link="Attributes\DataAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp.Tests\Attributes\DeviceAttribute.cs" Link="Attributes\DeviceAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp.Tests\Attributes\ResourceAttribute.cs" Link="Attributes\ResourceAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp.Tests\Extensions\GraphicsDeviceExtensions.cs" Link="Extensions\GraphicsDeviceExtensions.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,191 +0,0 @@
|
||||
using System;
|
||||
#if USE_D3D12MA
|
||||
using ComputeSharp.D3D12MemoryAllocator;
|
||||
#endif
|
||||
using ComputeSharp.Interop;
|
||||
using ComputeSharp.Tests.Attributes;
|
||||
using ComputeSharp.Tests.DeviceLost.Helpers;
|
||||
using ComputeSharp.Tests.Extensions;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using TerraFX.Interop.DirectX;
|
||||
using TerraFX.Interop.Windows;
|
||||
|
||||
namespace ComputeSharp.Tests.DeviceLost;
|
||||
|
||||
[TestClass]
|
||||
public partial class DeviceDisposalTests
|
||||
{
|
||||
[AssemblyInitialize]
|
||||
public static void ConfigureImageSharp(TestContext _)
|
||||
{
|
||||
#if USE_D3D12MA
|
||||
// If requested by the test runner, configure D3D12MA
|
||||
AllocationServices.ConfigureAllocatorFactory(new D3D12MemoryAllocatorFactory());
|
||||
#endif
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeviceDisposal_GetDefault_ReferenceCounting()
|
||||
{
|
||||
using ComPtr<ID3D12Device> d3D12Device = default;
|
||||
|
||||
using (GraphicsDevice graphicsDevice = GraphicsDevice.GetDefault())
|
||||
{
|
||||
GraphicsDeviceHelper.GetD3D12Device(graphicsDevice, in d3D12Device);
|
||||
}
|
||||
|
||||
Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(d3D12Device));
|
||||
}
|
||||
|
||||
[CombinatorialTestMethod]
|
||||
[AllDevices]
|
||||
public void DeviceDisposal_ReferenceCounting(Device device)
|
||||
{
|
||||
using ComPtr<ID3D12Device> d3D12Device = default;
|
||||
|
||||
using (GraphicsDevice graphicsDevice = device.Get())
|
||||
{
|
||||
GraphicsDeviceHelper.GetD3D12Device(graphicsDevice, in d3D12Device);
|
||||
}
|
||||
|
||||
Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(d3D12Device));
|
||||
}
|
||||
|
||||
[CombinatorialTestMethod]
|
||||
[AllDevices]
|
||||
[ExpectedException(typeof(ObjectDisposedException))]
|
||||
public unsafe void DeviceDisposal_InteropServicesThrowsObjectDisposedException(Device device)
|
||||
{
|
||||
using ComPtr<ID3D12Device> d3D12Device = default;
|
||||
|
||||
GraphicsDevice graphicsDevice = device.Get();
|
||||
|
||||
graphicsDevice.Dispose();
|
||||
|
||||
InteropServices.GetID3D12Device(graphicsDevice, Windows.__uuidof<ID3D12Device>(), (void**)d3D12Device.GetAddressOf());
|
||||
}
|
||||
|
||||
[CombinatorialTestMethod]
|
||||
[AllDevices]
|
||||
public void DeviceDisposal_DisposedResources_ReferenceCounting(Device device)
|
||||
{
|
||||
using ComPtr<ID3D12Device> d3D12Device = default;
|
||||
|
||||
using (GraphicsDevice graphicsDevice = device.Get())
|
||||
{
|
||||
using ConstantBuffer<float> r1 = graphicsDevice.AllocateConstantBuffer<float>(128);
|
||||
using ReadOnlyBuffer<float> r2 = graphicsDevice.AllocateReadOnlyBuffer<float>(128);
|
||||
using ReadWriteBuffer<float> r3 = graphicsDevice.AllocateReadWriteBuffer<float>(128);
|
||||
using ReadOnlyTexture2D<float> r4 = graphicsDevice.AllocateReadOnlyTexture2D<float>(128, 128);
|
||||
using ReadWriteTexture2D<float> r5 = graphicsDevice.AllocateReadWriteTexture2D<float>(128, 128);
|
||||
using UploadBuffer<float> r6 = graphicsDevice.AllocateUploadBuffer<float>(128);
|
||||
using ReadBackBuffer<float> r7 = graphicsDevice.AllocateReadBackBuffer<float>(128);
|
||||
using UploadTexture2D<float> r8 = graphicsDevice.AllocateUploadTexture2D<float>(128, 128);
|
||||
using ReadBackTexture2D<float> r9 = graphicsDevice.AllocateReadBackTexture2D<float>(128, 128);
|
||||
|
||||
GraphicsDeviceHelper.GetD3D12Device(graphicsDevice, in d3D12Device);
|
||||
}
|
||||
|
||||
Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(d3D12Device));
|
||||
}
|
||||
|
||||
[CombinatorialTestMethod]
|
||||
[AllDevices]
|
||||
public void DeviceDisposal_DisposedResourcesAfterDevice_ReferenceCounting(Device device)
|
||||
{
|
||||
using ComPtr<ID3D12Device> d3D12Device = default;
|
||||
|
||||
ConstantBuffer<float> r1;
|
||||
ReadOnlyBuffer<float> r2;
|
||||
ReadWriteBuffer<float> r3;
|
||||
ReadOnlyTexture2D<float> r4;
|
||||
ReadWriteTexture2D<float> r5;
|
||||
|
||||
using (GraphicsDevice graphicsDevice = device.Get())
|
||||
{
|
||||
r1 = graphicsDevice.AllocateConstantBuffer<float>(128);
|
||||
r2 = graphicsDevice.AllocateReadOnlyBuffer<float>(128);
|
||||
r3 = graphicsDevice.AllocateReadWriteBuffer<float>(128);
|
||||
r4 = graphicsDevice.AllocateReadOnlyTexture2D<float>(128, 128);
|
||||
r5 = graphicsDevice.AllocateReadWriteTexture2D<float>(128, 128);
|
||||
|
||||
GraphicsDeviceHelper.GetD3D12Device(graphicsDevice, in d3D12Device);
|
||||
}
|
||||
|
||||
r1.Dispose();
|
||||
r2.Dispose();
|
||||
r3.Dispose();
|
||||
r4.Dispose();
|
||||
r5.Dispose();
|
||||
|
||||
Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(d3D12Device));
|
||||
}
|
||||
|
||||
[CombinatorialTestMethod]
|
||||
[AllDevices]
|
||||
public void DeviceDisposal_WithComputeShader_ReferenceCounting(Device device)
|
||||
{
|
||||
using ComPtr<ID3D12Device> d3D12Device = default;
|
||||
|
||||
using (GraphicsDevice graphicsDevice = device.Get())
|
||||
{
|
||||
using ReadWriteBuffer<float> buffer = graphicsDevice.AllocateReadWriteBuffer<float>(128);
|
||||
|
||||
using (ComputeContext context = graphicsDevice.CreateComputeContext())
|
||||
{
|
||||
context.For(buffer.Length, new InitializeShader(buffer));
|
||||
}
|
||||
|
||||
GraphicsDeviceHelper.GetD3D12Device(graphicsDevice, in d3D12Device);
|
||||
}
|
||||
|
||||
Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(d3D12Device));
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct InitializeShader : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<float> buffer;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
this.buffer[ThreadIds.X] = ThreadIds.X;
|
||||
}
|
||||
}
|
||||
|
||||
[CombinatorialTestMethod]
|
||||
[AllDevices]
|
||||
public void DeviceDisposal_WithPixelShader_ReferenceCounting(Device device)
|
||||
{
|
||||
using ComPtr<ID3D12Device> d3D12Device = default;
|
||||
|
||||
using (GraphicsDevice graphicsDevice = device.Get())
|
||||
{
|
||||
using ReadWriteTexture2D<Rgba32, float4> texture = graphicsDevice.AllocateReadWriteTexture2D<Rgba32, float4>(128, 128);
|
||||
|
||||
using (ComputeContext context = graphicsDevice.CreateComputeContext())
|
||||
{
|
||||
context.ForEach(texture, default(HelloWorldShader));
|
||||
}
|
||||
|
||||
GraphicsDeviceHelper.GetD3D12Device(graphicsDevice, in d3D12Device);
|
||||
}
|
||||
|
||||
Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(d3D12Device));
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal partial struct HelloWorldShader : IComputeShader<float4>
|
||||
{
|
||||
public float4 Execute()
|
||||
{
|
||||
float2 uv = ThreadIds.Normalized.XY;
|
||||
float3 col = 0.5f + (0.5f * Hlsl.Cos(new float3(uv, uv.X) + new float3(0, 2, 4)));
|
||||
|
||||
return new(col, 1f);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using ComputeSharp.Tests.Attributes;
|
||||
using ComputeSharp.Tests.DeviceLost.Helpers;
|
||||
using ComputeSharp.Tests.Extensions;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using TerraFX.Interop.DirectX;
|
||||
using TerraFX.Interop.Windows;
|
||||
|
||||
namespace ComputeSharp.Tests.DeviceLost;
|
||||
|
||||
[TestClass]
|
||||
public class DeviceLostTests
|
||||
{
|
||||
[CombinatorialTestMethod]
|
||||
[AllDevices]
|
||||
public async Task DeviceLost_RaiseEvent(Device device)
|
||||
{
|
||||
using ComPtr<ID3D12Device> d3D12Device = default;
|
||||
|
||||
using (GraphicsDevice graphicsDevice = device.Get())
|
||||
{
|
||||
GraphicsDeviceHelper.GetD3D12Device(graphicsDevice, in d3D12Device);
|
||||
|
||||
List<(object? Sender, DeviceLostEventArgs Args)> args = [];
|
||||
|
||||
// Register the device lost callback
|
||||
graphicsDevice.DeviceLost += (s, e) => args.Add((s, e));
|
||||
|
||||
await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice);
|
||||
|
||||
Assert.AreEqual(1, args.Count);
|
||||
Assert.IsNotNull(args[0].Sender);
|
||||
Assert.IsNotNull(args[0].Args);
|
||||
Assert.AreSame(args[0].Sender, graphicsDevice);
|
||||
Assert.AreEqual(args[0].Args.Reason, DeviceLostReason.DeviceRemoved);
|
||||
|
||||
// Trying to remove the device again does nothing
|
||||
GraphicsDeviceHelper.RemoveDevice(graphicsDevice);
|
||||
GraphicsDeviceHelper.RemoveDevice(graphicsDevice);
|
||||
GraphicsDeviceHelper.RemoveDevice(graphicsDevice);
|
||||
GraphicsDeviceHelper.RemoveDevice(graphicsDevice);
|
||||
|
||||
// The event can only be raised once
|
||||
Assert.AreEqual(1, args.Count);
|
||||
}
|
||||
|
||||
// Ensure the device has been disposed correctly
|
||||
Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(in d3D12Device));
|
||||
}
|
||||
|
||||
[CombinatorialTestMethod]
|
||||
[AllDevices]
|
||||
[Resource(typeof(ConstantBuffer<>))]
|
||||
[Resource(typeof(ReadOnlyBuffer<>))]
|
||||
[Resource(typeof(ReadWriteBuffer<>))]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task DeviceLost_AllocateBuffer(Device device, Type bufferType)
|
||||
{
|
||||
using GraphicsDevice graphicsDevice = device.Get();
|
||||
|
||||
await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice);
|
||||
|
||||
using Resources.Buffer<float> _ = graphicsDevice.AllocateBuffer<float>(bufferType, 128);
|
||||
}
|
||||
|
||||
[CombinatorialTestMethod]
|
||||
[AllDevices]
|
||||
[Resource(typeof(ReadOnlyTexture2D<>))]
|
||||
[Resource(typeof(ReadWriteTexture2D<>))]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task DeviceLost_AllocateTexture2D(Device device, Type textureType)
|
||||
{
|
||||
using GraphicsDevice graphicsDevice = device.Get();
|
||||
|
||||
await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice);
|
||||
|
||||
using Resources.Texture2D<float> _ = graphicsDevice.AllocateTexture2D<float>(textureType, 128, 128);
|
||||
}
|
||||
|
||||
[CombinatorialTestMethod]
|
||||
[AllDevices]
|
||||
[Resource(typeof(ReadOnlyTexture3D<>))]
|
||||
[Resource(typeof(ReadWriteTexture3D<>))]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task DeviceLost_AllocateTexture3D(Device device, Type textureType)
|
||||
{
|
||||
using GraphicsDevice graphicsDevice = device.Get();
|
||||
|
||||
await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice);
|
||||
|
||||
using Resources.Texture3D<float> _ = graphicsDevice.AllocateTexture3D<float>(textureType, 128, 128, 3);
|
||||
}
|
||||
|
||||
[CombinatorialTestMethod]
|
||||
[AllDevices]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task DeviceLost_IsDoublePrecisionSupportAvailable(Device device)
|
||||
{
|
||||
using GraphicsDevice graphicsDevice = device.Get();
|
||||
|
||||
await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice);
|
||||
|
||||
_ = graphicsDevice.IsDoublePrecisionSupportAvailable();
|
||||
}
|
||||
|
||||
[CombinatorialTestMethod]
|
||||
[AllDevices]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task DeviceLost_IsReadOnlyTexture2DSupportedForType(Device device)
|
||||
{
|
||||
using GraphicsDevice graphicsDevice = device.Get();
|
||||
|
||||
await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice);
|
||||
|
||||
_ = graphicsDevice.IsReadOnlyTexture2DSupportedForType<float>();
|
||||
}
|
||||
|
||||
[CombinatorialTestMethod]
|
||||
[AllDevices]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task DeviceLost_IsReadWriteTexture2DSupportedForType(Device device)
|
||||
{
|
||||
using GraphicsDevice graphicsDevice = device.Get();
|
||||
|
||||
await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice);
|
||||
|
||||
_ = graphicsDevice.IsReadWriteTexture2DSupportedForType<float>();
|
||||
}
|
||||
|
||||
[CombinatorialTestMethod]
|
||||
[AllDevices]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task DeviceLost_IsReadOnlyTexture3DSupportedForType(Device device)
|
||||
{
|
||||
using GraphicsDevice graphicsDevice = device.Get();
|
||||
|
||||
await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice);
|
||||
|
||||
_ = graphicsDevice.IsReadOnlyTexture3DSupportedForType<float>();
|
||||
}
|
||||
|
||||
[CombinatorialTestMethod]
|
||||
[AllDevices]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task DeviceLost_IsReadWriteTexture3DSupportedForType(Device device)
|
||||
{
|
||||
using GraphicsDevice graphicsDevice = device.Get();
|
||||
|
||||
await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice);
|
||||
|
||||
_ = graphicsDevice.IsReadWriteTexture3DSupportedForType<float>();
|
||||
}
|
||||
|
||||
[CombinatorialTestMethod]
|
||||
[AllDevices]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task DeviceLost_CreateComputeContext(Device device)
|
||||
{
|
||||
using GraphicsDevice graphicsDevice = device.Get();
|
||||
|
||||
await GraphicsDeviceHelper.RemoveDeviceAsync(graphicsDevice);
|
||||
|
||||
using ComputeContext _ = graphicsDevice.CreateComputeContext();
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
namespace ComputeSharp.Tests.Extensions;
|
||||
|
||||
/// <summary>
|
||||
/// A helper class for testing <see cref="GraphicsDevice"/> APIs.
|
||||
/// </summary>
|
||||
public static class DeviceExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets a <see cref="GraphicsDevice"/> instance matching a specified type.
|
||||
/// </summary>
|
||||
/// <param name="type">The device to retrieve.</param>
|
||||
/// <returns>The device of the requested type.</returns>
|
||||
/// <exception cref="AssertInconclusiveException">Thrown when the requested device is not present.</exception>
|
||||
public static GraphicsDevice Get(this Device type)
|
||||
{
|
||||
GraphicsDevice? device = type switch
|
||||
{
|
||||
Device.Discrete => GraphicsDevice.QueryDevices(info => info.IsHardwareAccelerated).FirstOrDefault(),
|
||||
Device.Warp => GraphicsDevice.QueryDevices(info => !info.IsHardwareAccelerated).FirstOrDefault(),
|
||||
_ => throw new ArgumentException("Invalid device type.", nameof(type))
|
||||
};
|
||||
|
||||
if (device is null)
|
||||
{
|
||||
// If the device is null, fail only if the device was WARP (as it should always be available).
|
||||
// If a dedicated device was requested instead, just report the test as inconclusive (no GPU).
|
||||
switch (type)
|
||||
{
|
||||
case Device.Discrete: Assert.Inconclusive(); break;
|
||||
case Device.Warp: Assert.Fail(); break;
|
||||
}
|
||||
}
|
||||
|
||||
return device!;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Indicates a specific compute device.
|
||||
/// </summary>
|
||||
public enum Device
|
||||
{
|
||||
/// <summary>
|
||||
/// A discrete device.
|
||||
/// </summary>
|
||||
Discrete,
|
||||
|
||||
/// <summary>
|
||||
/// A WARP device (software fallback).
|
||||
/// </summary>
|
||||
Warp
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using ComputeSharp.Tests.DeviceLost.Helpers;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using TerraFX.Interop.DirectX;
|
||||
using TerraFX.Interop.Windows;
|
||||
|
||||
namespace ComputeSharp.Tests.DeviceLost;
|
||||
|
||||
[TestClass]
|
||||
public class GetDefaultDeviceTests
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task GetDefault_VerifyContract()
|
||||
{
|
||||
GraphicsDevice device1 = GraphicsDevice.GetDefault();
|
||||
|
||||
// The default device is never null (or the previous call would've thrown an exception)
|
||||
Assert.IsNotNull(device1);
|
||||
|
||||
using (ComPtr<ID3D12Device> d3D12Device = default)
|
||||
{
|
||||
GraphicsDeviceHelper.GetD3D12Device(device1, in d3D12Device);
|
||||
|
||||
GraphicsDevice device2 = GraphicsDevice.GetDefault();
|
||||
|
||||
// Assuming the device hasn't been disposed (tests don't run concurrently), calling
|
||||
// GraphicsDevice.GetDefault() again will always return the same cached instance.
|
||||
Assert.AreSame(device1, device2);
|
||||
|
||||
await GraphicsDeviceHelper.RemoveDeviceAsync(device1);
|
||||
|
||||
// The device is lost but not disposed, so the same instance should be returned yet again
|
||||
GraphicsDevice device3 = GraphicsDevice.GetDefault();
|
||||
|
||||
Assert.AreSame(device1, device3);
|
||||
|
||||
// Dispose the device, which should make its actual release logic execute
|
||||
device1.Dispose();
|
||||
|
||||
// The device is correctly marked as disposed
|
||||
_ = Assert.ThrowsException<ObjectDisposedException>(() => device1.IsDoublePrecisionSupportAvailable());
|
||||
|
||||
// Now there should just be this one last reference left to the native device
|
||||
Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(in d3D12Device));
|
||||
}
|
||||
|
||||
// Calling GraphicsDevice.GetDefault() after disposing it should always succeed...
|
||||
GraphicsDevice device4 = GraphicsDevice.GetDefault();
|
||||
|
||||
// But it will return a new instance (assuming the device has been disposed properly).
|
||||
// That is, the caller has to ensure that no other object is keeping the device alive.
|
||||
Assert.AreNotSame(device1, device4);
|
||||
|
||||
// The LUID should match though, as the same adapter should be returned
|
||||
Assert.AreEqual(device1.Luid, device4.Luid);
|
||||
|
||||
await GraphicsDeviceHelper.RemoveDeviceAsync(device4);
|
||||
|
||||
using (ComPtr<ID3D12Device> d3D12Device = default)
|
||||
{
|
||||
GraphicsDeviceHelper.GetD3D12Device(device4, in d3D12Device);
|
||||
|
||||
device4.Dispose();
|
||||
|
||||
// The device is correctly marked as disposed
|
||||
_ = Assert.ThrowsException<ObjectDisposedException>(() => device4.IsDoublePrecisionSupportAvailable());
|
||||
|
||||
// Sanity check that this is in fact the only reference keeping the device alive
|
||||
Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(in d3D12Device));
|
||||
|
||||
unsafe
|
||||
{
|
||||
HRESULT removalReason = d3D12Device.Get()->GetDeviceRemovedReason();
|
||||
|
||||
// Sanity check that the device is in fact removed
|
||||
Assert.AreEqual(DXGI.DXGI_ERROR_DEVICE_REMOVED, (int)removalReason);
|
||||
}
|
||||
|
||||
// Calling GraphicsDevice.GetDefault() will now throw, because the native device has not been disposed properly
|
||||
_ = Assert.ThrowsException<InvalidOperationException>(GraphicsDevice.GetDefault);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void GetDefault_DisposeAndUseNewInstance()
|
||||
{
|
||||
GraphicsDevice device1 = GraphicsDevice.GetDefault();
|
||||
|
||||
using (ComPtr<ID3D12Device> d3D12Device = default)
|
||||
{
|
||||
using (device1.AllocateReadOnlyBuffer<float>(128))
|
||||
{
|
||||
}
|
||||
|
||||
GraphicsDeviceHelper.GetD3D12Device(device1, in d3D12Device);
|
||||
|
||||
device1.Dispose();
|
||||
|
||||
Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(in d3D12Device));
|
||||
}
|
||||
|
||||
// Just same test but twice, just for good measure
|
||||
using (ComPtr<ID3D12Device> d3D12Device = default)
|
||||
{
|
||||
GraphicsDevice device2 = GraphicsDevice.GetDefault();
|
||||
|
||||
Assert.AreNotSame(device1, device2);
|
||||
|
||||
using (device2.AllocateReadOnlyBuffer<float>(128))
|
||||
{
|
||||
}
|
||||
|
||||
GraphicsDeviceHelper.GetD3D12Device(device2, in d3D12Device);
|
||||
|
||||
device2.Dispose();
|
||||
|
||||
Assert.AreEqual(1u, GraphicsDeviceHelper.GetD3D12DeviceRefCount(in d3D12Device));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using ComputeSharp.Interop;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using TerraFX.Interop.DirectX;
|
||||
using TerraFX.Interop.Windows;
|
||||
|
||||
namespace ComputeSharp.Tests.DeviceLost.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// A helper to do common checks on native device objects.
|
||||
/// </summary>
|
||||
internal static class GraphicsDeviceHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the underlying <see cref="ID3D12Device"/> object from a <see cref="GraphicsDevice"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="graphicsDevice">The input <see cref="GraphicsDevice"/> instance.</param>
|
||||
/// <param name="d3D12Device">The underlying <see cref="ID3D12Device"/> object for <paramref name="graphicsDevice"/>.</param>
|
||||
public static unsafe void GetD3D12Device(GraphicsDevice graphicsDevice, in ComPtr<ID3D12Device> d3D12Device)
|
||||
{
|
||||
fixed (ID3D12Device** ppvObject = d3D12Device)
|
||||
{
|
||||
InteropServices.GetID3D12Device(graphicsDevice, Windows.__uuidof<ID3D12Device>(), (void**)ppvObject);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the reference count for a given <see cref="ID3D12Device"/> object.
|
||||
/// </summary>
|
||||
/// <param name="d3D12Device">The target <see cref="ID3D12Device"/> object to get the reference count for.</param>
|
||||
public static unsafe uint GetD3D12DeviceRefCount(in ComPtr<ID3D12Device> d3D12Device)
|
||||
{
|
||||
// Tests using this helper have to ensure a GraphicsDevice instance correctly destroys the underlying
|
||||
// device when disposed. To verify this, we first get the underlying ID3D12Device* object, which causes
|
||||
// its reference count to be incremented by 1. Assuming GraphicsDevice is working correctly, once
|
||||
// it is disposed, the underlying ID3D12Device* object should have its ref count set to just 1,
|
||||
// which is the one we added when doing QueryInterface on it. To verify this, we first increment
|
||||
// that, and then release it to get the updated count. If everything is correct, the ref count
|
||||
// we got back should be 1, with the last one just being from our own ID3D12Device* local. We
|
||||
// can't just do Release() and check that, as that'd cause the ref count to just go to 0 but
|
||||
// without clearing the pointer stored in the ComPtr<T> local, which would then crash when
|
||||
// going out of scope and trying to dereference that object to call Release() on it.
|
||||
_ = d3D12Device.Get()->AddRef();
|
||||
|
||||
return d3D12Device.Get()->Release();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the underlying device for a given <see cref="GraphicsDevice"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="graphicsDevice">The target <see cref="GraphicsDevice"/> instance.</param>
|
||||
public static unsafe void RemoveDevice(GraphicsDevice graphicsDevice)
|
||||
{
|
||||
ID3D12Device5* d3D12Device = default;
|
||||
Guid d3D12Device5Guid = typeof(ID3D12Device5).GUID;
|
||||
|
||||
if (InteropServices.TryGetID3D12Device(graphicsDevice, &d3D12Device5Guid, (void**)&d3D12Device) != 0)
|
||||
{
|
||||
Assert.Inconclusive();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
d3D12Device->RemoveDevice();
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (d3D12Device is not null)
|
||||
{
|
||||
_ = d3D12Device->Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the underlying device for a given <see cref="GraphicsDevice"/> instance and waits for it to be reported.
|
||||
/// </summary>
|
||||
/// <param name="graphicsDevice">The target <see cref="GraphicsDevice"/> instance.</param>
|
||||
/// <remarks>
|
||||
/// Removing a device will cause the device removed callback to be invoked on a separate thread, to get a
|
||||
/// reference tracking lease for the device and then raise the event. If this is not awaited, it means
|
||||
/// that that callback might race against a thread just calling Dispose(), so that that thread would not
|
||||
/// actually cause the object to release resources until the device removed callback has also released its
|
||||
/// own lease. To avoid issues related to this, the event should always be awaited after removing a device.
|
||||
/// </remarks>
|
||||
public static async Task RemoveDeviceAsync(GraphicsDevice graphicsDevice)
|
||||
{
|
||||
TaskCompletionSource<object?> tcs = new();
|
||||
|
||||
graphicsDevice.DeviceLost += (s, e) => tcs.SetResult(null);
|
||||
|
||||
RemoveDevice(graphicsDevice);
|
||||
|
||||
_ = await tcs.Task;
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
[assembly: DoNotParallelize]
|
||||
@@ -1,29 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoConstructor" Version="5.6.0" PrivateAssets="all" />
|
||||
<PackageReference Include="MSTest" Version="3.8.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.Core\ComputeSharp.Core.csproj" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.Core.SourceGenerators\ComputeSharp.Core.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp\ComputeSharp.csproj" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\ComputeSharp.Tests\Attributes\AdditionalDataAttribute.cs" Link="Attributes\AdditionalDataAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp.Tests\Attributes\AdditionalResourceAttribute.cs" Link="Attributes\AdditionalResourceAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp.Tests\Attributes\AllDevicesAttribute.cs" Link="Attributes\AllDevicesAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp.Tests\Attributes\CombinatorialTestMethodAttribute.cs" Link="Attributes\CombinatorialTestMethodAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp.Tests\Attributes\DataAttribute.cs" Link="Attributes\DataAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp.Tests\Attributes\DeviceAttribute.cs" Link="Attributes\DeviceAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp.Tests\Attributes\ResourceAttribute.cs" Link="Attributes\ResourceAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp.Tests\Extensions\DeviceExtensions.cs" Link="Extensions\DeviceExtensions.cs" />
|
||||
<Compile Include="..\ComputeSharp.Tests\Extensions\GraphicsDeviceExtensions.cs" Link="Extensions\GraphicsDeviceExtensions.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,91 +0,0 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using ComputeSharp.Tests.Attributes;
|
||||
using ComputeSharp.Tests.Extensions;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
namespace ComputeSharp.Tests.DisableDynamicCompilation;
|
||||
|
||||
[TestClass]
|
||||
public partial class DispatchTests
|
||||
{
|
||||
[CombinatorialTestMethod]
|
||||
[AllDevices]
|
||||
public void ComputeShader_Test_Ok(Device device)
|
||||
{
|
||||
float[] array = Enumerable.Range(0, 128).Select(static i => (float)i).ToArray();
|
||||
|
||||
using ReadWriteBuffer<float> buffer = device.Get().AllocateReadWriteBuffer(array);
|
||||
|
||||
device.Get().For(128, 1, 1, new ComputeShader(buffer, 2.0f));
|
||||
|
||||
float[] result = buffer.ToArray();
|
||||
|
||||
foreach (ref float value in array.AsSpan())
|
||||
{
|
||||
value *= 2.0f;
|
||||
}
|
||||
|
||||
CollectionAssert.AreEqual(result, array);
|
||||
}
|
||||
|
||||
[AutoConstructor]
|
||||
[ThreadGroupSize(32, 1, 1)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct ComputeShader : IComputeShader
|
||||
{
|
||||
public readonly ReadWriteBuffer<float> buffer;
|
||||
public readonly float factor;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Execute()
|
||||
{
|
||||
this.buffer[ThreadIds.X] *= this.factor;
|
||||
}
|
||||
}
|
||||
|
||||
[CombinatorialTestMethod]
|
||||
[AllDevices]
|
||||
public void PixelShader_Test_Ok(Device device)
|
||||
{
|
||||
using ReadWriteTexture2D<Rgba32, float4> texture = device.Get().AllocateReadWriteTexture2D<Rgba32, float4>(128, 128);
|
||||
|
||||
device.Get().ForEach(texture, new PixelShader(0.3f, 0.6f));
|
||||
|
||||
Rgba32[,] result = texture.ToArray();
|
||||
|
||||
for (int i = 0; i < texture.Height; i++)
|
||||
{
|
||||
for (int j = 0; j < texture.Width; j++)
|
||||
{
|
||||
byte r = (byte)(j / (float)(texture.Width - 1) * 255f);
|
||||
byte g = (byte)(i / (float)(texture.Height - 1) * 255f);
|
||||
const byte b = (byte)(0.3f * 255f);
|
||||
const byte a = (byte)(0.6f * 255f);
|
||||
Rgba32 pixel = result[i, j];
|
||||
|
||||
// Use a delta of 1 to account for small differences of precision when rounding. This test is just
|
||||
// about validating the shader runs anyway, the actual accuracy is tested in other shader tests.
|
||||
Assert.IsTrue(Math.Abs(r - pixel.R) <= 1);
|
||||
Assert.IsTrue(Math.Abs(g - pixel.G) <= 1);
|
||||
Assert.AreEqual(pixel.B, b);
|
||||
Assert.AreEqual(pixel.A, a);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[AutoConstructor]
|
||||
[ThreadGroupSize(8, 8, 1)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct PixelShader : IComputeShader<float4>
|
||||
{
|
||||
private readonly float b;
|
||||
private readonly float a;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public float4 Execute()
|
||||
{
|
||||
return new(ThreadIds.Normalized.X, ThreadIds.Normalized.Y, this.b, this.a);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.Core\ComputeSharp.Core.csproj" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.Core.SourceGenerators\ComputeSharp.Core.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp\ComputeSharp.csproj" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,37 +0,0 @@
|
||||
using ComputeSharp;
|
||||
|
||||
float[] numbers = [.. Enumerable.Range(0, 128)];
|
||||
|
||||
using GraphicsDevice device = GraphicsDevice.GetDefault();
|
||||
using ReadWriteBuffer<float> buffer = device.AllocateReadWriteBuffer(numbers);
|
||||
|
||||
device.For(buffer.Length, new ApplyFunctionShader(buffer));
|
||||
|
||||
foreach (ref float number in numbers.AsSpan())
|
||||
{
|
||||
number = ApplyFunctionShader.AddHalf(number);
|
||||
}
|
||||
|
||||
float[] result = buffer.ToArray();
|
||||
|
||||
if (!numbers.SequenceEqual(result))
|
||||
{
|
||||
throw new Exception("The processed buffer does not match the expected results.");
|
||||
}
|
||||
|
||||
Console.WriteLine("Test passed successfully!");
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
public readonly partial struct ApplyFunctionShader(ReadWriteBuffer<float> sourceTexture) : IComputeShader
|
||||
{
|
||||
public static float AddHalf(float input)
|
||||
{
|
||||
return input + 0.5f;
|
||||
}
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
sourceTexture[ThreadIds.X] = AddHalf(sourceTexture[ThreadIds.X]);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MSTest" Version="3.8.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Remove="Project\*" />
|
||||
<None Include="Project\*" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,36 +0,0 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using ComputeSharp.Tests.NativeLibrariesResolver.Helpers;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
namespace ComputeSharp.Tests.NativeLibrariesResolver;
|
||||
|
||||
[TestClass]
|
||||
public class DxcNativeLibrariesResolverTests : NativeLibrariesResolverTestsBase
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
protected override string SampleProjectName => "ComputeSharp.Dxc.NuGet";
|
||||
|
||||
/// <summary>
|
||||
/// Performs static initialization for the assembly before any unit tests are run.
|
||||
/// </summary>
|
||||
/// <param name="_">The <see cref="TestContext"/> for the test runner instance in use.</param>
|
||||
[ClassInitialize]
|
||||
public static void InitializeDynamicDependencies(TestContext _)
|
||||
{
|
||||
string path = Path.GetDirectoryName(typeof(DxcNativeLibrariesResolverTests).Assembly.Location)!;
|
||||
|
||||
while (Path.GetFileName(path) is not "ComputeSharp")
|
||||
{
|
||||
path = Path.GetDirectoryName(path)!;
|
||||
}
|
||||
|
||||
string coreProjectPath = Path.Combine(path, "src", "ComputeSharp.Core", "ComputeSharp.Core.csproj");
|
||||
string projectPath = Path.Combine(path, "src", "ComputeSharp", "ComputeSharp.csproj");
|
||||
string dxcProjectPath = Path.Combine(path, "src", "ComputeSharp.Dxc", "ComputeSharp.Dxc.csproj");
|
||||
|
||||
Process.Start("dotnet", $"pack {coreProjectPath} -c Release").WaitForExit();
|
||||
Process.Start("dotnet", $"pack {projectPath} -c Release").WaitForExit();
|
||||
Process.Start("dotnet", $"pack {dxcProjectPath} -c Release").WaitForExit();
|
||||
}
|
||||
}
|
||||
@@ -1,299 +0,0 @@
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
namespace ComputeSharp.Tests.NativeLibrariesResolver.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// A base class to implement native libraries tests.
|
||||
/// </summary>
|
||||
public abstract class NativeLibrariesResolverTestsBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the name of the test project.
|
||||
/// </summary>
|
||||
protected abstract string SampleProjectName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the directory containing the current test project.
|
||||
/// </summary>
|
||||
private string SampleProjectDirectory
|
||||
{
|
||||
get
|
||||
{
|
||||
string path = Path.GetDirectoryName(typeof(NativeLibrariesResolverTestsBase).Assembly.Location)!;
|
||||
|
||||
while (Path.GetFileName(path) is not "tests")
|
||||
{
|
||||
path = Path.GetDirectoryName(path)!;
|
||||
}
|
||||
|
||||
return Path.Combine(path, SampleProjectName);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(Configuration.Debug, RID.None)]
|
||||
[DataRow(Configuration.Debug, RID.Win_x64)]
|
||||
[DataRow(Configuration.Release, RID.None)]
|
||||
[DataRow(Configuration.Release, RID.Win_x64)]
|
||||
public void DotnetRunWorks(Configuration configuration, RID rid)
|
||||
{
|
||||
CleanSampleProject(configuration, rid);
|
||||
|
||||
Assert.AreEqual(0, Exec(SampleProjectDirectory, "dotnet", $"run -c {configuration} {ToOption(rid)}"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(Configuration.Debug, RID.None)]
|
||||
[DataRow(Configuration.Debug, RID.Win_x64)]
|
||||
[DataRow(Configuration.Release, RID.None)]
|
||||
[DataRow(Configuration.Release, RID.Win_x64)]
|
||||
public void DotnetBuildWithRunningDotnetHostFromProjectDirectoryWorks(Configuration configuration, RID rid)
|
||||
{
|
||||
CleanSampleProject(configuration, rid);
|
||||
BuildSampleProject(configuration, rid);
|
||||
|
||||
string realtivePathToDll = Path.Combine("bin", $"{configuration}", "net8.0", $"{ToDirectory(rid)}", $"{SampleProjectName}.dll");
|
||||
|
||||
Assert.AreEqual(0, Exec(SampleProjectDirectory, "dotnet", realtivePathToDll));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(Configuration.Debug, RID.None)]
|
||||
[DataRow(Configuration.Debug, RID.Win_x64)]
|
||||
[DataRow(Configuration.Release, RID.None)]
|
||||
[DataRow(Configuration.Release, RID.Win_x64)]
|
||||
public void DotnetBuildWithRunningDotnetHostDirectlyWorks(Configuration configuration, RID rid)
|
||||
{
|
||||
CleanSampleProject(configuration, rid);
|
||||
BuildSampleProject(configuration, rid);
|
||||
|
||||
string pathToDllDirectory = Path.Combine(SampleProjectDirectory, "bin", $"{configuration}", "net8.0", $"{ToDirectory(rid)}");
|
||||
|
||||
Assert.AreEqual(0, Exec(pathToDllDirectory, "dotnet", $"{SampleProjectName}.dll"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(Configuration.Debug, RID.None)]
|
||||
[DataRow(Configuration.Debug, RID.Win_x64)]
|
||||
[DataRow(Configuration.Release, RID.None)]
|
||||
[DataRow(Configuration.Release, RID.Win_x64)]
|
||||
public void DotnetBuildWithRunningAppHostFromProjectDirectoryWorks(Configuration configuration, RID rid)
|
||||
{
|
||||
CleanSampleProject(configuration, rid);
|
||||
BuildSampleProject(configuration, rid);
|
||||
|
||||
string relativePathToAppHost = Path.Combine("bin", $"{configuration}", "net8.0", $"{ToDirectory(rid)}", $"{SampleProjectName}.exe");
|
||||
|
||||
Assert.AreEqual(0, Exec(SampleProjectDirectory, relativePathToAppHost, ""));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(Configuration.Debug, RID.None)]
|
||||
[DataRow(Configuration.Debug, RID.Win_x64)]
|
||||
[DataRow(Configuration.Release, RID.None)]
|
||||
[DataRow(Configuration.Release, RID.Win_x64)]
|
||||
public void DotnetBuildWithRunningAppHostDirectlyWorks(Configuration configuration, RID rid)
|
||||
{
|
||||
CleanSampleProject(configuration, rid);
|
||||
BuildSampleProject(configuration, rid);
|
||||
|
||||
string pathToAppHostDirectory = Path.Combine(SampleProjectDirectory, "bin", $"{configuration}", "net8.0", $"{ToDirectory(rid)}");
|
||||
|
||||
Assert.AreEqual(0, Exec(pathToAppHostDirectory, $"{SampleProjectName}.exe", ""));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(PublishMode.SelfContained, DeploymentMode.Multiassembly, NativeLibrariesDeploymentMode.NotApplicable)]
|
||||
[DataRow(PublishMode.FrameworkDependent, DeploymentMode.Multiassembly, NativeLibrariesDeploymentMode.NotApplicable)]
|
||||
[DataRow(PublishMode.SelfContained, DeploymentMode.SingleFile, NativeLibrariesDeploymentMode.CopyToApplicationDirectory)]
|
||||
[DataRow(PublishMode.SelfContained, DeploymentMode.SingleFile, NativeLibrariesDeploymentMode.ExtractToTemporaryDirectory)]
|
||||
[DataRow(PublishMode.FrameworkDependent, DeploymentMode.SingleFile, NativeLibrariesDeploymentMode.CopyToApplicationDirectory)]
|
||||
[DataRow(PublishMode.FrameworkDependent, DeploymentMode.SingleFile, NativeLibrariesDeploymentMode.ExtractToTemporaryDirectory)]
|
||||
public void DotnetPublishWorks(PublishMode publishMode, DeploymentMode deploymentMode, NativeLibrariesDeploymentMode nativeLibsDeploymentMode)
|
||||
{
|
||||
// Publishing without specifying a RID is not supported.
|
||||
// Furthermore, only publishing in Release mode is tested.
|
||||
CleanSampleProject(Configuration.Release, RID.Win_x64);
|
||||
|
||||
_ = Exec(SampleProjectDirectory, "dotnet", $"publish -c Release -r win-x64 {ToOption(publishMode)} {ToOption(deploymentMode)} {ToOption(nativeLibsDeploymentMode)} /bl");
|
||||
|
||||
string pathToAppHost = Path.Combine("bin", $"Release", "net8.0", "win-x64", "publish", $"{SampleProjectName}.exe");
|
||||
|
||||
Assert.AreEqual(0, Exec(SampleProjectDirectory, pathToAppHost, ""));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cleans the sample project's artifacts for a specific configuration and target runtime.
|
||||
/// This method is called at the start of each test method to work around bugs around some up-to-date checks
|
||||
/// Causing certain targets to not run and effectively corrupting the build output.
|
||||
/// </summary>
|
||||
/// <param name="configuration">The configuration for which the output is cleaned.</param>
|
||||
/// <param name="rid">The RID for which the output is cleaned.</param>
|
||||
private void CleanSampleProject(Configuration configuration, RID rid)
|
||||
{
|
||||
_ = Exec(SampleProjectDirectory, "dotnet", $"clean -c {configuration} {ToOption(rid)}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the sample project with a specific configuration and target runtime.
|
||||
/// </summary>
|
||||
/// <param name="configuration">The configuration to use to build the project.</param>
|
||||
/// <param name="rid">The RID to use to build the project.</param>
|
||||
private void BuildSampleProject(Configuration configuration, RID rid)
|
||||
{
|
||||
_ = Exec(SampleProjectDirectory, "dotnet", $"build -c {configuration} {ToOption(rid)}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes a specified process from the command line and returns the exit code.
|
||||
/// </summary>
|
||||
/// <param name="workingDirectory">The working directory to execute the process.</param>
|
||||
/// <param name="filePath">The target file path for the process to execute.</param>
|
||||
/// <param name="arguments">The arguments to invoke the process.</param>
|
||||
/// <returns>The exit code for the executed process.</returns>
|
||||
private static int Exec(string workingDirectory, string filePath, string arguments)
|
||||
{
|
||||
ProcessStartInfo startInfo = new()
|
||||
{
|
||||
UseShellExecute = true,
|
||||
CreateNoWindow = true,
|
||||
WindowStyle = ProcessWindowStyle.Hidden,
|
||||
FileName = filePath,
|
||||
Arguments = arguments,
|
||||
WorkingDirectory = workingDirectory
|
||||
};
|
||||
|
||||
using Process process = Process.Start(startInfo)!;
|
||||
|
||||
process.WaitForExit();
|
||||
|
||||
return process.ExitCode;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a text representation of the command line argument for the given <see cref="RID"/>.
|
||||
/// </summary>
|
||||
/// <param name="rid">The input <see cref="RID"/> value.</param>
|
||||
/// <returns>A text representation for <paramref name="rid"/>.</returns>
|
||||
private static string ToOption(RID rid)
|
||||
{
|
||||
return rid switch
|
||||
{
|
||||
RID.None => "",
|
||||
RID.Win_x64 => "-r win-x64",
|
||||
_ => throw new InvalidEnumArgumentException(nameof(rid), (int)rid, typeof(RID))
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a text representation of the command line argument for the given <see cref="PublishMode"/>.
|
||||
/// </summary>
|
||||
/// <param name="publishMode">The input <see cref="PublishMode"/> value.</param>
|
||||
/// <returns>A text representation for <paramref name="publishMode"/>.</returns>
|
||||
private static string ToOption(PublishMode publishMode)
|
||||
{
|
||||
return publishMode switch
|
||||
{
|
||||
PublishMode.FrameworkDependent => "--self-contained false",
|
||||
PublishMode.SelfContained => "--self-contained true",
|
||||
_ => throw new InvalidEnumArgumentException(nameof(publishMode), (int)publishMode, typeof(PublishMode))
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a text representation of the command line argument for the given <see cref="DeploymentMode"/>.
|
||||
/// </summary>
|
||||
/// <param name="deploymentMode">The input <see cref="DeploymentMode"/> value.</param>
|
||||
/// <returns>A text representation for <paramref name="deploymentMode"/>.</returns>
|
||||
private static string ToOption(DeploymentMode deploymentMode)
|
||||
{
|
||||
return deploymentMode switch
|
||||
{
|
||||
DeploymentMode.Multiassembly => "/p:PublishSingleFile=false",
|
||||
DeploymentMode.SingleFile => "/p:PublishSingleFile=true",
|
||||
_ => throw new InvalidEnumArgumentException(nameof(deploymentMode), (int)deploymentMode, typeof(DeploymentMode))
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a text representation of the command line argument for the given <see cref="NativeLibrariesDeploymentMode"/>.
|
||||
/// </summary>
|
||||
/// <param name="deploymentMode">The input <see cref="NativeLibrariesDeploymentMode"/> value.</param>
|
||||
/// <returns>A text representation for <paramref name="deploymentMode"/>.</returns>
|
||||
private static string ToOption(NativeLibrariesDeploymentMode deploymentMode)
|
||||
{
|
||||
return deploymentMode switch
|
||||
{
|
||||
NativeLibrariesDeploymentMode.NotApplicable => "",
|
||||
NativeLibrariesDeploymentMode.CopyToApplicationDirectory => "/p:IncludeNativeLibrariesForSelfExtract=false",
|
||||
NativeLibrariesDeploymentMode.ExtractToTemporaryDirectory => "/p:IncludeNativeLibrariesForSelfExtract=true",
|
||||
_ => throw new InvalidEnumArgumentException(nameof(deploymentMode), (int)deploymentMode, typeof(NativeLibrariesDeploymentMode))
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a text representation of the build folder for the given <see cref="RID"/>.
|
||||
/// </summary>
|
||||
/// <param name="rid">The input <see cref="RID"/> value.</param>
|
||||
/// <returns>A text representation for <paramref name="rid"/>.</returns>
|
||||
private static string ToDirectory(RID rid)
|
||||
{
|
||||
return rid switch
|
||||
{
|
||||
RID.None => "",
|
||||
RID.Win_x64 => "win-x64",
|
||||
_ => throw new InvalidEnumArgumentException(nameof(rid), (int)rid, typeof(RID))
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A build configuration.
|
||||
/// </summary>
|
||||
public enum Configuration
|
||||
{
|
||||
Debug,
|
||||
Release
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A runtime identifier.
|
||||
/// </summary>
|
||||
public enum RID
|
||||
{
|
||||
None,
|
||||
Win_x64
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Indicates how should the application carry the framework with itself.
|
||||
/// </summary>
|
||||
public enum PublishMode
|
||||
{
|
||||
FrameworkDependent,
|
||||
SelfContained
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Indicates how should the application be packaged. Notably, these tests employ .NET 8 style SingleFile,
|
||||
/// aka SuperHost. It does not affect native libraries packaging in .NET 8, but may in the future.
|
||||
/// </summary>
|
||||
public enum DeploymentMode
|
||||
{
|
||||
Multiassembly,
|
||||
SingleFile
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Indicates the deployment mode for application's native dependencies.
|
||||
/// Not applicable to multiassembly deployment mode.
|
||||
/// </summary>
|
||||
public enum NativeLibrariesDeploymentMode
|
||||
{
|
||||
NotApplicable,
|
||||
ExtractToTemporaryDirectory,
|
||||
CopyToApplicationDirectory
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using ComputeSharp.Tests.NativeLibrariesResolver.Helpers;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
namespace ComputeSharp.Tests.NativeLibrariesResolver;
|
||||
|
||||
[TestClass]
|
||||
public class NativeLibrariesResolverTests : NativeLibrariesResolverTestsBase
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
protected override string SampleProjectName => "ComputeSharp.NuGet";
|
||||
|
||||
/// <summary>
|
||||
/// Performs static initialization for the assembly before any unit tests are run.
|
||||
/// </summary>
|
||||
/// <param name="_">The <see cref="TestContext"/> for the test runner instance in use.</param>
|
||||
[ClassInitialize]
|
||||
public static void InitializeDynamicDependencies(TestContext _)
|
||||
{
|
||||
string path = Path.GetDirectoryName(typeof(DxcNativeLibrariesResolverTests).Assembly.Location)!;
|
||||
|
||||
while (Path.GetFileName(path) is not "ComputeSharp")
|
||||
{
|
||||
path = Path.GetDirectoryName(path)!;
|
||||
}
|
||||
|
||||
string coreProjectPath = Path.Combine(path, "src", "ComputeSharp.Core", "ComputeSharp.Core.csproj");
|
||||
string projectPath = Path.Combine(path, "src", "ComputeSharp", "ComputeSharp.csproj");
|
||||
|
||||
Process.Start("dotnet", $"pack {coreProjectPath} -c Release").WaitForExit();
|
||||
Process.Start("dotnet", $"pack {projectPath} -c Release").WaitForExit();
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using ComputeSharp.Tests.NativeLibrariesResolver.Helpers;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
namespace ComputeSharp.Tests.NativeLibrariesResolver;
|
||||
|
||||
[TestClass]
|
||||
public class PixNativeLibrariesResolverTests : NativeLibrariesResolverTestsBase
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
protected override string SampleProjectName => "ComputeSharp.Pix.NuGet";
|
||||
|
||||
/// <summary>
|
||||
/// Performs static initialization for the assembly before any unit tests are run.
|
||||
/// </summary>
|
||||
/// <param name="_">The <see cref="TestContext"/> for the test runner instance in use.</param>
|
||||
[ClassInitialize]
|
||||
public static void InitializeDynamicDependencies(TestContext _)
|
||||
{
|
||||
string path = Path.GetDirectoryName(typeof(PixNativeLibrariesResolverTests).Assembly.Location)!;
|
||||
|
||||
while (Path.GetFileName(path) is not "ComputeSharp")
|
||||
{
|
||||
path = Path.GetDirectoryName(path)!;
|
||||
}
|
||||
|
||||
string coreProjectPath = Path.Combine(path, "src", "ComputeSharp.Core", "ComputeSharp.Core.csproj");
|
||||
string projectPath = Path.Combine(path, "src", "ComputeSharp", "ComputeSharp.csproj");
|
||||
string pixProjectPath = Path.Combine(path, "src", "ComputeSharp.Pix", "ComputeSharp.Pix.csproj");
|
||||
|
||||
// Run dotnet pack and on the packaging projects, to ensure the local NuGet packages are available
|
||||
Process.Start("dotnet", $"pack {coreProjectPath} -c Release").WaitForExit();
|
||||
Process.Start("dotnet", $"pack {projectPath} -c Release").WaitForExit();
|
||||
Process.Start("dotnet", $"pack {pixProjectPath} -c Release").WaitForExit();
|
||||
}
|
||||
}
|
||||