summaryrefslogtreecommitdiffstats
path: root/tools/gfx-unit-test/texture-types-tests.cpp
blob: 89342f9cf76eb3c2f2ecb4d85ae6ef58fe3e7bab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
#include "gfx-test-texture-util.h"
#include "gfx-test-util.h"
#include "slang-gfx.h"
#include "source/core/slang-basic.h"
#include "tools/gfx-util/shader-cursor.h"
#include "tools/unit-test/slang-unit-test.h"

#if SLANG_WINDOWS_FAMILY
#include <d3d12.h>
#endif

using namespace Slang;
using namespace gfx;

namespace gfx_test
{
struct BaseTextureViewTest
{
    IDevice* device;
    UnitTestContext* context;

    IResourceView::Type viewType;
    size_t alignedRowStride;

    RefPtr<TextureInfo> textureInfo;
    RefPtr<ValidationTextureFormatBase> validationFormat;

    ComPtr<ITextureResource> texture;
    ComPtr<IResourceView> textureView;
    ComPtr<IBufferResource> resultsBuffer;
    ComPtr<IResourceView> bufferView;

    ComPtr<ISamplerState> sampler;

    const void* expectedTextureData;

    void init(
        IDevice* device,
        UnitTestContext* context,
        Format format,
        RefPtr<ValidationTextureFormatBase> validationFormat,
        IResourceView::Type viewType,
        IResource::Type type)
    {
        this->device = device;
        this->context = context;
        this->validationFormat = validationFormat;
        this->viewType = viewType;

        this->textureInfo = new TextureInfo();
        this->textureInfo->format = format;
        this->textureInfo->textureType = type;
    }

    ResourceState getDefaultResourceStateForViewType(IResourceView::Type type)
    {
        switch (type)
        {
        case IResourceView::Type::RenderTarget:
            return ResourceState::RenderTarget;
        case IResourceView::Type::DepthStencil:
            return ResourceState::DepthWrite;
        case IResourceView::Type::ShaderResource:
            return ResourceState::ShaderResource;
        case IResourceView::Type::UnorderedAccess:
            return ResourceState::UnorderedAccess;
        case IResourceView::Type::AccelerationStructure:
            return ResourceState::AccelerationStructure;
        default:
            return ResourceState::Undefined;
        }
    }

