54ファイル変更
+1255
-740
検索条件に一致するファイルはありません
+67
-12
@@ -17,8 +17,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Benchmark", "s
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.ImageProcessing", "samples\ComputeSharp.ImageProcessing\ComputeSharp.ImageProcessing.csproj", "{524CC5DD-1DEE-4A30-9515-AB90965E5207}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Sample", "samples\ComputeSharp.Sample\ComputeSharp.Sample.csproj", "{7A48A85D-8866-4DED-A404-653ED09BF396}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Tests", "tests\ComputeSharp.Tests\ComputeSharp.Tests.csproj", "{E91F4D24-922A-4921-A8D7-9C45A143C45D}"
|
||||
@@ -28,13 +26,33 @@ EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_SolutionItems", "_SolutionItems", "{1A9C4108-F61A-4ABE-B5CF-F524521EAE2D}"
|
||||
ProjectSection(SolutionItems) = preProject
|
||||
.gitignore = .gitignore
|
||||
global.json = global.json
|
||||
LICENSE = LICENSE
|
||||
README.md = README.md
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.SourceGenerators", "src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj", "{EB52CB67-4162-4722-874B-44EA8DA5450E}"
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.SourceGenerators", "src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj", "{EB52CB67-4162-4722-874B-44EA8DA5450E}"
|
||||
EndProject
|
||||
Project("{13B669BE-BB05-4DDF-9536-439F39A36129}") = "ComputeSharp.Package", "src\ComputeSharp.Package\ComputeSharp.Package.msbuildproj", "{0A6AE752-2A1D-40F8-B9E7-46B60F5321A3}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NuGet", "NuGet", "{FB17EF84-9208-47AC-921F-680CB1DAD8BA}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Sample.Local", "samples\ComputeSharp.Sample.Local\ComputeSharp.Sample.Local.csproj", "{7048DEEA-0A6F-46A0-B951-B682A8F1CB75}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Sample.NuGet", "samples\ComputeSharp.Sample.NuGet\ComputeSharp.Sample.NuGet.csproj", "{C423C061-64F7-4C12-8E5F-75C5351D6308}"
|
||||
EndProject
|
||||
Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "ComputeSharp.Sample.Shared", "samples\ComputeSharp.Sample.Shared\ComputeSharp.Sample.Shared.shproj", "{8CEFC324-CA6C-4845-9AD9-70B92BD87057}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Tests.Internals.SourceGenerators", "tests\ComputeSharp.Tests.Internals.SourceGenerators\ComputeSharp.Tests.Internals.SourceGenerators.csproj", "{BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.Tests.NativeLibrariesResolver", "tests\ComputeSharp.Tests.NativeLibrariesResolver\ComputeSharp.Tests.NativeLibrariesResolver.csproj", "{BF52326F-E415-49E6-8595-62762216762B}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SharedMSBuildProjectFiles) = preSolution
|
||||
samples\ComputeSharp.Sample.Shared\ComputeSharp.Sample.Shared.projitems*{7048deea-0a6f-46a0-b951-b682a8f1cb75}*SharedItemsImports = 5
|
||||
samples\ComputeSharp.Sample.Shared\ComputeSharp.Sample.Shared.projitems*{8cefc324-ca6c-4845-9ad9-70b92bd87057}*SharedItemsImports = 13
|
||||
samples\ComputeSharp.Sample.Shared\ComputeSharp.Sample.Shared.projitems*{c423c061-64f7-4c12-8e5f-75c5351d6308}*SharedItemsImports = 5
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Debug|x64 = Debug|x64
|
||||
@@ -90,14 +108,6 @@ Global
|
||||
{524CC5DD-1DEE-4A30-9515-AB90965E5207}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{524CC5DD-1DEE-4A30-9515-AB90965E5207}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{524CC5DD-1DEE-4A30-9515-AB90965E5207}.Release|x64.Build.0 = Release|Any CPU
|
||||
{7A48A85D-8866-4DED-A404-653ED09BF396}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{7A48A85D-8866-4DED-A404-653ED09BF396}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{7A48A85D-8866-4DED-A404-653ED09BF396}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{7A48A85D-8866-4DED-A404-653ED09BF396}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{7A48A85D-8866-4DED-A404-653ED09BF396}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{7A48A85D-8866-4DED-A404-653ED09BF396}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{7A48A85D-8866-4DED-A404-653ED09BF396}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{7A48A85D-8866-4DED-A404-653ED09BF396}.Release|x64.Build.0 = Release|Any CPU
|
||||
{E91F4D24-922A-4921-A8D7-9C45A143C45D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{E91F4D24-922A-4921-A8D7-9C45A143C45D}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{E91F4D24-922A-4921-A8D7-9C45A143C45D}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
@@ -122,6 +132,46 @@ Global
|
||||
{EB52CB67-4162-4722-874B-44EA8DA5450E}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{EB52CB67-4162-4722-874B-44EA8DA5450E}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{EB52CB67-4162-4722-874B-44EA8DA5450E}.Release|x64.Build.0 = Release|Any CPU
|
||||
{0A6AE752-2A1D-40F8-B9E7-46B60F5321A3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{0A6AE752-2A1D-40F8-B9E7-46B60F5321A3}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{0A6AE752-2A1D-40F8-B9E7-46B60F5321A3}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{0A6AE752-2A1D-40F8-B9E7-46B60F5321A3}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{0A6AE752-2A1D-40F8-B9E7-46B60F5321A3}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{0A6AE752-2A1D-40F8-B9E7-46B60F5321A3}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{0A6AE752-2A1D-40F8-B9E7-46B60F5321A3}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{0A6AE752-2A1D-40F8-B9E7-46B60F5321A3}.Release|x64.Build.0 = Release|Any CPU
|
||||
{7048DEEA-0A6F-46A0-B951-B682A8F1CB75}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{7048DEEA-0A6F-46A0-B951-B682A8F1CB75}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{7048DEEA-0A6F-46A0-B951-B682A8F1CB75}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{7048DEEA-0A6F-46A0-B951-B682A8F1CB75}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{7048DEEA-0A6F-46A0-B951-B682A8F1CB75}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{7048DEEA-0A6F-46A0-B951-B682A8F1CB75}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{7048DEEA-0A6F-46A0-B951-B682A8F1CB75}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{7048DEEA-0A6F-46A0-B951-B682A8F1CB75}.Release|x64.Build.0 = Release|Any CPU
|
||||
{C423C061-64F7-4C12-8E5F-75C5351D6308}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{C423C061-64F7-4C12-8E5F-75C5351D6308}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{C423C061-64F7-4C12-8E5F-75C5351D6308}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{C423C061-64F7-4C12-8E5F-75C5351D6308}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{C423C061-64F7-4C12-8E5F-75C5351D6308}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{C423C061-64F7-4C12-8E5F-75C5351D6308}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{C423C061-64F7-4C12-8E5F-75C5351D6308}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{C423C061-64F7-4C12-8E5F-75C5351D6308}.Release|x64.Build.0 = Release|Any CPU
|
||||
{BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}.Release|x64.Build.0 = Release|Any CPU
|
||||
{BF52326F-E415-49E6-8595-62762216762B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{BF52326F-E415-49E6-8595-62762216762B}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{BF52326F-E415-49E6-8595-62762216762B}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{BF52326F-E415-49E6-8595-62762216762B}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{BF52326F-E415-49E6-8595-62762216762B}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{BF52326F-E415-49E6-8595-62762216762B}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{BF52326F-E415-49E6-8595-62762216762B}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{BF52326F-E415-49E6-8595-62762216762B}.Release|x64.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
@@ -129,9 +179,14 @@ Global
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{34AFE6E6-9A4C-4C3F-AE69-DD3693086DAF} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1}
|
||||
{524CC5DD-1DEE-4A30-9515-AB90965E5207} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1}
|
||||
{7A48A85D-8866-4DED-A404-653ED09BF396} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1}
|
||||
{E91F4D24-922A-4921-A8D7-9C45A143C45D} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7}
|
||||
{E889E6D6-A814-4950-AAC1-68F1ECFC5BD6} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7}
|
||||
{0A6AE752-2A1D-40F8-B9E7-46B60F5321A3} = {FB17EF84-9208-47AC-921F-680CB1DAD8BA}
|
||||
{7048DEEA-0A6F-46A0-B951-B682A8F1CB75} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1}
|
||||
{C423C061-64F7-4C12-8E5F-75C5351D6308} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1}
|
||||
{8CEFC324-CA6C-4845-9AD9-70B92BD87057} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1}
|
||||
{BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7}
|
||||
{BF52326F-E415-49E6-8595-62762216762B} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {4664C5E3-0340-4E22-BCFD-98AAEDF5F2DC}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"sdk": {
|
||||
"version": "5.0.100"
|
||||
}
|
||||
}
|
||||
@@ -3,5 +3,6 @@
|
||||
<packageSources>
|
||||
<add key="TerraFX-CI" value="https://pkgs.terrafx.dev/index.json" />
|
||||
<add key="BenchmarkDotNet-CI" value="https://ci.appveyor.com/nuget/benchmarkdotnet" />
|
||||
<add key="ComputeSharp-Local" value="src\ComputeSharp.Package\bin\Release" />
|
||||
</packageSources>
|
||||
</configuration>
|
||||
@@ -11,11 +11,10 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\ComputeSharp\ComputeSharp.csproj" />
|
||||
<ProjectReference
|
||||
Include="..\..\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj"
|
||||
OutputItemType="Analyzer"
|
||||
ReferenceOutputAssembly="false"
|
||||
PrivateAssets="contentfiles;build"/>
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj"
|
||||
OutputItemType="Analyzer"
|
||||
ReferenceOutputAssembly="false"
|
||||
PrivateAssets="contentfiles;build" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
</Project>
|
||||
@@ -73,15 +73,15 @@ namespace ComputeSharp.Benchmark
|
||||
/// Kernel for <see cref="FullyConnectedForwardGpu"/>.
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
private readonly partial struct FullyConnectedForwardKernel : IComputeShader
|
||||
public readonly partial struct FullyConnectedForwardKernel : IComputeShader
|
||||
{
|
||||
private readonly int n;
|
||||
private readonly int m;
|
||||
private readonly int p;
|
||||
private readonly ReadOnlyBuffer<float> x;
|
||||
private readonly ReadOnlyBuffer<float> w;
|
||||
private readonly ReadOnlyBuffer<float> b;
|
||||
private readonly ReadWriteBuffer<float> y;
|
||||
public readonly int n;
|
||||
public readonly int m;
|
||||
public readonly int p;
|
||||
public readonly ReadOnlyBuffer<float> x;
|
||||
public readonly ReadOnlyBuffer<float> w;
|
||||
public readonly ReadOnlyBuffer<float> b;
|
||||
public readonly ReadWriteBuffer<float> y;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Execute(ThreadIds ids)
|
||||
|
||||
@@ -6,13 +6,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Remove="city.jpg" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Include="city.jpg">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</Content>
|
||||
<Content Include="city.jpg" CopyToOutputDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -21,11 +15,10 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\ComputeSharp\ComputeSharp.csproj" />
|
||||
<ProjectReference
|
||||
Include="..\..\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj"
|
||||
OutputItemType="Analyzer"
|
||||
ReferenceOutputAssembly="false"
|
||||
PrivateAssets="contentfiles;build"/>
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj"
|
||||
OutputItemType="Analyzer"
|
||||
ReferenceOutputAssembly="false"
|
||||
PrivateAssets="contentfiles;build"/>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,4 +1,5 @@
|
||||
using SixLabors.ImageSharp;
|
||||
using System.Numerics;
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
using SixLabors.ImageSharp.Processing.Processors;
|
||||
|
||||
@@ -7,7 +8,7 @@ namespace ComputeSharp.BokehBlur.Processors
|
||||
/// <summary>
|
||||
/// Applies bokeh blur processing to the image.
|
||||
/// </summary>
|
||||
public sealed class HlslBokehBlurProcessor : IImageProcessor
|
||||
public sealed partial class HlslBokehBlurProcessor : IImageProcessor
|
||||
{
|
||||
/// <summary>
|
||||
/// The default radius used by the parameterless constructor.
|
||||
@@ -63,5 +64,87 @@ namespace ComputeSharp.BokehBlur.Processors
|
||||
{
|
||||
return new HlslBokehBlurProcessor<TPixel>(this, configuration, source, sourceRectangle);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Kernel for the vertical convolution pass.
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
internal partial struct VerticalConvolutionProcessor : IComputeShader
|
||||
{
|
||||
public int width;
|
||||
public int maxY;
|
||||
public int maxX;
|
||||
public int kernelLength;
|
||||
|
||||
public ReadOnlyBuffer<Vector4> source;
|
||||
public ReadWriteBuffer<ComplexVector4> target;
|
||||
public ReadOnlyBuffer<Complex64> kernel;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Execute(ThreadIds ids)
|
||||
{
|
||||
Vector4 real = Vector4.Zero;
|
||||
Vector4 imaginary = Vector4.Zero;
|
||||
int radiusY = kernelLength >> 1;
|
||||
int sourceOffsetColumnBase = ids.X;
|
||||
|
||||
for (int i = 0; i < kernelLength; i++)
|
||||
{
|
||||
int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY);
|
||||
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX);
|
||||
Vector4 color = source[offsetY * width + offsetX];
|
||||
Complex64 factors = kernel[i];
|
||||
|
||||
real += factors.Real * color;
|
||||
imaginary += factors.Imaginary * color;
|
||||
}
|
||||
|
||||
int offsetXY = ids.Y * width + ids.X;
|
||||
|
||||
target[offsetXY].Real = real;
|
||||
target[offsetXY].Imaginary = imaginary;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Kernel for the horizontal convolution pass.
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
internal partial struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader
|
||||
{
|
||||
public int width;
|
||||
public int maxY;
|
||||
public int maxX;
|
||||
public int kernelLength;
|
||||
public float z;
|
||||
public float w;
|
||||
|
||||
public ReadWriteBuffer<ComplexVector4> source;
|
||||
public ReadWriteBuffer<Vector4> target;
|
||||
public ReadOnlyBuffer<Complex64> kernel;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Execute(ThreadIds ids)
|
||||
{
|
||||
Vector4 real = Vector4.Zero;
|
||||
Vector4 imaginary = Vector4.Zero;
|
||||
int radiusX = kernelLength >> 1;
|
||||
int sourceOffsetColumnBase = ids.X;
|
||||
int offsetY = Hlsl.Clamp(ids.Y, 0, maxY);
|
||||
|
||||
for (int i = 0; i < kernelLength; i++)
|
||||
{
|
||||
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX);
|
||||
var offsetXY = offsetY * width + offsetX;
|
||||
ComplexVector4 source4 = source[offsetXY];
|
||||
Complex64 factors = kernel[i];
|
||||
|
||||
real += factors.Real * source4.Real - factors.Imaginary * source4.Imaginary;
|
||||
imaginary += factors.Real * source4.Imaginary + factors.Imaginary * source4.Real;
|
||||
}
|
||||
|
||||
target[ids.Y * width + ids.X] += real * z + imaginary * w;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -301,7 +301,7 @@ namespace ComputeSharp.BokehBlur.Processors
|
||||
int height = Source.Height;
|
||||
int width = Source.Width;
|
||||
|
||||
VerticalConvolutionProcessor shader = new(
|
||||
HlslBokehBlurProcessor.VerticalConvolutionProcessor shader = new(
|
||||
width,
|
||||
maxY: height - 1,
|
||||
maxX: width - 1,
|
||||
@@ -313,47 +313,6 @@ namespace ComputeSharp.BokehBlur.Processors
|
||||
Gpu.Default.For(width, height, in shader);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Kernel for <see cref="ApplyVerticalConvolution"/>.
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
private partial struct VerticalConvolutionProcessor : IComputeShader
|
||||
{
|
||||
public int width;
|
||||
public int maxY;
|
||||
public int maxX;
|
||||
public int kernelLength;
|
||||
|
||||
public ReadOnlyBuffer<Vector4> source;
|
||||
public ReadWriteBuffer<ComplexVector4> target;
|
||||
public ReadOnlyBuffer<Complex64> kernel;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Execute(ThreadIds ids)
|
||||
{
|
||||
Vector4 real = Vector4.Zero;
|
||||
Vector4 imaginary = Vector4.Zero;
|
||||
int radiusY = kernelLength >> 1;
|
||||
int sourceOffsetColumnBase = ids.X;
|
||||
|
||||
for (int i = 0; i < kernelLength; i++)
|
||||
{
|
||||
int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY);
|
||||
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX);
|
||||
Vector4 color = source[offsetY * width + offsetX];
|
||||
Complex64 factors = kernel[i];
|
||||
|
||||
real += factors.Real * color;
|
||||
imaginary += factors.Imaginary * color;
|
||||
}
|
||||
|
||||
int offsetXY = ids.Y * width + ids.X;
|
||||
|
||||
target[offsetXY].Real = real;
|
||||
target[offsetXY].Imaginary = imaginary;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs an horizontal 1D complex convolution with the specified parameters.
|
||||
/// </summary>
|
||||
@@ -373,7 +332,7 @@ namespace ComputeSharp.BokehBlur.Processors
|
||||
int height = Source.Height;
|
||||
int width = Source.Width;
|
||||
|
||||
HorizontalConvolutionAndAccumulatePartialsProcessor shader = new(
|
||||
HlslBokehBlurProcessor.HorizontalConvolutionAndAccumulatePartialsProcessor shader = new(
|
||||
width,
|
||||
maxY: height - 1,
|
||||
maxX: width - 1,
|
||||
@@ -387,47 +346,6 @@ namespace ComputeSharp.BokehBlur.Processors
|
||||
Gpu.Default.For(width, height, in shader);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Kernel for <see cref="ApplyHorizontalConvolutionAndAccumulatePartials"/>.
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
private partial struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader
|
||||
{
|
||||
public int width;
|
||||
public int maxY;
|
||||
public int maxX;
|
||||
public int kernelLength;
|
||||
public float z;
|
||||
public float w;
|
||||
|
||||
public ReadWriteBuffer<ComplexVector4> source;
|
||||
public ReadWriteBuffer<Vector4> target;
|
||||
public ReadOnlyBuffer<Complex64> kernel;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Execute(ThreadIds ids)
|
||||
{
|
||||
Vector4 real = Vector4.Zero;
|
||||
Vector4 imaginary = Vector4.Zero;
|
||||
int radiusX = kernelLength >> 1;
|
||||
int sourceOffsetColumnBase = ids.X;
|
||||
int offsetY = Hlsl.Clamp(ids.Y, 0, maxY);
|
||||
|
||||
for (int i = 0; i < kernelLength; i++)
|
||||
{
|
||||
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX);
|
||||
var offsetXY = offsetY * width + offsetX;
|
||||
ComplexVector4 source4 = source[offsetXY];
|
||||
Complex64 factors = kernel[i];
|
||||
|
||||
real += factors.Real * source4.Real - factors.Imaginary * source4.Imaginary;
|
||||
imaginary += factors.Real * source4.Imaginary + factors.Imaginary * source4.Real;
|
||||
}
|
||||
|
||||
target[ids.Y * width + ids.X] += real * z + imaginary * w;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies the gamma correction/highlight to the input pixel buffer and returns an <see cref="IMemoryOwner{T}"/> instance with <see cref="Vector4"/> values.
|
||||
/// </summary>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using SixLabors.ImageSharp;
|
||||
using System.Numerics;
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
using SixLabors.ImageSharp.Processing.Processors;
|
||||
|
||||
@@ -7,7 +8,7 @@ namespace ComputeSharp.BokehBlur.Processors
|
||||
/// <summary>
|
||||
/// Defines Gaussian blur by a (Sigma, Radius) pair.
|
||||
/// </summary>
|
||||
public sealed class HlslGaussianBlurProcessor : IImageProcessor
|
||||
public sealed partial class HlslGaussianBlurProcessor : IImageProcessor
|
||||
{
|
||||
/// <summary>
|
||||
/// The default value for <see cref="Sigma"/>.
|
||||
@@ -52,5 +53,79 @@ namespace ComputeSharp.BokehBlur.Processors
|
||||
{
|
||||
return new HlslGaussianBlurProcessor<TPixel>(this, configuration, source, sourceRectangle);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Kernel for the vertical convolution pass.
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct VerticalConvolutionProcessor : IComputeShader
|
||||
{
|
||||
public readonly int width;
|
||||
public readonly int maxY;
|
||||
public readonly int maxX;
|
||||
public readonly int kernelLength;
|
||||
|
||||
public readonly ReadWriteBuffer<Vector4> source;
|
||||
public readonly ReadWriteBuffer<Vector4> target;
|
||||
public readonly ReadOnlyBuffer<float> kernel;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Execute(ThreadIds ids)
|
||||
{
|
||||
Vector4 result = Vector4.Zero;
|
||||
int radiusY = kernelLength >> 1;
|
||||
int sourceOffsetColumnBase = ids.X;
|
||||
|
||||
for (int i = 0; i < kernelLength; i++)
|
||||
{
|
||||
int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY);
|
||||
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX);
|
||||
Vector4 color = source[offsetY * width + offsetX];
|
||||
|
||||
result += kernel[i] * color;
|
||||
}
|
||||
|
||||
int offsetXY = ids.Y * width + ids.X;
|
||||
target[offsetXY] = result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Kernel for the horizontal convolution pass.
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader
|
||||
{
|
||||
public readonly int width;
|
||||
public readonly int maxY;
|
||||
public readonly int maxX;
|
||||
public readonly int kernelLength;
|
||||
|
||||
public readonly ReadWriteBuffer<Vector4> source;
|
||||
public readonly ReadWriteBuffer<Vector4> target;
|
||||
public readonly ReadOnlyBuffer<float> kernel;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Execute(ThreadIds ids)
|
||||
{
|
||||
Vector4 result = Vector4.Zero;
|
||||
int radiusX = kernelLength >> 1;
|
||||
int sourceOffsetColumnBase = ids.X;
|
||||
int offsetY = Hlsl.Clamp(ids.Y, 0, maxY);
|
||||
int offsetXY;
|
||||
|
||||
for (int i = 0; i < kernelLength; i++)
|
||||
{
|
||||
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX);
|
||||
offsetXY = offsetY * width + offsetX;
|
||||
Vector4 color = source[offsetXY];
|
||||
|
||||
result += kernel[i] * color;
|
||||
}
|
||||
|
||||
offsetXY = ids.Y * width + ids.X;
|
||||
target[offsetXY] = result;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+19
-91
@@ -13,7 +13,7 @@ namespace ComputeSharp.BokehBlur.Processors
|
||||
/// Applies Gaussian blur processing to an image.
|
||||
/// </summary>
|
||||
/// <typeparam name="TPixel">The pixel format.</typeparam>
|
||||
internal class HlslGaussianBlurProcessor<TPixel> : ImageProcessor<TPixel>
|
||||
internal sealed class HlslGaussianBlurProcessor<TPixel> : ImageProcessor<TPixel>
|
||||
where TPixel : unmanaged, IPixel<TPixel>
|
||||
{
|
||||
/// <summary>
|
||||
@@ -124,51 +124,16 @@ namespace ComputeSharp.BokehBlur.Processors
|
||||
int height = Source.Height;
|
||||
int width = Source.Width;
|
||||
|
||||
Gpu.Default.For(width, height, new VerticalConvolutionProcessor
|
||||
{
|
||||
width = width,
|
||||
maxY = height - 1,
|
||||
maxX = width - 1,
|
||||
kernelLength = kernel.Length,
|
||||
source = source,
|
||||
target = target,
|
||||
kernel = kernel
|
||||
});
|
||||
}
|
||||
HlslGaussianBlurProcessor.VerticalConvolutionProcessor shader = new(
|
||||
width,
|
||||
maxY: height - 1,
|
||||
maxX: width - 1,
|
||||
kernel.Length,
|
||||
source,
|
||||
target,
|
||||
kernel);
|
||||
|
||||
/// <summary>
|
||||
/// Kernel for <see cref="ApplyVerticalConvolution"/>.
|
||||
/// </summary>
|
||||
private struct VerticalConvolutionProcessor : IComputeShader
|
||||
{
|
||||
public int width;
|
||||
public int maxY;
|
||||
public int maxX;
|
||||
public int kernelLength;
|
||||
|
||||
public ReadWriteBuffer<Vector4> source;
|
||||
public ReadWriteBuffer<Vector4> target;
|
||||
public ReadOnlyBuffer<float> kernel;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Execute(ThreadIds ids)
|
||||
{
|
||||
Vector4 result = Vector4.Zero;
|
||||
int radiusY = kernelLength >> 1;
|
||||
int sourceOffsetColumnBase = ids.X;
|
||||
|
||||
for (int i = 0; i < kernelLength; i++)
|
||||
{
|
||||
int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY);
|
||||
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX);
|
||||
Vector4 color = source[offsetY * width + offsetX];
|
||||
|
||||
result += kernel[i] * color;
|
||||
}
|
||||
|
||||
int offsetXY = ids.Y * width + ids.X;
|
||||
target[offsetXY] = result;
|
||||
}
|
||||
Gpu.Default.For(width, height, in shader);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -186,53 +151,16 @@ namespace ComputeSharp.BokehBlur.Processors
|
||||
int height = Source.Height;
|
||||
int width = Source.Width;
|
||||
|
||||
Gpu.Default.For(width, height, new HorizontalConvolutionProcessor
|
||||
{
|
||||
width = width,
|
||||
maxY = height - 1,
|
||||
maxX = width - 1,
|
||||
kernelLength = kernel.Length,
|
||||
source = source,
|
||||
target = target,
|
||||
kernel = kernel
|
||||
});
|
||||
}
|
||||
HlslGaussianBlurProcessor.HorizontalConvolutionProcessor shader = new(
|
||||
width,
|
||||
maxY: height - 1,
|
||||
maxX: width - 1,
|
||||
kernel.Length,
|
||||
source,
|
||||
target,
|
||||
kernel);
|
||||
|
||||
/// <summary>
|
||||
/// Kernel for <see cref="ApplyHorizontalConvolution"/>.
|
||||
/// </summary>
|
||||
private struct HorizontalConvolutionProcessor : IComputeShader
|
||||
{
|
||||
public int width;
|
||||
public int maxY;
|
||||
public int maxX;
|
||||
public int kernelLength;
|
||||
|
||||
public ReadWriteBuffer<Vector4> source;
|
||||
public ReadWriteBuffer<Vector4> target;
|
||||
public ReadOnlyBuffer<float> kernel;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Execute(ThreadIds ids)
|
||||
{
|
||||
Vector4 result = Vector4.Zero;
|
||||
int radiusX = kernelLength >> 1;
|
||||
int sourceOffsetColumnBase = ids.X;
|
||||
int offsetY = Hlsl.Clamp(ids.Y, 0, maxY);
|
||||
int offsetXY;
|
||||
|
||||
for (int i = 0; i < kernelLength; i++)
|
||||
{
|
||||
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX);
|
||||
offsetXY = offsetY * width + offsetX;
|
||||
Vector4 color = source[offsetXY];
|
||||
|
||||
result += kernel[i] * color;
|
||||
}
|
||||
|
||||
offsetXY = ids.Y * width + ids.X;
|
||||
target[offsetXY] = result;
|
||||
}
|
||||
Gpu.Default.For(width, height, in shader);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net5.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\ComputeSharp\ComputeSharp.csproj" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj"
|
||||
OutputItemType="Analyzer"
|
||||
ReferenceOutputAssembly="false"
|
||||
PrivateAssets="contentfiles;build" />
|
||||
</ItemGroup>
|
||||
|
||||
<Import Project="..\ComputeSharp.Sample.Shared\ComputeSharp.Sample.Shared.projitems" Label="Shared" />
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,14 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net5.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ComputeSharp" Version="2.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<Import Project="..\ComputeSharp.Sample.Shared\ComputeSharp.Sample.Shared.projitems" Label="Shared" />
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<MSBuildAllProjects Condition="'$(MSBuildVersion)' == '' Or '$(MSBuildVersion)' < '16.0'">$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
|
||||
<HasSharedItems>true</HasSharedItems>
|
||||
<SharedGUID>8cefc324-ca6c-4845-9ad9-70b92bd87057</SharedGUID>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Label="Configuration">
|
||||
<Import_RootNamespace>ComputeSharp.Sample.Shared</Import_RootNamespace>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Program.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGuid>8cefc324-ca6c-4845-9ad9-70b92bd87057</ProjectGuid>
|
||||
<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" />
|
||||
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" />
|
||||
<PropertyGroup />
|
||||
<Import Project="ComputeSharp.Sample.Shared.projitems" Label="Shared" />
|
||||
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" />
|
||||
</Project>
|
||||
+2
-2
@@ -42,9 +42,9 @@ namespace ComputeSharp.Sample
|
||||
/// Kernel for <see cref="Main"/>.
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
private readonly partial struct MainKernel : IComputeShader
|
||||
internal readonly partial struct MainKernel : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<float> buffer;
|
||||
public readonly ReadWriteBuffer<float> buffer;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Execute(ThreadIds ids)
|
||||
@@ -1,17 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net5.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\ComputeSharp\ComputeSharp.csproj" />
|
||||
<ProjectReference
|
||||
Include="..\..\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj"
|
||||
OutputItemType="Analyzer"
|
||||
ReferenceOutputAssembly="false"
|
||||
PrivateAssets="contentfiles;build"/>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
+2
-2
@@ -5,7 +5,7 @@ using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
|
||||
namespace ComputeSharp
|
||||
namespace ComputeSharp.__Internals
|
||||
{
|
||||
/// <summary>
|
||||
/// An attribute that contains info on a processed compute shader that can be executed.
|
||||
@@ -13,7 +13,7 @@ namespace ComputeSharp
|
||||
/// <remarks>This attribute is not meant to be directly used by applications using ComputeSharp.</remarks>
|
||||
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
[Obsolete("This attribute is meant to be used from the source generator only")]
|
||||
[Obsolete("This attribute is not intended to be used directly by user code")]
|
||||
public sealed class IComputeShaderSourceAttribute : Attribute
|
||||
{
|
||||
/// <summary>
|
||||
+15
-5
@@ -5,9 +5,8 @@ using System.Diagnostics.Contracts;
|
||||
using System.Reflection;
|
||||
using ComputeSharp.Core.Extensions;
|
||||
using ComputeSharp.Exceptions;
|
||||
using Microsoft.Toolkit.Diagnostics;
|
||||
|
||||
namespace ComputeSharp
|
||||
namespace ComputeSharp.__Internals
|
||||
{
|
||||
/// <summary>
|
||||
/// An attribute that contains info on a processed shader method that can be executed within a shader.
|
||||
@@ -16,7 +15,7 @@ namespace ComputeSharp
|
||||
/// <remarks>This attribute is not meant to be directly used by applications using ComputeSharp.</remarks>
|
||||
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
[Obsolete("This attribute is meant to be used from the source generator only")]
|
||||
[Obsolete("This attribute is not intended to be used directly by user code")]
|
||||
public sealed class ShaderMethodSourceAttribute : Attribute
|
||||
{
|
||||
/// <summary>
|
||||
@@ -79,9 +78,12 @@ namespace ComputeSharp
|
||||
[Pure]
|
||||
internal static ShaderMethodSourceAttribute GetForDelegate(Delegate function)
|
||||
{
|
||||
Guard.IsTrue(function.Method.IsStatic, "Captured delegates need to wrap static methods");
|
||||
if (!function.Method.IsStatic)
|
||||
{
|
||||
ThrowArgumentExceptionForNonStaticShader();
|
||||
}
|
||||
|
||||
var attributes = function.Method.DeclaringType.Assembly.GetCustomAttributes<ShaderMethodSourceAttribute>();
|
||||
var attributes = function.Method.DeclaringType!.Assembly.GetCustomAttributes<ShaderMethodSourceAttribute>();
|
||||
string methodName = function.Method.GetFullName();
|
||||
|
||||
foreach (var attribute in attributes)
|
||||
@@ -94,5 +96,13 @@ namespace ComputeSharp
|
||||
|
||||
return MissingMethodSourceException.Throw(function);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Throws an <see cref="ArgumentException"/> when a given <see cref="Delegate"/> is not static.
|
||||
/// </summary>
|
||||
private static void ThrowArgumentExceptionForNonStaticShader()
|
||||
{
|
||||
throw new ArgumentException("Captured delegates in a shader need to wrap a static method.", "function");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,11 @@
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>netstandard2.0;net5.0</TargetFrameworks>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<LangVersion>9.0</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<LangVersion>9.0</LangVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Toolkit" Version="7.0.0-preview4" />
|
||||
<PackageReference Include="System.Numerics.Vectors" Version="4.5.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Text;
|
||||
using ComputeSharp.__Internals;
|
||||
using ComputeSharp.Core.Extensions;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace ComputeSharp.Graphics.Helpers
|
||||
namespace ComputeSharp.Core.Helpers
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> with helper methods to work with alignment and padding.
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Runtime.CompilerServices;
|
||||
using ComputeSharp.Core.Helpers;
|
||||
using ComputeSharp.Exceptions;
|
||||
using ComputeSharp.Graphics;
|
||||
using ComputeSharp.Graphics.Buffers.Abstract;
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net5.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="TerraFX.Interop.Windows" Version="10.0.19041-beta2-379749354" />
|
||||
<PackageReference Include="Microsoft.Toolkit" Version="7.0.0-preview4" />
|
||||
<PackageReference Include="TerraFX.Interop.Windows" Version="10.0.19041-beta2-449553204" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.CompilerServices;
|
||||
using ComputeSharp.Graphics;
|
||||
using ComputeSharp.Graphics.Buffers.Abstract;
|
||||
using TerraFX.Interop;
|
||||
|
||||
namespace ComputeSharp.__Internals
|
||||
{
|
||||
/// <summary>
|
||||
/// A helper class with some proxy methods to expose to generated code in external projects.
|
||||
/// </summary>
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
[Obsolete("This type is not intended to be used directly by user code")]
|
||||
public static class GraphicsResourceHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Validates the given buffer for usage with a specified device, and retrieves its GPU descriptor handle.
|
||||
/// </summary>
|
||||
/// <param name="buffer">The input <see cref="Buffer{T}"/> instance to check.</param>
|
||||
/// <param name="device">The target <see cref="GraphicsDevice"/> instance in use.</param>
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
[Obsolete("This method is not intended to be called directly by user code")]
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static ulong ValidateAndGetGpuDescriptorHandle<T>(Buffer<T> buffer, GraphicsDevice device)
|
||||
where T : unmanaged
|
||||
{
|
||||
buffer.ThrowIfDisposed();
|
||||
buffer.ThrowIfDeviceMismatch(device);
|
||||
|
||||
return Unsafe.As<D3D12_GPU_DESCRIPTOR_HANDLE, ulong>(ref Unsafe.AsRef(in buffer.D3D12GpuDescriptorHandle));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates the given buffer for usage with a specified device, and retrieves its GPU descriptor handle.
|
||||
/// </summary>
|
||||
/// <param name="buffer">The input <see cref="Texture2D{T}"/> instance to check.</param>
|
||||
/// <param name="device">The target <see cref="GraphicsDevice"/> instance in use.</param>
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
[Obsolete("This method is not intended to be called directly by user code")]
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static ulong ValidateAndGetGpuDescriptorHandle<T>(Texture2D<T> buffer, GraphicsDevice device)
|
||||
where T : unmanaged
|
||||
{
|
||||
buffer.ThrowIfDisposed();
|
||||
buffer.ThrowIfDeviceMismatch(device);
|
||||
|
||||
return Unsafe.As<D3D12_GPU_DESCRIPTOR_HANDLE, ulong>(ref Unsafe.AsRef(in buffer.D3D12GpuDescriptorHandle));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates the given buffer for usage with a specified device, and retrieves its GPU descriptor handle.
|
||||
/// </summary>
|
||||
/// <param name="buffer">The input <see cref="Texture3D{T}"/> instance to check.</param>
|
||||
/// <param name="device">The target <see cref="GraphicsDevice"/> instance in use.</param>
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
[Obsolete("This method is not intended to be called directly by user code")]
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static ulong ValidateAndGetGpuDescriptorHandle<T>(Texture3D<T> buffer, GraphicsDevice device)
|
||||
where T : unmanaged
|
||||
{
|
||||
buffer.ThrowIfDisposed();
|
||||
buffer.ThrowIfDeviceMismatch(device);
|
||||
|
||||
return Unsafe.As<D3D12_GPU_DESCRIPTOR_HANDLE, ulong>(ref Unsafe.AsRef(in buffer.D3D12GpuDescriptorHandle));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<Project Sdk="Microsoft.Build.NoTargets/2.0.1" DefaultTargets="Pack">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net5.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<PackageId>ComputeSharp</PackageId>
|
||||
<Description>A .NET 5 library to run C# code in parallel on the GPU through DX12 and dynamically generated HLSL compute shaders</Description>
|
||||
<PackageReleaseNotes>New interlocked intrinsics APIs, performance and memory optimizations</PackageReleaseNotes>
|
||||
<PackageVersion>2.0.0</PackageVersion>
|
||||
<RepositoryUrl>https://github.com/Sergio0694/ComputeSharp.git</RepositoryUrl>
|
||||
<ProjectUrl>https://github.com/Sergio0694/ComputeSharp</ProjectUrl>
|
||||
<Authors>Sergio Pedri</Authors>
|
||||
<Owners>Sergio Pedri</Owners>
|
||||
<Copyright>Copyright (c) 2020 Sergio Pedri</Copyright>
|
||||
<PackageLicenseExpression>MIT</PackageLicenseExpression>
|
||||
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
|
||||
<PackageIconUrl>https://i.imgur.com/ntvmD6P.png</PackageIconUrl>
|
||||
<PackageTags>dotnet net netcore netstandard csharp library graphics shader hlsl compute gpu</PackageTags>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\ComputeSharp\ComputeSharp.csproj" />
|
||||
<ProjectReference Include="..\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net5.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
|
||||
@@ -1,107 +0,0 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using System.Reflection.Emit;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Toolkit.Diagnostics;
|
||||
|
||||
namespace ComputeSharp.Shaders.Extensions
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that provides extension methods for the <see langword="ILGenerator"/> type.
|
||||
/// </summary>
|
||||
internal static class ILGeneratorExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Puts the appropriate <see langword="ldsfld"/>, <see langword="ldfld"/>, <see langword="call"/> or <see langword="callvirt"/> instruction to read a member onte the stream of instructions.
|
||||
/// </summary>
|
||||
/// <param name="il">The input <see cref="ILGenerator"/> instance to use to emit instructions.</param>
|
||||
/// <param name="member">The member to read.</param>
|
||||
public static void EmitReadMember(this ILGenerator il, MemberInfo member)
|
||||
{
|
||||
switch (member)
|
||||
{
|
||||
case FieldInfo field:
|
||||
il.Emit(field.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld, field);
|
||||
break;
|
||||
case PropertyInfo property when property.CanRead:
|
||||
il.EmitCall(property.GetMethod!.IsStatic ? OpCodes.Call : OpCodes.Callvirt, property.GetMethod, null);
|
||||
break;
|
||||
default: ThrowHelper.ThrowArgumentException("The input MemberInfo instance can't be read"); return;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Puts the appropriate <see langword="ldc.i4"/>, <see langword="conv.i"/> and <see langword="add"/> instructions to advance a reference onto the stream of instructions.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of reference at the top of the stack.</typeparam>
|
||||
/// <param name="il">The input <see cref="ILGenerator"/> instance to use to emit instructions.</param>
|
||||
/// <param name="offset">The offset to use to advance the current reference on top of the execution stack.</param>
|
||||
public static void EmitAddOffset<T>(this ILGenerator il, int offset) => il.EmitAddOffset(Unsafe.SizeOf<T>() * offset);
|
||||
|
||||
/// <summary>
|
||||
/// Puts the appropriate <see langword="ldc.i4"/>, <see langword="conv.i"/> and <see langword="add"/> instructions to advance a reference onto the stream of instructions.
|
||||
/// </summary>
|
||||
/// <param name="il">The input <see cref="ILGenerator"/> instance to use to emit instructions.</param>
|
||||
/// <param name="offset">The offset in bytes to use to advance the current reference on top of the execution stack.</param>
|
||||
public static void EmitAddOffset(this ILGenerator il, int offset)
|
||||
{
|
||||
// Push the offset to the stack
|
||||
if (offset < -128) il.Emit(OpCodes.Ldc_I4, offset);
|
||||
else if (offset < 0) il.Emit(OpCodes.Ldc_I4_S, (sbyte)offset);
|
||||
else if (offset <= 8)
|
||||
{
|
||||
il.Emit(offset switch
|
||||
{
|
||||
0 => OpCodes.Ldc_I4_0,
|
||||
1 => OpCodes.Ldc_I4_1,
|
||||
2 => OpCodes.Ldc_I4_2,
|
||||
3 => OpCodes.Ldc_I4_3,
|
||||
4 => OpCodes.Ldc_I4_4,
|
||||
5 => OpCodes.Ldc_I4_5,
|
||||
6 => OpCodes.Ldc_I4_6,
|
||||
7 => OpCodes.Ldc_I4_7,
|
||||
8 => OpCodes.Ldc_I4_8,
|
||||
_ => ThrowHelper.ThrowArgumentException<OpCode>("Invalid offset value")
|
||||
});
|
||||
}
|
||||
else if (offset <= 127) il.Emit(OpCodes.Ldc_I4_S, (byte)offset);
|
||||
else il.Emit(OpCodes.Ldc_I4, offset);
|
||||
|
||||
// Converts the offset to native int and adds to the address
|
||||
il.Emit(OpCodes.Conv_I);
|
||||
il.Emit(OpCodes.Add);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Puts the appropriate <see langword="stind"/> or <see langword="stobj"/> instruction to write to a reference onto the stream of instructions.
|
||||
/// </summary>
|
||||
/// <param name="il">The input <see cref="ILGenerator"/> instance to use to emit instructions.</param>
|
||||
/// <param name="type">The type of value being written to the current reference on top of the execution stack.</param>
|
||||
public static void EmitStoreToAddress(this ILGenerator il, Type type)
|
||||
{
|
||||
if (type.IsValueType)
|
||||
{
|
||||
// Pick the optimal opcode to set a value type
|
||||
OpCode opcode = Marshal.SizeOf(type) switch
|
||||
{
|
||||
// Use the faster op codes for sizes <= 8
|
||||
1 when type == typeof(byte) || type == typeof(sbyte) => OpCodes.Stind_I1,
|
||||
2 when type == typeof(short) || type == typeof(ushort) => OpCodes.Stind_I2,
|
||||
4 when type == typeof(float) => OpCodes.Stind_R4,
|
||||
4 when type == typeof(int) || type == typeof(uint) => OpCodes.Stind_I4,
|
||||
8 when type == typeof(double) => OpCodes.Stind_R8,
|
||||
8 when type == typeof(long) || type == typeof(ulong) => OpCodes.Stind_I8,
|
||||
|
||||
// Default to stobj for all other value types
|
||||
_ => OpCodes.Stobj
|
||||
};
|
||||
|
||||
// Also pass the type token if stobj is used
|
||||
if (opcode == OpCodes.Stobj) il.Emit(opcode, type);
|
||||
else il.Emit(opcode);
|
||||
}
|
||||
else il.Emit(OpCodes.Stind_Ref);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
using System;
|
||||
using System.Diagnostics.Contracts;
|
||||
|
||||
namespace ComputeSharp.Shaders.Extensions
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that provides extension methods for the <see cref="Type"/> type.
|
||||
/// </summary>
|
||||
internal static class TypeExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets whether or not the input <see cref="Type"/> represents a <see cref="Delegate"/>.
|
||||
/// </summary>
|
||||
/// <param name="type">The input type to analyze.</param>
|
||||
[Pure]
|
||||
public static bool IsDelegate(this Type type)
|
||||
{
|
||||
return type.IsSubclassOf(typeof(Delegate));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
|
||||
namespace System.Reflection.Emit
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that can be used to easily create dynamic methods.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of <see cref="Delegate"/> that will be used to wrap the new methods.</typeparam>
|
||||
internal static class DynamicMethod<T>
|
||||
where T : Delegate
|
||||
{
|
||||
/// <summary>
|
||||
/// The return type of the <typeparamref name="T"/> <see langword="delegate"/>.
|
||||
/// </summary>
|
||||
private static readonly Type ReturnType;
|
||||
|
||||
/// <summary>
|
||||
/// The types of the arguments of the <typeparamref name="T"/> <see langword="delegate"/>.
|
||||
/// </summary>
|
||||
private static readonly Type[] ParameterTypes;
|
||||
|
||||
/// <summary>
|
||||
/// Loads all the necessary <see cref="Type"/> info for the current <typeparamref name="T"/> parameter.
|
||||
/// </summary>
|
||||
static DynamicMethod()
|
||||
{
|
||||
MethodInfo method = typeof(T).GetMethod("Invoke")!;
|
||||
|
||||
ReturnType = method.ReturnType;
|
||||
ParameterTypes = new[] { typeof(object) }.Concat(method.GetParameters().Select(static p => p.ParameterType)).ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <typeparamref name="T"/> <see langword="delegate"/> for the target owner. For performance reasons,
|
||||
/// the underlying dynamic method will be created with an extra <see cref="object"/> parameter, and then bound to
|
||||
/// a <see langword="null"/> instance. This is to emulate the behavior of instance methods, which unlike static ones
|
||||
/// don't need to go through the shuffle thunk when the delegate is invoked. This would be needed to redirect the
|
||||
/// invocation to a stub that performs parameters swapping, as the Invoke method is an instance one with the parameters
|
||||
/// starting from offset 1, while the target static method would expect them to start from offset 0. This solution
|
||||
/// allows the delegate created for the dynamic method to avoid having a shuffle thunk at all, and with it only having
|
||||
/// to replace the hidden instance argument when being invoked, resulting in much better performance. Because of this,
|
||||
/// it is expected that <paramref name="builder"/> will emit the bytecode assuming that there is an extra unused argument
|
||||
/// at offset 0. As a result of this, all argument load and store opcodes will need to be shifted by one position forwards.
|
||||
/// </summary>
|
||||
/// <param name="builder">An <see cref="Action"/> that builds the IL bytecode for the new method.</param>
|
||||
/// <returns>A new dynamic method wrapped as a <typeparamref name="T"/> <see langword="delegate"/>.</returns>
|
||||
[Pure]
|
||||
public static T New(Action<ILGenerator> builder)
|
||||
{
|
||||
DynamicMethod method = new(string.Empty, ReturnType, ParameterTypes, true);
|
||||
|
||||
builder(method.GetILGenerator());
|
||||
|
||||
return method.CreateDelegate<T>(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,9 +12,9 @@ namespace ComputeSharp.Shaders.Translation.Models
|
||||
internal readonly ref struct DispatchData
|
||||
{
|
||||
/// <summary>
|
||||
/// The <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> array with the captured buffers.
|
||||
/// The <see cref="ulong"/> array (actually <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> values) with the captured buffers.
|
||||
/// </summary>
|
||||
private readonly D3D12_GPU_DESCRIPTOR_HANDLE[] resourcesArray;
|
||||
private readonly ulong[] resourcesArray;
|
||||
|
||||
/// <summary>
|
||||
/// The number of <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> values in <see cref="resourcesArray"/>.
|
||||
@@ -34,11 +34,11 @@ namespace ComputeSharp.Shaders.Translation.Models
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="DispatchData"/> instance with the specified parameters.
|
||||
/// </summary>
|
||||
/// <param name="resourcesArray">The <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> array with the captured buffers.</param>
|
||||
/// <param name="resourcesArray">The <see cref="ulong"/> array with the captured buffers.</param>
|
||||
/// <param name="resourcesCount">The number of <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> instances in <see cref="resourcesArray"/>.</param>
|
||||
/// <param name="variablesArray">The <see cref="byte"/> array with all the captured variables, with proper padding.</param>
|
||||
/// <param name="variablesByteSize">The actual size in bytes to use from <see cref="variablesArray"/>.</param>
|
||||
public DispatchData(D3D12_GPU_DESCRIPTOR_HANDLE[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesByteSize)
|
||||
public DispatchData(ulong[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesByteSize)
|
||||
{
|
||||
this.resourcesArray = resourcesArray;
|
||||
this.variablesArray = variablesArray;
|
||||
@@ -54,9 +54,10 @@ namespace ComputeSharp.Shaders.Translation.Models
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
get
|
||||
{
|
||||
ref D3D12_GPU_DESCRIPTOR_HANDLE r0 = ref MemoryMarshal.GetArrayDataReference(this.resourcesArray);
|
||||
ref ulong r0 = ref MemoryMarshal.GetArrayDataReference(this.resourcesArray);
|
||||
ref D3D12_GPU_DESCRIPTOR_HANDLE r1 = ref Unsafe.As<ulong, D3D12_GPU_DESCRIPTOR_HANDLE>(ref r0);
|
||||
|
||||
return MemoryMarshal.CreateReadOnlySpan(ref r0, this.resourcesCount);
|
||||
return MemoryMarshal.CreateReadOnlySpan(ref r1, this.resourcesCount);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,7 +80,7 @@ namespace ComputeSharp.Shaders.Translation.Models
|
||||
/// <inheritdoc cref="IDisposable.Dispose"/>
|
||||
public void Dispose()
|
||||
{
|
||||
ArrayPool<D3D12_GPU_DESCRIPTOR_HANDLE>.Shared.Return(this.resourcesArray);
|
||||
ArrayPool<ulong>.Shared.Return(this.resourcesArray);
|
||||
ArrayPool<byte>.Shared.Return(this.variablesArray);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeSharp.Core.Extensions;
|
||||
using ComputeSharp.Exceptions;
|
||||
using TerraFX.Interop;
|
||||
@@ -34,6 +37,8 @@ namespace ComputeSharp.Shaders.Translation
|
||||
/// </summary>
|
||||
static ShaderCompiler()
|
||||
{
|
||||
InitializeDxcLibrariesLoading();
|
||||
|
||||
using ComPtr<IDxcCompiler> dxcCompiler = default;
|
||||
using ComPtr<IDxcLibrary> dxcLibrary = default;
|
||||
using ComPtr<IDxcIncludeHandler> dxcIncludeHandler = default;
|
||||
@@ -51,6 +56,64 @@ namespace ComputeSharp.Shaders.Translation
|
||||
DxcIncludeHandler = dxcIncludeHandler.Move();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the DLL resolvers for the dxcompiler.dll and dxil.dll libraries.
|
||||
/// </summary>
|
||||
private static void InitializeDxcLibrariesLoading()
|
||||
{
|
||||
// Test whether the native libraries are present in the same folder of the executable
|
||||
// (which is the case when the program was built with a runtime identifier), or whether
|
||||
// they are in the "runtimes\win-x64\native" folder in the executable directory.
|
||||
string nugetNativeLibsPath = Path.Combine(AppContext.BaseDirectory, @"runtimes\win-x64\native");
|
||||
bool isNuGetRuntimeLibrariesDirectoryPresent = Directory.Exists(nugetNativeLibsPath);
|
||||
|
||||
// Register a custom library resolver for the two DXC libraries. We need to either manually load the two
|
||||
// libraries from the NuGet directory, if an RID is not in use, or we need to ensure that dxil.dll is
|
||||
// loaded correctly in case the program was executed with the host being in another directory.
|
||||
// This happens when doing eg. "dotnet bin\Debug\net5.0\MyApp.dll", which would crash at runtime.
|
||||
FX.ResolveLibrary += (n, a, s) => ResolveLibrary(n, a, s, isNuGetRuntimeLibrariesDirectoryPresent);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A custom resolver to override the default library resolution behavior for the DXC and DXIL libraries.
|
||||
/// This either loads the libraries from the NuGet directory, or just ensures that DXIL is always loaded.
|
||||
/// </summary>
|
||||
/// <inheritdoc cref="DllImportResolver"/>
|
||||
private static IntPtr ResolveLibrary(string libraryName, Assembly assembly, DllImportSearchPath? searchPath, bool isNuGetRuntimeLibrariesDirectoryPresent)
|
||||
{
|
||||
if (libraryName is not "dxcompiler") return IntPtr.Zero;
|
||||
|
||||
if (isNuGetRuntimeLibrariesDirectoryPresent)
|
||||
{
|
||||
string
|
||||
dxcompilerPath = Path.Combine(AppContext.BaseDirectory, @"runtimes\win-x64\native\dxcompiler.dll"),
|
||||
dxilPath = Path.Combine(AppContext.BaseDirectory, @"runtimes\win-x64\native\dxil.dll");
|
||||
|
||||
// Load DXIL first so that DXC doesn't fail to load it, and then DXIL, both from the NuGet path
|
||||
if (NativeLibrary.TryLoad(dxilPath, out _) && NativeLibrary.TryLoad(dxcompilerPath, out IntPtr handle))
|
||||
{
|
||||
return handle;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Even when the two libraries are correctly copied next to the executable in use, we load them
|
||||
// manually to ensure the operation is successful. This is to avoid failures in cases such as when
|
||||
// doing "dotnet bin\MyApp.dll", ie. when the host is in another path than the executable in use.
|
||||
// This is probably because DXIL is a native dependency for DXC, but the way Windows loads these
|
||||
// libraries doesn't take into account the .NET concepts of "app directory": neither the current "bin"
|
||||
// directory nor the "process directory", which is "C:\Program Files\dotnet", actually contain the
|
||||
// native library we need, hence the runtime crash. Manually loading the library this way solves this.
|
||||
if (NativeLibrary.TryLoad("dxil", assembly, searchPath, out _) &&
|
||||
NativeLibrary.TryLoad("dxcompiler", assembly, searchPath, out IntPtr handle))
|
||||
{
|
||||
return handle;
|
||||
}
|
||||
}
|
||||
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Compiles a new HLSL shader from the input source code.
|
||||
/// </summary>
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Reflection.Emit;
|
||||
using System.Runtime.CompilerServices;
|
||||
using ComputeSharp.Shaders.Extensions;
|
||||
|
||||
namespace ComputeSharp.Shaders.Translation
|
||||
{
|
||||
@@ -38,16 +34,11 @@ namespace ComputeSharp.Shaders.Translation
|
||||
{
|
||||
Id = HashCode.Combine(typeof(T));
|
||||
|
||||
// Get the valid delegates for delegate checking
|
||||
FieldInfo[] delegateFieldInfos = (
|
||||
from fieldInfo in typeof(T).GetFields()
|
||||
where fieldInfo.FieldType.IsDelegate()
|
||||
select fieldInfo).ToArray();
|
||||
|
||||
// If at least one delegate is present, build the hasher method
|
||||
if (delegateFieldInfos.Length > 0)
|
||||
// Get the generated hasher, if one if present
|
||||
if (typeof(T).Assembly.GetType("ComputeSharp.__Internals.HashCodeProvider") is Type type &&
|
||||
type.GetMethod("CombineHash", new[] { typeof(int), typeof(T).MakeByRefType() }) is MethodInfo method)
|
||||
{
|
||||
Hasher = BuildDynamicHasher<T>(delegateFieldInfos);
|
||||
Hasher = method.CreateDelegate<Hasher<T>>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,43 +71,5 @@ namespace ComputeSharp.Shaders.Translation
|
||||
/// <returns>The final hash value for the input closure.</returns>
|
||||
private delegate int Hasher<T>(int hash, in T shader)
|
||||
where T : struct, IComputeShader;
|
||||
|
||||
/// <summary>
|
||||
/// Builds a new <see cref="Hasher{T}"/> instance for the target <see cref="Type"/> and sequence of <see cref="FieldInfo"/> values.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of compute shader currently in use.</typeparam>
|
||||
/// <param name="fieldInfos">The list of captured fields to inspect.</param>
|
||||
[Pure]
|
||||
private static Hasher<T> BuildDynamicHasher<T>(IReadOnlyCollection<FieldInfo> fieldInfos)
|
||||
where T : struct, IComputeShader
|
||||
{
|
||||
return DynamicMethod<Hasher<T>>.New(il =>
|
||||
{
|
||||
MethodInfo
|
||||
getMethodInfo = typeof(Delegate).GetProperty(nameof(Delegate.Method))!.GetMethod!,
|
||||
getHashCodeInfo = typeof(object).GetMethod(nameof(object.GetHashCode))!;
|
||||
foreach (FieldInfo fieldInfo in fieldInfos)
|
||||
{
|
||||
// (hashcode << 5) + hashcode
|
||||
il.Emit(OpCodes.Ldarg_1);
|
||||
il.Emit(OpCodes.Ldc_I4_5);
|
||||
il.Emit(OpCodes.Shl);
|
||||
il.Emit(OpCodes.Ldarg_1);
|
||||
il.Emit(OpCodes.Add);
|
||||
|
||||
// hashcode += shader.Function[#].Method.GetHashCode();
|
||||
il.Emit(OpCodes.Ldarg_2);
|
||||
il.Emit(OpCodes.Ldfld, fieldInfo);
|
||||
il.EmitCall(OpCodes.Callvirt, getMethodInfo, null);
|
||||
il.EmitCall(OpCodes.Callvirt, getHashCodeInfo, null);
|
||||
il.Emit(OpCodes.Add);
|
||||
il.Emit(OpCodes.Starg_S, (byte)1);
|
||||
}
|
||||
|
||||
// Return the computed hash
|
||||
il.Emit(OpCodes.Ldarg_1);
|
||||
il.Emit(OpCodes.Ret);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeSharp.Graphics;
|
||||
using ComputeSharp.Shaders.Translation.Models;
|
||||
using TerraFX.Interop;
|
||||
|
||||
namespace ComputeSharp.Shaders.Translation
|
||||
{
|
||||
/// <inheritdoc cref="ShaderLoader{T}"/>
|
||||
internal sealed partial class ShaderLoader<T>
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="delegate"/> that loads all the captured members from a shader instance.
|
||||
/// </summary>
|
||||
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
|
||||
/// <param name="shader">The shader instance to load the data from.</param>
|
||||
/// <param name="r0">
|
||||
/// A reference to the buffer with all the captured <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> instances.
|
||||
/// This is just represented as a <see cref="ulong"/> reference, to avoid exposing the type publicly.
|
||||
/// </param>
|
||||
/// <param name="r1">A reference to the buffer to use to store all the captured value types.</param>
|
||||
/// <returns>The returned value indicates the total number of written bytes into <paramref name="r1"/>.</returns>
|
||||
private delegate int DispatchDataLoader(GraphicsDevice device, in T shader, ref ulong r0, ref byte r1);
|
||||
|
||||
/// <summary>
|
||||
/// The number of captured graphics resources (buffers).
|
||||
/// </summary>
|
||||
private int totalResourceCount;
|
||||
|
||||
/// <summary>
|
||||
/// The cached <see cref="DispatchDataLoader"/> instance to load dispatch data before execution.
|
||||
/// </summary>
|
||||
private DispatchDataLoader? dispatchDataLoader;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="List{T}"/> of <see cref="FieldInfo"/> instances mapping the captured variables in the current shader.
|
||||
/// </summary>
|
||||
private readonly List<FieldInfo> capturedFields = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets a new <see cref="DispatchData"/> instance with all the captured data for the current shader instance.
|
||||
/// </summary>
|
||||
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
|
||||
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
|
||||
/// <param name="x">The number of iterations to run on the X axis.</param>
|
||||
/// <param name="y">The number of iterations to run on the Y axis.</param>
|
||||
/// <param name="z">The number of iterations to run on the Z axis.</param>
|
||||
[Pure]
|
||||
public DispatchData GetDispatchData(GraphicsDevice device, in T shader, int x, int y, int z)
|
||||
{
|
||||
// Resources and variables buffers
|
||||
ulong[] resources = ArrayPool<ulong>.Shared.Rent(this.totalResourceCount);
|
||||
byte[] variables = ArrayPool<byte>.Shared.Rent(4096);
|
||||
|
||||
ref ulong r0 = ref MemoryMarshal.GetArrayDataReference(resources);
|
||||
ref byte r1 = ref MemoryMarshal.GetArrayDataReference(variables);
|
||||
|
||||
// Set the x, y and z counters
|
||||
Unsafe.As<byte, int>(ref r1) = x;
|
||||
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 1) = y;
|
||||
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 2) = z;
|
||||
|
||||
// Invoke the dynamic method to extract the captured data
|
||||
int totalVariablesByteSize = this.dispatchDataLoader!(device, in shader, ref r0, ref r1);
|
||||
|
||||
return new(resources, this.totalResourceCount, variables, totalVariablesByteSize);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the <see cref="DispatchDataLoader"/> instance that loads the dispatch data for the current shader type.
|
||||
/// </summary>
|
||||
private void InitializeDispatchDataLoader()
|
||||
{
|
||||
// Get the generated data loader
|
||||
Type[] argumentTypes = new[] { typeof(GraphicsDevice), typeof(T).MakeByRefType(), typeof(ulong).MakeByRefType(), typeof(byte).MakeByRefType() };
|
||||
Type type = typeof(T).Assembly.GetType("ComputeSharp.__Internals.DispatchDataLoader")!;
|
||||
MethodInfo method = type.GetMethod("LoadDispatchData", argumentTypes)!;
|
||||
|
||||
this.dispatchDataLoader = method.CreateDelegate<DispatchDataLoader>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,170 +0,0 @@
|
||||
using System.Buffers;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Reflection;
|
||||
using System.Reflection.Emit;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeSharp.Graphics;
|
||||
using ComputeSharp.Graphics.Buffers.Abstract;
|
||||
using ComputeSharp.Graphics.Helpers;
|
||||
using ComputeSharp.Graphics.Interop;
|
||||
using ComputeSharp.Shaders.Extensions;
|
||||
using ComputeSharp.Shaders.Mappings;
|
||||
using ComputeSharp.Shaders.Translation.Models;
|
||||
using Microsoft.Toolkit.Diagnostics;
|
||||
using TerraFX.Interop;
|
||||
using FX = TerraFX.Interop.Windows;
|
||||
|
||||
namespace ComputeSharp.Shaders.Translation
|
||||
{
|
||||
/// <inheritdoc cref="ShaderLoader{T}"/>
|
||||
internal sealed partial class ShaderLoader<T>
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="delegate"/> that loads all the captured members from a shader instance.
|
||||
/// </summary>
|
||||
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
|
||||
/// <param name="shader">The shader instance to load the data from.</param>
|
||||
/// <param name="r0">A reference to the buffer with all the captured <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> instances.</param>
|
||||
/// <param name="r1">A reference to the buffer to use to store all the captured value types.</param>
|
||||
private delegate void DispatchDataLoader(GraphicsDevice device, in T shader, ref D3D12_GPU_DESCRIPTOR_HANDLE r0, ref byte r1);
|
||||
|
||||
/// <summary>
|
||||
/// The number of captured graphics resources (buffers).
|
||||
/// </summary>
|
||||
private int totalResourceCount;
|
||||
|
||||
/// <summary>
|
||||
/// The size in bytes of the buffer with the captured variables.
|
||||
/// </summary>
|
||||
/// <remarks>Initially set to 3 <see cref="int"/> values for X, Y and Z threads counts.</remarks>
|
||||
private int totalVariablesByteSize = 3 * sizeof(int);
|
||||
|
||||
/// <summary>
|
||||
/// The cached <see cref="DispatchDataLoader"/> instance to load dispatch data before execution.
|
||||
/// </summary>
|
||||
private DispatchDataLoader? dispatchDataLoader;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="List{T}"/> of <see cref="FieldInfo"/> instances mapping the captured variables in the current shader.
|
||||
/// </summary>
|
||||
private readonly List<FieldInfo> capturedFields = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets a new <see cref="DispatchData"/> instance with all the captured data for the current shader instance.
|
||||
/// </summary>
|
||||
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
|
||||
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
|
||||
/// <param name="x">The number of iterations to run on the X axis.</param>
|
||||
/// <param name="y">The number of iterations to run on the Y axis.</param>
|
||||
/// <param name="z">The number of iterations to run on the Z axis.</param>
|
||||
[Pure]
|
||||
public DispatchData GetDispatchData(GraphicsDevice device, in T shader, int x, int y, int z)
|
||||
{
|
||||
// Resources and variables buffers
|
||||
D3D12_GPU_DESCRIPTOR_HANDLE[] resources = ArrayPool<D3D12_GPU_DESCRIPTOR_HANDLE>.Shared.Rent(this.totalResourceCount);
|
||||
byte[] variables = ArrayPool<byte>.Shared.Rent(this.totalVariablesByteSize);
|
||||
|
||||
ref D3D12_GPU_DESCRIPTOR_HANDLE r0 = ref MemoryMarshal.GetArrayDataReference(resources);
|
||||
ref byte r1 = ref MemoryMarshal.GetArrayDataReference(variables);
|
||||
|
||||
// Set the x, y and z counters
|
||||
Unsafe.As<byte, int>(ref r1) = x;
|
||||
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 1) = y;
|
||||
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 2) = z;
|
||||
|
||||
// Invoke the dynamic method to extract the captured data
|
||||
this.dispatchDataLoader!(device, in shader, ref r0, ref r1);
|
||||
|
||||
return new(resources, this.totalResourceCount, variables, this.totalVariablesByteSize);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a new <see cref="DispatchDataLoader"/> instance that loads the dispatch data for the current shader type.
|
||||
/// </summary>
|
||||
private void BuildDispatchDataLoader()
|
||||
{
|
||||
// The delegate signature is <GraphicsDevice, in T, ref D3D12_GPU_DESCRIPTOR_HANDLE, ref byte, void>.
|
||||
// Due to how DynamicMethod<T> is implemented (see notes in the XML docs for DynamicMethod<T>.New),
|
||||
// all offsets for the input arguments are shifted by one. Because of this, we have the following:
|
||||
//
|
||||
// ldarg.1 = GraphicsDevice
|
||||
// ldarg.2 = in T shader
|
||||
// ldarg.3 = ref D3D12_GPU_DESCRIPTOR_HANDLE r0
|
||||
// ldarg.4 = ref byte r1
|
||||
this.dispatchDataLoader = DynamicMethod<DispatchDataLoader>.New(il =>
|
||||
{
|
||||
foreach (FieldInfo fieldInfo in this.capturedFields)
|
||||
{
|
||||
if (HlslKnownTypes.IsKnownBufferType(fieldInfo.FieldType))
|
||||
{
|
||||
// Load the offset address into the resource buffers
|
||||
il.Emit(OpCodes.Ldarg_3);
|
||||
|
||||
if (totalResourceCount > 0)
|
||||
{
|
||||
il.EmitAddOffset<D3D12_GPU_DESCRIPTOR_HANDLE>(this.totalResourceCount);
|
||||
}
|
||||
|
||||
il.Emit(OpCodes.Ldarg_2);
|
||||
il.EmitReadMember(fieldInfo);
|
||||
|
||||
// Call NativeObject.ThrowIfDisposed()
|
||||
il.Emit(OpCodes.Dup);
|
||||
il.EmitCall(OpCodes.Callvirt, typeof(NativeObject).GetMethod(
|
||||
nameof(NativeObject.ThrowIfDisposed),
|
||||
BindingFlags.Instance | BindingFlags.NonPublic)!, null);
|
||||
|
||||
// Call ThrowIfDeviceMismatch(GraphicsDevice)
|
||||
il.Emit(OpCodes.Dup);
|
||||
il.Emit(OpCodes.Ldarg_1);
|
||||
il.EmitCall(OpCodes.Callvirt, fieldInfo.FieldType.GetMethod(
|
||||
nameof(Buffer<byte>.ThrowIfDeviceMismatch),
|
||||
BindingFlags.Instance | BindingFlags.NonPublic)!, null);
|
||||
|
||||
// Access D3D12GpuDescriptorHandle
|
||||
il.EmitReadMember(fieldInfo.FieldType.GetField(
|
||||
nameof(Buffer<byte>.D3D12GpuDescriptorHandle),
|
||||
BindingFlags.Instance | BindingFlags.NonPublic)!);
|
||||
il.EmitStoreToAddress(typeof(D3D12_GPU_DESCRIPTOR_HANDLE));
|
||||
|
||||
this.totalResourceCount++;
|
||||
}
|
||||
else if (HlslKnownTypes.IsKnownScalarType(fieldInfo.FieldType) ||
|
||||
HlslKnownTypes.IsKnownVectorType(fieldInfo.FieldType))
|
||||
{
|
||||
// Calculate the right offset with 16-bytes padding (HLSL constant buffer)
|
||||
int elementSizeInBytes = Marshal.SizeOf(fieldInfo.FieldType);
|
||||
|
||||
this.totalVariablesByteSize = AlignmentHelper.AlignToBoundary(
|
||||
this.totalVariablesByteSize,
|
||||
elementSizeInBytes,
|
||||
FX.D3D12_COMMONSHADER_CONSTANT_BUFFER_PARTIAL_UPDATE_EXTENTS_BYTE_ALIGNMENT);
|
||||
|
||||
// Load the target address into the variables buffer
|
||||
il.Emit(OpCodes.Ldarg_S, (byte)4);
|
||||
il.EmitAddOffset(totalVariablesByteSize);
|
||||
|
||||
il.Emit(OpCodes.Ldarg_2);
|
||||
il.EmitReadMember(fieldInfo);
|
||||
il.EmitStoreToAddress(fieldInfo.FieldType);
|
||||
|
||||
this.totalVariablesByteSize += elementSizeInBytes;
|
||||
}
|
||||
else ThrowHelper.ThrowArgumentException("Invalid captured member type");
|
||||
}
|
||||
|
||||
il.Emit(OpCodes.Ret);
|
||||
});
|
||||
|
||||
// After all the captured fields have been processed, ansure the reported byte size for
|
||||
// the local variables is padded to the standard alignment for constant buffers. This is
|
||||
// necessary to enable loading all the dispatch data after reinterpreting it to a sequence
|
||||
// of values of size 16 bytes (in particular, Int4 is used), without reading out of bounds.
|
||||
this.totalVariablesByteSize = AlignmentHelper.Pad(
|
||||
this.totalVariablesByteSize,
|
||||
FX.D3D12_COMMONSHADER_CONSTANT_BUFFER_PARTIAL_UPDATE_EXTENTS_BYTE_ALIGNMENT);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeSharp.__Internals;
|
||||
using ComputeSharp.Shaders.Mappings;
|
||||
using ComputeSharp.Shaders.Renderer.Models;
|
||||
using Microsoft.Toolkit.Diagnostics;
|
||||
@@ -113,7 +114,7 @@ namespace ComputeSharp.Shaders.Translation
|
||||
|
||||
@this.LoadFieldsInfo(box);
|
||||
@this.LoadMethodMetadata();
|
||||
@this.BuildDispatchDataLoader();
|
||||
@this.InitializeDispatchDataLoader();
|
||||
|
||||
return @this;
|
||||
}
|
||||
@@ -163,6 +164,7 @@ namespace ComputeSharp.Shaders.Translation
|
||||
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
|
||||
this.capturedFields.Add(fieldInfo);
|
||||
this.hlslResourceInfo.Add(new HlslResourceInfo.Constant(hlslType, hlslName, (int)this.constantBuffersCount++));
|
||||
this.totalResourceCount++;
|
||||
}
|
||||
else if (HlslKnownTypes.IsReadOnlyResourceType(fieldType))
|
||||
{
|
||||
@@ -171,6 +173,7 @@ namespace ComputeSharp.Shaders.Translation
|
||||
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
|
||||
this.capturedFields.Add(fieldInfo);
|
||||
this.hlslResourceInfo.Add(new HlslResourceInfo.ReadOnly(hlslType, hlslName, (int)this.readOnlyBuffersCount++));
|
||||
this.totalResourceCount++;
|
||||
}
|
||||
else if (HlslKnownTypes.IsReadWriteResourceType(fieldType))
|
||||
{
|
||||
@@ -179,6 +182,7 @@ namespace ComputeSharp.Shaders.Translation
|
||||
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
|
||||
this.capturedFields.Add(fieldInfo);
|
||||
this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++));
|
||||
this.totalResourceCount++;
|
||||
}
|
||||
else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType))
|
||||
{
|
||||
|
||||
@@ -1,18 +1,52 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<LangVersion>9.0</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<PackFolder>analyzers\dotnet\cs</PackFolder>
|
||||
<PackSymbols>false</PackSymbols>
|
||||
</PropertyGroup>
|
||||
|
||||
<!--The source generator cannot contain package references or project references, so instead we're just
|
||||
manually linking the source files from ComputeSharp.Core in here. We only need them to extract metadata
|
||||
and to match members based on full name, so the types being in the generator assembly are not an issue.-->
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.8.0" PrivateAssets="all" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.1" PrivateAssets="all" />
|
||||
<Compile Include="..\ComputeSharp.Core\Attributes\AutoConstructorAttribute.cs" Link="Core\Attributes\AutoConstructorAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Attributes\ShaderMethodAttribute.cs" Link="Core\Attributes\ShaderMethodAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Attributes\__Internals\IComputeShaderSourceAttribute.cs" Link="Core\Attributes\__Internals\IComputeShaderSourceAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Attributes\__Internals\ShaderMethodSourceAttribute.cs" Link="Core\Attributes\__Internals\ShaderMethodSourceAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Exceptions\InvalidExecutionContextException.cs" Link="Core\Exceptions\InvalidExecutionContextException.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Exceptions\MissingMethodSourceException.cs" Link="Core\Exceptions\MissingMethodSourceException.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Extensions\MethodInfoExtensions.cs" Link="Core\Extensions\MethodInfoExtensions.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Helpers\AlignmentHelper.cs" Link="Core\Helpers\AlignmentHelper.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Interfaces\IComputeShader.cs" Link="Core\Interfaces\IComputeShader.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Intrinsics\Attributes\PreserveMemberNameAttribute.cs" Link="Core\Intrinsics\Attributes\PreserveMemberNameAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Intrinsics\Hlsl.cs" Link="Core\Intrinsics\Hlsl.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Bool\Bool.cs" Link="Core\Primitives\Bool\Bool.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Bool\Bool2.cs" Link="Core\Primitives\Bool\Bool2.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Bool\Bool3.cs" Link="Core\Primitives\Bool\Bool3.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Bool\Bool4.cs" Link="Core\Primitives\Bool\Bool4.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Double\Double2.cs" Link="Core\Primitives\Double\Double2.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Double\Double3.cs" Link="Core\Primitives\Double\Double3.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Double\Double4.cs" Link="Core\Primitives\Double\Double4.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Float\Float2.cs" Link="Core\Primitives\Float\Float2.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Float\Float3.cs" Link="Core\Primitives\Float\Float3.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Float\Float4.cs" Link="Core\Primitives\Float\Float4.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Int\Int2.cs" Link="Core\Primitives\Int\Int2.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Int\Int3.cs" Link="Core\Primitives\Int\Int3.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Int\Int4.cs" Link="Core\Primitives\Int\Int4.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\ThreadIds.cs" Link="Core\Primitives\ThreadIds.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\UInt\UInt2.cs" Link="Core\Primitives\UInt\UInt2.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\UInt\UInt3.cs" Link="Core\Primitives\UInt\UInt3.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\UInt\UInt4.cs" Link="Core\Primitives\UInt\UInt4.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\ComputeSharp.Core\ComputeSharp.Core.csproj" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.8.0" PrivateAssets="all" Pack="false" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.1" PrivateAssets="all" Pack="false" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,172 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using ComputeSharp.Core.Helpers;
|
||||
using ComputeSharp.SourceGenerators.Extensions;
|
||||
using ComputeSharp.SourceGenerators.Mappings;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Text;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
namespace ComputeSharp.SourceGenerators
|
||||
{
|
||||
[Generator]
|
||||
public class IComputeShaderDataLoaderGenerator : ISourceGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public void Initialize(GeneratorInitializationContext context)
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Execute(GeneratorExecutionContext context)
|
||||
{
|
||||
// Find all the struct declarations
|
||||
ImmutableArray<StructDeclarationSyntax> structDeclarations = (
|
||||
from tree in context.Compilation.SyntaxTrees
|
||||
from structDeclaration in tree.GetRoot().DescendantNodes().OfType<StructDeclarationSyntax>()
|
||||
select structDeclaration).ToImmutableArray();
|
||||
|
||||
// Type attributes
|
||||
AttributeListSyntax[] attributes = new[]
|
||||
{
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments(
|
||||
AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))),
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName("Obsolete")).AddArgumentListArguments(
|
||||
AttributeArgument(LiteralExpression(
|
||||
SyntaxKind.StringLiteralExpression,
|
||||
Literal("This type is not intended to be used directly by user code"))))))
|
||||
};
|
||||
|
||||
foreach (StructDeclarationSyntax structDeclaration in structDeclarations)
|
||||
{
|
||||
SemanticModel semanticModel = context.Compilation.GetSemanticModel(structDeclaration.SyntaxTree);
|
||||
INamedTypeSymbol structDeclarationSymbol = semanticModel.GetDeclaredSymbol(structDeclaration)!;
|
||||
|
||||
// Only process compute shader types
|
||||
if (!structDeclarationSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) continue;
|
||||
|
||||
TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString());
|
||||
BlockSyntax block = Block(GetDispatchDataLoadingStatements(structDeclarationSymbol));
|
||||
|
||||
// Create a static method to create the combined hashcode for a given shader type.
|
||||
// This code takes a block syntax and produces a compilation unit as follows:
|
||||
//
|
||||
// using System;
|
||||
// using System.ComponentModel;
|
||||
//
|
||||
// namespace ComputeSharp.__Internals
|
||||
// {
|
||||
// internal static partial class DispatchDataLoader
|
||||
// {
|
||||
// [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)]
|
||||
// [System.Obsolete("This method is not intended to be called directly by user code")]
|
||||
// public static int LoadDispatchData(GraphicsDevice device, in ShaderType shader, ref ulong r0, ref byte r1)
|
||||
// {
|
||||
// ...
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
var source =
|
||||
CompilationUnit().AddUsings(
|
||||
UsingDirective(IdentifierName("System")),
|
||||
UsingDirective(IdentifierName("System.ComponentModel")),
|
||||
UsingDirective(IdentifierName("System.Runtime.CompilerServices"))).AddMembers(
|
||||
NamespaceDeclaration(IdentifierName("ComputeSharp.__Internals")).AddMembers(
|
||||
ClassDeclaration("DispatchDataLoader").AddModifiers(
|
||||
Token(SyntaxKind.InternalKeyword),
|
||||
Token(SyntaxKind.StaticKeyword),
|
||||
Token(SyntaxKind.PartialKeyword)).AddAttributeLists(attributes).AddMembers(
|
||||
MethodDeclaration(
|
||||
PredefinedType(Token(SyntaxKind.IntKeyword)),
|
||||
Identifier("LoadDispatchData")).AddAttributeLists(
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments(
|
||||
AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))),
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName("Obsolete")).AddArgumentListArguments(
|
||||
AttributeArgument(LiteralExpression(
|
||||
SyntaxKind.StringLiteralExpression,
|
||||
Literal("This method is not intended to be called directly by user code"))))))).AddModifiers(
|
||||
Token(SyntaxKind.PublicKeyword),
|
||||
Token(SyntaxKind.StaticKeyword)).AddParameterListParameters(
|
||||
Parameter(Identifier("device")).WithType(IdentifierName("ComputeSharp.Graphics.GraphicsDevice")),
|
||||
Parameter(Identifier("shader")).WithModifiers(TokenList(Token(SyntaxKind.InKeyword))).WithType(shaderType),
|
||||
Parameter(Identifier("r0")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(PredefinedType(Token(SyntaxKind.ULongKeyword))),
|
||||
Parameter(Identifier("r1")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(PredefinedType(Token(SyntaxKind.ByteKeyword))))
|
||||
.WithBody(block)))
|
||||
.WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList())))
|
||||
.NormalizeWhitespace()
|
||||
.ToFullString();
|
||||
|
||||
// Clear the attribute list to avoid duplicates
|
||||
attributes = Array.Empty<AttributeListSyntax>();
|
||||
|
||||
// Add the method source attribute
|
||||
context.AddSource(structDeclarationSymbol.GetGeneratedFileName<IComputeShaderDataLoaderGenerator>(), SourceText.From(source, Encoding.UTF8));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of statements to load the dispatch data for a given shader
|
||||
/// </summary>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
|
||||
[Pure]
|
||||
private static IEnumerable<StatementSyntax> GetDispatchDataLoadingStatements(INamedTypeSymbol structDeclarationSymbol)
|
||||
{
|
||||
int
|
||||
resourceOffset = 0,
|
||||
rawDataOffset = sizeof(int) * 3;
|
||||
|
||||
foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
|
||||
{
|
||||
INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type;
|
||||
string typeName = typeSymbol.GetFullMetadataName();
|
||||
|
||||
if (HlslKnownTypes.IsTypedResourceType(typeName))
|
||||
{
|
||||
yield return ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
ParseExpression($"Unsafe.Add(ref r0, {resourceOffset++})"),
|
||||
ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(shader.{fieldSymbol.Name}, device)")));
|
||||
}
|
||||
else if (HlslKnownTypes.IsScalarOrVectorType(typeName))
|
||||
{
|
||||
var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName);
|
||||
|
||||
// Calculate the right offset with 16-bytes padding (HLSL constant buffer).
|
||||
// Since we're in a constant buffer, we need to both pad the starting offset
|
||||
// to be aligned to the packing size of the type, and also to align the initial
|
||||
// offset to ensure that values do not cross 16 bytes boundaries either.
|
||||
rawDataOffset = AlignmentHelper.AlignToBoundary(
|
||||
AlignmentHelper.Pad(rawDataOffset, fieldPack),
|
||||
fieldSize,
|
||||
16);
|
||||
|
||||
yield return ExpressionStatement(
|
||||
ParseExpression($"Unsafe.WriteUnaligned(ref Unsafe.Add(ref r1, {rawDataOffset}), shader.{fieldSymbol.Name})"));
|
||||
|
||||
rawDataOffset += fieldSize;
|
||||
}
|
||||
}
|
||||
|
||||
// After all the captured fields have been processed, ansure the reported byte size for
|
||||
// the local variables is padded to the standard alignment for constant buffers. This is
|
||||
// necessary to enable loading all the dispatch data after reinterpreting it to a sequence
|
||||
// of values of size 16 bytes (in particular, Int4 is used), without reading out of bounds.
|
||||
rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
|
||||
|
||||
yield return ReturnStatement(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(rawDataOffset)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using ComputeSharp.SourceGenerators.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Text;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
namespace ComputeSharp.SourceGenerators
|
||||
{
|
||||
[Generator]
|
||||
public class IComputeShaderHashCodeGenerator : ISourceGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public void Initialize(GeneratorInitializationContext context)
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Execute(GeneratorExecutionContext context)
|
||||
{
|
||||
// Find all the struct declarations
|
||||
ImmutableArray<StructDeclarationSyntax> structDeclarations = (
|
||||
from tree in context.Compilation.SyntaxTrees
|
||||
from structDeclaration in tree.GetRoot().DescendantNodes().OfType<StructDeclarationSyntax>()
|
||||
select structDeclaration).ToImmutableArray();
|
||||
|
||||
// Type attributes
|
||||
AttributeListSyntax[] attributes = new[]
|
||||
{
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments(
|
||||
AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))),
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName("Obsolete")).AddArgumentListArguments(
|
||||
AttributeArgument(LiteralExpression(
|
||||
SyntaxKind.StringLiteralExpression,
|
||||
Literal("This type is not intended to be used directly by user code"))))))
|
||||
};
|
||||
|
||||
foreach (StructDeclarationSyntax structDeclaration in structDeclarations)
|
||||
{
|
||||
SemanticModel semanticModel = context.Compilation.GetSemanticModel(structDeclaration.SyntaxTree);
|
||||
INamedTypeSymbol structDeclarationSymbol = semanticModel.GetDeclaredSymbol(structDeclaration)!;
|
||||
|
||||
// Only process compute shader types
|
||||
if (!structDeclarationSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) continue;
|
||||
|
||||
TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString());
|
||||
BlockSyntax block = Block(GetDelegateHashCodeStatements(structDeclarationSymbol));
|
||||
|
||||
if (block.Statements.Count == 1) continue;
|
||||
|
||||
// Create a static method to create the combined hashcode for a given shader type.
|
||||
// This code takes a block syntax and produces a compilation unit as follows:
|
||||
//
|
||||
// using System;
|
||||
// using System.ComponentModel;
|
||||
//
|
||||
// namespace ComputeSharp.__Internals
|
||||
// {
|
||||
// internal static partial class HashCodeProvider
|
||||
// {
|
||||
// [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)]
|
||||
// [System.Obsolete("This method is not intended to be called directly by user code")]
|
||||
// public static int CombineHashCode(int hash, in ShaderType shader)
|
||||
// {
|
||||
// return ...;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
var source =
|
||||
CompilationUnit().AddUsings(
|
||||
UsingDirective(IdentifierName("System")),
|
||||
UsingDirective(IdentifierName("System.ComponentModel"))).AddMembers(
|
||||
NamespaceDeclaration(IdentifierName("ComputeSharp.__Internals")).AddMembers(
|
||||
ClassDeclaration("HashCodeProvider").AddModifiers(
|
||||
Token(SyntaxKind.InternalKeyword),
|
||||
Token(SyntaxKind.StaticKeyword),
|
||||
Token(SyntaxKind.PartialKeyword)).AddAttributeLists(attributes).AddMembers(
|
||||
MethodDeclaration(
|
||||
PredefinedType(Token(SyntaxKind.IntKeyword)),
|
||||
Identifier("CombineHash")).AddAttributeLists(
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments(
|
||||
AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))),
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName("Obsolete")).AddArgumentListArguments(
|
||||
AttributeArgument(LiteralExpression(
|
||||
SyntaxKind.StringLiteralExpression,
|
||||
Literal("This method is not intended to be called directly by user code"))))))).AddModifiers(
|
||||
Token(SyntaxKind.PublicKeyword),
|
||||
Token(SyntaxKind.StaticKeyword)).AddParameterListParameters(
|
||||
Parameter(Identifier("hash")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
|
||||
Parameter(Identifier("shader")).WithModifiers(TokenList(Token(SyntaxKind.InKeyword))).WithType(shaderType))
|
||||
.WithBody(block))))
|
||||
.NormalizeWhitespace()
|
||||
.ToFullString();
|
||||
|
||||
// Clear the attribute list to avoid duplicates
|
||||
attributes = Array.Empty<AttributeListSyntax>();
|
||||
|
||||
// Add the method source attribute
|
||||
context.AddSource(structDeclarationSymbol.GetGeneratedFileName<IComputeShaderHashCodeGenerator>(), SourceText.From(source, Encoding.UTF8));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of statements to process the hashcode of the captured delegates.
|
||||
/// </summary>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to hash the captured delegates.</returns>
|
||||
[Pure]
|
||||
private static IEnumerable<StatementSyntax> GetDelegateHashCodeStatements(INamedTypeSymbol structDeclarationSymbol)
|
||||
{
|
||||
foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
|
||||
{
|
||||
INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type;
|
||||
|
||||
if (typeSymbol.TypeKind != TypeKind.Delegate) continue;
|
||||
|
||||
// hash += hash << 5;
|
||||
yield return ExpressionStatement(ParseExpression($"hash += hash << 5"));
|
||||
|
||||
// hash += shader.Field[#i].Method.GetHashCode();
|
||||
yield return ExpressionStatement(ParseExpression($"hash += shader.{fieldSymbol.Name}.Method.GetHashCode()"));
|
||||
}
|
||||
|
||||
yield return ReturnStatement(IdentifierName("hash"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Collections.Immutable;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using ComputeSharp.__Internals;
|
||||
using ComputeSharp.SourceGenerators.Extensions;
|
||||
using ComputeSharp.SourceGenerators.Mappings;
|
||||
using ComputeSharp.SourceGenerators.SyntaxRewriters;
|
||||
@@ -81,7 +82,8 @@ namespace ComputeSharp.SourceGenerators
|
||||
|
||||
// Create the compilation unit with the source attribute
|
||||
var source =
|
||||
CompilationUnit().AddAttributeLists(
|
||||
CompilationUnit().AddUsings(
|
||||
UsingDirective(IdentifierName("ComputeSharp.__Internals"))).AddAttributeLists(
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName(typeof(IComputeShaderSourceAttribute).FullName)).AddArgumentListArguments(
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(structDeclarationSymbol.GetFullMetadataName()))),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Numerics;
|
||||
|
||||
namespace ComputeSharp.SourceGenerators.Mappings
|
||||
@@ -9,9 +10,9 @@ namespace ComputeSharp.SourceGenerators.Mappings
|
||||
internal static class HlslKnownSizes
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the mapping of supported known sizes to HLSL type names.
|
||||
/// The mapping of supported known sizes to HLSL type names.
|
||||
/// </summary>
|
||||
public static IReadOnlyDictionary<string, (int Size, int Pack)> KnownSizes { get; } = new Dictionary<string, (int, int)>
|
||||
private static IReadOnlyDictionary<string, (int, int)> KnownSizes = new Dictionary<string, (int, int)>
|
||||
{
|
||||
[typeof(bool).FullName] = (4, 4),
|
||||
[typeof(int).FullName] = (4, 4),
|
||||
@@ -43,5 +44,16 @@ namespace ComputeSharp.SourceGenerators.Mappings
|
||||
[typeof(Double3).FullName] = (24, 8),
|
||||
[typeof(Double3).FullName] = (32, 8)
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Gets the size and alignment info for a specified primitive type.
|
||||
/// </summary>
|
||||
/// <param name="typeName">The type name to get info for.</param>
|
||||
/// <returns>The size and and alignment for the input type.</returns>
|
||||
[Pure]
|
||||
public static (int Size, int Pack) GetTypeInfo(string typeName)
|
||||
{
|
||||
return KnownSizes[typeName];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -78,6 +78,18 @@ namespace ComputeSharp.SourceGenerators.Mappings
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether or not a given type name matches a typed resource type.
|
||||
/// </summary>
|
||||
/// <param name="typeName">The input type name to check.</param>
|
||||
/// <returns>Whether or not <paramref name="typeName"/> represents a typed resource type.</returns>
|
||||
public static bool IsScalarOrVectorType(string typeName)
|
||||
{
|
||||
return
|
||||
KnownTypes.ContainsKey(typeName) &&
|
||||
typeName != typeof(ThreadIds).FullName;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the mapped HLSL-compatible type name for the input type symbol.
|
||||
/// </summary>
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Collections.Immutable;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using ComputeSharp.__Internals;
|
||||
using ComputeSharp.SourceGenerators.Extensions;
|
||||
using ComputeSharp.SourceGenerators.SyntaxRewriters;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
@@ -2,9 +2,8 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net5.0</TargetFramework>
|
||||
<LangVersion>preview</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<LangVersion>9.0</LangVersion>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -12,8 +11,16 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="C:\Program Files (x86)\Windows Kits\10\Redist\D3D\x64\dxcompiler.dll" Visible="False" CopyToOutputDirectory="PreserveNewest" />
|
||||
<None Include="C:\Program Files (x86)\Windows Kits\10\Redist\D3D\x64\dxil.dll" Visible="False" CopyToOutputDirectory="PreserveNewest" />
|
||||
<None Include="Libraries\dxcompiler.dll"
|
||||
Link="dxcompiler.dll"
|
||||
Visible="False"
|
||||
CopyToOutputDirectory="PreserveNewest"
|
||||
PackFolder="runtimes\win-x64\native" />
|
||||
<None Include="Libraries\dxil.dll"
|
||||
Link="dxil.dll"
|
||||
Visible="False"
|
||||
CopyToOutputDirectory="PreserveNewest"
|
||||
PackFolder="runtimes\win-x64\native" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,26 +0,0 @@
|
||||
<?xml version="1.0"?>
|
||||
<package >
|
||||
<metadata>
|
||||
<id>ComputeSharp</id>
|
||||
<version>2.0.0</version>
|
||||
<title>ComputeSharp</title>
|
||||
<authors>Sergio Pedri</authors>
|
||||
<owners>Sergio Pedri</owners>
|
||||
<license type="expression">MIT</license>
|
||||
<projectUrl>https://github.com/Sergio0694/ComputeSharp</projectUrl>
|
||||
<iconUrl>https://i.imgur.com/ntvmD6P.png</iconUrl>
|
||||
<requireLicenseAcceptance>false</requireLicenseAcceptance>
|
||||
<description>A .NET 5 library to run C# code in parallel on the GPU through DX12 and dynamically generated HLSL compute shaders</description>
|
||||
<releaseNotes>New interlocked intrinsics APIs, performance and memory optimizations</releaseNotes>
|
||||
<copyright>Copyright (c) 2020 Sergio Pedri</copyright>
|
||||
<tags>dotnet net netcore netstandard csharp library graphics shader hlsl compute gpu</tags>
|
||||
<repository type="git" url="https://github.com/Sergio0694/ComputeSharp.git" branch="master" />
|
||||
<dependencies>
|
||||
<dependency id="ICSharpCode.Decompiler" version="5.0.2.5153" />
|
||||
<dependency id="Microsoft.CodeAnalysis.CSharp" version="3.7.0" />
|
||||
<dependency id="Microsoft.Toolkit" Version="7.0.0-preview4" />
|
||||
<dependency id="Stubble.Core" version="1.9.3" />
|
||||
<dependency id="TerraFX.Interop.Windows" version="10.0.19041-beta1" />
|
||||
</dependencies>
|
||||
</metadata>
|
||||
</package>
|
||||
バイナリファイルは表示されません。
バイナリファイルは表示されません。
@@ -0,0 +1,9 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="NuGetizer" Version="0.6.0" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net5.0</TargetFramework>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.3" />
|
||||
<PackageReference Include="MSTest.TestAdapter" Version="2.1.2" />
|
||||
<PackageReference Include="MSTest.TestFramework" Version="2.1.2" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="3.8.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
差分なしでファイル名を変更。
@@ -9,11 +9,9 @@
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.3" />
|
||||
<PackageReference Include="MSTest.TestAdapter" Version="2.1.2" />
|
||||
<PackageReference Include="MSTest.TestFramework" Version="2.1.2" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="3.8.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp\ComputeSharp.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
using System;
|
||||
using System.Reflection.Emit;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
namespace ComputeSharp.Tests.Internals
|
||||
{
|
||||
[TestClass]
|
||||
[TestCategory("DynamicMethod")]
|
||||
public class DynamicMethodTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void TestFunc()
|
||||
{
|
||||
Func<int, int> square = DynamicMethod<Func<int, int>>.New(il =>
|
||||
{
|
||||
// Due to the instance method trick, the first parameter is at offset 1.
|
||||
// See the docs on DynamicMethod<T>.New for more info on how this works.
|
||||
il.Emit(OpCodes.Ldarg_1);
|
||||
il.Emit(OpCodes.Dup);
|
||||
il.Emit(OpCodes.Mul);
|
||||
il.Emit(OpCodes.Ret);
|
||||
});
|
||||
|
||||
int result = square(2); // result = 2 * 2
|
||||
|
||||
Assert.IsTrue(result == 4);
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net5.0</TargetFramework>
|
||||
<LangVersion>9.0</LangVersion>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" />
|
||||
<PackageReference Include="MSTest.TestAdapter" Version="2.1.1" />
|
||||
<PackageReference Include="MSTest.TestFramework" Version="2.1.1" />
|
||||
<PackageReference Include="coverlet.collector" Version="1.3.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,196 @@
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
|
||||
namespace ComputeSharp.Tests.NativeLibrariesResolver
|
||||
{
|
||||
[TestClass]
|
||||
public class NativeLibrariesResolverTests
|
||||
{
|
||||
static NativeLibrariesResolverTests()
|
||||
{
|
||||
string path = Path.GetDirectoryName(typeof(NativeLibrariesResolverTests).Assembly.Location);
|
||||
|
||||
while (Path.GetFileName(path) is not "ComputeSharp")
|
||||
{
|
||||
path = Path.GetDirectoryName(path);
|
||||
}
|
||||
|
||||
SampleProjectDirectory = Path.Combine(path, "samples", "ComputeSharp.Sample.NuGet");
|
||||
|
||||
string
|
||||
sampleProjectPath = Path.Combine(SampleProjectDirectory, "ComputeSharp.Sample.NuGet.csproj"),
|
||||
packagingProjectPath = Path.Combine(path, "src", "ComputeSharp.Package", "ComputeSharp.Package.msbuildproj");
|
||||
|
||||
// Run dotnet pack and on the packaging project, to ensure the local NuGet package is
|
||||
// available. Then run dotnet restore on the sample project. This is done so that
|
||||
// other tests can skip the restore step to run faster, as there's lots of them.
|
||||
Process.Start("dotnet", $"pack {packagingProjectPath} -c Release").WaitForExit();
|
||||
Process.Start("dotnet", $"restore {sampleProjectPath}").WaitForExit();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the directory of the ComputeSharp.Sample.NuGet project.
|
||||
/// </summary>
|
||||
private static string SampleProjectDirectory { get; }
|
||||
|
||||
[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)
|
||||
{
|
||||
// "dotnet run" fails with "--no-restore", so in this case we restore packages as well
|
||||
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)
|
||||
{
|
||||
BuildSampleProject(configuration, rid);
|
||||
|
||||
string realtivePathToDll = Path.Combine("bin", $"{configuration}", "net5.0", $"{ToDirectory(rid)}", "ComputeSharp.Sample.NuGet.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)
|
||||
{
|
||||
BuildSampleProject(configuration, rid);
|
||||
|
||||
string pathToDllDirectory = Path.Combine(SampleProjectDirectory, "bin", $"{configuration}", "net5.0", $"{ToDirectory(rid)}");
|
||||
|
||||
Assert.AreEqual(0, Exec(pathToDllDirectory, "dotnet", "ComputeSharp.Sample.NuGet.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)
|
||||
{
|
||||
BuildSampleProject(configuration, rid);
|
||||
|
||||
string relativePathToAppHost = Path.Combine("bin", $"{configuration}", "net5.0", $"{ToDirectory(rid)}", "ComputeSharp.Sample.NuGet.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)
|
||||
{
|
||||
BuildSampleProject(configuration, rid);
|
||||
|
||||
string pathToAppHostDirectory = Path.Combine(SampleProjectDirectory, "bin", $"{configuration}", "net5.0", $"{ToDirectory(rid)}");
|
||||
|
||||
Assert.AreEqual(0, Exec(pathToAppHostDirectory, "ComputeSharp.Sample.NuGet.exe", ""));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(Configuration.Debug)]
|
||||
[DataRow(Configuration.Release)]
|
||||
public void DotnetPublishWorks(Configuration configuration)
|
||||
{
|
||||
// Publishing without specifying an RID is not supported
|
||||
Exec(SampleProjectDirectory, "dotnet", $"publish -c {configuration} -r win-x64 --no-restore");
|
||||
|
||||
string pathToAppHost = Path.Combine("bin", $"{configuration}", "net5.0", "win-x64", "publish", "ComputeSharp.Sample.NuGet.exe");
|
||||
|
||||
Assert.AreEqual(0, Exec(SampleProjectDirectory, pathToAppHost, ""));
|
||||
}
|
||||
|
||||
/// <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 static void BuildSampleProject(Configuration configuration, RID rid)
|
||||
{
|
||||
Exec(SampleProjectDirectory, "dotnet", $"build -c {configuration} {ToOption(rid)} --no-restore");
|
||||
}
|
||||
|
||||
/// <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
|
||||
};
|
||||
|
||||
Process process = Process.Start(startInfo);
|
||||
|
||||
process.WaitForExit();
|
||||
|
||||
return process.ExitCode;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a text representation of a cmd option for the dotnet tool, 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) => 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 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) => 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,11 +14,10 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\ComputeSharp\ComputeSharp.csproj" />
|
||||
<ProjectReference
|
||||
Include="..\..\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj"
|
||||
OutputItemType="Analyzer"
|
||||
ReferenceOutputAssembly="false"
|
||||
PrivateAssets="contentfiles;build"/>
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj"
|
||||
OutputItemType="Analyzer"
|
||||
ReferenceOutputAssembly="false"
|
||||
PrivateAssets="contentfiles;build"/>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
新しいイシューから参照
ユーザーをブロックする