diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index 1d2b6b8f..52e944dc 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -2,6 +2,10 @@ name: .NET on: [push, pull_request] +env: + EXCLUDE_RUN_ID_FROM_PACKAGE: false + EXCLUDE_SUFFIX_FROM_VERSION: false + jobs: # Build the whole ComputeSharp solution, in Debug @@ -44,8 +48,49 @@ jobs: run: msbuild -t:restore,build /p:Configuration=Release /p:Platform=x64 shell: cmd - # Run all the unit tests referencing the ComputeSharp project directly - run-tests: + # Build the .msbuildproj projects and the UWP/WinUI projects to generate all the NuGet packages. + # This workflow also uploads the resulting packages as artifacts. + build-packages: + runs-on: windows-2022 + steps: + - name: Git checkout + uses: actions/checkout@v2 + - name: Add msbuild to PATH + uses: microsoft/setup-msbuild@v1.0.3 + - name: Setup .NET 6 SDK + uses: actions/setup-dotnet@v1 + with: + dotnet-version: 6.0.x + - name: Build ComputeSharp.Core package + run: dotnet build src\ComputeSharp.Core.Package\ComputeSharp.Core.Package.msbuildproj -c Release + shell: cmd + - name: Build ComputeSharp package + run: dotnet build src\ComputeSharp.Package\ComputeSharp.Package.msbuildproj -c Release + shell: cmd + - name: Build ComputeSharp.Dynamic package + run: dotnet build src\ComputeSharp.Dynamic.Package\ComputeSharp.Dynamic.Package.msbuildproj -c Release + shell: cmd + - name: Build ComputeSharp.D2D1 package + run: dotnet build src\ComputeSharp.D2D1.Package\ComputeSharp.D2D1.Package.msbuildproj -c Release + shell: cmd + - name: Build ComputeSharp.Uwp package + run: msbuild src\ComputeSharp.Uwp\ComputeSharp.Uwp.csproj -t:restore,build,pack /p:Configuration=Release + shell: cmd + - name: Restore ComputeSharp.WinUI project + run: msbuild src\ComputeSharp.WinUI\ComputeSharp.WinUI.csproj -t:restore /p:Configuration=Release + shell: cmd + - name: Build ComputeSharp.WinUI package + run: msbuild src\ComputeSharp.WinUI\ComputeSharp.WinUI.csproj -t:pack /p:Configuration=Release + shell: cmd # Packing needs to be done separately and with no previous build target for it to work correctly + - name: Upload package artifacts + uses: actions/upload-artifact@v2 + with: + name: nuget_preview + path: artifacts\*.nupkg + if-no-files-found: error + + # Run all the DX12 unit tests referencing the ComputeSharp project directly + run-dx12-tests: if: success() needs: [build-solution-debug, build-solution-release] runs-on: windows-2022 @@ -91,10 +136,26 @@ jobs: run: dotnet test tests\ComputeSharp.Tests.SourceGenerators\ComputeSharp.Tests.SourceGenerators.csproj -v n -l "console;verbosity=detailed" shell: cmd - # Run all the local samples to ensure they build and run with no errors - run-samples: + # Run all the D2D1 unit tests (referencing ComputeSharp.D2D1) + run-d2d1-tests: if: success() - needs: [run-tests] + needs: [build-solution-debug, build-solution-release] + runs-on: windows-2022 + steps: + - name: Git checkout + uses: actions/checkout@v2 + - name: Setup .NET 6 SDK + uses: actions/setup-dotnet@v1 + with: + dotnet-version: 6.0.x + - name: Run ComputeSharp.D2D1.Tests + run: dotnet test tests\ComputeSharp.D2D1.Tests\ComputeSharp.D2D1.Tests.csproj -c Release -v n -l "console;verbosity=detailed" + shell: cmd + + # Run all the local samples to ensure they build and run with no errors + run-dx12-samples: + if: success() + needs: [build-solution-debug, build-solution-release] runs-on: windows-2022 steps: - name: Git checkout @@ -156,42 +217,12 @@ jobs: run: dotnet build samples\ComputeSharp.SwapChain\ComputeSharp.SwapChain.csproj -c Release shell: cmd - # Buils the .msbuildproj project to generate the NuGet package. - # This workflow also uploads the resulting package as an artifact. - build-package: + # Download the NuGet packages generated in the previous job and use them + # to build and run the sample project referencing them. This is used as + # a test to ensure the NuGet packages work in a consuming project. + verify-packages: if: success() - needs: [build-solution-debug, build-solution-release] - runs-on: windows-2022 - steps: - - name: Git checkout - uses: actions/checkout@v2 - - name: Setup .NET 6 SDK - uses: actions/setup-dotnet@v1 - with: - dotnet-version: 6.0.x - - name: Build ComputeSharp package - run: dotnet build src\ComputeSharp.Package\ComputeSharp.Package.msbuildproj -c Release /p:ContinuousIntegrationBuild=True - shell: cmd - - name: Upload ComputeSharp package artifact - uses: actions/upload-artifact@v2 - with: - name: ComputeSharp.nupkg - path: src\ComputeSharp.Package\bin\Release\*.nupkg - - name: Build ComputeSharp.Dynamic package - run: dotnet build src\ComputeSharp.Dynamic.Package\ComputeSharp.Dynamic.Package.msbuildproj -c Release /p:ContinuousIntegrationBuild=True - shell: cmd - - name: Upload ComputeSharp.Dynamic package artifact - uses: actions/upload-artifact@v2 - with: - name: ComputeSharp.Dynamic.nupkg - path: src\ComputeSharp.Dynamic.Package\bin\Release\*.nupkg - - # Download the NuGet package generated in the previous job and use it - # to build and run the sample project referencing it. This is used as - # a test to ensure the NuGet package works in a consuming project. - verify-package: - if: success() - needs: [build-package] + needs: [build-packages] runs-on: windows-2022 steps: - name: Git checkout @@ -201,18 +232,13 @@ jobs: with: dotnet-version: 6.0.x - name: Create local NuGet feed - run: mkdir src\ComputeSharp.Package\bin\Release + run: mkdir artifacts shell: cmd - - name: Download ComputeSharp package artifact + - name: Download package artifacts uses: actions/download-artifact@v2 with: - name: ComputeSharp.nupkg - path: src\ComputeSharp.Package\bin\Release\ComputeSharp.nupkg - - name: Download ComputeSharp.Dynamic package artifact - uses: actions/download-artifact@v2 - with: - name: ComputeSharp.Dynamic.nupkg - path: src\ComputeSharp.Dynamic.Package\bin\Release\ComputeSharp.Dynamic.nupkg + name: nuget_preview + path: artifacts - name: Build ComputeSharp.Sample.NuGet (.NET 6) run: dotnet build samples\ComputeSharp.Sample.NuGet\ComputeSharp.Sample.NuGet.csproj -c Release -f net6.0 shell: cmd @@ -237,7 +263,7 @@ jobs: # regardless of whether the app is shipping with R2R, self-contained, etc. verify-package-native-libs: if: success() - needs: [verify-package] + needs: [build-packages] runs-on: windows-2022 steps: - name: Git checkout @@ -248,55 +274,4 @@ jobs: dotnet-version: 6.0.x - name: Run ComputeSharp.Tests.NativeLibrariesResolver run: dotnet test tests\ComputeSharp.Tests.NativeLibrariesResolver\ComputeSharp.Tests.NativeLibrariesResolver.csproj -v n -l "console;verbosity=detailed" - shell: cmd - - # Build the WinUI project again to generate a NuGet package from it. - # This workflow also uploads the resulting package as an artifact. - build-package-winui: - if: success() - needs: [verify-package] - runs-on: windows-2022 - steps: - - name: Git checkout - uses: actions/checkout@v2 - - name: Add msbuild to PATH - uses: microsoft/setup-msbuild@v1.0.3 - - name: Setup .NET SDK - uses: actions/setup-dotnet@v1 - with: - dotnet-version: 6.0.x - - name: Build - run: msbuild src\ComputeSharp.WinUI\ComputeSharp.WinUI.csproj -t:restore /p:Configuration=Release /p:ContinuousIntegrationBuild=True - shell: cmd - - name: Build - run: msbuild src\ComputeSharp.WinUI\ComputeSharp.WinUI.csproj -t:pack /p:Configuration=Release /p:ContinuousIntegrationBuild=True - shell: cmd # Packing needs to be done separately and with no previous build target for it to work correctly - - name: Upload package artifact - uses: actions/upload-artifact@v2 - with: - name: ComputeSharp.WinUI.nupkg - path: src\ComputeSharp.WinUI\bin\Release\*.nupkg - - # Build the UWP project again to generate a NuGet package from it. - # This workflow also uploads the resulting package as an artifact, like the WinUI one. - build-package-uwp: - if: success() - needs: [verify-package] - runs-on: windows-2022 - steps: - - name: Git checkout - uses: actions/checkout@v2 - - name: Add msbuild to PATH - uses: microsoft/setup-msbuild@v1.0.3 - - name: Setup .NET SDK - uses: actions/setup-dotnet@v1 - with: - dotnet-version: 6.0.x - - name: Build - run: msbuild src\ComputeSharp.Uwp\ComputeSharp.Uwp.csproj -t:restore,build,pack /p:Configuration=Release /p:ContinuousIntegrationBuild=True - shell: cmd - - name: Upload package artifact - uses: actions/upload-artifact@v2 - with: - name: ComputeSharp.Uwp.nupkg - path: src\ComputeSharp.Uwp\bin\Release\*.nupkg \ No newline at end of file + shell: cmd \ No newline at end of file diff --git a/.gitignore b/.gitignore index b444c010..a49e5f52 100644 --- a/.gitignore +++ b/.gitignore @@ -27,6 +27,10 @@ bld/ [Oo]bj/ [Ll]og/ +# Include the bundled libraries +!**/Libraries/x64/ +!**/Libraries/arm64/ + # Debug view types !**/Resources/Debug diff --git a/ComputeSharp.sln b/ComputeSharp.sln index fe3ef9c6..b8413535 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -30,9 +30,12 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.SourceGenerato EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NuGet", "NuGet", "{FB17EF84-9208-47AC-921F-680CB1DAD8BA}" ProjectSection(SolutionItems) = preProject + src\ComputeSharp.Core.Package\ComputeSharp.Core.Package.msbuildproj = src\ComputeSharp.Core.Package\ComputeSharp.Core.Package.msbuildproj + src\ComputeSharp.D2D1.Package\ComputeSharp.D2D1.Package.msbuildproj = src\ComputeSharp.D2D1.Package\ComputeSharp.D2D1.Package.msbuildproj src\ComputeSharp.Dynamic.Package\ComputeSharp.Dynamic.Package.msbuildproj = src\ComputeSharp.Dynamic.Package\ComputeSharp.Dynamic.Package.msbuildproj src\ComputeSharp.Package\ComputeSharp.Package.msbuildproj = src\ComputeSharp.Package\ComputeSharp.Package.msbuildproj - src\ComputeSharp.Package\icon.png = src\ComputeSharp.Package\icon.png + src\ComputeSharp.Core.Package\icon.png = src\ComputeSharp.Core.Package\icon.png + src\ComputeSharp.Core.Package\icon_highres.png = src\ComputeSharp.Core.Package\icon_highres.png EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Sample", "samples\ComputeSharp.Sample\ComputeSharp.Sample.csproj", "{7048DEEA-0A6F-46A0-B951-B682A8F1CB75}" @@ -75,6 +78,26 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Dynamic", "src EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "TerraFX.Interop.Windows.Dynamic", "src\TerraFX.Interop.Windows.Dynamic\TerraFX.Interop.Windows.Dynamic.shproj", "{158F984D-CD96-4062-BD02-2268946031A0}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.D2D1", "src\ComputeSharp.D2D1\ComputeSharp.D2D1.csproj", "{4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}" +EndProject +Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "TerraFX.Interop.Windows.D2D1", "src\TerraFX.Interop.Windows.D2D1\TerraFX.Interop.Windows.D2D1.shproj", "{9DA1DA9F-F8B2-4B25-BE80-C21F773029E3}" +EndProject +Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "ComputeSharp.D2D1.NetStandard", "src\ComputeSharp.D2D1.NetStandard\ComputeSharp.D2D1.NetStandard.shproj", "{2608EB41-F98B-4BE5-9F4D-68FED6115088}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Core", "src\ComputeSharp.Core\ComputeSharp.Core.csproj", "{764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}" +EndProject +Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "ComputeSharp.Core.NetStandard", "src\ComputeSharp.Core.NetStandard\ComputeSharp.Core.NetStandard.shproj", "{3ACACF03-6B20-40BA-B8EC-11AC1624D2C9}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Core.SourceGenerators", "src\ComputeSharp.Core.SourceGenerators\ComputeSharp.Core.SourceGenerators.csproj", "{BFB003D1-788B-48DE-8065-39479C162CB0}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.D2D1.SourceGenerators", "src\ComputeSharp.D2D1.SourceGenerators\ComputeSharp.D2D1.SourceGenerators.csproj", "{E44053BD-A761-47FB-AA78-087A599672EA}" +EndProject +Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "ComputeSharp.SourceGeneration", "src\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.shproj", "{51D5A422-D3A5-4C4D-8A6D-A048940BF279}" +EndProject +Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "ComputeSharp.SourceGeneration.Hlsl", "src\ComputeSharp.SourceGeneration.Hlsl\ComputeSharp.SourceGeneration.Hlsl.shproj", "{9AC496A3-BBF0-4C8F-A50D-A20BF01C5E05}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.D2D1.Tests", "tests\ComputeSharp.D2D1.Tests\ComputeSharp.D2D1.Tests.csproj", "{209C95A3-FA53-431B-B688-3299CA6C29D2}" +EndProject Global GlobalSection(SharedMSBuildProjectFiles) = preSolution samples\ComputeSharp.SwapChain.Core.Shared\ComputeSharp.SwapChain.Core.Shared.projitems*{0071701e-b9c5-4098-be5f-ef556c4553c6}*SharedItemsImports = 5 @@ -82,18 +105,36 @@ Global samples\ComputeSharp.SwapChain.Shaders.Shared\ComputeSharp.SwapChain.Shaders.Shared.projitems*{0800bd51-499d-44c2-9417-fd1f7fdfe9c4}*SharedItemsImports = 13 src\ComputeSharp.UI\ComputeSharp.UI.projitems*{0c82ede1-5b8a-4df3-87da-700b29d5e265}*SharedItemsImports = 13 src\TerraFX.Interop.Windows.Dynamic\TerraFX.Interop.Windows.Dynamic.projitems*{158f984d-cd96-4062-bd02-2268946031a0}*SharedItemsImports = 13 + src\ComputeSharp.D2D1.NetStandard\ComputeSharp.D2D1.NetStandard.projitems*{2608eb41-f98b-4be5-9f4d-68fed6115088}*SharedItemsImports = 13 src\ComputeSharp.NetStandard\ComputeSharp.NetStandard.projitems*{314eb353-e7e3-4146-8111-685cc83ec1de}*SharedItemsImports = 5 src\TerraFX.Interop.Windows\TerraFX.Interop.Windows.projitems*{314eb353-e7e3-4146-8111-685cc83ec1de}*SharedItemsImports = 5 + src\ComputeSharp.Core.NetStandard\ComputeSharp.Core.NetStandard.projitems*{3acacf03-6b20-40ba-b8ec-11ac1624d2c9}*SharedItemsImports = 13 + src\ComputeSharp.D2D1.NetStandard\ComputeSharp.D2D1.NetStandard.projitems*{4d7d9ba8-a821-4b1c-9ee2-cbcf5849906e}*SharedItemsImports = 5 + src\TerraFX.Interop.Windows.D2D1\TerraFX.Interop.Windows.D2D1.projitems*{4d7d9ba8-a821-4b1c-9ee2-cbcf5849906e}*SharedItemsImports = 5 src\TerraFX.Interop.Windows\TerraFX.Interop.Windows.projitems*{514ff00e-bbf0-4d55-a47c-eeeb6208adce}*SharedItemsImports = 13 + src\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems*{51d5a422-d3a5-4c4d-8a6d-a048940bf279}*SharedItemsImports = 13 samples\ComputeSharp.Sample.Shared\ComputeSharp.Sample.Shared.projitems*{7048deea-0a6f-46a0-b951-b682a8f1cb75}*SharedItemsImports = 5 samples\ComputeSharp.SwapChain.Core.Shared\ComputeSharp.SwapChain.Core.Shared.projitems*{751bb05b-563d-4b3a-94c6-15e2d79d35ea}*SharedItemsImports = 13 + src\ComputeSharp.Core.NetStandard\ComputeSharp.Core.NetStandard.projitems*{764bc0f5-0c5e-49ad-abaa-e3874c0f3286}*SharedItemsImports = 5 src\TerraFX.Interop.Windows.Dynamic\TerraFX.Interop.Windows.Dynamic.projitems*{76c66257-fdaa-47ab-85e7-ef757eab10c0}*SharedItemsImports = 5 samples\ComputeSharp.Sample.Shared\ComputeSharp.Sample.Shared.projitems*{8cefc324-ca6c-4845-9ad9-70b92bd87057}*SharedItemsImports = 13 + src\ComputeSharp.SourceGeneration.Hlsl\ComputeSharp.SourceGeneration.Hlsl.projitems*{9ac496a3-bbf0-4c8f-a50d-a20bf01c5e05}*SharedItemsImports = 13 + src\TerraFX.Interop.Windows.D2D1\TerraFX.Interop.Windows.D2D1.projitems*{9da1da9f-f8b2-4b25-be80-c21f773029e3}*SharedItemsImports = 13 src\ComputeSharp.NetStandard\ComputeSharp.NetStandard.projitems*{a5997814-d8d2-4541-87ac-c3e53caa67c0}*SharedItemsImports = 13 src\ComputeSharp.UI\ComputeSharp.UI.projitems*{afaafdc9-be42-45d4-8c79-0ee8c8edbf52}*SharedItemsImports = 5 + src\ComputeSharp.Core.NetStandard\ComputeSharp.Core.NetStandard.projitems*{bfb003d1-788b-48de-8065-39479c162cb0}*SharedItemsImports = 5 + src\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems*{bfb003d1-788b-48de-8065-39479c162cb0}*SharedItemsImports = 5 + src\ComputeSharp.Core.NetStandard\ComputeSharp.Core.NetStandard.projitems*{e44053bd-a761-47fb-aa78-087a599672ea}*SharedItemsImports = 5 + src\ComputeSharp.D2D1.NetStandard\ComputeSharp.D2D1.NetStandard.projitems*{e44053bd-a761-47fb-aa78-087a599672ea}*SharedItemsImports = 5 + src\ComputeSharp.SourceGeneration.Hlsl\ComputeSharp.SourceGeneration.Hlsl.projitems*{e44053bd-a761-47fb-aa78-087a599672ea}*SharedItemsImports = 5 + src\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems*{e44053bd-a761-47fb-aa78-087a599672ea}*SharedItemsImports = 5 + src\TerraFX.Interop.Windows.D2D1\TerraFX.Interop.Windows.D2D1.projitems*{e44053bd-a761-47fb-aa78-087a599672ea}*SharedItemsImports = 5 samples\ComputeSharp.SwapChain.Shaders.Shared\ComputeSharp.SwapChain.Shaders.Shared.projitems*{e7c9247d-016b-4819-af9f-0e9b3591e04b}*SharedItemsImports = 5 samples\ComputeSharp.SwapChain.Shaders.Shared\ComputeSharp.SwapChain.Shaders.Shared.projitems*{e91f4d24-922a-4921-a8d7-9c45a143c45d}*SharedItemsImports = 5 + src\ComputeSharp.Core.NetStandard\ComputeSharp.Core.NetStandard.projitems*{eb52cb67-4162-4722-874b-44ea8da5450e}*SharedItemsImports = 5 src\ComputeSharp.NetStandard\ComputeSharp.NetStandard.projitems*{eb52cb67-4162-4722-874b-44ea8da5450e}*SharedItemsImports = 5 + src\ComputeSharp.SourceGeneration.Hlsl\ComputeSharp.SourceGeneration.Hlsl.projitems*{eb52cb67-4162-4722-874b-44ea8da5450e}*SharedItemsImports = 5 + src\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems*{eb52cb67-4162-4722-874b-44ea8da5450e}*SharedItemsImports = 5 src\TerraFX.Interop.Windows.Dynamic\TerraFX.Interop.Windows.Dynamic.projitems*{eb52cb67-4162-4722-874b-44ea8da5450e}*SharedItemsImports = 5 src\TerraFX.Interop.Windows\TerraFX.Interop.Windows.projitems*{eb52cb67-4162-4722-874b-44ea8da5450e}*SharedItemsImports = 5 src\ComputeSharp.UI\ComputeSharp.UI.projitems*{fa18ba9f-76bf-4de0-8d24-02fc7657e6cb}*SharedItemsImports = 5 @@ -337,6 +378,66 @@ Global {76C66257-FDAA-47AB-85E7-EF757EAB10C0}.Release|ARM64.Build.0 = Release|ARM64 {76C66257-FDAA-47AB-85E7-EF757EAB10C0}.Release|x64.ActiveCfg = Release|x64 {76C66257-FDAA-47AB-85E7-EF757EAB10C0}.Release|x64.Build.0 = Release|x64 + {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Debug|ARM64.ActiveCfg = Debug|Any CPU + {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Debug|ARM64.Build.0 = Debug|Any CPU + {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Debug|x64.ActiveCfg = Debug|Any CPU + {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Debug|x64.Build.0 = Debug|Any CPU + {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Release|Any CPU.Build.0 = Release|Any CPU + {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Release|ARM64.ActiveCfg = Release|Any CPU + {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Release|ARM64.Build.0 = Release|Any CPU + {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Release|x64.ActiveCfg = Release|Any CPU + {4D7D9BA8-A821-4B1C-9EE2-CBCF5849906E}.Release|x64.Build.0 = Release|Any CPU + {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Debug|Any CPU.Build.0 = Debug|Any CPU + {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Debug|ARM64.ActiveCfg = Debug|Any CPU + {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Debug|ARM64.Build.0 = Debug|Any CPU + {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Debug|x64.ActiveCfg = Debug|Any CPU + {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Debug|x64.Build.0 = Debug|Any CPU + {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Release|Any CPU.ActiveCfg = Release|Any CPU + {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Release|Any CPU.Build.0 = Release|Any CPU + {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Release|ARM64.ActiveCfg = Release|Any CPU + {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Release|ARM64.Build.0 = Release|Any CPU + {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Release|x64.ActiveCfg = Release|Any CPU + {764BC0F5-0C5E-49AD-ABAA-E3874C0F3286}.Release|x64.Build.0 = Release|Any CPU + {BFB003D1-788B-48DE-8065-39479C162CB0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BFB003D1-788B-48DE-8065-39479C162CB0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BFB003D1-788B-48DE-8065-39479C162CB0}.Debug|ARM64.ActiveCfg = Debug|Any CPU + {BFB003D1-788B-48DE-8065-39479C162CB0}.Debug|ARM64.Build.0 = Debug|Any CPU + {BFB003D1-788B-48DE-8065-39479C162CB0}.Debug|x64.ActiveCfg = Debug|Any CPU + {BFB003D1-788B-48DE-8065-39479C162CB0}.Debug|x64.Build.0 = Debug|Any CPU + {BFB003D1-788B-48DE-8065-39479C162CB0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BFB003D1-788B-48DE-8065-39479C162CB0}.Release|Any CPU.Build.0 = Release|Any CPU + {BFB003D1-788B-48DE-8065-39479C162CB0}.Release|ARM64.ActiveCfg = Release|Any CPU + {BFB003D1-788B-48DE-8065-39479C162CB0}.Release|ARM64.Build.0 = Release|Any CPU + {BFB003D1-788B-48DE-8065-39479C162CB0}.Release|x64.ActiveCfg = Release|Any CPU + {BFB003D1-788B-48DE-8065-39479C162CB0}.Release|x64.Build.0 = Release|Any CPU + {E44053BD-A761-47FB-AA78-087A599672EA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E44053BD-A761-47FB-AA78-087A599672EA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E44053BD-A761-47FB-AA78-087A599672EA}.Debug|ARM64.ActiveCfg = Debug|Any CPU + {E44053BD-A761-47FB-AA78-087A599672EA}.Debug|ARM64.Build.0 = Debug|Any CPU + {E44053BD-A761-47FB-AA78-087A599672EA}.Debug|x64.ActiveCfg = Debug|Any CPU + {E44053BD-A761-47FB-AA78-087A599672EA}.Debug|x64.Build.0 = Debug|Any CPU + {E44053BD-A761-47FB-AA78-087A599672EA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E44053BD-A761-47FB-AA78-087A599672EA}.Release|Any CPU.Build.0 = Release|Any CPU + {E44053BD-A761-47FB-AA78-087A599672EA}.Release|ARM64.ActiveCfg = Release|Any CPU + {E44053BD-A761-47FB-AA78-087A599672EA}.Release|ARM64.Build.0 = Release|Any CPU + {E44053BD-A761-47FB-AA78-087A599672EA}.Release|x64.ActiveCfg = Release|Any CPU + {E44053BD-A761-47FB-AA78-087A599672EA}.Release|x64.Build.0 = Release|Any CPU + {209C95A3-FA53-431B-B688-3299CA6C29D2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {209C95A3-FA53-431B-B688-3299CA6C29D2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {209C95A3-FA53-431B-B688-3299CA6C29D2}.Debug|ARM64.ActiveCfg = Debug|Any CPU + {209C95A3-FA53-431B-B688-3299CA6C29D2}.Debug|ARM64.Build.0 = Debug|Any CPU + {209C95A3-FA53-431B-B688-3299CA6C29D2}.Debug|x64.ActiveCfg = Debug|Any CPU + {209C95A3-FA53-431B-B688-3299CA6C29D2}.Debug|x64.Build.0 = Debug|Any CPU + {209C95A3-FA53-431B-B688-3299CA6C29D2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {209C95A3-FA53-431B-B688-3299CA6C29D2}.Release|Any CPU.Build.0 = Release|Any CPU + {209C95A3-FA53-431B-B688-3299CA6C29D2}.Release|ARM64.ActiveCfg = Release|Any CPU + {209C95A3-FA53-431B-B688-3299CA6C29D2}.Release|ARM64.Build.0 = Release|Any CPU + {209C95A3-FA53-431B-B688-3299CA6C29D2}.Release|x64.ActiveCfg = Release|Any CPU + {209C95A3-FA53-431B-B688-3299CA6C29D2}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -361,6 +462,10 @@ Global {751BB05B-563D-4B3A-94C6-15E2D79D35EA} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} {4A8FCE22-851C-442A-8BC9-3EC3FD00B637} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7} {158F984D-CD96-4062-BD02-2268946031A0} = {8DCE343F-BA78-4FE1-B562-B57C603A8BAA} + {9DA1DA9F-F8B2-4B25-BE80-C21F773029E3} = {8DCE343F-BA78-4FE1-B562-B57C603A8BAA} + {2608EB41-F98B-4BE5-9F4D-68FED6115088} = {8DCE343F-BA78-4FE1-B562-B57C603A8BAA} + {3ACACF03-6B20-40BA-B8EC-11AC1624D2C9} = {8DCE343F-BA78-4FE1-B562-B57C603A8BAA} + {209C95A3-FA53-431B-B688-3299CA6C29D2} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4664C5E3-0340-4E22-BCFD-98AAEDF5F2DC} diff --git a/Directory.Build.props b/Directory.Build.props index c507f133..86d987a3 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -7,9 +7,26 @@ $(NoWarn);MSB3270 + - 2.0.0.0 - 2.0.0 + $(MSBuildThisFileDirectory)artifacts/ + + + + + 2.0.0 + + + + $(ComputeSharpPackageVersion).0 + $(ComputeSharpPackageVersion) + alpha + pr + true https://github.com/Sergio0694/ComputeSharp/ git true diff --git a/Directory.Build.targets b/Directory.Build.targets new file mode 100644 index 00000000..34a9cdfe --- /dev/null +++ b/Directory.Build.targets @@ -0,0 +1,32 @@ + + + + + + + $(VersionPrefix)-$(VersionSuffix) + $(VersionPrefix) + + + + + $(Version).$(GITHUB_RUN_ID) + + + + + $(Version) + + \ No newline at end of file diff --git a/README.md b/README.md index 7458013b..68dd1af3 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ The sample app is available in the Microsoft Store, showcasing several pixel sha - [Inspecting shaders](#inspecting-shaders) - [DirectX interop](#directx-interop) - [Precompiled shaders](#precompiled-shaders) + - [D2D1 support](#d2d1-support) - [Requirements](#requirements) - [F# support](#f-support) - [Sponsors](#sponsors) @@ -46,6 +47,7 @@ The sample app is available in the Microsoft Store, showcasing several pixel sha | **ComputeSharp.Dynamic** | An extension for **ComputeSharp**, enabling dynamic shader compilation at runtime and shader metaprogramming | [![NuGet](https://img.shields.io/nuget/vpre/ComputeSharp.Dynamic.svg)](https://www.nuget.org/packages/ComputeSharp.Dynamic/) | | **ComputeSharp.Uwp** | A UWP library (targeting .NET Standard 2.0) with controls to render DX12 shaders powered by **ComputeSharp** | [![NuGet](https://img.shields.io/nuget/vpre/ComputeSharp.Uwp.svg)](https://www.nuget.org/packages/ComputeSharp.Uwp/) | | **ComputeSharp.WinUI** | A WinUI 3 library (targeting .NET 6) with controls to render DX12 shaders powered by **ComputeSharp** | [![NuGet](https://img.shields.io/nuget/vpre/ComputeSharp.WinUI.svg)](https://www.nuget.org/packages/ComputeSharp.WinUI/) | +| **ComputeSharp.D2D1** | A library to write D2D1 pixel shaders entirely with C# code, and to easily register and create ID2D1Effect-s from them | [![NuGet](https://img.shields.io/nuget/vpre/ComputeSharp.D2D1.svg)](https://www.nuget.org/packages/ComputeSharp.D2D1/) | # Installing from NuGet @@ -378,6 +380,41 @@ public readonly partial struct MultiplyByTwo : IPixelShader The values in the `[EmbeddedBytecode]` attribute map to the [`[numthreads]` HLSL attribute](https://docs.microsoft.com/windows/win32/direct3dhlsl/sm5-attributes-numthreads) for the shader entry point. Make sure to use the same values when dispatching the shader at runtime (either using the `GraphicsDevice.For` overload with explicit parameters for the tread numbers, or by relying on `GraphicsDevice.ForEach` to always use `(8, 8, 1)` for thread numbers, as it will be dispatching shaders on a 2D texture). +## D2D1 support + +**ComputeSharp** also offers [D2D1 support](https://docs.microsoft.com/en-us/windows/win32/direct2d/d2d1-namespace), through the dedicated package. This shares the same base APIs (primitives, intrinsics, etc.) from **ComputeSharp.Core**, but then adds D2D1 specific support, instead of using DX12 like the main package. This means it offers the ability to implement D2D1 pixel shaders, and to then either load them manually, or to register a D2D1 effect using them, optionally with a custom draw transform as well. + +For instance, here's a simple D2D1 pixel shader: + +```csharp +[D2DInputCount(1)] +[D2DInputSimple(0)] +[D2DEmbeddedBytecode(D2D1ShaderProfile.PixelShader50)] +[AutoConstructor] +public partial struct DifferenceEffect : ID2D1PixelShader +{ + public float amount; + + /// + public float4 Execute() + { + float4 color = D2D.GetInput(0); + float3 rgb = Hlsl.Saturate(this.amount - color.RGB); + + return new(rgb, 1); + } +} +``` + +This can then be used directly to get the shader bytecode and the buffer, like so: + +```csharp +ReadOnlyMemory bytecode = D2D1InteropServices.LoadShaderBytecode(); +ReadOnlyMemory buffer = D2D1InteropServices.GetPixelShaderConstantBuffer(new DifferenceEffect(1)); +``` + +There are also several other APIs to easily register a pixel shader effect from a shader written using **ComputeSharp.D2D1**, and to then create an `ID2D1Effect` instance from it (from the `D2D1PixelShaderEffect` type), as well as for reflecting into a shader and extract information about it, such as its HLSL source code (from the `D2D1ReflectionServices` type). + # Requirements Building and running **ComputeSharp** from the .NET solution filter has the following prerequisites: diff --git a/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj b/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj index 1ea30a7a..002e1078 100644 --- a/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj +++ b/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj @@ -23,12 +23,11 @@ + + - + \ No newline at end of file diff --git a/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj b/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj index 779450a0..59564f49 100644 --- a/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj +++ b/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj @@ -15,12 +15,11 @@ + + - + diff --git a/samples/ComputeSharp.Sample.FSharp.Shaders/ComputeSharp.Sample.FSharp.Shaders.csproj b/samples/ComputeSharp.Sample.FSharp.Shaders/ComputeSharp.Sample.FSharp.Shaders.csproj index 33165757..6ccc804e 100644 --- a/samples/ComputeSharp.Sample.FSharp.Shaders/ComputeSharp.Sample.FSharp.Shaders.csproj +++ b/samples/ComputeSharp.Sample.FSharp.Shaders/ComputeSharp.Sample.FSharp.Shaders.csproj @@ -5,12 +5,11 @@ + + - + diff --git a/samples/ComputeSharp.Sample.FSharp/ComputeSharp.Sample.FSharp.fsproj b/samples/ComputeSharp.Sample.FSharp/ComputeSharp.Sample.FSharp.fsproj index 0c746598..f559a565 100644 --- a/samples/ComputeSharp.Sample.FSharp/ComputeSharp.Sample.FSharp.fsproj +++ b/samples/ComputeSharp.Sample.FSharp/ComputeSharp.Sample.FSharp.fsproj @@ -15,12 +15,11 @@ + + - + diff --git a/samples/ComputeSharp.Sample.NuGet/ComputeSharp.Sample.NuGet.csproj b/samples/ComputeSharp.Sample.NuGet/ComputeSharp.Sample.NuGet.csproj index dd2769fd..f75aab80 100644 --- a/samples/ComputeSharp.Sample.NuGet/ComputeSharp.Sample.NuGet.csproj +++ b/samples/ComputeSharp.Sample.NuGet/ComputeSharp.Sample.NuGet.csproj @@ -7,8 +7,9 @@ - - + + + diff --git a/samples/ComputeSharp.Sample.NuGet/nuget.config b/samples/ComputeSharp.Sample.NuGet/nuget.config index c3f2b513..995d3a62 100644 --- a/samples/ComputeSharp.Sample.NuGet/nuget.config +++ b/samples/ComputeSharp.Sample.NuGet/nuget.config @@ -1,7 +1,8 @@ - - + + + diff --git a/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj b/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj index 138428ab..b1c021b0 100644 --- a/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj +++ b/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj @@ -7,12 +7,11 @@ + + - + diff --git a/samples/ComputeSharp.SwapChain.Uwp/ComputeSharp.SwapChain.Uwp.csproj b/samples/ComputeSharp.SwapChain.Uwp/ComputeSharp.SwapChain.Uwp.csproj index 7470e9ad..a5be5595 100644 --- a/samples/ComputeSharp.SwapChain.Uwp/ComputeSharp.SwapChain.Uwp.csproj +++ b/samples/ComputeSharp.SwapChain.Uwp/ComputeSharp.SwapChain.Uwp.csproj @@ -230,6 +230,8 @@ + + diff --git a/samples/ComputeSharp.SwapChain.WinUI/ComputeSharp.SwapChain.WinUI.csproj b/samples/ComputeSharp.SwapChain.WinUI/ComputeSharp.SwapChain.WinUI.csproj index f4dc10e2..f62c81b7 100644 --- a/samples/ComputeSharp.SwapChain.WinUI/ComputeSharp.SwapChain.WinUI.csproj +++ b/samples/ComputeSharp.SwapChain.WinUI/ComputeSharp.SwapChain.WinUI.csproj @@ -40,11 +40,9 @@ + - + diff --git a/samples/ComputeSharp.SwapChain/ComputeSharp.SwapChain.csproj b/samples/ComputeSharp.SwapChain/ComputeSharp.SwapChain.csproj index 7220b8f9..d6fcfddc 100644 --- a/samples/ComputeSharp.SwapChain/ComputeSharp.SwapChain.csproj +++ b/samples/ComputeSharp.SwapChain/ComputeSharp.SwapChain.csproj @@ -8,11 +8,10 @@ + + - + diff --git a/src/ComputeSharp.Core.NetStandard/ComputeSharp.Core.NetStandard.projitems b/src/ComputeSharp.Core.NetStandard/ComputeSharp.Core.NetStandard.projitems new file mode 100644 index 00000000..22578e69 --- /dev/null +++ b/src/ComputeSharp.Core.NetStandard/ComputeSharp.Core.NetStandard.projitems @@ -0,0 +1,18 @@ + + + + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) + true + 3acacf03-6b20-40ba-b8ec-11ac1624d2c9 + + + ComputeSharp.Core.NetStandard + + + + + + + + + \ No newline at end of file diff --git a/src/ComputeSharp.Core.NetStandard/ComputeSharp.Core.NetStandard.shproj b/src/ComputeSharp.Core.NetStandard/ComputeSharp.Core.NetStandard.shproj new file mode 100644 index 00000000..9964b218 --- /dev/null +++ b/src/ComputeSharp.Core.NetStandard/ComputeSharp.Core.NetStandard.shproj @@ -0,0 +1,13 @@ + + + + 3acacf03-6b20-40ba-b8ec-11ac1624d2c9 + 14.0 + + + + + + + + diff --git a/src/ComputeSharp.Core.NetStandard/System/InteropServices/MemoryMarshal.cs b/src/ComputeSharp.Core.NetStandard/System/InteropServices/MemoryMarshal.cs new file mode 100644 index 00000000..86710490 --- /dev/null +++ b/src/ComputeSharp.Core.NetStandard/System/InteropServices/MemoryMarshal.cs @@ -0,0 +1,36 @@ +using System; +using System.Runtime.CompilerServices; + +namespace ComputeSharp.Core.NetStandard.System.Runtime.InteropServices; + +/// +/// A polyfill type that mirrors some methods from on .NET 6. +/// +internal static class MemoryMarshal +{ + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ref T GetReference(Span span) + { + return ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(span); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ref T GetReference(ReadOnlySpan span) + { + return ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(span); + } + + /// + /// Creates a new from a given reference. + /// + /// The type of reference to wrap. + /// The target reference. + /// The length of the to create. + /// A new wrapping . + public static unsafe Span CreateSpan(ref T value, int length) + { + return new(Unsafe.AsPointer(ref value), length); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.NetStandard/System/Runtime/CompilerServices/InterpolatedStringHandlerArgumentAttribute.cs b/src/ComputeSharp.Core.NetStandard/System/Runtime.CompilerServices/InterpolatedStringHandlerArgumentAttribute.cs similarity index 100% rename from src/ComputeSharp.NetStandard/System/Runtime/CompilerServices/InterpolatedStringHandlerArgumentAttribute.cs rename to src/ComputeSharp.Core.NetStandard/System/Runtime.CompilerServices/InterpolatedStringHandlerArgumentAttribute.cs diff --git a/src/ComputeSharp.NetStandard/System/Runtime/CompilerServices/InterpolatedStringHandlerAttribute.cs b/src/ComputeSharp.Core.NetStandard/System/Runtime.CompilerServices/InterpolatedStringHandlerAttribute.cs similarity index 100% rename from src/ComputeSharp.NetStandard/System/Runtime/CompilerServices/InterpolatedStringHandlerAttribute.cs rename to src/ComputeSharp.Core.NetStandard/System/Runtime.CompilerServices/InterpolatedStringHandlerAttribute.cs diff --git a/src/ComputeSharp.Core.NetStandard/System/Runtime.CompilerServices/RuntimeHelpers.cs b/src/ComputeSharp.Core.NetStandard/System/Runtime.CompilerServices/RuntimeHelpers.cs new file mode 100644 index 00000000..9d2046fc --- /dev/null +++ b/src/ComputeSharp.Core.NetStandard/System/Runtime.CompilerServices/RuntimeHelpers.cs @@ -0,0 +1,18 @@ +using System; +using System.Runtime.InteropServices; + +namespace ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices; + +/// +/// A polyfill type that mirrors some methods from on .NET 5. +/// +internal static class RuntimeHelpers +{ + /// + /// Allocates some memory tied to the lifetime of a specific type. + /// + /// The type to associate the memory to. + /// The size in byte of the memory to allocate. + /// A pointer to the allocated memory. + public static IntPtr AllocateTypeAssociatedMemory(Type type, int size) => Marshal.AllocHGlobal(size); +} \ No newline at end of file diff --git a/src/ComputeSharp.NetStandard/System/Runtime/CompilerServices/SkipLocalsInitAttribute.cs b/src/ComputeSharp.Core.NetStandard/System/Runtime.CompilerServices/SkipLocalsInitAttribute.cs similarity index 100% rename from src/ComputeSharp.NetStandard/System/Runtime/CompilerServices/SkipLocalsInitAttribute.cs rename to src/ComputeSharp.Core.NetStandard/System/Runtime.CompilerServices/SkipLocalsInitAttribute.cs diff --git a/src/ComputeSharp.Core.Package/ComputeSharp.Core.Package.msbuildproj b/src/ComputeSharp.Core.Package/ComputeSharp.Core.Package.msbuildproj new file mode 100644 index 00000000..aa6080cc --- /dev/null +++ b/src/ComputeSharp.Core.Package/ComputeSharp.Core.Package.msbuildproj @@ -0,0 +1,22 @@ + + + + net6.0 + + + + ComputeSharp.Core + ComputeSharp.Core + A library containing basic primitives to support ComputeSharp (this package is not supposed to be referenced directly by developers) + + + + + + + + + + + + \ No newline at end of file diff --git a/src/ComputeSharp.Package/icon.png b/src/ComputeSharp.Core.Package/icon.png similarity index 100% rename from src/ComputeSharp.Package/icon.png rename to src/ComputeSharp.Core.Package/icon.png diff --git a/src/ComputeSharp.Package/icon_highres.png b/src/ComputeSharp.Core.Package/icon_highres.png similarity index 100% rename from src/ComputeSharp.Package/icon_highres.png rename to src/ComputeSharp.Core.Package/icon_highres.png diff --git a/src/ComputeSharp.Core.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.Core.SourceGenerators/AnalyzerReleases.Shipped.md new file mode 100644 index 00000000..cc5f50e7 --- /dev/null +++ b/src/ComputeSharp.Core.SourceGenerators/AnalyzerReleases.Shipped.md @@ -0,0 +1,9 @@ +; Shipped analyzer releases +; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md + +## Release 1.0 + +### New Rules + +Rule ID | Category | Severity | Notes +--------|----------|----------|------- diff --git a/src/ComputeSharp.Core.SourceGenerators/AnalyzerReleases.Unshipped.md b/src/ComputeSharp.Core.SourceGenerators/AnalyzerReleases.Unshipped.md new file mode 100644 index 00000000..6a6dd08d --- /dev/null +++ b/src/ComputeSharp.Core.SourceGenerators/AnalyzerReleases.Unshipped.md @@ -0,0 +1,2 @@ +; Unshipped analyzer release +; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md diff --git a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs b/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs similarity index 66% rename from src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs rename to src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs index b6afffe2..8a5771e5 100644 --- a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs +++ b/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs @@ -1,14 +1,15 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; -using ComputeSharp.SourceGenerators.Extensions; -using ComputeSharp.SourceGenerators.Models; +using ComputeSharp.Core.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -namespace ComputeSharp.SourceGenerators; +namespace ComputeSharp.Core.SourceGenerators; /// /// A source generator creating constructors for types annotated with . @@ -82,7 +83,7 @@ public sealed partial class AutoConstructorGenerator : IIncrementalGenerator // ... // } ConstructorDeclarationSyntax constructorDeclaration = - ConstructorDeclaration(hierarchyInfo.Names[0]) + ConstructorDeclaration(hierarchyInfo.Hierarchy[0].QualifiedName) .AddModifiers(Token(SyntaxKind.PublicKeyword)) .AddParameterListParameters(parameters.Select(field => Parameter(Identifier(field.Name)).WithType(IdentifierName(field.Type))).ToArray()) .AddBodyStatements(parameters.Select(field => ParseStatement($"this.{field.Name} = {field.Name};")).ToArray()); @@ -104,64 +105,7 @@ public sealed partial class AutoConstructorGenerator : IIncrementalGenerator AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))) }; - // Create the partial shader type declaration with the given method implementation. - // This code produces a struct declaration as follows: - // - // partial struct - // { - // - // } - StructDeclarationSyntax structDeclarationSyntax = - StructDeclaration(hierarchyInfo.Names[0]) - .AddModifiers(Token(SyntaxKind.PartialKeyword)) - .AddMembers(constructorDeclaration.AddAttributeLists(attributes)); - - TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax; - - // Add all parent types in ascending order, if any - foreach (string parentType in hierarchyInfo.Names.AsSpan().Slice(1)) - { - typeDeclarationSyntax = - ClassDeclaration(parentType) - .AddModifiers(Token(SyntaxKind.PartialKeyword)) - .AddMembers(typeDeclarationSyntax); - } - - if (hierarchyInfo.Namespace is "") - { - // If there is no namespace, attach the pragma directly to the declared type, - // and skip the namespace declaration. This will produce code as follows: - // - // #pragma warning disable - // - // - return - CompilationUnit().AddMembers( - typeDeclarationSyntax - .WithModifiers(TokenList(Token( - TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), - SyntaxKind.PartialKeyword, - TriviaList())))) - .NormalizeWhitespace(eol: "\n"); - } - - // Create the compilation unit with disabled warnings, target namespace and generated type. - // This will produce code as follows: - // - // #pragma warning disable - // - // namespace ; - // - // - return - CompilationUnit().AddMembers( - FileScopedNamespaceDeclaration(IdentifierName(hierarchyInfo.Namespace)) - .AddMembers(typeDeclarationSyntax) - .WithNamespaceKeyword(Token(TriviaList( - Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), - SyntaxKind.NamespaceKeyword, - TriviaList()))) - .NormalizeWhitespace(eol: "\n"); + return hierarchyInfo.GetSyntax(constructorDeclaration.AddAttributeLists(attributes)); } } } diff --git a/src/ComputeSharp.Core.SourceGenerators/ComputeSharp.Core.SourceGenerators.csproj b/src/ComputeSharp.Core.SourceGenerators/ComputeSharp.Core.SourceGenerators.csproj new file mode 100644 index 00000000..4a9583fa --- /dev/null +++ b/src/ComputeSharp.Core.SourceGenerators/ComputeSharp.Core.SourceGenerators.csproj @@ -0,0 +1,83 @@ + + + + netstandard2.0 + false + ComputeSharp.Core.SourceGenerators + $(NoWarn);CS1591;CS0649;CS1574 + + + + $(DefineConstants);SOURCE_GENERATOR + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ComputeSharp.SourceGenerators/EmbeddedResources/GlobalUsingDirectives.cs b/src/ComputeSharp.Core.SourceGenerators/EmbeddedResources/GlobalUsingDirectives.cs similarity index 100% rename from src/ComputeSharp.SourceGenerators/EmbeddedResources/GlobalUsingDirectives.cs rename to src/ComputeSharp.Core.SourceGenerators/EmbeddedResources/GlobalUsingDirectives.cs diff --git a/src/ComputeSharp.SourceGenerators/GlobalUsingDirectivesGenerator.cs b/src/ComputeSharp.Core.SourceGenerators/GlobalUsingDirectivesGenerator.cs similarity index 83% rename from src/ComputeSharp.SourceGenerators/GlobalUsingDirectivesGenerator.cs rename to src/ComputeSharp.Core.SourceGenerators/GlobalUsingDirectivesGenerator.cs index 30d8933d..8fb5b86b 100644 --- a/src/ComputeSharp.SourceGenerators/GlobalUsingDirectivesGenerator.cs +++ b/src/ComputeSharp.Core.SourceGenerators/GlobalUsingDirectivesGenerator.cs @@ -2,7 +2,7 @@ using System.Reflection; using Microsoft.CodeAnalysis; -namespace ComputeSharp.SourceGenerators; +namespace ComputeSharp.Core.SourceGenerators; /// /// A source generator to create global using directives for the HLSL primitive types. @@ -15,7 +15,7 @@ public sealed class GlobalUsingDirectivesGenerator : IIncrementalGenerator { context.RegisterPostInitializationOutput(static context => { - const string filename = "ComputeSharp.SourceGenerators.EmbeddedResources.GlobalUsingDirectives.cs"; + const string filename = "ComputeSharp.Core.SourceGenerators.EmbeddedResources.GlobalUsingDirectives.cs"; using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(filename); using StreamReader reader = new(stream); diff --git a/src/ComputeSharp.SourceGenerators/Models/ParameterInfo.cs b/src/ComputeSharp.Core.SourceGenerators/Models/ParameterInfo.cs similarity index 82% rename from src/ComputeSharp.SourceGenerators/Models/ParameterInfo.cs rename to src/ComputeSharp.Core.SourceGenerators/Models/ParameterInfo.cs index 137df444..ff276e79 100644 --- a/src/ComputeSharp.SourceGenerators/Models/ParameterInfo.cs +++ b/src/ComputeSharp.Core.SourceGenerators/Models/ParameterInfo.cs @@ -1,4 +1,4 @@ -namespace ComputeSharp.SourceGenerators.Models; +namespace ComputeSharp.Core.SourceGenerators.Models; /// /// A model describing info on a constructor parameter. diff --git a/src/ComputeSharp.Core.SourceGenerators/System.Runtime.CompilerServices/IsExternalInit.cs b/src/ComputeSharp.Core.SourceGenerators/System.Runtime.CompilerServices/IsExternalInit.cs new file mode 100644 index 00000000..a914bf06 --- /dev/null +++ b/src/ComputeSharp.Core.SourceGenerators/System.Runtime.CompilerServices/IsExternalInit.cs @@ -0,0 +1,12 @@ +using System.ComponentModel; + +namespace System.Runtime.CompilerServices; + +/// +/// Reserved to be used by the compiler for tracking metadata. +/// This class should not be used by developers in source code. +/// +[EditorBrowsable(EditorBrowsableState.Never)] +internal static class IsExternalInit +{ +} diff --git a/src/ComputeSharp/Core/Attributes/AutoConstructorAttribute.cs b/src/ComputeSharp.Core/Attributes/AutoConstructorAttribute.cs similarity index 100% rename from src/ComputeSharp/Core/Attributes/AutoConstructorAttribute.cs rename to src/ComputeSharp.Core/Attributes/AutoConstructorAttribute.cs diff --git a/src/ComputeSharp.Core/ComputeSharp.Core.csproj b/src/ComputeSharp.Core/ComputeSharp.Core.csproj new file mode 100644 index 00000000..8aa6a689 --- /dev/null +++ b/src/ComputeSharp.Core/ComputeSharp.Core.csproj @@ -0,0 +1,238 @@ + + + + netstandard2.0;net6.0 + bin\Release + ComputeSharp.Core.xml + + + + + true + true + + + + + + + + + + + + + + + Hlsl.Void.tt + True + True + + + True + True + Hlsl.tt + + + True + True + Bool2.tt + + + True + True + Bool3.tt + + + True + True + Bool4.tt + + + True + True + BoolMxN.tt + + + True + True + Double2.tt + + + True + True + Double3.tt + + + True + True + Double4.tt + + + True + True + DoubleMxN.tt + + + True + True + Float2.tt + + + True + True + Float3.tt + + + True + True + Float4.tt + + + True + True + FloatMxN.tt + + + True + True + Int2.tt + + + True + True + Int3.tt + + + True + True + Int4.tt + + + True + True + IntMxN.tt + + + True + True + UInt2.tt + + + True + True + UInt3.tt + + + True + True + UInt4.tt + + + True + True + UIntMxN.tt + + + + + + Hlsl.Void.g.cs + TextTemplatingFileGenerator + + + TextTemplatingFileGenerator + Hlsl.g.cs + + + TextTemplatingFileGenerator + Bool2.g.cs + + + TextTemplatingFileGenerator + Bool3.g.cs + + + TextTemplatingFileGenerator + Bool4.g.cs + + + TextTemplatingFileGenerator + BoolMxN.g.cs + + + TextTemplatingFileGenerator + Double2.g.cs + + + TextTemplatingFileGenerator + Double3.g.cs + + + TextTemplatingFileGenerator + Double4.g.cs + + + TextTemplatingFileGenerator + DoubleMxN.g.cs + + + TextTemplatingFileGenerator + Float2.g.cs + + + TextTemplatingFileGenerator + Float3.g.cs + + + TextTemplatingFileGenerator + Float4.g.cs + + + TextTemplatingFileGenerator + FloatMxN.g.cs + + + TextTemplatingFileGenerator + Int2.g.cs + + + TextTemplatingFileGenerator + Int3.g.cs + + + TextTemplatingFileGenerator + Int4.g.cs + + + TextTemplatingFileGenerator + IntMxN.g.cs + + + TextTemplatingFileGenerator + UInt2.g.cs + + + TextTemplatingFileGenerator + UInt3.g.cs + + + TextTemplatingFileGenerator + UInt4.g.cs + + + TextTemplatingFileGenerator + UIntMxN.g.cs + + + + + + + + + + + + + diff --git a/src/ComputeSharp.Core/ComputeSharp.Core.targets b/src/ComputeSharp.Core/ComputeSharp.Core.targets new file mode 100644 index 00000000..79dfea91 --- /dev/null +++ b/src/ComputeSharp.Core/ComputeSharp.Core.targets @@ -0,0 +1,53 @@ + + + + + + <_ComputeSharpAnalyzer Include="@(Analyzer)" Condition="'%(Analyzer.NuGetPackageId)' == 'ComputeSharp.Core'" /> + + + + + + + + + + + + + + + @(CurrentCompilerAssemblyIdentity->'%(Version)') + + + true + + + + + + + + + + + + + + + + + + + + diff --git a/src/ComputeSharp/Core/Exceptions/InvalidExecutionContextException.cs b/src/ComputeSharp.Core/Exceptions/InvalidExecutionContextException.cs similarity index 100% rename from src/ComputeSharp/Core/Exceptions/InvalidExecutionContextException.cs rename to src/ComputeSharp.Core/Exceptions/InvalidExecutionContextException.cs diff --git a/src/ComputeSharp/Core/Helpers/System.Runtime.CompilerServices/FormatInterpolatedStringHandler.cs b/src/ComputeSharp.Core/Helpers/FormatInterpolatedStringHandler.cs similarity index 100% rename from src/ComputeSharp/Core/Helpers/System.Runtime.CompilerServices/FormatInterpolatedStringHandler.cs rename to src/ComputeSharp.Core/Helpers/FormatInterpolatedStringHandler.cs diff --git a/src/ComputeSharp/Core/Helpers/System.Runtime.CompilerServices/TryWriteFormatInterpolatedStringHandler.cs b/src/ComputeSharp.Core/Helpers/TryWriteFormatInterpolatedStringHandler.cs similarity index 100% rename from src/ComputeSharp/Core/Helpers/System.Runtime.CompilerServices/TryWriteFormatInterpolatedStringHandler.cs rename to src/ComputeSharp.Core/Helpers/TryWriteFormatInterpolatedStringHandler.cs diff --git a/src/ComputeSharp/Core/Intrinsics/Attributes/HlslIntrinsicNameAttribute.cs b/src/ComputeSharp.Core/Intrinsics/Attributes/HlslIntrinsicNameAttribute.cs similarity index 100% rename from src/ComputeSharp/Core/Intrinsics/Attributes/HlslIntrinsicNameAttribute.cs rename to src/ComputeSharp.Core/Intrinsics/Attributes/HlslIntrinsicNameAttribute.cs diff --git a/src/ComputeSharp.Core/Intrinsics/Hlsl.Void.g.cs b/src/ComputeSharp.Core/Intrinsics/Hlsl.Void.g.cs new file mode 100644 index 00000000..a58bc20b --- /dev/null +++ b/src/ComputeSharp.Core/Intrinsics/Hlsl.Void.g.cs @@ -0,0 +1,308 @@ +using ComputeSharp.Core.Intrinsics.Attributes; +using ComputeSharp.Exceptions; + +namespace ComputeSharp; + +/// +partial class Hlsl +{ + /// + /// Discards the current pixel if the specified value is less than zero. + /// + /// The specified value. + /// + /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane. + /// Also, use the clip function to test for alpha behavior, as shown in the following example: + /// + /// Hlsl.Clip(color.A < 0.1f ? -1 : 1); + /// + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + /// + [HlslIntrinsicName("clip")] + public static void Clip(float x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(float)})"); + + /// + /// Discards the current pixel if the specified value is less than zero. + /// + /// The specified value. + /// + /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane. + /// Also, use the clip function to test for alpha behavior, as shown in the following example: + /// + /// Hlsl.Clip(color.A < 0.1f ? -1 : 1); + /// + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + /// + [HlslIntrinsicName("clip")] + public static void Clip(Float2 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float2)})"); + + /// + /// Discards the current pixel if the specified value is less than zero. + /// + /// The specified value. + /// + /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane. + /// Also, use the clip function to test for alpha behavior, as shown in the following example: + /// + /// Hlsl.Clip(color.A < 0.1f ? -1 : 1); + /// + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + /// + [HlslIntrinsicName("clip")] + public static void Clip(Float3 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float3)})"); + + /// + /// Discards the current pixel if the specified value is less than zero. + /// + /// The specified value. + /// + /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane. + /// Also, use the clip function to test for alpha behavior, as shown in the following example: + /// + /// Hlsl.Clip(color.A < 0.1f ? -1 : 1); + /// + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + /// + [HlslIntrinsicName("clip")] + public static void Clip(Float4 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float4)})"); + + /// + /// Discards the current pixel if the specified value is less than zero. + /// + /// The specified value. + /// + /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane. + /// Also, use the clip function to test for alpha behavior, as shown in the following example: + /// + /// Hlsl.Clip(color.A < 0.1f ? -1 : 1); + /// + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + /// + [HlslIntrinsicName("clip")] + public static void Clip(Float1x1 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float1x1)})"); + + /// + /// Discards the current pixel if the specified value is less than zero. + /// + /// The specified value. + /// + /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane. + /// Also, use the clip function to test for alpha behavior, as shown in the following example: + /// + /// Hlsl.Clip(color.A < 0.1f ? -1 : 1); + /// + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + /// + [HlslIntrinsicName("clip")] + public static void Clip(Float1x2 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float1x2)})"); + + /// + /// Discards the current pixel if the specified value is less than zero. + /// + /// The specified value. + /// + /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane. + /// Also, use the clip function to test for alpha behavior, as shown in the following example: + /// + /// Hlsl.Clip(color.A < 0.1f ? -1 : 1); + /// + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + /// + [HlslIntrinsicName("clip")] + public static void Clip(Float1x3 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float1x3)})"); + + /// + /// Discards the current pixel if the specified value is less than zero. + /// + /// The specified value. + /// + /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane. + /// Also, use the clip function to test for alpha behavior, as shown in the following example: + /// + /// Hlsl.Clip(color.A < 0.1f ? -1 : 1); + /// + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + /// + [HlslIntrinsicName("clip")] + public static void Clip(Float1x4 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float1x4)})"); + + /// + /// Discards the current pixel if the specified value is less than zero. + /// + /// The specified value. + /// + /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane. + /// Also, use the clip function to test for alpha behavior, as shown in the following example: + /// + /// Hlsl.Clip(color.A < 0.1f ? -1 : 1); + /// + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + /// + [HlslIntrinsicName("clip")] + public static void Clip(Float2x1 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float2x1)})"); + + /// + /// Discards the current pixel if the specified value is less than zero. + /// + /// The specified value. + /// + /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane. + /// Also, use the clip function to test for alpha behavior, as shown in the following example: + /// + /// Hlsl.Clip(color.A < 0.1f ? -1 : 1); + /// + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + /// + [HlslIntrinsicName("clip")] + public static void Clip(Float2x2 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float2x2)})"); + + /// + /// Discards the current pixel if the specified value is less than zero. + /// + /// The specified value. + /// + /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane. + /// Also, use the clip function to test for alpha behavior, as shown in the following example: + /// + /// Hlsl.Clip(color.A < 0.1f ? -1 : 1); + /// + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + /// + [HlslIntrinsicName("clip")] + public static void Clip(Float2x3 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float2x3)})"); + + /// + /// Discards the current pixel if the specified value is less than zero. + /// + /// The specified value. + /// + /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane. + /// Also, use the clip function to test for alpha behavior, as shown in the following example: + /// + /// Hlsl.Clip(color.A < 0.1f ? -1 : 1); + /// + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + /// + [HlslIntrinsicName("clip")] + public static void Clip(Float2x4 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float2x4)})"); + + /// + /// Discards the current pixel if the specified value is less than zero. + /// + /// The specified value. + /// + /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane. + /// Also, use the clip function to test for alpha behavior, as shown in the following example: + /// + /// Hlsl.Clip(color.A < 0.1f ? -1 : 1); + /// + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + /// + [HlslIntrinsicName("clip")] + public static void Clip(Float3x1 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float3x1)})"); + + /// + /// Discards the current pixel if the specified value is less than zero. + /// + /// The specified value. + /// + /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane. + /// Also, use the clip function to test for alpha behavior, as shown in the following example: + /// + /// Hlsl.Clip(color.A < 0.1f ? -1 : 1); + /// + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + /// + [HlslIntrinsicName("clip")] + public static void Clip(Float3x2 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float3x2)})"); + + /// + /// Discards the current pixel if the specified value is less than zero. + /// + /// The specified value. + /// + /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane. + /// Also, use the clip function to test for alpha behavior, as shown in the following example: + /// + /// Hlsl.Clip(color.A < 0.1f ? -1 : 1); + /// + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + /// + [HlslIntrinsicName("clip")] + public static void Clip(Float3x3 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float3x3)})"); + + /// + /// Discards the current pixel if the specified value is less than zero. + /// + /// The specified value. + /// + /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane. + /// Also, use the clip function to test for alpha behavior, as shown in the following example: + /// + /// Hlsl.Clip(color.A < 0.1f ? -1 : 1); + /// + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + /// + [HlslIntrinsicName("clip")] + public static void Clip(Float3x4 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float3x4)})"); + + /// + /// Discards the current pixel if the specified value is less than zero. + /// + /// The specified value. + /// + /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane. + /// Also, use the clip function to test for alpha behavior, as shown in the following example: + /// + /// Hlsl.Clip(color.A < 0.1f ? -1 : 1); + /// + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + /// + [HlslIntrinsicName("clip")] + public static void Clip(Float4x1 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float4x1)})"); + + /// + /// Discards the current pixel if the specified value is less than zero. + /// + /// The specified value. + /// + /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane. + /// Also, use the clip function to test for alpha behavior, as shown in the following example: + /// + /// Hlsl.Clip(color.A < 0.1f ? -1 : 1); + /// + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + /// + [HlslIntrinsicName("clip")] + public static void Clip(Float4x2 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float4x2)})"); + + /// + /// Discards the current pixel if the specified value is less than zero. + /// + /// The specified value. + /// + /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane. + /// Also, use the clip function to test for alpha behavior, as shown in the following example: + /// + /// Hlsl.Clip(color.A < 0.1f ? -1 : 1); + /// + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + /// + [HlslIntrinsicName("clip")] + public static void Clip(Float4x3 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float4x3)})"); + + /// + /// Discards the current pixel if the specified value is less than zero. + /// + /// The specified value. + /// + /// Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane. + /// Also, use the clip function to test for alpha behavior, as shown in the following example: + /// + /// Hlsl.Clip(color.A < 0.1f ? -1 : 1); + /// + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + /// + [HlslIntrinsicName("clip")] + public static void Clip(Float4x4 x) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Clip)}({typeof(Float4x4)})"); +} diff --git a/src/ComputeSharp.Core/Intrinsics/Hlsl.Void.tt b/src/ComputeSharp.Core/Intrinsics/Hlsl.Void.tt new file mode 100644 index 00000000..aedffb22 --- /dev/null +++ b/src/ComputeSharp.Core/Intrinsics/Hlsl.Void.tt @@ -0,0 +1,71 @@ +<#@include file="Hlsl.Void.ttinclude" #> +using ComputeSharp.Core.Intrinsics.Attributes; +using ComputeSharp.Exceptions; + +namespace ComputeSharp; + +/// +partial class Hlsl +{ +<# +PushIndent(" "); + +bool isFirst = true; + +foreach (var intrinsic in Intrinsics) +{ + foreach (var overload in intrinsic.Overloads) + { + if (isFirst) isFirst = false; + else WriteLine(""); + + WriteLine("/// "); + WriteLine($"/// {intrinsic.Summary}"); + WriteLine("/// "); + + foreach (var param in intrinsic.Parameters) + { + WriteLine($"/// {param.Info}"); + } + + if (intrinsic.Remarks.Length > 0) + { + var lines = intrinsic.Remarks.Replace("\r", "").Split('\n'); + + WriteLine("/// "); + + foreach (var line in lines) + { + string trimmedLine = line.Trim(); + + if (trimmedLine.Length > 0) + { + WriteLine($"/// {trimmedLine}"); + } + } + + WriteLine("/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior."); + WriteLine("/// "); + } + else + { + WriteLine("/// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior."); + } + + WriteLine($"[HlslIntrinsicName(\"{intrinsic.HlslName}\")]"); + + Write($"public static void {intrinsic.Name}("); + Write(string.Join(", ", intrinsic.Parameters.Zip(overload, (a, b) => $"{(a.IsOut ? "out " : "")}{b} {a.Name}"))); + Write(")"); + + Write(" => throw new InvalidExecutionContextException("); + + var parameters = string.Join(", ", overload.Select(t => $"{{typeof({t})}}")); + + WriteLine($"$\"{{typeof(Hlsl)}}.{{nameof({intrinsic.Name})}}({parameters})\");"); + } +} + +PopIndent(); +#> +} diff --git a/src/ComputeSharp.Core/Intrinsics/Hlsl.Void.ttinclude b/src/ComputeSharp.Core/Intrinsics/Hlsl.Void.ttinclude new file mode 100644 index 00000000..90dc8adf --- /dev/null +++ b/src/ComputeSharp.Core/Intrinsics/Hlsl.Void.ttinclude @@ -0,0 +1,51 @@ +<#@ template debug="false" hostspecific="false" language="C#" #> +<#@ assembly name="System.Core" #> +<#@ import namespace="System.Linq" #> +<#@ import namespace="System.Text" #> +<#@ import namespace="System.Text.RegularExpressions" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ output extension=".g.cs"#> +<# +var Intrinsics = new[] +{ + new + { + Name = "Clip", + HlslName = "clip", + Summary = "Discards the current pixel if the specified value is less than zero.", + Remarks = @" + Use the clip HLSL intrinsic function to simulate clipping planes if each component of the x parameter represents the distance from a plane. + Also, use the clip function to test for alpha behavior, as shown in the following example: + + Hlsl.Clip(color.A < 0.1f ? -1 : 1); + ", + Parameters = new[] + { + new { IsOut = false, IsRef = false, Name = "x", Info = "The specified value." } + }, + Overloads = new[] + { + new[] { "float" }, + new[] { "Float2" }, + new[] { "Float3" }, + new[] { "Float4" }, + new[] { "Float1x1" }, + new[] { "Float1x2" }, + new[] { "Float1x3" }, + new[] { "Float1x4" }, + new[] { "Float2x1" }, + new[] { "Float2x2" }, + new[] { "Float2x3" }, + new[] { "Float2x4" }, + new[] { "Float3x1" }, + new[] { "Float3x2" }, + new[] { "Float3x3" }, + new[] { "Float3x4" }, + new[] { "Float4x1" }, + new[] { "Float4x2" }, + new[] { "Float4x3" }, + new[] { "Float4x4" } + } + } +}; +#> \ No newline at end of file diff --git a/src/ComputeSharp/Core/Intrinsics/Hlsl.cs b/src/ComputeSharp.Core/Intrinsics/Hlsl.cs similarity index 93% rename from src/ComputeSharp/Core/Intrinsics/Hlsl.cs rename to src/ComputeSharp.Core/Intrinsics/Hlsl.cs index 535b8b38..a09a054b 100644 --- a/src/ComputeSharp/Core/Intrinsics/Hlsl.cs +++ b/src/ComputeSharp.Core/Intrinsics/Hlsl.cs @@ -1,4 +1,5 @@ -using ComputeSharp.Exceptions; +using ComputeSharp.Core.Intrinsics.Attributes; +using ComputeSharp.Exceptions; namespace ComputeSharp; @@ -7,6 +8,13 @@ namespace ComputeSharp; /// public static partial class Hlsl { + /// + /// Submits an error message to the information queue and terminates the current draw or dispatch call being executed. + /// + /// This operation does nothing on rasterizers that do not support it. + [HlslIntrinsicName("abort")] + public static void Abort() => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Abort)}()"); + /// /// Blocks execution of all threads in a group until all memory accesses have been completed. /// @@ -316,4 +324,24 @@ public static partial class Hlsl /// The original value. /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. public static void InterlockedXor(ref uint destination, uint value, out uint original) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(InterlockedXor)}({typeof(uint)}, {typeof(uint)}, {typeof(uint)})"); + + /// + /// Returns a lighting coefficient vector. + /// + /// The dot product of the normalized surface normal and the light vector. + /// The dot product of the half-angle vector and the surface normal. + /// A specular exponent. + /// The lighting coefficient vector. + /// + /// This function returns a lighting coefficient vector (ambient, diffuse, specular, 1) where: + /// + /// Ambient: 1. + /// Diffuse: n * l < 0 ? 0 : n * l. + /// Specular: n * l < 0 || n * h < 0 ? 0 : (n * h) ^ m. + /// + /// Where the vector n is the normal vector, l is the direction to light and h is the half vector. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + /// + [HlslIntrinsicName("lit")] + public static float Lit(float nDotL, float nDotH, float m) => default; } diff --git a/src/ComputeSharp/Core/Intrinsics/Hlsl.g.cs b/src/ComputeSharp.Core/Intrinsics/Hlsl.g.cs similarity index 95% rename from src/ComputeSharp/Core/Intrinsics/Hlsl.g.cs rename to src/ComputeSharp.Core/Intrinsics/Hlsl.g.cs index e74bba24..41a98d1b 100644 --- a/src/ComputeSharp/Core/Intrinsics/Hlsl.g.cs +++ b/src/ComputeSharp.Core/Intrinsics/Hlsl.g.cs @@ -4,7 +4,7 @@ using ComputeSharp.Exceptions; namespace ComputeSharp; /// -public static partial class Hlsl +partial class Hlsl { /// /// Returns the absolute value of the specified value. @@ -4492,6 +4492,510 @@ public static partial class Hlsl [HlslIntrinsicName("cross")] public static Float3 Cross(Float3 x, Float3 y) => default; + /// + /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx")] + public static float DerivativeOfDx(float x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx")] + public static Float2 DerivativeOfDx(Float2 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx")] + public static Float3 DerivativeOfDx(Float3 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx")] + public static Float4 DerivativeOfDx(Float4 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx")] + public static Float1x1 DerivativeOfDx(Float1x1 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx")] + public static Float1x2 DerivativeOfDx(Float1x2 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx")] + public static Float1x3 DerivativeOfDx(Float1x3 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx")] + public static Float1x4 DerivativeOfDx(Float1x4 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx")] + public static Float2x1 DerivativeOfDx(Float2x1 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx")] + public static Float2x2 DerivativeOfDx(Float2x2 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx")] + public static Float2x3 DerivativeOfDx(Float2x3 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx")] + public static Float2x4 DerivativeOfDx(Float2x4 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx")] + public static Float3x1 DerivativeOfDx(Float3x1 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx")] + public static Float3x2 DerivativeOfDx(Float3x2 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx")] + public static Float3x3 DerivativeOfDx(Float3x3 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx")] + public static Float3x4 DerivativeOfDx(Float3x4 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx")] + public static Float4x1 DerivativeOfDx(Float4x1 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx")] + public static Float4x2 DerivativeOfDx(Float4x2 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx")] + public static Float4x3 DerivativeOfDx(Float4x3 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx")] + public static Float4x4 DerivativeOfDx(Float4x4 x) => default; + + /// + /// Computes a low precision partial derivative with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The low precision partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx_coarse")] + public static float DerivativeOfDxLowPrecision(float x) => default; + + /// + /// Computes a low precision partial derivative with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The low precision partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx_coarse")] + public static Float2 DerivativeOfDxLowPrecision(Float2 x) => default; + + /// + /// Computes a low precision partial derivative with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The low precision partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx_coarse")] + public static Float3 DerivativeOfDxLowPrecision(Float3 x) => default; + + /// + /// Computes a low precision partial derivative with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The low precision partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx_coarse")] + public static Float4 DerivativeOfDxLowPrecision(Float4 x) => default; + + /// + /// Computes a high precision partial derivative with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The high precision partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx_fine")] + public static float DerivativeOfDxHighPrecision(float x) => default; + + /// + /// Computes a high precision partial derivative with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The high precision partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx_fine")] + public static Float2 DerivativeOfDxHighPrecision(Float2 x) => default; + + /// + /// Computes a high precision partial derivative with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The high precision partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx_fine")] + public static Float3 DerivativeOfDxHighPrecision(Float3 x) => default; + + /// + /// Computes a high precision partial derivative with respect to the screen-space x-coordinate. + /// + /// The specified value. + /// The high precision partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddx_fine")] + public static Float4 DerivativeOfDxHighPrecision(Float4 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy")] + public static float DerivativeOfDy(float x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy")] + public static Float2 DerivativeOfDy(Float2 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy")] + public static Float3 DerivativeOfDy(Float3 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy")] + public static Float4 DerivativeOfDy(Float4 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy")] + public static Float1x1 DerivativeOfDy(Float1x1 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy")] + public static Float1x2 DerivativeOfDy(Float1x2 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy")] + public static Float1x3 DerivativeOfDy(Float1x3 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy")] + public static Float1x4 DerivativeOfDy(Float1x4 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy")] + public static Float2x1 DerivativeOfDy(Float2x1 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy")] + public static Float2x2 DerivativeOfDy(Float2x2 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy")] + public static Float2x3 DerivativeOfDy(Float2x3 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy")] + public static Float2x4 DerivativeOfDy(Float2x4 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy")] + public static Float3x1 DerivativeOfDy(Float3x1 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy")] + public static Float3x2 DerivativeOfDy(Float3x2 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy")] + public static Float3x3 DerivativeOfDy(Float3x3 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy")] + public static Float3x4 DerivativeOfDy(Float3x4 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy")] + public static Float4x1 DerivativeOfDy(Float4x1 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy")] + public static Float4x2 DerivativeOfDy(Float4x2 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy")] + public static Float4x3 DerivativeOfDy(Float4x3 x) => default; + + /// + /// Returns the partial derivative of the specified value with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy")] + public static Float4x4 DerivativeOfDy(Float4x4 x) => default; + + /// + /// Computes a low precision partial derivative with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The low precision partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy_coarse")] + public static float DerivativeOfDyLowPrecision(float x) => default; + + /// + /// Computes a low precision partial derivative with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The low precision partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy_coarse")] + public static Float2 DerivativeOfDyLowPrecision(Float2 x) => default; + + /// + /// Computes a low precision partial derivative with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The low precision partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy_coarse")] + public static Float3 DerivativeOfDyLowPrecision(Float3 x) => default; + + /// + /// Computes a low precision partial derivative with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The low precision partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy_coarse")] + public static Float4 DerivativeOfDyLowPrecision(Float4 x) => default; + + /// + /// Computes a high precision partial derivative with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The high precision partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy_fine")] + public static float DerivativeOfDyHighPrecision(float x) => default; + + /// + /// Computes a high precision partial derivative with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The high precision partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy_fine")] + public static Float2 DerivativeOfDyHighPrecision(Float2 x) => default; + + /// + /// Computes a high precision partial derivative with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The high precision partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy_fine")] + public static Float3 DerivativeOfDyHighPrecision(Float3 x) => default; + + /// + /// Computes a high precision partial derivative with respect to the screen-space y-coordinate. + /// + /// The specified value. + /// The high precision partial derivative with respect to the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("ddy_fine")] + public static Float4 DerivativeOfDyHighPrecision(Float4 x) => default; + /// /// Converts the specified value from radians to degrees. /// @@ -5491,7 +5995,7 @@ public static partial class Hlsl /// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP). /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. [HlslIntrinsicName("fma")] - public static double FusedMultiplyAccumulate(double a, double b, double c) => default; + public static double FusedMultiplyAdd(double a, double b, double c) => default; /// /// Returns the double-precision fused multiply-addition of a * b + c. @@ -5502,7 +6006,7 @@ public static partial class Hlsl /// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP). /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. [HlslIntrinsicName("fma")] - public static Double2 FusedMultiplyAccumulate(Double2 a, Double2 b, Double2 c) => default; + public static Double2 FusedMultiplyAdd(Double2 a, Double2 b, Double2 c) => default; /// /// Returns the double-precision fused multiply-addition of a * b + c. @@ -5513,7 +6017,7 @@ public static partial class Hlsl /// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP). /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. [HlslIntrinsicName("fma")] - public static Double3 FusedMultiplyAccumulate(Double3 a, Double3 b, Double3 c) => default; + public static Double3 FusedMultiplyAdd(Double3 a, Double3 b, Double3 c) => default; /// /// Returns the double-precision fused multiply-addition of a * b + c. @@ -5524,7 +6028,7 @@ public static partial class Hlsl /// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP). /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. [HlslIntrinsicName("fma")] - public static Double4 FusedMultiplyAccumulate(Double4 a, Double4 b, Double4 c) => default; + public static Double4 FusedMultiplyAdd(Double4 a, Double4 b, Double4 c) => default; /// /// Returns the double-precision fused multiply-addition of a * b + c. @@ -5535,7 +6039,7 @@ public static partial class Hlsl /// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP). /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. [HlslIntrinsicName("fma")] - public static Double1x1 FusedMultiplyAccumulate(Double1x1 a, Double1x1 b, Double1x1 c) => default; + public static Double1x1 FusedMultiplyAdd(Double1x1 a, Double1x1 b, Double1x1 c) => default; /// /// Returns the double-precision fused multiply-addition of a * b + c. @@ -5546,7 +6050,7 @@ public static partial class Hlsl /// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP). /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. [HlslIntrinsicName("fma")] - public static Double1x2 FusedMultiplyAccumulate(Double1x2 a, Double1x2 b, Double1x2 c) => default; + public static Double1x2 FusedMultiplyAdd(Double1x2 a, Double1x2 b, Double1x2 c) => default; /// /// Returns the double-precision fused multiply-addition of a * b + c. @@ -5557,7 +6061,7 @@ public static partial class Hlsl /// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP). /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. [HlslIntrinsicName("fma")] - public static Double1x3 FusedMultiplyAccumulate(Double1x3 a, Double1x3 b, Double1x3 c) => default; + public static Double1x3 FusedMultiplyAdd(Double1x3 a, Double1x3 b, Double1x3 c) => default; /// /// Returns the double-precision fused multiply-addition of a * b + c. @@ -5568,7 +6072,7 @@ public static partial class Hlsl /// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP). /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. [HlslIntrinsicName("fma")] - public static Double1x4 FusedMultiplyAccumulate(Double1x4 a, Double1x4 b, Double1x4 c) => default; + public static Double1x4 FusedMultiplyAdd(Double1x4 a, Double1x4 b, Double1x4 c) => default; /// /// Returns the double-precision fused multiply-addition of a * b + c. @@ -5579,7 +6083,7 @@ public static partial class Hlsl /// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP). /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. [HlslIntrinsicName("fma")] - public static Double2x1 FusedMultiplyAccumulate(Double2x1 a, Double2x1 b, Double2x1 c) => default; + public static Double2x1 FusedMultiplyAdd(Double2x1 a, Double2x1 b, Double2x1 c) => default; /// /// Returns the double-precision fused multiply-addition of a * b + c. @@ -5590,7 +6094,7 @@ public static partial class Hlsl /// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP). /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. [HlslIntrinsicName("fma")] - public static Double2x2 FusedMultiplyAccumulate(Double2x2 a, Double2x2 b, Double2x2 c) => default; + public static Double2x2 FusedMultiplyAdd(Double2x2 a, Double2x2 b, Double2x2 c) => default; /// /// Returns the double-precision fused multiply-addition of a * b + c. @@ -5601,7 +6105,7 @@ public static partial class Hlsl /// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP). /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. [HlslIntrinsicName("fma")] - public static Double2x3 FusedMultiplyAccumulate(Double2x3 a, Double2x3 b, Double2x3 c) => default; + public static Double2x3 FusedMultiplyAdd(Double2x3 a, Double2x3 b, Double2x3 c) => default; /// /// Returns the double-precision fused multiply-addition of a * b + c. @@ -5612,7 +6116,7 @@ public static partial class Hlsl /// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP). /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. [HlslIntrinsicName("fma")] - public static Double2x4 FusedMultiplyAccumulate(Double2x4 a, Double2x4 b, Double2x4 c) => default; + public static Double2x4 FusedMultiplyAdd(Double2x4 a, Double2x4 b, Double2x4 c) => default; /// /// Returns the double-precision fused multiply-addition of a * b + c. @@ -5623,7 +6127,7 @@ public static partial class Hlsl /// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP). /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. [HlslIntrinsicName("fma")] - public static Double3x1 FusedMultiplyAccumulate(Double3x1 a, Double3x1 b, Double3x1 c) => default; + public static Double3x1 FusedMultiplyAdd(Double3x1 a, Double3x1 b, Double3x1 c) => default; /// /// Returns the double-precision fused multiply-addition of a * b + c. @@ -5634,7 +6138,7 @@ public static partial class Hlsl /// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP). /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. [HlslIntrinsicName("fma")] - public static Double3x2 FusedMultiplyAccumulate(Double3x2 a, Double3x2 b, Double3x2 c) => default; + public static Double3x2 FusedMultiplyAdd(Double3x2 a, Double3x2 b, Double3x2 c) => default; /// /// Returns the double-precision fused multiply-addition of a * b + c. @@ -5645,7 +6149,7 @@ public static partial class Hlsl /// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP). /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. [HlslIntrinsicName("fma")] - public static Double3x3 FusedMultiplyAccumulate(Double3x3 a, Double3x3 b, Double3x3 c) => default; + public static Double3x3 FusedMultiplyAdd(Double3x3 a, Double3x3 b, Double3x3 c) => default; /// /// Returns the double-precision fused multiply-addition of a * b + c. @@ -5656,7 +6160,7 @@ public static partial class Hlsl /// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP). /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. [HlslIntrinsicName("fma")] - public static Double3x4 FusedMultiplyAccumulate(Double3x4 a, Double3x4 b, Double3x4 c) => default; + public static Double3x4 FusedMultiplyAdd(Double3x4 a, Double3x4 b, Double3x4 c) => default; /// /// Returns the double-precision fused multiply-addition of a * b + c. @@ -5667,7 +6171,7 @@ public static partial class Hlsl /// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP). /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. [HlslIntrinsicName("fma")] - public static Double4x1 FusedMultiplyAccumulate(Double4x1 a, Double4x1 b, Double4x1 c) => default; + public static Double4x1 FusedMultiplyAdd(Double4x1 a, Double4x1 b, Double4x1 c) => default; /// /// Returns the double-precision fused multiply-addition of a * b + c. @@ -5678,7 +6182,7 @@ public static partial class Hlsl /// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP). /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. [HlslIntrinsicName("fma")] - public static Double4x2 FusedMultiplyAccumulate(Double4x2 a, Double4x2 b, Double4x2 c) => default; + public static Double4x2 FusedMultiplyAdd(Double4x2 a, Double4x2 b, Double4x2 c) => default; /// /// Returns the double-precision fused multiply-addition of a * b + c. @@ -5689,7 +6193,7 @@ public static partial class Hlsl /// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP). /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. [HlslIntrinsicName("fma")] - public static Double4x3 FusedMultiplyAccumulate(Double4x3 a, Double4x3 b, Double4x3 c) => default; + public static Double4x3 FusedMultiplyAdd(Double4x3 a, Double4x3 b, Double4x3 c) => default; /// /// Returns the double-precision fused multiply-addition of a * b + c. @@ -5700,7 +6204,7 @@ public static partial class Hlsl /// The double-precision fused multiply-addition of parameters a * b + c. The returned value must be accurate to 0.5 units of least precision (ULP). /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. [HlslIntrinsicName("fma")] - public static Double4x4 FusedMultiplyAccumulate(Double4x4 a, Double4x4 b, Double4x4 c) => default; + public static Double4x4 FusedMultiplyAdd(Double4x4 a, Double4x4 b, Double4x4 c) => default; /// /// Returns the floating-point remainder of x / y. @@ -6282,6 +6786,186 @@ public static partial class Hlsl [HlslIntrinsicName("frexp")] public static Float4x4 Frexp(Float4x4 x, out Float4x4 exp) => throw new InvalidExecutionContextException($"{typeof(Hlsl)}.{nameof(Frexp)}({typeof(Float4x4)}, {typeof(Float4x4)})"); + /// + /// Returns the absolute value of the partial derivatives of the specified value. + /// + /// The specified value. + /// The absolute value of the partial derivatives of the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("fwidth")] + public static float Fwidth(float x) => default; + + /// + /// Returns the absolute value of the partial derivatives of the specified value. + /// + /// The specified value. + /// The absolute value of the partial derivatives of the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("fwidth")] + public static Float2 Fwidth(Float2 x) => default; + + /// + /// Returns the absolute value of the partial derivatives of the specified value. + /// + /// The specified value. + /// The absolute value of the partial derivatives of the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("fwidth")] + public static Float3 Fwidth(Float3 x) => default; + + /// + /// Returns the absolute value of the partial derivatives of the specified value. + /// + /// The specified value. + /// The absolute value of the partial derivatives of the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("fwidth")] + public static Float4 Fwidth(Float4 x) => default; + + /// + /// Returns the absolute value of the partial derivatives of the specified value. + /// + /// The specified value. + /// The absolute value of the partial derivatives of the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("fwidth")] + public static Float1x1 Fwidth(Float1x1 x) => default; + + /// + /// Returns the absolute value of the partial derivatives of the specified value. + /// + /// The specified value. + /// The absolute value of the partial derivatives of the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("fwidth")] + public static Float1x2 Fwidth(Float1x2 x) => default; + + /// + /// Returns the absolute value of the partial derivatives of the specified value. + /// + /// The specified value. + /// The absolute value of the partial derivatives of the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("fwidth")] + public static Float1x3 Fwidth(Float1x3 x) => default; + + /// + /// Returns the absolute value of the partial derivatives of the specified value. + /// + /// The specified value. + /// The absolute value of the partial derivatives of the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("fwidth")] + public static Float1x4 Fwidth(Float1x4 x) => default; + + /// + /// Returns the absolute value of the partial derivatives of the specified value. + /// + /// The specified value. + /// The absolute value of the partial derivatives of the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("fwidth")] + public static Float2x1 Fwidth(Float2x1 x) => default; + + /// + /// Returns the absolute value of the partial derivatives of the specified value. + /// + /// The specified value. + /// The absolute value of the partial derivatives of the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("fwidth")] + public static Float2x2 Fwidth(Float2x2 x) => default; + + /// + /// Returns the absolute value of the partial derivatives of the specified value. + /// + /// The specified value. + /// The absolute value of the partial derivatives of the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("fwidth")] + public static Float2x3 Fwidth(Float2x3 x) => default; + + /// + /// Returns the absolute value of the partial derivatives of the specified value. + /// + /// The specified value. + /// The absolute value of the partial derivatives of the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("fwidth")] + public static Float2x4 Fwidth(Float2x4 x) => default; + + /// + /// Returns the absolute value of the partial derivatives of the specified value. + /// + /// The specified value. + /// The absolute value of the partial derivatives of the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("fwidth")] + public static Float3x1 Fwidth(Float3x1 x) => default; + + /// + /// Returns the absolute value of the partial derivatives of the specified value. + /// + /// The specified value. + /// The absolute value of the partial derivatives of the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("fwidth")] + public static Float3x2 Fwidth(Float3x2 x) => default; + + /// + /// Returns the absolute value of the partial derivatives of the specified value. + /// + /// The specified value. + /// The absolute value of the partial derivatives of the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("fwidth")] + public static Float3x3 Fwidth(Float3x3 x) => default; + + /// + /// Returns the absolute value of the partial derivatives of the specified value. + /// + /// The specified value. + /// The absolute value of the partial derivatives of the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("fwidth")] + public static Float3x4 Fwidth(Float3x4 x) => default; + + /// + /// Returns the absolute value of the partial derivatives of the specified value. + /// + /// The specified value. + /// The absolute value of the partial derivatives of the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("fwidth")] + public static Float4x1 Fwidth(Float4x1 x) => default; + + /// + /// Returns the absolute value of the partial derivatives of the specified value. + /// + /// The specified value. + /// The absolute value of the partial derivatives of the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("fwidth")] + public static Float4x2 Fwidth(Float4x2 x) => default; + + /// + /// Returns the absolute value of the partial derivatives of the specified value. + /// + /// The specified value. + /// The absolute value of the partial derivatives of the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("fwidth")] + public static Float4x3 Fwidth(Float4x3 x) => default; + + /// + /// Returns the absolute value of the partial derivatives of the specified value. + /// + /// The specified value. + /// The absolute value of the partial derivatives of the input parameter. + /// This method is an intrinsic and can only be used within a shader on the GPU. Using it on the CPU is undefined behavior. + [HlslIntrinsicName("fwidth")] + public static Float4x4 Fwidth(Float4x4 x) => default; + /// /// Determines if the specified floating-point value is finite. /// diff --git a/src/ComputeSharp/Core/Intrinsics/Hlsl.tt b/src/ComputeSharp.Core/Intrinsics/Hlsl.tt similarity index 98% rename from src/ComputeSharp/Core/Intrinsics/Hlsl.tt rename to src/ComputeSharp.Core/Intrinsics/Hlsl.tt index 676840f0..65c93f07 100644 --- a/src/ComputeSharp/Core/Intrinsics/Hlsl.tt +++ b/src/ComputeSharp.Core/Intrinsics/Hlsl.tt @@ -5,7 +5,7 @@ using ComputeSharp.Exceptions; namespace ComputeSharp; /// -public static partial class Hlsl +partial class Hlsl { <# PushIndent(" "); diff --git a/src/ComputeSharp/Core/Intrinsics/Hlsl.ttinclude b/src/ComputeSharp.Core/Intrinsics/Hlsl.ttinclude similarity index 94% rename from src/ComputeSharp/Core/Intrinsics/Hlsl.ttinclude rename to src/ComputeSharp.Core/Intrinsics/Hlsl.ttinclude index c6b47260..470fdde4 100644 --- a/src/ComputeSharp/Core/Intrinsics/Hlsl.ttinclude +++ b/src/ComputeSharp.Core/Intrinsics/Hlsl.ttinclude @@ -739,6 +739,146 @@ var Intrinsics = new[] } }, new + { + Name = "DerivativeOfDx", + HlslName = "ddx", + Summary = "Returns the partial derivative of the specified value with respect to the screen-space x-coordinate.", + Parameters = new[] + { + new { IsOut = false, Name = "x", Info = "The specified value." } + }, + Returns = "The partial derivative with respect to the input parameter.", + Overloads = new[] + { + new { Return = "float", Params = new[] { "float" } }, + new { Return = "Float2", Params = new[] { "Float2" } }, + new { Return = "Float3", Params = new[] { "Float3" } }, + new { Return = "Float4", Params = new[] { "Float4" } }, + new { Return = "Float1x1", Params = new[] { "Float1x1" } }, + new { Return = "Float1x2", Params = new[] { "Float1x2" } }, + new { Return = "Float1x3", Params = new[] { "Float1x3" } }, + new { Return = "Float1x4", Params = new[] { "Float1x4" } }, + new { Return = "Float2x1", Params = new[] { "Float2x1" } }, + new { Return = "Float2x2", Params = new[] { "Float2x2" } }, + new { Return = "Float2x3", Params = new[] { "Float2x3" } }, + new { Return = "Float2x4", Params = new[] { "Float2x4" } }, + new { Return = "Float3x1", Params = new[] { "Float3x1" } }, + new { Return = "Float3x2", Params = new[] { "Float3x2" } }, + new { Return = "Float3x3", Params = new[] { "Float3x3" } }, + new { Return = "Float3x4", Params = new[] { "Float3x4" } }, + new { Return = "Float4x1", Params = new[] { "Float4x1" } }, + new { Return = "Float4x2", Params = new[] { "Float4x2" } }, + new { Return = "Float4x3", Params = new[] { "Float4x3" } }, + new { Return = "Float4x4", Params = new[] { "Float4x4" } } + } + }, + new + { + Name = "DerivativeOfDxLowPrecision", + HlslName = "ddx_coarse", + Summary = "Computes a low precision partial derivative with respect to the screen-space x-coordinate.", + Parameters = new[] + { + new { IsOut = false, Name = "x", Info = "The specified value." } + }, + Returns = "The low precision partial derivative with respect to the input parameter.", + Overloads = new[] + { + new { Return = "float", Params = new[] { "float" } }, + new { Return = "Float2", Params = new[] { "Float2" } }, + new { Return = "Float3", Params = new[] { "Float3" } }, + new { Return = "Float4", Params = new[] { "Float4" } } + } + }, + new + { + Name = "DerivativeOfDxHighPrecision", + HlslName = "ddx_fine", + Summary = "Computes a high precision partial derivative with respect to the screen-space x-coordinate.", + Parameters = new[] + { + new { IsOut = false, Name = "x", Info = "The specified value." } + }, + Returns = "The high precision partial derivative with respect to the input parameter.", + Overloads = new[] + { + new { Return = "float", Params = new[] { "float" } }, + new { Return = "Float2", Params = new[] { "Float2" } }, + new { Return = "Float3", Params = new[] { "Float3" } }, + new { Return = "Float4", Params = new[] { "Float4" } } + } + }, + new + { + Name = "DerivativeOfDy", + HlslName = "ddy", + Summary = "Returns the partial derivative of the specified value with respect to the screen-space y-coordinate.", + Parameters = new[] + { + new { IsOut = false, Name = "x", Info = "The specified value." } + }, + Returns = "The partial derivative with respect to the input parameter.", + Overloads = new[] + { + new { Return = "float", Params = new[] { "float" } }, + new { Return = "Float2", Params = new[] { "Float2" } }, + new { Return = "Float3", Params = new[] { "Float3" } }, + new { Return = "Float4", Params = new[] { "Float4" } }, + new { Return = "Float1x1", Params = new[] { "Float1x1" } }, + new { Return = "Float1x2", Params = new[] { "Float1x2" } }, + new { Return = "Float1x3", Params = new[] { "Float1x3" } }, + new { Return = "Float1x4", Params = new[] { "Float1x4" } }, + new { Return = "Float2x1", Params = new[] { "Float2x1" } }, + new { Return = "Float2x2", Params = new[] { "Float2x2" } }, + new { Return = "Float2x3", Params = new[] { "Float2x3" } }, + new { Return = "Float2x4", Params = new[] { "Float2x4" } }, + new { Return = "Float3x1", Params = new[] { "Float3x1" } }, + new { Return = "Float3x2", Params = new[] { "Float3x2" } }, + new { Return = "Float3x3", Params = new[] { "Float3x3" } }, + new { Return = "Float3x4", Params = new[] { "Float3x4" } }, + new { Return = "Float4x1", Params = new[] { "Float4x1" } }, + new { Return = "Float4x2", Params = new[] { "Float4x2" } }, + new { Return = "Float4x3", Params = new[] { "Float4x3" } }, + new { Return = "Float4x4", Params = new[] { "Float4x4" } } + } + }, + new + { + Name = "DerivativeOfDyLowPrecision", + HlslName = "ddy_coarse", + Summary = "Computes a low precision partial derivative with respect to the screen-space y-coordinate.", + Parameters = new[] + { + new { IsOut = false, Name = "x", Info = "The specified value." } + }, + Returns = "The low precision partial derivative with respect to the input parameter.", + Overloads = new[] + { + new { Return = "float", Params = new[] { "float" } }, + new { Return = "Float2", Params = new[] { "Float2" } }, + new { Return = "Float3", Params = new[] { "Float3" } }, + new { Return = "Float4", Params = new[] { "Float4" } } + } + }, + new + { + Name = "DerivativeOfDyHighPrecision", + HlslName = "ddy_fine", + Summary = "Computes a high precision partial derivative with respect to the screen-space y-coordinate.", + Parameters = new[] + { + new { IsOut = false, Name = "x", Info = "The specified value." } + }, + Returns = "The high precision partial derivative with respect to the input parameter.", + Overloads = new[] + { + new { Return = "float", Params = new[] { "float" } }, + new { Return = "Float2", Params = new[] { "Float2" } }, + new { Return = "Float3", Params = new[] { "Float3" } }, + new { Return = "Float4", Params = new[] { "Float4" } } + } + }, + new { Name = "Degrees", HlslName = "degrees", @@ -977,7 +1117,7 @@ var Intrinsics = new[] }, new { - Name = "FusedMultiplyAccumulate", + Name = "FusedMultiplyAdd", HlslName = "fma", Summary = "Returns the double-precision fused multiply-addition of a * b + c.", Parameters = new[] @@ -1116,6 +1256,40 @@ var Intrinsics = new[] } }, new + { + Name = "Fwidth", + HlslName = "fwidth", + Summary = "Returns the absolute value of the partial derivatives of the specified value.", + Parameters = new[] + { + new { IsOut = false, Name = "x", Info = "The specified value." } + }, + Returns = "The absolute value of the partial derivatives of the input parameter.", + Overloads = new[] + { + new { Return = "float", Params = new[] { "float" } }, + new { Return = "Float2", Params = new[] { "Float2" } }, + new { Return = "Float3", Params = new[] { "Float3" } }, + new { Return = "Float4", Params = new[] { "Float4" } }, + new { Return = "Float1x1", Params = new[] { "Float1x1" } }, + new { Return = "Float1x2", Params = new[] { "Float1x2" } }, + new { Return = "Float1x3", Params = new[] { "Float1x3" } }, + new { Return = "Float1x4", Params = new[] { "Float1x4" } }, + new { Return = "Float2x1", Params = new[] { "Float2x1" } }, + new { Return = "Float2x2", Params = new[] { "Float2x2" } }, + new { Return = "Float2x3", Params = new[] { "Float2x3" } }, + new { Return = "Float2x4", Params = new[] { "Float2x4" } }, + new { Return = "Float3x1", Params = new[] { "Float3x1" } }, + new { Return = "Float3x2", Params = new[] { "Float3x2" } }, + new { Return = "Float3x3", Params = new[] { "Float3x3" } }, + new { Return = "Float3x4", Params = new[] { "Float3x4" } }, + new { Return = "Float4x1", Params = new[] { "Float4x1" } }, + new { Return = "Float4x2", Params = new[] { "Float4x2" } }, + new { Return = "Float4x3", Params = new[] { "Float4x3" } }, + new { Return = "Float4x4", Params = new[] { "Float4x4" } } + } + }, + new { Name = "IsFinite", HlslName = "isfinite", diff --git a/src/ComputeSharp/Core/Primitives/Bool/Bool.cs b/src/ComputeSharp.Core/Primitives/Bool/Bool.cs similarity index 100% rename from src/ComputeSharp/Core/Primitives/Bool/Bool.cs rename to src/ComputeSharp.Core/Primitives/Bool/Bool.cs diff --git a/src/ComputeSharp/Core/Primitives/Bool/Bool2.cs b/src/ComputeSharp.Core/Primitives/Bool/Bool2.cs similarity index 100% rename from src/ComputeSharp/Core/Primitives/Bool/Bool2.cs rename to src/ComputeSharp.Core/Primitives/Bool/Bool2.cs diff --git a/src/ComputeSharp/Core/Primitives/Bool/Bool2.g.cs b/src/ComputeSharp.Core/Primitives/Bool/Bool2.g.cs similarity index 99% rename from src/ComputeSharp/Core/Primitives/Bool/Bool2.g.cs rename to src/ComputeSharp.Core/Primitives/Bool/Bool2.g.cs index f1beeb1c..86158121 100644 --- a/src/ComputeSharp/Core/Primitives/Bool/Bool2.g.cs +++ b/src/ComputeSharp.Core/Primitives/Bool/Bool2.g.cs @@ -1,8 +1,8 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if !NET6_0_OR_GREATER -using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; -using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal; +using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal; #endif #nullable enable diff --git a/src/ComputeSharp/Core/Primitives/Bool/Bool2.tt b/src/ComputeSharp.Core/Primitives/Bool/Bool2.tt similarity index 100% rename from src/ComputeSharp/Core/Primitives/Bool/Bool2.tt rename to src/ComputeSharp.Core/Primitives/Bool/Bool2.tt diff --git a/src/ComputeSharp/Core/Primitives/Bool/Bool3.cs b/src/ComputeSharp.Core/Primitives/Bool/Bool3.cs similarity index 100% rename from src/ComputeSharp/Core/Primitives/Bool/Bool3.cs rename to src/ComputeSharp.Core/Primitives/Bool/Bool3.cs diff --git a/src/ComputeSharp/Core/Primitives/Bool/Bool3.g.cs b/src/ComputeSharp.Core/Primitives/Bool/Bool3.g.cs similarity index 99% rename from src/ComputeSharp/Core/Primitives/Bool/Bool3.g.cs rename to src/ComputeSharp.Core/Primitives/Bool/Bool3.g.cs index a70a8163..018577c6 100644 --- a/src/ComputeSharp/Core/Primitives/Bool/Bool3.g.cs +++ b/src/ComputeSharp.Core/Primitives/Bool/Bool3.g.cs @@ -1,8 +1,8 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if !NET6_0_OR_GREATER -using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; -using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal; +using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal; #endif #nullable enable diff --git a/src/ComputeSharp/Core/Primitives/Bool/Bool3.tt b/src/ComputeSharp.Core/Primitives/Bool/Bool3.tt similarity index 100% rename from src/ComputeSharp/Core/Primitives/Bool/Bool3.tt rename to src/ComputeSharp.Core/Primitives/Bool/Bool3.tt diff --git a/src/ComputeSharp/Core/Primitives/Bool/Bool4.cs b/src/ComputeSharp.Core/Primitives/Bool/Bool4.cs similarity index 100% rename from src/ComputeSharp/Core/Primitives/Bool/Bool4.cs rename to src/ComputeSharp.Core/Primitives/Bool/Bool4.cs diff --git a/src/ComputeSharp/Core/Primitives/Bool/Bool4.g.cs b/src/ComputeSharp.Core/Primitives/Bool/Bool4.g.cs similarity index 99% rename from src/ComputeSharp/Core/Primitives/Bool/Bool4.g.cs rename to src/ComputeSharp.Core/Primitives/Bool/Bool4.g.cs index 699eb862..175339be 100644 --- a/src/ComputeSharp/Core/Primitives/Bool/Bool4.g.cs +++ b/src/ComputeSharp.Core/Primitives/Bool/Bool4.g.cs @@ -1,8 +1,8 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if !NET6_0_OR_GREATER -using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; -using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal; +using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal; #endif #nullable enable diff --git a/src/ComputeSharp/Core/Primitives/Bool/Bool4.tt b/src/ComputeSharp.Core/Primitives/Bool/Bool4.tt similarity index 100% rename from src/ComputeSharp/Core/Primitives/Bool/Bool4.tt rename to src/ComputeSharp.Core/Primitives/Bool/Bool4.tt diff --git a/src/ComputeSharp/Core/Primitives/Bool/BoolMxN.g.cs b/src/ComputeSharp.Core/Primitives/Bool/BoolMxN.g.cs similarity index 99% rename from src/ComputeSharp/Core/Primitives/Bool/BoolMxN.g.cs rename to src/ComputeSharp.Core/Primitives/Bool/BoolMxN.g.cs index e34bc6bf..3925f701 100644 --- a/src/ComputeSharp/Core/Primitives/Bool/BoolMxN.g.cs +++ b/src/ComputeSharp.Core/Primitives/Bool/BoolMxN.g.cs @@ -1,8 +1,8 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if !NET6_0_OR_GREATER -using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; -using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal; +using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal; #endif namespace ComputeSharp; diff --git a/src/ComputeSharp/Core/Primitives/Bool/BoolMxN.tt b/src/ComputeSharp.Core/Primitives/Bool/BoolMxN.tt similarity index 100% rename from src/ComputeSharp/Core/Primitives/Bool/BoolMxN.tt rename to src/ComputeSharp.Core/Primitives/Bool/BoolMxN.tt diff --git a/src/ComputeSharp/Core/Primitives/Double/Double2.cs b/src/ComputeSharp.Core/Primitives/Double/Double2.cs similarity index 100% rename from src/ComputeSharp/Core/Primitives/Double/Double2.cs rename to src/ComputeSharp.Core/Primitives/Double/Double2.cs diff --git a/src/ComputeSharp/Core/Primitives/Double/Double2.g.cs b/src/ComputeSharp.Core/Primitives/Double/Double2.g.cs similarity index 99% rename from src/ComputeSharp/Core/Primitives/Double/Double2.g.cs rename to src/ComputeSharp.Core/Primitives/Double/Double2.g.cs index fdc974de..86c06ce4 100644 --- a/src/ComputeSharp/Core/Primitives/Double/Double2.g.cs +++ b/src/ComputeSharp.Core/Primitives/Double/Double2.g.cs @@ -3,8 +3,8 @@ using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if !NET6_0_OR_GREATER -using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; -using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal; +using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal; #endif #nullable enable diff --git a/src/ComputeSharp/Core/Primitives/Double/Double2.tt b/src/ComputeSharp.Core/Primitives/Double/Double2.tt similarity index 100% rename from src/ComputeSharp/Core/Primitives/Double/Double2.tt rename to src/ComputeSharp.Core/Primitives/Double/Double2.tt diff --git a/src/ComputeSharp/Core/Primitives/Double/Double3.cs b/src/ComputeSharp.Core/Primitives/Double/Double3.cs similarity index 100% rename from src/ComputeSharp/Core/Primitives/Double/Double3.cs rename to src/ComputeSharp.Core/Primitives/Double/Double3.cs diff --git a/src/ComputeSharp/Core/Primitives/Double/Double3.g.cs b/src/ComputeSharp.Core/Primitives/Double/Double3.g.cs similarity index 99% rename from src/ComputeSharp/Core/Primitives/Double/Double3.g.cs rename to src/ComputeSharp.Core/Primitives/Double/Double3.g.cs index b9eecdc9..6bad3710 100644 --- a/src/ComputeSharp/Core/Primitives/Double/Double3.g.cs +++ b/src/ComputeSharp.Core/Primitives/Double/Double3.g.cs @@ -3,8 +3,8 @@ using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if !NET6_0_OR_GREATER -using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; -using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal; +using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal; #endif #nullable enable diff --git a/src/ComputeSharp/Core/Primitives/Double/Double3.tt b/src/ComputeSharp.Core/Primitives/Double/Double3.tt similarity index 100% rename from src/ComputeSharp/Core/Primitives/Double/Double3.tt rename to src/ComputeSharp.Core/Primitives/Double/Double3.tt diff --git a/src/ComputeSharp/Core/Primitives/Double/Double4.cs b/src/ComputeSharp.Core/Primitives/Double/Double4.cs similarity index 100% rename from src/ComputeSharp/Core/Primitives/Double/Double4.cs rename to src/ComputeSharp.Core/Primitives/Double/Double4.cs diff --git a/src/ComputeSharp/Core/Primitives/Double/Double4.g.cs b/src/ComputeSharp.Core/Primitives/Double/Double4.g.cs similarity index 99% rename from src/ComputeSharp/Core/Primitives/Double/Double4.g.cs rename to src/ComputeSharp.Core/Primitives/Double/Double4.g.cs index 6b1a6b8e..47a8035a 100644 --- a/src/ComputeSharp/Core/Primitives/Double/Double4.g.cs +++ b/src/ComputeSharp.Core/Primitives/Double/Double4.g.cs @@ -3,8 +3,8 @@ using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if !NET6_0_OR_GREATER -using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; -using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal; +using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal; #endif #nullable enable diff --git a/src/ComputeSharp/Core/Primitives/Double/Double4.tt b/src/ComputeSharp.Core/Primitives/Double/Double4.tt similarity index 100% rename from src/ComputeSharp/Core/Primitives/Double/Double4.tt rename to src/ComputeSharp.Core/Primitives/Double/Double4.tt diff --git a/src/ComputeSharp/Core/Primitives/Double/DoubleMxN.g.cs b/src/ComputeSharp.Core/Primitives/Double/DoubleMxN.g.cs similarity index 99% rename from src/ComputeSharp/Core/Primitives/Double/DoubleMxN.g.cs rename to src/ComputeSharp.Core/Primitives/Double/DoubleMxN.g.cs index dfbca48e..0090b66a 100644 --- a/src/ComputeSharp/Core/Primitives/Double/DoubleMxN.g.cs +++ b/src/ComputeSharp.Core/Primitives/Double/DoubleMxN.g.cs @@ -1,8 +1,8 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if !NET6_0_OR_GREATER -using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; -using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal; +using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal; #endif namespace ComputeSharp; diff --git a/src/ComputeSharp/Core/Primitives/Double/DoubleMxN.tt b/src/ComputeSharp.Core/Primitives/Double/DoubleMxN.tt similarity index 100% rename from src/ComputeSharp/Core/Primitives/Double/DoubleMxN.tt rename to src/ComputeSharp.Core/Primitives/Double/DoubleMxN.tt diff --git a/src/ComputeSharp/Core/Primitives/Float/Float2.cs b/src/ComputeSharp.Core/Primitives/Float/Float2.cs similarity index 100% rename from src/ComputeSharp/Core/Primitives/Float/Float2.cs rename to src/ComputeSharp.Core/Primitives/Float/Float2.cs diff --git a/src/ComputeSharp/Core/Primitives/Float/Float2.g.cs b/src/ComputeSharp.Core/Primitives/Float/Float2.g.cs similarity index 99% rename from src/ComputeSharp/Core/Primitives/Float/Float2.g.cs rename to src/ComputeSharp.Core/Primitives/Float/Float2.g.cs index 0f398339..e1962a1a 100644 --- a/src/ComputeSharp/Core/Primitives/Float/Float2.g.cs +++ b/src/ComputeSharp.Core/Primitives/Float/Float2.g.cs @@ -3,8 +3,8 @@ using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if !NET6_0_OR_GREATER -using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; -using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal; +using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal; #endif #nullable enable diff --git a/src/ComputeSharp/Core/Primitives/Float/Float2.tt b/src/ComputeSharp.Core/Primitives/Float/Float2.tt similarity index 100% rename from src/ComputeSharp/Core/Primitives/Float/Float2.tt rename to src/ComputeSharp.Core/Primitives/Float/Float2.tt diff --git a/src/ComputeSharp/Core/Primitives/Float/Float3.cs b/src/ComputeSharp.Core/Primitives/Float/Float3.cs similarity index 100% rename from src/ComputeSharp/Core/Primitives/Float/Float3.cs rename to src/ComputeSharp.Core/Primitives/Float/Float3.cs diff --git a/src/ComputeSharp/Core/Primitives/Float/Float3.g.cs b/src/ComputeSharp.Core/Primitives/Float/Float3.g.cs similarity index 99% rename from src/ComputeSharp/Core/Primitives/Float/Float3.g.cs rename to src/ComputeSharp.Core/Primitives/Float/Float3.g.cs index 59c29513..22887d9d 100644 --- a/src/ComputeSharp/Core/Primitives/Float/Float3.g.cs +++ b/src/ComputeSharp.Core/Primitives/Float/Float3.g.cs @@ -3,8 +3,8 @@ using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if !NET6_0_OR_GREATER -using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; -using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal; +using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal; #endif #nullable enable diff --git a/src/ComputeSharp/Core/Primitives/Float/Float3.tt b/src/ComputeSharp.Core/Primitives/Float/Float3.tt similarity index 100% rename from src/ComputeSharp/Core/Primitives/Float/Float3.tt rename to src/ComputeSharp.Core/Primitives/Float/Float3.tt diff --git a/src/ComputeSharp/Core/Primitives/Float/Float4.cs b/src/ComputeSharp.Core/Primitives/Float/Float4.cs similarity index 100% rename from src/ComputeSharp/Core/Primitives/Float/Float4.cs rename to src/ComputeSharp.Core/Primitives/Float/Float4.cs diff --git a/src/ComputeSharp/Core/Primitives/Float/Float4.g.cs b/src/ComputeSharp.Core/Primitives/Float/Float4.g.cs similarity index 99% rename from src/ComputeSharp/Core/Primitives/Float/Float4.g.cs rename to src/ComputeSharp.Core/Primitives/Float/Float4.g.cs index 6f3f7a5a..c22bb7fe 100644 --- a/src/ComputeSharp/Core/Primitives/Float/Float4.g.cs +++ b/src/ComputeSharp.Core/Primitives/Float/Float4.g.cs @@ -3,8 +3,8 @@ using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if !NET6_0_OR_GREATER -using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; -using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal; +using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal; #endif #nullable enable diff --git a/src/ComputeSharp/Core/Primitives/Float/Float4.tt b/src/ComputeSharp.Core/Primitives/Float/Float4.tt similarity index 100% rename from src/ComputeSharp/Core/Primitives/Float/Float4.tt rename to src/ComputeSharp.Core/Primitives/Float/Float4.tt diff --git a/src/ComputeSharp/Core/Primitives/Float/FloatMxN.g.cs b/src/ComputeSharp.Core/Primitives/Float/FloatMxN.g.cs similarity index 99% rename from src/ComputeSharp/Core/Primitives/Float/FloatMxN.g.cs rename to src/ComputeSharp.Core/Primitives/Float/FloatMxN.g.cs index 6a838b30..54194c88 100644 --- a/src/ComputeSharp/Core/Primitives/Float/FloatMxN.g.cs +++ b/src/ComputeSharp.Core/Primitives/Float/FloatMxN.g.cs @@ -1,8 +1,8 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if !NET6_0_OR_GREATER -using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; -using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal; +using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal; #endif namespace ComputeSharp; diff --git a/src/ComputeSharp/Core/Primitives/Float/FloatMxN.tt b/src/ComputeSharp.Core/Primitives/Float/FloatMxN.tt similarity index 100% rename from src/ComputeSharp/Core/Primitives/Float/FloatMxN.tt rename to src/ComputeSharp.Core/Primitives/Float/FloatMxN.tt diff --git a/src/ComputeSharp/Core/Primitives/Int/Int2.cs b/src/ComputeSharp.Core/Primitives/Int/Int2.cs similarity index 100% rename from src/ComputeSharp/Core/Primitives/Int/Int2.cs rename to src/ComputeSharp.Core/Primitives/Int/Int2.cs diff --git a/src/ComputeSharp/Core/Primitives/Int/Int2.g.cs b/src/ComputeSharp.Core/Primitives/Int/Int2.g.cs similarity index 99% rename from src/ComputeSharp/Core/Primitives/Int/Int2.g.cs rename to src/ComputeSharp.Core/Primitives/Int/Int2.g.cs index 4ecee7dd..af6218ba 100644 --- a/src/ComputeSharp/Core/Primitives/Int/Int2.g.cs +++ b/src/ComputeSharp.Core/Primitives/Int/Int2.g.cs @@ -3,8 +3,8 @@ using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if !NET6_0_OR_GREATER -using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; -using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal; +using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal; #endif #nullable enable diff --git a/src/ComputeSharp/Core/Primitives/Int/Int2.tt b/src/ComputeSharp.Core/Primitives/Int/Int2.tt similarity index 100% rename from src/ComputeSharp/Core/Primitives/Int/Int2.tt rename to src/ComputeSharp.Core/Primitives/Int/Int2.tt diff --git a/src/ComputeSharp/Core/Primitives/Int/Int3.cs b/src/ComputeSharp.Core/Primitives/Int/Int3.cs similarity index 100% rename from src/ComputeSharp/Core/Primitives/Int/Int3.cs rename to src/ComputeSharp.Core/Primitives/Int/Int3.cs diff --git a/src/ComputeSharp/Core/Primitives/Int/Int3.g.cs b/src/ComputeSharp.Core/Primitives/Int/Int3.g.cs similarity index 99% rename from src/ComputeSharp/Core/Primitives/Int/Int3.g.cs rename to src/ComputeSharp.Core/Primitives/Int/Int3.g.cs index 40afd255..6b64d48c 100644 --- a/src/ComputeSharp/Core/Primitives/Int/Int3.g.cs +++ b/src/ComputeSharp.Core/Primitives/Int/Int3.g.cs @@ -3,8 +3,8 @@ using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if !NET6_0_OR_GREATER -using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; -using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal; +using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal; #endif #nullable enable diff --git a/src/ComputeSharp/Core/Primitives/Int/Int3.tt b/src/ComputeSharp.Core/Primitives/Int/Int3.tt similarity index 100% rename from src/ComputeSharp/Core/Primitives/Int/Int3.tt rename to src/ComputeSharp.Core/Primitives/Int/Int3.tt diff --git a/src/ComputeSharp/Core/Primitives/Int/Int4.cs b/src/ComputeSharp.Core/Primitives/Int/Int4.cs similarity index 100% rename from src/ComputeSharp/Core/Primitives/Int/Int4.cs rename to src/ComputeSharp.Core/Primitives/Int/Int4.cs diff --git a/src/ComputeSharp/Core/Primitives/Int/Int4.g.cs b/src/ComputeSharp.Core/Primitives/Int/Int4.g.cs similarity index 99% rename from src/ComputeSharp/Core/Primitives/Int/Int4.g.cs rename to src/ComputeSharp.Core/Primitives/Int/Int4.g.cs index a38f14a3..0189a123 100644 --- a/src/ComputeSharp/Core/Primitives/Int/Int4.g.cs +++ b/src/ComputeSharp.Core/Primitives/Int/Int4.g.cs @@ -3,8 +3,8 @@ using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if !NET6_0_OR_GREATER -using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; -using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal; +using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal; #endif #nullable enable diff --git a/src/ComputeSharp/Core/Primitives/Int/Int4.tt b/src/ComputeSharp.Core/Primitives/Int/Int4.tt similarity index 100% rename from src/ComputeSharp/Core/Primitives/Int/Int4.tt rename to src/ComputeSharp.Core/Primitives/Int/Int4.tt diff --git a/src/ComputeSharp/Core/Primitives/Int/IntMxN.g.cs b/src/ComputeSharp.Core/Primitives/Int/IntMxN.g.cs similarity index 99% rename from src/ComputeSharp/Core/Primitives/Int/IntMxN.g.cs rename to src/ComputeSharp.Core/Primitives/Int/IntMxN.g.cs index 5b48b091..7f37623c 100644 --- a/src/ComputeSharp/Core/Primitives/Int/IntMxN.g.cs +++ b/src/ComputeSharp.Core/Primitives/Int/IntMxN.g.cs @@ -1,8 +1,8 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if !NET6_0_OR_GREATER -using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; -using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal; +using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal; #endif namespace ComputeSharp; diff --git a/src/ComputeSharp/Core/Primitives/Int/IntMxN.tt b/src/ComputeSharp.Core/Primitives/Int/IntMxN.tt similarity index 100% rename from src/ComputeSharp/Core/Primitives/Int/IntMxN.tt rename to src/ComputeSharp.Core/Primitives/Int/IntMxN.tt diff --git a/src/ComputeSharp/Core/Primitives/MatrixIndex.cs b/src/ComputeSharp.Core/Primitives/MatrixIndex.cs similarity index 100% rename from src/ComputeSharp/Core/Primitives/MatrixIndex.cs rename to src/ComputeSharp.Core/Primitives/MatrixIndex.cs diff --git a/src/ComputeSharp/Core/Primitives/MatrixType.ttinclude b/src/ComputeSharp.Core/Primitives/MatrixType.ttinclude similarity index 98% rename from src/ComputeSharp/Core/Primitives/MatrixType.ttinclude rename to src/ComputeSharp.Core/Primitives/MatrixType.ttinclude index 01e662d5..e39de84a 100644 --- a/src/ComputeSharp/Core/Primitives/MatrixType.ttinclude +++ b/src/ComputeSharp.Core/Primitives/MatrixType.ttinclude @@ -13,8 +13,8 @@ void GenerateAllMatrixProperties(string typeName, int elementSize) using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if !NET6_0_OR_GREATER -using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; -using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal; +using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal; #endif namespace ComputeSharp; diff --git a/src/ComputeSharp/Core/Primitives/UInt/UInt2.cs b/src/ComputeSharp.Core/Primitives/UInt/UInt2.cs similarity index 100% rename from src/ComputeSharp/Core/Primitives/UInt/UInt2.cs rename to src/ComputeSharp.Core/Primitives/UInt/UInt2.cs diff --git a/src/ComputeSharp/Core/Primitives/UInt/UInt2.g.cs b/src/ComputeSharp.Core/Primitives/UInt/UInt2.g.cs similarity index 99% rename from src/ComputeSharp/Core/Primitives/UInt/UInt2.g.cs rename to src/ComputeSharp.Core/Primitives/UInt/UInt2.g.cs index b45dd25e..3de44ea2 100644 --- a/src/ComputeSharp/Core/Primitives/UInt/UInt2.g.cs +++ b/src/ComputeSharp.Core/Primitives/UInt/UInt2.g.cs @@ -3,8 +3,8 @@ using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if !NET6_0_OR_GREATER -using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; -using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal; +using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal; #endif #nullable enable diff --git a/src/ComputeSharp/Core/Primitives/UInt/UInt2.tt b/src/ComputeSharp.Core/Primitives/UInt/UInt2.tt similarity index 100% rename from src/ComputeSharp/Core/Primitives/UInt/UInt2.tt rename to src/ComputeSharp.Core/Primitives/UInt/UInt2.tt diff --git a/src/ComputeSharp/Core/Primitives/UInt/UInt3.cs b/src/ComputeSharp.Core/Primitives/UInt/UInt3.cs similarity index 100% rename from src/ComputeSharp/Core/Primitives/UInt/UInt3.cs rename to src/ComputeSharp.Core/Primitives/UInt/UInt3.cs diff --git a/src/ComputeSharp/Core/Primitives/UInt/UInt3.g.cs b/src/ComputeSharp.Core/Primitives/UInt/UInt3.g.cs similarity index 99% rename from src/ComputeSharp/Core/Primitives/UInt/UInt3.g.cs rename to src/ComputeSharp.Core/Primitives/UInt/UInt3.g.cs index 38114335..1a754e1a 100644 --- a/src/ComputeSharp/Core/Primitives/UInt/UInt3.g.cs +++ b/src/ComputeSharp.Core/Primitives/UInt/UInt3.g.cs @@ -3,8 +3,8 @@ using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if !NET6_0_OR_GREATER -using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; -using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal; +using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal; #endif #nullable enable diff --git a/src/ComputeSharp/Core/Primitives/UInt/UInt3.tt b/src/ComputeSharp.Core/Primitives/UInt/UInt3.tt similarity index 100% rename from src/ComputeSharp/Core/Primitives/UInt/UInt3.tt rename to src/ComputeSharp.Core/Primitives/UInt/UInt3.tt diff --git a/src/ComputeSharp/Core/Primitives/UInt/UInt4.cs b/src/ComputeSharp.Core/Primitives/UInt/UInt4.cs similarity index 100% rename from src/ComputeSharp/Core/Primitives/UInt/UInt4.cs rename to src/ComputeSharp.Core/Primitives/UInt/UInt4.cs diff --git a/src/ComputeSharp/Core/Primitives/UInt/UInt4.g.cs b/src/ComputeSharp.Core/Primitives/UInt/UInt4.g.cs similarity index 99% rename from src/ComputeSharp/Core/Primitives/UInt/UInt4.g.cs rename to src/ComputeSharp.Core/Primitives/UInt/UInt4.g.cs index 694718aa..e78eb14e 100644 --- a/src/ComputeSharp/Core/Primitives/UInt/UInt4.g.cs +++ b/src/ComputeSharp.Core/Primitives/UInt/UInt4.g.cs @@ -3,8 +3,8 @@ using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if !NET6_0_OR_GREATER -using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; -using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal; +using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal; #endif #nullable enable diff --git a/src/ComputeSharp/Core/Primitives/UInt/UInt4.tt b/src/ComputeSharp.Core/Primitives/UInt/UInt4.tt similarity index 100% rename from src/ComputeSharp/Core/Primitives/UInt/UInt4.tt rename to src/ComputeSharp.Core/Primitives/UInt/UInt4.tt diff --git a/src/ComputeSharp/Core/Primitives/UInt/UIntMxN.g.cs b/src/ComputeSharp.Core/Primitives/UInt/UIntMxN.g.cs similarity index 99% rename from src/ComputeSharp/Core/Primitives/UInt/UIntMxN.g.cs rename to src/ComputeSharp.Core/Primitives/UInt/UIntMxN.g.cs index b0359271..b2049e19 100644 --- a/src/ComputeSharp/Core/Primitives/UInt/UIntMxN.g.cs +++ b/src/ComputeSharp.Core/Primitives/UInt/UIntMxN.g.cs @@ -1,8 +1,8 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if !NET6_0_OR_GREATER -using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; -using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal; +using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal; #endif namespace ComputeSharp; diff --git a/src/ComputeSharp/Core/Primitives/UInt/UIntMxN.tt b/src/ComputeSharp.Core/Primitives/UInt/UIntMxN.tt similarity index 100% rename from src/ComputeSharp/Core/Primitives/UInt/UIntMxN.tt rename to src/ComputeSharp.Core/Primitives/UInt/UIntMxN.tt diff --git a/src/ComputeSharp/Core/Primitives/VectorType.ttinclude b/src/ComputeSharp.Core/Primitives/VectorType.ttinclude similarity index 98% rename from src/ComputeSharp/Core/Primitives/VectorType.ttinclude rename to src/ComputeSharp.Core/Primitives/VectorType.ttinclude index acf95d3b..de653781 100644 --- a/src/ComputeSharp/Core/Primitives/VectorType.ttinclude +++ b/src/ComputeSharp.Core/Primitives/VectorType.ttinclude @@ -61,8 +61,8 @@ void GenerateVectorProperties(string typeName, int elementSize) using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if !NET6_0_OR_GREATER -using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; -using MemoryMarshal = ComputeSharp.NetStandard.System.Runtime.InteropServices.MemoryMarshal; +using RuntimeHelpers = ComputeSharp.Core.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using MemoryMarshal = ComputeSharp.Core.NetStandard.System.Runtime.InteropServices.MemoryMarshal; #endif #nullable enable diff --git a/src/ComputeSharp.Core/Properties/AssemblyInfo.cs b/src/ComputeSharp.Core/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..0a698d43 --- /dev/null +++ b/src/ComputeSharp.Core/Properties/AssemblyInfo.cs @@ -0,0 +1,9 @@ +using System.Runtime.CompilerServices; + +[module: SkipLocalsInit] + +[assembly: InternalsVisibleTo("ComputeSharp")] +[assembly: InternalsVisibleTo("ComputeSharp.Dynamic")] +[assembly: InternalsVisibleTo("ComputeSharp.Uwp")] +[assembly: InternalsVisibleTo("ComputeSharp.WinUI")] +[assembly: InternalsVisibleTo("ComputeSharp.D2D1")] \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.NetStandard/ComputeSharp.D2D1.NetStandard.projitems b/src/ComputeSharp.D2D1.NetStandard/ComputeSharp.D2D1.NetStandard.projitems new file mode 100644 index 00000000..5e0080d3 --- /dev/null +++ b/src/ComputeSharp.D2D1.NetStandard/ComputeSharp.D2D1.NetStandard.projitems @@ -0,0 +1,21 @@ + + + + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) + true + 2608eb41-f98b-4be5-9f4d-68fed6115088 + + + ComputeSharp.D2D1.NetStandard + + + + + + + + + + + + \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.NetStandard/ComputeSharp.D2D1.NetStandard.shproj b/src/ComputeSharp.D2D1.NetStandard/ComputeSharp.D2D1.NetStandard.shproj new file mode 100644 index 00000000..78c7c427 --- /dev/null +++ b/src/ComputeSharp.D2D1.NetStandard/ComputeSharp.D2D1.NetStandard.shproj @@ -0,0 +1,13 @@ + + + + 2608eb41-f98b-4be5-9f4d-68fed6115088 + 14.0 + + + + + + + + diff --git a/src/ComputeSharp.D2D1.NetStandard/System/Buffers/BitOperations.cs b/src/ComputeSharp.D2D1.NetStandard/System/Buffers/BitOperations.cs new file mode 100644 index 00000000..a8f36d90 --- /dev/null +++ b/src/ComputeSharp.D2D1.NetStandard/System/Buffers/BitOperations.cs @@ -0,0 +1,32 @@ +using System.Runtime.CompilerServices; + +namespace ComputeSharp.D2D1.NetStandard.System.Buffers; + +/// +/// A polyfill type that mirrors some methods from on .NET 6. +/// +internal static class BitOperations +{ + /// + /// Rounds the given integral value up to a power of 2. + /// + /// The value. + /// + /// The smallest power of 2 which is greater than or equal to . + /// If is 0 or the result overflows, returns 0. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint RoundUpToPowerOf2(uint value) + { + // Based on https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 + --value; + + value |= value >> 1; + value |= value >> 2; + value |= value >> 4; + value |= value >> 8; + value |= value >> 16; + + return value + 1; + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.NetStandard/System/Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs b/src/ComputeSharp.D2D1.NetStandard/System/Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs new file mode 100644 index 00000000..1c6a222e --- /dev/null +++ b/src/ComputeSharp.D2D1.NetStandard/System/Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs @@ -0,0 +1,14 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Diagnostics.CodeAnalysis; + +/// +/// Applied to a method that will never return under any circumstance. +/// +/// Internal copy from the BCL attribute. +[AttributeUsage(AttributeTargets.Method, Inherited = false)] +internal sealed class DoesNotReturnAttribute : Attribute +{ +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.NetStandard/System/Math.cs b/src/ComputeSharp.D2D1.NetStandard/System/Math.cs new file mode 100644 index 00000000..7885d997 --- /dev/null +++ b/src/ComputeSharp.D2D1.NetStandard/System/Math.cs @@ -0,0 +1,46 @@ +using System.Runtime.CompilerServices; + +namespace ComputeSharp.D2D1.NetStandard.System; + +/// +/// A polyfill type that mirrors some methods from on .NET 6. +/// +internal static class Math +{ + /// + /// Returns clamped to the inclusive range of and . + /// + /// The value to be clamped. + /// The lower bound of the result. + /// The upper bound of the result. + /// The input value clamped to the inclusive range of and . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int Clamp(int value, int min, int max) + { + if (value < min) + { + return min; + } + + if (value > max) + { + return max; + } + + return value; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int Min(int val1, int val2) + { + return global::System.Math.Min(val1, val2); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int Max(int val1, int val2) + { + return global::System.Math.Max(val1, val2); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.NetStandard/System/Runtime/CompilerServices/RuntimeHelpers.cs b/src/ComputeSharp.D2D1.NetStandard/System/Runtime/CompilerServices/RuntimeHelpers.cs new file mode 100644 index 00000000..b7a2c4ee --- /dev/null +++ b/src/ComputeSharp.D2D1.NetStandard/System/Runtime/CompilerServices/RuntimeHelpers.cs @@ -0,0 +1,18 @@ +using System; +using System.Runtime.InteropServices; + +namespace ComputeSharp.D2D1.NetStandard.System.Runtime.CompilerServices; + +/// +/// A polyfill type that mirrors some methods from on .NET 5. +/// +internal static class RuntimeHelpers +{ + /// + /// Allocates some memory tied to the lifetime of a specific type. + /// + /// The type to associate the memory to. + /// The size in byte of the memory to allocate. + /// A pointer to the allocated memory. + public static IntPtr AllocateTypeAssociatedMemory(Type type, int size) => Marshal.AllocHGlobal(size); +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.NetStandard/System/Text/EncodingExtensions.cs b/src/ComputeSharp.D2D1.NetStandard/System/Text/EncodingExtensions.cs new file mode 100644 index 00000000..4f9f5f47 --- /dev/null +++ b/src/ComputeSharp.D2D1.NetStandard/System/Text/EncodingExtensions.cs @@ -0,0 +1,41 @@ +using System; +using System.Runtime.InteropServices; +using System.Text; + +namespace ComputeSharp.D2D1.NetStandard.System.Text; + +/// +/// A polyfill type that mirrors some methods from on .NET 5. +/// +internal static class EncodingExtensions +{ + /// + /// Encodes into a span of bytes a set of characters from the specified read-only span. + /// + /// The input instance to use. + /// The span containing the set of characters to encode. + /// The byte span to hold the encoded bytes. + /// The number of encoded bytes. + public static unsafe int GetBytes(this Encoding encoding, ReadOnlySpan chars, Span bytes) + { + fixed (char* charsPtr = &MemoryMarshal.GetReference(chars)) + fixed (byte* bytesPtr = &MemoryMarshal.GetReference(bytes)) + { + return encoding.GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length); + } + } + + /// + /// Decodes a text from a sequence of bytes. + /// + /// The input instance to use. + /// The byte span that holds the encoded bytes. + /// The resulting text. + public static unsafe string GetString(this Encoding encoding, ReadOnlySpan bytes) + { + fixed (byte* bytesPtr = &MemoryMarshal.GetReference(bytes)) + { + return encoding.GetString(bytesPtr, bytes.Length); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Package/ComputeSharp.D2D1.Package.msbuildproj b/src/ComputeSharp.D2D1.Package/ComputeSharp.D2D1.Package.msbuildproj new file mode 100644 index 00000000..2e056410 --- /dev/null +++ b/src/ComputeSharp.D2D1.Package/ComputeSharp.D2D1.Package.msbuildproj @@ -0,0 +1,28 @@ + + + + net6.0 + + + + ComputeSharp.D2D1 + ComputeSharp.D2D1 + A library to write D2D1 pixel shaders entirely with C# code, and to easily register and create ID2D1Effect-s from them + + + + + + + + + + + PackageVersion=$(PackageVersion) + + + PackageVersion=$(PackageVersion) + + + + \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md new file mode 100644 index 00000000..6cbb9ede --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md @@ -0,0 +1,50 @@ +; Shipped analyzer releases +; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md + +## Release 1.0 + +### New Rules + +Rule ID | Category | Severity | Notes +--------|----------|----------|------- +CMPSD2D0001 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0002 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0003 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0004 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0005 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0006 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0007 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0008 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0009 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0010 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0011 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0012 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0013 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0014 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0015 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0016 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0017 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0018 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0019 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0020 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0021 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0022 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0023 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0024 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0025 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0026 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0027 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0028 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0029 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0030 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0031 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0032 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0033 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0034 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0035 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0036 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0037 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0038 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0039 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0040 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0041 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Unshipped.md b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Unshipped.md new file mode 100644 index 00000000..6a6dd08d --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Unshipped.md @@ -0,0 +1,2 @@ +; Unshipped analyzer release +; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj b/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj new file mode 100644 index 00000000..095fcb7d --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj @@ -0,0 +1,104 @@ + + + + netstandard2.0 + false + ComputeSharp.D2D1.SourceGenerators + $(NoWarn);CS1591;CS0649;CS1574 + + + + $(DefineConstants);SOURCE_GENERATOR + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs new file mode 100644 index 00000000..9d65598d --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -0,0 +1,586 @@ +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.D2D1.SourceGenerators.Diagnostics; + +#pragma warning disable IDE0090 // Use 'new(...)' + +/// +/// A container for all instances for errors reported by analyzers in this project. +/// +internal static class DiagnosticDescriptors +{ + /// + /// Gets a for an invalid shader field. + /// + /// Format: "The compute shader of type {0} contains a field \"{1}\" of an invalid type {2}". + /// + /// + public static readonly DiagnosticDescriptor InvalidShaderField = new DiagnosticDescriptor( + id: "CMPSD2D0001", + title: "Invalid shader field", + messageFormat: "The compute shader of type {0} contains a field \"{1}\" of an invalid type {2}", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A type representing a compute shader contains a field of a type that is not supported in HLSL.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an invalid object creation expression. + /// + /// Format: "The type {0} cannot be created in a compute shader". + /// + /// + public static readonly DiagnosticDescriptor InvalidObjectCreationExpression = new DiagnosticDescriptor( + id: "CMPSD2D0002", + title: "Invalid object creation expression", + messageFormat: "The type {0} cannot be created in a compute shader (only unmanaged types are supported)", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "Only unmanaged value type objects can be created in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an anonymous object creation expression. + /// + public static readonly DiagnosticDescriptor AnonymousObjectCreationExpression = new DiagnosticDescriptor( + id: "CMPSD2D0003", + title: "Anonymous object creation expression", + messageFormat: "An anonymous object cannot be created in a compute shader", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "An anonymous object cannot be created in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an async modifier on a method or function. + /// + public static readonly DiagnosticDescriptor AsyncModifierOnMethodOrFunction = new DiagnosticDescriptor( + id: "CMPSD2D0004", + title: "Async modifier on method or function", + messageFormat: "The async modifier cannot be used in methods or functions used in a compute shader", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "The async modifier cannot be used in methods or functions used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an await expression. + /// + public static readonly DiagnosticDescriptor AwaitExpression = new DiagnosticDescriptor( + id: "CMPSD2D0005", + title: "Await expression", + messageFormat: "The await expression cannot be used in a compute shader", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "The await expression cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a checked expression. + /// + public static readonly DiagnosticDescriptor CheckedExpression = new DiagnosticDescriptor( + id: "CMPSD2D0006", + title: "Checked expression", + messageFormat: "A checked expression cannot be used in a compute shader", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A checked expression cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a checked statement. + /// + public static readonly DiagnosticDescriptor CheckedStatement = new DiagnosticDescriptor( + id: "CMPSD2D0007", + title: "Checked statement", + messageFormat: "A checked statement cannot be used in a compute shader", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A checked statement cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a fixed statement. + /// + public static readonly DiagnosticDescriptor FixedStatement = new DiagnosticDescriptor( + id: "CMPSD2D0008", + title: "Fixed statement", + messageFormat: "A fixed statement cannot be used in a compute shader", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A fixed statement cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a foreach statement. + /// + public static readonly DiagnosticDescriptor ForEachStatement = new DiagnosticDescriptor( + id: "CMPSD2D0009", + title: "Foreach statement", + messageFormat: "A foreach statement cannot be used in a compute shader", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A foreach statement cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a lock statement. + /// + public static readonly DiagnosticDescriptor LockStatement = new DiagnosticDescriptor( + id: "CMPSD2D0010", + title: "Foreach statement", + messageFormat: "A lock statement cannot be used in a compute shader", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A lock statement cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a query statement. + /// + public static readonly DiagnosticDescriptor QueryExpression = new DiagnosticDescriptor( + id: "CMPSD2D0011", + title: "Foreach statement", + messageFormat: "A LINQ query expression cannot be used in a compute shader", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A LINQ query expression cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a range expression. + /// + public static readonly DiagnosticDescriptor RangeExpression = new DiagnosticDescriptor( + id: "CMPSD2D0012", + title: "Range expression", + messageFormat: "A range expression cannot be used in a compute shader", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A range expression cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a recursive pattern. + /// + public static readonly DiagnosticDescriptor RecursivePattern = new DiagnosticDescriptor( + id: "CMPSD2D0013", + title: "Recursive pattern", + messageFormat: "A recursive pattern cannot be used in a compute shader", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A recursive pattern cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a ref type. + /// + public static readonly DiagnosticDescriptor RefType = new DiagnosticDescriptor( + id: "CMPSD2D0014", + title: "Ref type", + messageFormat: "A compute shader cannot have a ref type declaration", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A compute shader cannot have a ref type declaration.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a relational pattern. + /// + public static readonly DiagnosticDescriptor RelationalPattern = new DiagnosticDescriptor( + id: "CMPSD2D0015", + title: "Relational pattern", + messageFormat: "A relational pattern cannot be used in a compute shader", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A relational pattern cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a sizeof expression. + /// + public static readonly DiagnosticDescriptor SizeOfExpression = new DiagnosticDescriptor( + id: "CMPSD2D0016", + title: "Sizeof expression", + messageFormat: "A sizeof expression cannot be used in a compute shader", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A sizeof expression cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a stackalloc expression. + /// + public static readonly DiagnosticDescriptor StackAllocArrayCreationExpression = new DiagnosticDescriptor( + id: "CMPSD2D0017", + title: "Stackalloc expression", + messageFormat: "A stackalloc expression cannot be used in a compute shader", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A stackalloc expression cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a throw expression or statement. + /// + public static readonly DiagnosticDescriptor ThrowExpressionOrStatement = new DiagnosticDescriptor( + id: "CMPSD2D0018", + title: "Throw expression or statement", + messageFormat: "Throw expressions and statements cannot be used in a compute shader", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "Throw expressions and statements cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a try statement. + /// + public static readonly DiagnosticDescriptor TryStatement = new DiagnosticDescriptor( + id: "CMPSD2D0019", + title: "Try statement", + messageFormat: "A try statement cannot be used in a compute shader", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A try statement cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a tuple type. + /// + public static readonly DiagnosticDescriptor TupleType = new DiagnosticDescriptor( + id: "CMPSD2D0020", + title: "Tuple type", + messageFormat: "A compute shader cannot have a tuple type declaration", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A compute shader cannot have a tuple type declaration.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a using statement or declaration. + /// + public static readonly DiagnosticDescriptor UsingStatementOrDeclaration = new DiagnosticDescriptor( + id: "CMPSD2D0021", + title: "Using statement or declaration", + messageFormat: "Using statements and declarations cannot be used in a compute shader", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "Using statements and declarations cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a yield statement. + /// + public static readonly DiagnosticDescriptor YieldStatement = new DiagnosticDescriptor( + id: "CMPSD2D0022", + title: "Yield statement", + messageFormat: "A yield statement cannot be used in a compute shader", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A yield statement cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an invalid object declaration. + /// + /// Format: "A variable of type {0} cannot be declared in a compute shader". + /// + /// + public static readonly DiagnosticDescriptor InvalidObjectDeclaration = new DiagnosticDescriptor( + id: "CMPSD2D0023", + title: "Invalid object declaration", + messageFormat: "A variable of type {0} cannot be declared in a compute shader (only unmanaged types are supported)", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "Only unmanaged value type objects can be declared in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a pointer type. + /// + public static readonly DiagnosticDescriptor PointerType = new DiagnosticDescriptor( + id: "CMPSD2D0024", + title: "Pointer type", + messageFormat: "A compute shader cannot have a pointer type declaration", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A compute shader cannot have a pointer type declaration.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a function pointer type. + /// + public static readonly DiagnosticDescriptor FunctionPointer = new DiagnosticDescriptor( + id: "CMPSD2D0025", + title: "Function pointer type", + messageFormat: "A compute shader cannot have a function pointer type declaration", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A compute shader cannot have a function pointer type declaration.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an unsafe statement. + /// + public static readonly DiagnosticDescriptor UnsafeStatement = new DiagnosticDescriptor( + id: "CMPSD2D0026", + title: "Unsafe statement", + messageFormat: "A compute shader cannot have an unsafe statement", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A compute shader cannot have an unsafe statement.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an unsafe modifier on a method or function. + /// + public static readonly DiagnosticDescriptor UnsafeModifierOnMethodOrFunction = new DiagnosticDescriptor( + id: "CMPSD2D0027", + title: "Unsafe modifier on method or function", + messageFormat: "The unsafe modifier cannot be used in methods or functions used in a compute shader", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "The unsafe modifier cannot be used in methods or functions used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a string literal. + /// + public static readonly DiagnosticDescriptor StringLiteralExpression = new DiagnosticDescriptor( + id: "CMPSD2D0028", + title: "String literal expression", + messageFormat: "String literal expressions cannot be used in a compute shader", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "String literal expressions cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an incorrect matrix swizzling property argument. + /// + public static readonly DiagnosticDescriptor NonConstantMatrixSwizzledIndex = new DiagnosticDescriptor( + id: "CMPSD2D0029", + title: "Non constant matrix swizzled property argument", + messageFormat: "The arguments in a swizzled indexer for a matrix type must be compile-time constants", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "The arguments in a swizzled indexer for a matrix type must be compile-time constants.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an invalid shader static readonly field type. + /// + /// Format: "The compute shader of type {0} contains a static readonly field \"{1}\" of an invalid type {2} (only primitive, vector and matrix types are supported)". + /// + /// + public static readonly DiagnosticDescriptor InvalidShaderStaticFieldType = new DiagnosticDescriptor( + id: "CMPSD2D0030", + title: "Invalid shader static readonly field type", + messageFormat: "The compute shader of type {0} contains a static readonly field \"{1}\" of an invalid type {2} (only primitive, vector and matrix types are supported)", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A type representing a compute shader contains a static readonly field of a type that is not supported.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a property declaration. + /// + public static readonly DiagnosticDescriptor PropertyDeclaration = new DiagnosticDescriptor( + id: "CMPSD2D0031", + title: "Property declaration", + messageFormat: "Property declarations cannot be used in a compute shader", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "Property declarations cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a shader with a root signature that is too large. + /// + /// Format: "The compute shader of type {0} has exceeded the maximum allowed size for captured values and resources". + /// + /// + public static readonly DiagnosticDescriptor ShaderDispatchDataSizeExceeded = new DiagnosticDescriptor( + id: "CMPSD2D0032", + title: "Shader dispatch data size exceeded", + messageFormat: "The compute shader of type {0} has exceeded the maximum allowed size for captured values and resources", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "The compute shader of type {0} has exceeded the maximum allowed size for captured values and resources.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an embedded bytecode shader failed due to a Win32 exception. + /// + /// Format: "The shader of type {0} failed to compile due to a Win32 exception (HRESULT: {1:X8}, Message: "{2}")". + /// + /// + public static readonly DiagnosticDescriptor EmbeddedBytecodeFailedWithWin32Exception = new DiagnosticDescriptor( + id: "CMPSD2D0033", + title: "Embedded bytecode compilation failed due to Win32 exception", + messageFormat: "The shader of type {0} failed to compile due to a Win32 exception (HRESULT: {1:X8}, Message: \"{2}\")", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "The embedded bytecode for a shader failed to be compiled due to a Win32 exception.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an embedded bytecode shader failed due to an HLSL compilation exception. + /// + /// Format: "The shader of type {0} failed to compile due to an HLSL compiler error (Message: "{1}")". + /// + /// + public static readonly DiagnosticDescriptor EmbeddedBytecodeFailedWithDxcCompilationException = new DiagnosticDescriptor( + id: "CMPSD2D0034", + title: "Embedded bytecode compilation failed due to an HLSL compiler error", + messageFormat: "The shader of type {0} failed to compile due to an HLSL compiler error (Message: \"{1}\")", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "The embedded bytecode for a shader failed to be compiled due to an HLSL compiler error.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a invalid D2D input count value. + /// + /// Format: "The D2D1 shader of type {0} is using an incorrect value for [D2DInputCount] (the number of inputs must be in the [0, 8] range)". + /// + /// + public static readonly DiagnosticDescriptor InvalidD2DInputCount = new DiagnosticDescriptor( + id: "CMPSD2D0035", + title: "Invalid D2D1 shader input count", + messageFormat: "The D2D1 shader of type {0} is using an incorrect value for [D2DInputCount] (the number of inputs must be in the [0, 8] range)", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A D2D1 shader must have a number of inputs in the [1, 8] range.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for repeated indices for D2D simple indices. + /// + /// Format: "The D2D1 shader of type {0} is using repeated indices for some of its [D2DInputSimple] attributes". + /// + /// + public static readonly DiagnosticDescriptor RepeatedD2DInputSimpleIndices = new DiagnosticDescriptor( + id: "CMPSD2D0036", + title: "Repeated D2D1 shader simple input indices", + messageFormat: "The D2D1 shader of type {0} is using repeated indices for some of its [D2DInputSimple] attributes", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A D2D1 shader must only have unique indices for all of its [D2DInputSimple] attributes.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for repeated indices for D2D complex indices. + /// + /// Format: "The D2D1 shader of type {0} is using repeated indices for some of its [D2DInputComplex] attributes". + /// + /// + public static readonly DiagnosticDescriptor RepeatedD2DInputComplexIndices = new DiagnosticDescriptor( + id: "CMPSD2D0037", + title: "Repeated D2D1 shader complex input indices", + messageFormat: "The D2D1 shader of type {0} is using repeated indices for some of its [D2DInputComplex] attributes", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A D2D1 shader must only have unique indices for all of its [D2DInputComplex] attributes.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for invalid combination of simple and complex indices. + /// + /// Format: "The D2D1 shader of type {0} is using some indices in common for simple and complex input indices". + /// + /// + public static readonly DiagnosticDescriptor InvalidSimpleAndComplexIndicesCombination = new DiagnosticDescriptor( + id: "CMPSD2D0038", + title: "Invalid D2D1 shader simple and complex indices combination", + messageFormat: "The D2D1 shader of type {0} is using some indices in common for simple and complex input indices", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A D2D1 shader cannot use the same indices to indicate both simple and complex inputs.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a shader with an out of range input index (or more). + /// + /// Format: "The D2D1 shader of type {0} is using some out of range input indices". + /// + /// + public static readonly DiagnosticDescriptor OutOfRangeInputIndex = new DiagnosticDescriptor( + id: "CMPSD2D0039", + title: "Our of range D2D1 shader input indices", + messageFormat: "The D2D1 shader of type {0} is using some out of range input indices", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A D2D1 shader must have all the indices of its simple and complex inputs in the valid range (between 0 and the number of declared inputs).", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a method invocation that is not valid from a shader. + /// + /// Format: "The method {0} cannot be used in a D2D1 shader (methods need to either be HLSL intrinsics or with source available for analysis)". + /// + /// + public static readonly DiagnosticDescriptor InvalidMethodCall = new DiagnosticDescriptor( + id: "CMPSD2D0040", + title: "Invalid method invocation from a D2D1 shader", + messageFormat: "The method {0} cannot be used in a D2D1 shader (methods need to either be HLSL intrinsics or with source available for analysis)", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A D2D1 shader can only invoke methods that are either HLSL intrinsics or with source available for analysis.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an invalid discovered type. + /// + /// Format: "The D2D1 shader of type {0} uses the invalid type {1}". + /// + /// + public static readonly DiagnosticDescriptor InvalidDiscoveredType = new DiagnosticDescriptor( + id: "CMPSD2D0041", + title: "Invalid discovered type", + messageFormat: "The D2D1 shader of type {0} uses the invalid type {1} (only some .NET primitives and vector types, HLSL primitive, vector and matrix types, and custom types containing these types can be used)", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "D2D1 shaders can only use supported types (some .NET primitives and vector types, HLSL primitive, vector and matrix types, and custom types containing these types can be used).", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs new file mode 100644 index 00000000..9676c21f --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs @@ -0,0 +1,42 @@ +using ComputeSharp.D2D1.__Internals; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +partial class ID2D1ShaderGenerator +{ + /// + partial class BuildHlslSource + { + /// + /// Creates a instance for the BuildHlslSource method. + /// + /// The input HLSL source. + /// The resulting instance for the BuildHlslSource method. + public static MethodDeclarationSyntax GetSyntax(string hlslSource) + { + // This code produces a method declaration as follows: + // + // readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.BuildHlslSource(out string hlslSource) + // { + // hlslSource = ; + // } + return + MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("BuildHlslSource")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .AddParameterListParameters( + Parameter(Identifier("hlslSource")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(PredefinedType(Token(SyntaxKind.StringKeyword)))) + .WithBody(Block(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + IdentifierName("hlslSource"), + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(hlslSource)))))); + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs new file mode 100644 index 00000000..f68e444d --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs @@ -0,0 +1,608 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Text; +using ComputeSharp.D2D1.SourceGenerators.Diagnostics; +using ComputeSharp.D2D1.SourceGenerators.SyntaxRewriters; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Mappings; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618, RS1024 + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +partial class ID2D1ShaderGenerator +{ + /// + /// A helper with all logic to generate the BuildHlslSource method. + /// + internal static partial class BuildHlslSource + { + /// + /// Gathers all necessary information on a transpiled HLSL source for a given shader type. + /// + /// The input object currently in use. + /// The node to process. + /// The for . + /// The number of inputs for the shader. + /// The resulting diagnostics from the processing operation. + /// The HLSL source for the shader. + public static string GetHlslSource( + Compilation compilation, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + out int inputCount, + out ImmutableArray diagnostics) + { + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + + // Properties are not supported + DetectAndReportPropertyDeclarations(builder, structDeclarationSymbol); + + // We need to sets to track all discovered custom types and static methods + HashSet discoveredTypes = new(SymbolEqualityComparer.Default); + Dictionary staticMethods = new(SymbolEqualityComparer.Default); + Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); + + // Explore the syntax tree and extract the processed info + var semanticModelProvider = new SemanticModelProvider(compilation); + var valueFields = GetInstanceFields(builder, structDeclarationSymbol, discoveredTypes); + var (entryPoint, processedMethods) = GetProcessedMethods(builder, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions); + var declaredTypes = GetDeclaredTypes(builder, structDeclarationSymbol, discoveredTypes); + var definedConstants = GetDefinedConstants(constantDefinitions); + var staticFields = GetStaticFields(builder, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); + + // Gather the shader metadata + GatherD2D1AttributeInfo( + builder, + structDeclarationSymbol, + out inputCount, + out ImmutableArray inputSimpleIndices, + out ImmutableArray inputComplexIndices, + out bool requiresScenePosition); + + diagnostics = builder.ToImmutable(); + + // Get the HLSL source + return GetHlslSource( + definedConstants, + declaredTypes, + valueFields, + staticFields, + processedMethods, + entryPoint, + inputCount, + inputSimpleIndices, + inputComplexIndices, + requiresScenePosition); + } + + /// + /// Gets a sequence of captured fields and their mapped names. + /// + /// The collection of produced instances. + /// The input instance to process. + /// The collection of currently discovered types. + /// A sequence of captured fields in . + private static ImmutableArray<(string Name, string HlslType)> GetInstanceFields( + ImmutableArray.Builder diagnostics, + INamedTypeSymbol structDeclarationSymbol, + ICollection types) + { + ImmutableArray<(string, string)>.Builder values = ImmutableArray.CreateBuilder<(string, string)>(); + + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + { + if (fieldSymbol.IsStatic) + { + continue; + } + + // Captured fields must be named type symbols + if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol) + { + diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + string metadataName = typeSymbol.GetFullMetadataName(); + string typeName = HlslKnownTypes.GetMappedName(typeSymbol); + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + // Allowed fields must be unmanaged values + if (typeSymbol.IsUnmanagedType) + { + // Track the type if it's a custom struct + if (!HlslKnownTypes.IsKnownHlslType(metadataName)) + { + types.Add(typeSymbol); + } + + values.Add((mapping ?? fieldSymbol.Name, typeName)); + } + else + { + diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol); + } + } + + return values.ToImmutable(); + } + + /// + /// Gets a sequence of shader static fields and their mapped names. + /// + /// The collection of produced instances. + /// The instance for the type to process. + /// The instance for the current type. + /// The type symbol for the shader type. + /// The collection of currently discovered types. + /// The collection of discovered constant definitions. + /// A sequence of static constant fields in . + private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields( + ImmutableArray.Builder diagnostics, + SemanticModelProvider semanticModel, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + ICollection discoveredTypes, + IDictionary constantDefinitions) + { + ImmutableArray<(string, string, string?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, string?)>(); + + foreach (var fieldDeclaration in structDeclaration.Members.OfType()) + { + foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables) + { + IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.For(variableDeclarator).GetDeclaredSymbol(variableDeclarator)!; + + if (!fieldSymbol.IsStatic || fieldSymbol.IsConst) + { + continue; + } + + // Constant properties must be of a primitive, vector or matrix type + if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol || + !HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullMetadataName())) + { + diagnostics.Add(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + string typeDeclaration = fieldSymbol.IsReadOnly switch + { + true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}", + false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}" + }; + + StaticFieldRewriter staticFieldRewriter = new( + semanticModel, + discoveredTypes, + constantDefinitions, + diagnostics); + + string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace(eol: "\n").ToFullString(); + + builder.Add((mapping ?? fieldSymbol.Name, typeDeclaration, assignment)); + } + } + + return builder.ToImmutable(); + } + + /// + /// Gets a sequence of processed methods declared within a given type. + /// + /// The collection of produced instances. + /// The type symbol for the shader type. + /// The instance for the current type. + /// The instance for the type to process. + /// The collection of currently discovered types. + /// The set of discovered and processed static methods. + /// The collection of discovered constant definitions. + /// A sequence of processed methods in , and the entry point. + private static (string EntryPoint, ImmutableArray<(string Signature, string Definition)> Methods) GetProcessedMethods( + ImmutableArray.Builder diagnostics, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary staticMethods, + IDictionary constantDefinitions) + { + // Find all declared methods in the type + ImmutableArray methodDeclarations = ( + from syntaxNode in structDeclaration.DescendantNodes() + where syntaxNode.IsKind(SyntaxKind.MethodDeclaration) + select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray(); + + string? entryPoint = null; + ImmutableArray<(string, string)>.Builder methods = ImmutableArray.CreateBuilder<(string, string)>(); + + foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) + { + IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!; + bool isShaderEntryPoint = + methodDeclarationSymbol.Name == nameof(ID2D1PixelShader.Execute) && + methodDeclarationSymbol.ReturnType is not null && // TODO: match for pixel type + methodDeclarationSymbol.TypeParameters.Length == 0 && + methodDeclarationSymbol.Parameters.Length == 0; + + // Create the source rewriter for the current method + ShaderSourceRewriter shaderSourceRewriter = new( + structDeclarationSymbol, + semanticModel, + discoveredTypes, + staticMethods, + constantDefinitions, + diagnostics); + + // Rewrite the method syntax tree + MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); + + // Emit the extracted local functions first + foreach (var localFunction in shaderSourceRewriter.LocalFunctions) + { + methods.Add(( + localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString())); + } + + // If the method is the shader entry point, do additional processing + if (isShaderEntryPoint) + { + string entryPointDeclaration = processedMethod.NormalizeWhitespace(eol: "\n").ToFullString(); + string adjustedEntryPointDeclaration = entryPointDeclaration.Replace("float4 Execute()", "D2D_PS_ENTRY(Execute)"); + + entryPoint = adjustedEntryPointDeclaration; + } + else + { + methods.Add(( + processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + processedMethod.NormalizeWhitespace(eol: "\n").ToFullString())); + } + } + + // Process static methods as well + foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values) + { + methods.Add(( + staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + staticMethod.NormalizeWhitespace(eol: "\n").ToFullString())); + } + + return (entryPoint!, methods.ToImmutable()); + } + + /// + /// Gets a sequence of discovered constants. + /// + /// The collection of discovered constant definitions. + /// A sequence of discovered constants to declare in the shader. + private static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary constantDefinitions) + { + ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(constantDefinitions.Count); + + foreach (var constant in constantDefinitions) + { + var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); + var constantName = $"__{ownerTypeName}__{constant.Key.Name}"; + + builder.Add((constantName, constant.Value)); + } + + return builder.MoveToImmutable(); + } + + /// + /// Gets the sequence of processed discovered custom types. + /// + /// The collection of produced instances. + /// The type symbol for the shader type. + /// The sequence of discovered custom types. + /// A sequence of custom type definitions to add to the shader source. + private static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes( + ImmutableArray.Builder diagnostics, + INamedTypeSymbol structDeclarationSymbol, + IEnumerable types) + { + ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(); + IReadOnlyCollection invalidTypes; + + // Process the discovered types + foreach (var type in HlslKnownTypes.GetCustomTypes(types, out invalidTypes)) + { + var structType = type.GetFullMetadataName().ToHlslIdentifierName(); + var structDeclaration = StructDeclaration(structType); + + // Declare the fields of the current type + foreach (var field in type.GetMembers().OfType()) + { + if (field.IsStatic) continue; + + INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type; + + // Convert the name to the fully qualified HLSL version + if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullMetadataName(), out string? mapped)) + { + mapped = fieldType.GetFullMetadataName().ToHlslIdentifierName(); + } + + structDeclaration = structDeclaration.AddMembers( + FieldDeclaration(VariableDeclaration( + IdentifierName(mapped!)).AddVariables( + VariableDeclarator(Identifier(field.Name))))); + } + + // Insert the trailing ; right after the closing bracket (after normalization) + builder.Add(( + structType, + structDeclaration + .NormalizeWhitespace(eol: "\n") + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) + .ToFullString())); + } + + // Process the invalid types + foreach (INamedTypeSymbol invalidType in invalidTypes) + { + diagnostics.Add(InvalidDiscoveredType, structDeclarationSymbol, structDeclarationSymbol, invalidType); + } + + return builder.ToImmutable(); + } + + /// + /// Finds and reports all declared properties in a shader. + /// + /// The collection of produced instances. + /// The input instance to process. + private static void DetectAndReportPropertyDeclarations(ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol) + { + foreach (var propertySymbol in structDeclarationSymbol.GetMembers().OfType()) + { + diagnostics.Add(DiagnosticDescriptors.PropertyDeclaration, propertySymbol); + } + } + + /// + /// Extracts the metadata definition for the current shader. + /// + /// The collection of produced instances. + /// The input instance to process. + /// The number of shader inputs to declare. + /// The indicess of the simple shader inputs. + /// The indicess of the complex shader inputs. + /// Whether the shader requires the scene position. + private static void GatherD2D1AttributeInfo( + ImmutableArray.Builder diagnostics, + INamedTypeSymbol structDeclarationSymbol, + out int inputCount, + out ImmutableArray inputSimpleIndices, + out ImmutableArray inputComplexIndices, + out bool requiresScenePosition) + { + // We need a separate local here so we can keep the original value to apply + // diagnostics to, but without returning invalid values to the caller which + // might cause generator errors (eg. -1 would cause other code to just throw). + int rawInputCount = 0; + + inputCount = 0; + requiresScenePosition = false; + + ImmutableArray.Builder inputSimpleIndicesBuilder = ImmutableArray.CreateBuilder(); + ImmutableArray.Builder inputComplexIndicesBuilder = ImmutableArray.CreateBuilder(); + + foreach (AttributeData attributeData in structDeclarationSymbol.GetAttributes()) + { + switch (attributeData.AttributeClass?.GetFullMetadataName()) + { + case "ComputeSharp.D2D1.D2DInputCountAttribute": + rawInputCount = (int)attributeData.ConstructorArguments[0].Value!; + inputCount = Math.Max(rawInputCount, 0); + break; + case "ComputeSharp.D2D1.D2DInputSimpleAttribute": + inputSimpleIndicesBuilder.Add((int)attributeData.ConstructorArguments[0].Value!); + break; + case "ComputeSharp.D2D1.D2DInputComplexAttribute": + inputComplexIndicesBuilder.Add((int)attributeData.ConstructorArguments[0].Value!); + break; + case "ComputeSharp.D2D1.D2DRequiresScenePositionAttribute": + requiresScenePosition = true; + break; + default: + break; + } + } + + inputSimpleIndices = inputSimpleIndicesBuilder.ToImmutable(); + inputComplexIndices = inputComplexIndicesBuilder.ToImmutable(); + + // Validate the input count + if (rawInputCount is not (>= 0 and <= 8)) + { + diagnostics.Add(InvalidD2DInputCount, structDeclarationSymbol, structDeclarationSymbol); + + return; + } + + // All simple indices must be in range + if (inputSimpleIndicesBuilder.Concat(inputComplexIndicesBuilder).Any(i => (uint)i >= rawInputCount)) + { + diagnostics.Add(OutOfRangeInputIndex, structDeclarationSymbol, structDeclarationSymbol); + + return; + } + + HashSet inputSimpleIndicesAsSet = new(inputSimpleIndicesBuilder); + HashSet inputComplexIndicesAsSet = new(inputComplexIndicesBuilder); + + // All simple indices must be unique + if (inputSimpleIndicesAsSet.Count != inputSimpleIndicesBuilder.Count) + { + diagnostics.Add(RepeatedD2DInputSimpleIndices, structDeclarationSymbol, structDeclarationSymbol); + + return; + } + + // All complex indices must be unique + if (inputComplexIndicesAsSet.Count != inputComplexIndicesBuilder.Count) + { + diagnostics.Add(RepeatedD2DInputComplexIndices, structDeclarationSymbol, structDeclarationSymbol); + + return; + } + + // Simple and complex indices can't have indices in common + if (inputSimpleIndicesAsSet.Intersect(inputComplexIndicesAsSet).Any()) + { + diagnostics.Add(InvalidSimpleAndComplexIndicesCombination, structDeclarationSymbol, structDeclarationSymbol); + + return; + } + } + + /// + /// Produces the series of statements to build the current HLSL source. + /// + /// The sequence of defined constants for the shader. + /// The sequence of declared types used by the shader. + /// The sequence of value instance fields for the current shader. + /// The sequence of static fields referenced by the shader. + /// The sequence of processed methods used by the shader. + /// The body of the entry point of the shader. + /// The number of shader inputs to declare. + /// The indicess of the simple shader inputs. + /// The indicess of the complex shader inputs. + /// Whether the shader requires the scene position. + /// The series of statements to build the HLSL source to compile to execute the current shader. + private static string GetHlslSource( + ImmutableArray<(string Name, string Value)> definedConstants, + ImmutableArray<(string Name, string Definition)> declaredTypes, + ImmutableArray<(string Name, string HlslType)> valueFields, + ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields, + ImmutableArray<(string Signature, string Definition)> processedMethods, + string executeMethod, + int inputCount, + ImmutableArray inputSimpleIndices, + ImmutableArray inputComplexIndices, + bool requiresScenePosition) + { + StringBuilder hlslBuilder = new(); + + void AppendLF() + { + hlslBuilder.Append('\n'); + } + + void AppendLineAndLF(string text) + { + hlslBuilder.Append(text); + hlslBuilder.Append('\n'); + } + + // Header + AppendLineAndLF("// ================================================"); + AppendLineAndLF("// AUTO GENERATED"); + AppendLineAndLF("// ================================================"); + AppendLineAndLF("// This shader was created by ComputeSharp."); + AppendLineAndLF("// See: https://github.com/Sergio0694/ComputeSharp."); + AppendLF(); + + // Shader metadata + AppendLineAndLF($"#define D2D_INPUT_COUNT {inputCount}"); + + foreach (int simpleInput in inputSimpleIndices) + { + AppendLineAndLF($"#define D2D_INPUT{simpleInput}_SIMPLE"); + } + + foreach (int complexInput in inputComplexIndices) + { + AppendLineAndLF($"#define D2D_INPUT{complexInput}_COMPLEX"); + } + + if (requiresScenePosition) + { + AppendLineAndLF("#define D2D_REQUIRES_SCENE_POSITION"); + } + + // Add the "d2d1effecthelpers.hlsli" header + AppendLF(); + AppendLineAndLF("#include \"d2d1effecthelpers.hlsli\""); + + // Define declarations + foreach (var (name, value) in definedConstants) + { + AppendLineAndLF($"#define {name} {value}"); + } + + // Static fields + if (staticFields.Any()) + { + AppendLF(); + + foreach (var field in staticFields) + { + if (field.Assignment is string assignment) + { + AppendLineAndLF($"{field.TypeDeclaration} {field.Name} = {assignment};"); + } + else + { + AppendLineAndLF($"{field.TypeDeclaration} {field.Name};"); + } + } + } + + // Declared types + foreach (var (_, typeDefinition) in declaredTypes) + { + AppendLF(); + AppendLineAndLF(typeDefinition); + } + + // Captured variables + AppendLF(); + + // User-defined values + foreach (var (fieldName, fieldType) in valueFields) + { + AppendLineAndLF($"{fieldType} {fieldName};"); + } + + // Forward declarations + foreach (var (forwardDeclaration, _) in processedMethods) + { + AppendLF(); + AppendLineAndLF(forwardDeclaration); + } + + // Captured methods + foreach (var (_, method) in processedMethods) + { + AppendLF(); + AppendLineAndLF(method); + } + + // Entry point + AppendLF(); + AppendLineAndLF(executeMethod); + + return hlslBuilder.ToString(); + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs new file mode 100644 index 00000000..fcdb1248 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs @@ -0,0 +1,127 @@ +using System.Collections.Immutable; +using ComputeSharp.D2D1.__Internals; +using ComputeSharp.D2D1.SourceGenerators.Models; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +partial class ID2D1ShaderGenerator +{ + /// + partial class InitializeFromDispatchData + { + /// + /// Creates a instance for the InitializeFromDispatchData method. + /// + /// The dispatch info gathered for the current shader. + /// The resulting instance for the InitializeFromDispatchData method. + public static MethodDeclarationSyntax GetSyntax(DispatchDataInfo dispatchInfo) + { + // This code produces a method declaration as follows: + // + // readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InitializeFromDispatchData(global::System.ReadOnlySpan data) + // { + // + // } + return + MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("InitializeFromDispatchData")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) + .AddParameterListParameters(Parameter(Identifier("data")).WithType( + GenericName(Identifier("global::System.ReadOnlySpan")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))) + .WithBody(Block(GetDispatchDataUnloadingStatements(dispatchInfo.FieldInfos))); + } + + /// + /// Gets a sequence of statements to initialize a shader from a serialized dispatch data buffer. + /// + /// The array of values for all captured fields. + /// The sequence of instances to initialize a shader from the serialized dispatch data buffer. + private static ImmutableArray GetDispatchDataUnloadingStatements(ImmutableArray fieldInfos) + { + ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + + // Insert the fallback for empty shaders. This will generate the following code: + // + // if (data.IsEmpty) + // { + // return; + // } + statements.Add( + IfStatement( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("data"), + IdentifierName("IsEmpty")), + Block(ReturnStatement()))); + + // ref byte r0 = ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(data); + statements.Add( + LocalDeclarationStatement( + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("r0")) + .WithInitializer(EqualsValueClause( + RefExpression( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("global::System.Runtime.InteropServices.MemoryMarshal"), + IdentifierName("GetReference"))) + .AddArgumentListArguments(Argument(IdentifierName("data"))))))))); + + // Generate loading statements for each captured field + foreach (FieldInfo fieldInfo in fieldInfos) + { + switch (fieldInfo) + { + case FieldInfo.Primitive primitive: + + // Read a primitive value from the target buffer. This will generate: + // + // Unsafe.AsRef(in ) = global::System.Runtime.CompilerServices.Unsafe.As>( + // ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint))) + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", primitive.FieldPath)})"), + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset}))")))); + break; + + case FieldInfo.NonLinearMatrix matrix: + string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}"; + string rowLocalName = $"__{string.Join("_", matrix.FieldPath)}__row0"; + + // Declare a local to index into individual rows. This will generate: + // + // ref = ref global::System.Runtime.CompilerServices.Unsafe.As, >( + // ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in )); + statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", matrix.FieldPath)}));")); + + // Generate the loading code for each individual row, with proper alignment. + // This will result in the following (assuming Float2x3 m): + // + // ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m)); + // global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0) = global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)); + // global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1) = global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))); + for (int j = 0; j < matrix.Rows; j++) + { + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j})"), + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){matrix.Offsets[j]}))")))); + } + break; + } + } + + return statements.ToImmutable(); + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs new file mode 100644 index 00000000..27be5445 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs @@ -0,0 +1,187 @@ +using System; +using ComputeSharp.__Internals; +using ComputeSharp.D2D1.__Internals; +using ComputeSharp.D2D1.SourceGenerators.Models; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +partial class ID2D1ShaderGenerator +{ + /// + partial class LoadBytecode + { + /// + /// Creates a instance for the TryGetBytecode method. + /// + /// The input bytecode info. + /// An opaque instance to transform the final tree into text. + /// The resulting instance for the BuildHlslSource method. + public static MethodDeclarationSyntax GetSyntax(EmbeddedBytecodeInfo bytecodeInfo, out Func fixup) + { + BlockSyntax block = GetShaderBytecodeBody(bytecodeInfo, out string? bytecodeLiterals); + + if (bytecodeLiterals is not null) + { + fixup = tree => tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals); + } + else + { + fixup = static tree => tree.ToFullString(); + } + + // This code produces a method declaration as follows: + // + // readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadBytecode(ref TLoader loader, global::ComputeSharp.D2D1.D2D1ShaderProfile? shaderProfile) + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.VoidKeyword)), + Identifier("LoadBytecode")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .AddTypeParameterListParameters(TypeParameter(Identifier("TLoader"))) + .AddParameterListParameters( + Parameter(Identifier("loader")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("TLoader")), + Parameter(Identifier("shaderProfile")).WithType(NullableType(IdentifierName("global::ComputeSharp.D2D1.D2D1ShaderProfile")))) + .WithBody(block); + } + + /// + /// Gets a instance with the logic to try to get a compiled shader bytecode. + /// + /// The input bytecode info. + /// The resulting bytecode literals to insert into the final source code. + /// The instance trying to retrieve the precompiled shader. + private static unsafe BlockSyntax GetShaderBytecodeBody(EmbeddedBytecodeInfo bytecodeInfo, out string? bytecodeLiterals) + { + // This code produces a method declaration as follows: + // + // ComputeSharp.D2D1.__Internals.D2D1ShaderCompiler.LoadDynamicBytecode(ref loader, in this, shaderProfile, ); + ExpressionStatementSyntax dynamicLoadingStatement = + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("ComputeSharp.D2D1.__Internals.D2D1ShaderCompiler"), + IdentifierName("LoadDynamicBytecode"))) + .AddArgumentListArguments( + Argument(IdentifierName("loader")).WithRefKindKeyword(Token(SyntaxKind.RefKeyword)), + Argument(ThisExpression()).WithRefKindKeyword(Token(SyntaxKind.InKeyword)), + Argument(IdentifierName("shaderProfile")), + Argument(LiteralExpression(bytecodeInfo.IsLinkingSupported ? SyntaxKind.TrueLiteralExpression : SyntaxKind.FalseLiteralExpression)))); + + // If there is no precompiled bytecode, just return the dynamic path + if (bytecodeInfo.Bytecode.IsDefaultOrEmpty) + { + bytecodeLiterals = null; + + return Block(dynamicLoadingStatement); + } + + bytecodeLiterals = BuildShaderBytecodeExpressionString(bytecodeInfo.Bytecode.AsSpan()); + + // This code produces a branch as follows: + // + // if (shaderProfile is null or ) + // { + // global::System.ReadOnlySpan bytecode = new byte[] { __EMBEDDED_SHADER_BYTECODE }; + // loader.LoadEmbeddedBytecode(bytecode); + // } + // + // Note that the __EMBEDDED_SHADER_BYTECODE identifier will be replaced after the string + // is created by the generator. This greatly speeds up the code generation, as it avoids + // having to create/parse tens of thousands of literal expression nodes for every shader. + IfStatementSyntax embeddedBranch = + IfStatement( + IsPatternExpression( + IdentifierName("shaderProfile"), + BinaryPattern( + SyntaxKind.OrPattern, + ConstantPattern(LiteralExpression(SyntaxKind.NullLiteralExpression)), + ConstantPattern( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("global::ComputeSharp.D2D1.D2D1ShaderProfile"), + IdentifierName(bytecodeInfo.ShaderProfile.GetValueOrDefault().ToString()))))), + Block( + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("global::System.ReadOnlySpan")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("bytecode")) + .WithInitializer( + EqualsValueClause( + ArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) + .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) + .WithInitializer( + InitializerExpression( + SyntaxKind.ArrayInitializerExpression, + SingletonSeparatedList(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))))), + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("loader"), + IdentifierName("LoadEmbeddedBytecode"))) + .AddArgumentListArguments(Argument(IdentifierName("bytecode")))))); + + // Return the combined block + return Block(embeddedBranch.WithElse(ElseClause(Block(dynamicLoadingStatement)))); + } + + /// + /// A mapping of precomputed literals for all values. + /// + private static readonly string[] formattedBytes = + { + "0x00", "0x01", "0x02", "0x03", "0x04", "0x05", "0x06", "0x07", "0x08", "0x09", "0x0A", "0x0B", "0x0C", "0x0D", "0x0E", "0x0F", + "0x10", "0x11", "0x12", "0x13", "0x14", "0x15", "0x16", "0x17", "0x18", "0x19", "0x1A", "0x1B", "0x1C", "0x1D", "0x1E", "0x1F", + "0x20", "0x21", "0x22", "0x23", "0x24", "0x25", "0x26", "0x27", "0x28", "0x29", "0x2A", "0x2B", "0x2C", "0x2D", "0x2E", "0x2F", + "0x30", "0x31", "0x32", "0x33", "0x34", "0x35", "0x36", "0x37", "0x38", "0x39", "0x3A", "0x3B", "0x3C", "0x3D", "0x3E", "0x3F", + "0x40", "0x41", "0x42", "0x43", "0x44", "0x45", "0x46", "0x47", "0x48", "0x49", "0x4A", "0x4B", "0x4C", "0x4D", "0x4E", "0x4F", + "0x50", "0x51", "0x52", "0x53", "0x54", "0x55", "0x56", "0x57", "0x58", "0x59", "0x5A", "0x5B", "0x5C", "0x5D", "0x5E", "0x5F", + "0x60", "0x61", "0x62", "0x63", "0x64", "0x65", "0x66", "0x67", "0x68", "0x69", "0x6A", "0x6B", "0x6C", "0x6D", "0x6E", "0x6F", + "0x70", "0x71", "0x72", "0x73", "0x74", "0x75", "0x76", "0x77", "0x78", "0x79", "0x7A", "0x7B", "0x7C", "0x7D", "0x7E", "0x7F", + "0x80", "0x81", "0x82", "0x83", "0x84", "0x85", "0x86", "0x87", "0x88", "0x89", "0x8A", "0x8B", "0x8C", "0x8D", "0x8E", "0x8F", + "0x90", "0x91", "0x92", "0x93", "0x94", "0x95", "0x96", "0x97", "0x98", "0x99", "0x9A", "0x9B", "0x9C", "0x9D", "0x9E", "0x9F", + "0xA0", "0xA1", "0xA2", "0xA3", "0xA4", "0xA5", "0xA6", "0xA7", "0xA8", "0xA9", "0xAA", "0xAB", "0xAC", "0xAD", "0xAE", "0xAF", + "0xB0", "0xB1", "0xB2", "0xB3", "0xB4", "0xB5", "0xB6", "0xB7", "0xB8", "0xB9", "0xBA", "0xBB", "0xBC", "0xBD", "0xBE", "0xBF", + "0xC0", "0xC1", "0xC2", "0xC3", "0xC4", "0xC5", "0xC6", "0xC7", "0xC8", "0xC9", "0xCA", "0xCB", "0xCC", "0xCD", "0xCE", "0xCF", + "0xD0", "0xD1", "0xD2", "0xD3", "0xD4", "0xD5", "0xD6", "0xD7", "0xD8", "0xD9", "0xDA", "0xDB", "0xDC", "0xDD", "0xDE", "0xDF", + "0xE0", "0xE1", "0xE2", "0xE3", "0xE4", "0xE5", "0xE6", "0xE7", "0xE8", "0xE9", "0xEA", "0xEB", "0xEC", "0xED", "0xEE", "0xEF", + "0xF0", "0xF1", "0xF2", "0xF3", "0xF4", "0xF5", "0xF6", "0xF7", "0xF8", "0xF9", "0xFA", "0xFB", "0xFC", "0xFD", "0xFE", "0xFF" + }; + + /// + /// Creates a formatted expression to initialize a with a given shader data. + /// + /// The input shader bytecode to serialize. + /// A formatted with the serialized data. + private static string BuildShaderBytecodeExpressionString(ReadOnlySpan bytecode) + { + //The estimation is 4 characters per byte (up to "255" in hex), plus ", " to separate sequential values + using ArrayPoolStringBuilder builder = ArrayPoolStringBuilder.Create(bytecode.Length * 6); + + builder.Append(formattedBytes[bytecode[0]]); + + foreach (byte b in bytecode.Slice(1)) + { + builder.Append(", "); + builder.Append(formattedBytes[b]); + } + + return builder.WrittenSpan.ToString(); + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs new file mode 100644 index 00000000..f616dd12 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs @@ -0,0 +1,134 @@ +using System; +using System.Collections.Immutable; +using System.ComponentModel; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; +using System.Threading; +using ComputeSharp.D2D1.Exceptions; +using ComputeSharp.D2D1.Shaders.Translation; +using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Models; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors; + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +partial class ID2D1ShaderGenerator +{ + /// + internal static partial class LoadBytecode + { + /// + /// Extracts the shader profile for the current shader. + /// + /// The input instance to process. + /// The shader profile to use to compile the shader, if present. + public static D2D1ShaderProfile? GetShaderProfile(INamedTypeSymbol structDeclarationSymbol) + { + if (structDeclarationSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DEmbeddedBytecodeAttribute", out AttributeData? attributeData)) + { + return (D2D1ShaderProfile)attributeData!.ConstructorArguments[0].Value!; + } + + return null; + } + + /// + /// Extracts the metadata definition for the current shader. + /// + /// The input instance to process. + /// The number of inputs for the shader. + /// Whether the shader only has simple inputs. + public static bool IsSimpleInputShader(INamedTypeSymbol structDeclarationSymbol, int inputCount) + { + // Build a map of all simple inputs (unmarked inputs default to being complex) + bool[] simpleInputsMap = new bool[inputCount]; + + foreach (AttributeData attributeData in structDeclarationSymbol.GetAttributes()) + { + switch (attributeData.AttributeClass?.GetFullMetadataName()) + { + case "ComputeSharp.D2D1.D2DInputSimpleAttribute": + simpleInputsMap[(int)attributeData.ConstructorArguments[0].Value!] = true; + break; + } + } + + return simpleInputsMap.All(static x => x); + } + + /// + /// Gets a instance with the logic to try to get a compiled shader bytecode. + /// + /// The source info for the shader to compile. + /// The used to cancel the operation, if needed. + /// The resulting diagnostic from the processing operation, if any. + /// The instance with the compiled shader bytecode. + public static unsafe ImmutableArray GetBytecode(HlslShaderSourceInfo sourceInfo, CancellationToken token, out DiagnosticInfo? diagnostic) + { + ImmutableArray bytecode = ImmutableArray.Empty; + + // No embedded shader was requested, or there were some errors earlier in the pipeline. + // In this case, skip the compilation, as diagnostic will be emitted for those anyway. + // Compiling would just add overhead and result in more errors, as the HLSL would be invalid. + if (sourceInfo.HasErrors || + sourceInfo.ShaderProfile is null) + { + diagnostic = null; + + goto End; + } + + try + { + token.ThrowIfCancellationRequested(); + + // Compile the shader bytecode + using ComPtr dxcBlobBytecode = D2D1ShaderCompiler.Compile( + sourceInfo.HlslSource.AsSpan(), + sourceInfo.ShaderProfile.Value, + sourceInfo.IsLinkingSupported); + + token.ThrowIfCancellationRequested(); + + byte* buffer = (byte*)dxcBlobBytecode.Get()->GetBufferPointer(); + int length = checked((int)dxcBlobBytecode.Get()->GetBufferSize()); + + byte[] array = new ReadOnlySpan(buffer, length).ToArray(); + + bytecode = Unsafe.As>(ref array); + diagnostic = null; + } + catch (Win32Exception e) + { + diagnostic = new DiagnosticInfo(EmbeddedBytecodeFailedWithWin32Exception, e.HResult, FixupExceptionMessage(e.Message)); + } + catch (FxcCompilationException e) + { + diagnostic = new DiagnosticInfo(EmbeddedBytecodeFailedWithDxcCompilationException, FixupExceptionMessage(e.Message)); + } + + End: + return bytecode; + } + + /// + /// Fixes up an exception message to improve the way it's displayed in VS. + /// + /// The input exception message. + /// The updated exception message. + private static string FixupExceptionMessage(string message) + { + // Add square brackets around error headers + message = Regex.Replace(message, @"((?:error|warning) \w+):", static m => $"[{m.Groups[1].Value}]:"); + + return message.NormalizeToSingleLine(); + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs new file mode 100644 index 00000000..848298d9 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -0,0 +1,138 @@ +using System.Collections.Immutable; +using ComputeSharp.D2D1.__Internals; +using ComputeSharp.D2D1.SourceGenerators.Models; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +partial class ID2D1ShaderGenerator +{ + /// + partial class LoadDispatchData + { + /// + /// Creates a instance for the LoadDispatchDataMethod method. + /// + /// The dispatch info gathered for the current shader. + /// The resulting instance for the LoadDispatchDataMethod method. + public static MethodDeclarationSyntax GetSyntax(DispatchDataInfo dispatchInfo) + { + // This code produces a method declaration as follows: + // + // readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadDispatchData(ref TLoader loader) + // { + // + // } + return + MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("LoadDispatchData")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .AddTypeParameterListParameters(TypeParameter(Identifier("TLoader"))) + .AddParameterListParameters(Parameter(Identifier("loader")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("TLoader"))) + .WithBody(Block(GetDispatchDataLoadingStatements(dispatchInfo.FieldInfos, dispatchInfo.Root32BitConstantCount))); + } + + /// + /// Gets a sequence of statements to load the dispatch data for a given shader. + /// + /// The array of values for all captured fields. + /// The total number of needed 32 bit constants in the shader root signature. + /// The sequence of instances to load shader dispatch data. + private static ImmutableArray GetDispatchDataLoadingStatements(ImmutableArray fieldInfos, int root32BitConstantsCount) + { + ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + + // Generate loading statements for each captured field + foreach (FieldInfo fieldInfo in fieldInfos) + { + switch (fieldInfo) + { + case FieldInfo.Primitive primitive: + + // Read a primitive value and serialize it into the target buffer. This will generate: + // + // global::System.Runtime.CompilerServices.Unsafe.As>( + // ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint))) = + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset}))"), + ParseExpression($"{string.Join(".", primitive.FieldPath)}")))); + break; + + case FieldInfo.NonLinearMatrix matrix: + string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}"; + string rowLocalName = $"__{string.Join("_", matrix.FieldPath)}__row0"; + + // Declare a local to index into individual rows. This will generate: + // + // ref = ref global::System.Runtime.CompilerServices.Unsafe.As, >( + // ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in )); + statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", matrix.FieldPath)}));")); + + // Generate the loading code for each individual row, with proper alignment. + // This will result in the following (assuming Float2x3 m): + // + // ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m)); + // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0); + // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1); + for (int j = 0; j < matrix.Rows; j++) + { + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){matrix.Offsets[j]}))"), + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j})")))); + } + break; + } + } + + // global::System.Span data = stackalloc uint[]; + statements.Insert(0, + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("global::System.Span")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("data")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword))) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(root32BitConstantsCount))))))))))); + + // ref uint r0 = ref data[0]; + statements.Insert(1, + LocalDeclarationStatement( + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("r0")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("data")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))))))))); + + // loader.LoadConstantBuffer(data); + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("loader"), + IdentifierName("LoadConstantBuffer"))) + .AddArgumentListArguments(Argument(IdentifierName("data"))))); + + return statements.ToImmutable(); + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.cs new file mode 100644 index 00000000..14f23044 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.cs @@ -0,0 +1,176 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Runtime.CompilerServices; +using ComputeSharp.Core.Helpers; +using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Mappings; +using Microsoft.CodeAnalysis; +using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors; + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +partial class ID2D1ShaderGenerator +{ + /// + /// A helper with all logic to generate the LoadDispatchData method. + /// + private static partial class LoadDispatchData + { + /// + /// Explores a given type hierarchy and generates statements to load fields. + /// + /// The current shader type being explored. + /// The total number of needed 32 bit constants in the shader root signature. + /// The resulting diagnostics from the processing operation. + /// The sequence of instances for all captured resources and values. + public static ImmutableArray GetInfo( + ITypeSymbol structDeclarationSymbol, + out int root32BitConstantCount, + out ImmutableArray diagnostics) + { + // Helper method that uses boxes instead of ref-s (illegal in enumerators) + static IEnumerable GetCapturedFieldInfos( + ITypeSymbol currentTypeSymbol, + ImmutableArray fieldPath, + StrongBox rawDataOffset) + { + bool isFirstField = true; + + foreach ( + IFieldSymbol fieldSymbol in + from fieldSymbol in currentTypeSymbol.GetMembers().OfType() + where fieldSymbol.Type is INamedTypeSymbol { IsStatic: false } && + !fieldSymbol.IsConst && !fieldSymbol.IsStatic && + !fieldSymbol.IsFixedSizeBuffer + select fieldSymbol) + { + string fieldName = fieldSymbol.Name; + string typeName = fieldSymbol.Type.GetFullMetadataName(); + + // Disambiguates the name of target fields against the current input parameters + if (fieldName is "loader") + { + fieldName = $"this.{fieldName}"; + } + + // The first item in each nested struct needs to be aligned to 16 bytes + if (isFirstField && fieldPath.Length > 0) + { + rawDataOffset.Value = AlignmentHelper.Pad(rawDataOffset.Value, 16); + + isFirstField = false; + } + + if (HlslKnownTypes.IsKnownHlslType(typeName)) + { + yield return GetHlslKnownTypeFieldInfo(fieldPath.Add(fieldName), typeName, ref rawDataOffset.Value); + } + else if (fieldSymbol.Type.IsUnmanagedType) + { + // Custom struct type defined by the user + foreach (var fieldInfo in GetCapturedFieldInfos(fieldSymbol.Type, fieldPath.Add(fieldName), rawDataOffset)) + { + yield return fieldInfo; + } + } + } + } + + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + + // Setup the resource and byte offsets for tracking + StrongBox rawDataOffsetAsBox = new(); + + // Traverse all shader fields and gather info, and update the tracking offsets + ImmutableArray fieldInfos = GetCapturedFieldInfos( + structDeclarationSymbol, + ImmutableArray.Empty, + rawDataOffsetAsBox).ToImmutableArray(); + + // After all the captured fields have been processed, ansure the reported byte size for + // the local variables is padded to a multiple of a 32 bit value. This is necessary to + // enable loading all the dispatch data after reinterpreting it to a sequence of values + // of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds. + root32BitConstantCount = AlignmentHelper.Pad(rawDataOffsetAsBox.Value, sizeof(int)) / sizeof(int); + + // A shader root signature has a maximum size of 64 DWORDs, so 256 bytes. + // Loaded values in the root signature have the following costs: + // - Root constants cost 1 DWORD each, since they are 32-bit values. + // - Descriptor tables cost 1 DWORD each. + // - Root descriptors (64-bit GPU virtual addresses) cost 2 DWORDs each. + // So here we check whether the current signature respects that constraint, + // and emit a build error otherwise. For more info on this, see the docs here: + // https://docs.microsoft.com/windows/win32/direct3d12/root-signature-limits. + int rootSignatureDwordSize = root32BitConstantCount; + + if (rootSignatureDwordSize > 64) + { + builder.Add(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol); + } + + diagnostics = builder.ToImmutable(); + + return fieldInfos; + } + + /// + /// Gets info on a given captured HLSL primitive type (either a scalar, a vector or a matrix). + /// + /// The current path of the field with respect to the shader instance. + /// The type name currently being read. + /// The current offset within the loaded data buffer. + private static FieldInfo GetHlslKnownTypeFieldInfo( + ImmutableArray fieldPath, + string typeName, + ref int rawDataOffset) + { + // For scalar, vector and linear matrix types, serialize the value normally. + // Only the initial alignment needs to be considered, while data is packed. + var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName); + + // Check if the current type is a matrix type with more than one row. In this + // case, each row is aligned as if it was a separate array, so the start of + // each row needs to be at a multiple of 16 bytes (a float4 register). + if (HlslKnownTypes.IsNonLinearMatrixType(typeName, out string? elementName, out int rows, out int columns)) + { + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(rows); + + for (int j = 0; j < rows; j++) + { + int startingRawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); + + builder.Add(startingRawDataOffset); + + rawDataOffset = startingRawDataOffset + fieldPack * columns; + } + + return new FieldInfo.NonLinearMatrix( + fieldPath, + typeName, + elementName!, + rows, + columns, + builder.MoveToImmutable()); + } + else + { + // 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. + int startingRawDataOffset = AlignmentHelper.AlignToBoundary( + AlignmentHelper.Pad(rawDataOffset, fieldPack), + fieldSize, + 16); + + rawDataOffset = startingRawDataOffset + fieldSize; + + return new FieldInfo.Primitive(fieldPath, typeName, startingRawDataOffset); + } + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.Helpers.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.Helpers.cs new file mode 100644 index 00000000..9232e403 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.Helpers.cs @@ -0,0 +1,72 @@ +using System.Collections.Generic; +using ComputeSharp.SourceGeneration.Models; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +partial class ID2D1ShaderGenerator +{ + /// + /// Gets the shader type for a given shader, if any. + /// + /// The input instance to check. + /// The instance for . + /// Whether or not implements . + private static bool IsD2D1PixelShaderType(INamedTypeSymbol typeSymbol, INamedTypeSymbol d2D1PixelShaderSymbol) + { + foreach (INamedTypeSymbol interfaceSymbol in typeSymbol.Interfaces) + { + if (interfaceSymbol.Name == nameof(ID2D1PixelShader) && + SymbolEqualityComparer.Default.Equals(interfaceSymbol, d2D1PixelShaderSymbol)) + { + return true; + } + } + + return false; + } + + /// + /// Creates a instance wrapping the given method. + /// + /// The instance for the current type. + /// The item to insert. + /// Whether [SkipLocalsInit] can be used. + /// A object wrapping . + private static CompilationUnitSyntax GetCompilationUnitFromMethod( + HierarchyInfo hierarchyInfo, + MethodDeclarationSyntax methodDeclaration, + bool canUseSkipLocalsInit) + { + // Method attributes + List attributes = new() + { + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments( + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).FullName))), + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).Assembly.GetName().Version.ToString())))))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("global::System.ComponentModel.EditorBrowsable")).AddArgumentListArguments( + AttributeArgument(ParseExpression("global::System.ComponentModel.EditorBrowsableState.Never"))))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("global::System.Obsolete")).AddArgumentListArguments( + AttributeArgument(LiteralExpression( + SyntaxKind.StringLiteralExpression, + Literal("This method is not intended to be used directly by user code")))))) + }; + + // Add [SkipLocalsInit] if the target project allows it + if (canUseSkipLocalsInit) + { + attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit"))))); + } + + return hierarchyInfo.GetSyntax(methodDeclaration.AddAttributeLists(attributes.ToArray())); + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs new file mode 100644 index 00000000..62b802d5 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -0,0 +1,202 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Models; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +/// A source generator creating data loaders for the type. +/// +[Generator(LanguageNames.CSharp)] +public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator +{ + /// + public void Initialize(IncrementalGeneratorInitializationContext context) + { + // Check whether [SkipLocalsInit] can be used + IncrementalValueProvider canUseSkipLocalsInit = + context.CompilationProvider + .Select(static (compilation, token) => + compilation.Options is CSharpCompilationOptions { AllowUnsafe: true } && + compilation.GetTypeByMetadataName("System.Runtime.CompilerServices.SkipLocalsInitAttribute") is not null); + + // Get all declared struct types and their type symbols + IncrementalValuesProvider<(StructDeclarationSyntax Syntax, INamedTypeSymbol Symbol)> structDeclarations = + context.SyntaxProvider + .CreateSyntaxProvider( + static (node, token) => node is StructDeclarationSyntax structDeclaration, + static (context, token) => ( + (StructDeclarationSyntax)context.Node, + Symbol: (INamedTypeSymbol?)context.SemanticModel.GetDeclaredSymbol(context.Node, token))) + .Where(static pair => pair.Symbol is { Interfaces.IsEmpty: false })!; + + // Get the symbol for the ID2D1PixelShader interface + IncrementalValueProvider pixelShaderInterface = + context.CompilationProvider + .Select(static (compilation, token) => compilation.GetTypeByMetadataName(typeof(ID2D1PixelShader).FullName)!); + + // Filter struct declarations that implement the shader interface, and also gather the hierarchy info + IncrementalValuesProvider<(StructDeclarationSyntax Syntax, INamedTypeSymbol Symbol, HierarchyInfo Hierarchy)> shaderDeclarations = + structDeclarations + .Combine(pixelShaderInterface) + .Where(static item => IsD2D1PixelShaderType(item.Left.Symbol, item.Right)) + .Select(static (item, token) => (item.Left.Syntax, item.Left.Symbol, HierarchyInfo.From(item.Left.Symbol))); + + // Get the dispatch data, HLSL source and embedded bytecode info. This info is computed on the + // same step as parts are shared in following sub-branches in the incremental generator pipeline. + IncrementalValuesProvider<(HierarchyInfo Hierarchy, Result Dispatch, Result Source)> shaderInfoWithErrors = + shaderDeclarations + .Combine(context.CompilationProvider) + .Select(static (item, token) => + { + // LoadDispatchData() info + ImmutableArray fieldInfos = LoadDispatchData.GetInfo( + item.Left.Symbol, + out int root32BitConstantCount, + out ImmutableArray dispatchDataDiagnostics); + + token.ThrowIfCancellationRequested(); + + DispatchDataInfo dispatchDataInfo = new(fieldInfos, root32BitConstantCount); + + // Get HLSL source for BuildHlslSource() + string hlslSource = BuildHlslSource.GetHlslSource( + item.Right, + item.Left.Syntax, + item.Left.Symbol, + out int inputCount, + out ImmutableArray hlslSourceDiagnostics); + + token.ThrowIfCancellationRequested(); + + // Get the shader profile and linking info for LoadBytecode() + D2D1ShaderProfile? shaderProfile = LoadBytecode.GetShaderProfile(item.Left.Symbol); + bool hasErrors = !dispatchDataDiagnostics.IsDefaultOrEmpty || !hlslSourceDiagnostics.IsDefaultOrEmpty; + bool isLinkingSupported = !hasErrors && LoadBytecode.IsSimpleInputShader(item.Left.Symbol, inputCount); + + HlslShaderSourceInfo sourceInfo = new( + hlslSource, + shaderProfile, + isLinkingSupported, + hasErrors); + + token.ThrowIfCancellationRequested(); + + return ( + item.Left.Hierarchy, + new Result(dispatchDataInfo, dispatchDataDiagnostics), + new Result(sourceInfo, hlslSourceDiagnostics)); + }); + + // Output the diagnostics + context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.Dispatch.Errors)); + context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.Source.Errors)); + + // Filter all items to enable caching at a coarse level, and remove diagnostics + IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch, HlslShaderSourceInfo Source)> shaderInfo = + shaderInfoWithErrors + .Select(static (item, token) => (item.Hierarchy, item.Dispatch.Value, item.Source.Value)) + .WithComparers(HierarchyInfo.Comparer.Default, DispatchDataInfo.Comparer.Default, EqualityComparer.Default); + + // Get a filtered sequence to enable caching + IncrementalValuesProvider< (HierarchyInfo Hierarchy, DispatchDataInfo Dispatch)> dispatchDataInfo = + shaderInfo + .Select(static (item, token) => (item.Hierarchy, item.Dispatch)) + .WithComparers(HierarchyInfo.Comparer.Default, DispatchDataInfo.Comparer.Default); + + // Generate the LoadDispatchData() methods + context.RegisterSourceOutput(dispatchDataInfo.Combine(canUseSkipLocalsInit), static (context, item) => + { + MethodDeclarationSyntax loadDispatchDataMethod = LoadDispatchData.GetSyntax(item.Left.Dispatch); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, loadDispatchDataMethod, item.Right); + + context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(LoadDispatchData)}", compilationUnit.ToFullString()); + }); + + // Generate the InitializeFromDispatchData() methods + context.RegisterSourceOutput(dispatchDataInfo, static (context, item) => + { + MethodDeclarationSyntax loadDispatchDataMethod = InitializeFromDispatchData.GetSyntax(item.Dispatch); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, loadDispatchDataMethod, false); + + context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(InitializeFromDispatchData)}", compilationUnit.ToFullString()); + }); + + // Get the filtered sequence to enable caching + IncrementalValuesProvider<(HierarchyInfo Hierarchy, string HlslSource)> hlslSourceInfo = + shaderInfo + .Select(static (item, token) => (item.Hierarchy, item.Source.HlslSource)) + .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default); + + // Generate the BuildHlslSource() methods + context.RegisterSourceOutput(hlslSourceInfo, static (context, item) => + { + MethodDeclarationSyntax buildHlslStringMethod = BuildHlslSource.GetSyntax(item.HlslSource); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, buildHlslStringMethod, canUseSkipLocalsInit: false); + + context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(BuildHlslSource)}", compilationUnit.ToFullString()); + }); + + // Get a filtered sequence to enable caching + IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderSourceInfo Source)> shaderBytecodeInfo = + shaderInfo + .Select(static (item, token) => (item.Hierarchy, item.Source)) + .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default); + + // Compile the requested shader bytecodes + IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo, DiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors = + shaderBytecodeInfo + .Select(static (item, token) => + { + ImmutableArray bytecode = LoadBytecode.GetBytecode(item.Source, token, out DiagnosticInfo? diagnostic); + + token.ThrowIfCancellationRequested(); + + EmbeddedBytecodeInfo bytecodeInfo = new(item.Source.HlslSource, item.Source.ShaderProfile, item.Source.IsLinkingSupported, bytecode); + + return (item.Hierarchy, bytecodeInfo, diagnostic); + }); + + // Gather the diagnostics + IncrementalValuesProvider embeddedBytecodeDiagnostics = + embeddedBytecodeWithErrors + .Select(static (item, token) => (item.Hierarchy.FullyQualifiedMetadataName, item.Diagnostic)) + .Where(static item => item.Diagnostic is not null) + .Combine(context.CompilationProvider) + .Select(static (item, token) => + { + INamedTypeSymbol typeSymbol = item.Right.GetTypeByMetadataName(item.Left.FullyQualifiedMetadataName)!; + + return Diagnostic.Create( + item.Left.Diagnostic!.Descriptor, + typeSymbol.Locations.FirstOrDefault(), + new object[] { typeSymbol }.Concat(item.Left.Diagnostic.Args).ToArray()); + }); + + // Output the diagnostics + context.ReportDiagnostics(embeddedBytecodeDiagnostics); + + // Get the filtered sequence to enable caching + IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo)> embeddedBytecode = + embeddedBytecodeWithErrors + .Select(static (item, token) => (item.Hierarchy, item.BytecodeInfo)) + .WithComparers(HierarchyInfo.Comparer.Default, EmbeddedBytecodeInfo.Comparer.Default); + + // Generate the LoadBytecode() methods + context.RegisterSourceOutput(embeddedBytecode, static (context, item) => + { + MethodDeclarationSyntax loadBytecodeMethod = LoadBytecode.GetSyntax(item.BytecodeInfo, out Func fixup); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, loadBytecodeMethod, false); + string text = fixup(compilationUnit); + + context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(LoadBytecode)}", text); + }); + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownKeywords.cs b/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownKeywords.cs new file mode 100644 index 00000000..78098a82 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownKeywords.cs @@ -0,0 +1,22 @@ +using System.Collections.Generic; +using System.Reflection; +using ComputeSharp.Core.Intrinsics.Attributes; +using ComputeSharp.D2D1; + +namespace ComputeSharp.SourceGeneration.Mappings; + +/// +partial class HlslKnownKeywords +{ + /// + static partial void AddKnownKeywords(ICollection knownKeywords) + { + // D2D1 intrinsics method names + foreach (var method in typeof(D2D).GetMethods(BindingFlags.Public | BindingFlags.Static)) + { + string name = method.GetCustomAttribute()?.Name ?? method.Name; + + knownKeywords.Add(name); + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownMethods.cs b/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownMethods.cs new file mode 100644 index 00000000..99964394 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownMethods.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using ComputeSharp.Core.Intrinsics.Attributes; +using ComputeSharp.D2D1; + +namespace ComputeSharp.SourceGeneration.Mappings; + +/// +partial class HlslKnownMethods +{ + /// + + static partial void AddKnownMethods(IDictionary knownMethods) + { + // Programmatically load mappings from the D2D1 class as well + foreach (var method in + from method in typeof(D2D).GetMethods(BindingFlags.Public | BindingFlags.Static) + group method by method.Name + into groups + select groups.First()) + { + string hlslName = method.GetCustomAttribute()?.Name ?? method.Name; + + knownMethods.Add($"{typeof(D2D).FullName}{Type.Delimiter}{method.Name}", hlslName); + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownTypes.cs new file mode 100644 index 00000000..33dc9cbe --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -0,0 +1,23 @@ +using ComputeSharp.SourceGeneration.Extensions; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.SourceGeneration.Mappings; + +/// +partial class HlslKnownTypes +{ + /// + public static partial string GetMappedName(INamedTypeSymbol typeSymbol) + { + string typeName = typeSymbol.GetFullMetadataName(); + + // The captured field is of an HLSL primitive type + if (KnownHlslTypes.TryGetValue(typeName, out string? mappedType)) + { + return mappedType; + } + + // The captured field is of a custom struct type + return typeName.ToHlslIdentifierName(); + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/DispatchDataInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/DispatchDataInfo.cs new file mode 100644 index 00000000..a34e3bad --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/DispatchDataInfo.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; + +namespace ComputeSharp.D2D1.SourceGenerators.Models; + +/// +/// A model representing gathered info on a shader dispatch data. +/// +/// The description on shader instance fields. +/// The size of the shader root signature, in 32 bit constants. +internal sealed record DispatchDataInfo(ImmutableArray FieldInfos, int Root32BitConstantCount) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : Comparer + { + /// + protected override void AddToHashCode(ref HashCode hashCode, DispatchDataInfo obj) + { + hashCode.AddRange(obj.FieldInfos, FieldInfo.Comparer.Default); + hashCode.Add(obj.Root32BitConstantCount); + } + + /// + protected override bool AreEqual(DispatchDataInfo x, DispatchDataInfo y) + { + return + x.FieldInfos.SequenceEqual(y.FieldInfos, FieldInfo.Comparer.Default) && + x.Root32BitConstantCount == y.Root32BitConstantCount; + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeInfo.cs new file mode 100644 index 00000000..385b0144 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeInfo.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; + +namespace ComputeSharp.D2D1.SourceGenerators.Models; + +/// +/// A model representing a shared and its compiled bytecode, if available. +/// +/// The HLSL source for the shader. +/// The shader profile to use to compile the shader, if requested. +/// Whether linking is supported for the current shader. +/// The compiled shader bytecode, if available. +internal sealed record EmbeddedBytecodeInfo(string HlslSource, D2D1ShaderProfile? ShaderProfile, bool IsLinkingSupported, ImmutableArray Bytecode) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : Comparer + { + /// + protected override void AddToHashCode(ref HashCode hashCode, EmbeddedBytecodeInfo obj) + { + hashCode.Add(obj.HlslSource); + hashCode.Add(obj.ShaderProfile); + hashCode.Add(obj.IsLinkingSupported); + hashCode.AddBytes(obj.Bytecode.AsSpan()); + } + + /// + protected override bool AreEqual(EmbeddedBytecodeInfo x, EmbeddedBytecodeInfo y) + { + return + x.HlslSource == y.HlslSource && + x.ShaderProfile == y.ShaderProfile && + x.IsLinkingSupported == y.IsLinkingSupported && + x.Bytecode.SequenceEqual(y.Bytecode); + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/FieldInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/FieldInfo.cs new file mode 100644 index 00000000..073900bd --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/FieldInfo.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; + +namespace ComputeSharp.D2D1.SourceGenerators.Models; + +/// +/// A base type for a model describing a given captured field in a shader. +/// +internal abstract record FieldInfo +{ + /// + /// A captured primitive value (either a scalar, a vector, or a linear matrix). + /// + /// The path of the field with respect to the shader instance. + /// The full metadata name for the primitive type. + /// The byte offset of the value within the root signature. + public sealed record Primitive(ImmutableArray FieldPath, string TypeName, int Offset) : FieldInfo; + + /// + /// A captured non linear matrix value. + /// + /// The path of the field with respect to the shader instance. + /// The full metadata name for the matrix type. + /// The name of each element in the matrix type. + /// The number of rows in the matrix. + /// The number of columns in the matrix. + /// The sequence of byte offsets for each row within the root signature. + public sealed record NonLinearMatrix( + ImmutableArray FieldPath, + string TypeName, + string ElementName, + int Rows, + int Columns, + ImmutableArray Offsets) : FieldInfo; + + /// + /// An implementation for . + /// + public sealed class Comparer : Comparer + { + /// + protected override void AddToHashCode(ref HashCode hashCode, FieldInfo obj) + { + switch (obj) + { + case Primitive primitive: + hashCode.AddRange(primitive.FieldPath); + hashCode.Add(primitive.TypeName); + hashCode.Add(primitive.Offset); + break; + case NonLinearMatrix matrix: + hashCode.AddRange(matrix.FieldPath); + hashCode.Add(matrix.TypeName); + hashCode.Add(matrix.ElementName); + hashCode.Add(matrix.Rows); + hashCode.Add(matrix.Columns); + hashCode.AddRange(matrix.Offsets); + break; + default: + break; + } + } + + /// + protected override bool AreEqual(FieldInfo x, FieldInfo y) + { + if (x is Primitive primitiveX && y is Primitive primitiveY) + { + return + primitiveX.FieldPath.SequenceEqual(primitiveY.FieldPath) && + primitiveX.TypeName == primitiveY.TypeName && + primitiveX.Offset == primitiveY.Offset; + } + else if (x is NonLinearMatrix matrixX && y is NonLinearMatrix matrixY) + { + return + matrixX.FieldPath.SequenceEqual(matrixY.FieldPath) && + matrixX.TypeName == matrixY.TypeName && + matrixX.ElementName == matrixY.ElementName && + matrixX.Rows == matrixY.Rows && + matrixY.Columns == matrixY.Columns && + matrixX.Offsets.SequenceEqual(matrixY.Offsets); + } + + return false; + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslShaderSourceInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslShaderSourceInfo.cs new file mode 100644 index 00000000..76f7c60d --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslShaderSourceInfo.cs @@ -0,0 +1,10 @@ +namespace ComputeSharp.D2D1.SourceGenerators.Models; + +/// +/// A model for extracted info on a processed HLSL shader. +/// +/// The HLSL source. +/// The shader profile to use to compile the shader, if requested. +/// Whether the shader supports linking. +/// Whether any errors have been detected, and therefore the shader compilation should be skipped. +internal sealed record HlslShaderSourceInfo(string HlslSource, D2D1ShaderProfile? ShaderProfile, bool IsLinkingSupported, bool HasErrors); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs new file mode 100644 index 00000000..d722dd00 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs @@ -0,0 +1,205 @@ +using ComputeSharp.SourceGeneration.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors; + +namespace ComputeSharp.D2D1.SourceGenerators.SyntaxRewriters; + +/// +internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter +{ + /// + public override SyntaxNode? VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node) + { + var updatedNode = (AnonymousObjectCreationExpressionSyntax)base.VisitAnonymousObjectCreationExpression(node)!; + + Diagnostics.Add(AnonymousObjectCreationExpression, node); + + return updatedNode; + } + + /// + public override SyntaxNode? VisitAwaitExpression(AwaitExpressionSyntax node) + { + Diagnostics.Add(AwaitExpression, node); + + return base.VisitAwaitExpression(node); + } + + /// + public override SyntaxNode? VisitCheckedExpression(CheckedExpressionSyntax node) + { + Diagnostics.Add(CheckedExpression, node); + + return base.VisitCheckedExpression(node); + } + + /// + public override SyntaxNode? VisitCheckedStatement(CheckedStatementSyntax node) + { + Diagnostics.Add(CheckedStatement, node); + + return base.VisitCheckedStatement(node); + } + + /// + public override SyntaxNode? VisitFixedStatement(FixedStatementSyntax node) + { + Diagnostics.Add(FixedStatement, node); + + return base.VisitFixedStatement(node); + } + + /// + public override SyntaxNode? VisitForEachStatement(ForEachStatementSyntax node) + { + Diagnostics.Add(ForEachStatement, node); + + return base.VisitForEachStatement(node); + } + + /// + public override SyntaxNode? VisitForEachVariableStatement(ForEachVariableStatementSyntax node) + { + Diagnostics.Add(ForEachStatement, node); + + return base.VisitForEachVariableStatement(node); + } + + /// + public override SyntaxNode? VisitLockStatement(LockStatementSyntax node) + { + Diagnostics.Add(LockStatement, node); + + return base.VisitLockStatement(node); + } + + /// + public override SyntaxNode? VisitQueryExpression(QueryExpressionSyntax node) + { + Diagnostics.Add(QueryExpression, node); + + return base.VisitQueryExpression(node); + } + + /// + public override SyntaxNode? VisitRangeExpression(RangeExpressionSyntax node) + { + Diagnostics.Add(RangeExpression, node); + + return base.VisitRangeExpression(node); + } + + /// + public override SyntaxNode? VisitRecursivePattern(RecursivePatternSyntax node) + { + Diagnostics.Add(RecursivePattern, node); + + return base.VisitRecursivePattern(node); + } + + /// + public override SyntaxNode? VisitRefType(RefTypeSyntax node) + { + Diagnostics.Add(RefType, node); + + return base.VisitRefType(node); + } + + /// + public override SyntaxNode? VisitRelationalPattern(RelationalPatternSyntax node) + { + Diagnostics.Add(RelationalPattern, node); + + return base.VisitRelationalPattern(node); + } + + /// + public override SyntaxNode? VisitSizeOfExpression(SizeOfExpressionSyntax node) + { + Diagnostics.Add(SizeOfExpression, node); + + return base.VisitSizeOfExpression(node); + } + + /// + public override SyntaxNode? VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node) + { + Diagnostics.Add(StackAllocArrayCreationExpression, node); + + return base.VisitStackAllocArrayCreationExpression(node); + } + + /// + public override SyntaxNode? VisitThrowExpression(ThrowExpressionSyntax node) + { + Diagnostics.Add(ThrowExpressionOrStatement, node); + + return base.VisitThrowExpression(node); + } + + /// + public override SyntaxNode? VisitThrowStatement(ThrowStatementSyntax node) + { + Diagnostics.Add(ThrowExpressionOrStatement, node); + + return base.VisitThrowStatement(node); + } + + /// + public override SyntaxNode? VisitTryStatement(TryStatementSyntax node) + { + Diagnostics.Add(TryStatement, node); + + return base.VisitTryStatement(node); + } + + /// + public override SyntaxNode? VisitTupleType(TupleTypeSyntax node) + { + Diagnostics.Add(TupleType, node); + + return base.VisitTupleType(node); + } + + /// + public override SyntaxNode? VisitUsingStatement(UsingStatementSyntax node) + { + Diagnostics.Add(UsingStatementOrDeclaration, node); + + return base.VisitUsingStatement(node); + } + + /// + public override SyntaxNode? VisitYieldStatement(YieldStatementSyntax node) + { + Diagnostics.Add(YieldStatement, node); + + return base.VisitYieldStatement(node); + } + + /// + public override SyntaxNode? VisitFunctionPointerType(FunctionPointerTypeSyntax node) + { + Diagnostics.Add(FunctionPointer, node); + + return base.VisitFunctionPointerType(node); + } + + /// + public override SyntaxNode? VisitPointerType(PointerTypeSyntax node) + { + Diagnostics.Add(PointerType, node); + + return base.VisitPointerType(node); + } + + /// + public override SyntaxNode? VisitUnsafeStatement(UnsafeStatementSyntax node) + { + Diagnostics.Add(UnsafeStatement, node); + + return base.VisitUnsafeStatement(node); + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs new file mode 100644 index 00000000..83e1cecd --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs @@ -0,0 +1,301 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.Linq; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Mappings; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Operations; +using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.D2D1.SourceGenerators.SyntaxRewriters; + +/// +/// A base type that processes C# source to convert to HLSL compliant code. +/// This class contains only the shared logic for all derived HLSL source rewriters. +/// +internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter +{ + /// + /// The instance with semantic info on the target syntax tree. + /// + protected readonly SemanticModelProvider SemanticModel; + + /// + /// The collection of discovered custom types. + /// + protected readonly ICollection DiscoveredTypes; + + /// + /// The collection of discovered constant definitions. + /// + protected readonly IDictionary ConstantDefinitions; + + /// + /// The collection of produced instances. + /// + protected readonly ImmutableArray.Builder Diagnostics; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance for the target syntax tree. + /// The set of discovered custom types. + /// The collection of discovered constant definitions. + /// The collection of produced instances. + protected HlslSourceRewriter( + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary constantDefinitions, + ImmutableArray.Builder diagnostics) + { + SemanticModel = semanticModel; + DiscoveredTypes = discoveredTypes; + ConstantDefinitions = constantDefinitions; + Diagnostics = diagnostics; + } + + /// + public override SyntaxNode VisitCastExpression(CastExpressionSyntax node) + { + var updatedNode = (CastExpressionSyntax)base.VisitCastExpression(node)!; + + return updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); + } + + /// + public override SyntaxNode? VisitVariableDeclaration(VariableDeclarationSyntax node) + { + var updatedNode = (VariableDeclarationSyntax)base.VisitVariableDeclaration(node)!; + + if (SemanticModel.For(node).GetTypeInfo(node.Type).Type is ITypeSymbol { IsUnmanagedType: false } type) + { + Diagnostics.Add(InvalidObjectDeclaration, node, type); + } + + // If var is used, replace it with the explicit type + if (updatedNode.Type is IdentifierNameSyntax { IsVar: true }) + { + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); + } + + return updatedNode; + } + + /// + public override SyntaxNode VisitObjectCreationExpression(ObjectCreationExpressionSyntax node) + { + var updatedNode = (ObjectCreationExpressionSyntax)base.VisitObjectCreationExpression(node)!; + + if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type) + { + Diagnostics.Add(InvalidObjectCreationExpression, node, type); + } + + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node, SemanticModel.For(node), DiscoveredTypes); + + // New objects use the default HLSL cast syntax, eg. (float4)0 + if (updatedNode.ArgumentList!.Arguments.Count == 0) + { + return CastExpression(updatedNode.Type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); + } + + // Add explicit casts for matrix constructors to help the overload resolution + if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol matrixType && + HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName())) + { + for (int i = 0; i < node.ArgumentList!.Arguments.Count; i++) + { + IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.For(node).GetOperation(node.ArgumentList.Arguments[i])!; + INamedTypeSymbol elementType = (INamedTypeSymbol)argumentOperation.Parameter!.Type; + + updatedNode = updatedNode.ReplaceNode( + updatedNode.ArgumentList!.Arguments[i].Expression, + CastExpression(IdentifierName(HlslKnownTypes.GetMappedName(elementType)), updatedNode.ArgumentList.Arguments[i].Expression)); + } + } + + return InvocationExpression(updatedNode.Type, updatedNode.ArgumentList!); + } + + /// + public override SyntaxNode VisitImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node) + { + var updatedNode = (ImplicitObjectCreationExpressionSyntax)base.VisitImplicitObjectCreationExpression(node)!; + + if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type) + { + Diagnostics.Add(InvalidObjectCreationExpression, node, type); + } + + TypeSyntax explicitType = IdentifierName("").ReplaceAndTrackType(node, SemanticModel.For(node), DiscoveredTypes); + + // Mutate the syntax like with explicit object creation expressions + if (updatedNode.ArgumentList!.Arguments.Count == 0) + { + return CastExpression(explicitType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); + } + + // Add explicit casts like with the explicit object creation expressions above + if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol matrixType && + HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName())) + { + for (int i = 0; i < node.ArgumentList.Arguments.Count; i++) + { + IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.For(node).GetOperation(node.ArgumentList.Arguments[i])!; + INamedTypeSymbol elementType = (INamedTypeSymbol)argumentOperation.Parameter!.Type; + + updatedNode = updatedNode.ReplaceNode( + updatedNode.ArgumentList.Arguments[i].Expression, + CastExpression(IdentifierName(HlslKnownTypes.GetMappedName(elementType)), updatedNode.ArgumentList.Arguments[i].Expression)); + } + } + + return InvocationExpression(explicitType, updatedNode.ArgumentList); + } + + /// + public override SyntaxNode VisitDefaultExpression(DefaultExpressionSyntax node) + { + var updatedNode = (DefaultExpressionSyntax)base.VisitDefaultExpression(node)!; + + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); + + // A default expression becomes (T)0 in HLSL + return CastExpression(updatedNode.Type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); + } + + /// + public override SyntaxNode? VisitLiteralExpression(LiteralExpressionSyntax node) + { + var updatedNode = (LiteralExpressionSyntax)base.VisitLiteralExpression(node)!; + + if (updatedNode.IsKind(SyntaxKind.DefaultLiteralExpression)) + { + TypeSyntax type = node.TrackType(SemanticModel.For(node), DiscoveredTypes); + + // Same HLSL-style expression in the form (T)0 + return CastExpression(type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); + } + else if (updatedNode.IsKind(SyntaxKind.NumericLiteralExpression) && + SemanticModel.For(node).GetOperation(node) is ILiteralOperation operation && + operation.Type is INamedTypeSymbol type) + { + // If the expression is a literal floating point value, we need to ensure the proper suffixes are + // used in the HLSL representation. Floating point values accept either f or F, but they don't work + // when the literal doesn't contain a decimal point. Since 32 bit floating point values are the default + // in HLSL, we can remove the suffix entirely. As for 64 bit values, we simply use the 'L' suffix. + if (type.GetFullMetadataName().Equals(typeof(float).FullName)) + { + string literal = updatedNode.Token.ValueText; + + // If the numeric literal is neither a decimal nor an exponential, add the ".0" suffix + if (literal.IndexOfAny(new[] { '.', 'E' }) == -1) + { + literal += ".0"; + } + + return updatedNode.WithToken(Literal(literal, 0f)); + } + else if (type.GetFullMetadataName().Equals(typeof(double).FullName)) + { + return updatedNode.WithToken(Literal(updatedNode.Token.ValueText + "L", 0d)); + } + } + else if (updatedNode.IsKind(SyntaxKind.StringLiteralExpression)) + { + Diagnostics.Add(StringLiteralExpression, node); + } + + return updatedNode; + } + + /// + public override SyntaxNode? VisitElementAccessExpression(ElementAccessExpressionSyntax node) + { + var updatedNode = (ElementAccessExpressionSyntax)base.VisitElementAccessExpression(node)!; + + if (SemanticModel.For(node).GetOperation(node) is IPropertyReferenceOperation operation) + { + string propertyName = operation.Property.GetFullMetadataName(); + + // If the current property is a swizzled matrix indexer, ensure all the arguments are constants, and rewrite + // the property access to the corresponding HLSL syntax. For instance, m[M11, M12] will become m._m00_m01. + if (HlslKnownProperties.IsKnownMatrixIndexer(propertyName)) + { + bool isValid = true; + + // Validate the arguments + foreach (ArgumentSyntax argument in node.ArgumentList.Arguments) + { + if (SemanticModel.For(node).GetOperation(argument.Expression) is not IFieldReferenceOperation fieldReference || + !HlslKnownProperties.IsKnownMatrixIndex(fieldReference.Field.GetFullMetadataName())) + { + Diagnostics.Add(NonConstantMatrixSwizzledIndex, argument); + + isValid = false; + } + } + + if (isValid) + { + // Rewrite the indexer as a property access + string hlslPropertyName = string.Join("", + from argument in node.ArgumentList.Arguments + let fieldReference = (IFieldReferenceOperation)SemanticModel.For(node).GetOperation(argument.Expression)! + let fieldName = fieldReference.Field.Name + let row = (char)(fieldName[1] - 1) + let column = (char)(fieldName[2] - 1) + select $"_m{row}{column}"); + + return MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + updatedNode.Expression, + IdentifierName(hlslPropertyName)); + } + } + } + + return updatedNode; + } + + /// + public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node) + { + var updatedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node)!; + + if (SemanticModel.For(node).GetOperation(node) is IFieldReferenceOperation operation && + operation.Field.IsConst && + operation.Type!.TypeKind != TypeKind.Enum) + { + ConstantDefinitions[operation.Field] = ((IFormattable)operation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture); + + var ownerTypeName = ((INamedTypeSymbol)operation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); + var constantName = $"__{ownerTypeName}__{operation.Field.Name}"; + + return IdentifierName(constantName); + } + + return updatedNode; + } + + /// + public override SyntaxToken VisitToken(SyntaxToken token) + { + SyntaxToken updatedToken = base.VisitToken(token); + + // Replace all identifier tokens when needed, to avoid colliding with HLSL keywords + if (updatedToken.IsKind(SyntaxKind.IdentifierToken) && + HlslKnownKeywords.TryGetMappedName(updatedToken.Text, out string? mapped)) + { + return ParseToken(mapped!); + } + + return updatedToken.WithoutTrivia(); + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs new file mode 100644 index 00000000..b519066b --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -0,0 +1,350 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.Linq; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Mappings; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Operations; +using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.D2D1.SourceGenerators.SyntaxRewriters; + +/// +/// A custom type that processes C# methods to convert to HLSL compliant code. +/// +internal sealed class ShaderSourceRewriter : HlslSourceRewriter +{ + /// + /// The type symbol for the shader type. + /// + private readonly INamedTypeSymbol? shaderType; + + /// + /// The collection of discovered static methods. + /// + private readonly IDictionary staticMethods; + + /// + /// The collection of processed local functions in the current tree. + /// + private readonly Dictionary localFunctions; + + /// + /// The list of implicit variables to declare at the start of the body. + /// + private readonly List implicitVariables; + + /// + /// The current tree being visited. + /// + private MethodDeclarationSyntax? currentMethod; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The type symbol for the shader type. + /// The instance for the target syntax tree. + /// The set of discovered custom types. + /// The set of discovered and processed static methods. + /// The collection of discovered constant definitions. + /// The collection of produced instances. + public ShaderSourceRewriter( + INamedTypeSymbol shaderType, + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary staticMethods, + IDictionary constantDefinitions, + ImmutableArray.Builder diagnostics) + : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) + { + this.shaderType = shaderType; + this.staticMethods = staticMethods; + this.localFunctions = new(); + this.implicitVariables = new(); + } + + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance for the target syntax tree. + /// The set of discovered custom types. + /// The set of discovered and processed static methods. + /// The collection of discovered constant definitions. + /// The collection of produced instances. + public ShaderSourceRewriter( + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary staticMethods, + IDictionary constantDefinitions, + ImmutableArray.Builder diagnostics) + : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) + { + this.staticMethods = staticMethods; + this.implicitVariables = new(); + this.localFunctions = new(); + } + + /// + /// Gets the collection of processed local functions in the current tree. + /// + public IReadOnlyDictionary LocalFunctions => this.localFunctions; + + /// + public MethodDeclarationSyntax? Visit(MethodDeclarationSyntax? node) + { + this.currentMethod = node; + + var updatedNode = (MethodDeclarationSyntax?)base.Visit(node)!; + + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel.For(node), DiscoveredTypes); + + if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword))) + { + Diagnostics.Add(AsyncModifierOnMethodOrFunction, node); + } + + if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword))) + { + Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node); + } + + if (updatedNode is not null) + { + var implicitBlock = Block(this.implicitVariables.Select(static v => LocalDeclarationStatement(v)).ToArray()); + + // Add the tracked implicit declarations (at the start of the body) + updatedNode = updatedNode.WithBody(implicitBlock).AddBodyStatements(updatedNode.Body!.Statements.ToArray()); + } + + return updatedNode; + } + + /// + public override SyntaxNode VisitParameter(ParameterSyntax node) + { + var updatedNode = (ParameterSyntax)base.VisitParameter(node)!; + + // Convert the C# parameter modifiers to the HLSL equivalent + SyntaxToken modifier = + node.Modifiers + .Where(static m => m.Kind() is SyntaxKind.OutKeyword or SyntaxKind.RefKeyword or SyntaxKind.InKeyword) + .Select(static m => m.Kind() switch + { + SyntaxKind.OutKeyword => m, + SyntaxKind.InKeyword => m, + SyntaxKind.RefKeyword => ParseToken("inout"), + _ => Token(SyntaxKind.None) + }).FirstOrDefault(); + + return updatedNode + .WithAttributeLists(default) + .ReplaceAndTrackType(updatedNode.Type!, node.Type!, SemanticModel.For(node), DiscoveredTypes) + .WithModifiers(TokenList(modifier)); + } + + /// + public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) + { + var updatedNode = ((LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node)!); + + if (SemanticModel.For(node).GetOperation(node) is IOperation { Kind: OperationKind.UsingDeclaration }) + { + Diagnostics.Add(UsingStatementOrDeclaration, node); + } + + return updatedNode.ReplaceAndTrackType(updatedNode.Declaration.Type, node.Declaration.Type, SemanticModel.For(node), DiscoveredTypes); + } + + /// + public override SyntaxNode? VisitDeclarationExpression(DeclarationExpressionSyntax node) + { + var updatedNode = (DeclarationExpressionSyntax)base.VisitDeclarationExpression(node)!; + + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); + + // Add the variable to the list of implicit declarations + this.implicitVariables.Add(VariableDeclaration(updatedNode.Type).AddVariables(VariableDeclarator(updatedNode.Designation.ToString()))); + + return IdentifierName(updatedNode.Designation.ToString()); + } + + /// + public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node) + { + return + ((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!) + .WithBlockBody() + .WithoutAccessibilityModifiers() + .WithAttributeLists(List()); + } + + /// + public override SyntaxNode? VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) + { + var updatedNode = + ((LocalFunctionStatementSyntax)base.VisitLocalFunctionStatement(node)!) + .WithBlockBody() + .WithAttributeLists(List()) + .WithIdentifier(Identifier($"__{this.currentMethod!.Identifier.Text}__{node.Identifier.Text}")); + + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel.For(node), DiscoveredTypes); + + if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword))) + { + Diagnostics.Add(AsyncModifierOnMethodOrFunction, node); + } + + if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword))) + { + Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node); + } + + // HLSL doesn't support local functions, so we first process them as usual and then remove + // them from the current syntax tree completely. These will be added to the shader source + // as external static method with a special name to avoid conflicts with other methods. + // The name will simply be in the format: "____". + this.localFunctions.Add(updatedNode.Identifier.Text, updatedNode); + + return null; + } + + /// + public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node) + { + var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!; + + if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) && + SemanticModel.For(node).GetOperation(node) is IMemberReferenceOperation operation) + { + if (operation is IFieldReferenceOperation fieldOperation) + { + // If the member access is a constant, track it and replace the tree with the processed constant name + if (fieldOperation.Field.IsConst && + fieldOperation.Type!.TypeKind != TypeKind.Enum) + { + if (HlslKnownFields.TryGetMappedName(fieldOperation.Member.ToDisplayString(), out string? constantLiteral)) + { + return ParseExpression(constantLiteral!); + } + + ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture); + + var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); + var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}"; + + return IdentifierName(constantName); + } + + // If the member access is a this. access, rewrite it to strip "this." + if (node.Expression.IsKind(SyntaxKind.ThisExpression)) + { + return node.Name; + } + } + + // If the current member access is a field or property access, check the lookup table + // to see if the member should be rewritten for HLSL compliance, and rewrite if needed. + if (HlslKnownProperties.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping)) + { + // Static and instance members are handled differently, with static members being + // converted into a literal expression, and instance getting an updated identifier. + // For instance, consider these three cases: + // - Vector3.One (static) => float3(1.0f, 1.0f, 1.0f) + // - ThreadIds.X (custom) => ThreadIds.x + // - uint3.X (instance) => [arg].x + return operation.Member.IsStatic switch + { + true => ParseExpression(mapping!), + false => updatedNode.WithName(IdentifierName(mapping!)) + }; + } + } + + return updatedNode; + } + + /// + public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node) + { + var updatedNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!; + + if (SemanticModel.For(node).GetOperation(node) is IInvocationOperation operation && + operation.TargetMethod is IMethodSymbol method && + method.IsStatic) + { + // If the invocation consists of invoking a static method that has a direct + // mapping to HLSL, rewrite the expression in the current invocation node. + // For instance: Math.Abs(expr) => abs(expr). + if (HlslKnownMethods.TryGetMappedName(method.GetFullMetadataName(), out string? mapping)) + { + return updatedNode.WithExpression(ParseExpression(mapping!)); + } + + // Update the name if the target is a local function. The exact schema for the + // updated name is detailed in the override handling the local function statement. + if (method.MethodKind == MethodKind.LocalFunction) + { + var functionIdentifier = $"__{this.currentMethod!.Identifier.Text}__{method.Name}"; + + return updatedNode.WithExpression(ParseExpression(functionIdentifier)); + } + + // If the method is an external static method, import and rewrite it as well. + // This assumes that the target method is actually part of the same compilation. + // We need to check the declaring type to avoid rewriting static methods in the shader + // type as well, as they will be processed by the generator in a different path. + if (!SymbolEqualityComparer.Default.Equals(this.shaderType, method.ContainingType)) + { + var methodIdentifier = method.GetFullMetadataName().ToHlslIdentifierName(); + + if (!this.staticMethods.ContainsKey(method)) + { + if (method.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is not MethodDeclarationSyntax methodNode) + { + Diagnostics.Add(InvalidMethodCall, node, method); + + return updatedNode; + } + + ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Diagnostics); + MethodDeclarationSyntax processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace(eol: "\n").WithoutTrivia(); + + this.staticMethods.Add(method, processedMethod.WithIdentifier(Identifier(methodIdentifier))); + } + + return updatedNode.WithExpression(ParseExpression(methodIdentifier)); + } + } + + return updatedNode; + } + + /// + public override SyntaxNode? VisitArgument(ArgumentSyntax node) + { + var updatedNode = (ArgumentSyntax)base.VisitArgument(node)!; + + // Strip the ref keywords from arguments + updatedNode = updatedNode.WithRefKindKeyword(Token(SyntaxKind.None)); + + // Track and rewrite the discarded declaration + if (SemanticModel.For(node).GetOperation(node.Expression) is IDiscardOperation operation) + { + TypeSyntax typeSyntax = ParseTypeName(HlslKnownTypes.TrackType(operation.Type!, DiscoveredTypes)); + string identifier = $"__implicit{this.implicitVariables.Count}"; + + // Add the variable to the list of implicit declarations + this.implicitVariables.Add(VariableDeclaration(typeSyntax).AddVariables(VariableDeclarator(identifier))); + + return updatedNode.WithExpression(IdentifierName(identifier)); + } + + return updatedNode; + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs new file mode 100644 index 00000000..56623724 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs @@ -0,0 +1,116 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Mappings; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Operations; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.D2D1.SourceGenerators.SyntaxRewriters; + +/// +/// A custom type that processes C# static field to convert to HLSL static fields (possibly constant). +/// +internal sealed class StaticFieldRewriter : HlslSourceRewriter +{ + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance for the target syntax tree. + /// The set of discovered custom types. + /// The collection of discovered constant definitions. + /// The collection of produced instances. + public StaticFieldRewriter( + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary constantDefinitions, + ImmutableArray.Builder diagnostics) + : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) + { + } + + /// + public ExpressionSyntax? Visit(VariableDeclaratorSyntax? node) + { + if (node?.Initializer is EqualsValueClauseSyntax fieldInitializer) + { + return ((EqualsValueClauseSyntax)Visit(fieldInitializer))!.Value; + } + + return null; + } + + /// + public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node) + { + var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!; + + if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) && + SemanticModel.For(node).GetOperation(node) is IMemberReferenceOperation operation) + { + // Track and replace constants + if (operation is IFieldReferenceOperation fieldOperation && + fieldOperation.Field.IsConst && + fieldOperation.Type!.TypeKind != TypeKind.Enum) + { + if (HlslKnownFields.TryGetMappedName(fieldOperation.Member.ToDisplayString(), out string? constantLiteral)) + { + return ParseExpression(constantLiteral!); + } + + ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture); + + var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); + var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}"; + + return IdentifierName(constantName); + } + + if (HlslKnownProperties.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping)) + { + // Rewrite static and instance mapped members + return operation.Member.IsStatic switch + { + true => ParseExpression(mapping!), + false => updatedNode.WithName(IdentifierName(mapping!)) + }; + } + } + + return updatedNode; + } + + /// + public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node) + { + var updatedNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!; + + if (SemanticModel.For(node).GetOperation(node) is IInvocationOperation operation && + operation.TargetMethod is IMethodSymbol method && + method.IsStatic) + { + // Rewrite HLSL intrinsic methods + if (HlslKnownMethods.TryGetMappedName(method.GetFullMetadataName(), out string? mapping)) + { + return updatedNode.WithExpression(ParseExpression(mapping!)); + } + } + + return updatedNode; + } + + /// + public override SyntaxNode? VisitArgument(ArgumentSyntax node) + { + var updatedNode = (ArgumentSyntax)base.VisitArgument(node)!; + + updatedNode = updatedNode.WithRefKindKeyword(Token(SyntaxKind.None)); + + return updatedNode; + } +} diff --git a/src/ComputeSharp.D2D1/Attributes/D2DEmbeddedBytecodeAttribute.cs b/src/ComputeSharp.D2D1/Attributes/D2DEmbeddedBytecodeAttribute.cs new file mode 100644 index 00000000..ab9ab4c7 --- /dev/null +++ b/src/ComputeSharp.D2D1/Attributes/D2DEmbeddedBytecodeAttribute.cs @@ -0,0 +1,52 @@ +using System; +#if !SOURCE_GENERATOR +using ComputeSharp.D2D1.Helpers; +#endif + +namespace ComputeSharp.D2D1; + +/// +/// An attribute that indicates that a given D2D1 shader should be precompiled at build time and embedded +/// directly into the containing assembly as static bytecode, to avoid compiling it at runtime. +/// +/// This attribute can be used to annotate shader types as follows: +/// +/// // A compute shader that is dispatched on a target buffer +/// [D2DEmbeddedBytecode(D2D1ShaderProfile.PixelShader50)] +/// struct MyShader : ID2D1PixelShader +/// { +/// } +/// +/// +/// +/// +/// The runtime compilation will automatically be skipped if the shader bytecode is then retrieved using a matching profile, +/// otherwise the usual runtime compilation will be used as fallback (or an exception will be thrown, depending on the API). +/// +[AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)] +public sealed class D2DEmbeddedBytecodeAttribute : Attribute +{ + /// + /// Creates a new instance with the specified parameters. + /// + /// The target shader profile to use to compile the shader. + public D2DEmbeddedBytecodeAttribute(D2D1ShaderProfile shaderProfile) + { +#if !SOURCE_GENERATOR + ShaderProfile = shaderProfile switch + { + D2D1ShaderProfile.PixelShader40 or + D2D1ShaderProfile.PixelShader40Level91 or + D2D1ShaderProfile.PixelShader40Level93 or + D2D1ShaderProfile.PixelShader41 or + D2D1ShaderProfile.PixelShader50 => shaderProfile, + _ => ThrowHelper.ThrowArgumentException(nameof(shaderProfile), "Invalid shader profile value.") + }; +#endif + } + + /// + /// Gets the number of threads in each thread group for the X axis + /// + public D2D1ShaderProfile ShaderProfile { get; } +} diff --git a/src/ComputeSharp.D2D1/Attributes/D2DInputComplexAttribute.cs b/src/ComputeSharp.D2D1/Attributes/D2DInputComplexAttribute.cs new file mode 100644 index 00000000..59f8188b --- /dev/null +++ b/src/ComputeSharp.D2D1/Attributes/D2DInputComplexAttribute.cs @@ -0,0 +1,28 @@ +using System; + +namespace ComputeSharp.D2D1; + +/// +/// An attribute for a D2D1 shader indicating that an input resource at a specified index uses complex sampling. +/// This attribute is optional, and not using it will cause inputs to default to complex sampling as well. +/// +/// +/// This attribute directly maps to #define D2D_INPUT<N>_COMPLEX. +/// For more info, see . +[AttributeUsage(AttributeTargets.Struct, AllowMultiple = true)] +public sealed class D2DInputComplexAttribute : Attribute +{ + /// + /// Creates a new instance of the type with the specified arguments. + /// + /// The index of the resource to declare as using complex sampling. + public D2DInputComplexAttribute(int index) + { + Index = index; + } + + /// + /// Gets the index of the resource declared as using complex sampling. + /// + public int Index { get; } +} diff --git a/src/ComputeSharp.D2D1/Attributes/D2DInputCountAttribute.cs b/src/ComputeSharp.D2D1/Attributes/D2DInputCountAttribute.cs new file mode 100644 index 00000000..e578bf23 --- /dev/null +++ b/src/ComputeSharp.D2D1/Attributes/D2DInputCountAttribute.cs @@ -0,0 +1,28 @@ +using System; + +namespace ComputeSharp.D2D1; + +/// +/// An attribute for a D2D1 shader indicating the number of texture inputs for the shader. +/// Using this attribute is mandatory when defining a D2D1 shader. +/// +/// +/// This attribute directly maps to #define D2D_INPUT_COUNT <N>. +/// For more info, see . +[AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)] +public sealed class D2DInputCountAttribute : Attribute +{ + /// + /// Creates a new instance of the type with the specified arguments. + /// + /// The number of texture inputs for the shader. + public D2DInputCountAttribute(int count) + { + Count = count; + } + + /// + /// Gets the number of texture inputs for the shader. + /// + public int Count { get; } +} diff --git a/src/ComputeSharp.D2D1/Attributes/D2DInputSimpleAttribute.cs b/src/ComputeSharp.D2D1/Attributes/D2DInputSimpleAttribute.cs new file mode 100644 index 00000000..7a23e2ac --- /dev/null +++ b/src/ComputeSharp.D2D1/Attributes/D2DInputSimpleAttribute.cs @@ -0,0 +1,28 @@ +using System; + +namespace ComputeSharp.D2D1; + +/// +/// An attribute for a D2D1 shader indicating that an input resource at a specified index uses simple +/// sampling. This attribute is optional, and not using it will cause inputs to default to complex sampling. +/// +/// +/// This attribute directly maps to #define D2D_INPUT<N>_SIMPLE. +/// For more info, see . +[AttributeUsage(AttributeTargets.Struct, AllowMultiple = true)] +public sealed class D2DInputSimpleAttribute : Attribute +{ + /// + /// Creates a new instance of the type with the specified arguments. + /// + /// The index of the resource to declare as using simple sampling. + public D2DInputSimpleAttribute(int index) + { + Index = index; + } + + /// + /// Gets the index of the resource declared as using simple sampling. + /// + public int Index { get; } +} diff --git a/src/ComputeSharp.D2D1/Attributes/D2DRequiresScenePositionAttribute.cs b/src/ComputeSharp.D2D1/Attributes/D2DRequiresScenePositionAttribute.cs new file mode 100644 index 00000000..f61dbc35 --- /dev/null +++ b/src/ComputeSharp.D2D1/Attributes/D2DRequiresScenePositionAttribute.cs @@ -0,0 +1,16 @@ +using System; + +namespace ComputeSharp.D2D1; + +/// +/// An attribute for a D2D1 shader indicating that the shader function calls helper methods that use the scene position +/// value (that is, ). This parameter should only be included when necessary, since +/// only one function per linked shader can utilize this parameter. Defining this value is optional. +/// +/// +/// This attribute directly maps to #define D2D_REQUIRES_SCENE_POSITION. +/// For more info, see . +[AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)] +public sealed class D2DRequiresScenePositionAttribute : Attribute +{ +} diff --git a/src/ComputeSharp.D2D1/Attributes/Profiles/D2D1ShaderProfile.cs b/src/ComputeSharp.D2D1/Attributes/Profiles/D2D1ShaderProfile.cs new file mode 100644 index 00000000..2580c5d2 --- /dev/null +++ b/src/ComputeSharp.D2D1/Attributes/Profiles/D2D1ShaderProfile.cs @@ -0,0 +1,69 @@ +namespace ComputeSharp.D2D1; + +/// +/// A to be used with to indicate the shader profile to use to precompile a shader. +/// +public enum D2D1ShaderProfile +{ + /// + /// Indicates a D2D1 pixel shader compiled for Direct3D 9.1 feature level. + /// + /// This has the following features: + /// + /// 64 arithmetic and 32 texture instructions. + /// 12 temporary registers. + /// 4 levels of dependent reads. + /// + /// + /// + /// + /// For more info, see . + /// + PixelShader40Level91, + + /// + /// Indicates a D2D1 pixel shader compiled for Direct3D 9.3 feature level. + /// + /// This has the following features: + /// + /// 512 instructions. + /// 32 temporary registers. + /// Static flow control (max depth of 4). + /// Dynamic flow control (max depth of 24). + /// D3DPS20CAPS_ARBITRARYSWIZZLE. + /// D3DPS20CAPS_GRADIENTINSTRUCTIONS. + /// D3DPS20CAPS_PREDICATION. + /// D3DPS20CAPS_NODEPENDENTREADLIMIT. + /// D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT. + /// + /// + /// + /// + /// For more info, see . + /// + PixelShader40Level93, + + /// + /// Indicates a D2D1 pixel shader compiled for Direct3D 10.0 feature level. + /// + /// + /// For more info, see . + /// + PixelShader40, + + /// + /// Indicates a D2D1 pixel shader compiled for Direct3D 10.1 feature level. + /// + /// + /// For more info, see . + /// + PixelShader41, + + /// + /// Indicates a D2D1 pixel shader compiled for Direct3D 11.0 and 11.1 feature levels. + /// + /// + /// For more info, see . + /// + PixelShader50 +} diff --git a/src/ComputeSharp.D2D1/ComputeSharp.D2D1.csproj b/src/ComputeSharp.D2D1/ComputeSharp.D2D1.csproj new file mode 100644 index 00000000..653a3a30 --- /dev/null +++ b/src/ComputeSharp.D2D1/ComputeSharp.D2D1.csproj @@ -0,0 +1,35 @@ + + + netstandard2.0;net6.0 + bin\Release + ComputeSharp.D2D1.xml + + + + + + + + + + + + + + + + + + + + + true + true + + + + + + + + diff --git a/src/ComputeSharp.D2D1/ComputeSharp.D2D1.targets b/src/ComputeSharp.D2D1/ComputeSharp.D2D1.targets new file mode 100644 index 00000000..7db216b0 --- /dev/null +++ b/src/ComputeSharp.D2D1/ComputeSharp.D2D1.targets @@ -0,0 +1,56 @@ + + + + + + <_ComputeSharpAnalyzer Include="@(Analyzer)" Condition="'%(Analyzer.NuGetPackageId)' == 'ComputeSharp.D2D1'" /> + + + + + + + + + + + + + + + @(CurrentCompilerAssemblyIdentity->'%(Version)') + + + true + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ComputeSharp.D2D1/Extensions/ComPtrExtensions.cs b/src/ComputeSharp.D2D1/Extensions/ComPtrExtensions.cs new file mode 100644 index 00000000..ef82e319 --- /dev/null +++ b/src/ComputeSharp.D2D1/Extensions/ComPtrExtensions.cs @@ -0,0 +1,42 @@ +using System.Runtime.CompilerServices; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.D2D1.Extensions; + +/// +/// Helper methods for working with the type. +/// +/// Trimmed down version of the same file in ComputeSharp. +internal static class ComPtrExtensions +{ + /// + /// Gets the address of the current instance as a raw double pointer. + /// + /// The type to wrap in the current instance. + /// The input instance to get the address for. + /// The raw pointer to the input instance. + /// This method is only valid when the current instance is on the stack or pinned. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void** GetVoidAddressOf(this in ComPtr ptr) + where T : unmanaged + { + return (void**)Unsafe.AsPointer(ref Unsafe.AsRef(in ptr)); + } + + /// + /// Moves the current instance and resets it without releasing the reference. + /// + /// The type to wrap in the current instance. + /// The input instance to move. + /// The moved instance. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe ComPtr Move(this in ComPtr ptr) + where T : unmanaged + { + ComPtr copy = default; + + Unsafe.AsRef(in ptr).Swap(ref copy); + + return copy; + } +} diff --git a/src/ComputeSharp.D2D1/Extensions/HResultExtensions.cs b/src/ComputeSharp.D2D1/Extensions/HResultExtensions.cs new file mode 100644 index 00000000..1d5ef42c --- /dev/null +++ b/src/ComputeSharp.D2D1/Extensions/HResultExtensions.cs @@ -0,0 +1,53 @@ +using System.ComponentModel; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.D2D1.Extensions; + +/// +/// Helper methods to efficiently throw exceptions. +/// +/// Trimmed down version of the same file in ComputeSharp. +[DebuggerStepThrough] +internal static class HResultExtensions +{ + /// + /// Throws a if represents an error. + /// + /// The input to check. + /// Thrown if represents an error. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Assert(this HRESULT result) + { + if ((int)result < 0) + { + ThrowWin32Exception(result); + } + } + + /// + /// Throws a if represents an error. + /// + /// The input to check. + /// Thrown if represents an error. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Assert(this int result) + { + if (result < 0) + { + ThrowWin32Exception(result); + } + } + + /// + /// Throws a . + /// + /// The input return code. + [DoesNotReturn] + private static void ThrowWin32Exception(int result) + { + throw new Win32Exception(result); + } +} diff --git a/src/ComputeSharp.D2D1/Extensions/RECTExtensions.cs b/src/ComputeSharp.D2D1/Extensions/RECTExtensions.cs new file mode 100644 index 00000000..792b7374 --- /dev/null +++ b/src/ComputeSharp.D2D1/Extensions/RECTExtensions.cs @@ -0,0 +1,78 @@ +using System.Drawing; +using System.Runtime.CompilerServices; +using TerraFX.Interop.Windows; +#if NET6_0_OR_GREATER +using Math = System.Math; +#else +using Math = ComputeSharp.D2D1.NetStandard.System.Math; +#endif + +namespace ComputeSharp.D2D1.Extensions; + +/// +/// Helper methods for and . +/// +internal static class RECTExtensions +{ + /// + /// Modifies a target instance to be a D2D1 infinite rectangle. + /// + /// The target instance to modify. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void MakeD2D1Infinite(this ref RECT rect) + { + rect.left = int.MinValue; + rect.top = int.MinValue; + rect.right = int.MaxValue; + rect.bottom = int.MaxValue; + } + + /// + /// Creates a from a value. + /// + /// The input value. + /// The resulting value. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Rectangle ToRectangle(this in RECT rect) + { + int left = Math.Clamp(rect.left, int.MinValue / 2, int.MaxValue / 2); + int top = Math.Clamp(rect.top, int.MinValue / 2, int.MaxValue / 2); + int right = Math.Clamp(rect.right, int.MinValue / 2, int.MaxValue / 2); + int bottom = Math.Clamp(rect.bottom, int.MinValue / 2, int.MaxValue / 2); + + int minX = Math.Min(left, right); + int minY = Math.Min(top, bottom); + int maxX = Math.Max(left, right); + int maxY = Math.Max(top, bottom); + + return new(minX, minY, maxX - minX, maxY - minY); + } + + /// + /// Creates a from a value. + /// + /// The input value. + /// The resulting value. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static RECT ToRECT(this in Rectangle rectangle) + { + if (rectangle.IsD2D1Infinite()) + { + return new() + { + left = int.MinValue, + top = int.MinValue, + right = int.MaxValue, + bottom = int.MaxValue + }; + } + + return new() + { + left = rectangle.Left, + top = rectangle.Top, + right = rectangle.Right, + bottom = rectangle.Bottom + }; + } +} diff --git a/src/ComputeSharp.D2D1/Extensions/RectangleExtensions.cs b/src/ComputeSharp.D2D1/Extensions/RectangleExtensions.cs new file mode 100644 index 00000000..8826f625 --- /dev/null +++ b/src/ComputeSharp.D2D1/Extensions/RectangleExtensions.cs @@ -0,0 +1,39 @@ +using System.Drawing; +using System.Runtime.CompilerServices; + +namespace ComputeSharp.D2D1; + +/// +/// Helper methods for . +/// +public static class RectangleExtensions +{ + /// + /// Modifies a target instance to be a D2D1 infinite rectangle. + /// + /// The target instance to modify. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ToD2D1Infinite(this ref Rectangle rectangle) + { + rectangle = new Rectangle( + int.MinValue / 2, + int.MinValue / 2, + int.MaxValue, + int.MaxValue); + } + + /// + /// Checks whether a given instance represents a D2D1 infinite rectangle. + /// + /// The input instance to check. + /// Whether or not represents a D2D1 infinite rectangle. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsD2D1Infinite(this in Rectangle rectangle) + { + return rectangle == new Rectangle( + int.MinValue / 2, + int.MinValue / 2, + int.MaxValue, + int.MaxValue); + } +} diff --git a/src/ComputeSharp.D2D1/Helpers/ThrowHelper.cs b/src/ComputeSharp.D2D1/Helpers/ThrowHelper.cs new file mode 100644 index 00000000..012eca14 --- /dev/null +++ b/src/ComputeSharp.D2D1/Helpers/ThrowHelper.cs @@ -0,0 +1,69 @@ +using System; +using System.Diagnostics.CodeAnalysis; + +namespace ComputeSharp.D2D1.Helpers; + +/// +/// Helper methods to efficiently throw exceptions. +/// +internal static partial class ThrowHelper +{ + /// + /// Throws a new . + /// + /// The argument name. + /// The message to include in the exception. + /// Thrown with the specified parameters. + [DoesNotReturn] + public static void ThrowArgumentException(string? name, string? message) + { + throw new ArgumentException(message, name); + } + + /// + /// Throws a new . + /// + /// The type of expected result. + /// The argument name. + /// The message to include in the exception. + /// Thrown with the specified parameters. + /// This method always throws, so it actually never returns a value. + [DoesNotReturn] + public static T ThrowArgumentException(string? name, string? message) + { + throw new ArgumentException(message, name); + } + + /// + /// Throws a new . + /// + /// The argument name. + /// Thrown with the specified parameter. + [DoesNotReturn] + public static void ThrowArgumentOutOfRangeException(string? name) + { + throw new ArgumentOutOfRangeException(name); + } + + /// + /// Throws a new . + /// + /// The message to include in the exception. + /// Thrown with the specified parameter. + [DoesNotReturn] + public static void ThrowInvalidOperationException(string? message) + { + throw new InvalidOperationException(message); + } + + /// + /// Throws a new . + /// + /// The message to include in the exception. + /// Thrown with the specified parameter. + [DoesNotReturn] + public static void ThrowNotSupportedException(string? message) + { + throw new NotSupportedException(message); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Interfaces/ID2D1PixelShader.cs b/src/ComputeSharp.D2D1/Interfaces/ID2D1PixelShader.cs new file mode 100644 index 00000000..c748211a --- /dev/null +++ b/src/ComputeSharp.D2D1/Interfaces/ID2D1PixelShader.cs @@ -0,0 +1,17 @@ +using ComputeSharp.D2D1.__Internals; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1; + +/// +/// An representing a D2D1 pixel shader. +/// +public interface ID2D1PixelShader : ID2D1Shader +{ + /// + /// Executes the current pixel shader. + /// + /// The pixel value for the current invocation. + Float4 Execute(); +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Interfaces/ID2D1TransformMapper{T}.cs b/src/ComputeSharp.D2D1/Interfaces/ID2D1TransformMapper{T}.cs new file mode 100644 index 00000000..ef12cbe1 --- /dev/null +++ b/src/ComputeSharp.D2D1/Interfaces/ID2D1TransformMapper{T}.cs @@ -0,0 +1,80 @@ +using System; +using System.Drawing; + +namespace ComputeSharp.D2D1; + +/// +/// An providing support for custom, stateful draw transform mappings for shaders. +/// +public interface ID2D1TransformMapper + where T : unmanaged, ID2D1PixelShader +{ + /// + /// + /// Allows a transform to state how it would map a a set of sample rectangles on its input to an output rectangle. + /// + /// + /// This is effectively the inverse mapping of . + /// + /// + /// The input D2D1 pixel shader being executed on the current effect (this can be used to retrieve shader properties). + /// The input rectangles to be mapped to the output rectangle. This parameter is always equal to the input bounds. + /// The input rectangles to be mapped to the opaque output rectangle. + /// The output rectangle that maps to the corresponding input rectangle. + /// The output rectangle that maps to the corresponding opaque input rectangle. + /// + /// + /// Unlike and , this method is explicitly called by the renderer at + /// a determined place in its rendering algorithm. The transform implementation may change its state based on the input rectangles + /// and use this information to control its rendering information. This method is always called before the + /// and methods. + /// + /// + /// For more info, see . + /// + /// + void MapInputsToOutput( + in T shader, + ReadOnlySpan inputs, + ReadOnlySpan opaqueInputs, + out Rectangle output, + out Rectangle opaqueOutput); + + /// + /// Allows a transform to state how it would map a rectangle requested on its output to a set of sample rectangles on its input. + /// + /// The input D2D1 pixel shader being executed on the current effect (this can be used to retrieve shader properties). + /// The output rectangle from which the inputs must be mapped. + /// The corresponding set of inputs. The inputs will directly correspond to the transform inputs. + /// + /// + /// The transform implementation must regard this method as purely functional. It can base the mapped input and output rectangles on its + /// current state as specified by the encapsulating effect properties. However, it must not change its own state in response to this method + /// being invoked. The Direct2D renderer implementation reserves the right to call this method at any time and in any sequence. + /// + /// + /// For more info, see . + /// + /// + void MapOutputToInputs(in T shader, in Rectangle output, Span inputs); + + /// + /// Sets the input rectangles for this rendering pass into the transform. + /// + /// The input D2D1 pixel shader being executed on the current effect (this can be used to retrieve shader properties). + /// The index of the input rectangle. + /// The invalid input rectangle. + /// The output rectangle to which the input rectangle must be mapped. + /// + /// + /// The transform implementation must regard this method as purely functional. The transform implementation can base the mapped input rectangle on + /// the transform implementation's current state as specified by the encapsulating effect properties. But the transform implementation can't change + /// its own state in response to a call to . Direct2D can call this method at any time + /// and in any sequence following a call to . + /// + /// + /// For more info, see . + /// + /// + void MapInvalidOutput(in T shader, int inputIndex, Rectangle invalidInput, out Rectangle invalidOutput); +} diff --git a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1BytecodeLoader.cs b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1BytecodeLoader.cs new file mode 100644 index 00000000..1a20a785 --- /dev/null +++ b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1BytecodeLoader.cs @@ -0,0 +1,26 @@ +using System; +using System.ComponentModel; + +namespace ComputeSharp.D2D1.__Internals; + +/// +/// A base representing a bytecode loader for a D2D1 shader. +/// +[EditorBrowsable(EditorBrowsableState.Never)] +[Obsolete("This interface is not intended to be used directly by user code")] +public interface ID2D1BytecodeLoader +{ + /// + /// Loads a dynamic shader bytecode. + /// + /// An opaque handle to the shader bytecode. + /// Thrown if the shader has already been initialized or a precompiled bytecode was requested when not available. + void LoadDynamicBytecode(IntPtr handle); + + /// + /// Loads the embedded shader bytecode for the shader. + /// + /// The shader bytecode. + /// Thrown if the shader has already been initialized. + void LoadEmbeddedBytecode(ReadOnlySpan bytecode); +} diff --git a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1DispatchDataLoader.cs b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1DispatchDataLoader.cs new file mode 100644 index 00000000..447e3cc9 --- /dev/null +++ b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1DispatchDataLoader.cs @@ -0,0 +1,18 @@ +using System; +using System.ComponentModel; + +namespace ComputeSharp.D2D1.__Internals; + +/// +/// A base representing a data loader for a D2D1 shader being dispatched. +/// +[EditorBrowsable(EditorBrowsableState.Never)] +[Obsolete("This interface is not intended to be used directly by user code")] +public interface ID2D1DispatchDataLoader +{ + /// + /// Loads the captured values used by the D2D1 shader to be dispatched. + /// + /// The sequence of serialized captured values. + void LoadConstantBuffer(ReadOnlySpan data); +} diff --git a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs new file mode 100644 index 00000000..ef8f36db --- /dev/null +++ b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs @@ -0,0 +1,79 @@ +using System; +using System.ComponentModel; + +namespace ComputeSharp.D2D1.__Internals; + +/// +/// A base representing a given shader that can be dispatched. +/// +[EditorBrowsable(EditorBrowsableState.Never)] +[Obsolete("This interface is not intended to be used directly by user code")] +public interface ID2D1Shader +{ + /// + /// Initializes the current shader from a buffer with the serialized dispatch data. + /// + /// The input buffer with the serialized dispatch data. + /// The input buffer must be retrieved from . + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + void InitializeFromDispatchData(ReadOnlySpan data) +#if NET6_0_OR_GREATER + { + throw new NotImplementedException(); + } +#else + ; +#endif + + /// + /// Loads the dispatch data for the shader. + /// + /// The type of data loader being used. + /// The instance to use to load the data. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + void LoadDispatchData(ref TLoader loader) + where TLoader : struct, ID2D1DispatchDataLoader +#if NET6_0_OR_GREATER + { + throw new NotImplementedException(); + } +#else + ; +#endif + + /// + /// Builds the HLSL source code for the current shader instance. + /// + /// The resulting HLSL source. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + void BuildHlslSource(out string hlslSource) +#if NET6_0_OR_GREATER + { + throw new NotImplementedException(); + } +#else + ; +#endif + + /// + /// Loads the bytecode for the current shader. + /// + /// The type of bytecode loader being used. + /// The instance to use to load the bytecode. + /// The shader profile to use to get the shader bytecode (if , the precompiled shader will be used). + /// Thrown if a precompiled bytecode was requested ( is ), but it wasn't availablle. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be used directly by user code")] + void LoadBytecode(ref TLoader loader, D2D1ShaderProfile? shaderProfile) + where TLoader : struct, ID2D1BytecodeLoader +#if NET6_0_OR_GREATER + { + throw new NotImplementedException(); + } +#else + ; +#endif +} diff --git a/src/ComputeSharp.D2D1/Intrinsics/D2D.cs b/src/ComputeSharp.D2D1/Intrinsics/D2D.cs new file mode 100644 index 00000000..328e7dbd --- /dev/null +++ b/src/ComputeSharp.D2D1/Intrinsics/D2D.cs @@ -0,0 +1,67 @@ +using ComputeSharp.Core.Intrinsics.Attributes; +using ComputeSharp.Exceptions; + +namespace ComputeSharp.D2D1; + +/// +/// A that maps the supported HLSL intrinsic functions specifically for D2D1 shaders. +/// +/// For more info, see . +public static class D2D +{ + /// + /// Returns the color of the input texture at a specific index, for the curreent coordinate. + /// + /// The index of the input texture to get the input from. + /// The color from the target input at the current coordinate, in INPUTN format. + /// This method is only available for simple inputs. + [HlslIntrinsicName("D2DGetInput")] + public static Float4 GetInput(int index) => throw new InvalidExecutionContextException($"{typeof(D2D)}.{nameof(GetInput)}({typeof(int)})"); + + /// + /// Returns the coordinate of the input texture at a specific index. + /// + /// The index of the input texture to get the coordinate for. + /// The input coordinate, in TEXCOORDN format. + /// This method is only available for complex inputs. + [HlslIntrinsicName("D2DGetInputCoordinate")] + public static Float4 GetInputCoordinate(int index) => throw new InvalidExecutionContextException($"{typeof(D2D)}.{nameof(GetInputCoordinate)}({typeof(int)})"); + + /// + /// Returns the value of the current scene position. + /// + /// The current scene position, in SCENE_POSITION format. + /// This method is only available when is used on the shader type. + [HlslIntrinsicName("D2DGetScenePosition")] + public static Float4 GetScenePosition() => throw new InvalidExecutionContextException($"{typeof(D2D)}.{nameof(GetScenePosition)}()"); + + /// + /// Samples the input texture at a specified index and at a given position. + /// + /// The index of the input texture to sample. + /// The normalized coordinate to use to sample the texture. + /// The sampled value from the texture, in TEXCOORDN format. + /// This method is only available for complex inputs. + [HlslIntrinsicName("D2DSampleInput")] + public static Float4 SampleInput(int index, Float2 uv) => throw new InvalidExecutionContextException($"{typeof(D2D)}.{nameof(SampleInput)}({typeof(int)}, {typeof(Float2)})"); + + /// + /// Samples the input texturee at a specified index and at a given offset from the input coordinate. + /// + /// The index of the input texture to sample. + /// The normalized offset to use to sample the texture. + /// The sampled value from the texture, in TEXCOORDN format. + /// This method is only available for simple inputs. + [HlslIntrinsicName("D2DSampleInputAtOffset")] + public static Float4 SampleInputAtOffset(int index, Float2 offset) => throw new InvalidExecutionContextException($"{typeof(D2D)}.{nameof(SampleInputAtOffset)}({typeof(int)}, {typeof(Float2)})"); + + /// + /// Samples the input texture at a specified index and at an absolute scene position (not an input-relative position). + /// + /// The index of the input texture to sample. + /// The normalized coordinate to use to sample the texture. + /// The sampled value from the texture, in TEXCOORDN format. + /// This method is only available for complex inputs. + [HlslIntrinsicName("D2DSampleInputAtPosition")] + public static Float4 SampleInputAtPosition(int index, Float2 uv) => throw new InvalidExecutionContextException($"{typeof(D2D)}.{nameof(SampleInputAtPosition)}({typeof(int)}, {typeof(Float2)})"); +} diff --git a/src/ComputeSharp.D2D1/Properties/AssemblyInfo.cs b/src/ComputeSharp.D2D1/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..196f23c5 --- /dev/null +++ b/src/ComputeSharp.D2D1/Properties/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[module: SkipLocalsInit] \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1ByteArrayDispatchDataLoader.cs b/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1ByteArrayDispatchDataLoader.cs new file mode 100644 index 00000000..2b00632a --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1ByteArrayDispatchDataLoader.cs @@ -0,0 +1,36 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.D2D1.__Internals; +using TerraFX.Interop.DirectX; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.Shaders.Dispatching; + +/// +/// A data loader for D2D1 pixel shaders dispatched via . +/// +internal struct D2D1ByteArrayDispatchDataLoader : ID2D1DispatchDataLoader +{ + /// + /// The object in use. + /// + private byte[]? data; + + /// + /// Gets the resulting pixel shader constant buffer. + /// + /// A array with the constant buffer for the current shader. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public byte[] GetResultingDispatchData() + { + return this.data!; + } + + /// + public void LoadConstantBuffer(ReadOnlySpan data) + { + this.data = MemoryMarshal.AsBytes(data).ToArray(); + } +} diff --git a/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1DrawInfoDispatchDataLoader.cs b/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1DrawInfoDispatchDataLoader.cs new file mode 100644 index 00000000..be47d04c --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1DrawInfoDispatchDataLoader.cs @@ -0,0 +1,38 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.D2D1.__Internals; +using TerraFX.Interop.DirectX; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.Shaders.Dispatching; + +/// +/// A data loader for D2D1 pixel shaders dispatched via . +/// +internal readonly unsafe struct D2D1DrawInfoDispatchDataLoader : ID2D1DispatchDataLoader +{ + /// + /// The object in use. + /// + private readonly ID2D1DrawInfo* d2D1DrawInfo; + + /// + /// Creates a new instance. + /// + /// The object to use. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal D2D1DrawInfoDispatchDataLoader(ID2D1DrawInfo* d2D1DrawInfo) + { + this.d2D1DrawInfo = d2D1DrawInfo; + } + + /// + public void LoadConstantBuffer(ReadOnlySpan data) + { + this.d2D1DrawInfo->SetPixelShaderConstantBuffer( + buffer: (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(data)), + bufferCount: (uint)data.Length * sizeof(uint)); + } +} diff --git a/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1EffectDispatchDataLoader.cs b/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1EffectDispatchDataLoader.cs new file mode 100644 index 00000000..e5697042 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1EffectDispatchDataLoader.cs @@ -0,0 +1,41 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.D2D1.__Internals; +using ComputeSharp.D2D1.Extensions; +using TerraFX.Interop.DirectX; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.Shaders.Dispatching; + +/// +/// A data loader for D2D1 pixel shaders dispatched via . +/// +internal readonly unsafe struct D2D1EffectDispatchDataLoader : ID2D1DispatchDataLoader +{ + /// + /// The object in use. + /// + private readonly ID2D1Effect* d2D1Effect; + + /// + /// Creates a new instance. + /// + /// The object to use. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal D2D1EffectDispatchDataLoader(ID2D1Effect* d2D1Effect) + { + this.d2D1Effect = d2D1Effect; + } + + /// + public void LoadConstantBuffer(ReadOnlySpan data) + { + this.d2D1Effect->SetValue( + index: 0, + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_BLOB, + data: (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(data)), + dataSize: (uint)data.Length * sizeof(uint)).Assert(); + } +} diff --git a/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1ShaderBytecodeLoader.cs b/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1ShaderBytecodeLoader.cs new file mode 100644 index 00000000..0d0da779 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Dispatching/D2D1ShaderBytecodeLoader.cs @@ -0,0 +1,78 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.D2D1.__Internals; +using ComputeSharp.D2D1.Extensions; +using ComputeSharp.D2D1.Helpers; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.Shaders.Dispatching; + +/// +/// A bytecode loader for D2D1 shaders. +/// +internal unsafe struct D2D1ShaderBytecodeLoader : ID2D1BytecodeLoader +{ + /// + /// A pointer to the precompiled shader, if available. + /// + private byte* embeddedBytecodePtr; + + /// + /// The length of the precompiled shader buffer, if available. + /// + private int embeddedBytecodeSize; + + /// + /// The dynamically compiled shader bytecode blob, if available. + /// + private ComPtr d3DBlob; + + /// + /// Gets the resulting shader bytecode that was available. + /// + /// The precompiled bytecode, if available. + /// An with the shader bytecode, if dynamically compiled. + /// Either is empty, or the returned pointer is . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ComPtr GetResultingShaderBytecode(out ReadOnlySpan precompiledBytecode) + { + precompiledBytecode = new ReadOnlySpan(this.embeddedBytecodePtr, this.embeddedBytecodeSize); + + return this.d3DBlob.Move(); + } + + /// + public unsafe void LoadDynamicBytecode(IntPtr handle) + { + if (this.embeddedBytecodePtr is not null || + this.d3DBlob.Get() is not null) + { + ThrowHelper.ThrowInvalidOperationException("The shader has already been initialized."); + } + + if (handle == IntPtr.Zero) + { + ThrowHelper.ThrowNotSupportedException("Runtime shader compilation is not supported by the current configuration."); + } + + this.d3DBlob = new ComPtr((ID3DBlob*)handle); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void LoadEmbeddedBytecode(ReadOnlySpan bytecode) + { + if (this.embeddedBytecodePtr is not null || + this.d3DBlob.Get() is not null) + { + ThrowHelper.ThrowInvalidOperationException("The shader has already been initialized."); + } + + this.embeddedBytecodePtr = (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(bytecode)); + this.embeddedBytecodeSize = bytecode.Length; + } +} diff --git a/src/ComputeSharp.D2D1/Shaders/Exceptions/FxcCompilationException.cs b/src/ComputeSharp.D2D1/Shaders/Exceptions/FxcCompilationException.cs new file mode 100644 index 00000000..cdb5e2a3 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Exceptions/FxcCompilationException.cs @@ -0,0 +1,38 @@ +using System; +using System.Text; + +namespace ComputeSharp.D2D1.Exceptions; + +/// +/// A custom type that indicates when a shader compilation with the FXC compiler has failed. +/// +public sealed class FxcCompilationException : Exception +{ + /// + /// Creates a new instance. + /// + /// The error message produced by the DXC compiler. + internal FxcCompilationException(string error) + : base(GetExceptionMessage(error)) + { + } + + /// + /// Gets a formatted exception message for a given compilation error. + /// + /// The input compilatin error message from the FXC compiler. + /// A formatted error message for a new instance. + private static string GetExceptionMessage(string error) + { + StringBuilder builder = new(512); + + builder.AppendLine("The FXC compiler encountered one or more errors while trying to compile the shader:"); + builder.AppendLine(); + builder.AppendLine(error.Trim()); + builder.AppendLine(); + builder.AppendLine("Make sure to only be using supported features by checking the README file in the ComputeSharp repository: https://github.com/Sergio0694/ComputeSharp."); + builder.Append("If you're sure that your C# shader code is valid, please open an issue an include a working repro and this error message."); + + return builder.ToString(); + } +} diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriter.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriter.cs new file mode 100644 index 00000000..ebef74a0 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriter.cs @@ -0,0 +1,235 @@ +using System; +using System.Buffers; +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +#if !NET6_0_OR_GREATER +using ComputeSharp.D2D1.NetStandard.System.Text; +using BitOperations = ComputeSharp.D2D1.NetStandard.System.Buffers.BitOperations; +#endif + +namespace ComputeSharp.D2D1.Shaders.Interop.Buffers; + +/// +/// Represents a heap-based, array-backed output sink into which binary data can be written. +/// +internal ref struct ArrayPoolBinaryWriter +{ + /// + /// The default buffer size to use to expand empty arrays. + /// + public const int DefaultInitialBufferSize = 256; + + /// + /// The underlying array. + /// + private byte[]? array; + + /// + /// The starting offset within . + /// + private int index; + + /// + /// Initializes a new instance of the class. + /// + public ArrayPoolBinaryWriter(int capacity) + { + this.array = ArrayPool.Shared.Rent(capacity); + this.index = 0; + } + + /// + /// Gets the data written to the underlying buffer so far, as a . + /// + public ReadOnlySpan WrittenSpan + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + byte[]? array = this.array; + + if (array is null) + { + ThrowObjectDisposedException(); + } + + return array!.AsSpan(0, this.index); + } + } + + /// + /// Writes a value of type into the buffer. + /// + /// The type of value to write. + /// The value to write. + public unsafe void Write(in T value) + where T : unmanaged + { + Span span = GetSpan(sizeof(T)); + + MemoryMarshal.Write(span, ref Unsafe.AsRef(in value)); + + Advance(sizeof(T)); + } + + /// + /// Writes text as UTF8 bytes into the buffer. + /// + /// The text to write. + public unsafe void WriteAsUtf8(string text) + { + int maximumByteSize = Encoding.UTF8.GetMaxByteCount(text.Length); + + Span span = GetSpan(maximumByteSize); + + int writtenBytes = Encoding.UTF8.GetBytes(text.AsSpan(), span); + + Advance(writtenBytes); + } + + /// + /// Advances the current writer. + /// + /// The amount to advance. + /// Must be called after . + private void Advance(int count) + { + byte[]? array = this.array; + + if (array is null) + { + ThrowObjectDisposedException(); + } + + if (count < 0) + { + ThrowArgumentOutOfRangeExceptionForNegativeCount(); + } + + if (this.index > array!.Length - count) + { + ThrowArgumentExceptionForAdvancedTooFar(); + } + + this.index += count; + } + + /// + /// Gets a to write data to, with an optional minimum capacity. + /// + /// The capacity to request. + /// A to write data to. + private Span GetSpan(int sizeHint = 0) + { + CheckBufferAndEnsureCapacity(sizeHint); + + return this.array.AsSpan(this.index); + } + + /// + /// Ensures that has enough free space to contain a given number of new items. + /// + /// The minimum number of items to ensure space for in . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void CheckBufferAndEnsureCapacity(int sizeHint) + { + byte[]? array = this.array; + + if (array is null) + { + ThrowObjectDisposedException(); + } + + if (sizeHint < 0) + { + ThrowArgumentOutOfRangeExceptionForNegativeSizeHint(); + } + + if (sizeHint == 0) + { + sizeHint = 1; + } + + if (sizeHint > array!.Length - this.index) + { + ResizeBuffer(sizeHint); + } + } + + /// + /// Resizes to ensure it can fit the specified number of new items. + /// + /// The minimum number of items to ensure space for in . + [MethodImpl(MethodImplOptions.NoInlining)] + private void ResizeBuffer(int sizeHint) + { + uint minimumSize = (uint)this.index + (uint)sizeHint; + + // The ArrayPool class has a maximum threshold of 1024 * 1024 for the maximum length of + // pooled arrays, and once this is exceeded it will just allocate a new array every time + // of exactly the requested size. In that case, we manually round up the requested size to + // the nearest power of two, to ensure that repeated consecutive writes when the array in + // use is bigger than that threshold don't end up causing a resize every single time. + if (minimumSize > 1024 * 1024) + { + minimumSize = BitOperations.RoundUpToPowerOf2(minimumSize); + } + + byte[] newArray = ArrayPool.Shared.Rent((int)minimumSize); + + Buffer.BlockCopy(this.array!, 0, newArray, 0, this.index); + + ArrayPool.Shared.Return(this.array!); + + this.array = newArray; + } + + /// + public void Dispose() + { + byte[]? array = this.array; + + if (array is null) + { + return; + } + + this.array = null; + + ArrayPool.Shared.Return(array); + } + + /// + /// Throws an when the requested count is negative. + /// + private static void ThrowArgumentOutOfRangeExceptionForNegativeCount() + { + throw new ArgumentOutOfRangeException("count", "The count can't be a negative value."); + } + + /// + /// Throws an when the size hint is negative. + /// + private static void ThrowArgumentOutOfRangeExceptionForNegativeSizeHint() + { + throw new ArgumentOutOfRangeException("sizeHint", "The size hint can't be a negative value."); + } + + /// + /// Throws an when the requested count is negative. + /// + private static void ThrowArgumentExceptionForAdvancedTooFar() + { + throw new ArgumentException("The buffer writer has advanced too far."); + } + + /// + /// Throws an when is . + /// + private static void ThrowObjectDisposedException() + { + throw new ObjectDisposedException("The current buffer has already been disposed."); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/PinnedBufferMemoryManager.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/PinnedBufferMemoryManager.cs new file mode 100644 index 00000000..4fb3d71d --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/PinnedBufferMemoryManager.cs @@ -0,0 +1,60 @@ +using System; +using System.Buffers; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.D2D1.Helpers; + +namespace ComputeSharp.D2D1.Shaders.Interop.Buffers; + +/// +/// A custom that wraps a pinned memory buffer. +/// +internal sealed unsafe class PinnedBufferMemoryManager : MemoryManager +{ + /// + /// A pointer to the buffer. + /// + private readonly byte* buffer; + + /// + /// The length of the buffer. + /// + private readonly int length; + + /// + /// Initializes a new instance of the class with the specified parameters. + /// + /// A wrapping the input pinned buffer. + public PinnedBufferMemoryManager(ReadOnlySpan span) + { + this.buffer = (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(span)); + this.length = span.Length; + } + + /// + public override Span GetSpan() + { + return new(this.buffer, this.length); + } + + /// + public override unsafe MemoryHandle Pin(int elementIndex = 0) + { + if ((uint)elementIndex >= this.length) + { + ThrowHelper.ThrowArgumentOutOfRangeException(nameof(elementIndex)); + } + + return new(this.buffer + elementIndex); + } + + /// + public override void Unpin() + { + } + + /// + protected override void Dispose(bool disposing) + { + } +} diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1EffectRegistrationData.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1EffectRegistrationData.cs new file mode 100644 index 00000000..cba3bc9b --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1EffectRegistrationData.cs @@ -0,0 +1,301 @@ +using System; +using System.Runtime.InteropServices; +using System.Text; +using ComputeSharp.D2D1.Helpers; +#if !NET6_0_OR_GREATER +using ComputeSharp.D2D1.NetStandard.System.Text; +#endif + +namespace ComputeSharp.D2D1.Interop; + +/// +/// A helper type used to read and validate effect registration blobs produced +/// by . +/// +/// +/// +/// The values in a instance contain all necessary +/// information to register a new D2D1 effect by calling ID2D1Factory1::RegisterEffectFromString. +/// +/// +/// For more info, see . +/// +/// +public static class D2D1EffectRegistrationData +{ + /// + /// The containing type for deserialized version 1 registration blobs. + /// + public unsafe readonly struct V1 + { + /// + /// The blob id for V1 registration data. + /// + internal static readonly Guid BlobId = new(0xA1B4A55E, 0x4C78, 0x413F, 0xA2, 0xE6, 0x0A, 0x02, 0xE6, 0x0A, 0x76, 0x18); + + /// + /// Creates a new instance with the specified parameters. + /// + /// The effect class id. + /// The number of inputs for the effect. + /// The XML text that can be used to register the effect. + /// The values for the effect. + /// A pointer to the effect factory callback. + private V1( + Guid classId, + int numberOfInputs, + string propertyXml, + D2D1PropertyBinding[] propertyBindings, + nint effectFactory) + { + ClassId = classId; + NumberOfInputs = numberOfInputs; + PropertyXml = propertyXml; + PropertyBindings = propertyBindings; + EffectFactory = (void*)effectFactory; + } + + /// + /// Gets the id to use to register the effect. + /// + public Guid ClassId { get; } + + /// + /// Gets the number of inputs for the effect. + /// + public int NumberOfInputs { get; } + + /// + /// Gets the XML text with the effect description, that can be used to register it. + /// + public string PropertyXml { get; } + + /// + /// Gets the sequence of values for the effect. + /// + public ReadOnlyMemory PropertyBindings { get; } + + /// + /// Gets a callback to an effect factory (a ). + /// + public void* EffectFactory { get; } + + /// + /// Loads a instance from the input binary blob. + /// + /// The input binary blob to deserialize. + /// The resulting instance. + /// Thrown if the loading failed. + /// + /// The input blob should have been created by a call to any of the overloads + /// of . + /// + public static V1 Load(ReadOnlyMemory blob) + { + switch (TryLoadAndGetResult(blob, out V1 data)) + { + case LoadingResult.Success: + return data; + case LoadingResult.EmptyBuffer: + ThrowHelper.ThrowArgumentException(nameof(blob), "The input blob is empty."); + break; + case LoadingResult.BufferTooShort: + ThrowHelper.ThrowArgumentException(nameof(blob), "The input blob is too short."); + break; + case LoadingResult.BufferTooLong: + ThrowHelper.ThrowArgumentException(nameof(blob), "The input blob is too long."); + break; + case LoadingResult.MismatchedBlobVersionId: + ThrowHelper.ThrowArgumentException(nameof(blob), "The blob version id from the input blob does not match."); + break; + case LoadingResult.InvalidNumberOfInputs: + ThrowHelper.ThrowArgumentException(nameof(blob), "The input blob has an invalid number of inputs."); + break; + case LoadingResult.InvalidPropertyXml: + ThrowHelper.ThrowArgumentException(nameof(blob), "The property XML value in the input blob is invalid."); + break; + case LoadingResult.InvalidNumberOfBindings: + ThrowHelper.ThrowArgumentException(nameof(blob), "The input blob declares an invalid number of bindings."); + break; + case LoadingResult.InvalidBindingPropertyName: + ThrowHelper.ThrowArgumentException(nameof(blob), "The input blob has an invalid property name for one of its property bindings."); + break; + default: + ThrowHelper.ThrowArgumentException(nameof(blob), "The input blob failed to be loaded for an unknown reason."); + break; + } + + return data; + } + + /// + /// Tries to load a instance from the input binary blob. + /// + /// The input binary blob to deserialize. + /// The resulting instance, if successful. + /// Whether or not the input blob has been correctly deserialized (if it was not malformed). + /// + /// The input blob should have been created by a call to any of the overloads + /// of . + /// + public static bool TryLoad(ReadOnlyMemory blob, out V1 data) + { + return TryLoadAndGetResult(blob, out data) is LoadingResult.Success; + } + + /// + /// Tries to load a instance from the input binary blob and returns a result. + /// + /// The input binary blob to deserialize. + /// The resulting instance, if successful. + /// The result of the loading operation. + private static LoadingResult TryLoadAndGetResult(ReadOnlyMemory blob, out V1 data) + { + data = default; + + if (blob.IsEmpty) + { + return LoadingResult.EmptyBuffer; + } + + ReadOnlySpan span = blob.Span; + + // Blob id + if (!MemoryMarshal.TryRead(span, out Guid blobId)) + { + return LoadingResult.BufferTooShort; + } + + // Validate the blob id + if (blobId != BlobId) + { + return LoadingResult.MismatchedBlobVersionId; + } + + span = span.Slice(sizeof(Guid)); + + // Effect class id + if (!MemoryMarshal.TryRead(span, out Guid effectId)) + { + return LoadingResult.BufferTooShort; + } + + span = span.Slice(sizeof(Guid)); + + // Number of inputs + if (!MemoryMarshal.TryRead(span, out int numberOfInputs)) + { + return LoadingResult.BufferTooShort; + } + + // Validate the number of inputs + if (numberOfInputs < 0) + { + return LoadingResult.InvalidNumberOfInputs; + } + + span = span.Slice(sizeof(int)); + + // Effect property XML + int lengthOfXml = span.IndexOf((byte)'\0'); + + if (lengthOfXml == -1) + { + return LoadingResult.InvalidPropertyXml; + } + + string xml = Encoding.UTF8.GetString(span.Slice(0, lengthOfXml)); + + span = span.Slice(lengthOfXml + 1); + + // Number of bindings + if (!MemoryMarshal.TryRead(span, out int numberOfBindings)) + { + return LoadingResult.BufferTooShort; + } + + // Validate the number of bindings + if (numberOfBindings < 0) + { + return LoadingResult.InvalidNumberOfBindings; + } + + span = span.Slice(sizeof(int)); + + D2D1PropertyBinding[] propertyBindings = new D2D1PropertyBinding[numberOfBindings]; + + // Property bindings + for (int i = 0; i < numberOfBindings; i++) + { + // Property name + int lengthOfName = span.IndexOf((byte)'\0'); + + if (lengthOfName == -1) + { + return LoadingResult.InvalidBindingPropertyName; + } + + string name = Encoding.UTF8.GetString(span.Slice(0, lengthOfName)); + + span = span.Slice(lengthOfName + 1); + + // Property get function + if (!MemoryMarshal.TryRead(span, out nint getFunction)) + { + return LoadingResult.BufferTooShort; + } + + span = span.Slice(sizeof(nint)); + + // Property set function + if (!MemoryMarshal.TryRead(span, out nint setFunction)) + { + return LoadingResult.BufferTooShort; + } + + span = span.Slice(sizeof(nint)); + + propertyBindings[i] = new D2D1PropertyBinding(name, (void*)getFunction, (void*)setFunction); + } + + // Effect factory + if (!MemoryMarshal.TryRead(span, out nint effectFactory)) + { + return LoadingResult.BufferTooShort; + } + + span = span.Slice(sizeof(nint)); + + // If the buffer is bigger than expected, also consider it malformed + if (span.Length > 0) + { + return LoadingResult.BufferTooLong; + } + + data = new V1( + effectId, + numberOfInputs, + xml, + propertyBindings, + effectFactory); + + return LoadingResult.Success; + } + + /// + /// Indicates the result of a blob loading operation. + /// + private enum LoadingResult + { + Success, + EmptyBuffer, + BufferTooShort, + BufferTooLong, + MismatchedBlobVersionId, + InvalidNumberOfInputs, + InvalidPropertyXml, + InvalidNumberOfBindings, + InvalidBindingPropertyName + } + } +} diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InteropServices.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InteropServices.cs new file mode 100644 index 00000000..ab88fa9c --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InteropServices.cs @@ -0,0 +1,113 @@ +using System; +using System.Runtime.CompilerServices; +using ComputeSharp.D2D1.Shaders.Dispatching; +using ComputeSharp.D2D1.Shaders.Interop.Buffers; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.Interop; + +/// +/// Provides methods to interop with D2D1 APIs and compile shaders or extract their constant buffer data. +/// +public static unsafe class D2D1InteropServices +{ + /// + /// Loads the bytecode from an input D2D1 pixel shader. + /// + /// The type of D2D1 pixel shader to load the bytecode for. + /// A instance with the resulting shader bytecode. + /// + /// This method will only compile the shader using if no precompiled shader is available. + /// + /// If the input shader was precompiled, the returned instance will wrap a pinned memory buffer (from the PE section). + /// If the shader was compiled at runtime, the returned instance will wrap a array with the bytecode. + /// + /// + public static ReadOnlyMemory LoadShaderBytecode() + where T : unmanaged, ID2D1PixelShader + { + return LoadOrCompileShaderBytecode(null); + } + + /// + /// Loads the bytecode from an input D2D1 pixel shader. + /// + /// The type of D2D1 pixel shader to load the bytecode for. + /// The shader profile to use to get the shader bytecode. + /// A instance with the resulting shader bytecode. + /// + /// If the input shader was precompiled, the returned instance will wrap a pinned memory buffer (from the PE section). + /// If the shader was compiled at runtime, the returned instance will wrap a array with the bytecode. + /// + public static ReadOnlyMemory LoadShaderBytecode(D2D1ShaderProfile shaderProfile) + where T : unmanaged, ID2D1PixelShader + { + return LoadOrCompileShaderBytecode(shaderProfile); + } + + /// + /// Loads or compiles the bytecode from an input D2D1 pixel shader. + /// + /// The type of D2D1 pixel shader to load the bytecode for. + /// The shader profile to use to get the shader bytecode. + /// A instance with the resulting shader bytecode. + /// Thrown if the input shader has not been precompiled. + private static ReadOnlyMemory LoadOrCompileShaderBytecode(D2D1ShaderProfile? shaderProfile) + where T : unmanaged, ID2D1PixelShader + { + D2D1ShaderBytecodeLoader bytecodeLoader = default; + + Unsafe.NullRef().LoadBytecode(ref bytecodeLoader, shaderProfile); + + using ComPtr dynamicBytecode = bytecodeLoader.GetResultingShaderBytecode(out ReadOnlySpan precompiledBytecode); + + // If a precompiled shader is available, return it + if (!precompiledBytecode.IsEmpty) + { + return new PinnedBufferMemoryManager(precompiledBytecode).Memory; + } + + // Otherwise, return the dynamic shader instead + byte* bytecodePtr = (byte*)dynamicBytecode.Get()->GetBufferPointer(); + int bytecodeSize = (int)dynamicBytecode.Get()->GetBufferSize(); + + return new ReadOnlySpan(bytecodePtr, bytecodeSize).ToArray(); + } + + /// + /// Gets the constant buffer from an input D2D1 pixel shader. + /// + /// The type of D2D1 pixel shader to retrieve info for. + /// The input D2D1 pixel shader to retrieve info for. + /// A instance with the pixel shader constant buffer. + /// + /// This method will allocate a buffer every time it is invoked. + /// For a zero-allocation alternative, use . + public static ReadOnlyMemory GetPixelShaderConstantBuffer(in T shader) + where T : unmanaged, ID2D1PixelShader + { + D2D1ByteArrayDispatchDataLoader dataLoader = default; + + Unsafe.AsRef(in shader).LoadDispatchData(ref dataLoader); + + return dataLoader.GetResultingDispatchData(); + } + + /// + /// Sets the constant buffer from an input D2D1 pixel shader, by calling ID2D1DrawInfo::SetPixelShaderConstantBuffer. + /// + /// The type of D2D1 pixel shader to set the constant buffer for. + /// The input D2D1 pixel shader to set the contant buffer for. + /// A pointer to the ID2D1DrawInfo instance to use. + /// For more info, see . + public static void SetPixelShaderConstantBufferForD2D1DrawInfo(in T shader, void* d2D1DrawInfo) + where T : unmanaged, ID2D1PixelShader + { + D2D1DrawInfoDispatchDataLoader dataLoader = new((ID2D1DrawInfo*)d2D1DrawInfo); + + Unsafe.AsRef(in shader).LoadDispatchData(ref dataLoader); + } +} diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs new file mode 100644 index 00000000..c10c6ad3 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs @@ -0,0 +1,313 @@ +using System; +using System.Runtime.CompilerServices; +#if !NET6_0_OR_GREATER +using System.Runtime.InteropServices; +#endif +using System.Text; +using ComputeSharp.D2D1.Extensions; +using ComputeSharp.D2D1.Helpers; +using ComputeSharp.D2D1.Interop.Effects; +using ComputeSharp.D2D1.Shaders.Dispatching; +using ComputeSharp.D2D1.Shaders.Interop.Buffers; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.Interop; + +/// +/// An implementation of a D2D1 pixel shader effect that can be used to instantiate ID2D1Effect objects. +/// +public static unsafe class D2D1PixelShaderEffect +{ + /// + /// Registers an effect from an input D2D1 pixel shader, by calling ID2D1Factory1::RegisterEffectFromString. + /// + /// The type of D2D1 pixel shader to register. + /// A pointer to the ID2D1Factory1 instance to use. + /// The of the registered effect, which can be used to call ID2D1DeviceContext::CreateEffect. + /// Thrown if an effect is registered multiple times with different properties. + /// For more info, see . + public static unsafe void RegisterForD2D1Factory1(void* d2D1Factory1, out Guid effectId) + where T : unmanaged, ID2D1PixelShader + { + RegisterForD2D1Factory1(d2D1Factory1, null, out effectId); + } + + /// + /// Registers an effect from an input D2D1 pixel shader, by calling ID2D1Factory1::RegisterEffectFromString. + /// + /// The type of D2D1 pixel shader to register. + /// The type of implementation to register. + /// A pointer to the ID2D1Factory1 instance to use. + /// The of the registered effect, which can be used to call ID2D1DeviceContext::CreateEffect. + /// Thrown if an effect is registered multiple times with different properties. + /// For more info, see . + public static unsafe void RegisterForD2D1Factory1(void* d2D1Factory1, out Guid effectId) + where T : unmanaged, ID2D1PixelShader + where TMapper : class, ID2D1TransformMapper, new() + { + RegisterForD2D1Factory1(d2D1Factory1, static () => new TMapper(), out effectId); + } + + /// + /// Registers an effect from an input D2D1 pixel shader, by calling ID2D1Factory1::RegisterEffectFromString. + /// + /// The type of D2D1 pixel shader to register. + /// A pointer to the ID2D1Factory1 instance to use. + /// An optional factory of instances to use for the transform. + /// The of the registered effect, which can be used to call ID2D1DeviceContext::CreateEffect. + /// Thrown if an effect is registered multiple times with different properties. + /// For more info, see . + public static unsafe void RegisterForD2D1Factory1(void* d2D1Factory1, Func>? mapperFactory, out Guid effectId) + where T : unmanaged, ID2D1PixelShader + { + effectId = default; + + PixelShaderEffect.For.Initialize(mapperFactory); + + // Setup the input string + StringBuilder effectInputsBuilder = new(); + + for (int i = 0; i < PixelShaderEffect.For.NumberOfInputs; i++) + { + effectInputsBuilder.Append(""); + } + + // Prepare the XML with a variable number of inputs + string xml = @$" + + + + + + + {effectInputsBuilder} + + + + +"; + + fixed (char* pXml = xml) + fixed (char* pPropertyName = "Buffer") + { + // Prepare the effect binding functions + D2D1_PROPERTY_BINDING d2D1PropertyBinding; + d2D1PropertyBinding.propertyName = (ushort*)pPropertyName; + d2D1PropertyBinding.getFunction = + (delegate* unmanaged[Stdcall]) +#if NET6_0_OR_GREATER + (delegate* unmanaged) + &PixelShaderEffect.GetConstantBuffer; +#else + (void*)Marshal.GetFunctionPointerForDelegate(PixelShaderEffect.GetConstantBufferWrapper); +#endif + d2D1PropertyBinding.setFunction = + (delegate* unmanaged[Stdcall]) +#if NET6_0_OR_GREATER + (delegate* unmanaged) + &PixelShaderEffect.SetConstantBuffer; +#else + (void*)Marshal.GetFunctionPointerForDelegate(PixelShaderEffect.SetConstantBufferWrapper); +#endif + + fixed (Guid* pGuid = &PixelShaderEffect.For.Id) + { + // Register the effect + ((ID2D1Factory1*)d2D1Factory1)->RegisterEffectFromString( + classId: pGuid, + propertyXml: (ushort*)pXml, + bindings: &d2D1PropertyBinding, + bindingsCount: 1, + effectFactory: PixelShaderEffect.For.Factory).Assert(); + } + + effectId = PixelShaderEffect.For.Id; + } + } + + /// + /// Gets a binary blob containing serialized information that can be used to register an effect, by using ID2D1Factory1::RegisterEffectFromString. + /// + /// The type of D2D1 pixel shader to register. + /// The of the registered effect, which can be used to call ID2D1DeviceContext::CreateEffect. + /// A blob containing serialized information that can be used to register an effect. + /// Thrown if an effect is registered multiple times with different properties. + /// For more info and for details on the binary format, see . + public static unsafe ReadOnlyMemory GetRegistrationBlob(out Guid effectId) + where T : unmanaged, ID2D1PixelShader + { + return GetRegistrationBlob(null, out effectId); + } + + /// + /// Gets a binary blob containing serialized information that can be used to register an effect, by using ID2D1Factory1::RegisterEffectFromString. + /// + /// The type of D2D1 pixel shader to register. + /// The type of implementation to register. + /// The of the registered effect, which can be used to call ID2D1DeviceContext::CreateEffect. + /// A blob containing serialized information that can be used to register an effect. + /// Thrown if an effect is registered multiple times with different properties. + /// For more info and for details on the binary format, see . + public static unsafe ReadOnlyMemory GetRegistrationBlob(out Guid effectId) + where T : unmanaged, ID2D1PixelShader + where TMapper : class, ID2D1TransformMapper, new() + { + return GetRegistrationBlob(static () => new TMapper(), out effectId); + } + + /// + /// Gets a binary blob containing serialized information that can be used to register an effect, by using ID2D1Factory1::RegisterEffectFromString. + /// + /// The type of D2D1 pixel shader to get the registration blob for. + /// An optional factory of instances to use for the transform. + /// The of the registered effect, which can be used to call ID2D1DeviceContext::CreateEffect. + /// A blob containing serialized information that can be used to register an effect. + /// Thrown if an effect is registered multiple times with different properties. + /// + /// + /// This blob can be useful to marshal registration data across an app domain boundary without having assembly references cross this boundary as well. + /// + /// + /// For instance, an application could allow plugins to create effects through the ComputeSharp.D2D1 APIs, and to then create an effect registration + /// blob to pass to the main application, which could then use it to register the effect. This way, even if a plugin was loaded with a separate assembly load + /// context and using a different (potentially incompatible) version of ComputeSharp.D2D1, the two could still work side by side with no issues. + /// + /// + /// The binary blob contains information with the following format: + /// + /// The blob version id (a ). + /// The effect id (a ). + /// The number of inputs for the effect (an ). + /// The effect XML description (as null-terminated UTF8 text). + /// The number of property bindings (an ). + /// The property name (as null-terminated UTF8 text). + /// The property getter (a ). + /// The property setter (a ). + /// The effect factory (a ). + /// + /// The property name, getter and setter are grouped together after the number of bindings. + /// + /// + /// To make the deserialization easier, the type can be used to read and validate the returned blob. + /// The leading blob id will determine what subtype should be used to deserialize the blob (eg. ). + /// + /// + /// For more info, see . + /// + /// + public static unsafe ReadOnlyMemory GetRegistrationBlob(Func>? mapperFactory, out Guid effectId) + where T : unmanaged, ID2D1PixelShader + { + effectId = default; + + PixelShaderEffect.For.Initialize(mapperFactory); + + using ArrayPoolBinaryWriter writer = new(ArrayPoolBinaryWriter.DefaultInitialBufferSize); + + // Blob id + writer.Write(D2D1EffectRegistrationData.V1.BlobId); + + // Effect id and number of inputs + writer.Write(PixelShaderEffect.For.Id); + writer.Write(PixelShaderEffect.For.NumberOfInputs); + + // Build the XML text + writer.WriteAsUtf8(@" + + + + + + + "); + + // Add the input nodes + for (int i = 0; i < PixelShaderEffect.For.NumberOfInputs; i++) + { + writer.WriteAsUtf8(""); + } + + // Write the last part of the XML (including the buffer property) + writer.WriteAsUtf8(@" + + + + +"); + + // Null terminator for the text + writer.Write((byte)'\0'); + + // Property accessors +#if NET6_0_OR_GREATER + nint getBufferPointer = (nint)(delegate* unmanaged)&PixelShaderEffect.GetConstantBuffer; + nint setBufferPointer = (nint)(delegate* unmanaged)&PixelShaderEffect.SetConstantBuffer; +#else + nint getBufferPointer = Marshal.GetFunctionPointerForDelegate(PixelShaderEffect.GetConstantBufferWrapper); + nint setBufferPointer = Marshal.GetFunctionPointerForDelegate(PixelShaderEffect.SetConstantBufferWrapper); +#endif + + // Bindings + writer.Write(1); + writer.WriteAsUtf8("Buffer"); + writer.Write((byte)'\0'); + writer.Write(getBufferPointer); + writer.Write(setBufferPointer); + + // Effect factory + writer.Write((nint)PixelShaderEffect.For.Factory); + + effectId = PixelShaderEffect.For.Id; + + return writer.WrittenSpan.ToArray(); + } + + /// + /// Creates an effect wrapping an input D2D1 pixel shader, by calling ID2D1DeviceContext::CreateEffect. + /// + /// The type of D2D1 pixel shader to create an effect for. + /// A pointer to the ID2D1DeviceContext instance to use. + /// A pointer to the resulting ID2D1Effect* pointer to produce. + /// + /// Thrown if this method is called before initializing a shader effect for the shader type . + /// To do so, make sure to call either (or an overload), or + /// to use (or an overload), and use that blob to register an effect. + /// + /// For more info, see . + public static unsafe void CreateFromD2D1DeviceContext(void* d2D1DeviceContext, void** d2D1Effect) + where T : unmanaged, ID2D1PixelShader + { + if (!PixelShaderEffect.For.TryGetId(out Guid id)) + { + ThrowHelper.ThrowInvalidOperationException("The effect for the input shader type has not been initialized yet."); + } + + ((ID2D1DeviceContext*)d2D1DeviceContext)->CreateEffect( + effectId: &id, + effect: (ID2D1Effect**)d2D1Effect).Assert(); + } + + /// + /// Sets the constant buffer from an input D2D1 effect, by calling ID2D1Effect::SetValue. + /// + /// The type of D2D1 pixel shader to set the constant buffer for. + /// The input D2D1 pixel shader to set the contant buffer for. + /// A pointer to the ID2D1Effect instance to use. + /// For more info, see . + public static unsafe void SetConstantBufferForD2D1Effect(in T shader, void* d2D1Effect) + where T : unmanaged, ID2D1PixelShader + { + D2D1EffectDispatchDataLoader dataLoader = new((ID2D1Effect*)d2D1Effect); + + Unsafe.AsRef(in shader).LoadDispatchData(ref dataLoader); + } +} diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PropertyBinding.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PropertyBinding.cs new file mode 100644 index 00000000..0b78e89f --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PropertyBinding.cs @@ -0,0 +1,35 @@ +namespace ComputeSharp.D2D1.Interop; + +/// +/// A model representing a property binding for an effect. +/// +public unsafe readonly struct D2D1PropertyBinding +{ + /// + /// Creates a new instance with the specified parameters. + /// + /// The property name. + /// A pointer to the property get function callback + /// A pointer to the property set function callback + internal D2D1PropertyBinding(string name, void* getFunction, void* setFunction) + { + PropertyName = name; + GetFunction = getFunction; + SetFunction = setFunction; + } + + /// + /// Gets the name of the property. + /// + public string PropertyName { get; } + + /// + /// Gets the property get function (a ). + /// + public void* GetFunction { get; } + + /// + /// Gets the property set function (a ). + /// + public void* SetFunction { get; } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ReflectionServices.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ReflectionServices.cs new file mode 100644 index 00000000..e226bed9 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ReflectionServices.cs @@ -0,0 +1,87 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.D2D1.Extensions; +using ComputeSharp.D2D1.Shaders.Dispatching; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.Interop; + +/// +/// Provides methods to extract reflection info on D2D1 shaders generated using this library. +/// +public static class D2D1ReflectionServices +{ + /// + /// Gets the shader info associated with a given D2D1 shader. + /// + /// The type of D2D1 shader to retrieve info for. + /// The resulting instance. + public static unsafe D2D1ShaderInfo GetShaderInfo() + where T : struct, ID2D1PixelShader + { + Unsafe.NullRef().BuildHlslSource(out string hlslSource); + + D2D1ShaderBytecodeLoader bytecodeLoader = default; + + Unsafe.NullRef().LoadBytecode(ref bytecodeLoader, D2D1ShaderProfile.PixelShader50); + + using ComPtr dynamicBytecode = bytecodeLoader.GetResultingShaderBytecode(out ReadOnlySpan precompiledBytecode); + + byte* bytecodePtr; + int bytecodeSize; + + if (!precompiledBytecode.IsEmpty) + { + bytecodePtr = (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(precompiledBytecode)); + bytecodeSize = precompiledBytecode.Length; + } + else + { + bytecodePtr = (byte*)dynamicBytecode.Get()->GetBufferPointer(); + bytecodeSize = (int)dynamicBytecode.Get()->GetBufferSize(); + } + + using ComPtr d3D11ShaderReflection = default; + + DirectX.D3DReflect( + pSrcData: bytecodePtr, + SrcDataSize: (nuint)bytecodeSize, + pInterface: Windows.__uuidof(), + ppReflector: d3D11ShaderReflection.GetVoidAddressOf()).Assert(); + + D3D11_SHADER_DESC d3D11ShaderDescription; + + d3D11ShaderReflection.Get()->GetDesc(&d3D11ShaderDescription).Assert(); + + return new( + CompilerVersion: new string(d3D11ShaderDescription.Creator), + HlslSource: hlslSource, + ConstantBufferCount: d3D11ShaderDescription.ConstantBuffers, + BoundResourceCount: d3D11ShaderDescription.BoundResources, + InstructionCount: d3D11ShaderDescription.InstructionCount, + TemporaryRegisterCount: d3D11ShaderDescription.TempRegisterCount, + TemporaryArrayCount: d3D11ShaderDescription.TempArrayCount, + ConstantDefineCount: d3D11ShaderDescription.DefCount, + DeclarationCount: d3D11ShaderDescription.DclCount, + TextureNormalInstructions: d3D11ShaderDescription.TextureNormalInstructions, + TextureLoadInstructionCount: d3D11ShaderDescription.TextureLoadInstructions, + TextureStoreInstructionCount: d3D11ShaderDescription.cTextureStoreInstructions, + FloatInstructionCount: d3D11ShaderDescription.FloatInstructionCount, + IntInstructionCount: d3D11ShaderDescription.IntInstructionCount, + UIntInstructionCount: d3D11ShaderDescription.UintInstructionCount, + StaticFlowControlInstructionCount: d3D11ShaderDescription.StaticFlowControlCount, + DynamicFlowControlInstructionCount: d3D11ShaderDescription.DynamicFlowControlCount, + EmitInstructionCount: d3D11ShaderDescription.EmitInstructionCount, + BarrierInstructionCount: d3D11ShaderDescription.cBarrierInstructions, + InterlockedInstructionCount: d3D11ShaderDescription.cInterlockedInstructions, + BitwiseInstructionCount: d3D11ShaderReflection.Get()->GetBitwiseInstructionCount(), + MovcInstructionCount: d3D11ShaderReflection.Get()->GetMovcInstructionCount(), + MovInstructionCount: d3D11ShaderReflection.Get()->GetMovInstructionCount(), + InterfaceSlotCount: d3D11ShaderReflection.Get()->GetNumInterfaceSlots(), + RequiresDoublePrecisionSupport: (d3D11ShaderReflection.Get()->GetRequiresFlags() & (D3D.D3D_SHADER_REQUIRES_DOUBLES | D3D.D3D_SHADER_REQUIRES_11_1_DOUBLE_EXTENSIONS)) != 0); + } +} diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ShaderInfo.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ShaderInfo.cs new file mode 100644 index 00000000..1fada0b5 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ShaderInfo.cs @@ -0,0 +1,56 @@ +namespace ComputeSharp.D2D1.Interop; + +/// +/// A model representing reflection info for a given D2D1 shader. +/// +/// The compiler version used to build the shader. +/// The HLSL source code the shader was built from. +/// The number of shader constant buffers. +/// The number of resource (textures and buffers) bound to a shader. +/// The number of intermediate-language instructions in the compiled shader. +/// The number of temporary registers in the compiled shader. +/// The number of temporary arrays used. +/// The number of constant defines. +/// The number of declarations (input + output). +/// The number of non-categorized texture instructions. +/// The number of texture load instructions. +/// The number of texture write instructions. +/// The number of floating point arithmetic instructions used. +/// The number of signed integer arithmetic instructions used. +/// The number of unsigned integer arithmetic instructions used. +/// The number of static flow control instructions used. +/// The number of dynamic flow control instructions used. +/// The number of emit instructions used. +/// The number of barrier instructions used. +/// The number of interlocked instructions used. +/// The number of bitwise instructions used. +/// The number of movc instructions used. +/// The number of mov instructions used. +/// The number of interface slots used. +/// Indicates whether support for double precision floating point numbers is required. +public sealed record D2D1ShaderInfo( + string CompilerVersion, + string HlslSource, + uint ConstantBufferCount, + uint BoundResourceCount, + uint InstructionCount, + uint TemporaryRegisterCount, + uint TemporaryArrayCount, + uint ConstantDefineCount, + uint DeclarationCount, + uint TextureNormalInstructions, + uint TextureLoadInstructionCount, + uint TextureStoreInstructionCount, + uint FloatInstructionCount, + uint IntInstructionCount, + uint UIntInstructionCount, + uint StaticFlowControlInstructionCount, + uint DynamicFlowControlInstructionCount, + uint EmitInstructionCount, + uint BarrierInstructionCount, + uint InterlockedInstructionCount, + uint BitwiseInstructionCount, + uint MovcInstructionCount, + uint MovInstructionCount, + uint InterfaceSlotCount, + bool RequiresDoublePrecisionSupport); diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/D2D1TransformMapper.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/D2D1TransformMapper.cs new file mode 100644 index 00000000..7a60e8d4 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/D2D1TransformMapper.cs @@ -0,0 +1,106 @@ +using System; +using System.Drawing; +using System.Runtime.CompilerServices; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.Interop.Effects; + +/// +/// A base type to support non-generic uses. +/// +internal abstract class D2D1TransformMapper +{ + /// + /// The buffer with the serialized shader dispatch data, if any. + /// The input rectangles to be mapped to the output rectangle. This parameter is always equal to the input bounds. + /// The input rectangles to be mapped to the opaque output rectangle. + /// The output rectangle that maps to the corresponding input rectangle. + /// The output rectangle that maps to the corresponding opaque input rectangle. + public abstract void MapInputsToOutput( + ReadOnlySpan buffer, + ReadOnlySpan inputs, + ReadOnlySpan opaqueInputs, + out Rectangle output, + out Rectangle opaqueOutput); + + /// + /// The buffer with the serialized shader dispatch data, if any. + /// The output rectangle from which the inputs must be mapped. + /// The corresponding set of inputs. The inputs will directly correspond to the transform inputs. + public abstract void MapOutputToInputs(ReadOnlySpan buffer, in Rectangle output, Span inputs); + + /// + /// The buffer with the serialized shader dispatch data, if any. + /// The index of the input rectangle. + /// The invalid input rectangle. + /// The output rectangle to which the input rectangle must be mapped. + public abstract void MapInvalidOutput(ReadOnlySpan buffer, int inputIndex, Rectangle invalidInput, out Rectangle invalidOutput); + + /// + /// A generic implementation for a specific shader type. + /// + /// The target shader type. + public sealed class For : D2D1TransformMapper + where T : unmanaged, ID2D1PixelShader + { + /// + /// The instance to use. + /// + private readonly ID2D1TransformMapper transformMapper; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance to use. + private For(ID2D1TransformMapper transformMapper) + { + this.transformMapper = transformMapper; + } + + /// + /// Creates a new instance for a given transform mapper, if there is one. + /// + /// The instance to usse, if there is one. + /// A new instance wrapping , or . + public static For? Get(ID2D1TransformMapper? transformMapper) + { + if (transformMapper is null) + { + return null; + } + + return new(transformMapper); + } + + /// + public override void MapInputsToOutput(ReadOnlySpan buffer, ReadOnlySpan inputs, ReadOnlySpan opaqueInputs, out Rectangle output, out Rectangle opaqueOutput) + { + Unsafe.SkipInit(out T shader); + + shader.InitializeFromDispatchData(buffer); + + this.transformMapper.MapInputsToOutput(in shader, inputs, opaqueInputs, out output, out opaqueOutput); + } + + /// + public override void MapOutputToInputs(ReadOnlySpan buffer, in Rectangle output, Span inputs) + { + Unsafe.SkipInit(out T shader); + + shader.InitializeFromDispatchData(buffer); + + this.transformMapper.MapOutputToInputs(in shader, in output, inputs); + } + + /// + public override void MapInvalidOutput(ReadOnlySpan buffer, int inputIndex, Rectangle invalidInput, out Rectangle invalidOutput) + { + Unsafe.SkipInit(out T shader); + + shader.InitializeFromDispatchData(buffer); + + this.transformMapper.MapInvalidOutput(in shader, inputIndex, invalidInput, out invalidOutput); + } + } +} diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs new file mode 100644 index 00000000..cc8fbf5a --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs @@ -0,0 +1,186 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.D2D1.Helpers; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +#if NET6_0_OR_GREATER +using RuntimeHelpers = System.Runtime.CompilerServices.RuntimeHelpers; +#else +using RuntimeHelpers = ComputeSharp.D2D1.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +#endif + +namespace ComputeSharp.D2D1.Interop.Effects; + +/// +/// A simple and implementation for a given pixel shader. +/// +internal unsafe partial struct PixelShaderEffect +{ + /// + /// A generic pixel shader implementation. + /// + /// The type of shader. + public static class For + where T : unmanaged, ID2D1PixelShader + { + /// + /// The wrapper for the shader factory. + /// + private static readonly FactoryDelegate EffectFactory = CreateEffect; + + /// + /// Indicates whether or not initialization has completed. + /// + private static bool isInitialized; + + /// + /// The for the shader. + /// + /// + /// This field could have used to reduce some verbosity where it is + /// being used to pass its address to a native API, but the attribute is incompatible with collectible assemblies. + /// Because of that, it can't be used, as this project is explicitly meant to support plugin-like scenarios. + /// + private static Guid shaderId; + + /// + /// The number of inputs for the shader. + /// + private static int numberOfInputs; + + /// + /// The shader bytecode. + /// + private static byte* bytecode; + + /// + /// The size of . + /// + private static int bytecodeSize; + + /// + /// The factory of instances to use for each created effect. + /// + private static Func>? d2D1DrawTransformMapperFactory; + + /// + /// Initializes the shared state. + /// + /// The factory of instances to use for each created effect. + /// Thrown if initialization is attempted with a mismatched transform factory. + public static void Initialize(Func>? factory) + { + // This conceptually acts as a static constructor, and this type is + // internal, so in this very specific case locking on the type is fine. + lock (typeof(For)) + { + if (isInitialized) + { + // If the factory is already initialized, ensure the draw transform mapper is the same + if (d2D1DrawTransformMapperFactory != factory) + { + ThrowHelper.ThrowInvalidOperationException( + "Cannot initialize an ID2D1Effect factory for the same shader type with two different transform mappings. " + + "Make sure to only ever register a pixel shader effect with either no transform, or the same transform type."); + } + } + else + { + // Load all shader properties + Guid guid = typeof(T).GUID; + int inputCount = ((D2DInputCountAttribute[])typeof(T).GetCustomAttributes(typeof(D2DInputCountAttribute), false))[0].Count; + ReadOnlyMemory buffer = D2D1InteropServices.LoadShaderBytecode(); + byte* typeAssociatedMemory = (byte*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), buffer.Length); + + // Copy the bytecode to the target buffer + buffer.Span.CopyTo(new Span(typeAssociatedMemory, buffer.Length)); + + // Set the shared state and mark the type as initialized + shaderId = guid; + numberOfInputs = inputCount; + bytecode = typeAssociatedMemory; + bytecodeSize = buffer.Length; + d2D1DrawTransformMapperFactory = factory; + + isInitialized = true; + } + } + } + + /// + /// Gets a reference to the id of the effect. + /// + public static ref Guid Id + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ref shaderId; + } + + /// + /// Gets the factory for the current effect. + /// + public static delegate* unmanaged[Stdcall] Factory + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (delegate* unmanaged[Stdcall])Marshal.GetFunctionPointerForDelegate(EffectFactory); + } + + /// + /// Gets the number of inputs for the effect. + /// + public static int NumberOfInputs => numberOfInputs; + + /// + /// Tries to get the effect id, if it has been initialized. + /// + /// The resulting effect id. + /// Whether or not the effect had been initialized. + public static bool TryGetId(out Guid id) + { + lock (typeof(For)) + { + if (isInitialized) + { + id = Id; + + return true; + } + } + + id = default; + + return false; + } + + /// + private static int CreateEffect(IUnknown** effectImpl) + { + D2D1TransformMapper? d2D1TransformMapper; + + // If there is a custom draw transform factory, run it in a try block and handle exceptions. This + // is needed because the factory will be running user code from a method that's invoked by COM, + // and managed exceptions should never cross the ABI boundary. If it throws, just return the HRESULT. + try + { + ID2D1TransformMapper? d2D1DrawTransformMapper = d2D1DrawTransformMapperFactory?.Invoke(); + + d2D1TransformMapper = D2D1TransformMapper.For.Get(d2D1DrawTransformMapper); + } + catch (Exception e) + { + *effectImpl = null; + + return e.HResult; + } + + return PixelShaderEffect.Factory( + shaderId, + numberOfInputs, + bytecode, + bytecodeSize, + d2D1TransformMapper, + effectImpl); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs new file mode 100644 index 00000000..d9833da2 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs @@ -0,0 +1,278 @@ +using System; +using System.Drawing; +using System.Runtime.InteropServices; +using ComputeSharp.D2D1.Extensions; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +#if !NET6_0_OR_GREATER +using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute; +#endif + +namespace ComputeSharp.D2D1.Interop.Effects; + +/// +partial struct PixelShaderEffect +{ + /// + /// The implementation for . + /// + private unsafe static class ID2D1DrawTransformMethods + { +#if !NET6_0_OR_GREATER + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate uint GetInputCountDelegate(PixelShaderEffect* @this); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int MapOutputRectToInputRectsDelegate(PixelShaderEffect* @this, RECT* outputRect, RECT* inputRects, uint inputRectsCount); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int MapInputRectsToOutputRectDelegate(PixelShaderEffect* @this, RECT* inputRects, RECT* inputOpaqueSubRects, uint inputRectCount, RECT* outputRect, RECT* outputOpaqueSubRect); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int MapInvalidRectDelegate(PixelShaderEffect* @this, uint inputIndex, RECT invalidInputRect, RECT* invalidOutputRect); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int SetDrawInfoDelegate(PixelShaderEffect* @this, ID2D1DrawInfo* drawInfo); + + /// + /// A cached instance wrapping . + /// + public static readonly QueryInterfaceDelegate QueryInterfaceWrapper = QueryInterface; + + /// + /// A cached instance wrapping . + /// + public static readonly AddRefDelegate AddRefWrapper = AddRef; + + /// + /// A cached instance wrapping . + /// + public static readonly ReleaseDelegate ReleaseWrapper = Release; + + /// + /// A cached instance wrapping . + /// + public static readonly GetInputCountDelegate GetInputCountWrapper = GetInputCount; + + /// + /// A cached instance wrapping . + /// + public static readonly MapOutputRectToInputRectsDelegate MapOutputRectToInputRectsWrapper = MapOutputRectToInputRects; + + /// + /// A cached instance wrapping . + /// + public static readonly MapInputRectsToOutputRectDelegate MapInputRectsToOutputRectWrapper = MapInputRectsToOutputRect; + + /// + /// A cached instance wrapping . + /// + public static readonly MapInvalidRectDelegate MapInvalidRectWrapper = MapInvalidRect; + + /// + /// A cached instance wrapping . + /// + public static readonly SetDrawInfoDelegate SetDrawInfoWrapper = SetDrawInfo; +#endif + + /// + [UnmanagedCallersOnly] + public static int QueryInterface(PixelShaderEffect* @this, Guid* riid, void** ppvObject) + { + @this = (PixelShaderEffect*)&((void**)@this)[-1]; + + return @this->QueryInterface(riid, ppvObject); + } + + /// + [UnmanagedCallersOnly] + public static uint AddRef(PixelShaderEffect* @this) + { + @this = (PixelShaderEffect*)&((void**)@this)[-1]; + + return @this->AddRef(); + } + + /// + [UnmanagedCallersOnly] + public static uint Release(PixelShaderEffect* @this) + { + @this = (PixelShaderEffect*)&((void**)@this)[-1]; + + return @this->Release(); + } + + /// + [UnmanagedCallersOnly] + public static uint GetInputCount(PixelShaderEffect* @this) + { + @this = (PixelShaderEffect*)&((void**)@this)[-1]; + + return (uint)@this->numberOfInputs; + } + + /// + [UnmanagedCallersOnly] + public static int MapOutputRectToInputRects(PixelShaderEffect* @this, RECT* outputRect, RECT* inputRects, uint inputRectsCount) + { + @this = (PixelShaderEffect*)&((void**)@this)[-1]; + + if (inputRectsCount != @this->numberOfInputs) + { + return E.E_INVALIDARG; + } + + if (@this->d2D1TransformMapperHandle.Target is D2D1TransformMapper d2D1TransformMapper) + { + Rectangle output = outputRect->ToRectangle(); + Span inputs = stackalloc Rectangle[8].Slice(0, (int)inputRectsCount); + + for (int i = 0; i < (int)inputRectsCount; i++) + { + inputs[i] = inputRects[i].ToRectangle(); + } + + ReadOnlySpan buffer = new(@this->constantBuffer, @this->constantBufferSize); + + // Invoke MapOutputToInputs and handle exceptions so they don't cross the ABI boundary + try + { + d2D1TransformMapper.MapOutputToInputs(buffer, in output, inputs); + } + catch (Exception e) + { + return e.HResult; + } + + for (int i = 0; i < (int)inputRectsCount; i++) + { + inputRects[i] = inputs[i].ToRECT(); + } + } + else + { + // Default mapping + for (int i = 0; i < (int)inputRectsCount; i++) + { + inputRects[i] = *outputRect; + } + } + + return S.S_OK; + } + + /// + [UnmanagedCallersOnly] + public static int MapInputRectsToOutputRect(PixelShaderEffect* @this, RECT* inputRects, RECT* inputOpaqueSubRects, uint inputRectCount, RECT* outputRect, RECT* outputOpaqueSubRect) + { + @this = (PixelShaderEffect*)&((void**)@this)[-1]; + + if (inputRectCount != @this->numberOfInputs) + { + return E.E_INVALIDARG; + } + + if (@this->d2D1TransformMapperHandle.Target is D2D1TransformMapper d2D1TransformMapper) + { + Span inputs = stackalloc Rectangle[8].Slice(0, (int)inputRectCount); + Span opaqueInputs = stackalloc Rectangle[8].Slice(0, (int)inputRectCount); + + for (int i = 0; i < (int)inputRectCount; i++) + { + inputs[i] = inputRects[i].ToRectangle(); + opaqueInputs[i] = inputOpaqueSubRects[i].ToRectangle(); + } + + ReadOnlySpan buffer = new(@this->constantBuffer, @this->constantBufferSize); + + Rectangle output; + Rectangle opaqueOutput; + + // Handle exceptions, as mentioned above + try + { + d2D1TransformMapper.MapInputsToOutput(buffer, inputs, opaqueInputs, out output, out opaqueOutput); + } + catch (Exception e) + { + return e.HResult; + } + + *outputRect = output.ToRECT(); + *outputOpaqueSubRect = opaqueOutput.ToRECT(); + } + else if (inputRectCount == 0) + { + // If there are no inputs, make the output rectangle infinite. This is useful + // to make output-only effects work fine by default, without needing a custom + // transform. In this case, the target area will be the output node anyway. + outputRect->MakeD2D1Infinite(); + + @this->inputRect = default; + + *outputOpaqueSubRect = default; + } + else + { + // Default mapping + *outputRect = inputRects[0]; + + @this->inputRect = inputRects[0]; + + *outputOpaqueSubRect = default; + } + + return S.S_OK; + } + + /// + [UnmanagedCallersOnly] + public static int MapInvalidRect(PixelShaderEffect* @this, uint inputIndex, RECT invalidInputRect, RECT* invalidOutputRect) + { + @this = (PixelShaderEffect*)&((void**)@this)[-1]; + + if (@this->d2D1TransformMapperHandle.Target is D2D1TransformMapper d2D1TransformMapper) + { + Rectangle invalidInput = invalidInputRect.ToRectangle(); + Rectangle invalidOutput; + + ReadOnlySpan buffer = new(@this->constantBuffer, @this->constantBufferSize); + + // Handle exceptions once again + try + { + d2D1TransformMapper.MapInvalidOutput(buffer, (int)inputIndex, invalidInput, out invalidOutput); + } + catch (Exception e) + { + return e.HResult; + } + + *invalidOutputRect = invalidOutput.ToRECT(); + } + else + { + // Default mapping + *invalidOutputRect = @this->inputRect; + } + + return S.S_OK; + } + + /// + [UnmanagedCallersOnly] + public static int SetDrawInfo(PixelShaderEffect* @this, ID2D1DrawInfo* drawInfo) + { + @this = (PixelShaderEffect*)&((void**)@this)[-1]; + + @this->d2D1DrawInfo = drawInfo; + + return drawInfo->SetPixelShader(&@this->shaderId); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs new file mode 100644 index 00000000..902fbaa5 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs @@ -0,0 +1,124 @@ +using System; +using System.Runtime.InteropServices; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +#if !NET6_0_OR_GREATER +using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute; +#endif + +namespace ComputeSharp.D2D1.Interop.Effects; + +/// +/// A simple and implementation for a given pixel shader. +/// +internal unsafe partial struct PixelShaderEffect +{ + /// + /// The implementation for . + /// + private static class ID2D1EffectImplMethods + { +#if !NET6_0_OR_GREATER + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int InitializeDelegate(PixelShaderEffect* @this, ID2D1EffectContext* effectContext, ID2D1TransformGraph* transformGraph); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int PrepareForRenderDelegate(PixelShaderEffect* @this, D2D1_CHANGE_TYPE changeType); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int SetGraphDelegate(PixelShaderEffect* @this, ID2D1TransformGraph* transformGraph); + + /// + /// A cached instance wrapping . + /// + public static readonly QueryInterfaceDelegate QueryInterfaceWrapper = QueryInterface; + + /// + /// A cached instance wrapping . + /// + public static readonly AddRefDelegate AddRefWrapper = AddRef; + + /// + /// A cached instance wrapping . + /// + public static readonly ReleaseDelegate ReleaseWrapper = Release; + + /// + /// A cached instance wrapping . + /// + public static readonly InitializeDelegate InitializeWrapper = Initialize; + + /// + /// A cached instance wrapping . + /// + public static readonly PrepareForRenderDelegate PrepareForRenderWrapper = PrepareForRender; + + /// + /// A cached instance wrapping . + /// + public static readonly SetGraphDelegate SetGraphWrapper = SetGraph; +#endif + + /// + [UnmanagedCallersOnly] + public static int QueryInterface(PixelShaderEffect* @this, Guid* riid, void** ppvObject) + { + return @this->QueryInterface(riid, ppvObject); + } + + /// + [UnmanagedCallersOnly] + public static uint AddRef(PixelShaderEffect* @this) + { + return @this->AddRef(); + } + + /// + [UnmanagedCallersOnly] + public static uint Release(PixelShaderEffect* @this) + { + return @this->Release(); + } + + /// + [UnmanagedCallersOnly] + public static int Initialize(PixelShaderEffect* @this, ID2D1EffectContext* effectContext, ID2D1TransformGraph* transformGraph) + { + int hresult = effectContext->LoadPixelShader( + shaderId: &@this->shaderId, + shaderBuffer: @this->bytecode, + shaderBufferCount: (uint)@this->bytecodeSize); + + if (Windows.SUCCEEDED(hresult)) + { + hresult = transformGraph->SetSingleTransformNode((ID2D1TransformNode*)&@this->lpVtblForID2D1DrawTransform); + } + + return hresult; + } + + /// + [UnmanagedCallersOnly] + public static int PrepareForRender(PixelShaderEffect* @this, D2D1_CHANGE_TYPE changeType) + { + if (@this->constantBuffer is not null) + { + return @this->d2D1DrawInfo->SetPixelShaderConstantBuffer( + buffer: @this->constantBuffer, + bufferCount: (uint)@this->constantBufferSize); + } + + return S.S_OK; + } + + /// + [UnmanagedCallersOnly] + public static int SetGraph(PixelShaderEffect* @this, ID2D1TransformGraph* transformGraph) + { + return E.E_NOTIMPL; + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs new file mode 100644 index 00000000..6b46dca5 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs @@ -0,0 +1,320 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +#if NET6_0_OR_GREATER +using RuntimeHelpers = System.Runtime.CompilerServices.RuntimeHelpers; +#else +using RuntimeHelpers = ComputeSharp.D2D1.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute; +#endif + +namespace ComputeSharp.D2D1.Interop.Effects; + +/// +/// A simple and implementation for a given pixel shader. +/// +internal unsafe partial struct PixelShaderEffect +{ + /// + /// A wrapper for an effect factory. + /// + /// The resulting effect factory. + /// The HRESULT for the operation. + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int FactoryDelegate(IUnknown** effectImpl); + +#if !NET6_0_OR_GREATER + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int QueryInterfaceDelegate(PixelShaderEffect* @this, Guid* riid, void** ppvObject); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate uint AddRefDelegate(PixelShaderEffect* @this); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate uint ReleaseDelegate(PixelShaderEffect* @this); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int GetConstantBufferDelegate(IUnknown* effect, byte* data, uint dataSize, uint* actualSize); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int SetConstantBufferDelegate(IUnknown* effect, byte* data, uint dataSize); + + /// + /// A cached instance wrapping . + /// + public static readonly GetConstantBufferDelegate GetConstantBufferWrapper = GetConstantBuffer; + + /// + /// A cached instance wrapping . + /// + public static readonly SetConstantBufferDelegate SetConstantBufferWrapper = SetConstantBuffer; +#endif + + /// + /// The shared vtable pointer for instance, for . + /// + private static readonly void** VtblForID2D1EffectImpl; + + /// + /// The shared vtable pointer for instance, for . + /// + private static readonly void** VtblForID2D1DrawTransform; + + /// + /// Initializes the shared state for . + /// + static PixelShaderEffect() + { + void** lpVtbl = (void**)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(PixelShaderEffect), sizeof(void*) * 14); + + // ID2D1EffectImpl +#if NET6_0_OR_GREATER + lpVtbl[0] = (delegate* unmanaged)&ID2D1EffectImplMethods.QueryInterface; + lpVtbl[1] = (delegate* unmanaged)&ID2D1EffectImplMethods.AddRef; + lpVtbl[2] = (delegate* unmanaged)&ID2D1EffectImplMethods.Release; + lpVtbl[3] = (delegate* unmanaged)&ID2D1EffectImplMethods.Initialize; + lpVtbl[4] = (delegate* unmanaged)&ID2D1EffectImplMethods.PrepareForRender; + lpVtbl[5] = (delegate* unmanaged)&ID2D1EffectImplMethods.SetGraph; +#else + lpVtbl[0] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1EffectImplMethods.QueryInterfaceWrapper); + lpVtbl[1] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1EffectImplMethods.AddRefWrapper); + lpVtbl[2] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1EffectImplMethods.ReleaseWrapper); + lpVtbl[3] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1EffectImplMethods.InitializeWrapper); + lpVtbl[4] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1EffectImplMethods.PrepareForRenderWrapper); + lpVtbl[5] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1EffectImplMethods.SetGraphWrapper); +#endif + + // ID2D1DrawTransform +#if NET6_0_OR_GREATER + lpVtbl[6 + 0] = (delegate* unmanaged)&ID2D1DrawTransformMethods.QueryInterface; + lpVtbl[6 + 1] = (delegate* unmanaged)&ID2D1DrawTransformMethods.AddRef; + lpVtbl[6 + 2] = (delegate* unmanaged)&ID2D1DrawTransformMethods.Release; + lpVtbl[6 + 3] = (delegate* unmanaged)&ID2D1DrawTransformMethods.GetInputCount; + lpVtbl[6 + 4] = (delegate* unmanaged)&ID2D1DrawTransformMethods.MapOutputRectToInputRects; + lpVtbl[6 + 5] = (delegate* unmanaged)&ID2D1DrawTransformMethods.MapInputRectsToOutputRect; + lpVtbl[6 + 6] = (delegate* unmanaged)&ID2D1DrawTransformMethods.MapInvalidRect; + lpVtbl[6 + 7] = (delegate* unmanaged)&ID2D1DrawTransformMethods.SetDrawInfo; +#else + lpVtbl[6 + 0] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawTransformMethods.QueryInterfaceWrapper); + lpVtbl[6 + 1] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawTransformMethods.AddRefWrapper); + lpVtbl[6 + 2] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawTransformMethods.ReleaseWrapper); + lpVtbl[6 + 3] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawTransformMethods.GetInputCountWrapper); + lpVtbl[6 + 4] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawTransformMethods.MapOutputRectToInputRectsWrapper); + lpVtbl[6 + 5] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawTransformMethods.MapInputRectsToOutputRectWrapper); + lpVtbl[6 + 6] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawTransformMethods.MapInvalidRectWrapper); + lpVtbl[6 + 7] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawTransformMethods.SetDrawInfoWrapper); +#endif + + VtblForID2D1EffectImpl = lpVtbl; + VtblForID2D1DrawTransform = &lpVtbl[6]; + } + + /// + /// The vtable pointer for the current instance, for . + /// + private void** lpVtblForID2D1EffectImpl; + + /// + /// The vtable pointer for the current instance, for . + /// + private void** lpVtblForID2D1DrawTransform; + + /// + /// The current reference count for the object (from IUnknown). + /// + private volatile int referenceCount; + + /// + /// The constant buffer data, if set. + /// + private byte* constantBuffer; + + /// + /// The size of , if set. + /// + private int constantBufferSize; + + /// + /// The for the shader. + /// + private Guid shaderId; + + /// + /// The number of inputs for the shader. + /// + private int numberOfInputs; + + /// + /// The shader bytecode. + /// + private byte* bytecode; + + /// + /// The size of . + /// + private int bytecodeSize; + + /// + /// The handle for the instance in use, if any. + /// + private GCHandle d2D1TransformMapperHandle; + + /// + /// The current input rectangle. + /// + private RECT inputRect; + + /// + /// The instance currently in use. + /// + private ID2D1DrawInfo* d2D1DrawInfo; + + /// + /// The factory method for . + /// + /// The for the shader. + /// The number of inputs for the shader. + /// The shader bytecode. + /// The size of . + /// The instance to use for the effect. + /// The resulting effect instance. + /// This always returns 0. + private static int Factory( + Guid shaderId, + int numberOfInputs, + byte* bytecode, + int bytecodeSize, + D2D1TransformMapper? d2D1TransformMapper, + IUnknown** effectImpl) + { + PixelShaderEffect* @this = (PixelShaderEffect*)NativeMemory.Alloc((nuint)sizeof(PixelShaderEffect)); + + *@this = default; + + @this->lpVtblForID2D1EffectImpl = VtblForID2D1EffectImpl; + @this->lpVtblForID2D1DrawTransform = VtblForID2D1DrawTransform; + @this->referenceCount = 1; + @this->shaderId = shaderId; + @this->numberOfInputs = numberOfInputs; + @this->bytecode = bytecode; + @this->bytecodeSize = bytecodeSize; + @this->d2D1TransformMapperHandle = GCHandle.Alloc(d2D1TransformMapper); + + *effectImpl = (IUnknown*)@this; + + return S.S_OK; + } + + /// + [UnmanagedCallersOnly] + public static int GetConstantBuffer(IUnknown* effect, byte* data, uint dataSize, uint* actualSize) + { + PixelShaderEffect* @this = (PixelShaderEffect*)effect; + + if (@this->constantBufferSize == 0) + { + *actualSize = 0; + } + else + { + int bytesToCopy = Math.Min((int)dataSize, @this->constantBufferSize); + + Buffer.MemoryCopy(@this->constantBuffer, data, dataSize, bytesToCopy); + + *actualSize = (uint)bytesToCopy; + } + + return S.S_OK; + } + + /// + [UnmanagedCallersOnly] + public static int SetConstantBuffer(IUnknown* effect, byte* data, uint dataSize) + { + PixelShaderEffect* @this = (PixelShaderEffect*)effect; + + if (@this->constantBuffer is not null) + { + NativeMemory.Free(@this->constantBuffer); + } + + void* buffer = NativeMemory.Alloc(dataSize); + + Buffer.MemoryCopy(data, buffer, dataSize, dataSize); + + @this->constantBuffer = (byte*)buffer; + @this->constantBufferSize = (int)dataSize; + + return S.S_OK; + } + + /// + private int QueryInterface(Guid* riid, void** ppvObject) + { + if (ppvObject is null) + { + return E.E_POINTER; + } + + // ID2D1EffectImpl + if (riid->Equals(Windows.__uuidof()) || + riid->Equals(Windows.__uuidof())) + { + _ = Interlocked.Increment(ref this.referenceCount); + + *ppvObject = Unsafe.AsPointer(ref this); + + return S.S_OK; + } + + // ID2D1DrawTransform + if (riid->Equals(Windows.__uuidof()) || + riid->Equals(Windows.__uuidof()) || + riid->Equals(Windows.__uuidof())) + { + _ = Interlocked.Increment(ref this.referenceCount); + + *ppvObject = (void**)Unsafe.AsPointer(ref this) + 1; + + return S.S_OK; + } + + *ppvObject = null; + + return E.E_NOINTERFACE; + } + + /// + private uint AddRef() + { + return (uint)Interlocked.Increment(ref this.referenceCount); + } + + /// + private uint Release() + { + uint referenceCount = (uint)Interlocked.Decrement(ref this.referenceCount); + + if (referenceCount == 0) + { + if (this.constantBuffer is not null) + { + NativeMemory.Free(this.constantBuffer); + } + + this.d2D1TransformMapperHandle.Free(); + + NativeMemory.Free(Unsafe.AsPointer(ref this)); + } + + return referenceCount; + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Translation/D2D1ShaderCompiler.ID3DInclude.cs b/src/ComputeSharp.D2D1/Shaders/Translation/D2D1ShaderCompiler.ID3DInclude.cs new file mode 100644 index 00000000..7e59f3ab --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Translation/D2D1ShaderCompiler.ID3DInclude.cs @@ -0,0 +1,153 @@ +using System; +using System.IO; +using System.Reflection; +using System.Runtime.InteropServices; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +#if NET6_0_OR_GREATER +using RuntimeHelpers = System.Runtime.CompilerServices.RuntimeHelpers; +#else +using RuntimeHelpers = ComputeSharp.D2D1.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute; +#endif + +namespace ComputeSharp.D2D1.Shaders.Translation; + +/// +partial class D2D1ShaderCompiler +{ + /// + /// A custom fallback implementation to use on systems with no support for it. + /// + private unsafe struct ID3DIncludeForD2DHelpers + { +#if !NET6_0_OR_GREATER + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int OpenDelegate(ID3DIncludeForD2DHelpers* @this, D3D_INCLUDE_TYPE IncludeType, sbyte* pFileName, void* pParentData, void** ppData, uint* pBytes); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int CloseDelegate(ID3DIncludeForD2DHelpers* @this, void* pData); + + /// + /// A cached instance wrapping . + /// + private static readonly OpenDelegate OpenWrapper = Open; + + /// + /// A cached instance wrapping . + /// + private static readonly CloseDelegate CloseWrapper = Close; +#endif + + /// + /// The shared method table pointer for all instances. + /// + private static readonly void** Vtbl = InitVtbl(); + + /// + /// A pointer to a buffer with the contents of d2d1effecthelpers.hlsli. + /// + private static void* d2D1EffectHelpersData; + + /// + /// The size of the buffer in . + /// + private static int d2D1EffectHelpersSize; + + /// + /// Builds the custom method table pointer for . + /// + /// The method table pointer for . + private static void** InitVtbl() + { + void** lpVtbl = (void**)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(ID3DIncludeForD2DHelpers), sizeof(void*) * 2); + +#if NET6_0_OR_GREATER + lpVtbl[0] = (delegate* unmanaged)&Open; + lpVtbl[1] = (delegate* unmanaged)&Close; +#else + lpVtbl[0] = (void*)Marshal.GetFunctionPointerForDelegate(OpenWrapper); + lpVtbl[1] = (void*)Marshal.GetFunctionPointerForDelegate(CloseWrapper); +#endif + + return lpVtbl; + } + + /// + /// The method table pointer for the current instance. + /// + private void** lpVtbl; + + /// + /// Creates and initializes a new instance. + /// + /// A pointer to a new instance. + public static ID3DIncludeForD2DHelpers* Create() + { + ID3DIncludeForD2DHelpers* @this = (ID3DIncludeForD2DHelpers*)NativeMemory.Alloc((nuint)sizeof(ID3DIncludeForD2DHelpers)); + + @this->lpVtbl = Vtbl; + + return @this; + } + + /// + [UnmanagedCallersOnly] + public static int Open(ID3DIncludeForD2DHelpers* @this, D3D_INCLUDE_TYPE IncludeType, sbyte* pFileName, void* pParentData, void** ppData, uint* pBytes) + { + if (new string(pFileName) == "d2d1effecthelpers.hlsli") + { + // Load the header if needed + if (d2D1EffectHelpersData is null) + { + d2D1EffectHelpersData = LoadD2D1EffectHelpersHeader(out d2D1EffectHelpersSize); + } + + *ppData = d2D1EffectHelpersData; + *pBytes = (uint)d2D1EffectHelpersSize; + + return S.S_OK; + } + + return S.S_FALSE; + } + + /// + [UnmanagedCallersOnly] + public static int Close(ID3DIncludeForD2DHelpers* @this, void* pData) + { + return S.S_OK; + } + + /// + /// Loads the d2d1effecthelpers.hlsli header into a persistent buffer. + /// + /// The size of the header. + /// A pointer to a buffer with the contents of d2d1effecthelpers.hlsli. + private static void* LoadD2D1EffectHelpersHeader(out int size) + { +#if SOURCE_GENERATOR + const string headerFilename = "ComputeSharp.D2D1.SourceGenerators.ComputeSharp.D2D1.Shaders.Translation.Headers.d2d1effecthelpers.hlsli"; +#else + const string headerFilename = "ComputeSharp.D2D1.Shaders.Translation.Headers.d2d1effecthelpers.hlsli"; +#endif + + using Stream source = Assembly.GetExecutingAssembly().GetManifestResourceStream(headerFilename)!; + using MemoryStream destination = new(); + + source.CopyTo(destination); + + byte[] buffer = destination.GetBuffer(); + + size = (int)destination.Position; + + void* pointer = NativeMemory.Alloc((nuint)size); + + buffer.AsSpan(0, size).CopyTo(new Span(pointer, size)); + + return pointer; + } + } +} diff --git a/src/ComputeSharp.D2D1/Shaders/Translation/D2D1ShaderCompiler.cs b/src/ComputeSharp.D2D1/Shaders/Translation/D2D1ShaderCompiler.cs new file mode 100644 index 00000000..9b879275 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Translation/D2D1ShaderCompiler.cs @@ -0,0 +1,355 @@ +using System; +using System.Buffers; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.RegularExpressions; +using ComputeSharp.D2D1.Exceptions; +using ComputeSharp.D2D1.Extensions; +#if !NET6_0_OR_GREATER +using ComputeSharp.D2D1.NetStandard.System.Text; +#endif +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +#pragma warning disable IDE1006 + +namespace ComputeSharp.D2D1.Shaders.Translation; + +/// +/// A that uses the FXC APIs to compile D2D1 pixel shaders. +/// +internal static unsafe partial class D2D1ShaderCompiler +{ + /// + /// The instance to load d2d1effecthelpers.hlsli. + /// + private static readonly ID3DIncludeForD2DHelpers* D3DIncludeForD2D1EffectHelpers = ID3DIncludeForD2DHelpers.Create(); + + /// + /// Compiles a new HLSL shader from the input source code. + /// + /// The HLSL source code to compile. + /// The shader profile to use to compile the shader. + /// Whether to enable linking support for the shader. + /// The bytecode for the compiled shader. + public static ComPtr Compile(ReadOnlySpan source, D2D1ShaderProfile shaderProfile, bool enableLinkingSupport) + { + // Compile the standalone D2D1 full shader + using ComPtr d3DBlobFullShader = CompileD2DFullShader(source, shaderProfile); + + if (!enableLinkingSupport) + { + return d3DBlobFullShader.Move(); + } + + // Compile the export function and embed it as private data if requested + using ComPtr d3DBlobFunction = CompileD2DFunction(source, shaderProfile); + using ComPtr d3DBlobLinked = EmbedD2DFunctionPrivateData(d3DBlobFullShader.Get(), d3DBlobFunction.Get()); + + return d3DBlobLinked.Move(); + } + + /// + /// Compiles a D2D1 pixel shader with D2D_FULL_SHADER. + /// + /// The HLSL source code to compile. + /// The shader profile to use to compile the shader. + /// The bytecode for the compiled shader. + private static ComPtr CompileD2DFullShader(ReadOnlySpan source, D2D1ShaderProfile shaderProfile) + { + // Encode the HLSL source to ASCII + int maxLength = Encoding.ASCII.GetMaxByteCount(source.Length); + byte[] buffer = ArrayPool.Shared.Rent(maxLength); + int writtenBytes = Encoding.ASCII.GetBytes(source, buffer); + + using ComPtr d3DBlobBytecode = default; + using ComPtr d3DBlobErrors = default; + + int hResult; + + fixed (byte* bufferPtr = buffer) + { + // Prepare the macros for full shader compilation: + // + // -D D2D_FULL_SHADER + // -D D2D_ENTRY=Execute + D3D_SHADER_MACRO* macros = stackalloc D3D_SHADER_MACRO[] + { + new() + { + Name = (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(ASCII.D2D_FULL_SHADER)), + Definition = (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(ASCII.NullTerminator)) + }, + new() + { + Name = (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(ASCII.D2D_ENTRY)), + Definition = (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(ASCII.Execute)) + }, + new() + }; + + // Compile the shader with -ps_5_0 -O3 -We -Zpr + hResult = DirectX.D3DCompile( + pSrcData: bufferPtr, + SrcDataSize: (nuint)writtenBytes, + pSourceName: null, + pDefines: macros, + pInclude: D3DIncludeForD2D1EffectHelpers, + pEntrypoint: (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(ASCII.Execute)), + pTarget: (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(ASCII.GetPixelShaderProfile(shaderProfile))), + Flags1: D3DCOMPILE.D3DCOMPILE_OPTIMIZATION_LEVEL3 | D3DCOMPILE.D3DCOMPILE_WARNINGS_ARE_ERRORS | D3DCOMPILE.D3DCOMPILE_PACK_MATRIX_ROW_MAJOR, + Flags2: 0, + ppCode: d3DBlobBytecode.GetAddressOf(), + ppErrorMsgs: d3DBlobErrors.GetAddressOf()); + } + + ArrayPool.Shared.Return(buffer); + + // Throw if an error was retrieved, then also double check the HRESULT + if (d3DBlobErrors.Get() is not null) + { + ThrowHslsCompilationException(d3DBlobErrors.Get()); + } + + hResult.Assert(); + + return d3DBlobBytecode.Move(); + } + + /// + /// Compiles a D2D1 pixel shader with D2D_FUNCTION. + /// + /// The HLSL source code to compile. + /// The shader profile to use to compile the shader. + /// The bytecode for the compiled shader. + private static ComPtr CompileD2DFunction(ReadOnlySpan source, D2D1ShaderProfile shaderProfile) + { + int maxLength = Encoding.ASCII.GetMaxByteCount(source.Length); + byte[] buffer = ArrayPool.Shared.Rent(maxLength); + int writtenBytes = Encoding.ASCII.GetBytes(source, buffer); + + using ComPtr d3DBlobBytecode = default; + using ComPtr d3DBlobErrors = default; + + int hResult; + + fixed (byte* bufferPtr = buffer) + { + // Prepare the macros for full shader compilation: + // + // -D D2D_FUNCTION + // -D D2D_ENTRY=Execute + D3D_SHADER_MACRO* macros = stackalloc D3D_SHADER_MACRO[] + { + new() + { + Name = (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(ASCII.D2D_FUNCTION)), + Definition = (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(ASCII.NullTerminator)) + }, + new() + { + Name = (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(ASCII.D2D_ENTRY)), + Definition = (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(ASCII.Execute)) + }, + new() + }; + + // Compile the shader with -lib_5_0 -O3 -We -Zpr + hResult = DirectX.D3DCompile( + pSrcData: bufferPtr, + SrcDataSize: (nuint)writtenBytes, + pSourceName: null, + pDefines: macros, + pInclude: D3DIncludeForD2D1EffectHelpers, + pEntrypoint: null, + pTarget: (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(ASCII.GetLibraryProfile(shaderProfile))), + Flags1: D3DCOMPILE.D3DCOMPILE_OPTIMIZATION_LEVEL3 | D3DCOMPILE.D3DCOMPILE_WARNINGS_ARE_ERRORS | D3DCOMPILE.D3DCOMPILE_PACK_MATRIX_ROW_MAJOR, + Flags2: 0, + ppCode: d3DBlobBytecode.GetAddressOf(), + ppErrorMsgs: d3DBlobErrors.GetAddressOf()); + } + + ArrayPool.Shared.Return(buffer); + + // Check for errors and double check like above + if (d3DBlobErrors.Get() is not null) + { + ThrowHslsCompilationException(d3DBlobErrors.Get()); + } + + hResult.Assert(); + + return d3DBlobBytecode.Move(); + } + + /// + /// Embeds the bytecode for an exported shader as private data into another shader bytecode. + /// + /// The bytecode produced by . + /// The bytecode produced by . + /// An instance with the combined data of and . + private static ComPtr EmbedD2DFunctionPrivateData(ID3DBlob* shaderBlob, ID3DBlob* exportBlob) + { + void* shaderPtr = shaderBlob->GetBufferPointer(); + nuint shaderSize = shaderBlob->GetBufferSize(); + + void* exportPtr = exportBlob->GetBufferPointer(); + nuint exportSize = exportBlob->GetBufferSize(); + + using ComPtr resultBlob = default; + + DirectX.D3DSetBlobPart( + pSrcData: shaderPtr, + SrcDataSize: shaderSize, + Part: D3D_BLOB_PART.D3D_BLOB_PRIVATE_DATA, + Flags: 0, + pPart: exportPtr, + PartSize: exportSize, + ppNewShader: resultBlob.GetAddressOf()).Assert(); + + return resultBlob.Move(); + } + + /// + /// Throws an exception when a shader compilation fails. + /// + /// The input (faulting) operation. + /// This method always throws and never actually returs. + [DoesNotReturn] + [MethodImpl(MethodImplOptions.NoInlining)] + private static void ThrowHslsCompilationException(ID3DBlob* d3DOperationResult) + { + string message = new((sbyte*)d3DOperationResult->GetBufferPointer()); + + // The error message will be in a format like this: + // "C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\Roslyn\Shader@0x0000019AD1B4BA70(22,32-35): error X3004: undeclared identifier 'this'" + // This regex tries to match the unnecessary header and remove it, if present. This doesn't need to be bulletproof, and this regex should match all cases anyway. + message = Regex.Replace(message, @"^[A-Z]:\\[^:]+: (\w+ \w+:)", static m => m.Groups[1].Value, RegexOptions.Multiline).Trim(); + + // Add a trailing '.' if not present + if (message is { Length: > 0 } && + message[message.Length - 1] != '.') + { + message += '.'; + } + + throw new FxcCompilationException(message); + } + + /// + /// A container for ASCII encoded, null-terminated constant strings. + /// + private static class ASCII + { + /// + /// Gets a with the "D2D_FUNCTION" ASCII text. + /// + public static ReadOnlySpan D2D_FUNCTION => new[] { (byte)'D', (byte)'2', (byte)'D', (byte)'_', (byte)'F', (byte)'U', (byte)'N', (byte)'C', (byte)'T', (byte)'I', (byte)'O', (byte)'N', (byte)'\0' }; + + /// + /// Gets a with the "D2D_FULL_SHADER" ASCII text. + /// + public static ReadOnlySpan D2D_FULL_SHADER => new[] { (byte)'D', (byte)'2', (byte)'D', (byte)'_', (byte)'F', (byte)'U', (byte)'L', (byte)'L', (byte)'_', (byte)'S', (byte)'H', (byte)'A', (byte)'D', (byte)'E', (byte)'R', (byte)'\0' }; + + /// + /// Gets a with the '\0' ASCII character. + /// + public static ReadOnlySpan NullTerminator => new[] { (byte)'\0' }; + + /// + /// Gets a with the "D2D_ENTRY" ASCII text. + /// + public static ReadOnlySpan D2D_ENTRY => new[] { (byte)'D', (byte)'2', (byte)'D', (byte)'_', (byte)'E', (byte)'N', (byte)'T', (byte)'R', (byte)'Y', (byte)'\0' }; + + /// + /// Gets a with the "Execute" ASCII text. + /// + public static ReadOnlySpan Execute => new[] { (byte)'E', (byte)'x', (byte)'e', (byte)'c', (byte)'u', (byte)'t', (byte)'e', (byte)'\0' }; + + /// + /// Gets a with the "lib_4_0_level_9_1" ASCII text. + /// + private static ReadOnlySpan lib_4_0_level_9_1 => new[] { (byte)'l', (byte)'i', (byte)'b', (byte)'_', (byte)'4', (byte)'_', (byte)'0', (byte)'_', (byte)'l', (byte)'e', (byte)'v', (byte)'e', (byte)'l', (byte)'_', (byte)'9', (byte)'_', (byte)'1', (byte)'\0' }; + + /// + /// Gets a with the "lib_4_0_level_9_3" ASCII text. + /// + private static ReadOnlySpan lib_4_0_level_9_3 => new[] { (byte)'l', (byte)'i', (byte)'b', (byte)'_', (byte)'4', (byte)'_', (byte)'0', (byte)'_', (byte)'l', (byte)'e', (byte)'v', (byte)'e', (byte)'l', (byte)'_', (byte)'9', (byte)'_', (byte)'3', (byte)'\0' }; + + /// + /// Gets a with the "lib_4_0" ASCII text. + /// + private static ReadOnlySpan lib_4_0 => new[] { (byte)'l', (byte)'i', (byte)'b', (byte)'_', (byte)'4', (byte)'_', (byte)'0', (byte)'\0' }; + + /// + /// Gets a with the "lib_4_1" ASCII text. + /// + private static ReadOnlySpan lib_4_1 => new[] { (byte)'l', (byte)'i', (byte)'b', (byte)'_', (byte)'4', (byte)'_', (byte)'1', (byte)'\0' }; + + /// + /// Gets a with the "lib_5_0" ASCII text. + /// + private static ReadOnlySpan lib_5_0 => new[] { (byte)'l', (byte)'i', (byte)'b', (byte)'_', (byte)'5', (byte)'_', (byte)'0', (byte)'\0' }; + + /// + /// Gets a with the "ps_4_0_level_9_1" ASCII text. + /// + private static ReadOnlySpan ps_4_0_level_9_1 => new[] { (byte)'p', (byte)'s', (byte)'_', (byte)'4', (byte)'_', (byte)'0', (byte)'_', (byte)'l', (byte)'e', (byte)'v', (byte)'e', (byte)'l', (byte)'_', (byte)'9', (byte)'_', (byte)'1', (byte)'\0' }; + + /// + /// Gets a with the "ps_4_0_level_9_3" ASCII text. + /// + private static ReadOnlySpan ps_4_0_level_9_3 => new[] { (byte)'p', (byte)'s', (byte)'_', (byte)'4', (byte)'_', (byte)'0', (byte)'_', (byte)'l', (byte)'e', (byte)'v', (byte)'e', (byte)'l', (byte)'_', (byte)'9', (byte)'_', (byte)'3', (byte)'\0' }; + + /// + /// Gets a with the "ps_4_0" ASCII text. + /// + private static ReadOnlySpan ps_4_0 => new[] { (byte)'p', (byte)'s', (byte)'_', (byte)'4', (byte)'_', (byte)'0', (byte)'\0' }; + + /// + /// Gets a with the "ps_4_1" ASCII text. + /// + private static ReadOnlySpan ps_4_1 => new[] { (byte)'p', (byte)'s', (byte)'_', (byte)'4', (byte)'_', (byte)'1', (byte)'\0' }; + + /// + /// Gets a with the "ps_5_0" ASCII text. + /// + private static ReadOnlySpan ps_5_0 => new[] { (byte)'p', (byte)'s', (byte)'_', (byte)'5', (byte)'_', (byte)'0', (byte)'\0' }; + + /// + /// Gets a for a given shader profile, for a library. + /// + /// The input shaader profile to use. + /// A for a given shader profile, for a library. + public static ReadOnlySpan GetLibraryProfile(D2D1ShaderProfile shaderProfile) + { + return shaderProfile switch + { + D2D1ShaderProfile.PixelShader40Level91 => lib_4_0_level_9_1, + D2D1ShaderProfile.PixelShader40Level93 => lib_4_0_level_9_3, + D2D1ShaderProfile.PixelShader40 => lib_4_0, + D2D1ShaderProfile.PixelShader41 => lib_4_1, + _ => lib_5_0 + }; + } + + /// + /// Gets a for a given shader profile, for a full shader. + /// + /// The input shaader profile to use. + /// A for a given shader profile, for a full shader. + public static ReadOnlySpan GetPixelShaderProfile(D2D1ShaderProfile shaderProfile) + { + return shaderProfile switch + { + D2D1ShaderProfile.PixelShader40Level91 => ps_4_0_level_9_1, + D2D1ShaderProfile.PixelShader40Level93 => ps_4_0_level_9_3, + D2D1ShaderProfile.PixelShader40 => ps_4_0, + D2D1ShaderProfile.PixelShader41 => ps_4_1, + _ => ps_5_0 + }; + } + } +} diff --git a/src/ComputeSharp.D2D1/Shaders/Translation/Headers/d2d1effecthelpers.hlsli b/src/ComputeSharp.D2D1/Shaders/Translation/Headers/d2d1effecthelpers.hlsli new file mode 100644 index 00000000..aaa56597 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Translation/Headers/d2d1effecthelpers.hlsli @@ -0,0 +1,316 @@ +//--------------------------------------------------------------------------- +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// This file is automatically generated. Please do not edit it directly. +// +//--------------------------------------------------------------------------- + +// File contents: +// - Helpers methods for authoring D2D Effect shader code. +// These are located at the end of the file (D2DGetInput, etc.). +// - The top portion contains definitions and initialization required by the helpers. +// These elements are prefaced with "__D2D" and can be safely ignored. +// +// To use these helpers, the following values must be defined before inclusion: +// D2D_INPUT_COUNT - The number of texture inputs to the effect. +// D2D_INPUT[N]_SIMPLE or D2D_INPUT[N]_COMPLEX - How the effect will sample each input. (If unspecificed, defaults to _COMPLEX.) +// D2D_ENTRY - The name of the entry point being compiled. This will usually be defined on the command line at compilation time. +// +// The following values can be optionally defined: +// D2D_FUNCTION - Compile the entry point as an export function. This will usually be defined on the command line at compilation time. +// D2D_FULL_SHADER - Compile the entry point as a full shader. This will usually be defined on the command line at compilation time. +// D2D_FULL_SHADER_ONLY - Only compile the in-scope entry points to full shaders, never to export functions. +// + +#define __D2D_DEFINE_PS_GLOBALS(inputIndex) \ +Texture2D InputTexture##inputIndex : register(t##inputIndex); \ +SamplerState InputSampler##inputIndex : register(s##inputIndex); \ + +// Define a texture and sampler pair for each D2D effect input. +#if (D2D_INPUT_COUNT >= 1) +__D2D_DEFINE_PS_GLOBALS(0) +#endif +#if (D2D_INPUT_COUNT >= 2) +__D2D_DEFINE_PS_GLOBALS(1) +#endif +#if (D2D_INPUT_COUNT >= 3) +__D2D_DEFINE_PS_GLOBALS(2) +#endif +#if (D2D_INPUT_COUNT >= 4) +__D2D_DEFINE_PS_GLOBALS(3) +#endif +#if (D2D_INPUT_COUNT >= 5) +__D2D_DEFINE_PS_GLOBALS(4) +#endif +#if (D2D_INPUT_COUNT >= 6) +__D2D_DEFINE_PS_GLOBALS(5) +#endif +#if (D2D_INPUT_COUNT >= 7) +__D2D_DEFINE_PS_GLOBALS(6) +#endif +#if (D2D_INPUT_COUNT >= 8) +__D2D_DEFINE_PS_GLOBALS(7) +#endif + +#define __D2D_MAXIMUM_INPUT_COUNT 8 + +// Validate that all required shader information has been defined. +#ifndef D2D_INPUT_COUNT +#error D2D_INPUT_COUNT is undefined. +#endif + +#if (D2D_INPUT_COUNT > __D2D_MAXIMUM_INPUT_COUNT) +#error D2D_INPUT_COUNT exceeds the maximum input count. +#endif + +// Define global statics to hold the values needed by intrinsic methods. +// These values are initialized by the entry point wrapper before calling into the +// effect's shader implementation. +#if !defined(D2D_FUNCTION) || defined(D2D_REQUIRES_SCENE_POSITION) +static float4 __d2dstatic_scenePos = float4(0, 0, 0, 0); +#endif + +#define __D2D_DEFINE_INPUT_STATICS(inputIndex) \ +static float4 __d2dstatic_input##inputIndex = float4(0, 0, 0, 0); \ +static float4 __d2dstatic_uv##inputIndex = float4(0, 0, 0, 0); \ + +#if (D2D_INPUT_COUNT >= 1) +__D2D_DEFINE_INPUT_STATICS(0) +#endif +#if (D2D_INPUT_COUNT >= 2) +__D2D_DEFINE_INPUT_STATICS(1) +#endif +#if (D2D_INPUT_COUNT >= 3) +__D2D_DEFINE_INPUT_STATICS(2) +#endif +#if (D2D_INPUT_COUNT >= 4) +__D2D_DEFINE_INPUT_STATICS(3) +#endif +#if (D2D_INPUT_COUNT >= 5) +__D2D_DEFINE_INPUT_STATICS(4) +#endif +#if (D2D_INPUT_COUNT >= 6) +__D2D_DEFINE_INPUT_STATICS(5) +#endif +#if (D2D_INPUT_COUNT >= 7) +__D2D_DEFINE_INPUT_STATICS(6) +#endif +#if (D2D_INPUT_COUNT >= 8) +__D2D_DEFINE_INPUT_STATICS(7) +#endif + +// Define the scene position parameter according to whether the shader requires it, +// and whether it is the only parameter. +// The scene position input always needs to be defined for full shaders. +#if (!defined(D2D_FUNCTION) || defined(D2D_REQUIRES_SCENE_POSITION)) +#if (D2D_INPUT_COUNT == 0) +#define __D2D_SCENE_POS float4 __d2dinput_scenePos : SCENE_POSITION +#define __D2D_INIT_STATIC_SCENE_POS __d2dstatic_scenePos = __d2dinput_scenePos +#else +#define __D2D_SCENE_POS float4 __d2dinput_scenePos : SCENE_POSITION, +#define __D2D_INIT_STATIC_SCENE_POS __d2dstatic_scenePos = __d2dinput_scenePos; + #endif +#else + #define __D2D_SCENE_POS + #define __D2D_INIT_STATIC_SCENE_POS +#endif + +// When compiling a function version, simple and complex inputs have different definitions. +// When compiling a full shader, they have the same definition. +// Access to input parameters also differs between functions and full shaders. +#if defined(D2D_FUNCTION) +#define __D2D_SIMPLE_INPUT(index) float4 __d2dinput_color##index : INPUT##index +#define __D2D_INIT_SIMPLE_STATIC(index) __d2dstatic_input##index = __d2dinput_color##index +#else +#define __D2D_SIMPLE_INPUT(index) float4 __d2dinput_uv##index : TEXCOORD##index +#define __D2D_INIT_SIMPLE_STATIC(index) __d2dstatic_uv##index = __d2dinput_uv##index +#endif + +#define __D2D_COMPLEX_INPUT(index) float4 __d2dinput_uv##index : TEXCOORD##index +#define __D2D_INIT_COMPLEX_STATIC(index) __d2dstatic_uv##index = __d2dinput_uv##index + +#define __D2D_SAMPLE_INPUT(index) InputTexture##index.Sample(InputSampler##index, __d2dstatic_uv##index.xy) + +// Define each input as either simple or complex. +#if defined(D2D_INPUT0_SIMPLE) +#define __D2D_INPUT0 __D2D_SIMPLE_INPUT(0) +#define __D2D_INIT_STATIC0 __D2D_INIT_SIMPLE_STATIC(0) +#define __D2D_GET_INPUT0 __d2dstatic_input0 +#else +#define __D2D_INPUT0 __D2D_COMPLEX_INPUT(0) +#define __D2D_INIT_STATIC0 __D2D_INIT_COMPLEX_STATIC(0) +#define __D2D_GET_INPUT0 __D2D_SAMPLE_INPUT(0) +#endif +#if defined(D2D_INPUT1_SIMPLE) +#define __D2D_INPUT1 __D2D_SIMPLE_INPUT(1) +#define __D2D_INIT_STATIC1 __D2D_INIT_SIMPLE_STATIC(1) +#define __D2D_GET_INPUT1 __d2dstatic_input1 +#else +#define __D2D_INPUT1 __D2D_COMPLEX_INPUT(1) +#define __D2D_INIT_STATIC1 __D2D_INIT_COMPLEX_STATIC(1) +#define __D2D_GET_INPUT1 __D2D_SAMPLE_INPUT(1) +#endif +#if defined(D2D_INPUT2_SIMPLE) +#define __D2D_INPUT2 __D2D_SIMPLE_INPUT(2) +#define __D2D_INIT_STATIC2 __D2D_INIT_SIMPLE_STATIC(2) +#define __D2D_GET_INPUT2 __d2dstatic_input2 +#else +#define __D2D_INPUT2 __D2D_COMPLEX_INPUT(2) +#define __D2D_INIT_STATIC2 __D2D_INIT_COMPLEX_STATIC(2) +#define __D2D_GET_INPUT2 __D2D_SAMPLE_INPUT(2) +#endif +#if defined(D2D_INPUT3_SIMPLE) +#define __D2D_INPUT3 __D2D_SIMPLE_INPUT(3) +#define __D2D_INIT_STATIC3 __D2D_INIT_SIMPLE_STATIC(3) +#define __D2D_GET_INPUT3 __d2dstatic_input3 +#else +#define __D2D_INPUT3 __D2D_COMPLEX_INPUT(3) +#define __D2D_INIT_STATIC3 __D2D_INIT_COMPLEX_STATIC(3) +#define __D2D_GET_INPUT3 __D2D_SAMPLE_INPUT(3) +#endif +#if defined(D2D_INPUT4_SIMPLE) +#define __D2D_INPUT4 __D2D_SIMPLE_INPUT(4) +#define __D2D_INIT_STATIC4 __D2D_INIT_SIMPLE_STATIC(4) +#define __D2D_GET_INPUT4 __d2dstatic_input4 +#else +#define __D2D_INPUT4 __D2D_COMPLEX_INPUT(4) +#define __D2D_INIT_STATIC4 __D2D_INIT_COMPLEX_STATIC(4) +#define __D2D_GET_INPUT4 __D2D_SAMPLE_INPUT(4) +#endif +#if defined(D2D_INPUT5_SIMPLE) +#define __D2D_INPUT5 __D2D_SIMPLE_INPUT(5) +#define __D2D_INIT_STATIC5 __D2D_INIT_SIMPLE_STATIC(5) +#define __D2D_GET_INPUT5 __d2dstatic_input5 +#else +#define __D2D_INPUT5 __D2D_COMPLEX_INPUT(5) +#define __D2D_INIT_STATIC5 __D2D_INIT_COMPLEX_STATIC(5) +#define __D2D_GET_INPUT5 __D2D_SAMPLE_INPUT(5) +#endif +#if defined(D2D_INPUT6_SIMPLE) +#define __D2D_INPUT6 __D2D_SIMPLE_INPUT(6) +#define __D2D_INIT_STATIC6 __D2D_INIT_SIMPLE_STATIC(6) +#define __D2D_GET_INPUT6 __d2dstatic_input6 +#else +#define __D2D_INPUT6 __D2D_COMPLEX_INPUT(6) +#define __D2D_INIT_STATIC6 __D2D_INIT_COMPLEX_STATIC(6) +#define __D2D_GET_INPUT6 __D2D_SAMPLE_INPUT(6) +#endif +#if defined(D2D_INPUT7_SIMPLE) +#define __D2D_INPUT7 __D2D_SIMPLE_INPUT(7) +#define __D2D_INIT_STATIC7 __D2D_INIT_SIMPLE_STATIC(7) +#define __D2D_GET_INPUT7 __d2dstatic_input7 +#else +#define __D2D_INPUT7 __D2D_COMPLEX_INPUT(7) +#define __D2D_INIT_STATIC7 __D2D_INIT_COMPLEX_STATIC(7) +#define __D2D_GET_INPUT7 __D2D_SAMPLE_INPUT(7) +#endif +#if defined(D2D_INPUT8_SIMPLE) +#define __D2D_INPUT8 __D2D_SIMPLE_INPUT(8) +#define __D2D_INIT_STATIC8 __D2D_INIT_SIMPLE_STATIC(8) +#define __D2D_GET_INPUT8 __d2dstatic_input8 +#else +#define __D2D_INPUT8 __D2D_COMPLEX_INPUT(8) +#define __D2D_INIT_STATIC8 __D2D_INIT_COMPLEX_STATIC(8) +#define __D2D_GET_INPUT8 __D2D_SAMPLE_INPUT(8) +#endif + +// Define the export function inputs based on the defined input count and types. +#if (D2D_INPUT_COUNT == 0) +#define __D2D_FUNCTION_INPUTS __D2D_SCENE_POS +#define __D2D_INIT_STATICS __D2D_INIT_STATIC_SCENE_POS +#elif (D2D_INPUT_COUNT == 1) +#define __D2D_FUNCTION_INPUTS __D2D_SCENE_POS __D2D_INPUT0 +#define __D2D_INIT_STATICS __D2D_INIT_STATIC_SCENE_POS __D2D_INIT_STATIC0 +#elif (D2D_INPUT_COUNT == 2) +#define __D2D_FUNCTION_INPUTS __D2D_SCENE_POS __D2D_INPUT0, __D2D_INPUT1 +#define __D2D_INIT_STATICS __D2D_INIT_STATIC_SCENE_POS __D2D_INIT_STATIC0; __D2D_INIT_STATIC1 +#elif (D2D_INPUT_COUNT == 3) +#define __D2D_FUNCTION_INPUTS __D2D_SCENE_POS __D2D_INPUT0, __D2D_INPUT1, __D2D_INPUT2 +#define __D2D_INIT_STATICS __D2D_INIT_STATIC_SCENE_POS __D2D_INIT_STATIC0; __D2D_INIT_STATIC1; __D2D_INIT_STATIC2 +#elif (D2D_INPUT_COUNT == 4) +#define __D2D_FUNCTION_INPUTS __D2D_SCENE_POS __D2D_INPUT0, __D2D_INPUT1, __D2D_INPUT2, __D2D_INPUT3 +#define __D2D_INIT_STATICS __D2D_INIT_STATIC_SCENE_POS __D2D_INIT_STATIC0; __D2D_INIT_STATIC1; __D2D_INIT_STATIC2; __D2D_INIT_STATIC3 +#elif (D2D_INPUT_COUNT == 5) +#define __D2D_FUNCTION_INPUTS __D2D_SCENE_POS __D2D_INPUT0, __D2D_INPUT1, __D2D_INPUT2, __D2D_INPUT3, __D2D_INPUT4 +#define __D2D_INIT_STATICS __D2D_INIT_STATIC_SCENE_POS __D2D_INIT_STATIC0; __D2D_INIT_STATIC1; __D2D_INIT_STATIC2; __D2D_INIT_STATIC3; __D2D_INIT_STATIC4 +#elif (D2D_INPUT_COUNT == 6) +#define __D2D_FUNCTION_INPUTS __D2D_SCENE_POS __D2D_INPUT0, __D2D_INPUT1, __D2D_INPUT2, __D2D_INPUT3, __D2D_INPUT4, __D2D_INPUT5 +#define __D2D_INIT_STATICS __D2D_INIT_STATIC_SCENE_POS __D2D_INIT_STATIC0; __D2D_INIT_STATIC1; __D2D_INIT_STATIC2; __D2D_INIT_STATIC3; __D2D_INIT_STATIC4; __D2D_INIT_STATIC5 +#elif (D2D_INPUT_COUNT == 7) +#define __D2D_FUNCTION_INPUTS __D2D_SCENE_POS __D2D_INPUT0, __D2D_INPUT1, __D2D_INPUT2, __D2D_INPUT3, __D2D_INPUT4, __D2D_INPUT5, __D2D_INPUT6 +#define __D2D_INIT_STATICS __D2D_INIT_STATIC_SCENE_POS __D2D_INIT_STATIC0; __D2D_INIT_STATIC1; __D2D_INIT_STATIC2; __D2D_INIT_STATIC3; __D2D_INIT_STATIC4; __D2D_INIT_STATIC5; __D2D_INIT_STATIC6 +#elif (D2D_INPUT_COUNT == 8) +#define __D2D_FUNCTION_INPUTS __D2D_SCENE_POS __D2D_INPUT0, __D2D_INPUT1, __D2D_INPUT2, __D2D_INPUT3, __D2D_INPUT4, __D2D_INPUT5, __D2D_INPUT6, __D2D_INPUT7 +#define __D2D_INIT_STATICS __D2D_INIT_STATIC_SCENE_POS __D2D_INIT_STATIC0; __D2D_INIT_STATIC1; __D2D_INIT_STATIC2; __D2D_INIT_STATIC3; __D2D_INIT_STATIC4; __D2D_INIT_STATIC5; __D2D_INIT_STATIC6; __D2D_INIT_STATIC7 +#endif + +#if !defined(CONCAT) +#define CONCAT(str1, str2) str1##str2 +#endif + +// Rename the entry point target function so that the actual entry point can use the name. +// This expansion is the same for both full shaders and functions. +#define D2D_PS_ENTRY(name) float4 CONCAT(name, _Impl)() + +// If neither D2D_FUNCTION or D2D_FULL_SHADER is defined, behave as if D2D_FULL_SHADER is defined. +#if defined(D2D_FUNCTION) && !defined(D2D_FULL_SHADER_ONLY) + + // Replaces simple samples with either static variable or an actual sample, + // depending on whether the input is declared as simple or complex. + #define D2DGetInput(index) __D2D_GET_INPUT##index + + #if !defined(D2D_CUSTOM_ENTRY) + // Declare function prototype for the target function so that it can be referenced before definition. + // D2D_ENTRY is a macro whose actual name resolves to the effect's target "entry point" function. + float4 CONCAT(D2D_ENTRY, _Impl)(); + + // This is the actual entry point definition, which forwards the call to the target function. + export float4 D2D_func_entry(__D2D_FUNCTION_INPUTS) + { + __D2D_INIT_STATICS; + return CONCAT(D2D_ENTRY, _Impl)(); + } + + #endif + +#else // !defined(D2D_FUNCTION) + + // Replaces simple samples with actual samples. + #define D2DGetInput(index) __D2D_SAMPLE_INPUT(index) + + #if !defined(D2D_CUSTOM_ENTRY) + // Declare function prototype for the target function so that it can be referenced before definition. + // D2D_ENTRY is a macro whose actual name resolves to the effect's target "entry point" function. + float4 CONCAT(D2D_ENTRY, _Impl)(); + + // This is the actual entry point definition, which forwards the call to the target function. + float4 D2D_ENTRY (float4 pos : SV_POSITION, __D2D_FUNCTION_INPUTS) : SV_TARGET + { + __D2D_INIT_STATICS; + return CONCAT(D2D_ENTRY, _Impl)(); + } + + #endif + +#endif // D2D_FUNCTION + +//=============================================================== +// Along with D2DGetInput defined above, the following macros and +// methods define D2D intrinsics for use in effect shader code. +//=============================================================== + +#if !defined(D2D_FUNCTION) || defined(D2D_REQUIRES_SCENE_POSITION) +inline float4 D2DGetScenePosition() +{ + return __d2dstatic_scenePos; +} +#endif + +#define D2DGetInputCoordinate(index) __d2dstatic_uv##index + +#define D2DSampleInput(index, position) InputTexture##index.Sample(InputSampler##index, position) + +#define D2DSampleInputAtOffset(index, offset) InputTexture##index.Sample(InputSampler##index, __d2dstatic_uv##index.xy + offset * __d2dstatic_uv##index.zw) + +#define D2DSampleInputAtPosition(index, pos) InputTexture##index.Sample(InputSampler##index, __d2dstatic_uv##index.xy + __d2dstatic_uv##index.zw * (pos - __d2dstatic_scenePos.xy)) + diff --git a/src/ComputeSharp.D2D1/Shaders/Translation/__Internals/D2D1ShaderCompiler.cs b/src/ComputeSharp.D2D1/Shaders/Translation/__Internals/D2D1ShaderCompiler.cs new file mode 100644 index 00000000..47867a3a --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Translation/__Internals/D2D1ShaderCompiler.cs @@ -0,0 +1,38 @@ +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.D2D1.__Internals; + +/// +/// A that uses the DXC APIs to compile compute shaders. +/// +[EditorBrowsable(EditorBrowsableState.Never)] +[Obsolete("This type is not intended to be used directly by user code")] +public static class D2D1ShaderCompiler +{ + /// + /// Compiles a new HLSL shader from the input source code. + /// + /// The type of bytecode loader being used. + /// The type of D2D1 shader being dispatched. + /// The instance to use to load the bytecode. + /// The input instance representing the D2D1 shader to run. + /// The shader profile to use to compile the shader. + /// Whether to enable linking support for the shader. + public static unsafe void LoadDynamicBytecode(ref TLoader loader, in T shader, D2D1ShaderProfile? shaderProfile, bool enableLinkingSupport) + where TLoader : struct, ID2D1BytecodeLoader + where T : struct, ID2D1Shader + { + Unsafe.AsRef(in shader).BuildHlslSource(out string hlslSource); + + using ComPtr d3DBlobBytecode = Shaders.Translation.D2D1ShaderCompiler.Compile( + hlslSource.AsSpan(), + shaderProfile ?? D2D1ShaderProfile.PixelShader50, + enableLinkingSupport); + + loader.LoadDynamicBytecode((IntPtr)d3DBlobBytecode.Get()); + } +} diff --git a/src/ComputeSharp.Dynamic.Package/ComputeSharp.Dynamic.Package.msbuildproj b/src/ComputeSharp.Dynamic.Package/ComputeSharp.Dynamic.Package.msbuildproj index 4705f643..cb63e3af 100644 --- a/src/ComputeSharp.Dynamic.Package/ComputeSharp.Dynamic.Package.msbuildproj +++ b/src/ComputeSharp.Dynamic.Package/ComputeSharp.Dynamic.Package.msbuildproj @@ -11,7 +11,7 @@ - + diff --git a/src/ComputeSharp.Dynamic/ComputeSharp.Dynamic.csproj b/src/ComputeSharp.Dynamic/ComputeSharp.Dynamic.csproj index 4b638e24..7c23d229 100644 --- a/src/ComputeSharp.Dynamic/ComputeSharp.Dynamic.csproj +++ b/src/ComputeSharp.Dynamic/ComputeSharp.Dynamic.csproj @@ -12,15 +12,13 @@ true - + - + diff --git a/src/ComputeSharp.Dynamic/Shaders/Exceptions/HlslCompilationException.cs b/src/ComputeSharp.Dynamic/Shaders/Exceptions/DxcCompilationException.cs similarity index 85% rename from src/ComputeSharp.Dynamic/Shaders/Exceptions/HlslCompilationException.cs rename to src/ComputeSharp.Dynamic/Shaders/Exceptions/DxcCompilationException.cs index f0b3aa06..3c315dd7 100644 --- a/src/ComputeSharp.Dynamic/Shaders/Exceptions/HlslCompilationException.cs +++ b/src/ComputeSharp.Dynamic/Shaders/Exceptions/DxcCompilationException.cs @@ -6,13 +6,13 @@ namespace ComputeSharp.Exceptions; /// /// A custom type that indicates when a shader compilation with the DXC compiler has failed. /// -public sealed class HlslCompilationException : Exception +public sealed class DxcCompilationException : Exception { /// - /// Creates a new instance. + /// Creates a new instance. /// /// The error message produced by the DXC compiler. - internal HlslCompilationException(string error) + internal DxcCompilationException(string error) : base(GetExceptionMessage(error)) { } @@ -21,7 +21,7 @@ public sealed class HlslCompilationException : Exception /// Gets a formatted exception message for a given compilation error. /// /// The input compilatin error message from the DXC compiler. - /// A formatted error message for a new instance. + /// A formatted error message for a new instance. private static string GetExceptionMessage(string error) { StringBuilder builder = new(512); diff --git a/src/ComputeSharp.Dynamic/Shaders/Interop/ReflectionServices.cs b/src/ComputeSharp.Dynamic/Shaders/Interop/ReflectionServices.cs index 394b55f3..51a04792 100644 --- a/src/ComputeSharp.Dynamic/Shaders/Interop/ReflectionServices.cs +++ b/src/ComputeSharp.Dynamic/Shaders/Interop/ReflectionServices.cs @@ -104,9 +104,9 @@ public static class ReflectionServices private static unsafe ShaderInfo GetNonGenericShaderInfo(in T shader) where T : struct, IShader { - Unsafe.AsRef(in shader).BuildHlslString(out ArrayPoolStringBuilder shaderSource, 1, 1, 1); + Unsafe.AsRef(in shader).BuildHlslSource(out ArrayPoolStringBuilder shaderSource, 1, 1, 1); - using ComPtr dxcBlobBytecode = Shaders.Translation.ShaderCompiler.Instance.CompileShader(shaderSource.WrittenSpan); + using ComPtr dxcBlobBytecode = Shaders.Translation.ShaderCompiler.Instance.Compile(shaderSource.WrittenSpan); shaderSource.Dispose(); diff --git a/src/ComputeSharp.Dynamic/Shaders/Translation/ShaderCompiler.cs b/src/ComputeSharp.Dynamic/Shaders/Translation/ShaderCompiler.cs index 4ecb1c10..aff3c606 100644 --- a/src/ComputeSharp.Dynamic/Shaders/Translation/ShaderCompiler.cs +++ b/src/ComputeSharp.Dynamic/Shaders/Translation/ShaderCompiler.cs @@ -1,5 +1,6 @@ using System; using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; using ComputeSharp.Core.Extensions; using ComputeSharp.Exceptions; using TerraFX.Interop.DirectX; @@ -83,7 +84,7 @@ internal sealed unsafe partial class ShaderCompiler /// /// The HLSL source code to compile. /// The bytecode for the compiled shader. - public ComPtr CompileShader(ReadOnlySpan source) + public ComPtr Compile(ReadOnlySpan source) { using ComPtr dxcBlobEncoding = default; using ComPtr dxcOperationResult = default; @@ -151,6 +152,22 @@ internal sealed unsafe partial class ShaderCompiler string message = new((sbyte*)dxcBlobEncodingError.Get()->GetBufferPointer()); - throw new HlslCompilationException(message); + // The error message will be in a format like this: + // "hlsl.hlsl:11:20: error: redefinition of 'float1' as different kind of symbol + // static const float float1 = asfloat(0xFFC00000); + // ^ + // note: previous definition is here" + // These regex-s try to match the unnecessary headers and remove them, if present. + // This doesn't need to be bulletproof, and these regex-s should match all cases anyway. + message = Regex.Replace(message, @"^hlsl\.hlsl:\d+:\d+: (\w+:)", static m => m.Groups[1].Value, RegexOptions.Multiline); + + // Add a trailing '.' if not present + if (message is { Length: > 0 } && + message[message.Length - 1] != '.') + { + message += '.'; + } + + throw new DxcCompilationException(message); } -} +} \ No newline at end of file diff --git a/src/ComputeSharp.Dynamic/Shaders/Translation/__Internals/ShaderCompiler.cs b/src/ComputeSharp.Dynamic/Shaders/Translation/__Internals/ShaderCompiler.cs index 487d5e08..e93dc7f6 100644 --- a/src/ComputeSharp.Dynamic/Shaders/Translation/__Internals/ShaderCompiler.cs +++ b/src/ComputeSharp.Dynamic/Shaders/Translation/__Internals/ShaderCompiler.cs @@ -27,9 +27,9 @@ public static class ShaderCompiler where TLoader : struct, IBytecodeLoader where T : struct, IShader { - Unsafe.AsRef(in shader).BuildHlslString(out ArrayPoolStringBuilder builder, threadsX, threadsY, threadsZ); + Unsafe.AsRef(in shader).BuildHlslSource(out ArrayPoolStringBuilder builder, threadsX, threadsY, threadsZ); - using ComPtr dxcBlobBytecode = Shaders.Translation.ShaderCompiler.Instance.CompileShader(builder.WrittenSpan); + using ComPtr dxcBlobBytecode = Shaders.Translation.ShaderCompiler.Instance.Compile(builder.WrittenSpan); builder.Dispose(); diff --git a/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems b/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems index 330d197f..f9ab186d 100644 --- a/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems +++ b/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems @@ -18,10 +18,7 @@ - - - diff --git a/src/ComputeSharp.Package/ComputeSharp.Package.msbuildproj b/src/ComputeSharp.Package/ComputeSharp.Package.msbuildproj index 3cf4d1dd..e23b4715 100644 --- a/src/ComputeSharp.Package/ComputeSharp.Package.msbuildproj +++ b/src/ComputeSharp.Package/ComputeSharp.Package.msbuildproj @@ -11,12 +11,18 @@ - + + + PackageVersion=$(PackageVersion) + + + PackageVersion=$(PackageVersion) + \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems new file mode 100644 index 00000000..f41ade8b --- /dev/null +++ b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems @@ -0,0 +1,21 @@ + + + + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) + true + 9ac496a3-bbf0-4c8f-a50d-a20bf01c5e05 + + + ComputeSharp.SourceGeneration.Hlsl + + + + + + + + + + + + \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.shproj b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.shproj new file mode 100644 index 00000000..4c441b94 --- /dev/null +++ b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.shproj @@ -0,0 +1,13 @@ + + + + 9ac496a3-bbf0-4c8f-a50d-a20bf01c5e05 + 14.0 + + + + + + + + diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/Extensions/StringExtensions.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Extensions/StringExtensions.cs new file mode 100644 index 00000000..f01e6d86 --- /dev/null +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Extensions/StringExtensions.cs @@ -0,0 +1,69 @@ +using System; +using System.Buffers; + +namespace ComputeSharp.SourceGeneration.Extensions; + +/// +/// Extension methods for types. +/// +internal static class StringExtensions +{ + /// + /// Converts a given instance to a valid HLSL identifier name. + /// + /// The input instance to convert. + /// An valid HLSL identifier name from . + public static string ToHlslIdentifierName(this string text) + { + return text.Replace('.', '_').Replace('+', '_'); + } + + /// + /// Normalizes a given instance to make it single line and with no repeated spaces. + /// + /// The input instance to normalize. + /// The normalized version of . + public static string NormalizeToSingleLine(this string text) + { + if (text is "") + { + return text; + } + + char[] buffer = ArrayPool.Shared.Rent(text.Length); + int index = 0; + char lastCharacter = '\0'; + + foreach (char newCharacter in text) + { + char pendingCharacter = newCharacter; + + // Ignore '\r' characters + if (pendingCharacter is '\r') + { + continue; + } + + // Convert newlines to spaces (this avoids VS droppping multiline diagnostics) + if (pendingCharacter is '\n') + { + pendingCharacter = ' '; + } + + // Drop duplicate spaces + if (pendingCharacter is ' ' && + lastCharacter is ' ') + { + continue; + } + + buffer[index++] = lastCharacter = pendingCharacter; + } + + text = buffer.AsSpan(0, index).ToString(); + + ArrayPool.Shared.Return(buffer); + + return text; + } +} diff --git a/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Extensions/SyntaxNodeExtensions.cs similarity index 96% rename from src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs rename to src/ComputeSharp.SourceGeneration.Hlsl/Extensions/SyntaxNodeExtensions.cs index b4513d51..86d574e5 100644 --- a/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Extensions/SyntaxNodeExtensions.cs @@ -1,12 +1,12 @@ using System.Collections.Generic; using System.Linq; -using ComputeSharp.SourceGenerators.Mappings; +using ComputeSharp.SourceGeneration.Mappings; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -namespace ComputeSharp.SourceGenerators.Extensions; +namespace ComputeSharp.SourceGeneration.Extensions; /// /// A with some extension methods for C# syntax nodes. @@ -61,7 +61,7 @@ internal static class SyntaxNodeExtensions return node; } - string typeName = typeSymbol.ToDisplayString(ISymbolExtensions.FullyQualifiedWithoutGlobalFormat); + string typeName = typeSymbol.GetFullyQualifiedName(); discoveredTypes.Add((INamedTypeSymbol)typeSymbol); @@ -85,7 +85,7 @@ internal static class SyntaxNodeExtensions public static TypeSyntax TrackType(this SyntaxNode node, SemanticModel semanticModel, ICollection discoveredTypes) { ITypeSymbol typeSymbol = semanticModel.GetTypeInfo(node).Type!; - string typeName = typeSymbol.ToDisplayString(ISymbolExtensions.FullyQualifiedWithoutGlobalFormat); + string typeName = typeSymbol.GetFullyQualifiedName(); discoveredTypes.Add((INamedTypeSymbol)typeSymbol); diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownFields.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownFields.cs new file mode 100644 index 00000000..7728ab5b --- /dev/null +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownFields.cs @@ -0,0 +1,44 @@ +using System.Collections.Generic; + +namespace ComputeSharp.SourceGeneration.Mappings; + +/// +/// A that contains and maps known HLSL field names to common .NET fields. +/// +internal static partial class HlslKnownFields +{ + /// + /// The mapping of supported known fields to HLSL names. + /// + private static readonly IReadOnlyDictionary KnownFields = BuildKnownFieldsMap(); + + /// + /// Builds the mapping of supported known fields to HLSL names. + /// + private static IReadOnlyDictionary BuildKnownFieldsMap() + { + Dictionary knownMembers = new() + { + [$"float.{nameof(float.NaN)}"] = "asfloat(0xFFC00000)", + [$"float.{nameof(float.PositiveInfinity)}"] = "asfloat(0x7F800000)", + [$"float.{nameof(float.NegativeInfinity)}"] = "asfloat(0xFF800000)", + + [$"double.{nameof(double.NaN)}"] = "asdouble(0x00000000, 0xFFF80000)", + [$"double.{nameof(double.PositiveInfinity)}"] = "asdouble(0x00000000, 0x7FF00000)", + [$"double.{nameof(double.NegativeInfinity)}"] = "asdouble(0x00000000, 0xFFF00000)" + }; + + return knownMembers; + } + + /// + /// Tries to get the mapped HLSL-compatible field name for the input field name. + /// + /// The input fully qualified field name. + /// The mapped name, if one is found. + /// The HLSL-compatible field name that can be used in an HLSL shader. + public static bool TryGetMappedName(string name, out string? mapped) + { + return KnownFields.TryGetValue(name, out mapped); + } +} diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownKeywords.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownKeywords.cs new file mode 100644 index 00000000..e995b5b5 --- /dev/null +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownKeywords.cs @@ -0,0 +1,79 @@ +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using ComputeSharp.Core.Intrinsics.Attributes; + +namespace ComputeSharp.SourceGeneration.Mappings; + +/// +/// A that contains and maps known HLSL identifier names valid HLSL names. +/// +internal static partial class HlslKnownKeywords +{ + /// + /// The mapping of known HLSL keywords. + /// + private static readonly IReadOnlyCollection KnownKeywords = BuildKnownKeywordsMap(); + + /// + /// Builds the mapping of all known HLSL keywords. + /// + private static IReadOnlyCollection BuildKnownKeywordsMap() + { + // HLSL keywords + HashSet knownKeywords = new(new[] + { + "asm", "asm_fragment", "cbuffer", "centroid", "column_major", + "compile", "discard", "dword", "export", "fxgroup", "groupshared", + "half", "inline", "inout", "line", "lineadj", "linear", "matrix", + "nointerpolation", "noperspective", "NULL", "packoffset", "pass", + "pixelfragment", "point", "precise", "register", "row_major", "sample", + "sampler", "shared", "snorm", "stateblock", "stateblock_state", "tbuffer", + "technique", "typedef", "triangle", "triangleadj", "uniform", "unorm", + "unsigned", "vector", "vertexfragment", "zero", "float1", "double1", + "int1", "uint1", "bool1" + }); + + // HLSL primitive names + foreach (var type in HlslKnownTypes.KnownVectorTypes.Concat(HlslKnownTypes.KnownMatrixTypes)) + { + knownKeywords.Add(type.Name.ToLower()); + } + + // HLSL intrinsics method names + foreach (var method in typeof(Hlsl).GetMethods(BindingFlags.Public | BindingFlags.Static)) + { + string name = method.GetCustomAttribute()?.Name ?? method.Name; + + knownKeywords.Add(name); + } + + // Let other types inject additional keywords + AddKnownKeywords(knownKeywords); + + return knownKeywords; + } + + /// + /// Adds more known keywords to the collection to use. + /// + /// The collection of known keywords being built. + static partial void AddKnownKeywords(ICollection knownKeywords); + + /// + /// Tries to get the mapped HLSL-compatible identifier name for the input identifier name. + /// + /// The input identifier name. + /// The mapped identifier name, if a replacement is needed. + /// The HLSL-compatible identifier name that can be used in an HLSL shader. + public static bool TryGetMappedName(string name, out string? mapped) + { + mapped = KnownKeywords.Contains(name) switch + { + true => $"__reserved__{name}", + false => null + }; + + return mapped is not null; + } +} diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMethods.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownMethods.cs similarity index 94% rename from src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMethods.cs rename to src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownMethods.cs index 39130e76..7a6f51ed 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMethods.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownMethods.cs @@ -5,12 +5,12 @@ using System.Numerics; using System.Reflection; using ComputeSharp.Core.Intrinsics.Attributes; -namespace ComputeSharp.SourceGenerators.Mappings; +namespace ComputeSharp.SourceGeneration.Mappings; /// /// A that contains and maps known HLSL method names to common .NET methods. /// -internal static class HlslKnownMethods +internal static partial class HlslKnownMethods { /// /// The mapping of supported known methods to HLSL names. @@ -137,9 +137,18 @@ internal static class HlslKnownMethods knownMethods.Add($"{typeof(Hlsl).FullName}{Type.Delimiter}{method.Name}", hlslName); } + // Let other types inject additional methods + AddKnownMethods(knownMethods); + return knownMethods; } + /// + /// Adds more known methods to the mapping to use. + /// + /// The mapping of known methods being built. + static partial void AddKnownMethods(IDictionary knownMethods); + /// /// Tries to get the mapped HLSL-compatible method name for the input method name. /// diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownProperties.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownProperties.cs new file mode 100644 index 00000000..699fbb2f --- /dev/null +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownProperties.cs @@ -0,0 +1,242 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Numerics; +using System.Reflection; +using System.Text.RegularExpressions; + +namespace ComputeSharp.SourceGeneration.Mappings; + +/// +/// A that contains and maps known HLSL properties names to common .NET properties. +/// +internal static partial class HlslKnownProperties +{ + /// + /// The mapping of supported known properties to HLSL names. + /// + private static readonly IReadOnlyDictionary KnownProperties = BuildKnownPropertiesMap(); + + /// + /// Builds the mapping of supported known properties to HLSL names. + /// + private static IReadOnlyDictionary BuildKnownPropertiesMap() + { + Dictionary knownProperties = new() + { + [$"{typeof(Vector2).FullName}.{nameof(Vector2.X)}"] = "x", + [$"{typeof(Vector2).FullName}.{nameof(Vector2.Y)}"] = "y", + [$"{typeof(Vector2).FullName}.{nameof(Vector2.Zero)}"] = "(float2)0", + [$"{typeof(Vector2).FullName}.{nameof(Vector2.One)}"] = "float2(1.0f, 1.0f)", + [$"{typeof(Vector2).FullName}.{nameof(Vector2.UnitX)}"] = "float2(1.0f, 0.0f)", + [$"{typeof(Vector2).FullName}.{nameof(Vector2.UnitY)}"] = "float2(0.0f, 1.0f)", + + [$"{typeof(Vector3).FullName}.{nameof(Vector3.X)}"] = "x", + [$"{typeof(Vector3).FullName}.{nameof(Vector3.Y)}"] = "y", + [$"{typeof(Vector3).FullName}.{nameof(Vector3.Z)}"] = "z", + [$"{typeof(Vector3).FullName}.{nameof(Vector3.Zero)}"] = "(float3)0", + [$"{typeof(Vector3).FullName}.{nameof(Vector3.One)}"] = "float3(1.0f, 1.0f, 1.0f)", + [$"{typeof(Vector3).FullName}.{nameof(Vector3.UnitX)}"] = "float3(1.0f, 0.0f, 0.0f)", + [$"{typeof(Vector3).FullName}.{nameof(Vector3.UnitY)}"] = "float3(0.0f, 1.0f, 0.0f)", + [$"{typeof(Vector3).FullName}.{nameof(Vector3.UnitZ)}"] = "float3(0.0f, 0.0f, 1.0f)", + + [$"{typeof(Vector4).FullName}.{nameof(Vector4.X)}"] = "x", + [$"{typeof(Vector4).FullName}.{nameof(Vector4.Y)}"] = "y", + [$"{typeof(Vector4).FullName}.{nameof(Vector4.Z)}"] = "z", + [$"{typeof(Vector4).FullName}.{nameof(Vector4.W)}"] = "w", + [$"{typeof(Vector4).FullName}.{nameof(Vector4.Zero)}"] = "(float4)0", + [$"{typeof(Vector4).FullName}.{nameof(Vector4.One)}"] = "float4(1.0f, 1.0f, 1.0f, 1.0f)", + + [$"{typeof(Bool2).FullName}.{nameof(Bool2.False)}"] = "(bool2)0", + [$"{typeof(Bool2).FullName}.{nameof(Bool2.True)}"] = "bool2(true, true)", + [$"{typeof(Bool2).FullName}.{nameof(Bool2.TrueX)}"] = "bool2(true, false)", + [$"{typeof(Bool2).FullName}.{nameof(Bool2.TrueY)}"] = "bool2(false, true)", + + [$"{typeof(Bool3).FullName}.{nameof(Bool3.False)}"] = "(bool3)0", + [$"{typeof(Bool3).FullName}.{nameof(Bool3.True)}"] = "bool3(true, true, true)", + [$"{typeof(Bool3).FullName}.{nameof(Bool3.TrueX)}"] = "bool3(true, false, false)", + [$"{typeof(Bool3).FullName}.{nameof(Bool3.TrueY)}"] = "bool3(false, true, false)", + [$"{typeof(Bool3).FullName}.{nameof(Bool3.TrueZ)}"] = "bool3(false, false, true)", + + [$"{typeof(Bool4).FullName}.{nameof(Bool4.False)}"] = "(bool4)0", + [$"{typeof(Bool4).FullName}.{nameof(Bool4.True)}"] = "bool4(true, true, true, true)", + [$"{typeof(Bool4).FullName}.{nameof(Bool4.TrueX)}"] = "bool4(true, false, false, false)", + [$"{typeof(Bool4).FullName}.{nameof(Bool4.TrueY)}"] = "bool4(false, true, false, false)", + [$"{typeof(Bool4).FullName}.{nameof(Bool4.TrueZ)}"] = "bool4(false, false, true, false)", + [$"{typeof(Bool4).FullName}.{nameof(Bool4.TrueW)}"] = "bool4(false, false, false, true)", + + [$"{typeof(Int2).FullName}.{nameof(Int2.Zero)}"] = "(int2)0", + [$"{typeof(Int2).FullName}.{nameof(Int2.One)}"] = "int2(1, 1)", + [$"{typeof(Int2).FullName}.{nameof(Int2.UnitX)}"] = "int2(1, 0)", + [$"{typeof(Int2).FullName}.{nameof(Int2.UnitY)}"] = "int2(0, 1)", + + [$"{typeof(Int3).FullName}.{nameof(Int3.Zero)}"] = "(int3)0", + [$"{typeof(Int3).FullName}.{nameof(Int3.One)}"] = "int3(1, 1, 1)", + [$"{typeof(Int3).FullName}.{nameof(Int3.UnitX)}"] = "int3(1, 0, 0)", + [$"{typeof(Int3).FullName}.{nameof(Int3.UnitY)}"] = "int3(0, 1, 0)", + [$"{typeof(Int3).FullName}.{nameof(Int3.UnitZ)}"] = "int3(0, 0, 1)", + + [$"{typeof(Int4).FullName}.{nameof(Int4.Zero)}"] = "(int4)0", + [$"{typeof(Int4).FullName}.{nameof(Int4.One)}"] = "int4(1, 1, 1, 1)", + [$"{typeof(Int4).FullName}.{nameof(Int4.UnitX)}"] = "int4(1, 0, 0, 0)", + [$"{typeof(Int4).FullName}.{nameof(Int4.UnitY)}"] = "int4(0, 1, 0, 0)", + [$"{typeof(Int4).FullName}.{nameof(Int4.UnitZ)}"] = "int4(0, 0, 1, 0)", + [$"{typeof(Int4).FullName}.{nameof(Int4.UnitW)}"] = "int4(0, 0, 0, 1)", + + [$"{typeof(UInt2).FullName}.{nameof(UInt2.Zero)}"] = "(uint2)0", + [$"{typeof(UInt2).FullName}.{nameof(UInt2.One)}"] = "uint2(1u, 1u)", + [$"{typeof(UInt2).FullName}.{nameof(UInt2.UnitX)}"] = "uint2(1u, 0u)", + [$"{typeof(UInt2).FullName}.{nameof(UInt2.UnitY)}"] = "uint2(0u, 1u)", + + [$"{typeof(UInt3).FullName}.{nameof(UInt3.Zero)}"] = "(uint3)0", + [$"{typeof(UInt3).FullName}.{nameof(UInt3.One)}"] = "uint3(1u, 1u, 1u)", + [$"{typeof(UInt3).FullName}.{nameof(UInt3.UnitX)}"] = "uint3(1u, 0u, 0u)", + [$"{typeof(UInt3).FullName}.{nameof(UInt3.UnitY)}"] = "uint3(0u, 1u, 0u)", + [$"{typeof(UInt3).FullName}.{nameof(UInt3.UnitZ)}"] = "uint3(0u, 0u, 1u)", + + [$"{typeof(UInt4).FullName}.{nameof(UInt4.Zero)}"] = "(uint4)0", + [$"{typeof(UInt4).FullName}.{nameof(UInt4.One)}"] = "uint4(1u, 1u, 1u, 1u)", + [$"{typeof(UInt4).FullName}.{nameof(UInt4.UnitX)}"] = "uint4(1u, 0u, 0u, 0u)", + [$"{typeof(UInt4).FullName}.{nameof(UInt4.UnitY)}"] = "uint4(0u, 1u, 0u, 0u)", + [$"{typeof(UInt4).FullName}.{nameof(UInt4.UnitZ)}"] = "uint4(0u, 0u, 1u, 0u)", + [$"{typeof(UInt4).FullName}.{nameof(UInt4.UnitW)}"] = "uint4(0u, 0u, 0u, 1u)", + + [$"{typeof(Float2).FullName}.{nameof(Float2.Zero)}"] = "(float2)0", + [$"{typeof(Float2).FullName}.{nameof(Float2.One)}"] = "float2(1.0f, 1.0f)", + [$"{typeof(Float2).FullName}.{nameof(Float2.UnitX)}"] = "float2(1.0f, 0.0f)", + [$"{typeof(Float2).FullName}.{nameof(Float2.UnitY)}"] = "float2(0.0f, 1.0f)", + + [$"{typeof(Float3).FullName}.{nameof(Float3.Zero)}"] = "(float3)0", + [$"{typeof(Float3).FullName}.{nameof(Float3.One)}"] = "float3(1.0f, 1.0f, 1.0f)", + [$"{typeof(Float3).FullName}.{nameof(Float3.UnitX)}"] = "float3(1.0f, 0.0f, 0.0f)", + [$"{typeof(Float3).FullName}.{nameof(Float3.UnitY)}"] = "float3(0.0f, 1.0f, 0.0f)", + [$"{typeof(Float3).FullName}.{nameof(Float3.UnitZ)}"] = "float3(0.0f, 0.0f, 1.0f)", + + [$"{typeof(Float4).FullName}.{nameof(Float4.Zero)}"] = "(float4)0", + [$"{typeof(Float4).FullName}.{nameof(Float4.One)}"] = "float4(1.0f, 1.0f, 1.0f, 1.0f)", + [$"{typeof(Float4).FullName}.{nameof(Float4.UnitX)}"] = "float4(1.0f, 0.0f, 0.0f, 0.0f)", + [$"{typeof(Float4).FullName}.{nameof(Float4.UnitY)}"] = "float4(0.0f, 1.0f, 0.0f, 0.0f)", + [$"{typeof(Float4).FullName}.{nameof(Float4.UnitZ)}"] = "float4(0.0f, 0.0f, 1.0f, 0.0f)", + [$"{typeof(Float4).FullName}.{nameof(Float4.UnitW)}"] = "float4(0.0f, 0.0f, 0.0f, 1.0f)", + + [$"{typeof(Double2).FullName}.{nameof(Double2.Zero)}"] = "(double2)0", + [$"{typeof(Double2).FullName}.{nameof(Double2.One)}"] = "double2(1.0, 1.0)", + [$"{typeof(Double2).FullName}.{nameof(Double2.UnitX)}"] = "double2(1.0, 0.0)", + [$"{typeof(Double2).FullName}.{nameof(Double2.UnitY)}"] = "double2(0.0, 1.0)", + + [$"{typeof(Double3).FullName}.{nameof(Double3.Zero)}"] = "(double3)0", + [$"{typeof(Double3).FullName}.{nameof(Double3.One)}"] = "double3(1.0, 1.0, 1.0)", + [$"{typeof(Double3).FullName}.{nameof(Double3.UnitX)}"] = "double3(1.0, 0.0, 0.0)", + [$"{typeof(Double3).FullName}.{nameof(Double3.UnitY)}"] = "double3(0.0, 1.0, 0.0)", + [$"{typeof(Double3).FullName}.{nameof(Double3.UnitZ)}"] = "double3(0.0, 0.0, 1.0)", + + [$"{typeof(Double4).FullName}.{nameof(Double4.Zero)}"] = "(double4)0", + [$"{typeof(Double4).FullName}.{nameof(Double4.One)}"] = "double4(1.0, 1.0, 1.0, 1.0)", + [$"{typeof(Double4).FullName}.{nameof(Double4.UnitX)}"] = "double4(1.0, 0.0, 0.0, 0.0)", + [$"{typeof(Double4).FullName}.{nameof(Double4.UnitY)}"] = "double4(0.0, 1.0, 0.0, 0.0)", + [$"{typeof(Double4).FullName}.{nameof(Double4.UnitZ)}"] = "double4(0.0, 0.0, 1.0, 0.0)", + [$"{typeof(Double4).FullName}.{nameof(Double4.UnitW)}"] = "double4(0.0, 0.0, 0.0, 1.0)" + }; + + // Programmatically load mappings for the instance members of the HLSL vector types + foreach (var item in + from type in HlslKnownTypes.KnownVectorTypes + from property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public) + select (Type: type, Property: property)) + { + knownProperties.Add($"{item.Type.FullName}{Type.Delimiter}{item.Property.Name}", $"{item.Property.Name.ToLower()}"); + } + + // Load mappings for the matrix properties as well + foreach (var item in + from type in HlslKnownTypes.KnownMatrixTypes + from property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public) + where Regex.IsMatch(property.Name, "^M[1-4]{2}$") + select (Type: type, Property: property)) + { + char row = (char)(item.Property.Name[1] - 1); + char column = (char)(item.Property.Name[2] - 1); + + knownProperties.Add($"{item.Type.FullName}{Type.Delimiter}{item.Property.Name}", $"_m{row}{column}"); + } + + // Let other types inject additional properties + AddKnownProperties(knownProperties); + + return knownProperties; + } + + /// + /// Adds more known members to the mapping to use. + /// + /// The mapping of known properties being built. + static partial void AddKnownProperties(IDictionary knownProperties); + + /// + /// The mapping of supported known properties to HLSL names. + /// + private static readonly IReadOnlyCollection KnownMatrixIndexers = BuildKnownMatrixIndexers(); + + /// + /// Builds the mapping of swizzled matrix indexer properties. + /// + private static IReadOnlyCollection BuildKnownMatrixIndexers() + { + return ( + from type in Assembly.GetExecutingAssembly().ExportedTypes + where Regex.IsMatch(type.FullName, @"ComputeSharp\.(Bool|Double|Float|Int|UInt)[1-4]x[1-4]") + from property in type.GetProperties() + let indices = property.GetIndexParameters() + where indices.Length > 0 && + indices.All(static index => index.ParameterType == typeof(MatrixIndex)) + let metadataName = $"{type.FullName}.this[{string.Join(", ", indices.Select(index => index.ParameterType))}]" + select metadataName).ToImmutableHashSet(); + } + + /// + /// The mapping of supported known members to HLSL names. + /// + private static readonly IReadOnlyCollection KnownMatrixIndices = BuildKnownMatrixIndices(); + + /// + /// Builds the mapping of swizzled matrix indices. + /// + private static IReadOnlyCollection BuildKnownMatrixIndices() + { + return ( + from name in Enum.GetNames(typeof(MatrixIndex)) + select $"{typeof(MatrixIndex).FullName}.{name}").ToImmutableHashSet(); + } + + /// + /// Checks whether or not a given property fullname matches a matrix swizzled indexer. + /// + /// The input fully qualified member name. + /// Whether or not is a matrix swizzled indexer. + public static bool IsKnownMatrixIndexer(string name) + { + return KnownMatrixIndexers.Contains(name); + } + + /// + /// Checks whether or not a given property fullname matches a matrix swizzled index. + /// + /// The input fully qualified member name. + /// Whether or not is a matrix swizzled index. + public static bool IsKnownMatrixIndex(string name) + { + return KnownMatrixIndices.Contains(name); + } + + /// + /// Tries to get the mapped HLSL-compatible property name for the input property name. + /// + /// The input fully qualified property name. + /// The mapped name, if one is found. + /// The HLSL-compatible property name that can be used in an HLSL shader. + public static bool TryGetMappedName(string name, out string? mapped) + { + return KnownProperties.TryGetValue(name, out mapped); + } +} diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownSizes.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownSizes.cs similarity index 92% rename from src/ComputeSharp.SourceGenerators/Mappings/HlslKnownSizes.cs rename to src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownSizes.cs index ab74da12..44bc07f8 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownSizes.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownSizes.cs @@ -4,7 +4,7 @@ using System.Numerics; using System.Reflection; using System.Text.RegularExpressions; -namespace ComputeSharp.SourceGenerators.Mappings; +namespace ComputeSharp.SourceGeneration.Mappings; /// /// A that contains and maps known HLSL types to their alignment sizes. @@ -14,7 +14,7 @@ internal static class HlslKnownSizes /// /// The mapping of supported known sizes to HLSL type names. /// - private static IReadOnlyDictionary KnownSizes = BuildKnownSizesMap(); + private static readonly IReadOnlyDictionary KnownSizes = BuildKnownSizesMap(); /// /// Builds the mapping of known type sizes and alignments. diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownTypes.cs new file mode 100644 index 00000000..37566220 --- /dev/null +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownTypes.cs @@ -0,0 +1,315 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Numerics; +using System.Text.RegularExpressions; +using ComputeSharp.SourceGeneration.Extensions; +using Microsoft.CodeAnalysis; + +#pragma warning disable RS1024 + +namespace ComputeSharp.SourceGeneration.Mappings; + +/// +/// A that contains and maps known HLSL type names to common .NET types. +/// +internal static partial class HlslKnownTypes +{ + /// + /// Gets the set of HLSL vector types. + /// + public static IReadOnlyCollection KnownVectorTypes { get; } = new[] + { + typeof(Bool2), typeof(Bool3), typeof(Bool4), + typeof(Int2), typeof(Int3), typeof(Int4), + typeof(UInt2), typeof(UInt3), typeof(UInt4), + typeof(Float2), typeof(Float3), typeof(Float4), + typeof(Double2), typeof(Double3), typeof(Double4) + }; + + /// + /// Gets the set of HLSL matrix types. + /// + public static IReadOnlyCollection KnownMatrixTypes { get; } = new[] + { + typeof(Bool1x1), typeof(Bool1x2), typeof(Bool1x3), typeof(Bool1x4), + typeof(Bool2x1), typeof(Bool2x2), typeof(Bool2x3), typeof(Bool2x4), + typeof(Bool3x1), typeof(Bool3x2), typeof(Bool3x3), typeof(Bool3x4), + typeof(Bool4x1), typeof(Bool4x2), typeof(Bool4x3), typeof(Bool4x4), + typeof(Int1x1), typeof(Int1x2), typeof(Int1x3), typeof(Int1x4), + typeof(Int2x1), typeof(Int2x2), typeof(Int2x3), typeof(Int2x4), + typeof(Int3x1), typeof(Int3x2), typeof(Int3x3), typeof(Int3x4), + typeof(Int4x1), typeof(Int4x2), typeof(Int4x3), typeof(Int4x4), + typeof(UInt1x1), typeof(UInt1x2), typeof(UInt1x3), typeof(UInt1x4), + typeof(UInt2x1), typeof(UInt2x2), typeof(UInt2x3), typeof(UInt2x4), + typeof(UInt3x1), typeof(UInt3x2), typeof(UInt3x3), typeof(UInt3x4), + typeof(UInt4x1), typeof(UInt4x2), typeof(UInt4x3), typeof(UInt4x4), + typeof(Float1x1), typeof(Float1x2), typeof(Float1x3), typeof(Float1x4), + typeof(Float2x1), typeof(Float2x2), typeof(Float2x3), typeof(Float2x4), + typeof(Float3x1), typeof(Float3x2), typeof(Float3x3), typeof(Float3x4), + typeof(Float4x1), typeof(Float4x2), typeof(Float4x3), typeof(Float4x4), + typeof(Double1x1), typeof(Double1x2), typeof(Double1x3), typeof(Double1x4), + typeof(Double2x1), typeof(Double2x2), typeof(Double2x3), typeof(Double2x4), + typeof(Double3x1), typeof(Double3x2), typeof(Double3x3), typeof(Double3x4), + typeof(Double4x1), typeof(Double4x2), typeof(Double4x3), typeof(Double4x4) + }; + + /// + /// The mapping of supported known types to HLSL types. + /// + private static readonly IReadOnlyDictionary KnownHlslTypes = BuildKnownHlslTypes(); + + /// + /// Builds the mapping of known primitive types. + /// + private static IReadOnlyDictionary BuildKnownHlslTypes() + { + Dictionary knownTypes = new() + { + [typeof(bool).FullName] = "bool", + [typeof(int).FullName] = "int", + [typeof(uint).FullName] = "uint", + [typeof(float).FullName] = "float", + [typeof(Vector2).FullName] = "float2", + [typeof(Vector3).FullName] = "float3", + [typeof(Vector4).FullName] = "float4", + [typeof(double).FullName] = "double" + }; + + // Add all the vector types + foreach (var type in KnownVectorTypes) + { + knownTypes.Add(type.FullName, type.Name.ToLower()); + } + + // Add all the matrix types + foreach (var type in KnownMatrixTypes) + { + knownTypes.Add(type.FullName, type.Name.ToLower()); + } + + return knownTypes; + } + + /// + /// Checks whether or not a given type name matches a known HLSL primitive type (scalar, vector or matrix). + /// + /// The input type name to check. + /// Whether or not represents a scalar, vector or matrix type. + public static bool IsKnownHlslType(string typeName) + { + return KnownHlslTypes.ContainsKey(typeName); + } + + /// + /// Checks whether or not a given type name matches a vector type. + /// + /// The input type name to check. + /// Whether or not represents a vector type. + public static bool IsVectorType(string typeName) + { + return KnownVectorTypes.Any(type => type.FullName == typeName); + } + + /// + /// Checks whether or not a given type name matches a matrix type. + /// + /// The input type name to check. + /// Whether or not represents a matrix type. + public static bool IsMatrixType(string typeName) + { + return KnownMatrixTypes.Any(type => type.FullName == typeName); + } + + /// + /// Checks whether or not a given type name is a non linear matrix type. + /// That is, a matrix type with more than a single row (which affects the constant buffer alignment). + /// + /// The input type name to check. + /// The element name of the matrix type. + /// The number of rows in the matrix type. + /// The number of columns in the matrix type. + /// Whether or not represents a non linear matrix type. + public static bool IsNonLinearMatrixType(string typeName, out string? elementName, out int rows, out int columns) + { + if (KnownMatrixTypes.Any(type => type.FullName == typeName)) + { + var match = Regex.Match(typeName, @"^ComputeSharp\.(Bool|Int|UInt|Float|Double)([2-4])x([1-4])$"); + + if (match.Success) + { + elementName = match.Groups[1].Value; + rows = int.Parse(match.Groups[2].Value); + columns = int.Parse(match.Groups[3].Value); + + return true; + } + } + + elementName = null; + rows = columns = 0; + + return false; + } + + /// + /// Gets the mapped HLSL-compatible type name for the input type symbol. + /// + /// The input type to map. + /// The HLSL-compatible type name that can be used in an HLSL shader. + public static partial string GetMappedName(INamedTypeSymbol typeSymbol); + + /// + /// Gets the mapped HLSL-compatible type name for the input element type symbol. + /// + /// The input type to map. + /// The HLSL-compatible type name that can be used in an HLSL shader. + public static string GetMappedElementName(IArrayTypeSymbol typeSymbol) + { + string elementTypeName = ((INamedTypeSymbol)typeSymbol.ElementType).GetFullMetadataName(); + + if (KnownHlslTypes.TryGetValue(elementTypeName, out string? mapped)) + { + return mapped; + } + + return elementTypeName.ToHlslIdentifierName(); + } + + /// + /// Gets the mapped HLSL-compatible type name for the input type name. + /// + /// The input type name to map. + /// The resulting mapped type name, if found. + /// The HLSL-compatible type name that can be used in an HLSL shader. + public static bool TryGetMappedName(string originalName, out string? mappedName) + { + return KnownHlslTypes.TryGetValue(originalName, out mappedName); + } + + /// + /// Tracks an instance and returns an HLSL compatible type name. + /// + /// The input instance to process. + /// The collection of currently discovered types. + /// A type name that represents a type compatible with HLSL. + public static string TrackType(ITypeSymbol typeSymbol, ICollection discoveredTypes) + { + string typeName = typeSymbol.GetFullyQualifiedName(); + + discoveredTypes.Add((INamedTypeSymbol)typeSymbol); + + if (TryGetMappedName(typeName, out string? mappedName)) + { + return mappedName!; + } + + return typeName.ToHlslIdentifierName(); + } + + /// + /// Gets the sequence of unique custom types from a collection of discovered types. + /// + /// The input collection of discovered types. + /// The collection of discovered invalid types, if any. + /// The list of unique custom types. + public static IEnumerable GetCustomTypes(IEnumerable discoveredTypes, out IReadOnlyCollection invalidTypes) + { + // Local function to recursively gather nested types + static void ExploreTypes(INamedTypeSymbol type, HashSet customTypes, HashSet invalidTypes) + { + if (KnownHlslTypes.ContainsKey(type.GetFullMetadataName())) return; + + // Check if the type is unsupported + if (!type.IsUnmanagedType || + type.TypeKind is TypeKind.Enum || + type.IsGenericType || + type.IsRefLikeType || + type.GetFullyQualifiedName().StartsWith("System.")) + { + invalidTypes.Add(type); + + return; + } + + if (!customTypes.Add(type)) return; + + foreach (var field in type.GetMembers().OfType()) + { + if (field.IsStatic) continue; + + ExploreTypes((INamedTypeSymbol)field.Type, customTypes, invalidTypes); + } + } + + HashSet customTypes = new(SymbolEqualityComparer.Default); + HashSet invalidTypes2 = new(SymbolEqualityComparer.Default); + + // Explore all input types and their nested types + foreach (INamedTypeSymbol type in discoveredTypes) + { + ExploreTypes(type, customTypes, invalidTypes2); + } + + invalidTypes = invalidTypes2; + + return OrderByDependency(customTypes, invalidTypes2); + } + + /// + /// Orders the input sequence of types so that they can be declared in HLSL successfully. + /// + /// The input collection of types to declare. + /// The collection of discovered invalid types, if any. + /// The same list as input, but in a valid HLSL declaration order. + private static IEnumerable OrderByDependency(IEnumerable types, IReadOnlyCollection invalidTypes) + { + Queue<(INamedTypeSymbol Type, HashSet Fields)> queue = new(); + + // Build a mapping of type dependencies for all the captured types. A type depends on another + // when the latter is a field in the first type. HLSL requires custom types to be declared in + // order of usage, so we need to ensure that types are declared in an order that guarantees + // that no type will be referenced before being defined. To do so, we can create a mapping of + // types and their dependencies, and iteratively remove items from the map when they have no + // dependencies left. When one type is processed and removed, it is also removed from the list + // of dependencies of all other remaining types in the map, until there is none left. + foreach (var type in types) + { + HashSet dependencies = new(SymbolEqualityComparer.Default); + + // Only add other custom types as dependencies, and ignore HLSL types + foreach (var field in type.GetMembers().OfType()) + { + if (field.IsStatic) continue; + + INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type; + + if (!KnownHlslTypes.ContainsKey(fieldType.GetFullMetadataName()) && + !invalidTypes.Contains(fieldType)) + { + _ = dependencies.Add(fieldType); + } + } + + queue.Enqueue((type, dependencies)); + } + + while (queue.Count > 0) + { + var entry = queue.Dequeue(); + + // No dependencies left, we can declare this type + if (entry.Fields.Count == 0) + { + // Remove the current type from dependencies of others + foreach (var pair in queue) + { + _ = pair.Fields.Remove(entry.Type); + } + + yield return entry.Type; + } + else queue.Enqueue(entry); + } + } +} diff --git a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems new file mode 100644 index 00000000..30b2bcf1 --- /dev/null +++ b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems @@ -0,0 +1,26 @@ + + + + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) + true + 51d5a422-d3a5-4c4d-8a6d-a048940bf279 + + + ComputeSharp.SourceGeneration + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.shproj b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.shproj new file mode 100644 index 00000000..00042f22 --- /dev/null +++ b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.shproj @@ -0,0 +1,13 @@ + + + + 51d5a422-d3a5-4c4d-8a6d-a048940bf279 + 14.0 + + + + + + + + diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs similarity index 84% rename from src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs rename to src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs index 8584bee1..8426ed9c 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs @@ -2,7 +2,7 @@ using System.Linq; using Microsoft.CodeAnalysis; -namespace ComputeSharp.SourceGenerators.Diagnostics; +namespace ComputeSharp.SourceGeneration.Extensions; /// /// Extension methods for , specifically for reporting diagnostics. @@ -73,6 +73,19 @@ internal static class DiagnosticsExtensions diagnostics.Add(Diagnostic.Create(descriptor, node.GetLocation(), args)); } + /// + /// Registers an output node into an to output diagnostics. + /// + /// The input instance. + /// The input sequence of diagnostics. + public static void ReportDiagnostics(this IncrementalGeneratorInitializationContext context, IncrementalValuesProvider diagnostics) + { + context.RegisterSourceOutput(diagnostics, static (context, diagnostic) => + { + context.ReportDiagnostic(diagnostic); + }); + } + /// /// Registers an output node into an to output diagnostics. /// diff --git a/src/ComputeSharp.SourceGenerators/Extensions/HashCodeExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/HashCodeExtensions.cs similarity index 96% rename from src/ComputeSharp.SourceGenerators/Extensions/HashCodeExtensions.cs rename to src/ComputeSharp.SourceGeneration/Extensions/HashCodeExtensions.cs index 7d486566..6830252e 100644 --- a/src/ComputeSharp.SourceGenerators/Extensions/HashCodeExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/HashCodeExtensions.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Collections.Immutable; -namespace ComputeSharp.SourceGenerators.Extensions; +namespace ComputeSharp.SourceGeneration.Extensions; /// /// Extension methods for . diff --git a/src/ComputeSharp.SourceGenerators/Extensions/IEqualityComparerExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/IEqualityComparerExtensions.cs similarity index 97% rename from src/ComputeSharp.SourceGenerators/Extensions/IEqualityComparerExtensions.cs rename to src/ComputeSharp.SourceGeneration/Extensions/IEqualityComparerExtensions.cs index 306d8c11..0c7a9aa7 100644 --- a/src/ComputeSharp.SourceGenerators/Extensions/IEqualityComparerExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/IEqualityComparerExtensions.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Collections.Immutable; -namespace ComputeSharp.SourceGenerators.Extensions; +namespace ComputeSharp.SourceGeneration.Extensions; /// /// Extension methods for . diff --git a/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/ISymbolExtensions.cs similarity index 68% rename from src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs rename to src/ComputeSharp.SourceGeneration/Extensions/ISymbolExtensions.cs index 0974e9b6..404a9da3 100644 --- a/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/ISymbolExtensions.cs @@ -1,12 +1,9 @@ -using System.Collections.Generic; +using System.Collections.Immutable; using System.Linq; using System.Text; -using ComputeSharp.SourceGenerators.Mappings; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -namespace ComputeSharp.SourceGenerators.Extensions; +namespace ComputeSharp.SourceGeneration.Extensions; /// /// Extension methods for types. @@ -19,21 +16,35 @@ internal static class ISymbolExtensions public static readonly SymbolDisplayFormat FullyQualifiedWithoutGlobalFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, - genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters); + genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, + miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers); /// /// A custom instance with fully qualified style, without global:: and parameters. /// - private static readonly SymbolDisplayFormat FullyQualifiedWithoutGlobalAndParametersFormat = - FullyQualifiedWithoutGlobalFormat - .WithMemberOptions(SymbolDisplayMemberOptions.IncludeContainingType) - .WithParameterOptions(SymbolDisplayParameterOptions.None); + private static readonly SymbolDisplayFormat FullyQualifiedWithoutGlobalAndParametersFormat = new( + globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, + typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, + genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, + miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers, + memberOptions: SymbolDisplayMemberOptions.IncludeContainingType, + parameterOptions: SymbolDisplayParameterOptions.None); /// - /// Gets the full metadata name for a given instance. + /// Gets the fully qualified name for a given symbol. + /// + /// The input instance. + /// The fully qualified name for . + public static string GetFullyQualifiedName(this ISymbol symbol) + { + return symbol.ToDisplayString(FullyQualifiedWithoutGlobalFormat); + } + + /// + /// Gets a valid filename for a given instance. /// /// The input instance. - /// The full metadata name for . + /// The full metadata name for that is also a valid filename. public static string GetFullMetadataName(this ITypeSymbol symbol) { static StringBuilder BuildFrom(ISymbol? symbol, StringBuilder builder) @@ -113,22 +124,28 @@ internal static class ISymbolExtensions } /// - /// Tracks an instance and returns an HLSL compatible object. + /// Tries to get an attribute with the specified full metadata name. /// - /// The input instance to process. - /// The collection of currently discovered types. - /// A instance that represents a type compatible with HLSL. - public static TypeSyntax TrackType(this ITypeSymbol typeSymbol, ICollection discoveredTypes) + /// The input instance to check. + /// The attribute name to look for. + /// The resulting attribute data, if found. + /// Whether or not has an attribute with the specified name. + public static bool TryGetAttributeWithFullMetadataName(this ISymbol symbol, string name, out AttributeData? attributeData) { - string typeName = typeSymbol.ToDisplayString(FullyQualifiedWithoutGlobalFormat); + ImmutableArray attributes = symbol.GetAttributes(); - discoveredTypes.Add((INamedTypeSymbol)typeSymbol); - - if (HlslKnownTypes.TryGetMappedName(typeName, out string? mappedName)) + foreach (AttributeData attribute in attributes) { - return ParseTypeName(mappedName!); + if (attribute.AttributeClass?.GetFullMetadataName() == name) + { + attributeData = attribute; + + return true; + } } - return ParseTypeName(typeName.ToHlslIdentifierName()); + attributeData = null; + + return false; } } diff --git a/src/ComputeSharp.SourceGenerators/Extensions/ImmutableArrayExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/ImmutableArrayExtensions.cs similarity index 97% rename from src/ComputeSharp.SourceGenerators/Extensions/ImmutableArrayExtensions.cs rename to src/ComputeSharp.SourceGeneration/Extensions/ImmutableArrayExtensions.cs index e4100441..a6a11304 100644 --- a/src/ComputeSharp.SourceGenerators/Extensions/ImmutableArrayExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/ImmutableArrayExtensions.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Collections.Immutable; -namespace ComputeSharp.SourceGenerators.Extensions; +namespace ComputeSharp.SourceGeneration.Extensions; /// /// Extension methods for . diff --git a/src/ComputeSharp.SourceGenerators/Extensions/IncrementalValuesProviderExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/IncrementalValuesProviderExtensions.cs similarity index 99% rename from src/ComputeSharp.SourceGenerators/Extensions/IncrementalValuesProviderExtensions.cs rename to src/ComputeSharp.SourceGeneration/Extensions/IncrementalValuesProviderExtensions.cs index bdcd5290..a7d0e73d 100644 --- a/src/ComputeSharp.SourceGenerators/Extensions/IncrementalValuesProviderExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/IncrementalValuesProviderExtensions.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using Microsoft.CodeAnalysis; -namespace ComputeSharp.SourceGenerators.Extensions; +namespace ComputeSharp.SourceGeneration.Extensions; /// /// Extension methods for . diff --git a/src/ComputeSharp.SourceGeneration/Helpers/Comparer{T,TSelf}.cs b/src/ComputeSharp.SourceGeneration/Helpers/Comparer{T,TSelf}.cs new file mode 100644 index 00000000..71ee2e1a --- /dev/null +++ b/src/ComputeSharp.SourceGeneration/Helpers/Comparer{T,TSelf}.cs @@ -0,0 +1,68 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; + +namespace ComputeSharp.SourceGeneration.Helpers; + +/// +/// A base implementation for instances. +/// +/// The type of items to compare. +/// The concrete comparer type. +internal abstract class Comparer : IEqualityComparer + where TSelf : Comparer, new() +{ + /// + /// The singleton instance. + /// + public static TSelf Default { get; } = new(); + + /// + public bool Equals(T? x, T? y) + { + if (x is null && y is null) + { + return true; + } + + if (x is null || y is null) + { + return false; + } + + if (ReferenceEquals(x, y)) + { + return true; + } + + return AreEqual(x, y); + } + + /// + public int GetHashCode(T obj) + { + HashCode hashCode = default; + + AddToHashCode(ref hashCode, obj); + + return hashCode.ToHashCode(); + } + + /// + /// Adds the current instance to an incremental value. + /// + /// The target value. + /// The instance being inspected. + protected abstract void AddToHashCode(ref HashCode hashCode, T obj); + + /// + /// Compares two instances for equality. + /// + /// The first instance to compare. + /// The second instance to compare. + /// Whether or not and are equal. + protected abstract bool AreEqual(T x, T y); +} diff --git a/src/ComputeSharp.SourceGenerators/Helpers/HashCode.cs b/src/ComputeSharp.SourceGeneration/Helpers/HashCode.cs similarity index 100% rename from src/ComputeSharp.SourceGenerators/Helpers/HashCode.cs rename to src/ComputeSharp.SourceGeneration/Helpers/HashCode.cs diff --git a/src/ComputeSharp.SourceGenerators/Helpers/SemanticModelProvider.cs b/src/ComputeSharp.SourceGeneration/Helpers/SemanticModelProvider.cs similarity index 97% rename from src/ComputeSharp.SourceGenerators/Helpers/SemanticModelProvider.cs rename to src/ComputeSharp.SourceGeneration/Helpers/SemanticModelProvider.cs index ca6efc34..b4dd8b35 100644 --- a/src/ComputeSharp.SourceGenerators/Helpers/SemanticModelProvider.cs +++ b/src/ComputeSharp.SourceGeneration/Helpers/SemanticModelProvider.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using Microsoft.CodeAnalysis; -namespace ComputeSharp.SourceGenerators.Helpers; +namespace ComputeSharp.SourceGeneration.Helpers; /// /// A type providing instances for nodes. diff --git a/src/ComputeSharp.SourceGenerators/Models/DiagnosticInfo.cs b/src/ComputeSharp.SourceGeneration/Models/DiagnosticInfo.cs similarity index 52% rename from src/ComputeSharp.SourceGenerators/Models/DiagnosticInfo.cs rename to src/ComputeSharp.SourceGeneration/Models/DiagnosticInfo.cs index e3711b93..88639f74 100644 --- a/src/ComputeSharp.SourceGenerators/Models/DiagnosticInfo.cs +++ b/src/ComputeSharp.SourceGeneration/Models/DiagnosticInfo.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; -using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using Microsoft.CodeAnalysis; -namespace ComputeSharp.SourceGenerators.Models; +namespace ComputeSharp.SourceGeneration.Models; /// /// A model for a serializeable diagnostic provider. @@ -16,49 +16,25 @@ internal sealed record DiagnosticInfo(DiagnosticDescriptor Descriptor, params ob /// /// An implementation for . /// - public sealed class Comparer : IEqualityComparer + public sealed class Comparer : Comparer { - /// - /// The singleton instance. - /// - public static Comparer Default { get; } = new(); - /// - public bool Equals(DiagnosticInfo? x, DiagnosticInfo? y) + protected override void AddToHashCode(ref HashCode hashCode, DiagnosticInfo obj) { - if (x is null && y is null) - { - return true; - } - - if (x is null || y is null) - { - return false; - } - - if (ReferenceEquals(x, y)) - { - return true; - } - - return - x.Descriptor.Equals(y.Descriptor) && - x.Args.SequenceEqual(y.Args); - } - - /// - public int GetHashCode(DiagnosticInfo obj) - { - HashCode hashCode = default; - hashCode.Add(obj.Descriptor); - + foreach (object arg in obj.Args) { hashCode.Add(arg); } + } - return hashCode.ToHashCode(); + /// + protected override bool AreEqual(DiagnosticInfo x, DiagnosticInfo y) + { + return + x.Descriptor.Equals(y.Descriptor) && + x.Args.SequenceEqual(y.Args); } } } diff --git a/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs b/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs new file mode 100644 index 00000000..68ee9fa4 --- /dev/null +++ b/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; +using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle; + +namespace ComputeSharp.SourceGeneration.Models; + +/// +/// A model describing the hierarchy info for a specific type. +/// +/// The filename hint for the current type. +/// The fully qualified metadata name for the current type. +/// Gets the namespace for the current type. +/// Gets the sequence of type definitions containing the current type. +internal sealed partial record HierarchyInfo(string FilenameHint, string FullyQualifiedMetadataName, string Namespace, ImmutableArray Hierarchy) +{ + /// + /// Creates a new instance from a given . + /// + /// The input instance to gather info for. + /// A instance describing . + public static HierarchyInfo From(INamedTypeSymbol typeSymbol) + { + ImmutableArray.Builder hierarchy = ImmutableArray.CreateBuilder(); + + for (INamedTypeSymbol? parent = typeSymbol; + parent is not null; + parent = parent.ContainingType) + { + hierarchy.Add(new TypeInfo( + parent.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), + parent.TypeKind, + parent.IsRecord)); + } + + return new( + typeSymbol.GetGeneratedFileName(), + typeSymbol.GetFullMetadataName(), + typeSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)), + hierarchy.ToImmutable()); + } + + /// + /// Creates a instance for the current hierarchy. + /// + /// The member declarations to add to the generated type. + /// A instance for the current hierarchy. + public CompilationUnitSyntax GetSyntax(params MemberDeclarationSyntax[] memberDeclarations) + { + // Create the partial type declaration with for the current hierarchy. + // This code produces a type declaration as follows: + // + // partial + // { + // + // } + TypeDeclarationSyntax typeDeclarationSyntax = + Hierarchy[0].GetSyntax() + .AddModifiers(Token(SyntaxKind.PartialKeyword)) + .AddMembers(memberDeclarations); + + // Add all parent types in ascending order, if any + foreach (TypeInfo parentType in Hierarchy.AsSpan().Slice(1)) + { + typeDeclarationSyntax = + parentType.GetSyntax() + .AddModifiers(Token(SyntaxKind.PartialKeyword)) + .AddMembers(typeDeclarationSyntax); + } + + if (Namespace is "") + { + // If there is no namespace, attach the pragma directly to the declared type, + // and skip the namespace declaration. This will produce code as follows: + // + // #pragma warning disable + // + // + return + CompilationUnit().AddMembers( + typeDeclarationSyntax + .WithModifiers(TokenList(Token( + TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), + SyntaxKind.PartialKeyword, + TriviaList())))) + .NormalizeWhitespace(eol: "\n"); + } + + // Create the compilation unit with disabled warnings, target namespace and generated type. + // This will produce code as follows: + // + // #pragma warning disable + // + // namespace ; + // + // + return + CompilationUnit().AddMembers( + FileScopedNamespaceDeclaration(IdentifierName(Namespace)) + .AddMembers(typeDeclarationSyntax) + .WithNamespaceKeyword(Token(TriviaList( + Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), + SyntaxKind.NamespaceKeyword, + TriviaList()))) + .NormalizeWhitespace(eol: "\n"); + } + + /// + /// An implementation for . + /// + public sealed class Comparer : Comparer + { + /// + protected override void AddToHashCode(ref HashCode hashCode, HierarchyInfo obj) + { + hashCode.Add(obj.FilenameHint); + hashCode.Add(obj.FullyQualifiedMetadataName); + hashCode.Add(obj.Namespace); + hashCode.AddRange(obj.Hierarchy); + } + + /// + protected override bool AreEqual(HierarchyInfo x, HierarchyInfo y) + { + return + x.FilenameHint == y.FilenameHint && + x.FullyQualifiedMetadataName == y.FullyQualifiedMetadataName && + x.Namespace == y.Namespace && + x.Hierarchy.SequenceEqual(y.Hierarchy); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/Models/Result{T}.cs b/src/ComputeSharp.SourceGeneration/Models/Result{T}.cs similarity index 91% rename from src/ComputeSharp.SourceGenerators/Models/Result{T}.cs rename to src/ComputeSharp.SourceGeneration/Models/Result{T}.cs index 4bee6af9..923ec833 100644 --- a/src/ComputeSharp.SourceGenerators/Models/Result{T}.cs +++ b/src/ComputeSharp.SourceGeneration/Models/Result{T}.cs @@ -1,7 +1,7 @@ using System.Collections.Immutable; using Microsoft.CodeAnalysis; -namespace ComputeSharp.SourceGenerators.Models; +namespace ComputeSharp.SourceGeneration.Models; /// /// A model representing a value and an associated set of diagnostic errors. diff --git a/src/ComputeSharp.SourceGeneration/Models/TypeInfo.cs b/src/ComputeSharp.SourceGeneration/Models/TypeInfo.cs new file mode 100644 index 00000000..f6d48c0a --- /dev/null +++ b/src/ComputeSharp.SourceGeneration/Models/TypeInfo.cs @@ -0,0 +1,42 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGeneration.Models; + +/// +/// A model describing a type info in a type hierarchy. +/// +/// The qualified name for the type. +/// The type of the type in the hierarchy. +/// Whether the type is a record type. +internal sealed record TypeInfo(string QualifiedName, TypeKind Kind, bool IsRecord) +{ + /// + /// Creates a instance for the current info. + /// + /// A instance for the current info. + public TypeDeclarationSyntax GetSyntax() + { + // Create the partial type declaration with the kind. + // This code produces a class declaration as follows: + // + // + // { + // } + // + // Note that specifically for record declarations, we also need to explicitly add the open + // and close brace tokens, otherwise member declarations will not be formatted correctly. + return Kind switch + { + TypeKind.Struct => StructDeclaration(QualifiedName), + TypeKind.Interface => InterfaceDeclaration(QualifiedName), + TypeKind.Class when IsRecord => + RecordDeclaration(Token(SyntaxKind.RecordKeyword), QualifiedName) + .WithOpenBraceToken(Token(SyntaxKind.OpenBraceToken)) + .WithCloseBraceToken(Token(SyntaxKind.CloseBraceToken)), + _ => ClassDeclaration(QualifiedName) + }; + } +} diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md index 1e3bcdee..254bf2b1 100644 --- a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md @@ -7,51 +7,53 @@ Rule ID | Category | Severity | Notes --------|----------|----------|------- -CMPS0001 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0002 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0003 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0004 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0005 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0006 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0007 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0008 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0009 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0010 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0011 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0012 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0013 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0014 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0015 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0016 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0017 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0018 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0019 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0020 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0021 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0022 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0023 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0024 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0025 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0026 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0027 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0028 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0029 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0030 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0031 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0032 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0033 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0034 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0035 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0036 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0037 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0038 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0039 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0040 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0041 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0042 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0043 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0044 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0045 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0046 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0047 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0048 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0001 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0002 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0003 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0004 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0005 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0006 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0007 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0008 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0009 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0010 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0011 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0012 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0013 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0014 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0015 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0016 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0017 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0018 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0019 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0020 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0021 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0022 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0023 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0024 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0025 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0026 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0027 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0028 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0029 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0030 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0031 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0032 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0033 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0034 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0035 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0036 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0037 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0038 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0039 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0040 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0041 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0042 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0043 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0044 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0045 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0046 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0047 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0048 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0049 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0050 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index bfd2581e..24881627 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -11,11 +11,56 @@ $(DefineConstants);SOURCE_GENERATOR - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -27,53 +72,12 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + @@ -87,12 +91,6 @@ - - - - - - @@ -100,7 +98,12 @@ - + + + + + + diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 6f41eb53..d57ee454 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -19,7 +19,7 @@ internal static class DiagnosticDescriptors id: "CMPS0001", title: "Invalid shader field", messageFormat: "The compute shader of type {0} contains a field \"{1}\" of an invalid type {2}", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A type representing a compute shader contains a field of a type that is not supported in HLSL.", @@ -35,7 +35,7 @@ internal static class DiagnosticDescriptors id: "CMPS0002", title: "Invalid group shared field type", messageFormat: "The compute shader of type {0} contains a group shared field \"{1}\" of an invalid type {2} (it must be an array)", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A group shared field must be of an array type.", @@ -51,7 +51,7 @@ internal static class DiagnosticDescriptors id: "CMPS0003", title: "Invalid group shared field element type", messageFormat: "The compute shader of type {0} contains a group shared field \"{1}\" of an invalid type {2} (it must be a primitive or unmanaged type)", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A group shared field element must be of a primitive or unmanaged type.", @@ -67,7 +67,7 @@ internal static class DiagnosticDescriptors id: "CMPS0004", title: "Invalid group shared field declaration", messageFormat: "The compute shader of type {0} contains a group shared field \"{1}\" that is not static", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A group shared field must be static.", @@ -83,7 +83,7 @@ internal static class DiagnosticDescriptors id: "CMPS0005", title: "Missing shader resources", messageFormat: "The compute shader of type {0} contains no resources to work on", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A compute shader must contain at least one resource.", @@ -96,7 +96,7 @@ internal static class DiagnosticDescriptors id: "CMPS0006", title: "Invalid ThreadIds usage", messageFormat: "The ThreadIds type can only be used within the main body of a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "The ThreadIds type can only be used within the main body of a compute shader.", @@ -109,7 +109,7 @@ internal static class DiagnosticDescriptors id: "CMPS0007", title: "Invalid GroupIds usage", messageFormat: "The GroupIds type can only be used within the main body of a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "The GroupIds type can only be used within the main body of a compute shader.", @@ -122,7 +122,7 @@ internal static class DiagnosticDescriptors id: "CMPS0008", title: "Invalid GroupSize usage", messageFormat: "The GroupSize type can only be used within the main body of a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "The GroupSize type can only be used within the main body of a compute shader.", @@ -135,7 +135,7 @@ internal static class DiagnosticDescriptors id: "CMPS0009", title: "Invalid GridIds usage", messageFormat: "The GridIds type can only be used within the main body of a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "The GridIds type can only be used within the main body of a compute shader.", @@ -151,7 +151,7 @@ internal static class DiagnosticDescriptors id: "CMPS0010", title: "Invalid object creation expression", messageFormat: "The type {0} cannot be created in a compute shader (only unmanaged types are supported)", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "Only unmanaged value type objects can be created in a compute shader.", @@ -164,7 +164,7 @@ internal static class DiagnosticDescriptors id: "CMPS0011", title: "Anonymous object creation expression", messageFormat: "An anonymous object cannot be created in a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "An anonymous object cannot be created in a compute shader.", @@ -177,7 +177,7 @@ internal static class DiagnosticDescriptors id: "CMPS0012", title: "Async modifier on method or function", messageFormat: "The async modifier cannot be used in methods or functions used in a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "The async modifier cannot be used in methods or functions used in a compute shader.", @@ -190,7 +190,7 @@ internal static class DiagnosticDescriptors id: "CMPS0013", title: "Await expression", messageFormat: "The await expression cannot be used in a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "The await expression cannot be used in a compute shader.", @@ -203,7 +203,7 @@ internal static class DiagnosticDescriptors id: "CMPS0014", title: "Checked expression", messageFormat: "A checked expression cannot be used in a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A checked expression cannot be used in a compute shader.", @@ -216,7 +216,7 @@ internal static class DiagnosticDescriptors id: "CMPS0015", title: "Checked statement", messageFormat: "A checked statement cannot be used in a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A checked statement cannot be used in a compute shader.", @@ -229,7 +229,7 @@ internal static class DiagnosticDescriptors id: "CMPS0016", title: "Fixed statement", messageFormat: "A fixed statement cannot be used in a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A fixed statement cannot be used in a compute shader.", @@ -242,7 +242,7 @@ internal static class DiagnosticDescriptors id: "CMPS0017", title: "Foreach statement", messageFormat: "A foreach statement cannot be used in a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A foreach statement cannot be used in a compute shader.", @@ -255,7 +255,7 @@ internal static class DiagnosticDescriptors id: "CMPS0018", title: "Foreach statement", messageFormat: "A lock statement cannot be used in a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A lock statement cannot be used in a compute shader.", @@ -268,7 +268,7 @@ internal static class DiagnosticDescriptors id: "CMPS0019", title: "Foreach statement", messageFormat: "A LINQ query expression cannot be used in a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A LINQ query expression cannot be used in a compute shader.", @@ -281,7 +281,7 @@ internal static class DiagnosticDescriptors id: "CMPS0020", title: "Range expression", messageFormat: "A range expression cannot be used in a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A range expression cannot be used in a compute shader.", @@ -294,7 +294,7 @@ internal static class DiagnosticDescriptors id: "CMPS0021", title: "Recursive pattern", messageFormat: "A recursive pattern cannot be used in a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A recursive pattern cannot be used in a compute shader.", @@ -307,7 +307,7 @@ internal static class DiagnosticDescriptors id: "CMPS0022", title: "Ref type", messageFormat: "A compute shader cannot have a ref type declaration", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A compute shader cannot have a ref type declaration.", @@ -320,7 +320,7 @@ internal static class DiagnosticDescriptors id: "CMPS0023", title: "Relational pattern", messageFormat: "A relational pattern cannot be used in a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A relational pattern cannot be used in a compute shader.", @@ -333,7 +333,7 @@ internal static class DiagnosticDescriptors id: "CMPS0024", title: "Sizeof expression", messageFormat: "A sizeof expression cannot be used in a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A sizeof expression cannot be used in a compute shader.", @@ -346,7 +346,7 @@ internal static class DiagnosticDescriptors id: "CMPS0025", title: "Stackalloc expression", messageFormat: "A stackalloc expression cannot be used in a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A stackalloc expression cannot be used in a compute shader.", @@ -359,7 +359,7 @@ internal static class DiagnosticDescriptors id: "CMPS0026", title: "Throw expression or statement", messageFormat: "Throw expressions and statements cannot be used in a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "Throw expressions and statements cannot be used in a compute shader.", @@ -372,7 +372,7 @@ internal static class DiagnosticDescriptors id: "CMPS0027", title: "Try statement", messageFormat: "A try statement cannot be used in a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A try statement cannot be used in a compute shader.", @@ -385,7 +385,7 @@ internal static class DiagnosticDescriptors id: "CMPS0028", title: "Tuple type", messageFormat: "A compute shader cannot have a tuple type declaration", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A compute shader cannot have a tuple type declaration.", @@ -398,7 +398,7 @@ internal static class DiagnosticDescriptors id: "CMPS0029", title: "Using statement or declaration", messageFormat: "Using statements and declarations cannot be used in a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "Using statements and declarations cannot be used in a compute shader.", @@ -411,7 +411,7 @@ internal static class DiagnosticDescriptors id: "CMPS0030", title: "Yield statement", messageFormat: "A yield statement cannot be used in a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A yield statement cannot be used in a compute shader.", @@ -427,7 +427,7 @@ internal static class DiagnosticDescriptors id: "CMPS0031", title: "Invalid object declaration", messageFormat: "A variable of type {0} cannot be declared in a compute shader (only unmanaged types are supported)", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "Only unmanaged value type objects can be declared in a compute shader.", @@ -440,7 +440,7 @@ internal static class DiagnosticDescriptors id: "CMPS0032", title: "Pointer type", messageFormat: "A compute shader cannot have a pointer type declaration", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A compute shader cannot have a pointer type declaration.", @@ -453,7 +453,7 @@ internal static class DiagnosticDescriptors id: "CMPS0033", title: "Function pointer type", messageFormat: "A compute shader cannot have a function pointer type declaration", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A compute shader cannot have a function pointer type declaration.", @@ -466,7 +466,7 @@ internal static class DiagnosticDescriptors id: "CMPS0034", title: "Unsafe statement", messageFormat: "A compute shader cannot have an unsafe statement", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A compute shader cannot have an unsafe statement.", @@ -479,7 +479,7 @@ internal static class DiagnosticDescriptors id: "CMPS0035", title: "Unsafe modifier on method or function", messageFormat: "The unsafe modifier cannot be used in methods or functions used in a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "The unsafe modifier cannot be used in methods or functions used in a compute shader.", @@ -492,7 +492,7 @@ internal static class DiagnosticDescriptors id: "CMPS0036", title: "String literal expression", messageFormat: "String literal expressions cannot be used in a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "String literal expressions cannot be used in a compute shader.", @@ -505,7 +505,7 @@ internal static class DiagnosticDescriptors id: "CMPS0037", title: "Non constant matrix swizzled property argument", messageFormat: "The arguments in a swizzled indexer for a matrix type must be compile-time constants", - category: typeof(ShaderMethodSourceGenerator).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "The arguments in a swizzled indexer for a matrix type must be compile-time constants.", @@ -521,7 +521,7 @@ internal static class DiagnosticDescriptors id: "CMPS0038", title: "Invalid shader static field type", messageFormat: "The compute shader of type {0} contains a static field \"{1}\" of an invalid type {2} (only primitive, vector and matrix types are supported)", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A type representing a compute shader contains a static field of a type that is not supported.", @@ -534,7 +534,7 @@ internal static class DiagnosticDescriptors id: "CMPS0039", title: "Invalid DispatchSize usage", messageFormat: "The DispatchSize type can only be used within the main body of a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "The DispatchSize type can only be used within the main body of a compute shader.", @@ -547,7 +547,7 @@ internal static class DiagnosticDescriptors id: "CMPS0040", title: "Property declaration", messageFormat: "Property declarations cannot be used in a compute shader", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "Property declarations cannot be used in a compute shader.", @@ -563,7 +563,7 @@ internal static class DiagnosticDescriptors id: "CMPS0041", title: "Shader dispatch data size exceeded", messageFormat: "The compute shader of type {0} has exceeded the maximum allowed size for captured values and resources", - category: typeof(IComputeShader).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "The compute shader of type {0} has exceeded the maximum allowed size for captured values and resources.", @@ -579,7 +579,7 @@ internal static class DiagnosticDescriptors id: "CMPS0042", title: "Multiple shader implementations for type declaration", messageFormat: "The shader of type {0} cannot implement more than one shader interface", - category: typeof(IShaderGenerator).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A shader type cannot implement more than one shader interface.", @@ -595,7 +595,7 @@ internal static class DiagnosticDescriptors id: "CMPS0043", title: "Embedded bytecode for dynamic shader", messageFormat: "The shader of type {0} cannot be precompiled, as it is dynamic (it captures delegate fields)", - category: typeof(IShaderGenerator).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A shader type cannot be precompiled if it captures one or more delegate values.", @@ -611,7 +611,7 @@ internal static class DiagnosticDescriptors id: "CMPS0044", title: "Invalid thread ids for shader with embedded bytecode", messageFormat: "The shader of type {0} is annotated with invalid thread ids values ({1}, {2}, {3})", - category: typeof(IShaderGenerator).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "The thread ids values for a shader marked as embedded bytecode have to be in the valid range.", @@ -627,7 +627,7 @@ internal static class DiagnosticDescriptors id: "CMPS0045", title: "Embedded bytecode compilation failed due to Win32 exception", messageFormat: "The shader of type {0} failed to compile due to a Win32 exception (HRESULT: {1:X8}, Message: \"{2}\")", - category: typeof(IShaderGenerator).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "The embedded bytecode for a shader failed to be compiled due to a Win32 exception.", @@ -639,11 +639,11 @@ internal static class DiagnosticDescriptors /// Format: "The shader of type {{0}} failed to compile due to an HLSL compiler error (Message: "{1}")". /// /// - public static readonly DiagnosticDescriptor EmbeddedBytecodeFailedWithHlslCompilationException = new DiagnosticDescriptor( + public static readonly DiagnosticDescriptor EmbeddedBytecodeFailedWithDxcCompilationException = new DiagnosticDescriptor( id: "CMPS0046", title: "Embedded bytecode compilation failed due to an HLSL compiler error", messageFormat: "The shader of type {0} failed to compile due to an HLSL compiler error (Message: \"{1}\")", - category: typeof(IShaderGenerator).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "The embedded bytecode for a shader failed to be compiled due to an HLSL compiler error.", @@ -659,7 +659,7 @@ internal static class DiagnosticDescriptors id: "CMPS0047", title: "Embedded bytecode compilation failed due to an HLSL compiler error", messageFormat: "The shader of type {0} needs to be annotated as having embedded bytecode (using the [EmbeddedBytecode] attribute), as dynamic shader compilation is not supported", - category: typeof(IShaderGenerator).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "When dynamic shader compilation is not supported (ie. when ComputeSharp.Dynamic is not referenced), all shaders need to be annotated as having embedded bytecode (using the [EmbeddedBytecode] attribute).", @@ -675,9 +675,41 @@ internal static class DiagnosticDescriptors id: "CMPS0048", title: "Invalid dispatch axis for shader with embedded bytecode", messageFormat: "The shader of type {0} is annotated with with an invalid dispatch axis value", - category: typeof(IShaderGenerator).FullName, + category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "The dispatch axis value for a shader marked as embedded bytecode have to be valid (flags are not supported).", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a method invocation that is not valid from a shader. + /// + /// Format: "The method {0} cannot be used in a shader (methods need to either be HLSL intrinsics or with source available for analysis)". + /// + /// + public static readonly DiagnosticDescriptor InvalidMethodCall = new DiagnosticDescriptor( + id: "CMPS0049", + title: "Invalid method invocation from a shader", + messageFormat: "The method {0} cannot be used in a shader (methods need to either be HLSL intrinsics or with source available for analysis)", + category: "ComputeSharp.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "Shaders can only invoke methods that are either HLSL intrinsics or with source available for analysis.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an invalid discovered type. + /// + /// Format: "The compute shader or method {0} uses the invalid type {1}". + /// + /// + public static readonly DiagnosticDescriptor InvalidDiscoveredType = new DiagnosticDescriptor( + id: "CMPS0050", + title: "Invalid discovered type", + messageFormat: "The compute shader or method {0} uses the invalid type {1} (only some .NET primitives and vector types, HLSL primitive, vector and matrix types, and custom types containing these types can be used)", + category: "ComputeSharp.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "Shaders and shader methods can only use supported types (some .NET primitives and vector types, HLSL primitive, vector and matrix types, and custom types containing these types can be used).", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } diff --git a/src/ComputeSharp.SourceGenerators/Extensions/StringExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/StringExtensions.cs deleted file mode 100644 index 993450dc..00000000 --- a/src/ComputeSharp.SourceGenerators/Extensions/StringExtensions.cs +++ /dev/null @@ -1,18 +0,0 @@ - -namespace ComputeSharp.SourceGenerators.Extensions; - -/// -/// Extension methods for types. -/// -internal static class StringExtensions -{ - /// - /// Converts a given instance to a valid HLSL identifier name. - /// - /// The input instance to convert. - /// An valid HLSL identifier name from . - public static string ToHlslIdentifierName(this string text) - { - return text.Replace('.', '_').Replace('+', '_'); - } -} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs similarity index 97% rename from src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs rename to src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs index ce88d435..9140019e 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs @@ -12,17 +12,17 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGenerators; /// -public sealed partial class IShaderGenerator +partial class IShaderGenerator { /// - internal static partial class BuildHlslString + partial class BuildHlslSource { /// - /// Creates a instance for the BuildHlslString method. + /// Creates a instance for the BuildHlslSource method. /// /// The input instance to use. /// Indicates whether or not dynamic shaders are supported. - /// The resulting instance for the BuildHlslString method. + /// The resulting instance for the BuildHlslSource method. public static MethodDeclarationSyntax GetSyntax(HlslShaderSourceInfo hlslSourceInfo, bool supportsDynamicShaders) { // Generate the necessary body statements depending on whether dynamic shaders are supported @@ -32,14 +32,14 @@ public sealed partial class IShaderGenerator // This code produces a method declaration as follows: // - // readonly void global::ComputeSharp.__Internals.IShader.BuildHlslString(out global::ComputeSharp.__Internals.ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ) + // readonly void global::ComputeSharp.__Internals.IShader.BuildHlslSource(out global::ComputeSharp.__Internals.ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ) // { // // } return MethodDeclaration( PredefinedType(Token(SyntaxKind.VoidKeyword)), - Identifier("BuildHlslString")) + Identifier("BuildHlslSource")) .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) .AddParameterListParameters( diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs similarity index 96% rename from src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs rename to src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs index 89bff376..3e35ad4b 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs @@ -3,10 +3,10 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Mappings; using ComputeSharp.SourceGenerators.Diagnostics; -using ComputeSharp.SourceGenerators.Extensions; -using ComputeSharp.SourceGenerators.Helpers; -using ComputeSharp.SourceGenerators.Mappings; using ComputeSharp.SourceGenerators.Models; using ComputeSharp.SourceGenerators.SyntaxRewriters; using Microsoft.CodeAnalysis; @@ -20,12 +20,12 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGenerators; /// -public sealed partial class IShaderGenerator +partial class IShaderGenerator { /// - /// A helper with all logic to generate the BuildHlslString method. + /// A helper with all logic to generate the BuildHlslSource method. /// - internal static partial class BuildHlslString + internal static partial class BuildHlslSource { /// /// Gathers all necessary information on a transpiled HLSL source for a given shader type. @@ -67,7 +67,7 @@ public sealed partial class IShaderGenerator var sharedBuffers = GetSharedBuffers(builder, structDeclarationSymbol, discoveredTypes); var (entryPoint, processedMethods, isSamplerUsed) = GetProcessedMethods(builder, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); var implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?); - var declaredTypes = GetDeclaredTypes(discoveredTypes); + var declaredTypes = GetDeclaredTypes(builder, structDeclarationSymbol, discoveredTypes); var definedConstants = GetDefinedConstants(constantDefinitions); var staticFields = GetStaticFields(builder, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); @@ -432,12 +432,19 @@ public sealed partial class IShaderGenerator /// Gets the sequence of processed discovered custom types. /// /// The sequence of discovered custom types. + /// The symbol for the current object being processed. + /// The collection of produced instances. /// A sequence of custom type definitions to add to the shader source. - internal static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(IEnumerable types) + internal static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes( + ImmutableArray.Builder diagnostics, + ISymbol sourceSymbol, + IEnumerable types) { ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(); + IReadOnlyCollection invalidTypes; - foreach (var type in HlslKnownTypes.GetCustomTypes(types)) + // Process the discovered types + foreach (var type in HlslKnownTypes.GetCustomTypes(types, out invalidTypes)) { var structType = type.GetFullMetadataName().ToHlslIdentifierName(); var structDeclaration = StructDeclaration(structType); @@ -470,6 +477,12 @@ public sealed partial class IShaderGenerator .ToFullString())); } + // Process the invalid types + foreach (INamedTypeSymbol invalidType in invalidTypes) + { + diagnostics.Add(InvalidDiscoveredType, sourceSymbol, sourceSymbol, invalidType); + } + return builder.ToImmutable(); } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs index 6018704f..e2ce418e 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs @@ -10,10 +10,10 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGenerators; /// -public sealed partial class IShaderGenerator +partial class IShaderGenerator { /// - private static partial class GetDispatchId + partial class GetDispatchId { /// /// Creates a instance for the GetDispatchId method. diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs index c8af7e86..ebeb772e 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs @@ -5,7 +5,7 @@ using Microsoft.CodeAnalysis; namespace ComputeSharp.SourceGenerators; /// -public sealed partial class IShaderGenerator +partial class IShaderGenerator { /// /// A helper with all logic to generate the GetDispatchId method. diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs index 4b2378e4..7784cedd 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs @@ -11,10 +11,10 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGenerators; /// -public sealed partial class IShaderGenerator +partial class IShaderGenerator { /// - private static partial class LoadBytecode + partial class LoadBytecode { /// /// Creates a instance for the TryGetBytecode method. @@ -22,7 +22,7 @@ public sealed partial class IShaderGenerator /// The input instance. /// Indicates whether or not dynamic shaders are supported. /// An opaque instance to transform the final tree into text. - /// The resulting instance for the BuildHlslString method. + /// The resulting instance for the BuildHlslSource method. public static MethodDeclarationSyntax GetSyntax(EmbeddedBytecodeInfo bytecodeInfo, bool supportsDynamicShaders, out Func fixup) { BlockSyntax block = GetShaderBytecodeBody(bytecodeInfo, supportsDynamicShaders, out string? bytecodeLiterals); @@ -171,11 +171,11 @@ public sealed partial class IShaderGenerator IdentifierName("ComputeSharp.__Internals.ShaderCompiler"), IdentifierName("LoadDynamicBytecode"))) .AddArgumentListArguments( - Argument(IdentifierName("loader")).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)), + Argument(IdentifierName("loader")).WithRefKindKeyword(Token(SyntaxKind.RefKeyword)), Argument(IdentifierName("threadsX")), Argument(IdentifierName("threadsY")), Argument(IdentifierName("threadsZ")), - Argument(ThisExpression()).WithRefOrOutKeyword(Token(SyntaxKind.InKeyword)))); + Argument(ThisExpression()).WithRefKindKeyword(Token(SyntaxKind.InKeyword)))); } /// diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs index 6597e031..f535b721 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs @@ -6,10 +6,12 @@ using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using System.Text.RegularExpressions; using System.Threading; using ComputeSharp.Exceptions; using ComputeSharp.Shaders.Translation; -using ComputeSharp.SourceGenerators.Diagnostics; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Models; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -20,7 +22,7 @@ using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; namespace ComputeSharp.SourceGenerators; /// -public sealed partial class IShaderGenerator +partial class IShaderGenerator { /// /// A helper with all logic to generate the LoadBytecode method. @@ -172,7 +174,7 @@ public sealed partial class IShaderGenerator .Replace("", threadIds.Z.ToString()); // Compile the shader bytecode - using ComPtr dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(hlslSource.AsSpan()); + using ComPtr dxcBlobBytecode = ShaderCompiler.Instance.Compile(hlslSource.AsSpan()); token.ThrowIfCancellationRequested(); @@ -186,17 +188,36 @@ public sealed partial class IShaderGenerator } catch (Win32Exception e) { - diagnostic = new DiagnosticInfo(EmbeddedBytecodeFailedWithWin32Exception, e.HResult, e.Message); + diagnostic = new DiagnosticInfo(EmbeddedBytecodeFailedWithWin32Exception, e.HResult, FixupExceptionMessage(e.Message)); } - catch (HlslCompilationException e) + catch (DxcCompilationException e) { - diagnostic = new DiagnosticInfo(EmbeddedBytecodeFailedWithHlslCompilationException, e.Message); + diagnostic = new DiagnosticInfo(EmbeddedBytecodeFailedWithDxcCompilationException, FixupExceptionMessage(e.Message)); } End: return bytecode; } + /// + /// Fixes up an exception message to improve the way it's displayed in VS. + /// + /// The input exception message. + /// The updated exception message. + private static string FixupExceptionMessage(string message) + { + // Add square brackets around error headers + message = Regex.Replace(message, @"^(error|warning):", static m => $"[{m.Groups[1].Value}]:", RegexOptions.Multiline); + + // Remove lines with notes + message = Regex.Replace(message, @"^note:.+", string.Empty, RegexOptions.Multiline); + + // Remove syntax error indicators + message = Regex.Replace(message, @"^ +\^", string.Empty, RegexOptions.Multiline); + + return message.NormalizeToSingleLine(); + } + /// /// Extracts and loads the dxcompiler.dll and dxil.dll libraries. /// diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs index 2c9391cc..006f1058 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -11,10 +11,10 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGenerators; /// -public sealed partial class IShaderGenerator +partial class IShaderGenerator { /// - private static partial class LoadDispatchData + partial class LoadDispatchData { /// /// Creates a instance for the LoadDispatchDataMethod method. @@ -148,7 +148,7 @@ public sealed partial class IShaderGenerator // This will result in the following (assuming Float2x3 m): // // ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m)); - // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0); + // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0); // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1); for (int j = 0; j < matrix.Rows; j++) { diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs index 813722bf..f7a20523 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs @@ -4,9 +4,8 @@ using System.Collections.Immutable; using System.Linq; using System.Runtime.CompilerServices; using ComputeSharp.Core.Helpers; -using ComputeSharp.SourceGenerators.Diagnostics; -using ComputeSharp.SourceGenerators.Extensions; -using ComputeSharp.SourceGenerators.Mappings; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Mappings; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; @@ -14,7 +13,7 @@ using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; namespace ComputeSharp.SourceGenerators; /// -public sealed partial class IShaderGenerator +partial class IShaderGenerator { /// /// A helper with all logic to generate the LoadDispatchData method. diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs index 0e5f945f..deb62ae2 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs @@ -11,10 +11,10 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGenerators; /// -public sealed partial class IShaderGenerator +partial class IShaderGenerator { /// - private static partial class LoadDispatchMetadata + partial class LoadDispatchMetadata { /// /// Creates a instance for the LoadDispatchMetadata method. diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs index 5132b5d0..b89652a4 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs @@ -1,11 +1,11 @@ using System.Collections.Immutable; -using ComputeSharp.SourceGenerators.Mappings; +using ComputeSharp.SourceGeneration.Mappings; using ComputeSharp.SourceGenerators.Models; namespace ComputeSharp.SourceGenerators; /// -public sealed partial class IShaderGenerator +partial class IShaderGenerator { /// /// A helper with all logic to generate the LoadDispatchMetadata method. diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs index 1352edac..88d0550c 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using ComputeSharp.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -9,7 +9,7 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGenerators; /// -public sealed partial class IShaderGenerator +partial class IShaderGenerator { /// /// Gets the shader type for a given shader, if any. @@ -79,64 +79,6 @@ public sealed partial class IShaderGenerator attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit"))))); } - // Create the partial shader type declaration with the given method implementation. - // This code produces a struct declaration as follows: - // - // partial struct - // { - // - // } - StructDeclarationSyntax structDeclarationSyntax = - StructDeclaration(hierarchyInfo.Names[0]) - .AddModifiers(Token(SyntaxKind.PartialKeyword)) - .AddMembers(methodDeclaration.AddAttributeLists(attributes.ToArray())); - - TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax; - - // Add all parent types in ascending order, if any - foreach (string parentType in hierarchyInfo.Names.AsSpan().Slice(1)) - { - typeDeclarationSyntax = - ClassDeclaration(parentType) - .AddModifiers(Token(SyntaxKind.PartialKeyword)) - .AddMembers(typeDeclarationSyntax); - } - - if (hierarchyInfo.Namespace is "") - { - // If there is no namespace, attach the pragma directly to the declared type, - // and skip the namespace declaration. This is the same additional path also - // used when generating custom constructors. This will produce code as follows: - // - // #pragma warning disable - // - // - return - CompilationUnit().AddMembers( - typeDeclarationSyntax - .WithModifiers(TokenList(Token( - TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), - SyntaxKind.PartialKeyword, - TriviaList())))) - .NormalizeWhitespace(eol: "\n"); - } - - // Create the compilation unit with disabled warnings, target namespace and generated type. - // This will produce code as follows: - // - // #pragma warning disable - // - // namespace ; - // - // - return - CompilationUnit().AddMembers( - FileScopedNamespaceDeclaration(IdentifierName(hierarchyInfo.Namespace)) - .AddMembers(typeDeclarationSyntax) - .WithNamespaceKeyword(Token(TriviaList( - Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), - SyntaxKind.NamespaceKeyword, - TriviaList()))) - .NormalizeWhitespace(eol: "\n"); + return hierarchyInfo.GetSyntax(methodDeclaration.AddAttributeLists(attributes.ToArray())); } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index df87587d..db71bc07 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -2,8 +2,9 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Models; using ComputeSharp.SourceGenerators.Diagnostics; -using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -14,7 +15,7 @@ namespace ComputeSharp.SourceGenerators; /// /// A source generator creating data loaders for and types. /// -[Generator] +[Generator(LanguageNames.CSharp)] public sealed partial class IShaderGenerator : IIncrementalGenerator { /// @@ -100,8 +101,8 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator token.ThrowIfCancellationRequested(); - // BuildHlslString() info - HlslShaderSourceInfo hlslSourceInfo = BuildHlslString.GetInfo( + // BuildHlslSource() info + HlslShaderSourceInfo hlslSourceInfo = BuildHlslSource.GetInfo( item.Right, item.Left.Left.Syntax, item.Left.Left.Symbol, @@ -118,6 +119,13 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator token.ThrowIfCancellationRequested(); + // Ensure the bytecode generation is disabled if any errors are present + if (!dispatchDataDiagnostics.IsDefaultOrEmpty || + !hlslSourceDiagnostics.IsDefaultOrEmpty) + { + threadIds = new ThreadIdsInfo(true, 0, 0, 0); + } + return ( new Result(dispatchDataInfo, dispatchDataDiagnostics), new Result(hlslSourceInfo, hlslSourceDiagnostics), @@ -133,7 +141,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator IncrementalValuesProvider<(DispatchDataInfo Dispatch, HlslShaderSourceInfo Hlsl, ThreadIdsInfo ThreadIds)> shaderInfo = shaderInfoWithErrors .Select(static (item, token) => (item.Dispatch.Value, item.Hlsl.Value, item.ThreadIds.Value)) - .WithComparers(DispatchDataInfo.Comparer.Default, HlslShaderSourceInfo.Comparer.Default, ThreadIdsInfo.Comparer.Default); + .WithComparers(DispatchDataInfo.Comparer.Default, HlslShaderSourceInfo.Comparer.Default, EqualityComparer.Default); // Get a filtered sequence to enable caching IncrementalValuesProvider dispatchDataInfo = @@ -161,13 +169,13 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator .Select(static (item, token) => (item.Left.Dispatch.Hierarchy, item.Left.Hlsl, item.Right)) .WithComparers(HierarchyInfo.Comparer.Default, HlslShaderSourceInfo.Comparer.Default, EqualityComparer.Default); - // Generate the BuildHlslString() methods + // Generate the BuildHlslSource() methods context.RegisterSourceOutput(hlslSourceInfo.Combine(canUseSkipLocalsInit), static (context, item) => { - MethodDeclarationSyntax buildHlslStringMethod = BuildHlslString.GetSyntax(item.Left.SourceInfo, item.Left.SupportsDynamicShaders); + MethodDeclarationSyntax buildHlslStringMethod = BuildHlslSource.GetSyntax(item.Left.SourceInfo, item.Left.SupportsDynamicShaders); CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, buildHlslStringMethod, item.Right); - context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(BuildHlslString)}", compilationUnit.ToFullString()); + context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(BuildHlslSource)}", compilationUnit.ToFullString()); }); // Get the dispatch metadata info @@ -199,8 +207,8 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator // Transform the raw HLSL source to compile IncrementalValuesProvider<(HierarchyInfo Hierarchy, string Hlsl, ThreadIdsInfo ThreadIds)> shaderBytecodeInfo = shaderInfo - .Select(static (item, token) => (item.Dispatch.Hierarchy, BuildHlslString.GetNonDynamicHlslSource(item.Hlsl), item.ThreadIds)) - .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default, ThreadIdsInfo.Comparer.Default); + .Select(static (item, token) => (item.Dispatch.Hierarchy, BuildHlslSource.GetNonDynamicHlslSource(item.Hlsl), item.ThreadIds)) + .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default, EqualityComparer.Default); // Compile the requested shader bytecodes IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo, DiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors = @@ -221,20 +229,19 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator }); // Gather the diagnostics - IncrementalValuesProvider> embeddedBytecodeDiagnostics = + IncrementalValuesProvider embeddedBytecodeDiagnostics = embeddedBytecodeWithErrors - .Select(static (item, token) => (item.Hierarchy.MetadataName, item.Diagnostic)) + .Select(static (item, token) => (item.Hierarchy.FullyQualifiedMetadataName, item.Diagnostic)) .Where(static item => item.Diagnostic is not null) .Combine(context.CompilationProvider) .Select(static (item, token) => { - INamedTypeSymbol? typeSymbol = item.Right.GetTypeByMetadataName(item.Left.MetadataName)!; - Diagnostic diagnostic = Diagnostic.Create( + INamedTypeSymbol typeSymbol = item.Right.GetTypeByMetadataName(item.Left.FullyQualifiedMetadataName)!; + + return Diagnostic.Create( item.Left.Diagnostic!.Descriptor, typeSymbol.Locations.FirstOrDefault(), new object[] { typeSymbol }.Concat(item.Left.Diagnostic.Args).ToArray()); - - return ImmutableArray.Create(diagnostic); }); // Output the diagnostics diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownKeywords.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownKeywords.cs index 0c1d7c5f..40ce2cbb 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownKeywords.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownKeywords.cs @@ -1,69 +1,17 @@ using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using ComputeSharp.Core.Intrinsics.Attributes; -namespace ComputeSharp.SourceGenerators.Mappings; +namespace ComputeSharp.SourceGeneration.Mappings; -/// -/// A that contains and maps known HLSL identifier names valid HLSL names. -/// -internal static class HlslKnownKeywords +/// +internal static partial class HlslKnownKeywords { - /// - /// The mapping of known HLSL keywords. - /// - private static readonly IReadOnlyCollection KnownKeywords = BuildKnownKeywordsMap(); - - /// - /// Builds the mapping of all known HLSL keywords. - /// - private static IReadOnlyCollection BuildKnownKeywordsMap() + /// + static partial void AddKnownKeywords(ICollection knownKeywords) { - // HLSL keywords - HashSet knownKeywords = new(new[] - { - "asm", "asm_fragment", "cbuffer", "centroid", "column_major", - "compile", "discard", "dword", "export", "fxgroup", "groupshared", - "half", "inline", "inout", "line", "lineadj", "linear", "matrix", - "nointerpolation", "noperspective", "NULL", "packoffset", "pass", - "pixelfragment", "point", "precise", "register", "row_major", "sample", - "sampler", "shared", "snorm", "stateblock", "stateblock_state", "tbuffer", - "technique", "typedef", "triangle", "triangleadj", "uniform", "unorm", - "unsigned", "vector", "vertexfragment", "zero" - }); - // Dispatch type names knownKeywords.Add(nameof(ThreadIds)); knownKeywords.Add(nameof(GroupIds)); knownKeywords.Add(nameof(GroupSize)); knownKeywords.Add(nameof(GridIds)); - - // HLSL intrinsics method names - foreach (var method in typeof(Hlsl).GetMethods(BindingFlags.Public | BindingFlags.Static)) - { - string name = method.GetCustomAttribute()?.Name ?? method.Name; - - knownKeywords.Add(name); - } - - return knownKeywords; - } - - /// - /// Tries to get the mapped HLSL-compatible identifier name for the input identifier name. - /// - /// The input identifier name. - /// The mapped identifier name, if a replacement is needed. - /// The HLSL-compatible identifier name that can be used in an HLSL shader. - public static bool TryGetMappedName(string name, out string? mapped) - { - mapped = KnownKeywords.Contains(name) switch - { - true => $"__reserved__{name}", - false => null - }; - - return mapped is not null; } } diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs deleted file mode 100644 index a3d99549..00000000 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs +++ /dev/null @@ -1,440 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Linq; -using System.Numerics; -using System.Reflection; -using System.Text.RegularExpressions; - -namespace ComputeSharp.SourceGenerators.Mappings; - -/// -/// A that contains and maps known HLSL member names to common .NET members. -/// -internal static class HlslKnownMembers -{ - /// - /// The mapping of supported known indexers to HLSL resource type names. - /// - private static readonly IReadOnlyDictionary KnownResourceIndexers = new Dictionary - { - [$"ComputeSharp.ReadOnlyTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", - [$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", - [$"ComputeSharp.ReadWriteTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", - [$"ComputeSharp.ReadWriteTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", - [$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", - [$"ComputeSharp.IReadWriteTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", - [$"ComputeSharp.IReadOnlyNormalizedTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", - [$"ComputeSharp.IReadWriteNormalizedTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", - [$"ComputeSharp.ReadOnlyTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", - [$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", - [$"ComputeSharp.ReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", - [$"ComputeSharp.ReadWriteTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", - [$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", - [$"ComputeSharp.IReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", - [$"ComputeSharp.IReadOnlyNormalizedTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", - [$"ComputeSharp.IReadWriteNormalizedTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3" - }; - - /// - /// The mapping of supported known samplers to HLSL resource type names. - /// - private static readonly IReadOnlyDictionary KnownResourceSamplers = new Dictionary - { - [$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2", - [$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(Float2).FullName}]"] = null, - [$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2", - [$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(Float2).FullName}]"] = null, - [$"ComputeSharp.IReadOnlyNormalizedTexture2D`1.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2", - [$"ComputeSharp.IReadOnlyNormalizedTexture2D`1.this[{typeof(Float2).FullName}]"] = null, - [$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3", - [$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(Float3).FullName}]"] = null, - [$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3", - [$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(Float3).FullName}]"] = null, - [$"ComputeSharp.IReadOnlyNormalizedTexture3D`1.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3", - [$"ComputeSharp.IReadOnlyNormalizedTexture3D`1.this[{typeof(Float3).FullName}]"] = null - }; - - /// - /// The mapping of supported known size accessors for HLSL resource types. - /// - private static readonly IReadOnlyDictionary KnownSizeAccessors = new Dictionary - { - ["ComputeSharp.Resources.Buffer`1.Length"] = (2, 0), - ["ComputeSharp.Resources.Texture2D`1.Width"] = (2, 0), - ["ComputeSharp.Resources.Texture2D`1.Height"] = (2, 1), - ["ComputeSharp.Resources.Texture3D`1.Width"] = (3, 0), - ["ComputeSharp.Resources.Texture3D`1.Height"] = (3, 1), - ["ComputeSharp.Resources.Texture3D`1.Depth"] = (3, 2), - ["ComputeSharp.IReadOnlyTexture2D`1.Width"] = (2, 0), - ["ComputeSharp.IReadOnlyTexture2D`1.Height"] = (2, 1), - ["ComputeSharp.IReadOnlyTexture3D`1.Width"] = (3, 0), - ["ComputeSharp.IReadOnlyTexture3D`1.Height"] = (3, 1), - ["ComputeSharp.IReadOnlyTexture3D`1.Depth"] = (3, 2), - ["ComputeSharp.IReadOnlyNormalizedTexture2D`1.Width"] = (2, 0), - ["ComputeSharp.IReadOnlyNormalizedTexture2D`1.Height"] = (2, 1), - ["ComputeSharp.IReadOnlyNormalizedTexture3D`1.Width"] = (3, 0), - ["ComputeSharp.IReadOnlyNormalizedTexture3D`1.Height"] = (3, 1), - ["ComputeSharp.IReadOnlyNormalizedTexture3D`1.Depth"] = (3, 2), - ["ComputeSharp.IReadWriteNormalizedTexture2D`1.Width"] = (2, 0), - ["ComputeSharp.IReadWriteNormalizedTexture2D`1.Height"] = (2, 1), - ["ComputeSharp.IReadWriteNormalizedTexture3D`1.Width"] = (3, 0), - ["ComputeSharp.IReadWriteNormalizedTexture3D`1.Height"] = (3, 1), - ["ComputeSharp.IReadWriteNormalizedTexture3D`1.Depth"] = (3, 2) - }; - - /// - /// The mapping of supported known members to HLSL names. - /// - private static readonly IReadOnlyDictionary KnownMembers = BuildKnownMembersMap(); - - /// - /// Builds the mapping of supported known members to HLSL names. - /// - private static IReadOnlyDictionary BuildKnownMembersMap() - { - Dictionary knownMembers = new() - { - [$"{typeof(Vector2).FullName}.{nameof(Vector2.X)}"] = "x", - [$"{typeof(Vector2).FullName}.{nameof(Vector2.Y)}"] = "y", - [$"{typeof(Vector2).FullName}.{nameof(Vector2.Zero)}"] = "(float2)0", - [$"{typeof(Vector2).FullName}.{nameof(Vector2.One)}"] = "float2(1.0f, 1.0f)", - [$"{typeof(Vector2).FullName}.{nameof(Vector2.UnitX)}"] = "float2(1.0f, 0.0f)", - [$"{typeof(Vector2).FullName}.{nameof(Vector2.UnitY)}"] = "float2(0.0f, 1.0f)", - - [$"{typeof(Vector3).FullName}.{nameof(Vector3.X)}"] = "x", - [$"{typeof(Vector3).FullName}.{nameof(Vector3.Y)}"] = "y", - [$"{typeof(Vector3).FullName}.{nameof(Vector3.Z)}"] = "z", - [$"{typeof(Vector3).FullName}.{nameof(Vector3.Zero)}"] = "(float3)0", - [$"{typeof(Vector3).FullName}.{nameof(Vector3.One)}"] = "float3(1.0f, 1.0f, 1.0f)", - [$"{typeof(Vector3).FullName}.{nameof(Vector3.UnitX)}"] = "float3(1.0f, 0.0f, 0.0f)", - [$"{typeof(Vector3).FullName}.{nameof(Vector3.UnitY)}"] = "float3(0.0f, 1.0f, 0.0f)", - [$"{typeof(Vector3).FullName}.{nameof(Vector3.UnitZ)}"] = "float3(0.0f, 0.0f, 1.0f)", - - [$"{typeof(Vector4).FullName}.{nameof(Vector4.X)}"] = "x", - [$"{typeof(Vector4).FullName}.{nameof(Vector4.Y)}"] = "y", - [$"{typeof(Vector4).FullName}.{nameof(Vector4.Z)}"] = "z", - [$"{typeof(Vector4).FullName}.{nameof(Vector4.W)}"] = "w", - [$"{typeof(Vector4).FullName}.{nameof(Vector4.Zero)}"] = "(float4)0", - [$"{typeof(Vector4).FullName}.{nameof(Vector4.One)}"] = "float4(1.0f, 1.0f, 1.0f, 1.0f)", - - [$"{typeof(Bool2).FullName}.{nameof(Bool2.False)}"] = "(bool2)0", - [$"{typeof(Bool2).FullName}.{nameof(Bool2.True)}"] = "bool2(true, true)", - [$"{typeof(Bool2).FullName}.{nameof(Bool2.TrueX)}"] = "bool2(true, false)", - [$"{typeof(Bool2).FullName}.{nameof(Bool2.TrueY)}"] = "bool2(false, true)", - - [$"{typeof(Bool3).FullName}.{nameof(Bool3.False)}"] = "(bool3)0", - [$"{typeof(Bool3).FullName}.{nameof(Bool3.True)}"] = "bool3(true, true, true)", - [$"{typeof(Bool3).FullName}.{nameof(Bool3.TrueX)}"] = "bool3(true, false, false)", - [$"{typeof(Bool3).FullName}.{nameof(Bool3.TrueY)}"] = "bool3(false, true, false)", - [$"{typeof(Bool3).FullName}.{nameof(Bool3.TrueZ)}"] = "bool3(false, false, true)", - - [$"{typeof(Bool4).FullName}.{nameof(Bool4.False)}"] = "(bool4)0", - [$"{typeof(Bool4).FullName}.{nameof(Bool4.True)}"] = "bool4(true, true, true, true)", - [$"{typeof(Bool4).FullName}.{nameof(Bool4.TrueX)}"] = "bool4(true, false, false, false)", - [$"{typeof(Bool4).FullName}.{nameof(Bool4.TrueY)}"] = "bool4(false, true, false, false)", - [$"{typeof(Bool4).FullName}.{nameof(Bool4.TrueZ)}"] = "bool4(false, false, true, false)", - [$"{typeof(Bool4).FullName}.{nameof(Bool4.TrueW)}"] = "bool4(false, false, false, true)", - - [$"{typeof(Int2).FullName}.{nameof(Int2.Zero)}"] = "(int2)0", - [$"{typeof(Int2).FullName}.{nameof(Int2.One)}"] = "int2(1, 1)", - [$"{typeof(Int2).FullName}.{nameof(Int2.UnitX)}"] = "int2(1, 0)", - [$"{typeof(Int2).FullName}.{nameof(Int2.UnitY)}"] = "int2(0, 1)", - - [$"{typeof(Int3).FullName}.{nameof(Int3.Zero)}"] = "(int3)0", - [$"{typeof(Int3).FullName}.{nameof(Int3.One)}"] = "int3(1, 1, 1)", - [$"{typeof(Int3).FullName}.{nameof(Int3.UnitX)}"] = "int3(1, 0, 0)", - [$"{typeof(Int3).FullName}.{nameof(Int3.UnitY)}"] = "int3(0, 1, 0)", - [$"{typeof(Int3).FullName}.{nameof(Int3.UnitZ)}"] = "int3(0, 0, 1)", - - [$"{typeof(Int4).FullName}.{nameof(Int4.Zero)}"] = "(int4)0", - [$"{typeof(Int4).FullName}.{nameof(Int4.One)}"] = "int4(1, 1, 1, 1)", - [$"{typeof(Int4).FullName}.{nameof(Int4.UnitX)}"] = "int4(1, 0, 0, 0)", - [$"{typeof(Int4).FullName}.{nameof(Int4.UnitY)}"] = "int4(0, 1, 0, 0)", - [$"{typeof(Int4).FullName}.{nameof(Int4.UnitZ)}"] = "int4(0, 0, 1, 0)", - [$"{typeof(Int4).FullName}.{nameof(Int4.UnitW)}"] = "int4(0, 0, 0, 1)", - - [$"{typeof(UInt2).FullName}.{nameof(UInt2.Zero)}"] = "(uint2)0", - [$"{typeof(UInt2).FullName}.{nameof(UInt2.One)}"] = "uint2(1u, 1u)", - [$"{typeof(UInt2).FullName}.{nameof(UInt2.UnitX)}"] = "uint2(1u, 0u)", - [$"{typeof(UInt2).FullName}.{nameof(UInt2.UnitY)}"] = "uint2(0u, 1u)", - - [$"{typeof(UInt3).FullName}.{nameof(UInt3.Zero)}"] = "(uint3)0", - [$"{typeof(UInt3).FullName}.{nameof(UInt3.One)}"] = "uint3(1u, 1u, 1u)", - [$"{typeof(UInt3).FullName}.{nameof(UInt3.UnitX)}"] = "uint3(1u, 0u, 0u)", - [$"{typeof(UInt3).FullName}.{nameof(UInt3.UnitY)}"] = "uint3(0u, 1u, 0u)", - [$"{typeof(UInt3).FullName}.{nameof(UInt3.UnitZ)}"] = "uint3(0u, 0u, 1u)", - - [$"{typeof(UInt4).FullName}.{nameof(UInt4.Zero)}"] = "(uint4)0", - [$"{typeof(UInt4).FullName}.{nameof(UInt4.One)}"] = "uint4(1u, 1u, 1u, 1u)", - [$"{typeof(UInt4).FullName}.{nameof(UInt4.UnitX)}"] = "uint4(1u, 0u, 0u, 0u)", - [$"{typeof(UInt4).FullName}.{nameof(UInt4.UnitY)}"] = "uint4(0u, 1u, 0u, 0u)", - [$"{typeof(UInt4).FullName}.{nameof(UInt4.UnitZ)}"] = "uint4(0u, 0u, 1u, 0u)", - [$"{typeof(UInt4).FullName}.{nameof(UInt4.UnitW)}"] = "uint4(0u, 0u, 0u, 1u)", - - [$"{typeof(Float2).FullName}.{nameof(Float2.Zero)}"] = "(float2)0", - [$"{typeof(Float2).FullName}.{nameof(Float2.One)}"] = "float2(1.0f, 1.0f)", - [$"{typeof(Float2).FullName}.{nameof(Float2.UnitX)}"] = "float2(1.0f, 0.0f)", - [$"{typeof(Float2).FullName}.{nameof(Float2.UnitY)}"] = "float2(0.0f, 1.0f)", - - [$"{typeof(Float3).FullName}.{nameof(Float3.Zero)}"] = "(float3)0", - [$"{typeof(Float3).FullName}.{nameof(Float3.One)}"] = "float3(1.0f, 1.0f, 1.0f)", - [$"{typeof(Float3).FullName}.{nameof(Float3.UnitX)}"] = "float3(1.0f, 0.0f, 0.0f)", - [$"{typeof(Float3).FullName}.{nameof(Float3.UnitY)}"] = "float3(0.0f, 1.0f, 0.0f)", - [$"{typeof(Float3).FullName}.{nameof(Float3.UnitZ)}"] = "float3(0.0f, 0.0f, 1.0f)", - - [$"{typeof(Float4).FullName}.{nameof(Float4.Zero)}"] = "(float4)0", - [$"{typeof(Float4).FullName}.{nameof(Float4.One)}"] = "float4(1.0f, 1.0f, 1.0f, 1.0f)", - [$"{typeof(Float4).FullName}.{nameof(Float4.UnitX)}"] = "float4(1.0f, 0.0f, 0.0f, 0.0f)", - [$"{typeof(Float4).FullName}.{nameof(Float4.UnitY)}"] = "float4(0.0f, 1.0f, 0.0f, 0.0f)", - [$"{typeof(Float4).FullName}.{nameof(Float4.UnitZ)}"] = "float4(0.0f, 0.0f, 1.0f, 0.0f)", - [$"{typeof(Float4).FullName}.{nameof(Float4.UnitW)}"] = "float4(0.0f, 0.0f, 0.0f, 1.0f)", - - [$"{typeof(Double2).FullName}.{nameof(Double2.Zero)}"] = "(double2)0", - [$"{typeof(Double2).FullName}.{nameof(Double2.One)}"] = "double2(1.0, 1.0)", - [$"{typeof(Double2).FullName}.{nameof(Double2.UnitX)}"] = "double2(1.0, 0.0)", - [$"{typeof(Double2).FullName}.{nameof(Double2.UnitY)}"] = "double2(0.0, 1.0)", - - [$"{typeof(Double3).FullName}.{nameof(Double3.Zero)}"] = "(double3)0", - [$"{typeof(Double3).FullName}.{nameof(Double3.One)}"] = "double3(1.0, 1.0, 1.0)", - [$"{typeof(Double3).FullName}.{nameof(Double3.UnitX)}"] = "double3(1.0, 0.0, 0.0)", - [$"{typeof(Double3).FullName}.{nameof(Double3.UnitY)}"] = "double3(0.0, 1.0, 0.0)", - [$"{typeof(Double3).FullName}.{nameof(Double3.UnitZ)}"] = "double3(0.0, 0.0, 1.0)", - - [$"{typeof(Double4).FullName}.{nameof(Double4.Zero)}"] = "(double4)0", - [$"{typeof(Double4).FullName}.{nameof(Double4.One)}"] = "double4(1.0, 1.0, 1.0, 1.0)", - [$"{typeof(Double4).FullName}.{nameof(Double4.UnitX)}"] = "double4(1.0, 0.0, 0.0, 0.0)", - [$"{typeof(Double4).FullName}.{nameof(Double4.UnitY)}"] = "double4(0.0, 1.0, 0.0, 0.0)", - [$"{typeof(Double4).FullName}.{nameof(Double4.UnitZ)}"] = "double4(0.0, 0.0, 1.0, 0.0)", - [$"{typeof(Double4).FullName}.{nameof(Double4.UnitW)}"] = "double4(0.0, 0.0, 0.0, 1.0)" - }; - - // Programmatically load mappings for the instance members of the HLSL vector types - foreach (var item in - from type in HlslKnownTypes.KnownVectorTypes - from property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public) - select (Type: type, Property: property)) - { - knownMembers.Add($"{item.Type.FullName}{Type.Delimiter}{item.Property.Name}", $"{item.Property.Name.ToLower()}"); - } - - // Load mappings for the matrix properties as well - foreach (var item in - from type in HlslKnownTypes.KnownMatrixTypes - from property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public) - where Regex.IsMatch(property.Name, "^M[1-4]{2}$") - select (Type: type, Property: property)) - { - char row = (char)(item.Property.Name[1] - 1); - char column = (char)(item.Property.Name[2] - 1); - - knownMembers.Add($"{item.Type.FullName}{Type.Delimiter}{item.Property.Name}", $"_m{row}{column}"); - } - - // Store GroupIds.Index for a quicker comparison afterwards - PropertyInfo groupindexProperty = typeof(GroupIds).GetProperty(nameof(GroupIds.Index), BindingFlags.Static | BindingFlags.Public); - - // Programmatically load mappings for the dispatch types - foreach (var item in - from type in HlslKnownTypes.HlslDispatchTypes - from property in type.GetProperties(BindingFlags.Static | BindingFlags.Public) - select (Type: type, Property: property)) - { - if (item.Property == groupindexProperty) - { - // The thread group index is a standalone parameter, so if this property is used, we - // just map the access directly to that implicit and hidden parameter name instead. - knownMembers.Add($"{item.Type.FullName}{Type.Delimiter}{item.Property.Name}", $"__{nameof(GroupIds)}__get_Index"); - } - else - { - knownMembers.Add($"{item.Type.FullName}{Type.Delimiter}{item.Property.Name}", $"{item.Type.Name}.{item.Property.Name.ToLower()}"); - } - } - - // Programmatically load mappings for the normalized thread ids - foreach (var property in typeof(ThreadIds.Normalized).GetProperties(BindingFlags.Static | BindingFlags.Public)) - { - string key = $"{typeof(ThreadIds).FullName}{Type.Delimiter}{typeof(ThreadIds.Normalized).Name}{Type.Delimiter}{property.Name}"; - - switch (property.Name) - { - case string name when name.Length == 1: - knownMembers.Add(key, $"{typeof(ThreadIds).Name}.{char.ToLower(name[0])} / (float)__{char.ToLower(name[0])}"); - break; - case string name when name.Length == 2: - { - string numerator = $"float2({typeof(ThreadIds).Name}.{char.ToLower(name[0])}, {typeof(ThreadIds).Name}.{char.ToLower(name[1])})"; - string denominator = $"float2(__{char.ToLower(name[0])}, __{char.ToLower(name[1])})"; - - knownMembers.Add(key, $"{numerator} / {denominator}"); - break; - } - case string name when name.Length == 3: - { - string numerator = $"float3({typeof(ThreadIds).Name}.{char.ToLower(name[0])}, {typeof(ThreadIds).Name}.{char.ToLower(name[1])}, {typeof(ThreadIds).Name}.{char.ToLower(name[2])})"; - string denominator = $"float3(__{char.ToLower(name[0])}, __{char.ToLower(name[1])}, __{char.ToLower(name[2])})"; - - knownMembers.Add(key, $"{numerator} / {denominator}"); - break; - } - } - } - - // Programmatically load mappings for the group size - foreach (var property in typeof(GroupSize).GetProperties(BindingFlags.Static | BindingFlags.Public)) - { - string key = $"{typeof(GroupSize).FullName}{Type.Delimiter}{property.Name}"; - - switch (property.Name) - { - case nameof(GroupSize.Count): - knownMembers.Add(key, "__GroupSize__get_X * __GroupSize__get_Y * __GroupSize__get_Z"); - break; - case string name when name.Length == 1: - knownMembers.Add(key, $"__GroupSize__get_{name}"); - break; - case string name when name.Length == 2: - knownMembers.Add(key, $"int2(__GroupSize__get_{name[0]}, __GroupSize__get_{name[1]})"); - break; - case string name when name.Length == 3: - knownMembers.Add(key, $"int3(__GroupSize__get_{name[0]}, __GroupSize__get_{name[1]}, __GroupSize__get_{name[2]})"); - break; - } - } - - // Programmatically load mappings for the dispatch size - foreach (var property in typeof(DispatchSize).GetProperties(BindingFlags.Static | BindingFlags.Public)) - { - string key = $"{typeof(DispatchSize).FullName}{Type.Delimiter}{property.Name}"; - - switch (property.Name) - { - case nameof(DispatchSize.Count): - knownMembers.Add(key, "__x * __y * __z"); - break; - case string name when name.Length == 1: - knownMembers.Add(key, $"__{char.ToLower(name[0])}"); - break; - case string name when name.Length == 2: - knownMembers.Add(key, $"int2(__{char.ToLower(name[0])}, __{char.ToLower(name[1])})"); - break; - case string name when name.Length == 3: - knownMembers.Add(key, $"int3(__{char.ToLower(name[0])}, __{char.ToLower(name[1])}, __{char.ToLower(name[2])})"); - break; - } - } - - return knownMembers; - } - - /// - /// The mapping of supported known members to HLSL names. - /// - private static readonly IReadOnlyCollection KnownMatrixIndexers = BuildKnownMatrixIndexers(); - - /// - /// Builds the mapping of swizzled matrix indexer properties. - /// - private static IReadOnlyCollection BuildKnownMatrixIndexers() - { - return ( - from type in Assembly.GetExecutingAssembly().ExportedTypes - where Regex.IsMatch(type.FullName, @"ComputeSharp\.(Bool|Double|Float|Int|UInt)[1-4]x[1-4]") - from property in type.GetProperties() - let indices = property.GetIndexParameters() - where indices.Length > 0 && - indices.All(static index => index.ParameterType == typeof(MatrixIndex)) - let metadataName = $"{type.FullName}.this[{string.Join(", ", indices.Select(index => index.ParameterType))}]" - select metadataName).ToImmutableHashSet(); - } - - /// - /// The mapping of supported known members to HLSL names. - /// - private static readonly IReadOnlyCollection KnownMatrixIndices = BuildKnownMatrixIndices(); - - /// - /// Builds the mapping of swizzled matrix indices. - /// - private static IReadOnlyCollection BuildKnownMatrixIndices() - { - return ( - from name in Enum.GetNames(typeof(MatrixIndex)) - select $"{typeof(MatrixIndex).FullName}.{name}").ToImmutableHashSet(); - } - - /// - /// Checks whether or not a given property fullname matches a matrix swizzled indexer. - /// - /// The input fully qualified member name. - /// Whether or not is a matrix swizzled indexer. - public static bool IsKnownMatrixIndexer(string name) - { - return KnownMatrixIndexers.Contains(name); - } - - /// - /// Checks whether or not a given property fullname matches a matrix swizzled index. - /// - /// The input fully qualified member name. - /// Whether or not is a matrix swizzled index. - public static bool IsKnownMatrixIndex(string name) - { - return KnownMatrixIndices.Contains(name); - } - - /// - /// Tries to get the mapped HLSL-compatible member name for the input member name. - /// - /// The input fully qualified member name. - /// The mapped name, if one is found. - /// The HLSL-compatible member name that can be used in an HLSL shader. - public static bool TryGetMappedName(string name, out string? mapped) - { - return KnownMembers.TryGetValue(name, out mapped); - } - - /// - /// Tries to get the mapped HLSL-compatible indexer resource type name for the input indexer name. - /// - /// The input fully qualified indexer name. - /// The mapped type name, if one is found. - /// The HLSL-compatible type name that can be used in an HLSL shader for the given indexer. - public static bool TryGetMappedResourceIndexerTypeName(string name, out string? mapped) - { - return KnownResourceIndexers.TryGetValue(name, out mapped); - } - - /// - /// Tries to get the mapped HLSL-compatible sampler resource type name for the input indexer name. - /// - /// The input fully qualified indexer name. - /// The mapped type name, if one is found. - /// The HLSL-compatible type name that can be used in an HLSL shader for the given sampler. - public static bool TryGetMappedResourceSamplerAccessType(string name, out string? mapped) - { - return KnownResourceSamplers.TryGetValue(name, out mapped); - } - - /// - /// Tries to get the mapped rank and axis for a given indexer name. - /// - /// The input fully qualified indexer name. - /// The resulting indexer rank, if found. - /// The resulting indexer axis, if found. - /// Whether or not a rank and axis could be resolved by the input indexer name. - public static bool TryGetAccessorRankAndAxis(string name, out int rank, out int axis) - { - if (KnownSizeAccessors.TryGetValue(name, out var info)) - { - (rank, axis) = info; - - return true; - } - - (rank, axis) = default((int, int)); - - return false; - } -} diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownProperties.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownProperties.cs new file mode 100644 index 00000000..c4d8c0af --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownProperties.cs @@ -0,0 +1,221 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; + +namespace ComputeSharp.SourceGeneration.Mappings; + +/// +partial class HlslKnownProperties +{ + /// + /// The mapping of supported known indexers to HLSL resource type names. + /// + private static readonly IReadOnlyDictionary KnownResourceIndexers = new Dictionary + { + [$"ComputeSharp.ReadOnlyTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", + [$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", + [$"ComputeSharp.ReadWriteTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", + [$"ComputeSharp.ReadWriteTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", + [$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", + [$"ComputeSharp.IReadWriteTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", + [$"ComputeSharp.IReadOnlyNormalizedTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", + [$"ComputeSharp.IReadWriteNormalizedTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", + [$"ComputeSharp.ReadOnlyTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", + [$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", + [$"ComputeSharp.ReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", + [$"ComputeSharp.ReadWriteTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", + [$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", + [$"ComputeSharp.IReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", + [$"ComputeSharp.IReadOnlyNormalizedTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", + [$"ComputeSharp.IReadWriteNormalizedTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3" + }; + + /// + /// The mapping of supported known samplers to HLSL resource type names. + /// + private static readonly IReadOnlyDictionary KnownResourceSamplers = new Dictionary + { + [$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2", + [$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(Float2).FullName}]"] = null, + [$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2", + [$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(Float2).FullName}]"] = null, + [$"ComputeSharp.IReadOnlyNormalizedTexture2D`1.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2", + [$"ComputeSharp.IReadOnlyNormalizedTexture2D`1.this[{typeof(Float2).FullName}]"] = null, + [$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3", + [$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(Float3).FullName}]"] = null, + [$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3", + [$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(Float3).FullName}]"] = null, + [$"ComputeSharp.IReadOnlyNormalizedTexture3D`1.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3", + [$"ComputeSharp.IReadOnlyNormalizedTexture3D`1.this[{typeof(Float3).FullName}]"] = null + }; + + /// + /// The mapping of supported known size accessors for HLSL resource types. + /// + private static readonly IReadOnlyDictionary KnownSizeAccessors = new Dictionary + { + ["ComputeSharp.Resources.Buffer`1.Length"] = (2, 0), + ["ComputeSharp.Resources.Texture2D`1.Width"] = (2, 0), + ["ComputeSharp.Resources.Texture2D`1.Height"] = (2, 1), + ["ComputeSharp.Resources.Texture3D`1.Width"] = (3, 0), + ["ComputeSharp.Resources.Texture3D`1.Height"] = (3, 1), + ["ComputeSharp.Resources.Texture3D`1.Depth"] = (3, 2), + ["ComputeSharp.IReadOnlyTexture2D`1.Width"] = (2, 0), + ["ComputeSharp.IReadOnlyTexture2D`1.Height"] = (2, 1), + ["ComputeSharp.IReadOnlyTexture3D`1.Width"] = (3, 0), + ["ComputeSharp.IReadOnlyTexture3D`1.Height"] = (3, 1), + ["ComputeSharp.IReadOnlyTexture3D`1.Depth"] = (3, 2), + ["ComputeSharp.IReadOnlyNormalizedTexture2D`1.Width"] = (2, 0), + ["ComputeSharp.IReadOnlyNormalizedTexture2D`1.Height"] = (2, 1), + ["ComputeSharp.IReadOnlyNormalizedTexture3D`1.Width"] = (3, 0), + ["ComputeSharp.IReadOnlyNormalizedTexture3D`1.Height"] = (3, 1), + ["ComputeSharp.IReadOnlyNormalizedTexture3D`1.Depth"] = (3, 2), + ["ComputeSharp.IReadWriteNormalizedTexture2D`1.Width"] = (2, 0), + ["ComputeSharp.IReadWriteNormalizedTexture2D`1.Height"] = (2, 1), + ["ComputeSharp.IReadWriteNormalizedTexture3D`1.Width"] = (3, 0), + ["ComputeSharp.IReadWriteNormalizedTexture3D`1.Height"] = (3, 1), + ["ComputeSharp.IReadWriteNormalizedTexture3D`1.Depth"] = (3, 2) + }; + + /// + static partial void AddKnownProperties(IDictionary knownProperties) + { + // Store GroupIds.Index for a quicker comparison afterwards + PropertyInfo groupindexProperty = typeof(GroupIds).GetProperty(nameof(GroupIds.Index), BindingFlags.Static | BindingFlags.Public); + + // Programmatically load mappings for the dispatch types + foreach (var item in + from type in HlslKnownTypes.HlslDispatchTypes + from property in type.GetProperties(BindingFlags.Static | BindingFlags.Public) + select (Type: type, Property: property)) + { + if (item.Property == groupindexProperty) + { + // The thread group index is a standalone parameter, so if this property is used, we + // just map the access directly to that implicit and hidden parameter name instead. + knownProperties.Add($"{item.Type.FullName}{Type.Delimiter}{item.Property.Name}", $"__{nameof(GroupIds)}__get_Index"); + } + else + { + knownProperties.Add($"{item.Type.FullName}{Type.Delimiter}{item.Property.Name}", $"{item.Type.Name}.{item.Property.Name.ToLower()}"); + } + } + + // Programmatically load mappings for the normalized thread ids + foreach (var property in typeof(ThreadIds.Normalized).GetProperties(BindingFlags.Static | BindingFlags.Public)) + { + string key = $"{typeof(ThreadIds).FullName}{Type.Delimiter}{typeof(ThreadIds.Normalized).Name}{Type.Delimiter}{property.Name}"; + + switch (property.Name) + { + case string name when name.Length == 1: + knownProperties.Add(key, $"{typeof(ThreadIds).Name}.{char.ToLower(name[0])} / (float)__{char.ToLower(name[0])}"); + break; + case string name when name.Length == 2: + { + string numerator = $"float2({typeof(ThreadIds).Name}.{char.ToLower(name[0])}, {typeof(ThreadIds).Name}.{char.ToLower(name[1])})"; + string denominator = $"float2(__{char.ToLower(name[0])}, __{char.ToLower(name[1])})"; + + knownProperties.Add(key, $"{numerator} / {denominator}"); + break; + } + case string name when name.Length == 3: + { + string numerator = $"float3({typeof(ThreadIds).Name}.{char.ToLower(name[0])}, {typeof(ThreadIds).Name}.{char.ToLower(name[1])}, {typeof(ThreadIds).Name}.{char.ToLower(name[2])})"; + string denominator = $"float3(__{char.ToLower(name[0])}, __{char.ToLower(name[1])}, __{char.ToLower(name[2])})"; + + knownProperties.Add(key, $"{numerator} / {denominator}"); + break; + } + } + } + + // Programmatically load mappings for the group size + foreach (var property in typeof(GroupSize).GetProperties(BindingFlags.Static | BindingFlags.Public)) + { + string key = $"{typeof(GroupSize).FullName}{Type.Delimiter}{property.Name}"; + + switch (property.Name) + { + case nameof(GroupSize.Count): + knownProperties.Add(key, "__GroupSize__get_X * __GroupSize__get_Y * __GroupSize__get_Z"); + break; + case string name when name.Length == 1: + knownProperties.Add(key, $"__GroupSize__get_{name}"); + break; + case string name when name.Length == 2: + knownProperties.Add(key, $"int2(__GroupSize__get_{name[0]}, __GroupSize__get_{name[1]})"); + break; + case string name when name.Length == 3: + knownProperties.Add(key, $"int3(__GroupSize__get_{name[0]}, __GroupSize__get_{name[1]}, __GroupSize__get_{name[2]})"); + break; + } + } + + // Programmatically load mappings for the dispatch size + foreach (var property in typeof(DispatchSize).GetProperties(BindingFlags.Static | BindingFlags.Public)) + { + string key = $"{typeof(DispatchSize).FullName}{Type.Delimiter}{property.Name}"; + + switch (property.Name) + { + case nameof(DispatchSize.Count): + knownProperties.Add(key, "__x * __y * __z"); + break; + case string name when name.Length == 1: + knownProperties.Add(key, $"__{char.ToLower(name[0])}"); + break; + case string name when name.Length == 2: + knownProperties.Add(key, $"int2(__{char.ToLower(name[0])}, __{char.ToLower(name[1])})"); + break; + case string name when name.Length == 3: + knownProperties.Add(key, $"int3(__{char.ToLower(name[0])}, __{char.ToLower(name[1])}, __{char.ToLower(name[2])})"); + break; + } + } + } + + /// + /// Tries to get the mapped HLSL-compatible indexer resource type name for the input indexer name. + /// + /// The input fully qualified indexer name. + /// The mapped type name, if one is found. + /// The HLSL-compatible type name that can be used in an HLSL shader for the given indexer. + public static bool TryGetMappedResourceIndexerTypeName(string name, out string? mapped) + { + return KnownResourceIndexers.TryGetValue(name, out mapped); + } + + /// + /// Tries to get the mapped HLSL-compatible sampler resource type name for the input indexer name. + /// + /// The input fully qualified indexer name. + /// The mapped type name, if one is found. + /// The HLSL-compatible type name that can be used in an HLSL shader for the given sampler. + public static bool TryGetMappedResourceSamplerAccessType(string name, out string? mapped) + { + return KnownResourceSamplers.TryGetValue(name, out mapped); + } + + /// + /// Tries to get the mapped rank and axis for a given indexer name. + /// + /// The input fully qualified indexer name. + /// The resulting indexer rank, if found. + /// The resulting indexer axis, if found. + /// Whether or not a rank and axis could be resolved by the input indexer name. + public static bool TryGetAccessorRankAndAxis(string name, out int rank, out int axis) + { + if (KnownSizeAccessors.TryGetValue(name, out var info)) + { + (rank, axis) = info; + + return true; + } + + (rank, axis) = default((int, int)); + + return false; + } +} diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index 2625d3f7..109e1b16 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -1,19 +1,13 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Numerics; -using System.Text.RegularExpressions; -using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGeneration.Extensions; using Microsoft.CodeAnalysis; -#pragma warning disable RS1024 +namespace ComputeSharp.SourceGeneration.Mappings; -namespace ComputeSharp.SourceGenerators.Mappings; - -/// -/// A that contains and maps known HLSL type names to common .NET types. -/// -internal static class HlslKnownTypes +/// +partial class HlslKnownTypes { /// /// Gets the known HLSL dispatch types. @@ -25,82 +19,6 @@ internal static class HlslKnownTypes typeof(GridIds) }; - /// - /// Gets the set of HLSL vector types. - /// - public static IReadOnlyCollection KnownVectorTypes { get; } = new[] - { - typeof(Bool2), typeof(Bool3), typeof(Bool4), - typeof(Int2), typeof(Int3), typeof(Int4), - typeof(UInt2), typeof(UInt3), typeof(UInt4), - typeof(Float2), typeof(Float3), typeof(Float4), - typeof(Double2), typeof(Double3), typeof(Double4) - }; - - /// - /// Gets the set of HLSL matrix types. - /// - public static IReadOnlyCollection KnownMatrixTypes { get; } = new[] - { - typeof(Bool1x1), typeof(Bool1x2), typeof(Bool1x3), typeof(Bool1x4), - typeof(Bool2x1), typeof(Bool2x2), typeof(Bool2x3), typeof(Bool2x4), - typeof(Bool3x1), typeof(Bool3x2), typeof(Bool3x3), typeof(Bool3x4), - typeof(Bool4x1), typeof(Bool4x2), typeof(Bool4x3), typeof(Bool4x4), - typeof(Int1x1), typeof(Int1x2), typeof(Int1x3), typeof(Int1x4), - typeof(Int2x1), typeof(Int2x2), typeof(Int2x3), typeof(Int2x4), - typeof(Int3x1), typeof(Int3x2), typeof(Int3x3), typeof(Int3x4), - typeof(Int4x1), typeof(Int4x2), typeof(Int4x3), typeof(Int4x4), - typeof(UInt1x1), typeof(UInt1x2), typeof(UInt1x3), typeof(UInt1x4), - typeof(UInt2x1), typeof(UInt2x2), typeof(UInt2x3), typeof(UInt2x4), - typeof(UInt3x1), typeof(UInt3x2), typeof(UInt3x3), typeof(UInt3x4), - typeof(UInt4x1), typeof(UInt4x2), typeof(UInt4x3), typeof(UInt4x4), - typeof(Float1x1), typeof(Float1x2), typeof(Float1x3), typeof(Float1x4), - typeof(Float2x1), typeof(Float2x2), typeof(Float2x3), typeof(Float2x4), - typeof(Float3x1), typeof(Float3x2), typeof(Float3x3), typeof(Float3x4), - typeof(Float4x1), typeof(Float4x2), typeof(Float4x3), typeof(Float4x4), - typeof(Double1x1), typeof(Double1x2), typeof(Double1x3), typeof(Double1x4), - typeof(Double2x1), typeof(Double2x2), typeof(Double2x3), typeof(Double2x4), - typeof(Double3x1), typeof(Double3x2), typeof(Double3x3), typeof(Double3x4), - typeof(Double4x1), typeof(Double4x2), typeof(Double4x3), typeof(Double4x4) - }; - - /// - /// The mapping of supported known types to HLSL types. - /// - private static readonly IReadOnlyDictionary KnownHlslTypes = BuildKnownHlslTypes(); - - /// - /// Builds the mapping of known primitive types. - /// - private static IReadOnlyDictionary BuildKnownHlslTypes() - { - Dictionary knownTypes = new() - { - [typeof(bool).FullName] = "bool", - [typeof(int).FullName] = "int", - [typeof(uint).FullName] = "uint", - [typeof(float).FullName] = "float", - [typeof(Vector2).FullName] = "float2", - [typeof(Vector3).FullName] = "float3", - [typeof(Vector4).FullName] = "float4", - [typeof(double).FullName] = "double" - }; - - // Add all the vector types - foreach (var type in KnownVectorTypes) - { - knownTypes.Add(type.FullName, type.Name.ToLower()); - } - - // Add all the matrix types - foreach (var type in KnownMatrixTypes) - { - knownTypes.Add(type.FullName, type.Name.ToLower()); - } - - return knownTypes; - } - /// /// Checks whether or not a given type name matches a constant buffer type. /// @@ -199,73 +117,8 @@ internal static class HlslKnownTypes }; } - /// - /// Checks whether or not a given type name matches a known HLSL primitive type (scalar, vector or matrix). - /// - /// The input type name to check. - /// Whether or not represents a scalar, vector or matrix type. - public static bool IsKnownHlslType(string typeName) - { - return KnownHlslTypes.ContainsKey(typeName); - } - - /// - /// Checks whether or not a given type name matches a vector type. - /// - /// The input type name to check. - /// Whether or not represents a vector type. - public static bool IsVectorType(string typeName) - { - return KnownVectorTypes.Any(type => type.FullName == typeName); - } - - /// - /// Checks whether or not a given type name matches a matrix type. - /// - /// The input type name to check. - /// Whether or not represents a matrix type. - public static bool IsMatrixType(string typeName) - { - return KnownMatrixTypes.Any(type => type.FullName == typeName); - } - - /// - /// Checks whether or not a given type name is a non linear matrix type. - /// That is, a matrix type with more than a single row (which affects the constant buffer alignment). - /// - /// The input type name to check. - /// The element name of the matrix type. - /// The number of rows in the matrix type. - /// The number of columns in the matrix type. - /// Whether or not represents a non linear matrix type. - public static bool IsNonLinearMatrixType(string typeName, out string? elementName, out int rows, out int columns) - { - if (KnownMatrixTypes.Any(type => type.FullName == typeName)) - { - var match = Regex.Match(typeName, @"^ComputeSharp\.(Bool|Int|UInt|Float|Double)([2-4])x([1-4])$"); - - if (match.Success) - { - elementName = match.Groups[1].Value; - rows = int.Parse(match.Groups[2].Value); - columns = int.Parse(match.Groups[3].Value); - - return true; - } - } - - elementName = null; - rows = columns = 0; - - return false; - } - - /// - /// Gets the mapped HLSL-compatible type name for the input type symbol. - /// - /// The input type to map. - /// The HLSL-compatible type name that can be used in an HLSL shader. - public static string GetMappedName(INamedTypeSymbol typeSymbol) + /// + public static partial string GetMappedName(INamedTypeSymbol typeSymbol) { // Delegate types just return an empty string, as they're not actually // used in the generated shaders, but just mapped to a function at runtime. @@ -336,120 +189,4 @@ internal static class HlslKnownTypes // Construct the HLSL type name return $"RWTexture2D"; } - - /// - /// Gets the mapped HLSL-compatible type name for the input element type symbol. - /// - /// The input type to map. - /// The HLSL-compatible type name that can be used in an HLSL shader. - public static string GetMappedElementName(IArrayTypeSymbol typeSymbol) - { - string elementTypeName = ((INamedTypeSymbol)typeSymbol.ElementType).GetFullMetadataName(); - - if (KnownHlslTypes.TryGetValue(elementTypeName, out string? mapped)) - { - return mapped; - } - - return elementTypeName.ToHlslIdentifierName(); - } - - /// - /// Gets the mapped HLSL-compatible type name for the input type name. - /// - /// The input type name to map. - /// The resulting mapped type name, if found. - /// The HLSL-compatible type name that can be used in an HLSL shader. - public static bool TryGetMappedName(string originalName, out string? mappedName) - { - return KnownHlslTypes.TryGetValue(originalName, out mappedName); - } - - /// - /// Gets the sequence of unique custom types from a collection of discovered types. - /// - /// The input collection of discovered types. - /// The list of unique custom types. - public static IEnumerable GetCustomTypes(IEnumerable discoveredTypes) - { - // Local function to recursively gather nested types - static void ExploreTypes(INamedTypeSymbol type, HashSet customTypes) - { - if (KnownHlslTypes.ContainsKey(type.GetFullMetadataName())) return; - - if (!customTypes.Add(type)) return; - - foreach (var field in type.GetMembers().OfType()) - { - if (field.IsStatic) continue; - - ExploreTypes((INamedTypeSymbol)field.Type, customTypes); - } - } - - HashSet customTypes = new(SymbolEqualityComparer.Default); - - // Explore all input types and their nested types - foreach (INamedTypeSymbol type in discoveredTypes) - { - ExploreTypes(type, customTypes); - } - - return OrderByDependency(customTypes); - } - - /// - /// Orders the input sequence of types so that they can be declared in HLSL successfully. - /// - /// The input collection of types to declare. - /// The same list as input, but in a valid HLSL declaration order. - private static IEnumerable OrderByDependency(IEnumerable types) - { - Queue<(INamedTypeSymbol Type, HashSet Fields)> queue = new(); - - // Build a mapping of type dependencies for all the captured types. A type depends on another - // when the latter is a field in the first type. HLSL requires custom types to be declared in - // order of usage, so we need to ensure that types are declared in an order that guarantees - // that no type will be referenced before being defined. To do so, we can create a mapping of - // types and their dependencies, and iteratively remove items from the map when they have no - // dependencies left. When one type is processed and removed, it is also removed from the list - // of dependencies of all other remaining types in the map, until there is none left. - foreach (var type in types) - { - HashSet dependencies = new(SymbolEqualityComparer.Default); - - // Only add other custom types as dependencies, and ignore HLSL types - foreach (var field in type.GetMembers().OfType()) - { - if (field.IsStatic) continue; - - INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type; - - if (!KnownHlslTypes.ContainsKey(fieldType.GetFullMetadataName())) - { - _ = dependencies.Add(fieldType); - } - } - - queue.Enqueue((type, dependencies)); - } - - while (queue.Count > 0) - { - var entry = queue.Dequeue(); - - // No dependencies left, we can declare this type - if (entry.Fields.Count == 0) - { - // Remove the current type from dependencies of others - foreach (var pair in queue) - { - _ = pair.Fields.Remove(entry.Type); - } - - yield return entry.Type; - } - else queue.Enqueue(entry); - } - } } diff --git a/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs b/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs index b1462dad..a87e21f0 100644 --- a/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; -using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Models; namespace ComputeSharp.SourceGenerators.Models; @@ -23,31 +25,21 @@ internal sealed record DispatchDataInfo( /// /// An implementation for . /// - public sealed class Comparer : IEqualityComparer + public sealed class Comparer : Comparer { - /// - /// The singleton instance. - /// - public static Comparer Default { get; } = new(); + /// + protected override void AddToHashCode(ref HashCode hashCode, DispatchDataInfo obj) + { + hashCode.Add(HierarchyInfo.Comparer.Default.GetHashCode(obj.Hierarchy)); + hashCode.Add(obj.Type); + hashCode.AddRange(obj.FieldInfos, FieldInfo.Comparer.Default); + hashCode.Add(obj.ResourceCount); + hashCode.Add(obj.Root32BitConstantCount); + } /// - public bool Equals(DispatchDataInfo? x, DispatchDataInfo? y) + protected override bool AreEqual(DispatchDataInfo x, DispatchDataInfo y) { - if (x is null && y is null) - { - return true; - } - - if (x is null || y is null) - { - return false; - } - - if (ReferenceEquals(x, y)) - { - return true; - } - return HierarchyInfo.Comparer.Default.Equals(x.Hierarchy, y.Hierarchy) && x.Type == y.Type && @@ -55,19 +47,5 @@ internal sealed record DispatchDataInfo( x.ResourceCount == y.ResourceCount && x.Root32BitConstantCount == y.Root32BitConstantCount; } - - /// - public int GetHashCode(DispatchDataInfo obj) - { - HashCode hashCode = default; - - hashCode.Add(HierarchyInfo.Comparer.Default.GetHashCode(obj.Hierarchy)); - hashCode.Add(obj.Type); - hashCode.AddRange(obj.FieldInfos, FieldInfo.Comparer.Default); - hashCode.Add(obj.ResourceCount); - hashCode.Add(obj.Root32BitConstantCount); - - return hashCode.ToHashCode(); - } } } diff --git a/src/ComputeSharp.SourceGenerators/Models/DispatchIdInfo.cs b/src/ComputeSharp.SourceGenerators/Models/DispatchIdInfo.cs index 373eb800..348ef0c7 100644 --- a/src/ComputeSharp.SourceGenerators/Models/DispatchIdInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/DispatchIdInfo.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; -using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.SourceGenerators.Models; @@ -14,42 +15,18 @@ internal sealed record DispatchIdInfo(ImmutableArray Delegates) /// /// An implementation for . /// - public sealed class Comparer : IEqualityComparer + public sealed class Comparer : Comparer { - /// - /// The singleton instance. - /// - public static Comparer Default { get; } = new(); - /// - public bool Equals(DispatchIdInfo? x, DispatchIdInfo? y) + protected override void AddToHashCode(ref HashCode hashCode, DispatchIdInfo obj) { - if (x is null && y is null) - { - return true; - } - - if (x is null || y is null) - { - return false; - } - - if (ReferenceEquals(x, y)) - { - return true; - } - - return x.Delegates.SequenceEqual(y.Delegates); + hashCode.AddRange(obj.Delegates); } /// - public int GetHashCode(DispatchIdInfo obj) + protected override bool AreEqual(DispatchIdInfo x, DispatchIdInfo y) { - HashCode hashCode = default; - - hashCode.AddRange(obj.Delegates); - - return hashCode.ToHashCode(); + return x.Delegates.SequenceEqual(y.Delegates); } } } diff --git a/src/ComputeSharp.SourceGenerators/Models/DispatchMetadataInfo.cs b/src/ComputeSharp.SourceGenerators/Models/DispatchMetadataInfo.cs index cbf3bc4f..f49ccb64 100644 --- a/src/ComputeSharp.SourceGenerators/Models/DispatchMetadataInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/DispatchMetadataInfo.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; -using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.SourceGenerators.Models; @@ -19,47 +20,23 @@ internal sealed record DispatchMetadataInfo( /// /// An implementation for . /// - public sealed class Comparer : IEqualityComparer + public sealed class Comparer : Comparer { - /// - /// The singleton instance. - /// - public static Comparer Default { get; } = new(); + /// + protected override void AddToHashCode(ref HashCode hashCode, DispatchMetadataInfo obj) + { + hashCode.Add(obj.Root32BitConstantCount); + hashCode.Add(obj.IsSamplerUsed); + hashCode.AddRange(obj.ResourceDescriptors); + } /// - public bool Equals(DispatchMetadataInfo? x, DispatchMetadataInfo? y) + protected override bool AreEqual(DispatchMetadataInfo x, DispatchMetadataInfo y) { - if (x is null && y is null) - { - return true; - } - - if (x is null || y is null) - { - return false; - } - - if (ReferenceEquals(x, y)) - { - return true; - } - return x.Root32BitConstantCount == y.Root32BitConstantCount && x.IsSamplerUsed == y.IsSamplerUsed && - x.ResourceDescriptors.SequenceEqual(y.ResourceDescriptors, ResourceDescriptor.Comparer.Default); - } - - /// - public int GetHashCode(DispatchMetadataInfo obj) - { - HashCode hashCode = default; - - hashCode.Add(obj.Root32BitConstantCount); - hashCode.Add(obj.IsSamplerUsed); - hashCode.AddRange(obj.ResourceDescriptors, ResourceDescriptor.Comparer.Default); - - return hashCode.ToHashCode(); + x.ResourceDescriptors.SequenceEqual(y.ResourceDescriptors); } } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Models/EmbeddedBytecodeInfo.cs b/src/ComputeSharp.SourceGenerators/Models/EmbeddedBytecodeInfo.cs index df208415..df2931af 100644 --- a/src/ComputeSharp.SourceGenerators/Models/EmbeddedBytecodeInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/EmbeddedBytecodeInfo.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; -using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.SourceGenerators.Models; @@ -17,49 +18,25 @@ internal sealed record EmbeddedBytecodeInfo(int X, int Y, int Z, ImmutableArray< /// /// An implementation for . /// - public sealed class Comparer : IEqualityComparer + public sealed class Comparer : Comparer { - /// - /// The singleton instance. - /// - public static Comparer Default { get; } = new(); + /// + protected override void AddToHashCode(ref HashCode hashCode, EmbeddedBytecodeInfo obj) + { + hashCode.Add(obj.X); + hashCode.Add(obj.Y); + hashCode.Add(obj.Z); + hashCode.AddBytes(obj.Bytecode.AsSpan()); + } /// - public bool Equals(EmbeddedBytecodeInfo? x, EmbeddedBytecodeInfo? y) + protected override bool AreEqual(EmbeddedBytecodeInfo x, EmbeddedBytecodeInfo y) { - if (x is null && y is null) - { - return true; - } - - if (x is null || y is null) - { - return false; - } - - if (ReferenceEquals(x, y)) - { - return true; - } - return x.X == y.X && x.Y == y.Y && x.Z == y.Z && x.Bytecode.SequenceEqual(y.Bytecode); } - - /// - public int GetHashCode(EmbeddedBytecodeInfo obj) - { - HashCode hashCode = default; - - hashCode.Add(obj.X); - hashCode.Add(obj.Y); - hashCode.Add(obj.Z); - hashCode.AddBytes(obj.Bytecode.AsSpan()); - - return hashCode.ToHashCode(); - } } } diff --git a/src/ComputeSharp.SourceGenerators/Models/FieldInfo.cs b/src/ComputeSharp.SourceGenerators/Models/FieldInfo.cs index 25f7a5d7..ccfecb7b 100644 --- a/src/ComputeSharp.SourceGenerators/Models/FieldInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/FieldInfo.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; -using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.SourceGenerators.Models; @@ -46,31 +47,39 @@ internal abstract record FieldInfo /// /// An implementation for . /// - public sealed class Comparer : IEqualityComparer + public sealed class Comparer : Comparer { - /// - /// The singleton instance. - /// - public static Comparer Default { get; } = new(); + /// + protected override void AddToHashCode(ref HashCode hashCode, FieldInfo obj) + { + switch (obj) + { + case Resource resource: + hashCode.Add(resource.FieldName); + hashCode.Add(resource.TypeName); + hashCode.Add(resource.Offset); + break; + case Primitive primitive: + hashCode.AddRange(primitive.FieldPath); + hashCode.Add(primitive.TypeName); + hashCode.Add(primitive.Offset); + break; + case NonLinearMatrix matrix: + hashCode.AddRange(matrix.FieldPath); + hashCode.Add(matrix.TypeName); + hashCode.Add(matrix.ElementName); + hashCode.Add(matrix.Rows); + hashCode.Add(matrix.Columns); + hashCode.AddRange(matrix.Offsets); + break; + default: + break; + } + } /// - public bool Equals(FieldInfo? x, FieldInfo? y) + protected override bool AreEqual(FieldInfo x, FieldInfo y) { - if (x is null && y is null) - { - return true; - } - - if (x is null || y is null) - { - return false; - } - - if (ReferenceEquals(x, y)) - { - return true; - } - if (x is Resource resourceX && y is Resource resourceY) { return @@ -98,40 +107,5 @@ internal abstract record FieldInfo return false; } - - /// - public int GetHashCode(FieldInfo obj) - { - switch (obj) - { - case Resource resource: - return HashCode.Combine(resource.FieldName, resource.TypeName, resource.Offset); - case Primitive primitive: - { - HashCode hashCode = default; - - hashCode.AddRange(primitive.FieldPath); - hashCode.Add(primitive.TypeName); - hashCode.Add(primitive.Offset); - - return hashCode.ToHashCode(); - } - case NonLinearMatrix matrix: - { - HashCode hashCode = default; - - hashCode.AddRange(matrix.FieldPath); - hashCode.Add(matrix.TypeName); - hashCode.Add(matrix.ElementName); - hashCode.Add(matrix.Rows); - hashCode.Add(matrix.Columns); - hashCode.AddRange(matrix.Offsets); - - return hashCode.ToHashCode(); - } - default: - return 0; - } - } } } diff --git a/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs deleted file mode 100644 index 571f4516..00000000 --- a/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs +++ /dev/null @@ -1,90 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using ComputeSharp.SourceGenerators.Extensions; -using Microsoft.CodeAnalysis; -using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle; - -namespace ComputeSharp.SourceGenerators.Models; - -/// -/// A model describing the hierarchy info for a specific type. -/// -/// The filename hint for the current type. -/// The metadata name for the current type. -/// Gets the namespace for the current type. -/// Gets the sequence of type definitions containing the current type. -internal sealed record HierarchyInfo(string FilenameHint, string MetadataName, string Namespace, ImmutableArray Names) -{ - /// - /// Creates a new instance from a given . - /// - /// The input instance to gather info for. - /// A instance describing . - public static HierarchyInfo From(INamedTypeSymbol typeSymbol) - { - ImmutableArray.Builder names = ImmutableArray.CreateBuilder(); - - for (INamedTypeSymbol? parent = typeSymbol; - parent is not null; - parent = parent.ContainingType) - { - names.Add(parent.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); - } - - return new( - typeSymbol.GetGeneratedFileName(), - typeSymbol.MetadataName, - typeSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)), - names.ToImmutable()); - } - - /// - /// An implementation for . - /// - public sealed class Comparer : IEqualityComparer - { - /// - /// The singleton instance. - /// - public static Comparer Default { get; } = new(); - - /// - public bool Equals(HierarchyInfo? x, HierarchyInfo? y) - { - if (x is null && y is null) - { - return true; - } - - if (x is null || y is null) - { - return false; - } - - if (ReferenceEquals(x, y)) - { - return true; - } - - return - x.FilenameHint == y.FilenameHint && - x.MetadataName == y.MetadataName && - x.Namespace == y.Namespace && - x.Names.SequenceEqual(y.Names); - } - - /// - public int GetHashCode(HierarchyInfo obj) - { - HashCode hashCode = default; - - hashCode.Add(obj.FilenameHint); - hashCode.Add(obj.MetadataName); - hashCode.Add(obj.Namespace); - hashCode.AddRange(obj.Names); - - return hashCode.ToHashCode(); - } - } -} diff --git a/src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs index 40788938..f2d18357 100644 --- a/src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; -using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.SourceGenerators.Models; @@ -23,31 +24,21 @@ internal sealed record HlslMethodSourceInfo( /// /// An implementation for . /// - public sealed class Comparer : IEqualityComparer + public sealed class Comparer : Comparer { - /// - /// The singleton instance. - /// - public static Comparer Default { get; } = new(); + /// + protected override void AddToHashCode(ref HashCode hashCode, HlslMethodSourceInfo obj) + { + hashCode.Add(obj.MetadataName); + hashCode.Add(obj.EntryPoint); + hashCode.AddRange(obj.DefinedTypes); + hashCode.AddRange(obj.DefinedConstants); + hashCode.AddRange(obj.DependentMethods); + } /// - public bool Equals(HlslMethodSourceInfo? x, HlslMethodSourceInfo? y) + protected override bool AreEqual(HlslMethodSourceInfo x, HlslMethodSourceInfo y) { - if (x is null && y is null) - { - return true; - } - - if (x is null || y is null) - { - return false; - } - - if (ReferenceEquals(x, y)) - { - return true; - } - return x.MetadataName == y.MetadataName && x.EntryPoint == y.EntryPoint && @@ -55,19 +46,5 @@ internal sealed record HlslMethodSourceInfo( x.DefinedConstants.SequenceEqual(y.DefinedConstants) && x.DependentMethods.SequenceEqual(y.DependentMethods); } - - /// - public int GetHashCode(HlslMethodSourceInfo obj) - { - HashCode hashCode = default; - - hashCode.Add(obj.MetadataName); - hashCode.Add(obj.EntryPoint); - hashCode.AddRange(obj.DefinedTypes); - hashCode.AddRange(obj.DefinedConstants); - hashCode.AddRange(obj.DependentMethods); - - return hashCode.ToHashCode(); - } } } diff --git a/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs index 82067efa..46f21c35 100644 --- a/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; -using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.SourceGenerators.Models; @@ -41,31 +42,30 @@ internal sealed record HlslShaderSourceInfo( /// /// An implementation for . /// - public sealed class Comparer : IEqualityComparer + public sealed class Comparer : Comparer { - /// - /// The singleton instance. - /// - public static Comparer Default { get; } = new(); + /// + protected override void AddToHashCode(ref HashCode hashCode, HlslShaderSourceInfo obj) + { + hashCode.Add(obj.HeaderAndThreadsX); + hashCode.Add(obj.ThreadsY); + hashCode.Add(obj.ThreadsZ); + hashCode.Add(obj.Defines); + hashCode.Add(obj.StaticFieldsAndDeclaredTypes); + hashCode.Add(obj.CapturedFieldsAndResourcesAndForwardDeclarations); + hashCode.Add(obj.CapturedMethods); + hashCode.Add(obj.EntryPoint); + hashCode.Add(obj.ImplicitTextureType); + hashCode.Add(obj.IsSamplerUsed); + hashCode.AddRange(obj.DefinedTypes); + hashCode.AddRange(obj.DefinedConstants); + hashCode.AddRange(obj.MethodSignatures); + hashCode.AddRange(obj.Delegates); + } /// - public bool Equals(HlslShaderSourceInfo? x, HlslShaderSourceInfo? y) + protected override bool AreEqual(HlslShaderSourceInfo x, HlslShaderSourceInfo y) { - if (x is null && y is null) - { - return true; - } - - if (x is null || y is null) - { - return false; - } - - if (ReferenceEquals(x, y)) - { - return true; - } - return x.HeaderAndThreadsX == y.HeaderAndThreadsX && x.ThreadsY == y.ThreadsY && @@ -82,28 +82,5 @@ internal sealed record HlslShaderSourceInfo( x.MethodSignatures.SequenceEqual(y.MethodSignatures) && x.Delegates.SequenceEqual(y.Delegates); } - - /// - public int GetHashCode(HlslShaderSourceInfo obj) - { - HashCode hashCode = default; - - hashCode.Add(obj.HeaderAndThreadsX); - hashCode.Add(obj.ThreadsY); - hashCode.Add(obj.ThreadsZ); - hashCode.Add(obj.Defines); - hashCode.Add(obj.StaticFieldsAndDeclaredTypes); - hashCode.Add(obj.CapturedFieldsAndResourcesAndForwardDeclarations); - hashCode.Add(obj.CapturedMethods); - hashCode.Add(obj.EntryPoint); - hashCode.Add(obj.ImplicitTextureType); - hashCode.Add(obj.IsSamplerUsed); - hashCode.AddRange(obj.DefinedTypes); - hashCode.AddRange(obj.DefinedConstants); - hashCode.AddRange(obj.MethodSignatures); - hashCode.AddRange(obj.Delegates); - - return hashCode.ToHashCode(); - } } } diff --git a/src/ComputeSharp.SourceGenerators/Models/ResourceDescriptor.cs b/src/ComputeSharp.SourceGenerators/Models/ResourceDescriptor.cs index bb5070c4..a1fd1553 100644 --- a/src/ComputeSharp.SourceGenerators/Models/ResourceDescriptor.cs +++ b/src/ComputeSharp.SourceGenerators/Models/ResourceDescriptor.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; - -namespace ComputeSharp.SourceGenerators.Models; +namespace ComputeSharp.SourceGenerators.Models; /// /// A resource descriptor for a captured resource in a shader. @@ -9,46 +6,4 @@ namespace ComputeSharp.SourceGenerators.Models; /// The type id for the resource. /// The offset of the resource in its containing register. /// The offset of the resource descriptor in the shader root signature. -internal sealed record ResourceDescriptor(int TypeId, int RegisterOffset, int Offset) -{ - /// - /// An implementation for . - /// - public sealed class Comparer : IEqualityComparer - { - /// - /// The singleton instance. - /// - public static Comparer Default { get; } = new(); - - /// - public bool Equals(ResourceDescriptor? x, ResourceDescriptor? y) - { - if (x is null && y is null) - { - return true; - } - - if (x is null || y is null) - { - return false; - } - - if (ReferenceEquals(x, y)) - { - return true; - } - - return - x.TypeId == y.TypeId && - x.RegisterOffset == y.RegisterOffset && - x.Offset == y.Offset; - } - - /// - public int GetHashCode(ResourceDescriptor obj) - { - return HashCode.Combine(obj.TypeId, obj.RegisterOffset, obj.Offset); - } - } -} +internal sealed record ResourceDescriptor(int TypeId, int RegisterOffset, int Offset); diff --git a/src/ComputeSharp.SourceGenerators/Models/ThreadIdsInfo.cs b/src/ComputeSharp.SourceGenerators/Models/ThreadIdsInfo.cs index dfcd72b8..4bca599b 100644 --- a/src/ComputeSharp.SourceGenerators/Models/ThreadIdsInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/ThreadIdsInfo.cs @@ -1,56 +1,10 @@ -using System; -using System.Collections.Generic; - -namespace ComputeSharp.SourceGenerators.Models; +namespace ComputeSharp.SourceGenerators.Models; /// /// A model representing gathered info on a embedded thread ids. /// -/// Whether the values are diascarded. +/// Whether the values are discarded. /// The thread ids value for the X axis. /// The thread ids value for the Y axis. /// The thread ids value for the Z axis. -internal sealed record ThreadIdsInfo(bool IsDefault, int X, int Y, int Z) -{ - /// - /// An implementation for . - /// - public sealed class Comparer : IEqualityComparer - { - /// - /// The singleton instance. - /// - public static Comparer Default { get; } = new(); - - /// - public bool Equals(ThreadIdsInfo? x, ThreadIdsInfo? y) - { - if (x is null && y is null) - { - return true; - } - - if (x is null || y is null) - { - return false; - } - - if (ReferenceEquals(x, y)) - { - return true; - } - - return - x.IsDefault == y.IsDefault && - x.X == y.X && - x.Y == y.Y && - x.Z == y.Y; - } - - /// - public int GetHashCode(ThreadIdsInfo obj) - { - return HashCode.Combine(obj.IsDefault, obj.X, obj.Y, obj.Z); - } - } -} +internal sealed record ThreadIdsInfo(bool IsDefault, int X, int Y, int Z); diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 457513f4..675e960b 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -2,9 +2,9 @@ using System.Collections.Immutable; using System.Linq; using ComputeSharp.__Internals; -using ComputeSharp.SourceGenerators.Diagnostics; -using ComputeSharp.SourceGenerators.Extensions; -using ComputeSharp.SourceGenerators.Helpers; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Models; using ComputeSharp.SourceGenerators.Models; using ComputeSharp.SourceGenerators.SyntaxRewriters; using Microsoft.CodeAnalysis; @@ -89,15 +89,19 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator IMethodSymbol methodSymbol, out ImmutableArray diagnostics) { + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + // We need to sets to track all discovered custom types and static methods HashSet discoveredTypes = new(SymbolEqualityComparer.Default); Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); // Explore the syntax tree and extract the processed info var semanticModel = new SemanticModelProvider(compilation); - var (entryPoint, dependentMethods) = GetProcessedMethods(methodDeclaration, semanticModel, discoveredTypes, constantDefinitions, out diagnostics); - var definedTypes = IShaderGenerator.BuildHlslString.GetDeclaredTypes(discoveredTypes); - var definedConstants = IShaderGenerator.BuildHlslString.GetDefinedConstants(constantDefinitions); + var (entryPoint, dependentMethods) = GetProcessedMethods(builder, methodDeclaration, semanticModel, discoveredTypes, constantDefinitions); + var definedTypes = IShaderGenerator.BuildHlslSource.GetDeclaredTypes(builder, methodSymbol, discoveredTypes); + var definedConstants = IShaderGenerator.BuildHlslSource.GetDefinedConstants(constantDefinitions); + + diagnostics = builder.ToImmutable(); return new( methodSymbol.GetFullMetadataName(includeParameters: true), @@ -110,25 +114,22 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator /// /// Gets a sequence of processed methods from a target method declaration. /// + /// The collection of produced instances. /// The instance for the current method. /// The instance for the method to process. /// The collection of currently discovered types. /// The collection of discovered constant definitions. - /// The resulting diagnostics from the processing operation. /// A sequence of processed methods in (main method and all captured methods). private static (string TargetMethod, ImmutableArray<(string Signature, string Definition)> DependentMethods) GetProcessedMethods( + ImmutableArray.Builder diagnostics, MethodDeclarationSyntax methodDeclaration, SemanticModelProvider semanticModel, ICollection discoveredTypes, - IDictionary constantDefinitions, - out ImmutableArray diagnostics) + IDictionary constantDefinitions) { Dictionary staticMethods = new(SymbolEqualityComparer.Default); - ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); - ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions, builder); - - diagnostics = builder.ToImmutable(); + ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions, diagnostics); // Rewrite the method syntax tree var targetMethod = shaderSourceRewriter diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs index ca805ce7..a22fb426 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs @@ -1,4 +1,4 @@ -using ComputeSharp.SourceGenerators.Diagnostics; +using ComputeSharp.SourceGeneration.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs index 59ab4edf..b34408c7 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs @@ -3,10 +3,9 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; using System.Linq; -using ComputeSharp.SourceGenerators.Diagnostics; -using ComputeSharp.SourceGenerators.Extensions; -using ComputeSharp.SourceGenerators.Helpers; -using ComputeSharp.SourceGenerators.Mappings; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Mappings; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -232,7 +231,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter // Rewrite texture resource indices taking individual indices a vector argument, as per HLSL spec. // For instance: texture[ThreadIds.X, ThreadIds.Y] will be rewritten as texture[int2(ThreadIds.X, ThreadIds.Y)]. - if (HlslKnownMembers.TryGetMappedResourceIndexerTypeName(propertyName, out string? mapping)) + if (HlslKnownProperties.TryGetMappedResourceIndexerTypeName(propertyName, out string? mapping)) { var index = InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments)); @@ -240,7 +239,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter } // Rewrite texture resource sampled accesses, if needed - if (HlslKnownMembers.TryGetMappedResourceSamplerAccessType(propertyName, out mapping)) + if (HlslKnownProperties.TryGetMappedResourceSamplerAccessType(propertyName, out mapping)) { IsSamplerUsed = true; @@ -267,7 +266,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter // If the current property is a swizzled matrix indexer, ensure all the arguments are constants, and rewrite // the property access to the corresponding HLSL syntax. For instance, m[M11, M12] will become m._m00_m01. - if (HlslKnownMembers.IsKnownMatrixIndexer(propertyName)) + if (HlslKnownProperties.IsKnownMatrixIndexer(propertyName)) { bool isValid = true; @@ -275,7 +274,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter foreach (ArgumentSyntax argument in node.ArgumentList.Arguments) { if (SemanticModel.For(node).GetOperation(argument.Expression) is not IFieldReferenceOperation fieldReference || - !HlslKnownMembers.IsKnownMatrixIndex(fieldReference.Field.GetFullMetadataName())) + !HlslKnownProperties.IsKnownMatrixIndex(fieldReference.Field.GetFullMetadataName())) { Diagnostics.Add(NonConstantMatrixSwizzledIndex, argument); diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 0cf712f9..59e5e7fd 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -3,10 +3,9 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; using System.Linq; -using ComputeSharp.SourceGenerators.Diagnostics; -using ComputeSharp.SourceGenerators.Extensions; -using ComputeSharp.SourceGenerators.Helpers; -using ComputeSharp.SourceGenerators.Mappings; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Mappings; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -255,22 +254,35 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) && SemanticModel.For(node).GetOperation(node) is IMemberReferenceOperation operation) { - // If the member access is a constant, track it and replace the tree with the processed constant name - if (operation is IFieldReferenceOperation fieldOperation && - fieldOperation.Field.IsConst && - fieldOperation.Type!.TypeKind != TypeKind.Enum) + if (operation is IFieldReferenceOperation fieldOperation) { - ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture); + // If the member access is a constant, track it and replace the tree with the processed constant name + if (fieldOperation.Field.IsConst && + fieldOperation.Type!.TypeKind != TypeKind.Enum) + { + if (HlslKnownFields.TryGetMappedName(fieldOperation.Member.ToDisplayString(), out string? constantLiteral)) + { + return ParseExpression(constantLiteral!); + } - var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); - var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}"; + ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture); - return IdentifierName(constantName); + var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); + var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}"; + + return IdentifierName(constantName); + } + + // If the member access is a this. access, rewrite it to strip "this." + if (node.Expression.IsKind(SyntaxKind.ThisExpression)) + { + return node.Name; + } } // If the current member access is a field or property access, check the lookup table // to see if the member should be rewritten for HLSL compliance, and rewrite if needed. - if (HlslKnownMembers.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping)) + if (HlslKnownProperties.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping)) { // Mark which dispatch properties have been used, to optimize the declaration afterwards if (operation.Member.IsStatic) @@ -319,7 +331,7 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter // property access into an invocation of an autogenerated static helper method to get the target // dimension for the buffer in use. The helper method is added to the list of static helpers. if (operation is IPropertyReferenceOperation propertyOperation && - HlslKnownMembers.TryGetAccessorRankAndAxis(propertyOperation.Property.GetFullMetadataName(), out int rank, out int axis)) + HlslKnownProperties.TryGetAccessorRankAndAxis(propertyOperation.Property.GetFullMetadataName(), out int rank, out int axis)) { IMethodSymbol key = propertyOperation.Property.GetMethod!; @@ -404,8 +416,14 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter if (!this.staticMethods.ContainsKey(method)) { + if (method.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is not MethodDeclarationSyntax methodNode) + { + Diagnostics.Add(InvalidMethodCall, node, method); + + return updatedNode; + } + ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Diagnostics); - MethodDeclarationSyntax methodNode = (MethodDeclarationSyntax)method.DeclaringSyntaxReferences[0].GetSyntax(); MethodDeclarationSyntax processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace(eol: "\n").WithoutTrivia(); this.staticMethods.Add(method, processedMethod.WithIdentifier(Identifier(methodIdentifier))); @@ -429,7 +447,7 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter // Track and rewrite the discarded declaration if (SemanticModel.For(node).GetOperation(node.Expression) is IDiscardOperation operation) { - TypeSyntax typeSyntax = operation.Type!.TrackType(DiscoveredTypes); + TypeSyntax typeSyntax = ParseTypeName(HlslKnownTypes.TrackType(operation.Type!, DiscoveredTypes)); string identifier = $"__implicit{this.implicitVariables.Count}"; // Add the variable to the list of implicit declarations diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs index b724fc9d..939f8b79 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs @@ -2,10 +2,9 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; -using ComputeSharp.SourceGenerators.Diagnostics; -using ComputeSharp.SourceGenerators.Extensions; -using ComputeSharp.SourceGenerators.Helpers; -using ComputeSharp.SourceGenerators.Mappings; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Mappings; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -60,6 +59,11 @@ internal sealed class StaticFieldRewriter : HlslSourceRewriter fieldOperation.Field.IsConst && fieldOperation.Type!.TypeKind != TypeKind.Enum) { + if (HlslKnownFields.TryGetMappedName(fieldOperation.Member.ToDisplayString(), out string? constantLiteral)) + { + return ParseExpression(constantLiteral!); + } + ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture); var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); @@ -68,7 +72,7 @@ internal sealed class StaticFieldRewriter : HlslSourceRewriter return IdentifierName(constantName); } - if (HlslKnownMembers.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping)) + if (HlslKnownProperties.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping)) { if (operation.Member.IsStatic) { diff --git a/src/ComputeSharp.Uwp/ComputeSharp.Uwp.csproj b/src/ComputeSharp.Uwp/ComputeSharp.Uwp.csproj index 06046c44..cf837b3a 100644 --- a/src/ComputeSharp.Uwp/ComputeSharp.Uwp.csproj +++ b/src/ComputeSharp.Uwp/ComputeSharp.Uwp.csproj @@ -27,7 +27,7 @@ - + diff --git a/src/ComputeSharp.WinUI/ComputeSharp.WinUI.csproj b/src/ComputeSharp.WinUI/ComputeSharp.WinUI.csproj index cdb1b032..6062ddd5 100644 --- a/src/ComputeSharp.WinUI/ComputeSharp.WinUI.csproj +++ b/src/ComputeSharp.WinUI/ComputeSharp.WinUI.csproj @@ -19,7 +19,7 @@ - + diff --git a/src/ComputeSharp/ComputeSharp.csproj b/src/ComputeSharp/ComputeSharp.csproj index 34893c6a..ce8db878 100644 --- a/src/ComputeSharp/ComputeSharp.csproj +++ b/src/ComputeSharp/ComputeSharp.csproj @@ -11,6 +11,10 @@ true + + + + @@ -44,203 +48,4 @@ - - - - - - - - True - True - Hlsl.tt - - - True - True - Bool2.tt - - - True - True - Bool3.tt - - - True - True - Bool4.tt - - - True - True - BoolMxN.tt - - - True - True - Double2.tt - - - True - True - Double3.tt - - - True - True - Double4.tt - - - True - True - DoubleMxN.tt - - - True - True - Float2.tt - - - True - True - Float3.tt - - - True - True - Float4.tt - - - True - True - FloatMxN.tt - - - True - True - Int2.tt - - - True - True - Int3.tt - - - True - True - Int4.tt - - - True - True - IntMxN.tt - - - True - True - UInt2.tt - - - True - True - UInt3.tt - - - True - True - UInt4.tt - - - True - True - UIntMxN.tt - - - - - - TextTemplatingFileGenerator - Hlsl.g.cs - - - TextTemplatingFileGenerator - Bool2.g.cs - - - TextTemplatingFileGenerator - Bool3.g.cs - - - TextTemplatingFileGenerator - Bool4.g.cs - - - TextTemplatingFileGenerator - BoolMxN.g.cs - - - TextTemplatingFileGenerator - Double2.g.cs - - - TextTemplatingFileGenerator - Double3.g.cs - - - TextTemplatingFileGenerator - Double4.g.cs - - - TextTemplatingFileGenerator - DoubleMxN.g.cs - - - TextTemplatingFileGenerator - Float2.g.cs - - - TextTemplatingFileGenerator - Float3.g.cs - - - TextTemplatingFileGenerator - Float4.g.cs - - - TextTemplatingFileGenerator - FloatMxN.g.cs - - - TextTemplatingFileGenerator - Int2.g.cs - - - TextTemplatingFileGenerator - Int3.g.cs - - - TextTemplatingFileGenerator - Int4.g.cs - - - TextTemplatingFileGenerator - IntMxN.g.cs - - - TextTemplatingFileGenerator - UInt2.g.cs - - - TextTemplatingFileGenerator - UInt3.g.cs - - - TextTemplatingFileGenerator - UInt4.g.cs - - - TextTemplatingFileGenerator - UIntMxN.g.cs - - diff --git a/src/ComputeSharp/Core/Dispatch/DispatchAxis.cs b/src/ComputeSharp/Core/Dispatch/DispatchAxis.cs index 8dbe1294..7e95cd93 100644 --- a/src/ComputeSharp/Core/Dispatch/DispatchAxis.cs +++ b/src/ComputeSharp/Core/Dispatch/DispatchAxis.cs @@ -1,7 +1,7 @@ namespace ComputeSharp; /// -/// A to be used with to indicate the dispatch +/// A to be used with to indicate the dispatch axis to precompile a shader for. /// public enum DispatchAxis { diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IBytecodeLoader.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IBytecodeLoader.cs index 943cef72..1ca5ee68 100644 --- a/src/ComputeSharp/Core/Interfaces/__Internals/IBytecodeLoader.cs +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IBytecodeLoader.cs @@ -15,6 +15,7 @@ public interface IBytecodeLoader /// /// An opaque handle to the shader bytecode. /// Thrown if the shader has already been initialized. + /// Thrown if is (indicating an unsupported configuration). void LoadDynamicBytecode(IntPtr handle); /// diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs index 262b7d0d..e688929b 100644 --- a/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs @@ -73,7 +73,7 @@ public interface IShader /// The number of threads in each thread group for the Z axis. [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This method is not intended to be called directly by user code")] - void BuildHlslString(out ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ) + void BuildHlslSource(out ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ) #if NET6_0_OR_GREATER { throw new NotImplementedException(); @@ -90,6 +90,7 @@ public interface IShader /// The number of threads in each thread group for the X axis. /// The number of threads in each thread group for the Y axis. /// The number of threads in each thread group for the Z axis. + /// Thrown if the bytecode required runtime compilation and it wasn't supported on the current configuration. [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This method is not intended to be used directly by user code")] void LoadBytecode(ref TLoader loader, int threadsX, int threadsY, int threadsZ) diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/D2D1_PROPERTY_TYPE.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/D2D1_PROPERTY_TYPE.cs new file mode 100644 index 00000000..e7c40874 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/D2D1_PROPERTY_TYPE.cs @@ -0,0 +1,12 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1_1.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +namespace TerraFX.Interop.DirectX +{ + internal enum D2D1_PROPERTY_TYPE : uint + { + D2D1_PROPERTY_TYPE_BLOB = 9 + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1DeviceContext.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1DeviceContext.cs new file mode 100644 index 00000000..e612b6d4 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1DeviceContext.cs @@ -0,0 +1,29 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1_1.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649 + +namespace TerraFX.Interop.DirectX +{ + [Guid("E8F7FE7A-191C-466D-AD95-975678BDA998")] + [NativeTypeName("struct ID2D1DeviceContext : ID2D1RenderTarget")] + [NativeInheritance("ID2D1RenderTarget")] + internal unsafe partial struct ID2D1DeviceContext + { + public void** lpVtbl; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(63)] + public HRESULT CreateEffect([NativeTypeName("const IID &")] Guid* effectId, ID2D1Effect** effect) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[63]))((ID2D1DeviceContext*)Unsafe.AsPointer(ref this), effectId, effect); + } + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1Effect.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1Effect.cs new file mode 100644 index 00000000..faa1afde --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1Effect.cs @@ -0,0 +1,29 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1_1.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649 + +namespace TerraFX.Interop.DirectX +{ + [Guid("28211A43-7D89-476F-8181-2D6159B220AD")] + [NativeTypeName("struct ID2D1Effect : ID2D1Properties")] + [NativeInheritance("ID2D1Properties")] + internal unsafe partial struct ID2D1Effect + { + public void** lpVtbl; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(9)] + public HRESULT SetValue([NativeTypeName("UINT32")] uint index, D2D1_PROPERTY_TYPE type, [NativeTypeName("const BYTE *")] byte* data, [NativeTypeName("UINT32")] uint dataSize) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[9]))((ID2D1Effect*)Unsafe.AsPointer(ref this), index, type, data, dataSize); + } + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1Factory1.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1Factory1.cs new file mode 100644 index 00000000..15c8bf2c --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1Factory1.cs @@ -0,0 +1,29 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1_1.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649 + +namespace TerraFX.Interop.DirectX +{ + [Guid("BB12D362-DAEE-4B9A-AA1D-14BA401CFA1F")] + [NativeTypeName("struct ID2D1Factory1 : ID2D1Factory")] + [NativeInheritance("ID2D1Factory")] + internal unsafe partial struct ID2D1Factory1 + { + public void** lpVtbl; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(23)] + public HRESULT RegisterEffectFromString([NativeTypeName("const IID &")] Guid* classId, [NativeTypeName("PCWSTR")] ushort* propertyXml, [NativeTypeName("const D2D1_PROPERTY_BINDING *")] D2D1_PROPERTY_BINDING* bindings, [NativeTypeName("UINT32")] uint bindingsCount, [NativeTypeName("const PD2D1_EFFECT_FACTORY")] delegate* unmanaged[Stdcall] effectFactory) + { + return ((delegate* unmanaged[Stdcall], int>)(lpVtbl[23]))((ID2D1Factory1*)Unsafe.AsPointer(ref this), classId, propertyXml, bindings, bindingsCount, effectFactory); + } + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/D2D1_CHANGE_TYPE.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/D2D1_CHANGE_TYPE.cs new file mode 100644 index 00000000..071cdb7c --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/D2D1_CHANGE_TYPE.cs @@ -0,0 +1,19 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1effectauthor.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; + +namespace TerraFX.Interop.DirectX +{ + [Flags] + internal enum D2D1_CHANGE_TYPE : uint + { + D2D1_CHANGE_TYPE_NONE = 0, + D2D1_CHANGE_TYPE_PROPERTIES = 1, + D2D1_CHANGE_TYPE_CONTEXT = 2, + D2D1_CHANGE_TYPE_GRAPH = 3, + D2D1_CHANGE_TYPE_FORCE_DWORD = 0xffffffff, + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/D2D1_PIXEL_OPTIONS.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/D2D1_PIXEL_OPTIONS.cs new file mode 100644 index 00000000..446d86ae --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/D2D1_PIXEL_OPTIONS.cs @@ -0,0 +1,17 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1effectauthor.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; + +namespace TerraFX.Interop.DirectX +{ + [Flags] + internal enum D2D1_PIXEL_OPTIONS : uint + { + D2D1_PIXEL_OPTIONS_NONE = 0, + D2D1_PIXEL_OPTIONS_TRIVIAL_SAMPLING = 1, + D2D1_PIXEL_OPTIONS_FORCE_DWORD = 0xffffffff, + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/D2D1_PROPERTY_BINDING.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/D2D1_PROPERTY_BINDING.cs new file mode 100644 index 00000000..260517aa --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/D2D1_PROPERTY_BINDING.cs @@ -0,0 +1,23 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1effectauthor.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +#pragma warning disable CS0649 + +using TerraFX.Interop.Windows; + +namespace TerraFX.Interop.DirectX +{ + internal unsafe partial struct D2D1_PROPERTY_BINDING + { + [NativeTypeName("PCWSTR")] + public ushort* propertyName; + + [NativeTypeName("PD2D1_PROPERTY_SET_FUNCTION")] + public delegate* unmanaged[Stdcall] setFunction; + + [NativeTypeName("PD2D1_PROPERTY_GET_FUNCTION")] + public delegate* unmanaged[Stdcall] getFunction; + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1DrawInfo.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1DrawInfo.cs new file mode 100644 index 00000000..2c94d473 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1DrawInfo.cs @@ -0,0 +1,37 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1effectauthor.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using TerraFX.Interop.Windows; +using static TerraFX.Interop.DirectX.D2D1_PIXEL_OPTIONS; + +#pragma warning disable CS0649 + +namespace TerraFX.Interop.DirectX +{ + [Guid("693CE632-7F2F-45DE-93FE-18D88B37AA21")] + [NativeTypeName("struct ID2D1DrawInfo : ID2D1RenderInfo")] + [NativeInheritance("ID2D1RenderInfo")] + internal unsafe partial struct ID2D1DrawInfo + { + public void** lpVtbl; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(7)] + public HRESULT SetPixelShaderConstantBuffer([NativeTypeName("const BYTE *")] byte* buffer, [NativeTypeName("UINT32")] uint bufferCount) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[7]))((ID2D1DrawInfo*)Unsafe.AsPointer(ref this), buffer, bufferCount); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(10)] + public HRESULT SetPixelShader([NativeTypeName("const GUID &")] Guid* shaderId, D2D1_PIXEL_OPTIONS pixelOptions = D2D1_PIXEL_OPTIONS_NONE) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[10]))((ID2D1DrawInfo*)Unsafe.AsPointer(ref this), shaderId, pixelOptions); + } + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1DrawTransform.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1DrawTransform.cs new file mode 100644 index 00000000..064cece3 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1DrawTransform.cs @@ -0,0 +1,81 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1effectauthor.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649 + +namespace TerraFX.Interop.DirectX +{ + [Guid("36BFDCB6-9739-435D-A30D-A653BEFF6A6F")] + [NativeTypeName("struct ID2D1DrawTransform : ID2D1Transform")] + [NativeInheritance("ID2D1Transform")] + internal unsafe partial struct ID2D1DrawTransform + { + public void** lpVtbl; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(0)] + public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[0]))((ID2D1DrawTransform*)Unsafe.AsPointer(ref this), riid, ppvObject); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(1)] + [return: NativeTypeName("ULONG")] + public uint AddRef() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[1]))((ID2D1DrawTransform*)Unsafe.AsPointer(ref this)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(2)] + [return: NativeTypeName("ULONG")] + public uint Release() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[2]))((ID2D1DrawTransform*)Unsafe.AsPointer(ref this)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(3)] + [return: NativeTypeName("UINT32")] + public uint GetInputCount() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[3]))((ID2D1DrawTransform*)Unsafe.AsPointer(ref this)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(4)] + public HRESULT MapOutputRectToInputRects([NativeTypeName("const D2D1_RECT_L *")] RECT* outputRect, [NativeTypeName("D2D1_RECT_L *")] RECT* inputRects, [NativeTypeName("UINT32")] uint inputRectsCount) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[4]))((ID2D1DrawTransform*)Unsafe.AsPointer(ref this), outputRect, inputRects, inputRectsCount); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(5)] + public HRESULT MapInputRectsToOutputRect([NativeTypeName("const D2D1_RECT_L *")] RECT* inputRects, [NativeTypeName("const D2D1_RECT_L *")] RECT* inputOpaqueSubRects, [NativeTypeName("UINT32")] uint inputRectCount, [NativeTypeName("D2D1_RECT_L *")] RECT* outputRect, [NativeTypeName("D2D1_RECT_L *")] RECT* outputOpaqueSubRect) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[5]))((ID2D1DrawTransform*)Unsafe.AsPointer(ref this), inputRects, inputOpaqueSubRects, inputRectCount, outputRect, outputOpaqueSubRect); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(6)] + public HRESULT MapInvalidRect([NativeTypeName("UINT32")] uint inputIndex, [NativeTypeName("D2D1_RECT_L")] RECT invalidInputRect, [NativeTypeName("D2D1_RECT_L *")] RECT* invalidOutputRect) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[6]))((ID2D1DrawTransform*)Unsafe.AsPointer(ref this), inputIndex, invalidInputRect, invalidOutputRect); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(7)] + public HRESULT SetDrawInfo(ID2D1DrawInfo* drawInfo) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[7]))((ID2D1DrawTransform*)Unsafe.AsPointer(ref this), drawInfo); + } + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1EffectContext.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1EffectContext.cs new file mode 100644 index 00000000..21bcf154 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1EffectContext.cs @@ -0,0 +1,43 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1effectauthor.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649 + +namespace TerraFX.Interop.DirectX +{ + [Guid("3D9F916B-27DC-4AD7-B4F1-64945340F563")] + [NativeTypeName("struct ID2D1EffectContext : IUnknown")] + [NativeInheritance("IUnknown")] + internal unsafe partial struct ID2D1EffectContext + { + public void** lpVtbl; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(4)] + public HRESULT CreateEffect([NativeTypeName("const IID &")] Guid* effectId, void** effect) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[4]))((ID2D1EffectContext*)Unsafe.AsPointer(ref this), effectId, effect); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(11)] + public HRESULT LoadPixelShader([NativeTypeName("const GUID &")] Guid* shaderId, [NativeTypeName("const BYTE *")] byte* shaderBuffer, [NativeTypeName("UINT32")] uint shaderBufferCount) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[11]))((ID2D1EffectContext*)Unsafe.AsPointer(ref this), shaderId, shaderBuffer, shaderBufferCount); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(14)] + public int IsShaderLoaded([NativeTypeName("const GUID &")] Guid* shaderId) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[14]))((ID2D1EffectContext*)Unsafe.AsPointer(ref this), shaderId); + } + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1EffectImpl.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1EffectImpl.cs new file mode 100644 index 00000000..1480f720 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1EffectImpl.cs @@ -0,0 +1,66 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1effectauthor.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649 + +namespace TerraFX.Interop.DirectX +{ + [Guid("A248FD3F-3E6C-4E63-9F03-7F68ECC91DB9")] + [NativeTypeName("struct ID2D1EffectImpl : IUnknown")] + [NativeInheritance("IUnknown")] + internal unsafe partial struct ID2D1EffectImpl + { + public void** lpVtbl; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(0)] + public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[0]))((ID2D1EffectImpl*)Unsafe.AsPointer(ref this), riid, ppvObject); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(1)] + [return: NativeTypeName("ULONG")] + public uint AddRef() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[1]))((ID2D1EffectImpl*)Unsafe.AsPointer(ref this)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(2)] + [return: NativeTypeName("ULONG")] + public uint Release() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[2]))((ID2D1EffectImpl*)Unsafe.AsPointer(ref this)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(3)] + public HRESULT Initialize(ID2D1EffectContext* effectContext, ID2D1TransformGraph* transformGraph) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[3]))((ID2D1EffectImpl*)Unsafe.AsPointer(ref this), effectContext, transformGraph); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(4)] + public HRESULT PrepareForRender(D2D1_CHANGE_TYPE changeType) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[4]))((ID2D1EffectImpl*)Unsafe.AsPointer(ref this), changeType); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(5)] + public HRESULT SetGraph(ID2D1TransformGraph* transformGraph) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[5]))((ID2D1EffectImpl*)Unsafe.AsPointer(ref this), transformGraph); + } + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1Transform.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1Transform.cs new file mode 100644 index 00000000..0db52274 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1Transform.cs @@ -0,0 +1,20 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1effectauthor.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.Runtime.InteropServices; + +#pragma warning disable CS0649 + +namespace TerraFX.Interop.DirectX +{ + [Guid("EF1A287D-342A-4F76-8FDB-DA0D6EA9F92B")] + [NativeTypeName("struct ID2D1Transform : ID2D1TransformNode")] + [NativeInheritance("ID2D1TransformNode")] + internal unsafe partial struct ID2D1Transform + { + public void** lpVtbl; + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1TransformGraph.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1TransformGraph.cs new file mode 100644 index 00000000..923993c1 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1TransformGraph.cs @@ -0,0 +1,29 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1effectauthor.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649 + +namespace TerraFX.Interop.DirectX +{ + [Guid("13D29038-C3E6-4034-9081-13B53A417992")] + [NativeTypeName("struct ID2D1TransformGraph : IUnknown")] + [NativeInheritance("IUnknown")] + internal unsafe partial struct ID2D1TransformGraph + { + public void** lpVtbl; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(4)] + public HRESULT SetSingleTransformNode(ID2D1TransformNode* node) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[4]))((ID2D1TransformGraph*)Unsafe.AsPointer(ref this), node); + } + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1TransformNode.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1TransformNode.cs new file mode 100644 index 00000000..aa2a61c9 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1TransformNode.cs @@ -0,0 +1,20 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1effectauthor.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.Runtime.InteropServices; + +#pragma warning disable CS0649 + +namespace TerraFX.Interop.DirectX +{ + [Guid("B2EFE1E7-729F-4102-949F-505FA21BF666")] + [NativeTypeName("struct ID2D1TransformNode : IUnknown")] + [NativeInheritance("IUnknown")] + internal unsafe partial struct ID2D1TransformNode + { + public void** lpVtbl; + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3d11shadeer/D3D11_SHADER_DESC.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3d11shadeer/D3D11_SHADER_DESC.cs new file mode 100644 index 00000000..2bb5b6cf --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3d11shadeer/D3D11_SHADER_DESC.cs @@ -0,0 +1,87 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d3d11shader.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +namespace TerraFX.Interop.DirectX +{ + internal unsafe partial struct D3D11_SHADER_DESC + { + public uint Version; + + [NativeTypeName("LPCSTR")] + public sbyte* Creator; + + public uint Flags; + + public uint ConstantBuffers; + + public uint BoundResources; + + public uint InputParameters; + + public uint OutputParameters; + + public uint InstructionCount; + + public uint TempRegisterCount; + + public uint TempArrayCount; + + public uint DefCount; + + public uint DclCount; + + public uint TextureNormalInstructions; + + public uint TextureLoadInstructions; + + public uint TextureCompInstructions; + + public uint TextureBiasInstructions; + + public uint TextureGradientInstructions; + + public uint FloatInstructionCount; + + public uint IntInstructionCount; + + public uint UintInstructionCount; + + public uint StaticFlowControlCount; + + public uint DynamicFlowControlCount; + + public uint MacroInstructionCount; + + public uint ArrayInstructionCount; + + public uint CutInstructionCount; + + public uint EmitInstructionCount; + + public D3D_PRIMITIVE_TOPOLOGY GSOutputTopology; + + public uint GSMaxOutputVertexCount; + + public D3D_PRIMITIVE InputPrimitive; + + public uint PatchConstantParameters; + + public uint cGSInstanceCount; + + public uint cControlPoints; + + public D3D_TESSELLATOR_OUTPUT_PRIMITIVE HSOutputPrimitive; + + public D3D_TESSELLATOR_PARTITIONING HSPartitioning; + + public D3D_TESSELLATOR_DOMAIN TessellatorDomain; + + public uint cBarrierInstructions; + + public uint cInterlockedInstructions; + + public uint cTextureStoreInstructions; + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3d11shadeer/ID3D11ShaderReflection.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3d11shadeer/ID3D11ShaderReflection.cs new file mode 100644 index 00000000..ed1349c1 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3d11shadeer/ID3D11ShaderReflection.cs @@ -0,0 +1,112 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d3d11shader.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649 + +namespace TerraFX.Interop.DirectX +{ + [Guid("8D536CA1-0CCA-4956-A837-786963755584")] + [NativeTypeName("struct ID3D11ShaderReflection : IUnknown")] + [NativeInheritance("IUnknown")] + internal unsafe partial struct ID3D11ShaderReflection + { + public void** lpVtbl; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(0)] + public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[0]))((ID3D11ShaderReflection*)Unsafe.AsPointer(ref this), riid, ppvObject); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(1)] + [return: NativeTypeName("ULONG")] + public uint AddRef() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[1]))((ID3D11ShaderReflection*)Unsafe.AsPointer(ref this)); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(2)] + [return: NativeTypeName("ULONG")] + public uint Release() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[2]))((ID3D11ShaderReflection*)Unsafe.AsPointer(ref this)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(3)] + public HRESULT GetDesc(D3D11_SHADER_DESC* pDesc) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[3]))((ID3D11ShaderReflection*)Unsafe.AsPointer(ref this), pDesc); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(12)] + public uint GetMovInstructionCount() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[12]))((ID3D11ShaderReflection*)Unsafe.AsPointer(ref this)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(13)] + public uint GetMovcInstructionCount() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[13]))((ID3D11ShaderReflection*)Unsafe.AsPointer(ref this)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(14)] + public uint GetConversionInstructionCount() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[14]))((ID3D11ShaderReflection*)Unsafe.AsPointer(ref this)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(15)] + public uint GetBitwiseInstructionCount() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[15]))((ID3D11ShaderReflection*)Unsafe.AsPointer(ref this)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(16)] + public D3D_PRIMITIVE GetGSInputPrimitive() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[16]))((ID3D11ShaderReflection*)Unsafe.AsPointer(ref this)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(18)] + public uint GetNumInterfaceSlots() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[18]))((ID3D11ShaderReflection*)Unsafe.AsPointer(ref this)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(20)] + public uint GetThreadGroupSize(uint* pSizeX, uint* pSizeY, uint* pSizeZ) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[20]))((ID3D11ShaderReflection*)Unsafe.AsPointer(ref this), pSizeX, pSizeY, pSizeZ); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(21)] + [return: NativeTypeName("UINT64")] + public ulong GetRequiresFlags() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[21]))((ID3D11ShaderReflection*)Unsafe.AsPointer(ref this)); + } + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3dcommon/D3D_INCLUDE_TYPE.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3dcommon/D3D_INCLUDE_TYPE.cs new file mode 100644 index 00000000..65ca6cc7 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3dcommon/D3D_INCLUDE_TYPE.cs @@ -0,0 +1,16 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from d3dcommon.h in Microsoft.Direct3D.D3D12 v1.600.10 +// Original source is Copyright © Microsoft. Licensed under the MIT license + +namespace TerraFX.Interop.DirectX +{ + internal enum D3D_INCLUDE_TYPE + { + D3D_INCLUDE_LOCAL = 0, + D3D_INCLUDE_SYSTEM = (D3D_INCLUDE_LOCAL + 1), + D3D10_INCLUDE_LOCAL = D3D_INCLUDE_LOCAL, + D3D10_INCLUDE_SYSTEM = D3D_INCLUDE_SYSTEM, + D3D_INCLUDE_FORCE_DWORD = 0x7fffffff, + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3dcommon/D3D_SHADER_MACRO.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3dcommon/D3D_SHADER_MACRO.cs new file mode 100644 index 00000000..d1c4c0ec --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3dcommon/D3D_SHADER_MACRO.cs @@ -0,0 +1,16 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from d3dcommon.h in Microsoft.Direct3D.D3D12 v1.600.10 +// Original source is Copyright © Microsoft. Licensed under the MIT license + +namespace TerraFX.Interop.DirectX +{ + internal unsafe partial struct D3D_SHADER_MACRO + { + [NativeTypeName("LPCSTR")] + public sbyte* Name; + + [NativeTypeName("LPCSTR")] + public sbyte* Definition; + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3dcommon/ID3DInclude.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3dcommon/ID3DInclude.cs new file mode 100644 index 00000000..8fd92f76 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3dcommon/ID3DInclude.cs @@ -0,0 +1,31 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from d3dcommon.h in Microsoft.Direct3D.D3D12 v1.600.10 +// Original source is Copyright © Microsoft. Licensed under the MIT license + +using System.Runtime.CompilerServices; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649 + +namespace TerraFX.Interop.DirectX +{ + internal unsafe partial struct ID3DInclude + { + public void** lpVtbl; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(0)] + public HRESULT Open(D3D_INCLUDE_TYPE IncludeType, [NativeTypeName("LPCSTR")] sbyte* pFileName, [NativeTypeName("LPCVOID")] void* pParentData, [NativeTypeName("LPCVOID *")] void** ppData, uint* pBytes) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[0]))((ID3DInclude*)Unsafe.AsPointer(ref this), IncludeType, pFileName, pParentData, ppData, pBytes); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(1)] + public HRESULT Close([NativeTypeName("LPCVOID")] void* pData) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[1]))((ID3DInclude*)Unsafe.AsPointer(ref this), pData); + } + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3dcompiler/D3DCOMPILE.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3dcompiler/D3DCOMPILE.cs new file mode 100644 index 00000000..a7841e13 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3dcompiler/D3DCOMPILE.cs @@ -0,0 +1,112 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d3dcompiler.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +namespace TerraFX.Interop.DirectX +{ + internal static partial class D3DCOMPILE + { + [NativeTypeName("#define D3DCOMPILE_DEBUG (1 << 0)")] + public const int D3DCOMPILE_DEBUG = (1 << 0); + + [NativeTypeName("#define D3DCOMPILE_SKIP_VALIDATION (1 << 1)")] + public const int D3DCOMPILE_SKIP_VALIDATION = (1 << 1); + + [NativeTypeName("#define D3DCOMPILE_SKIP_OPTIMIZATION (1 << 2)")] + public const int D3DCOMPILE_SKIP_OPTIMIZATION = (1 << 2); + + [NativeTypeName("#define D3DCOMPILE_PACK_MATRIX_ROW_MAJOR (1 << 3)")] + public const int D3DCOMPILE_PACK_MATRIX_ROW_MAJOR = (1 << 3); + + [NativeTypeName("#define D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR (1 << 4)")] + public const int D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR = (1 << 4); + + [NativeTypeName("#define D3DCOMPILE_PARTIAL_PRECISION (1 << 5)")] + public const int D3DCOMPILE_PARTIAL_PRECISION = (1 << 5); + + [NativeTypeName("#define D3DCOMPILE_FORCE_VS_SOFTWARE_NO_OPT (1 << 6)")] + public const int D3DCOMPILE_FORCE_VS_SOFTWARE_NO_OPT = (1 << 6); + + [NativeTypeName("#define D3DCOMPILE_FORCE_PS_SOFTWARE_NO_OPT (1 << 7)")] + public const int D3DCOMPILE_FORCE_PS_SOFTWARE_NO_OPT = (1 << 7); + + [NativeTypeName("#define D3DCOMPILE_NO_PRESHADER (1 << 8)")] + public const int D3DCOMPILE_NO_PRESHADER = (1 << 8); + + [NativeTypeName("#define D3DCOMPILE_AVOID_FLOW_CONTROL (1 << 9)")] + public const int D3DCOMPILE_AVOID_FLOW_CONTROL = (1 << 9); + + [NativeTypeName("#define D3DCOMPILE_PREFER_FLOW_CONTROL (1 << 10)")] + public const int D3DCOMPILE_PREFER_FLOW_CONTROL = (1 << 10); + + [NativeTypeName("#define D3DCOMPILE_ENABLE_STRICTNESS (1 << 11)")] + public const int D3DCOMPILE_ENABLE_STRICTNESS = (1 << 11); + + [NativeTypeName("#define D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY (1 << 12)")] + public const int D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY = (1 << 12); + + [NativeTypeName("#define D3DCOMPILE_IEEE_STRICTNESS (1 << 13)")] + public const int D3DCOMPILE_IEEE_STRICTNESS = (1 << 13); + + [NativeTypeName("#define D3DCOMPILE_OPTIMIZATION_LEVEL0 (1 << 14)")] + public const int D3DCOMPILE_OPTIMIZATION_LEVEL0 = (1 << 14); + + [NativeTypeName("#define D3DCOMPILE_OPTIMIZATION_LEVEL1 0")] + public const int D3DCOMPILE_OPTIMIZATION_LEVEL1 = 0; + + [NativeTypeName("#define D3DCOMPILE_OPTIMIZATION_LEVEL2 ((1 << 14) | (1 << 15))")] + public const int D3DCOMPILE_OPTIMIZATION_LEVEL2 = ((1 << 14) | (1 << 15)); + + [NativeTypeName("#define D3DCOMPILE_OPTIMIZATION_LEVEL3 (1 << 15)")] + public const int D3DCOMPILE_OPTIMIZATION_LEVEL3 = (1 << 15); + + [NativeTypeName("#define D3DCOMPILE_RESERVED16 (1 << 16)")] + public const int D3DCOMPILE_RESERVED16 = (1 << 16); + + [NativeTypeName("#define D3DCOMPILE_RESERVED17 (1 << 17)")] + public const int D3DCOMPILE_RESERVED17 = (1 << 17); + + [NativeTypeName("#define D3DCOMPILE_WARNINGS_ARE_ERRORS (1 << 18)")] + public const int D3DCOMPILE_WARNINGS_ARE_ERRORS = (1 << 18); + + [NativeTypeName("#define D3DCOMPILE_RESOURCES_MAY_ALIAS (1 << 19)")] + public const int D3DCOMPILE_RESOURCES_MAY_ALIAS = (1 << 19); + + [NativeTypeName("#define D3DCOMPILE_ENABLE_UNBOUNDED_DESCRIPTOR_TABLES (1 << 20)")] + public const int D3DCOMPILE_ENABLE_UNBOUNDED_DESCRIPTOR_TABLES = (1 << 20); + + [NativeTypeName("#define D3DCOMPILE_ALL_RESOURCES_BOUND (1 << 21)")] + public const int D3DCOMPILE_ALL_RESOURCES_BOUND = (1 << 21); + + [NativeTypeName("#define D3DCOMPILE_DEBUG_NAME_FOR_SOURCE (1 << 22)")] + public const int D3DCOMPILE_DEBUG_NAME_FOR_SOURCE = (1 << 22); + + [NativeTypeName("#define D3DCOMPILE_DEBUG_NAME_FOR_BINARY (1 << 23)")] + public const int D3DCOMPILE_DEBUG_NAME_FOR_BINARY = (1 << 23); + + [NativeTypeName("#define D3DCOMPILE_EFFECT_CHILD_EFFECT (1 << 0)")] + public const int D3DCOMPILE_EFFECT_CHILD_EFFECT = (1 << 0); + + [NativeTypeName("#define D3DCOMPILE_EFFECT_ALLOW_SLOW_OPS (1 << 1)")] + public const int D3DCOMPILE_EFFECT_ALLOW_SLOW_OPS = (1 << 1); + + [NativeTypeName("#define D3DCOMPILE_FLAGS2_FORCE_ROOT_SIGNATURE_LATEST 0")] + public const int D3DCOMPILE_FLAGS2_FORCE_ROOT_SIGNATURE_LATEST = 0; + + [NativeTypeName("#define D3DCOMPILE_FLAGS2_FORCE_ROOT_SIGNATURE_1_0 (1 << 4)")] + public const int D3DCOMPILE_FLAGS2_FORCE_ROOT_SIGNATURE_1_0 = (1 << 4); + + [NativeTypeName("#define D3DCOMPILE_FLAGS2_FORCE_ROOT_SIGNATURE_1_1 (1 << 5)")] + public const int D3DCOMPILE_FLAGS2_FORCE_ROOT_SIGNATURE_1_1 = (1 << 5); + + [NativeTypeName("#define D3DCOMPILE_SECDATA_MERGE_UAV_SLOTS 0x00000001")] + public const int D3DCOMPILE_SECDATA_MERGE_UAV_SLOTS = 0x00000001; + + [NativeTypeName("#define D3DCOMPILE_SECDATA_PRESERVE_TEMPLATE_SLOTS 0x00000002")] + public const int D3DCOMPILE_SECDATA_PRESERVE_TEMPLATE_SLOTS = 0x00000002; + + [NativeTypeName("#define D3DCOMPILE_SECDATA_REQUIRE_TEMPLATE_MATCH 0x00000004")] + public const int D3DCOMPILE_SECDATA_REQUIRE_TEMPLATE_MATCH = 0x00000004; + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3dcompiler/D3D_BLOB_PART.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3dcompiler/D3D_BLOB_PART.cs new file mode 100644 index 00000000..f61ad7ee --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3dcompiler/D3D_BLOB_PART.cs @@ -0,0 +1,44 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d3dcompiler.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +namespace TerraFX.Interop.DirectX +{ + internal enum D3D_BLOB_PART + { + D3D_BLOB_INPUT_SIGNATURE_BLOB, + + D3D_BLOB_OUTPUT_SIGNATURE_BLOB, + + D3D_BLOB_INPUT_AND_OUTPUT_SIGNATURE_BLOB, + + D3D_BLOB_PATCH_CONSTANT_SIGNATURE_BLOB, + + D3D_BLOB_ALL_SIGNATURE_BLOB, + + D3D_BLOB_DEBUG_INFO, + + D3D_BLOB_LEGACY_SHADER, + + D3D_BLOB_XNA_PREPASS_SHADER, + + D3D_BLOB_XNA_SHADER, + + D3D_BLOB_PDB, + + D3D_BLOB_PRIVATE_DATA, + + D3D_BLOB_ROOT_SIGNATURE, + + D3D_BLOB_DEBUG_NAME, + + D3D_BLOB_TEST_ALTERNATE_SHADER = 0x8000, + + D3D_BLOB_TEST_COMPILE_DETAILS, + + D3D_BLOB_TEST_COMPILE_PERF, + + D3D_BLOB_TEST_COMPILE_REPORT, + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3dcompiler/DirectX.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3dcompiler/DirectX.cs new file mode 100644 index 00000000..ba483f7e --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3dcompiler/DirectX.cs @@ -0,0 +1,23 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d3dcompiler.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.Runtime.InteropServices; +using TerraFX.Interop.Windows; + +namespace TerraFX.Interop.DirectX +{ + internal static unsafe partial class DirectX + { + [DllImport("d3dcompiler_47", ExactSpelling = true)] + public static extern HRESULT D3DCompile([NativeTypeName("LPCVOID")] void* pSrcData, [NativeTypeName("SIZE_T")] nuint SrcDataSize, [NativeTypeName("LPCSTR")] sbyte* pSourceName, [NativeTypeName("const D3D_SHADER_MACRO *")] D3D_SHADER_MACRO* pDefines, [NativeTypeName("const ID3DInclude *")] void* pInclude, [NativeTypeName("LPCSTR")] sbyte* pEntrypoint, [NativeTypeName("LPCSTR")] sbyte* pTarget, uint Flags1, uint Flags2, ID3DBlob** ppCode, ID3DBlob** ppErrorMsgs); + + [DllImport("d3dcompiler_47", ExactSpelling = true)] + public static extern HRESULT D3DReflect([NativeTypeName("LPCVOID")] void* pSrcData, [NativeTypeName("SIZE_T")] nuint SrcDataSize, [NativeTypeName("const IID &")] Guid* pInterface, void** ppReflector); + + [DllImport("d3dcompiler_47", ExactSpelling = true)] + public static extern HRESULT D3DSetBlobPart([NativeTypeName("LPCVOID")] void* pSrcData, [NativeTypeName("SIZE_T")] nuint SrcDataSize, D3D_BLOB_PART Part, uint Flags, [NativeTypeName("LPCVOID")] void* pPart, [NativeTypeName("SIZE_T")] nuint PartSize, ID3DBlob** ppNewShader); + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems b/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems new file mode 100644 index 00000000..942865b5 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems @@ -0,0 +1,53 @@ + + + + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) + true + 9da1da9f-f8b2-4b25-be80-c21f773029e3 + + + TerraFX.Interop.Windows.D2D1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.shproj b/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.shproj new file mode 100644 index 00000000..4ebe595b --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.shproj @@ -0,0 +1,13 @@ + + + + 9da1da9f-f8b2-4b25-be80-c21f773029e3 + 14.0 + + + + + + + + diff --git a/src/TerraFX.Interop.Windows.D2D1/Windows/shared/uuids/Windows.Manual.cs b/src/TerraFX.Interop.Windows.D2D1/Windows/shared/uuids/Windows.Manual.cs new file mode 100644 index 00000000..d8316436 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/Windows/shared/uuids/Windows.Manual.cs @@ -0,0 +1,90 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from shared/uuids.h in the Windows SDK for Windows 10.0.20348.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; +#if NET6_0_OR_GREATER +using RuntimeHelpers = System.Runtime.CompilerServices.RuntimeHelpers; +#else +using RuntimeHelpers = ComputeSharp.D2D1.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +#endif + +namespace TerraFX.Interop.Windows +{ + internal static partial class Windows + { + /// Retrieves the GUID of of a specified type. + /// A value of type . + /// The type to retrieve the GUID for. + /// A value wrapping a pointer to the GUID data for the input type. This value can be either converted to a pointer, or implicitly assigned to a value. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe UuidOfType __uuidof(T value) // for type inference similar to C++'s __uuidof + where T : unmanaged + { + return new UuidOfType(UUID.RIID); + } + + /// Retrieves the GUID of of a specified type. + /// A pointer to a value of type . + /// The type to retrieve the GUID for. + /// A value wrapping a pointer to the GUID data for the input type. This value can be either converted to a pointer, or implicitly assigned to a value. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe UuidOfType __uuidof(T* value) // for type inference similar to C++'s __uuidof + where T : unmanaged + { + return new UuidOfType(UUID.RIID); + } + + /// Retrieves the GUID of of a specified type. + /// The type to retrieve the GUID for. + /// A value wrapping a pointer to the GUID data for the input type. This value can be either converted to a pointer, or implicitly assigned to a value. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe UuidOfType __uuidof() + where T : unmanaged + { + return new UuidOfType(UUID.RIID); + } + + /// A proxy type that wraps a pointer to GUID data. Values of this type can be implicitly converted to and assigned to * or parameters. + [EditorBrowsable(EditorBrowsableState.Never)] + public readonly unsafe ref struct UuidOfType + { + private readonly Guid* riid; + + internal UuidOfType(Guid* riid) + { + this.riid = riid; + } + + /// Reads a value from the GUID buffer for a given instance. + /// The input instance to read data for. + public static implicit operator Guid(UuidOfType guid) => *guid.riid; + + /// Returns the * pointer to the GUID buffer for a given instance. + /// The input instance to read data for. + public static implicit operator Guid*(UuidOfType guid) => guid.riid; + } + + /// A helper type to provide static GUID buffers for specific types. + /// The type to allocate a GUID buffer for. + private static unsafe class UUID + where T : unmanaged + { + /// The pointer to the value for the current type. + /// The target memory area should never be written to. + public static readonly Guid* RIID = CreateRIID(); + + /// Allocates memory for a value and initializes it. + /// A pointer to memory holding the value for the current type. + private static Guid* CreateRIID() + { + var p = (Guid*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(T), sizeof(Guid)); + *p = typeof(T).GUID; + return p; + } + } + } +} diff --git a/src/TerraFX.Interop.Windows.D2D1/Windows/shared/windef/RECT.cs b/src/TerraFX.Interop.Windows.D2D1/Windows/shared/windef/RECT.cs new file mode 100644 index 00000000..614ff8b9 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/Windows/shared/windef/RECT.cs @@ -0,0 +1,24 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from shared/windef.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +#pragma warning disable CS0649 + +namespace TerraFX.Interop.Windows +{ + internal struct RECT + { + [NativeTypeName("LONG")] + public int left; + + [NativeTypeName("LONG")] + public int top; + + [NativeTypeName("LONG")] + public int right; + + [NativeTypeName("LONG")] + public int bottom; + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/E.cs b/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/E.cs new file mode 100644 index 00000000..83bdfaaa --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/E.cs @@ -0,0 +1,22 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from shared/winerror.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +namespace TerraFX.Interop.Windows +{ + internal static class E + { + [NativeTypeName("#define E_NOTIMPL _HRESULT_TYPEDEF_(0x80004001L)")] + public const int E_NOTIMPL = unchecked((int)(0x80004001)); + + [NativeTypeName("#define E_INVALIDARG _HRESULT_TYPEDEF_(0x80070057L)")] + public const int E_INVALIDARG = unchecked((int)(0x80070057)); + + [NativeTypeName("#define E_NOINTERFACE _HRESULT_TYPEDEF_(0x80004002L)")] + public const int E_NOINTERFACE = unchecked((int)(0x80004002)); + + [NativeTypeName("#define E_POINTER _HRESULT_TYPEDEF_(0x80004003L)")] + public const int E_POINTER = unchecked((int)(0x80004003)); + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/Windows.cs b/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/Windows.cs new file mode 100644 index 00000000..b02c142b --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/Windows.cs @@ -0,0 +1,15 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from shared/winerror.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +namespace TerraFX.Interop.Windows +{ + internal static partial class Windows + { + public static bool SUCCEEDED(HRESULT hr) + { + return hr >= 0; + } + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows/DirectX/um/d3d11shader/D3D.cs b/src/TerraFX.Interop.Windows/DirectX/um/d3d11shader/D3D.cs index 1bb7a5a9..2f63108a 100644 --- a/src/TerraFX.Interop.Windows/DirectX/um/d3d11shader/D3D.cs +++ b/src/TerraFX.Interop.Windows/DirectX/um/d3d11shader/D3D.cs @@ -5,7 +5,7 @@ namespace TerraFX.Interop.DirectX { - public static partial class D3D + internal static partial class D3D { [NativeTypeName("#define D3D_SHADER_REQUIRES_DOUBLES 0x00000001")] public const int D3D_SHADER_REQUIRES_DOUBLES = 0x00000001; diff --git a/src/TerraFX.Interop.Windows/DirectX/um/d3dcommon/ID3DBlob.cs b/src/TerraFX.Interop.Windows/DirectX/um/d3dcommon/ID3DBlob.cs index d4f4c705..5eebe81e 100644 --- a/src/TerraFX.Interop.Windows/DirectX/um/d3dcommon/ID3DBlob.cs +++ b/src/TerraFX.Interop.Windows/DirectX/um/d3dcommon/ID3DBlob.cs @@ -8,6 +8,8 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using TerraFX.Interop.Windows; +#pragma warning disable CS0649 + namespace TerraFX.Interop.DirectX { [Guid("8BA5FB08-5195-40E2-AC58-0D989C3A0102")] diff --git a/src/TerraFX.Interop.Windows/Windows/um/Unknwnbase/IUnknown.cs b/src/TerraFX.Interop.Windows/Windows/um/Unknwnbase/IUnknown.cs index f5226076..10af550b 100644 --- a/src/TerraFX.Interop.Windows/Windows/um/Unknwnbase/IUnknown.cs +++ b/src/TerraFX.Interop.Windows/Windows/um/Unknwnbase/IUnknown.cs @@ -7,6 +7,8 @@ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +#pragma warning disable CS0649 + namespace TerraFX.Interop.Windows { [Guid("00000000-0000-0000-C000-000000000046")] diff --git a/tests/ComputeSharp.D2D1.Tests/Assets/Landscape.png b/tests/ComputeSharp.D2D1.Tests/Assets/Landscape.png new file mode 100644 index 00000000..7a09dc6d Binary files /dev/null and b/tests/ComputeSharp.D2D1.Tests/Assets/Landscape.png differ diff --git a/tests/ComputeSharp.D2D1.Tests/Assets/Landscape_Inverted.png b/tests/ComputeSharp.D2D1.Tests/Assets/Landscape_Inverted.png new file mode 100644 index 00000000..966ba3a4 Binary files /dev/null and b/tests/ComputeSharp.D2D1.Tests/Assets/Landscape_Inverted.png differ diff --git a/tests/ComputeSharp.D2D1.Tests/Assets/Landscape_Pixelate.png b/tests/ComputeSharp.D2D1.Tests/Assets/Landscape_Pixelate.png new file mode 100644 index 00000000..eac0297f Binary files /dev/null and b/tests/ComputeSharp.D2D1.Tests/Assets/Landscape_Pixelate.png differ diff --git a/tests/ComputeSharp.D2D1.Tests/Assets/ZonePlate.png b/tests/ComputeSharp.D2D1.Tests/Assets/ZonePlate.png new file mode 100644 index 00000000..3971ea5f Binary files /dev/null and b/tests/ComputeSharp.D2D1.Tests/Assets/ZonePlate.png differ diff --git a/tests/ComputeSharp.D2D1.Tests/ComputeSharp.D2D1.Tests.csproj b/tests/ComputeSharp.D2D1.Tests/ComputeSharp.D2D1.Tests.csproj new file mode 100644 index 00000000..5816c386 --- /dev/null +++ b/tests/ComputeSharp.D2D1.Tests/ComputeSharp.D2D1.Tests.csproj @@ -0,0 +1,43 @@ + + + + net6.0 + false + $(NoWarn);CS0419;CA1416 + + + + + + + + + + + + + + + + + + + + + + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + + diff --git a/tests/ComputeSharp.D2D1.Tests/Effects/InvertEffect.cs b/tests/ComputeSharp.D2D1.Tests/Effects/InvertEffect.cs new file mode 100644 index 00000000..14faec33 --- /dev/null +++ b/tests/ComputeSharp.D2D1.Tests/Effects/InvertEffect.cs @@ -0,0 +1,19 @@ +namespace ComputeSharp.D2D1.Tests.Effects; + +[D2DInputCount(1)] +[D2DInputSimple(0)] +[D2DEmbeddedBytecode(D2D1ShaderProfile.PixelShader50)] +[AutoConstructor] +public partial struct InvertEffect : ID2D1PixelShader +{ + public float number; + + /// + public float4 Execute() + { + float4 color = D2D.GetInput(0); + float3 rgb = Hlsl.Saturate(this.number - color.RGB); + + return new(rgb, 1); + } +} diff --git a/tests/ComputeSharp.D2D1.Tests/Effects/PixelateEffect.cs b/tests/ComputeSharp.D2D1.Tests/Effects/PixelateEffect.cs new file mode 100644 index 00000000..4a79dec9 --- /dev/null +++ b/tests/ComputeSharp.D2D1.Tests/Effects/PixelateEffect.cs @@ -0,0 +1,69 @@ +using System; +using System.Drawing; + +namespace ComputeSharp.D2D1.Tests.Effects; + +public sealed partial class PixelateEffect : ID2D1TransformMapper +{ + /// + void ID2D1TransformMapper.MapInputsToOutput(in Shader shader, ReadOnlySpan inputs, ReadOnlySpan opaqueInputs, out Rectangle output, out Rectangle opaqueOutput) + { + output = inputs[0]; + opaqueOutput = Rectangle.Empty; + } + + /// + void ID2D1TransformMapper.MapInvalidOutput(in Shader shader, int inputIndex, Rectangle invalidInput, out Rectangle invalidOutput) + { + invalidOutput = invalidInput; + } + + /// + void ID2D1TransformMapper.MapOutputToInputs(in Shader shader, in Rectangle output, Span inputs) + { + inputs.Fill(output); + } + + [D2DInputCount(1)] + [D2DInputComplex(0)] + [D2DRequiresScenePosition] + [D2DEmbeddedBytecode(D2D1ShaderProfile.PixelShader40)] + [AutoConstructor] + public partial struct Shader : ID2D1PixelShader + { + [AutoConstructor] + public partial struct Constants + { + public readonly int inputWidth; + public readonly int inputHeight; + public readonly int cellSize; + } + + private readonly Constants constants; + + public float4 Execute() + { + float2 scenePos = D2D.GetScenePosition().XY; + uint x = (uint)Hlsl.Floor(scenePos.X); + uint y = (uint)Hlsl.Floor(scenePos.Y); + + int cellX = (int)Hlsl.Floor(x / this.constants.cellSize); + int cellY = (int)Hlsl.Floor(y / this.constants.cellSize); + + int x0 = cellX * this.constants.cellSize; + int y0 = cellY * this.constants.cellSize; + + int x1 = Hlsl.Min(this.constants.inputWidth, x0 + this.constants.cellSize) - 1; + int y1 = Hlsl.Min(this.constants.inputHeight, y0 + this.constants.cellSize) - 1; + + float4 sample0 = D2D.SampleInputAtPosition(0, new int2(x0, y0)); + float4 sample1 = D2D.SampleInputAtPosition(0, new int2(x1, y0)); + float4 sample2 = D2D.SampleInputAtPosition(0, new int2(x0, y1)); + float4 sample3 = D2D.SampleInputAtPosition(0, new int2(x1, y1)); + + float4 color = (sample0 + sample1 + sample2 + sample3) / 4; + + return color; + } + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.Tests/Effects/ZonePlateEffect.cs b/tests/ComputeSharp.D2D1.Tests/Effects/ZonePlateEffect.cs new file mode 100644 index 00000000..bff94d85 --- /dev/null +++ b/tests/ComputeSharp.D2D1.Tests/Effects/ZonePlateEffect.cs @@ -0,0 +1,34 @@ +using System; + +namespace ComputeSharp.D2D1.Tests.Effects; + +[D2DInputCount(0)] +[D2DRequiresScenePosition] +[D2DEmbeddedBytecode(D2D1ShaderProfile.PixelShader50)] +[AutoConstructor] +public readonly partial struct ZonePlateEffect : ID2D1PixelShader +{ + private readonly int width; + private readonly int height; + private readonly float diameter; + + /// + public float4 Execute() + { + float2 scenePos = D2D.GetScenePosition().XY; + + float xo = scenePos.X - (this.width >> 1); + float yo = scenePos.Y - (this.height >> 1); + + float rm = 0.5f * this.diameter; + float km = 0.7f / this.diameter * MathF.PI; + float w = rm / 10.0f; + + float yd = yo * yo; + float xd = xo * xo; + float d = xd + yd; + float v = 1.0f + (1.0f + Hlsl.Tanh((rm - Hlsl.Sqrt(d)) / w)) * Hlsl.Sin(km * d) * 0.5f; + + return new Float4(v, v, v, 1.0f); + } +} diff --git a/tests/ComputeSharp.D2D1.Tests/EndToEndTests.cs b/tests/ComputeSharp.D2D1.Tests/EndToEndTests.cs new file mode 100644 index 00000000..851d4e07 --- /dev/null +++ b/tests/ComputeSharp.D2D1.Tests/EndToEndTests.cs @@ -0,0 +1,113 @@ +using System; +using System.IO; +using System.Reflection; +using System.Runtime.CompilerServices; +using ComputeSharp.D2D1.Tests.Effects; +using ComputeSharp.D2D1.Tests.Helpers; +using ComputeSharp.Tests.Helpers; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.D2D1.Tests; + +[TestClass] +[TestCategory("EndToEnd")] +public class EndToEndTests +{ + [TestMethod] + public unsafe void InvertWithCustomThreshold() + { + RunAndCompareShader(new InvertEffect(1), null, "Landscape.png", "Landscape_Inverted.png"); + } + + [TestMethod] + public unsafe void Pixelate() + { + RunAndCompareShader( + new PixelateEffect.Shader(new PixelateEffect.Shader.Constants(1280, 720, 16)), + static () => new PixelateEffect(), + "Landscape.png", + "Landscape_Pixelate.png"); + } + + [TestMethod] + public unsafe void ZonePlate() + { + RunAndCompareShader(new ZonePlateEffect(1280, 720, 800), null, 1280, 720, "ZonePlate.png"); + } + + /// + /// Executes a pixel shader and compares the expected results. + /// + /// The type of pixel shader to run. + /// A custom factory for the effect. + /// The name of the source image. + /// The name of the expected result image. + /// The name of the destination image to save results to. + /// The shader to run. + private static void RunAndCompareShader( + in T shader, + Func>? transformMapperFactory, + string originalFileName, + string expectedFileName, + [CallerMemberName] string destinationFileName = "") + where T : unmanaged, ID2D1PixelShader + { + string assetsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets"); + string temporaryPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "temp"); + + _ = Directory.CreateDirectory(temporaryPath); + + string originalPath = Path.Combine(assetsPath, originalFileName); + string expectedPath = Path.Combine(assetsPath, expectedFileName); + string destinationPath = Path.Combine(temporaryPath, $"{destinationFileName}.png"); + + // Run the shader + D2D1TestRunner.ExecutePixelShaderAndCompareResults( + in shader, + transformMapperFactory, + originalPath, + destinationPath); + + // Compare the results + TolerantImageComparer.AssertEqual(destinationPath, expectedPath, 0.00001f); + } + + /// + /// Executes a pixel shader and compares the expected results. + /// + /// The type of pixel shader to run. + /// A custom factory for the effect. + /// The resulting width. + /// The resulting height. + /// The name of the expected result image. + /// The name of the destination image to save results to. + /// The shader to run. + private static void RunAndCompareShader( + in T shader, + Func>? transformMapperFactory, + int width, + int height, + string expectedFileName, + [CallerMemberName] string destinationFileName = "") + where T : unmanaged, ID2D1PixelShader + { + string assetsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets"); + string temporaryPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "temp"); + + _ = Directory.CreateDirectory(temporaryPath); + + string expectedPath = Path.Combine(assetsPath, expectedFileName); + string destinationPath = Path.Combine(temporaryPath, $"{destinationFileName}.png"); + + // Run the shader + D2D1TestRunner.ExecutePixelShaderAndCompareResults( + in shader, + transformMapperFactory, + width, + height, + destinationPath); + + // Compare the results + TolerantImageComparer.AssertEqual(destinationPath, expectedPath, 0.00001f); + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.Tests/Extensions/ComPtrExtensions.cs b/tests/ComputeSharp.D2D1.Tests/Extensions/ComPtrExtensions.cs new file mode 100644 index 00000000..27904fb6 --- /dev/null +++ b/tests/ComputeSharp.D2D1.Tests/Extensions/ComPtrExtensions.cs @@ -0,0 +1,28 @@ +using System.Runtime.CompilerServices; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.D2D1.Tests.Extensions; + +/// +/// Helper methods for working with the type. +/// +/// Trimmed down version of the same file in ComputeSharp. +internal static class ComPtrExtensions +{ + /// + /// Moves the current instance and resets it without releasing the reference. + /// + /// The type to wrap in the current instance. + /// The input instance to move. + /// The moved instance. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe ComPtr Move(this in ComPtr ptr) + where T : unmanaged, IUnknown.Interface + { + ComPtr copy = default; + + Unsafe.AsRef(in ptr).Swap(ref copy); + + return copy; + } +} diff --git a/tests/ComputeSharp.D2D1.Tests/Extensions/HResultExtensions.cs b/tests/ComputeSharp.D2D1.Tests/Extensions/HResultExtensions.cs new file mode 100644 index 00000000..c0d233a6 --- /dev/null +++ b/tests/ComputeSharp.D2D1.Tests/Extensions/HResultExtensions.cs @@ -0,0 +1,53 @@ +using System.ComponentModel; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.D2D1.Tests.Extensions; + +/// +/// Helper methods to efficiently throw exceptions. +/// +/// Trimmed down version of the same file in ComputeSharp. +[DebuggerStepThrough] +internal static class HResultExtensions +{ + /// + /// Throws a if represents an error. + /// + /// The input to check. + /// Thrown if represents an error. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Assert(this HRESULT result) + { + if ((int)result < 0) + { + ThrowWin32Exception(result); + } + } + + /// + /// Throws a if represents an error. + /// + /// The input to check. + /// Thrown if represents an error. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Assert(this int result) + { + if (result < 0) + { + ThrowWin32Exception(result); + } + } + + /// + /// Throws a . + /// + /// The input return code. + [DoesNotReturn] + private static void ThrowWin32Exception(int result) + { + throw new Win32Exception(result); + } +} diff --git a/tests/ComputeSharp.D2D1.Tests/Helpers/D2D1Helper.cs b/tests/ComputeSharp.D2D1.Tests/Helpers/D2D1Helper.cs new file mode 100644 index 00000000..5a6b2ded --- /dev/null +++ b/tests/ComputeSharp.D2D1.Tests/Helpers/D2D1Helper.cs @@ -0,0 +1,220 @@ +using ComputeSharp.D2D1.Tests.Extensions; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.D2D1.Tests.Helpers; + +/// +/// A that uses the D2D1 APIs to configure and run effects. +/// +internal static class D2D1Helper +{ + /// + /// Creates an instance. + /// + /// A new instance. + public static unsafe ComPtr CreateD2D1Factory2() + { + using ComPtr d2D1Factory2 = default; + + D2D1_FACTORY_OPTIONS d2D1FactoryOptions = default; + + // Create a Direct2D factory + DirectX.D2D1CreateFactory( + factoryType: D2D1_FACTORY_TYPE.D2D1_FACTORY_TYPE_SINGLE_THREADED, + riid: Windows.__uuidof(), + pFactoryOptions: &d2D1FactoryOptions, + ppIFactory: (void**)d2D1Factory2.GetAddressOf()).Assert(); + + return d2D1Factory2.Move(); + } + + /// + /// Creates an instance. + /// + /// The input instance to use to create the device. + /// A new instance. + public static unsafe ComPtr CreateD2D1Device(ID2D1Factory2* d2D1Factory2) + { + using ComPtr d3D11Device = default; + + uint creationFlags = (uint)D3D11_CREATE_DEVICE_FLAG.D3D11_CREATE_DEVICE_BGRA_SUPPORT; + D3D_FEATURE_LEVEL* featureLevels = stackalloc[] + { + D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_11_1, + D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_11_0, + D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_10_1, + D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_10_0, + D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_9_3, + D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_9_2, + D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_9_1 + }; + D3D_FEATURE_LEVEL d3DFeatureLevel; + + // Create the Direct3D 11 API device and context + DirectX.D3D11CreateDevice( + pAdapter: null, + DriverType: D3D_DRIVER_TYPE.D3D_DRIVER_TYPE_HARDWARE, + Software: HMODULE.NULL, + Flags: creationFlags, + pFeatureLevels: featureLevels, + FeatureLevels: 7, + SDKVersion: D3D11.D3D11_SDK_VERSION, + ppDevice: d3D11Device.GetAddressOf(), + pFeatureLevel: &d3DFeatureLevel, + ppImmediateContext: null).Assert(); + + using ComPtr dxgiDevice3 = default; + + // Get a DXGI device from the D3D11 device + d3D11Device.CopyTo(dxgiDevice3.GetAddressOf()).Assert(); + + using ComPtr d2D1Device = default; + + // Create a D2D1 device + d2D1Factory2->CreateDevice( + dxgiDevice: (IDXGIDevice*)dxgiDevice3.Get(), + d2dDevice: d2D1Device.GetAddressOf()); + + return d2D1Device.Move(); + } + + /// + /// Creates an instance. + /// + /// The input instance to use to create the context. + /// A new instance. + public static unsafe ComPtr CreateD2D1DeviceContext(ID2D1Device* d2D1Device) + { + using ComPtr d2D1DeviceContext = default; + + // Create a D2D1 device context + d2D1Device->CreateDeviceContext( + options: D2D1_DEVICE_CONTEXT_OPTIONS.D2D1_DEVICE_CONTEXT_OPTIONS_NONE, + deviceContext: d2D1DeviceContext.GetAddressOf()).Assert(); + + return d2D1DeviceContext.Move(); + } + + /// + /// Creates an instance. + /// + /// The input instance to use to create the bitmap source. + /// The input to use to create the bitmap source. + /// The input to set the source for. + /// A new instance. + public static unsafe ComPtr CreateD2D1BitmapAndSetAsSource(ID2D1DeviceContext* d2D1DeviceContext, IWICBitmap* wicBitmap, ID2D1Effect* d2D1Effect) + { + using ComPtr d2D1BitmapSource = default; + + // Create a source D2D1 bitmap from the WIC bitmap + d2D1DeviceContext->CreateBitmapFromWicBitmap( + wicBitmapSource: (IWICBitmapSource*)wicBitmap, + bitmap: d2D1BitmapSource.GetAddressOf()).Assert(); + + d2D1Effect->SetInput(0, (ID2D1Image*)d2D1BitmapSource.Get()); + + return d2D1BitmapSource.Move(); + } + + /// + /// Creates an instance. + /// + /// The input instance to use to create the bitmap source. + /// The width of the bitmap to create. + /// The height of the bitmap to create. + /// A new instance. + public static unsafe ComPtr CreateD2D1BitmapAndSetAsTarget(ID2D1DeviceContext* d2D1DeviceContext, uint width, uint height) + { + D2D_SIZE_U d2DSize; + d2DSize.width = width; + d2DSize.height = height; + + D2D1_BITMAP_PROPERTIES1 d2DBitmapProperties1Target = default; + d2DBitmapProperties1Target.pixelFormat.format = DXGI_FORMAT.DXGI_FORMAT_B8G8R8A8_UNORM; + d2DBitmapProperties1Target.pixelFormat.alphaMode = D2D1_ALPHA_MODE.D2D1_ALPHA_MODE_PREMULTIPLIED; + d2DBitmapProperties1Target.bitmapOptions = + D2D1_BITMAP_OPTIONS.D2D1_BITMAP_OPTIONS_TARGET | + D2D1_BITMAP_OPTIONS.D2D1_BITMAP_OPTIONS_CANNOT_DRAW; + + using ComPtr d2D1Bitmap1Target = default; + + // Create a target D2D1 bitmap + d2D1DeviceContext->CreateBitmap( + size: d2DSize, + sourceData: null, + pitch: 0, + bitmapProperties: &d2DBitmapProperties1Target, + bitmap: (ID2D1Bitmap1**)d2D1Bitmap1Target.GetAddressOf()).Assert(); + + d2D1DeviceContext->SetTarget((ID2D1Image*)d2D1Bitmap1Target.Get()); + + return d2D1Bitmap1Target.Move(); + } + + /// + /// Creates an instance and copies data from a source bitmap. + /// + /// The input instance to use to create the bitmap. + /// The input to read data from. + /// The resulting for the bitmap. + /// A new instance. + public static unsafe ComPtr CreateD2D1Bitmap1Buffer(ID2D1DeviceContext* d2D1DeviceContext, ID2D1Bitmap* d2D1Bitmap, out D2D1_MAPPED_RECT d2D1MappedRect) + { + D2D_SIZE_U d2DSize = d2D1Bitmap->GetPixelSize(); + + D2D1_BITMAP_PROPERTIES1 d2DBitmapProperties1Buffer = default; + d2DBitmapProperties1Buffer.pixelFormat.format = DXGI_FORMAT.DXGI_FORMAT_B8G8R8A8_UNORM; + d2DBitmapProperties1Buffer.pixelFormat.alphaMode = D2D1_ALPHA_MODE.D2D1_ALPHA_MODE_PREMULTIPLIED; + d2DBitmapProperties1Buffer.bitmapOptions = D2D1_BITMAP_OPTIONS.D2D1_BITMAP_OPTIONS_CPU_READ | D2D1_BITMAP_OPTIONS.D2D1_BITMAP_OPTIONS_CANNOT_DRAW; + + using ComPtr d2D1Bitmap1Buffer = default; + + // Create a buffer D2D1 bitmap + d2D1DeviceContext->CreateBitmap( + size: d2DSize, + sourceData: null, + pitch: 0, + bitmapProperties: &d2DBitmapProperties1Buffer, + bitmap: d2D1Bitmap1Buffer.GetAddressOf()).Assert(); + + D2D_POINT_2U d2DPointDestination = default; + D2D_RECT_U d2DRectSource = new(0, 0, d2DSize.width, d2DSize.height); + + // Copy the image from the target to the readback bitmap + d2D1Bitmap1Buffer.Get()->CopyFromBitmap( + destPoint: &d2DPointDestination, + bitmap: d2D1Bitmap, + srcRect: &d2DRectSource); + + fixed (D2D1_MAPPED_RECT* d2D1MappedRectPtr = &d2D1MappedRect) + { + // Map the buffer bitmap + d2D1Bitmap1Buffer.Get()->Map( + options: D2D1_MAP_OPTIONS.D2D1_MAP_OPTIONS_READ, + mappedRect: d2D1MappedRectPtr).Assert(); + } + + return d2D1Bitmap1Buffer.Move(); + } + + /// + /// Draws a given effect onto a context. + /// + /// The input instance to use to draw the effect. + /// The input to draw. + public static unsafe void DrawEffect(ID2D1DeviceContext* d2D1DeviceContext, ID2D1Effect* d2D1Effect) + { + d2D1DeviceContext->BeginDraw(); + + // Draw the image with the effect + d2D1DeviceContext->DrawImage( + effect: d2D1Effect, + targetOffset: null, + imageRectangle: null, + interpolationMode: D2D1_INTERPOLATION_MODE.D2D1_INTERPOLATION_MODE_NEAREST_NEIGHBOR, + compositeMode: D2D1_COMPOSITE_MODE.D2D1_COMPOSITE_MODE_SOURCE_COPY); + + d2D1DeviceContext->EndDraw().Assert(); + } +} diff --git a/tests/ComputeSharp.D2D1.Tests/Helpers/D2D1TestRunner.cs b/tests/ComputeSharp.D2D1.Tests/Helpers/D2D1TestRunner.cs new file mode 100644 index 00000000..65de58db --- /dev/null +++ b/tests/ComputeSharp.D2D1.Tests/Helpers/D2D1TestRunner.cs @@ -0,0 +1,90 @@ +using System; +using ComputeSharp.D2D1.Interop; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.D2D1.Tests.Helpers; + +/// +/// A test helper for D2D1 pixel shaders. +/// +internal static class D2D1TestRunner +{ + /// + /// Executes a pixel shader to produce an image. + /// + /// The shader type to execute. + /// The shader to run. + /// A custom factory for the effect. + /// The source path for the image to run the shader on. + /// The destination path for the result. + public static unsafe void ExecutePixelShaderAndCompareResults( + in T shader, + Func>? transformMapperFactory, + string sourcePath, + string destinationPath) + where T : unmanaged, ID2D1PixelShader + { + using ComPtr d2D1Factory2 = D2D1Helper.CreateD2D1Factory2(); + using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); + using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); + + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), transformMapperFactory, out _); + + using ComPtr d2D1Effect = default; + + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf()); + + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in shader, d2D1Effect.Get()); + + using ComPtr wicBitmap = WICHelper.LoadBitmapFromFile(sourcePath, out uint width, out uint height); + using ComPtr d2D1BitmapSource = D2D1Helper.CreateD2D1BitmapAndSetAsSource(d2D1DeviceContext.Get(), wicBitmap.Get(), d2D1Effect.Get()); + using ComPtr d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), width, height); + + D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get()); + + using ComPtr d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect); + + // Save the image + WICHelper.SaveBitmapToFile(destinationPath, width, height, d2D1MappedRect.pitch, d2D1MappedRect.bits); + } + + /// + /// Executes a pixel shader to produce an image. + /// + /// The shader type to execute. + /// The shader to run. + /// The resulting width. + /// The resulting height. + /// A custom factory for the effect. + /// The destination path for the result. + public static unsafe void ExecutePixelShaderAndCompareResults( + in T shader, + Func>? transformMapperFactory, + int width, + int height, + string destinationPath) + where T : unmanaged, ID2D1PixelShader + { + using ComPtr d2D1Factory2 = D2D1Helper.CreateD2D1Factory2(); + using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); + using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); + + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), transformMapperFactory, out _); + + using ComPtr d2D1Effect = default; + + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf()); + + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in shader, d2D1Effect.Get()); + + using ComPtr d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), (uint)width, (uint)height); + + D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get()); + + using ComPtr d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect); + + // Save the image + WICHelper.SaveBitmapToFile(destinationPath, (uint)width, (uint)height, d2D1MappedRect.pitch, d2D1MappedRect.bits); + } +} diff --git a/tests/ComputeSharp.D2D1.Tests/Helpers/WICHelper.cs b/tests/ComputeSharp.D2D1.Tests/Helpers/WICHelper.cs new file mode 100644 index 00000000..34b2e0af --- /dev/null +++ b/tests/ComputeSharp.D2D1.Tests/Helpers/WICHelper.cs @@ -0,0 +1,203 @@ +using System; +using System.Runtime.CompilerServices; +using ComputeSharp.D2D1.Tests.Extensions; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.D2D1.Tests.Helpers; + +/// +/// A that uses the WIC APIs to load and decode images. +/// +internal static class WICHelper +{ + /// + /// Loads an instance from a given path. + /// + /// The path to load the image from. + /// The resulting image width. + /// The resulting image height. + /// The resulting instance. + public static unsafe ComPtr LoadBitmapFromFile(string filename, out uint width, out uint height) + { + using ComPtr wicImagingFactory2 = default; + + // Create a Windows Imaging Component (WIC) factory + Windows.CoCreateInstance( + rclsid: (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_WICImagingFactory2)), + pUnkOuter: null, + dwClsContext: (uint)CLSCTX.CLSCTX_INPROC_SERVER, + riid: Windows.__uuidof(), + ppv: (void**)wicImagingFactory2.GetAddressOf()).Assert(); + + using ComPtr wicBitmapDecoder = default; + + // Get the bitmap decoder for the target file + fixed (char* p = filename) + { + wicImagingFactory2.Get()->CreateDecoderFromFilename( + wzFilename: (ushort*)p, + pguidVendor: null, + dwDesiredAccess: Windows.GENERIC_READ, + metadataOptions: WICDecodeOptions.WICDecodeMetadataCacheOnDemand, + ppIDecoder: wicBitmapDecoder.GetAddressOf()).Assert(); + } + + using ComPtr wicBitmapFrameDecode = default; + + // Get the first frame of the loaded image (if more are present, they will be ignored) + wicBitmapDecoder.Get()->GetFrame(0, wicBitmapFrameDecode.GetAddressOf()).Assert(); + + fixed (uint* widthPtr = &width) + fixed (uint* heightPtr = &height) + { + // Extract the image size info + wicBitmapFrameDecode.Get()->GetSize(widthPtr, heightPtr).Assert(); + } + + Guid wicTargetPixelFormatGuid = GUID.GUID_WICPixelFormat32bppPBGRA; + Guid wicActualPixelFormatGuid; + + // Get the current and target pixel format info + wicBitmapFrameDecode.Get()->GetPixelFormat(&wicActualPixelFormatGuid).Assert(); + + using ComPtr wicBitmap = default; + + // Create the target bitmap + wicImagingFactory2.Get()->CreateBitmap( + uiWidth: width, + uiHeight: height, + pixelFormat: &wicTargetPixelFormatGuid, + option: WICBitmapCreateCacheOption.WICBitmapCacheOnLoad, + ppIBitmap: wicBitmap.GetAddressOf()).Assert(); + + WICRect wicRect; + wicRect.X = 0; + wicRect.Y = 0; + wicRect.Width = (int)width; + wicRect.Height = (int)height; + + using (ComPtr wicBitmapLock = default) + { + // Lock the bitmap + wicBitmap.Get()->Lock( + prcLock: &wicRect, + flags: (uint)WICBitmapLockFlags.WICBitmapLockWrite, + ppILock: wicBitmapLock.GetAddressOf()).Assert(); + + uint wicBitmapStride; + + // Get the stride + wicBitmapLock.Get()->GetStride(&wicBitmapStride).Assert(); + + uint wicBitmapSize; + byte* wicBitmapPointer; + + // Get the bitmap size and pointer + wicBitmapLock.Get()->GetDataPointer(&wicBitmapSize, &wicBitmapPointer).Assert(); + + // Check if a pixel format conversion is needed + if (wicTargetPixelFormatGuid == wicActualPixelFormatGuid) + { + // No conversion is needed, just copy the pixels directly + wicBitmapFrameDecode.Get()->CopyPixels( + prc: &wicRect, + cbStride: wicBitmapStride, + cbBufferSize: wicBitmapSize, + pbBuffer: wicBitmapPointer).Assert(); + } + else + { + using ComPtr wicFormatConverter = default; + + // Create a format converter + wicImagingFactory2.Get()->CreateFormatConverter(wicFormatConverter.GetAddressOf()).Assert(); + + // Get a format converter to decode the pixel data + wicFormatConverter.Get()->Initialize( + pISource: (IWICBitmapSource*)wicBitmapFrameDecode.Get(), + dstFormat: &wicTargetPixelFormatGuid, + dither: WICBitmapDitherType.WICBitmapDitherTypeNone, + pIPalette: null, + alphaThresholdPercent: 0, + paletteTranslate: WICBitmapPaletteType.WICBitmapPaletteTypeCustom).Assert(); + + // Decode the pixel data into the upload buffer + wicFormatConverter.Get()->CopyPixels( + prc: &wicRect, + cbStride: wicBitmapStride, + cbBufferSize: wicBitmapSize, + pbBuffer: wicBitmapPointer).Assert(); + } + } + + return wicBitmap.Move(); + } + + /// + /// Saves a given image buffer to a target path. + /// + /// The path to save the image to. + /// The image width. + /// The image height. + /// The image stride in bytes. + /// The image pixel buffer. + public static unsafe void SaveBitmapToFile(string filename, uint width, uint height, uint strideInBytes, byte* buffer) + { + using ComPtr wicImagingFactory2 = default; + + // Create a Windows Imaging Component (WIC) factory + Windows.CoCreateInstance( + rclsid: (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_WICImagingFactory2)), + pUnkOuter: null, + dwClsContext: (uint)CLSCTX.CLSCTX_INPROC_SERVER, + riid: Windows.__uuidof(), + ppv: (void**)wicImagingFactory2.GetAddressOf()).Assert(); + + using ComPtr wicBitmapEncoder = default; + + // Create the image encoder + wicImagingFactory2.Get()->CreateEncoder( + guidContainerFormat: (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in GUID.GUID_ContainerFormatPng)), + pguidVendor: null, + ppIEncoder: wicBitmapEncoder.GetAddressOf()).Assert(); + + using ComPtr wicStream = default; + + // Create and initialize a stream to the target file + wicImagingFactory2.Get()->CreateStream(wicStream.GetAddressOf()).Assert(); + + fixed (char* p = filename) + { + // Initialize the stream to the target file + wicStream.Get()->InitializeFromFilename((ushort*)p, Windows.GENERIC_WRITE); + } + + // Initialize the encoder + wicBitmapEncoder.Get()->Initialize( + pIStream: (IStream*)wicStream.Get(), + cacheOption: WICBitmapEncoderCacheOption.WICBitmapEncoderNoCache).Assert(); + + using ComPtr wicBitmapFrameEncode = default; + + // Create the image frame and initialize it + wicBitmapEncoder.Get()->CreateNewFrame(wicBitmapFrameEncode.GetAddressOf(), null).Assert(); + + Guid wicTargetPixelFormatGuid = GUID.GUID_WICPixelFormat32bppPBGRA; + + // Set the encoding properties + wicBitmapFrameEncode.Get()->Initialize(null).Assert(); + wicBitmapFrameEncode.Get()->SetSize(width, height).Assert(); + wicBitmapFrameEncode.Get()->SetPixelFormat(&wicTargetPixelFormatGuid).Assert(); + + // Encode the target image + wicBitmapFrameEncode.Get()->WritePixels( + lineCount: height, + cbStride: strideInBytes, + cbBufferSize: strideInBytes * height, + pbPixels: buffer).Assert(); + + // Flush the changes + wicBitmapFrameEncode.Get()->Commit(); + wicBitmapEncoder.Get()->Commit(); + } +} diff --git a/tests/ComputeSharp.Tests.DisableDynamicCompilation/ComputeSharp.Tests.DisableDynamicCompilation.csproj b/tests/ComputeSharp.Tests.DisableDynamicCompilation/ComputeSharp.Tests.DisableDynamicCompilation.csproj index 7e8c771b..58e1ee6b 100644 --- a/tests/ComputeSharp.Tests.DisableDynamicCompilation/ComputeSharp.Tests.DisableDynamicCompilation.csproj +++ b/tests/ComputeSharp.Tests.DisableDynamicCompilation/ComputeSharp.Tests.DisableDynamicCompilation.csproj @@ -15,11 +15,10 @@ + + - + - - + + diff --git a/tests/ComputeSharp.Tests/Helpers/TolerantImageComparer.cs b/tests/ComputeSharp.Tests/Helpers/TolerantImageComparer.cs new file mode 100644 index 00000000..1c7c16ef --- /dev/null +++ b/tests/ComputeSharp.Tests/Helpers/TolerantImageComparer.cs @@ -0,0 +1,144 @@ +using System; +using System.Collections.Generic; +using System.Text; +using SixLabors.ImageSharp; +using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Advanced; +using System.Runtime.CompilerServices; + +namespace ComputeSharp.Tests.Helpers; + +/// +/// An tolerant image comparer type, from ImageSharp. +/// +internal static class TolerantImageComparer +{ + /// + /// Asserts that two images are equal. + /// + /// The path to the reference image. + /// The path to the expected image. + /// The allowed difference threshold for the normalized delta. + public static void AssertEqual(string expectedPath, string actualPath, float threshold) + { + using var expected = Image.Load(expectedPath); + using var actual = Image.Load(actualPath); + + AssertEqual(expected, actual, threshold); + } + + /// + /// Asserts that two images are equal. + /// + /// The type of image pixels to analyze. + /// The reference image. + /// The expected image. + /// The allowed difference threshold for the normalized delta. + public static void AssertEqual(Image expected, Image actual, float threshold) + where TPixel : unmanaged, IPixel + { + if (expected.Size() != actual.Size()) + { + Assert.Fail($"The input images have different sizes: {expected.Size()} and {actual.Size()}"); + } + + if (expected.Frames.Count != actual.Frames.Count || + expected.Frames.Count != 1 || + actual.Frames.Count != 1) + { + Assert.Fail("The two input images must have 1 frame each"); + } + + int width = actual.Width; + + float totalDifference = 0F; + + var differences = new List(20); + Span aBuffer = new ImageSharpRgba32[actual.Width]; + Span bBuffer = new ImageSharpRgba32[actual.Width]; + + for (int y = 0; y < actual.Height; y++) + { + Span aSpan = expected.GetPixelRowSpan(y); + Span bSpan = actual.GetPixelRowSpan(y); + + PixelOperations.Instance.ToRgba32(actual.GetConfiguration(), aSpan, aBuffer); + PixelOperations.Instance.ToRgba32(actual.GetConfiguration(), bSpan, bBuffer); + + for (int x = 0; x < width; x++) + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static int GetManhattanDistanceInRgbaSpace(ref ImageSharpRgba32 a, ref ImageSharpRgba32 b) + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static int Diff(ushort a, ushort b) => Math.Abs(a - b); + + return Diff(a.R, b.R) + Diff(a.G, b.G) + Diff(a.B, b.B) + Diff(a.A, b.A); + } + + int d = GetManhattanDistanceInRgbaSpace(ref aBuffer[x], ref bBuffer[x]); + + if (d > 0) + { + if (differences.Count < 20) + { + var diff = new PixelDifference(new Point(x, y), aBuffer[x], bBuffer[x]); + differences.Add(diff); + } + + totalDifference += d; + } + } + } + + float normalizedDifference = totalDifference / (actual.Width * (float)actual.Height); + normalizedDifference /= 4F * 65535F; + + if (normalizedDifference > threshold) + { + StringBuilder builder = new(); + builder.AppendLine($"The input images don't match. Normalized delta: {normalizedDifference}%"); + builder.AppendLine($"First {differences.Count} pixel deltas:"); + + foreach (var delta in differences) + { + builder.AppendLine(delta.ToString()); + } + + Assert.Fail(builder.ToString()); + } + } + + /// + /// A simple model repressenting info about a difference between two pixels. + /// + private readonly struct PixelDifference + { + public PixelDifference(Point position, ImageSharpRgba32 expected, ImageSharpRgba32 actual) + { + this.Position = position; + this.RedDifference = actual.R - expected.R; + this.GreenDifference = actual.G - expected.G; + this.BlueDifference = actual.B - expected.B; + this.AlphaDifference = actual.A - expected.A; + } + + public readonly Point Position; + + public readonly int RedDifference; + + public readonly int GreenDifference; + + public readonly int BlueDifference; + + public readonly int AlphaDifference; + + /// + public override string ToString() + { + return $"[delta({RedDifference},{GreenDifference},{BlueDifference},{AlphaDifference}) @ ({Position.X},{Position.Y})]"; + } + } +} diff --git a/tests/ComputeSharp.Tests/ImageProcessingTests.cs b/tests/ComputeSharp.Tests/ImageProcessingTests.cs index 3399defc..99c6e5b1 100644 --- a/tests/ComputeSharp.Tests/ImageProcessingTests.cs +++ b/tests/ComputeSharp.Tests/ImageProcessingTests.cs @@ -3,6 +3,7 @@ using System.Reflection; using ComputeSharp.BokehBlur.Processors; using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; +using ComputeSharp.Tests.Helpers; using Microsoft.VisualStudio.TestTools.UnitTesting; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Processing; @@ -37,7 +38,7 @@ public class ImageProcessingTests cpu.Save(expectedPath); gpu.Save(actualPath); - ImagingTests.TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.000009f); + TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.000009f); } [CombinatorialTestMethod] @@ -61,6 +62,6 @@ public class ImageProcessingTests cpu.Save(expectedPath); gpu.Save(actualPath); - ImagingTests.TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.0000046f); + TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.0000046f); } } diff --git a/tests/ComputeSharp.Tests/ImagingTests.cs b/tests/ComputeSharp.Tests/ImagingTests.cs index e301aa2d..75849c9a 100644 --- a/tests/ComputeSharp.Tests/ImagingTests.cs +++ b/tests/ComputeSharp.Tests/ImagingTests.cs @@ -1,21 +1,17 @@ using System; using System.Buffers; -using System.Collections.Generic; using System.IO; using System.Reflection; -using System.Runtime.CompilerServices; -using System.Text; using CommunityToolkit.HighPerformance.Buffers; using ComputeSharp.Resources; using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; using SixLabors.ImageSharp; -using SixLabors.ImageSharp.Advanced; -using SixLabors.ImageSharp.PixelFormats; using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; using ImageSharpBgra32 = SixLabors.ImageSharp.PixelFormats.Bgra32; using ImageSharpL8 = SixLabors.ImageSharp.PixelFormats.L8; +using ComputeSharp.Tests.Helpers; namespace ComputeSharp.Tests; @@ -530,137 +526,4 @@ public class ImagingTests texture.Save(typeof(string), null!); } - - /// - /// An tolerant image comparer type, from ImageSharp. - /// - internal static class TolerantImageComparer - { - /// - /// Asserts that two images are equal. - /// - /// The path to the reference image. - /// The path to the expected image. - /// The allowed difference threshold for the normalized delta. - public static void AssertEqual(string expectedPath, string actualPath, float threshold) - { - using var expected = Image.Load(expectedPath); - using var actual = Image.Load(actualPath); - - AssertEqual(expected, actual, threshold); - } - - /// - /// Asserts that two images are equal. - /// - /// The type of image pixels to analyze. - /// The reference image. - /// The expected image. - /// The allowed difference threshold for the normalized delta. - public static void AssertEqual(Image expected, Image actual, float threshold) - where TPixel : unmanaged, IPixel - { - if (expected.Size() != actual.Size()) - { - Assert.Fail($"The input images have different sizes: {expected.Size()} and {actual.Size()}"); - } - - if (expected.Frames.Count != actual.Frames.Count || - expected.Frames.Count != 1 || - actual.Frames.Count != 1) - { - Assert.Fail("The two input images must have 1 frame each"); - } - - int width = actual.Width; - - float totalDifference = 0F; - - var differences = new List(20); - Span aBuffer = new ImageSharpRgba32[actual.Width]; - Span bBuffer = new ImageSharpRgba32[actual.Width]; - - for (int y = 0; y < actual.Height; y++) - { - Span aSpan = expected.GetPixelRowSpan(y); - Span bSpan = actual.GetPixelRowSpan(y); - - PixelOperations.Instance.ToRgba32(actual.GetConfiguration(), aSpan, aBuffer); - PixelOperations.Instance.ToRgba32(actual.GetConfiguration(), bSpan, bBuffer); - - for (int x = 0; x < width; x++) - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - static int GetManhattanDistanceInRgbaSpace(ref ImageSharpRgba32 a, ref ImageSharpRgba32 b) - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - static int Diff(ushort a, ushort b) => Math.Abs(a - b); - - return Diff(a.R, b.R) + Diff(a.G, b.G) + Diff(a.B, b.B) + Diff(a.A, b.A); - } - - int d = GetManhattanDistanceInRgbaSpace(ref aBuffer[x], ref bBuffer[x]); - - if (d > 0) - { - if (differences.Count < 20) - { - var diff = new PixelDifference(new Point(x, y), aBuffer[x], bBuffer[x]); - differences.Add(diff); - } - - totalDifference += d; - } - } - } - - float normalizedDifference = totalDifference / (actual.Width * (float)actual.Height); - normalizedDifference /= 4F * 65535F; - - if (normalizedDifference > threshold) - { - StringBuilder builder = new(); - builder.AppendLine($"The input images don't match. Normalized delta: {normalizedDifference}%"); - builder.AppendLine($"First {differences.Count} pixel deltas:"); - - foreach (var delta in differences) - { - builder.AppendLine(delta.ToString()); - } - - Assert.Fail(builder.ToString()); - } - } - - /// - /// A simple model repressenting info about a difference between two pixels. - /// - private readonly struct PixelDifference - { - public PixelDifference(Point position, ImageSharpRgba32 expected, ImageSharpRgba32 actual) - { - this.Position = position; - this.RedDifference = actual.R - expected.R; - this.GreenDifference = actual.G - expected.G; - this.BlueDifference = actual.B - expected.B; - this.AlphaDifference = actual.A - expected.A; - } - - public readonly Point Position; - - public readonly int RedDifference; - - public readonly int GreenDifference; - - public readonly int BlueDifference; - - public readonly int AlphaDifference; - - /// - public override string ToString() - { - return $"[delta({RedDifference},{GreenDifference},{BlueDifference},{AlphaDifference}) @ ({Position.X},{Position.Y})]"; - } - } - } } diff --git a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs index 9996ffb9..fbaca8b5 100644 --- a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs +++ b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs @@ -20,13 +20,15 @@ namespace ComputeSharp.Tests { public readonly ReadWriteBuffer row_major; public readonly float dword; + public readonly float float2; + public readonly int int2x2; public void Execute() { float exp = Hlsl.Exp(dword * row_major[ThreadIds.X]); float log = Hlsl.Log(1 + exp); - row_major[ThreadIds.X] = log / dword; + row_major[ThreadIds.X] = log / dword + float2 + int2x2; } } @@ -214,6 +216,25 @@ namespace ComputeSharp.Tests buffer[ThreadIds.X] *= factor + 3.14; } } + + [TestMethod] + public void FieldAccessWithThisExpression() + { + _ = ReflectionServices.GetShaderInfo(); + } + + [AutoConstructor] + internal readonly partial struct FieldAccessWithThisExpressionShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + public readonly float number; + + /// + public void Execute() + { + this.buffer[ThreadIds.X] *= this.number; + } + } } } diff --git a/tests/ComputeSharp.Tests/ShaderRewriterTests.cs b/tests/ComputeSharp.Tests/ShaderRewriterTests.cs new file mode 100644 index 00000000..741a05fb --- /dev/null +++ b/tests/ComputeSharp.Tests/ShaderRewriterTests.cs @@ -0,0 +1,85 @@ +using ComputeSharp.Tests.Attributes; +using ComputeSharp.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.Tests; + +[TestClass] +[TestCategory("ShaderRewriter")] +public partial class ShaderRewriterTests +{ + [CombinatorialTestMethod] + [AllDevices] + public void NanAndInfinite(Device device) + { + if (!device.Get().IsDoublePrecisionSupportAvailable()) + { + Assert.Inconclusive(); + } + + using ReadWriteBuffer buffer1 = device.Get().AllocateReadWriteBuffer(16); + using ReadWriteBuffer buffer2 = device.Get().AllocateReadWriteBuffer(16); + + device.Get().For(1, new NanAndInfiniteShader(buffer1, buffer2)); + + float[] results1 = buffer1.ToArray(); + double[] results2 = buffer2.ToArray(); + + Assert.IsTrue(float.IsNaN(results1[0])); + Assert.IsTrue(float.IsPositiveInfinity(results1[1])); + Assert.IsTrue(float.IsNegativeInfinity(results1[2])); + Assert.AreEqual(results1[3], 1); + Assert.AreEqual(results1[4], 1); + Assert.AreEqual(results1[5], 1); + Assert.IsTrue(float.IsNaN(results1[6])); + Assert.IsTrue(float.IsPositiveInfinity(results1[7])); + Assert.IsTrue(float.IsNegativeInfinity(results1[8])); + Assert.AreEqual(results1[9], 1); + Assert.AreEqual(results1[10], 1); + Assert.AreEqual(results1[11], 1); + + Assert.IsTrue(double.IsNaN(results2[0])); + Assert.IsTrue(double.IsPositiveInfinity(results2[1])); + Assert.IsTrue(double.IsNegativeInfinity(results2[2])); + Assert.IsTrue(double.IsNaN(results2[3])); + Assert.IsTrue(double.IsPositiveInfinity(results2[4])); + Assert.IsTrue(double.IsNegativeInfinity(results2[5])); + } + + [AutoConstructor] + internal readonly partial struct NanAndInfiniteShader : IComputeShader + { + public readonly ReadWriteBuffer buffer1; + public readonly ReadWriteBuffer buffer2; + + static readonly float float1 = float.NaN; + static readonly float float2 = float.PositiveInfinity; + static readonly float float3 = float.NegativeInfinity; + static readonly double double1 = double.NaN; + static readonly double double2 = double.PositiveInfinity; + static readonly double double3 = double.NegativeInfinity; + + public void Execute() + { + buffer1[0] = float.NaN; + buffer1[1] = float.PositiveInfinity; + buffer1[2] = float.NegativeInfinity; + buffer1[3] = Hlsl.IsNaN(buffer1[0]) ? 1 : 0; + buffer1[4] = Hlsl.IsInfinite(buffer1[1]) ? 1 : 0; + buffer1[5] = Hlsl.IsInfinite(buffer1[2]) ? 1 : 0; + buffer1[6] = float1; + buffer1[7] = float2; + buffer1[8] = float3; + buffer1[9] = Hlsl.IsNaN(buffer1[6]) ? 1 : 0; + buffer1[10] = Hlsl.IsInfinite(buffer1[7]) ? 1 : 0; + buffer1[11] = Hlsl.IsInfinite(buffer1[8]) ? 1 : 0; + + buffer2[0] = double.NaN; + buffer2[1] = double.PositiveInfinity; + buffer2[2] = double.NegativeInfinity; + buffer2[3] = double1; + buffer2[4] = double2; + buffer2[5] = double3; + } + } +} diff --git a/tests/ComputeSharp.Tests/ShadersTests.cs b/tests/ComputeSharp.Tests/ShadersTests.cs index 31a9b1e0..bc04c844 100644 --- a/tests/ComputeSharp.Tests/ShadersTests.cs +++ b/tests/ComputeSharp.Tests/ShadersTests.cs @@ -6,6 +6,7 @@ using ComputeSharp.Interop; using ComputeSharp.SwapChain.Shaders; using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; +using ComputeSharp.Tests.Helpers; using Microsoft.VisualStudio.TestTools.UnitTesting; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats.Png; @@ -196,7 +197,7 @@ public class ShadersTests image.SaveAsPng(actualPath, new PngEncoder() { CompressionLevel = PngCompressionLevel.BestCompression, ColorType = PngColorType.Rgb }); - ImagingTests.TolerantImageComparer.AssertEqual(expectedPath, actualPath, delta); + TolerantImageComparer.AssertEqual(expectedPath, actualPath, delta); } /// @@ -256,6 +257,6 @@ public class ShadersTests image.SaveAsPng(actualPath, new PngEncoder() { CompressionLevel = PngCompressionLevel.BestCompression, ColorType = PngColorType.Rgb }); - ImagingTests.TolerantImageComparer.AssertEqual(expectedPath, actualPath, delta); + TolerantImageComparer.AssertEqual(expectedPath, actualPath, delta); } } diff --git a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs index 30ef0a3c..f357dfc0 100644 --- a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs +++ b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs @@ -68,7 +68,7 @@ public partial class Texture2DTests using var processed = destination.ToImage(); - ImagingTests.TolerantImageComparer.AssertEqual(sampled, processed, 0.0000017f); + TolerantImageComparer.AssertEqual(sampled, processed, 0.0000017f); } [AutoConstructor] @@ -101,7 +101,7 @@ public partial class Texture2DTests using var processed = destination.ToImage(); - ImagingTests.TolerantImageComparer.AssertEqual(sampled, processed, 0.0000017f); + TolerantImageComparer.AssertEqual(sampled, processed, 0.0000017f); } [AutoConstructor]