    String getShaderEntryPoint()
    {
        String base = "resourceViewTest";
        String shape;
        String view;

        switch (textureInfo->textureType)
        {
        case IResource::Type::Texture1D:
            shape = "1D";
            break;
        case IResource::Type::Texture2D:
            shape = "2D";
            break;
        case IResource::Type::Texture3D:
            shape = "3D";
            break;
        case IResource::Type::TextureCube:
            shape = "Cube";
            break;
        default:
            assert(!"Invalid texture shape");
            SLANG_CHECK_ABORT(false);
        }

        switch (viewType)
        {
        case IResourceView::Type::RenderTarget:
            view = "Render";
            break;
        case IResourceView::Type::DepthStencil:
            view = "Depth";
            break;
        case IResourceView::Type::ShaderResource:
            view = "Shader";
            break;
        case IResourceView::Type::UnorderedAccess:
            view = "Unordered";
            break;
        case IResourceView::Type::AccelerationStructure:
            view = "Accel";
            break;
        default:
            assert(!"Invalid resource view");
            SLANG_CHECK_ABORT(false);
        }

        return base + shape + view;
    }
};

// used for shaderresource and unorderedaccess
struct ShaderAndUnorderedTests : BaseTextureViewTest
{
    void createRequiredResources()
    {
        ITextureResource::Desc textureDesc = {};
        textureDesc.type = textureInfo->textureType;
        textureDesc.numMipLevels = textureInfo->mipLevelCount;
        textureDesc.arraySize = textureInfo->arrayLayerCount;
        textureDesc.size = textureInfo->extents;
        textureDesc.defaultState = getDefaultResourceStateForViewType(viewType);
        textureDesc.allowedStates = ResourceStateSet(
            textureDesc.defaultState,
            ResourceState::CopySource,
            ResourceState::CopyDestination);
        textureDesc.format = textureInfo->format;

        GFX_CHECK_CALL_ABORT(device->createTextureResource(
            textureDesc,
            textureInfo->subresourceDatas.getBuffer(),
            texture.writeRef()));

        IResourceView::Desc textureViewDesc = {};
        textureViewDesc.type = viewType;
        textureViewDesc.format =
            textureDesc.format; // TODO: Handle typeless formats - gfxIsTypelessFormat(format) ?
                                // convertTypelessFormat(format) : format;
        GFX_CHECK_CALL_ABORT(
            device->createTextureView(texture, textureViewDesc, textureView.writeRef()));

        auto texelSize = getTexelSize(textureInfo->format);
        size_t alignment;
        device->getTextureRowAlignment(&alignment);
        alignedRowStride =
            (textureInfo->extents.width * texelSize + alignment - 1) & ~(alignment - 1);
        IBufferResource::Desc bufferDesc = {};
        // All of the values read back from the shader will be uint32_t
        bufferDesc.sizeInBytes = textureDesc.size.width * textureDesc.size.height *
                                 textureDesc.size.depth * texelSize * sizeof(uint32_t);
        bufferDesc.format = Format::Unknown;
        bufferDesc.elementSize = sizeof(uint32_t);
        bufferDesc.defaultState = ResourceState::UnorderedAccess;
        bufferDesc.allowedStates = ResourceStateSet(
            bufferDesc.defaultState,
            ResourceState::CopyDestination,
            ResourceState::CopySource);
        bufferDesc.memoryType = MemoryType::DeviceLocal;

        GFX_CHECK_CALL_ABORT(
            device->createBufferResource(bufferDesc, nullptr, resultsBuffer.writeRef()));

        IResourceView::Desc bufferViewDesc = {};
        bufferViewDesc.type = IResourceView::Type::UnorderedAccess;
        bufferViewDesc.format = Format::Unknown;
        GFX_CHECK_CALL_ABORT(device->createBufferView(
            resultsBuffer,
            nullptr,
            bufferViewDesc,
            bufferView.writeRef()));
    }

    void submitShaderWork(const char* entryPoint)
    {
        Slang::ComPtr<ITransientResourceHeap> transientHeap;
        ITransientResourceHeap::Desc transientHeapDesc = {};
        transientHeapDesc.constantBufferSize = 4096;
        GFX_CHECK_CALL_ABORT(
            device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));

        ComPtr<IShaderProgram> shaderProgram;
        slang::ProgramLayout* slangReflection;
        GFX_CHECK_CALL_ABORT(loadComputeProgram(
            device,
            shaderProgram,
            "trivial-copy-textures",
            entryPoint,
            slangReflection));

        ComputePipelineStateDesc pipelineDesc = {};
        pipelineDesc.program = shaderProgram.get();
        ComPtr<gfx::IPipelineState> pipelineState;
        GFX_CHECK_CALL_ABORT(
            device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));

        // We have done all the set up work, now it is time to start recording a command buffer for
        // GPU execution.
        {
            ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
            auto queue = device->createCommandQueue(queueDesc);

            auto commandBuffer = transientHeap->createCommandBuffer();
            auto encoder = commandBuffer->encodeComputeCommands();

            auto rootObject = encoder->bindPipeline(pipelineState);

            ShaderCursor entryPointCursor(
                rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.

            auto width = textureInfo->extents.width;
            auto height = textureInfo->extents.height;
            auto depth = textureInfo->extents.depth;

            entryPointCursor["width"].setData(width);
            entryPointCursor["height"].setData(height);
            entryPointCursor["depth"].setData(depth);

            // Bind texture view to the entry point
            entryPointCursor["resourceView"].setResource(
                textureView); // TODO: Bind nullptr and make sure it doesn't splut - should be 0
                              // everywhere
            entryPointCursor["testResults"].setResource(bufferView);

            if (sampler)
                entryPointCursor["sampler"].setSampler(
                    sampler); // TODO: Bind nullptr and make sure it doesn't splut

            auto bufferElementCount = width * height * depth;
            encoder->dispatchCompute(bufferElementCount, 1, 1);
            encoder->endEncoding();
            commandBuffer->close();
            queue->executeCommandBuffer(commandBuffer);
            queue->waitOnHost();
        }
    }

