yum-mirror/slang

Making it easier to work with shaders

git clone https://git.yummers.dev/yum-mirror/slang

Gangzheng TongConvert gfx unit tests and examples to use slang-rhi (#7577)43d0c2100

master
8.0 KiB230 linesraw
1#include "core/slang-basic.h"
2#include "core/slang-blob.h"
3#include "core/slang-io.h"
4#include "core/slang-memory-file-system.h"
5#include "gfx-test-util.h"
6#include "slang-rhi.h"
7#include "slang-rhi/shader-cursor.h"
8#include "unit-test/slang-unit-test.h"
9
10#include <mutex>
11using namespace rhi;
12
13namespace gfx_test
14{
15// Test that precompiled module cache is working.
16
17Slang::ComPtr<slang::ISession> createSession(rhi::IDevice* device, ISlangFileSystemExt* fileSys)
18{
19    static std::mutex m;
20    std::lock_guard<std ::mutex> lock(m);
21
22    Slang::ComPtr<slang::ISession> slangSession;
23    device->getSlangSession(slangSession.writeRef());
24    slang::SessionDesc sessionDesc = {};
25    sessionDesc.searchPathCount = 1;
26    const char* searchPath = "cache/";
27    sessionDesc.searchPaths = &searchPath;
28    sessionDesc.targetCount = 1;
29    sessionDesc.compilerOptionEntryCount = 1;
30    slang::CompilerOptionEntry entry;
31    entry.name = slang::CompilerOptionName::UseUpToDateBinaryModule;
32    entry.value.kind = slang::CompilerOptionValueKind::Int;
33    entry.value.intValue0 = 1;
34    sessionDesc.compilerOptionEntries = &entry;
35    slang::TargetDesc targetDesc = {};
36    switch (device->getInfo().deviceType)
37    {
38    case rhi::DeviceType::D3D12:
39        targetDesc.format = SLANG_DXIL;
40        targetDesc.profile = device->getSlangSession()->getGlobalSession()->findProfile("sm_6_1");
41        break;
42    case rhi::DeviceType::Vulkan:
43        targetDesc.format = SLANG_SPIRV;
44        targetDesc.profile = device->getSlangSession()->getGlobalSession()->findProfile("GLSL_460");
45        break;
46    }
47    sessionDesc.targets = &targetDesc;
48    sessionDesc.fileSystem = fileSys;
49    auto globalSession = slangSession->getGlobalSession();
50    globalSession->createSession(sessionDesc, slangSession.writeRef());
51    return slangSession;
52}
53
54static Slang::Result precompileProgram(
55    rhi::IDevice* device,
56    ISlangMutableFileSystem* fileSys,
57    const char* shaderModuleName)
58{
59    Slang::ComPtr<slang::ISession> slangSession = createSession(device, fileSys);
60
61    Slang::ComPtr<slang::IBlob> diagnosticsBlob;
62    slang::IModule* module = slangSession->loadModule(shaderModuleName, diagnosticsBlob.writeRef());
63    diagnoseIfNeeded(diagnosticsBlob);
64    if (!module)
65        return SLANG_FAIL;
66
67    // Write loaded modules to memory file system.
68    for (SlangInt i = 0; i < slangSession->getLoadedModuleCount(); i++)
69    {
70        auto module = slangSession->getLoadedModule(i);
71        auto path = module->getFilePath();
72        if (path)
73        {
74            auto name = module->getName();
75            ComPtr<ISlangBlob> outBlob;
76            module->serialize(outBlob.writeRef());
77            fileSys->saveFileBlob(
78                (Slang::String("cache/") + Slang::String(name) + ".slang-module").getBuffer(),
79                outBlob);
80        }
81    }
82    return SLANG_OK;
83}
84
85void precompiledModuleCacheTestImpl(IDevice* device, UnitTestContext* context)
86{
87    // First, Initialize our file system.
88    ComPtr<ISlangMutableFileSystem> memoryFileSystem =
89        ComPtr<ISlangMutableFileSystem>(new Slang::MemoryFileSystem());
90    memoryFileSystem->createDirectory("cache");
91
92    const char* moduleSrc = R"(
93            import "precompiled-module-imported";
94
95            // Main entry-point. 
96
97            using namespace ns;
98
99            [shader("compute")]
100            [numthreads(4, 1, 1)]
101            void computeMain(
102                uint3 sv_dispatchThreadID : SV_DispatchThreadID,
103                uniform RWStructuredBuffer <float> buffer)
104            {
105                buffer[sv_dispatchThreadID.x] = helperFunc() + helperFunc1();
106            }
107        )";
108    memoryFileSystem->saveFile("precompiled-module.slang", moduleSrc, strlen(moduleSrc));
109
110    const char* moduleSrc2 = R"(
111            module "precompiled-module-imported";
112
113            __include "precompiled-module-included.slang";
114
115            namespace ns
116            {
117                public int helperFunc()
118                {
119                    return 1;
120                }
121            }
122        )";
123    memoryFileSystem->saveFile("precompiled-module-imported.slang", moduleSrc2, strlen(moduleSrc2));
124    const char* moduleSrc3 = R"(
125            implementing "precompiled-module-imported";
126
127            namespace ns
128            {
129                public int helperFunc1()
130                {
131                    return 2;
132                }
133            }
134        )";
135    memoryFileSystem->saveFile("precompiled-module-included.slang", moduleSrc3, strlen(moduleSrc3));
136
137    // Precompile a module.
138    ComPtr<IShaderProgram> shaderProgram;
139    slang::ProgramLayout* slangReflection;
140    GFX_CHECK_CALL_ABORT(
141        precompileProgram(device, memoryFileSystem.get(), "precompiled-module-imported"));
142
143    // Next, load the precompiled slang program.
144    Slang::ComPtr<slang::ISession> slangSession = createSession(device, memoryFileSystem);
145    ComPtr<ISlangBlob> binaryBlob;
146    memoryFileSystem->loadFile(
147        "cache/precompiled-module-imported.slang-module",
148        binaryBlob.writeRef());
149    auto upToDate =
150        slangSession->isBinaryModuleUpToDate("precompiled-module-imported.slang", binaryBlob);
151    SLANG_CHECK(upToDate); // The module should be up-to-date.
152
153    GFX_CHECK_CALL_ABORT(loadComputeProgram(
154        device,
155        slangSession,
156        shaderProgram,
157        "precompiled-module",
158        "computeMain",
159        slangReflection));
160
161    ComputePipelineDesc pipelineDesc = {};
162    pipelineDesc.program = shaderProgram.get();
163    ComPtr<IComputePipeline> computePipeline;
164    GFX_CHECK_CALL_ABORT(device->createComputePipeline(pipelineDesc, computePipeline.writeRef()));
165
166    const int numberCount = 4;
167    float initialData[] = {0.0f, 0.0f, 0.0f, 0.0f};
168    BufferDesc bufferDesc = {};
169    bufferDesc.size = numberCount * sizeof(float);
170    bufferDesc.usage = BufferUsage::UnorderedAccess | BufferUsage::ShaderResource |
171                       BufferUsage::CopySource | BufferUsage::CopyDestination;
172    bufferDesc.memoryType = MemoryType::DeviceLocal;
173
174    ComPtr<IBuffer> numbersBuffer;
175    GFX_CHECK_CALL_ABORT(
176        device->createBuffer(bufferDesc, (void*)initialData, numbersBuffer.writeRef()));
177
178    // We have done all the set up work, now it is time to start recording a command buffer for
179    // GPU execution.
180    {
181        auto queue = device->getQueue(QueueType::Graphics);
182
183        auto commandEncoder = queue->createCommandEncoder();
184        auto encoder = commandEncoder->beginComputePass();
185
186        ComPtr<IShaderObject> rootObject;
187        device->createRootShaderObject(shaderProgram, rootObject.writeRef());
188        encoder->bindPipeline(computePipeline, rootObject);
189
190        ShaderCursor entryPointCursor(
191            rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
192        // Bind buffer to the entry point.
193        entryPointCursor.getPath("buffer").setBinding(numbersBuffer);
194
195        encoder->dispatchCompute(1, 1, 1);
196        encoder->end();
197        queue->submit(commandEncoder->finish());
198        queue->waitOnHost();
199    }
200
201    compareComputeResult(device, numbersBuffer, std::array{3.0f, 3.0f, 3.0f, 3.0f});
202
203    // Now we change the source and check if the precompiled module is still up-to-date.
204    const char* moduleSrc4 = R"(
205            implementing "precompiled-module-imported";
206            namespace ns {
207                public int helperFunc1() {
208                    return 2;
209                }
210            }
211        )";
212    memoryFileSystem->saveFile("precompiled-module-included.slang", moduleSrc4, strlen(moduleSrc4));
213
214    slangSession = createSession(device, memoryFileSystem);
215    upToDate =
216        slangSession->isBinaryModuleUpToDate("precompiled-module-imported.slang", binaryBlob);
217    SLANG_CHECK(!upToDate); // The module should not be up-to-date because the source has changed.
218}
219
220SLANG_UNIT_TEST(precompiledModuleCacheD3D12)
221{
222    runTestImpl(precompiledModuleCacheTestImpl, unitTestContext, DeviceType::D3D12, {});
223}
224
225SLANG_UNIT_TEST(precompiledModuleCacheVulkan)
226{
227    runTestImpl(precompiledModuleCacheTestImpl, unitTestContext, DeviceType::Vulkan, {});
228}
229
230} // namespace gfx_test