    void validateTextureValues(ValidationTextureData actual, ValidationTextureData original)
    {
        // TODO: needs to be extended to cover mip levels and array layers
        for (GfxIndex x = 0; x < actual.extents.width; ++x)
        {
            for (GfxIndex y = 0; y < actual.extents.height; ++y)
            {
                for (GfxIndex z = 0; z < actual.extents.depth; ++z)
                {
                    auto actualBlock = (uint8_t*)actual.getBlockAt(x, y, z);
                    for (Int i = 0; i < 4; ++i)
                    {
                        SLANG_CHECK(actualBlock[i] == 1);
                    }
                }
            }
        }
    }

    void checkTestResults()
    {
        // Shader resources are read-only, so we don't need to check that writes to the resource
        // were correct.
        if (viewType != IResourceView::Type::ShaderResource)
        {
            ComPtr<ISlangBlob> textureBlob;
            size_t rowPitch;
            size_t pixelSize;
            GFX_CHECK_CALL_ABORT(device->readTextureResource(
                texture,
                ResourceState::CopySource,
                textureBlob.writeRef(),
                &rowPitch,
                &pixelSize));
            auto textureValues = (uint8_t*)textureBlob->getBufferPointer();

            ValidationTextureData textureResults;
            textureResults.extents = textureInfo->extents;
            textureResults.textureData = textureValues;
            textureResults.strides.x = (uint32_t)pixelSize;
            textureResults.strides.y = (uint32_t)rowPitch;
            textureResults.strides.z = textureResults.extents.height * textureResults.strides.y;

            ValidationTextureData originalData;
            originalData.extents = textureInfo->extents;
            originalData.textureData = textureInfo->subresourceDatas.getBuffer();
            originalData.strides.x = (uint32_t)pixelSize;
            originalData.strides.y = textureInfo->extents.width * originalData.strides.x;
            originalData.strides.z = textureInfo->extents.height * originalData.strides.y;

            validateTextureValues(textureResults, originalData);
        }

        ComPtr<ISlangBlob> bufferBlob;
        GFX_CHECK_CALL_ABORT(device->readBufferResource(
            resultsBuffer,
            0,
            resultsBuffer->getDesc()->sizeInBytes,
            bufferBlob.writeRef()));
        auto results = (uint32_t*)bufferBlob->getBufferPointer();

        auto elementCount = textureInfo->extents.width * textureInfo->extents.height *
                            textureInfo->extents.depth * 4;
        auto castedTextureData = (uint8_t*)expectedTextureData;
        for (Int i = 0; i < elementCount; ++i)
        {
            SLANG_CHECK(results[i] == castedTextureData[i]);
        }
    }

    void run()
    {
        // TODO: Should test with samplers
        //             ISamplerState::Desc samplerDesc;
        //             sampler = device->createSamplerState(samplerDesc);

        // TODO: Should test multiple mip levels and array layers
        textureInfo->extents.width = 4;
        textureInfo->extents.height =
            (textureInfo->textureType == IResource::Type::Texture1D) ? 1 : 4;
        textureInfo->extents.depth =
            (textureInfo->textureType != IResource::Type::Texture3D) ? 1 : 2;
        textureInfo->mipLevelCount = 1;
        textureInfo->arrayLayerCount = 1;
        generateTextureData(textureInfo, validationFormat);

        // We need to save the pointer to the original texture data for results checking because the
        // texture will be overwritten during testing (if the texture can be written to).
        expectedTextureData = textureInfo->subresourceDatas[getSubresourceIndex(0, 1, 0)].data;

        createRequiredResources();
        auto entryPointName = getShaderEntryPoint();
        // printf("%s\n", entryPointName.getBuffer());
        submitShaderWork(entryPointName.getBuffer());

        checkTestResults();
    }
};

// used for rendertarget and depthstencil
struct RenderTargetTests : BaseTextureViewTest
{
    struct Vertex
    {
        float position[3];
        float color[3];
    };

    const int kVertexCount = 12;
    const Vertex kVertexData[12] = {
        // Triangle 1
        {{0, 0, 0.5}, {1, 0, 0}},
        {{1, 1, 0.5}, {1, 0, 0}},
        {{-1, 1, 0.5}, {1, 0, 0}},

        // Triangle 2
        {{-1, 1, 0.5}, {0, 1, 0}},
        {{0, 0, 0.5}, {0, 1, 0}},
        {{-1, -1, 0.5}, {0, 1, 0}},

        // Triangle 3
        {{-1, -1, 0.5}, {0, 0, 1}},
        {{0, 0, 0.5}, {0, 0, 1}},
        {{1, -1, 0.5}, {0, 0, 1}},

        // Triangle 4
        {{1, -1, 0.5}, {0, 0, 0}},
        {{0, 0, 0.5}, {0, 0, 0}},
        {{1, 1, 0.5}, {0, 0, 0}},
    };

    int sampleCount = 1;

    ComPtr<ITransientResourceHeap> transientHeap;
    ComPtr<IPipelineState> pipelineState;
    ComPtr<IRenderPassLayout> renderPass;
    ComPtr<IFramebuffer> framebuffer;

    ComPtr<ITextureResource> sampledTexture;
    ComPtr<IBufferResource> vertexBuffer;

    void createRequiredResources()
    {
        IBufferResource::Desc vertexBufferDesc;
        vertexBufferDesc.type = IResource::Type::Buffer;
        vertexBufferDesc.sizeInBytes = kVertexCount * sizeof(Vertex);
        vertexBufferDesc.defaultState = ResourceState::VertexBuffer;
        vertexBufferDesc.allowedStates = ResourceState::VertexBuffer;
        vertexBuffer = device->createBufferResource(vertexBufferDesc, &kVertexData[0]);
        SLANG_CHECK_ABORT(vertexBuffer != nullptr);

        VertexStreamDesc vertexStreams[] = {
            {sizeof(Vertex), InputSlotClass::PerVertex, 0},
        };

        InputElementDesc inputElements[] = {
            // Vertex buffer data
            {"POSITION", 0, Format::R32G32B32_FLOAT, offsetof(Vertex, position), 0},
            {"COLOR", 0, Format::R32G32B32_FLOAT, offsetof(Vertex, color), 0},
        };

        ITextureResource::Desc sampledTexDesc = {};
        sampledTexDesc.type = textureInfo->textureType;
        sampledTexDesc.numMipLevels = textureInfo->mipLevelCount;
        sampledTexDesc.arraySize = textureInfo->arrayLayerCount;
        sampledTexDesc.size = textureInfo->extents;
        sampledTexDesc.defaultState = getDefaultResourceStateForViewType(viewType);
        sampledTexDesc.allowedStates = ResourceStateSet(
            sampledTexDesc.defaultState,
            ResourceState::ResolveSource,
            ResourceState::CopySource);
        sampledTexDesc.format = textureInfo->format;
        sampledTexDesc.sampleDesc.numSamples = sampleCount;

        GFX_CHECK_CALL_ABORT(device->createTextureResource(
            sampledTexDesc,
            textureInfo->subresourceDatas.getBuffer(),
            sampledTexture.writeRef()));

        ITextureResource::Desc texDesc = {};
        texDesc.type = textureInfo->textureType;
        texDesc.numMipLevels = textureInfo->mipLevelCount;
        texDesc.arraySize = textureInfo->arrayLayerCount;
        texDesc.size = textureInfo->extents;
        texDesc.defaultState = ResourceState::ResolveDestination;
        texDesc.allowedStates =
            ResourceStateSet(ResourceState::ResolveDestination, ResourceState::CopySource);
        texDesc.format = textureInfo->format;

        GFX_CHECK_CALL_ABORT(device->createTextureResource(
            texDesc,
            textureInfo->subresourceDatas.getBuffer(),
            texture.writeRef()));

        IInputLayout::Desc inputLayoutDesc = {};
        inputLayoutDesc.inputElementCount = SLANG_COUNT_OF(inputElements);
        inputLayoutDesc.inputElements = inputElements;
        inputLayoutDesc.vertexStreamCount = SLANG_COUNT_OF(vertexStreams);
        inputLayoutDesc.vertexStreams = vertexStreams;
        auto inputLayout = device->createInputLayout(inputLayoutDesc);
        SLANG_CHECK_ABORT(inputLayout != nullptr);

        ITransientResourceHeap::Desc transientHeapDesc = {};
        transientHeapDesc.constantBufferSize = 4096;
        GFX_CHECK_CALL_ABORT(
            device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));

        ComPtr<IShaderProgram> shaderProgram;
        slang::ProgramLayout* slangReflection;
        GFX_CHECK_CALL_ABORT(loadGraphicsProgram(
            device,
            shaderProgram,
            "trivial-copy-textures",
            "vertexMain",
            "fragmentMain",
            slangReflection));

        IFramebufferLayout::TargetLayout targetLayout;
        targetLayout.format = textureInfo->format;
        targetLayout.sampleCount = sampleCount;

        IFramebufferLayout::Desc framebufferLayoutDesc;
        framebufferLayoutDesc.renderTargetCount = 1;
        framebufferLayoutDesc.renderTargets = &targetLayout;
        ComPtr<gfx::IFramebufferLayout> framebufferLayout =
            device->createFramebufferLayout(framebufferLayoutDesc);
        SLANG_CHECK_ABORT(framebufferLayout != nullptr);

        GraphicsPipelineStateDesc pipelineDesc = {};
        pipelineDesc.program = shaderProgram.get();
        pipelineDesc.inputLayout = inputLayout;
        pipelineDesc.framebufferLayout = framebufferLayout;
        pipelineDesc.depthStencil.depthTestEnable = false;
        pipelineDesc.depthStencil.depthWriteEnable = false;
        GFX_CHECK_CALL_ABORT(
            device->createGraphicsPipelineState(pipelineDesc, pipelineState.writeRef()));

        IRenderPassLayout::Desc renderPassDesc = {};
        renderPassDesc.framebufferLayout = framebufferLayout;
        renderPassDesc.renderTargetCount = 1;
        IRenderPassLayout::TargetAccessDesc renderTargetAccess = {};
        renderTargetAccess.loadOp = IRenderPassLayout::TargetLoadOp::Clear;
        renderTargetAccess.storeOp = IRenderPassLayout::TargetStoreOp::Store;
        renderTargetAccess.initialState = getDefaultResourceStateForViewType(viewType);
        renderTargetAccess.finalState = ResourceState::ResolveSource;
        renderPassDesc.renderTargetAccess = &renderTargetAccess;
        GFX_CHECK_CALL_ABORT(device->createRenderPassLayout(renderPassDesc, renderPass.writeRef()));

        gfx::IResourceView::Desc colorBufferViewDesc;
        memset(&colorBufferViewDesc, 0, sizeof(colorBufferViewDesc));
        colorBufferViewDesc.format = textureInfo->format;
        colorBufferViewDesc.renderTarget.shape = textureInfo->textureType; // TODO: TextureCube?
        colorBufferViewDesc.type = viewType;
        auto rtv = device->createTextureView(sampledTexture, colorBufferViewDesc);

        gfx::IFramebuffer::Desc framebufferDesc;
        framebufferDesc.renderTargetCount = 1;
        framebufferDesc.depthStencilView = nullptr;
        framebufferDesc.renderTargetViews = rtv.readRef();
        framebufferDesc.layout = framebufferLayout;
        GFX_CHECK_CALL_ABORT(device->createFramebuffer(framebufferDesc, framebuffer.writeRef()));

        auto texelSize = getTexelSize(textureInfo->format);
        size_t alignment;
        device->getTextureRowAlignment(&alignment);
        alignedRowStride =
            (textureInfo->extents.width * texelSize + alignment - 1) & ~(alignment - 1);
    }

    void submitShaderWork(const char* entryPointName)
    {
        ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
        auto queue = device->createCommandQueue(queueDesc);

        auto commandBuffer = transientHeap->createCommandBuffer();
        auto renderEncoder = commandBuffer->encodeRenderCommands(renderPass, framebuffer);
        auto rootObject = renderEncoder->bindPipeline(pipelineState);

        gfx::Viewport viewport = {};
        viewport.maxZ = (float)textureInfo->extents.depth;
        viewport.extentX = (float)textureInfo->extents.width;
        viewport.extentY = (float)textureInfo->extents.height;
        renderEncoder->setViewportAndScissor(viewport);

        renderEncoder->setVertexBuffer(0, vertexBuffer);
        renderEncoder->setPrimitiveTopology(PrimitiveTopology::TriangleList);
        renderEncoder->draw(kVertexCount, 0);
        renderEncoder->endEncoding();

        auto resourceEncoder = commandBuffer->encodeResourceCommands();

        if (sampleCount > 1)
        {
            SubresourceRange msaaSubresource = {};
            msaaSubresource.aspectMask = TextureAspect::Color;
            msaaSubresource.mipLevel = 0;
            msaaSubresource.mipLevelCount = 1;
            msaaSubresource.baseArrayLayer = 0;
            msaaSubresource.layerCount = 1;

            SubresourceRange dstSubresource = {};
            dstSubresource.aspectMask = TextureAspect::Color;
            dstSubresource.mipLevel = 0;
            dstSubresource.mipLevelCount = 1;
            dstSubresource.baseArrayLayer = 0;
            dstSubresource.layerCount = 1;

            resourceEncoder->resolveResource(
                sampledTexture,
                ResourceState::ResolveSource,
                msaaSubresource,
                texture,
                ResourceState::ResolveDestination,
                dstSubresource);
            resourceEncoder->textureBarrier(
                texture,
                ResourceState::ResolveDestination,
                ResourceState::CopySource);
        }
        else
        {
            resourceEncoder->textureBarrier(
                sampledTexture,
                ResourceState::ResolveSource,
                ResourceState::CopySource);
        }
        resourceEncoder->endEncoding();
        commandBuffer->close();
        queue->executeCommandBuffer(commandBuffer);
        queue->waitOnHost();
    }

    // TODO: Should take a value indicating the slice that was rendered into
    // TODO: Needs to handle either the correct slice or array layer (will not always check z)
    void validateTextureValues(ValidationTextureData actual)
    {
        for (GfxIndex x = 0; x < actual.extents.width; ++x)
        {
            for (GfxIndex y = 0; y < actual.extents.height; ++y)
            {
                for (GfxIndex z = 0; z < actual.extents.depth; ++z)
                {
                    auto actualBlock = (float*)actual.getBlockAt(x, y, z);
                    for (Int i = 0; i < 4; ++i)
                    {
                        if (z == 0)
                        {
                            // Slice being rendered into
                            SLANG_CHECK(actualBlock[i] == (float)i + 1);
                        }
                        else
                        {
                            SLANG_CHECK(actualBlock[i] == 0.0f);
                        }
                    }
                }
            }
        }
    }

    void checkTestResults()
    {
        ComPtr<ISlangBlob> textureBlob;
        size_t rowPitch;
        size_t pixelSize;
        if (sampleCount > 1)
        {
            GFX_CHECK_CALL_ABORT(device->readTextureResource(
                texture,
                ResourceState::CopySource,
                textureBlob.writeRef(),
                &rowPitch,
                &pixelSize));
        }
        else
        {
            GFX_CHECK_CALL_ABORT(device->readTextureResource(
                sampledTexture,
                ResourceState::CopySource,
                textureBlob.writeRef(),
                &rowPitch,
                &pixelSize));
        }
        auto textureValues = (float*)textureBlob->getBufferPointer();

        ValidationTextureData textureResults;
        textureResults.extents = textureInfo->extents;
        textureResults.textureData = textureValues;
        textureResults.strides.x = (uint32_t)pixelSize;
        textureResults.strides.y = (uint32_t)rowPitch;
        textureResults.strides.z = textureResults.extents.height * textureResults.strides.y;

        validateTextureValues(textureResults);
    }

    void run()
    {
        auto entryPointName = getShaderEntryPoint();
        //             printf("%s\n", entryPointName.getBuffer());

        // TODO: Sampler state and null state?
        //             ISamplerState::Desc samplerDesc;
        //             sampler = device->createSamplerState(samplerDesc);

        textureInfo->extents.width = 4;
        textureInfo->extents.height =
            (textureInfo->textureType == IResource::Type::Texture1D) ? 1 : 4;
        textureInfo->extents.depth =
            (textureInfo->textureType != IResource::Type::Texture3D) ? 1 : 2;
        textureInfo->mipLevelCount = 1;
        textureInfo->arrayLayerCount = 1;
        generateTextureData(textureInfo, validationFormat);

        // We need to save the pointer to the original texture data for results checking because the
        // texture will be overwritten during testing (if the texture can be written to).
        expectedTextureData = textureInfo->subresourceDatas[getSubresourceIndex(0, 1, 0)].data;

        createRequiredResources();
        submitShaderWork(entryPointName.getBuffer());

        checkTestResults();
    }
};

void shaderAndUnorderedTestImpl(IDevice* device, UnitTestContext* context)
{
    // TODO: Buffer and TextureCube
    for (Int i = 2; i < (int32_t)IResource::Type::TextureCube; ++i)
    {
        for (Int j = 3; j < (int32_t)IResourceView::Type::AccelerationStructure; ++j)
        {
            auto shape = (IResource::Type)i;
            auto view = (IResourceView::Type)j;
            auto format = Format::R8G8B8A8_UINT;
            auto validationFormat = getValidationTextureFormat(format);
            if (!validationFormat)
                SLANG_CHECK_ABORT(false);

            ShaderAndUnorderedTests test;
            test.init(device, context, format, validationFormat, view, shape);
            test.run();
        }
    }
}

void renderTargetTestImpl(IDevice* device, UnitTestContext* context)
{
    // TODO: Buffer and TextureCube
    for (Int i = 2; i < (int32_t)IResource::Type::TextureCube; ++i)
    {
        auto shape = (IResource::Type)i;
        auto view = IResourceView::Type::RenderTarget;
        auto format = Format::R32G32B32A32_FLOAT;
        auto validationFormat = getValidationTextureFormat(format);
        if (!validationFormat)
            SLANG_CHECK_ABORT(false);

        RenderTargetTests test;
        test.init(device, context, format, validationFormat, view, shape);
        test.run();
    }
}

SLANG_UNIT_TEST(shaderAndUnorderedAccessTests)
{
    runTestImpl(shaderAndUnorderedTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
    runTestImpl(shaderAndUnorderedTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
}

SLANG_UNIT_TEST(renderTargetTests)
{
    runTestImpl(renderTargetTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
    runTestImpl(renderTargetTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
}
} // namespace gfx_test

// 1D + array + multisample, ditto for 2D, ditto for 3D
// one test with something bound, one test with nothing bound, one test with subset of layers (set
// values in SubresourceRange and assign in desc)