xref: /aosp_15_r20/external/deqp/external/vulkancts/modules/vulkan/mesh_shader/vktMeshShaderApiTests.cpp (revision 35238bce31c2a825756842865a792f8cf7f89930)
1 /*------------------------------------------------------------------------
2  * Vulkan Conformance Tests
3  * ------------------------
4  *
5  * Copyright (c) 2021 The Khronos Group Inc.
6  * Copyright (c) 2021 Valve Corporation.
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  *//*!
21  * \file
22  * \brief Mesh Shader API Tests
23  *//*--------------------------------------------------------------------*/
24 
25 #include "vktMeshShaderApiTests.hpp"
26 #include "vktMeshShaderUtil.hpp"
27 #include "vktTestCase.hpp"
28 
29 #include "vkTypeUtil.hpp"
30 #include "vkImageWithMemory.hpp"
31 #include "vkBufferWithMemory.hpp"
32 #include "vkObjUtil.hpp"
33 #include "vkBuilderUtil.hpp"
34 #include "vkCmdUtil.hpp"
35 #include "vkImageUtil.hpp"
36 
37 #include "tcuMaybe.hpp"
38 #include "tcuTestLog.hpp"
39 #include "tcuImageCompare.hpp"
40 
41 #include "deRandom.hpp"
42 
43 #include <iostream>
44 #include <sstream>
45 #include <vector>
46 #include <algorithm>
47 #include <iterator>
48 #include <limits>
49 
50 namespace vkt
51 {
52 namespace MeshShader
53 {
54 
55 namespace
56 {
57 
58 using namespace vk;
59 
60 using GroupPtr            = de::MovePtr<tcu::TestCaseGroup>;
61 using ImageWithMemoryPtr  = de::MovePtr<ImageWithMemory>;
62 using BufferWithMemoryPtr = de::MovePtr<BufferWithMemory>;
63 
64 enum class DrawType
65 {
66     DRAW = 0,
67     DRAW_INDIRECT,
68     DRAW_INDIRECT_COUNT,
69 };
70 
operator <<(std::ostream & stream,DrawType drawType)71 std::ostream &operator<<(std::ostream &stream, DrawType drawType)
72 {
73     switch (drawType)
74     {
75     case DrawType::DRAW:
76         stream << "draw";
77         break;
78     case DrawType::DRAW_INDIRECT:
79         stream << "draw_indirect";
80         break;
81     case DrawType::DRAW_INDIRECT_COUNT:
82         stream << "draw_indirect_count";
83         break;
84     default:
85         DE_ASSERT(false);
86         break;
87     }
88     return stream;
89 }
90 
91 // This helps test the maxDrawCount rule for the DRAW_INDIRECT_COUNT case.
92 enum class IndirectCountLimitType
93 {
94     BUFFER_VALUE = 0, // The actual count will be given by the count buffer.
95     MAX_COUNT,        // The actual count will be given by the maxDrawCount argument passed to the draw command.
96 };
97 
98 struct IndirectArgs
99 {
100     uint32_t offset;
101     uint32_t stride;
102 };
103 
104 struct TestParams
105 {
106     DrawType drawType;
107     uint32_t seed;
108     uint32_t drawCount;                                    // Equivalent to taskCount or drawCount.
109     uint32_t firstTask;                                    // Equivalent to firstTask in every call.
110     tcu::Maybe<IndirectArgs> indirectArgs;                 // Only used for DRAW_INDIRECT*.
111     tcu::Maybe<IndirectCountLimitType> indirectCountLimit; // Only used for DRAW_INDIRECT_COUNT.
112     tcu::Maybe<uint32_t> indirectCountOffset;              // Only used for DRAW_INDIRECT_COUNT.
113     bool useTask;
114 };
115 
116 // The framebuffer will have a number of rows and 32 columns. Each mesh shader workgroup will generate geometry to fill a single
117 // framebuffer row, using a triangle list with 32 triangles of different colors, each covering a framebuffer pixel.
118 //
119 // Note: the total framebuffer rows is called "full" below (e.g. 64). When using a task shader to generate work, each workgroup will
120 // generate a single mesh workgroup using a push constant instead of a compile-time constant.
121 //
122 // When using DRAW, the task count will tell us how many rows of pixels will be filled in the framebuffer.
123 //
124 // When using indirect draws, the full framebuffer will always be drawn into by using multiple draw command structures, except in
125 // the case of drawCount==0. Each draw will spawn the needed number of tasks to fill the whole framebuffer. In addition, in order to
126 // make all argument structures different, the number of tasks in each draw count will be slightly different and assigned
127 // pseudorandomly.
128 //
129 // DRAW: taskCount=0, taskCount=1, taskCount=2, taskCount=half, taskCount=full
130 //
131 // DRAW_INDIRECT: drawCount=0, drawCount=1, drawCount=2, drawCount=half, drawCount=full.
132 //  * With offset 0 and pseudorandom (multiples of 4).
133 //  * With stride adding a padding of 0 and pseudorandom (multiples of 4).
134 //
135 // DRAW_INDIRECT_COUNT: same as indirect in two variants:
136 //  1. Passing the count in a buffer with a large maximum.
137 //  2. Passing a large value in the buffer and limiting it with the maximum.
138 
139 class MeshApiCase : public vkt::TestCase
140 {
141 public:
MeshApiCase(tcu::TestContext & testCtx,const std::string & name,const TestParams & params)142     MeshApiCase(tcu::TestContext &testCtx, const std::string &name, const TestParams &params)
143         : vkt::TestCase(testCtx, name)
144         , m_params(params)
145     {
146     }
~MeshApiCase(void)147     virtual ~MeshApiCase(void)
148     {
149     }
150 
151     void initPrograms(vk::SourceCollections &programCollection) const override;
152     void checkSupport(Context &context) const override;
153     TestInstance *createInstance(Context &context) const override;
154 
155 protected:
156     TestParams m_params;
157 };
158 
159 class MeshApiInstance : public vkt::TestInstance
160 {
161 public:
MeshApiInstance(Context & context,const TestParams & params)162     MeshApiInstance(Context &context, const TestParams &params) : vkt::TestInstance(context), m_params(params)
163     {
164     }
~MeshApiInstance(void)165     virtual ~MeshApiInstance(void)
166     {
167     }
168 
169     tcu::TestStatus iterate(void) override;
170 
171 protected:
172     TestParams m_params;
173 };
174 
createInstance(Context & context) const175 TestInstance *MeshApiCase::createInstance(Context &context) const
176 {
177     return new MeshApiInstance(context, m_params);
178 }
179 
180 struct PushConstantData
181 {
182     uint32_t width;
183     uint32_t height;
184     uint32_t firstTaskMesh;
185     uint32_t one;
186     uint32_t firstTaskTask;
187 
getRangesvkt::MeshShader::__anon7f9adc6d0111::PushConstantData188     std::vector<VkPushConstantRange> getRanges(bool includeTask) const
189     {
190         constexpr uint32_t offsetMesh = 0u;
191         constexpr uint32_t offsetTask = static_cast<uint32_t>(offsetof(PushConstantData, one));
192         constexpr uint32_t sizeMesh   = offsetTask;
193         constexpr uint32_t sizeTask   = static_cast<uint32_t>(sizeof(PushConstantData)) - offsetTask;
194 
195         const VkPushConstantRange meshRange = {
196             VK_SHADER_STAGE_MESH_BIT_NV, // VkShaderStageFlags stageFlags;
197             offsetMesh,                  // uint32_t offset;
198             sizeMesh,                    // uint32_t size;
199         };
200         const VkPushConstantRange taskRange = {
201             VK_SHADER_STAGE_TASK_BIT_NV, // VkShaderStageFlags stageFlags;
202             offsetTask,                  // uint32_t offset;
203             sizeTask,                    // uint32_t size;
204         };
205 
206         std::vector<VkPushConstantRange> ranges(1u, meshRange);
207         if (includeTask)
208             ranges.push_back(taskRange);
209         return ranges;
210     }
211 };
212 
initPrograms(vk::SourceCollections & programCollection) const213 void MeshApiCase::initPrograms(vk::SourceCollections &programCollection) const
214 {
215     const std::string taskDataDecl = "taskNV TaskData {\n"
216                                      "    uint blockNumber;\n"
217                                      "    uint blockRow;\n"
218                                      "} td;\n";
219 
220     // Task shader if needed.
221     if (m_params.useTask)
222     {
223         std::ostringstream task;
224         task << "#version 460\n"
225              << "#extension GL_NV_mesh_shader : enable\n"
226              << "\n"
227              << "layout (local_size_x=1) in;\n"
228              << "\n"
229              << "layout (push_constant, std430) uniform TaskPushConstantBlock {\n"
230              << "    layout (offset=12) uint one;\n"
231              << "    layout (offset=16) uint firstTask;\n"
232              << "} pc;\n"
233              << "\n"
234              << "out " << taskDataDecl << "\n"
235              << "void main ()\n"
236              << "{\n"
237              << "    gl_TaskCountNV  = pc.one;\n"
238              << "    td.blockNumber  = uint(gl_DrawID);\n"
239              << "    td.blockRow     = gl_WorkGroupID.x - pc.firstTask;\n"
240              << "}\n";
241         programCollection.glslSources.add("task") << glu::TaskSource(task.str());
242     }
243 
244     // Mesh shader.
245     {
246         std::ostringstream mesh;
247         mesh << "#version 460\n"
248              << "#extension GL_NV_mesh_shader : enable\n"
249              << "\n"
250              << "layout (local_size_x=32) in;\n"
251              << "layout (triangles) out;\n"
252              << "layout (max_vertices=96, max_primitives=32) out;\n"
253              << "\n"
254              << "layout (push_constant, std430) uniform MeshPushConstantBlock {\n"
255              << "    uint width;\n"
256              << "    uint height;\n"
257              << "    uint firstTask;\n"
258              << "} pc;\n"
259              << "\n"
260              << "layout (location=0) perprimitiveNV out vec4 primitiveColor[];\n"
261              << "\n"
262              << (m_params.useTask ? ("in " + taskDataDecl) : "") << "\n"
263              << "layout (set=0, binding=0, std430) readonly buffer BlockSizes {\n"
264              << "    uint blockSize[];\n"
265              << "} bsz;\n"
266              << "\n"
267              << "uint startOfBlock (uint blockNumber)\n"
268              << "{\n"
269              << "    uint start = 0;\n"
270              << "    for (uint i = 0; i < blockNumber; i++)\n"
271              << "        start += bsz.blockSize[i];\n"
272              << "    return start;\n"
273              << "}\n"
274              << "\n"
275              << "void main ()\n"
276              << "{\n"
277              << "    const uint blockNumber = " << (m_params.useTask ? "td.blockNumber" : "uint(gl_DrawID)") << ";\n"
278              << "    const uint blockRow = " << (m_params.useTask ? "td.blockRow" : "(gl_WorkGroupID.x - pc.firstTask)")
279              << ";\n"
280              << "\n"
281              << "    // Each workgroup will fill one row, and each invocation will generate a\n"
282              << "    // triangle around the pixel center in each column.\n"
283              << "    const uint row = startOfBlock(blockNumber) + blockRow;\n"
284              << "    const uint col = gl_LocalInvocationID.x;\n"
285              << "\n"
286              << "    const float fHeight = float(pc.height);\n"
287              << "    const float fWidth = float(pc.width);\n"
288              << "\n"
289              << "    // Pixel coordinates, normalized.\n"
290              << "    const float rowNorm = (float(row) + 0.5) / fHeight;\n"
291              << "    const float colNorm = (float(col) + 0.5) / fWidth;\n"
292              << "\n"
293              << "    // Framebuffer coordinates.\n"
294              << "    const float coordX = (colNorm * 2.0) - 1.0;\n"
295              << "    const float coordY = (rowNorm * 2.0) - 1.0;\n"
296              << "\n"
297              << "    const float pixelWidth = 2.0 / fWidth;\n"
298              << "    const float pixelHeight = 2.0 / fHeight;\n"
299              << "\n"
300              << "    const float offsetX = pixelWidth / 2.0;\n"
301              << "    const float offsetY = pixelHeight / 2.0;\n"
302              << "\n"
303              << "    const uint baseIndex = col*3;\n"
304              << "    const uvec3 indices = uvec3(baseIndex, baseIndex + 1, baseIndex + 2);\n"
305              << "\n"
306              << "    gl_PrimitiveCountNV = 32u;\n"
307              << "    primitiveColor[col] = vec4(rowNorm, colNorm, 0.0, 1.0);\n"
308              << "\n"
309              << "    gl_PrimitiveIndicesNV[indices.x] = indices.x;\n"
310              << "    gl_PrimitiveIndicesNV[indices.y] = indices.y;\n"
311              << "    gl_PrimitiveIndicesNV[indices.z] = indices.z;\n"
312              << "\n"
313              << "    gl_MeshVerticesNV[indices.x].gl_Position = vec4(coordX - offsetX, coordY + offsetY, 0.0, 1.0);\n"
314              << "    gl_MeshVerticesNV[indices.y].gl_Position = vec4(coordX + offsetX, coordY + offsetY, 0.0, 1.0);\n"
315              << "    gl_MeshVerticesNV[indices.z].gl_Position = vec4(coordX, coordY - offsetY, 0.0, 1.0);\n"
316              << "}\n";
317         programCollection.glslSources.add("mesh") << glu::MeshSource(mesh.str());
318     }
319 
320     // Frag shader.
321     {
322         std::ostringstream frag;
323         frag << "#version 460\n"
324              << "#extension GL_NV_mesh_shader : enable\n"
325              << "\n"
326              << "layout (location=0) perprimitiveNV in vec4 primitiveColor;\n"
327              << "layout (location=0) out vec4 outColor;\n"
328              << "\n"
329              << "void main ()\n"
330              << "{\n"
331              << "    outColor = primitiveColor;\n"
332              << "}\n";
333         programCollection.glslSources.add("frag") << glu::FragmentSource(frag.str());
334     }
335 }
336 
checkSupport(Context & context) const337 void MeshApiCase::checkSupport(Context &context) const
338 {
339     checkTaskMeshShaderSupportNV(context, m_params.useTask, true);
340 
341     // VUID-vkCmdDrawMeshTasksIndirectNV-drawCount-02718
342     if (m_params.drawType == DrawType::DRAW_INDIRECT && m_params.drawCount > 1u)
343     {
344         context.requireDeviceCoreFeature(DEVICE_CORE_FEATURE_MULTI_DRAW_INDIRECT);
345     }
346 
347     // VUID-vkCmdDrawMeshTasksIndirectCountNV-None-04445
348     if (m_params.drawType == DrawType::DRAW_INDIRECT_COUNT)
349         context.requireDeviceFunctionality("VK_KHR_draw_indirect_count");
350 }
351 
352 template <typename T>
makeStridedBuffer(const DeviceInterface & vkd,VkDevice device,Allocator & alloc,const std::vector<T> & elements,uint32_t offset,uint32_t stride,VkBufferUsageFlags usage,uint32_t endPadding)353 BufferWithMemoryPtr makeStridedBuffer(const DeviceInterface &vkd, VkDevice device, Allocator &alloc,
354                                       const std::vector<T> &elements, uint32_t offset, uint32_t stride,
355                                       VkBufferUsageFlags usage, uint32_t endPadding)
356 {
357     const auto elementSize  = static_cast<uint32_t>(sizeof(T));
358     const auto actualStride = std::max(elementSize, stride);
359     const auto bufferSize   = static_cast<size_t>(offset) + static_cast<size_t>(actualStride) * elements.size() +
360                             static_cast<size_t>(endPadding);
361     const auto bufferInfo = makeBufferCreateInfo(static_cast<VkDeviceSize>(bufferSize), usage);
362 
363     BufferWithMemoryPtr buffer(new BufferWithMemory(vkd, device, alloc, bufferInfo, MemoryRequirement::HostVisible));
364     auto &bufferAlloc   = buffer->getAllocation();
365     char *bufferDataPtr = reinterpret_cast<char *>(bufferAlloc.getHostPtr());
366 
367     char *itr = bufferDataPtr + offset;
368     for (const auto &elem : elements)
369     {
370         deMemcpy(itr, &elem, sizeof(elem));
371         itr += actualStride;
372     }
373     if (endPadding > 0u)
374         deMemset(itr, 0xFF, endPadding);
375 
376     flushAlloc(vkd, device, bufferAlloc);
377 
378     return buffer;
379 }
380 
getExtent()381 VkExtent3D getExtent()
382 {
383     return makeExtent3D(32u, 64u, 1u);
384 }
385 
iterate(void)386 tcu::TestStatus MeshApiInstance::iterate(void)
387 {
388     const auto &vkd       = m_context.getDeviceInterface();
389     const auto device     = m_context.getDevice();
390     auto &alloc           = m_context.getDefaultAllocator();
391     const auto queueIndex = m_context.getUniversalQueueFamilyIndex();
392     const auto queue      = m_context.getUniversalQueue();
393 
394     const auto extent = getExtent();
395     const auto iExtent3D =
396         tcu::IVec3(static_cast<int>(extent.width), static_cast<int>(extent.height), static_cast<int>(extent.depth));
397     const auto iExtent2D  = tcu::IVec2(iExtent3D.x(), iExtent3D.y());
398     const auto format     = VK_FORMAT_R8G8B8A8_UNORM;
399     const auto tcuFormat  = mapVkFormat(format);
400     const auto colorUsage = (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT);
401     const auto colorSRR   = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, 1u);
402     const tcu::Vec4 clearColor(0.0f, 0.0f, 0.0f, 1.0f);
403     const float colorThres = 0.005f; // 1/255 < 0.005 < 2/255
404     const tcu::Vec4 threshold(colorThres, colorThres, 0.0f, 0.0f);
405 
406     ImageWithMemoryPtr colorBuffer;
407     Move<VkImageView> colorBufferView;
408     {
409         const VkImageCreateInfo colorBufferInfo = {
410             VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, // VkStructureType sType;
411             nullptr,                             // const void* pNext;
412             0u,                                  // VkImageCreateFlags flags;
413             VK_IMAGE_TYPE_2D,                    // VkImageType imageType;
414             format,                              // VkFormat format;
415             extent,                              // VkExtent3D extent;
416             1u,                                  // uint32_t mipLevels;
417             1u,                                  // uint32_t arrayLayers;
418             VK_SAMPLE_COUNT_1_BIT,               // VkSampleCountFlagBits samples;
419             VK_IMAGE_TILING_OPTIMAL,             // VkImageTiling tiling;
420             colorUsage,                          // VkImageUsageFlags usage;
421             VK_SHARING_MODE_EXCLUSIVE,           // VkSharingMode sharingMode;
422             0u,                                  // uint32_t queueFamilyIndexCount;
423             nullptr,                             // const uint32_t* pQueueFamilyIndices;
424             VK_IMAGE_LAYOUT_UNDEFINED,           // VkImageLayout initialLayout;
425         };
426         colorBuffer =
427             ImageWithMemoryPtr(new ImageWithMemory(vkd, device, alloc, colorBufferInfo, MemoryRequirement::Any));
428         colorBufferView = makeImageView(vkd, device, colorBuffer->get(), VK_IMAGE_VIEW_TYPE_2D, format, colorSRR);
429     }
430 
431     // Prepare buffer containing the array of block sizes.
432     de::Random rnd(m_params.seed);
433     std::vector<uint32_t> blockSizes;
434 
435     const uint32_t vectorSize = std::max(1u, m_params.drawCount);
436     const uint32_t largeDrawCount =
437         vectorSize + 1u; // The indirect buffer needs to have some padding at the end. See below.
438     const uint32_t evenBlockSize = extent.height / vectorSize;
439     uint32_t remainingRows       = extent.height;
440 
441     blockSizes.reserve(vectorSize);
442     for (uint32_t i = 0; i < vectorSize - 1u; ++i)
443     {
444         const auto blockSize = static_cast<uint32_t>(rnd.getInt(1, evenBlockSize));
445         remainingRows -= blockSize;
446         blockSizes.push_back(blockSize);
447     }
448     blockSizes.push_back(remainingRows);
449 
450     const auto blockSizesBufferSize = static_cast<VkDeviceSize>(de::dataSize(blockSizes));
451     BufferWithMemoryPtr blockSizesBuffer =
452         makeStridedBuffer(vkd, device, alloc, blockSizes, 0u, 0u, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, 0u);
453 
454     // Descriptor set layout, pool and set.
455     DescriptorSetLayoutBuilder layoutBuilder;
456     layoutBuilder.addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_SHADER_STAGE_MESH_BIT_NV);
457     const auto setLayout = layoutBuilder.build(vkd, device);
458 
459     DescriptorPoolBuilder poolBuilder;
460     poolBuilder.addType(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
461     const auto descriptorPool = poolBuilder.build(vkd, device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, 1u);
462 
463     const auto descriptorSet = makeDescriptorSet(vkd, device, descriptorPool.get(), setLayout.get());
464 
465     // Update descriptor set.
466     {
467         DescriptorSetUpdateBuilder updateBuilder;
468 
469         const auto location             = DescriptorSetUpdateBuilder::Location::binding(0u);
470         const auto descriptorBufferInfo = makeDescriptorBufferInfo(blockSizesBuffer->get(), 0ull, blockSizesBufferSize);
471 
472         updateBuilder.writeSingle(descriptorSet.get(), location, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
473                                   &descriptorBufferInfo);
474         updateBuilder.update(vkd, device);
475     }
476 
477     // Pipeline layout.
478     PushConstantData pcData;
479     const auto pcRanges       = pcData.getRanges(m_params.useTask);
480     const auto pipelineLayout = makePipelineLayout(vkd, device, 1u, &setLayout.get(),
481                                                    static_cast<uint32_t>(pcRanges.size()), de::dataOrNull(pcRanges));
482 
483     // Push constants.
484     pcData.width         = extent.width;
485     pcData.height        = extent.height;
486     pcData.firstTaskMesh = m_params.firstTask;
487     pcData.one           = 1u;
488     pcData.firstTaskTask = m_params.firstTask;
489 
490     // Render pass and framebuffer.
491     const auto renderPass = makeRenderPass(vkd, device, format);
492     const auto framebuffer =
493         makeFramebuffer(vkd, device, renderPass.get(), colorBufferView.get(), extent.width, extent.height);
494 
495     // Pipeline.
496     Move<VkShaderModule> taskModule;
497     Move<VkShaderModule> meshModule;
498     Move<VkShaderModule> fragModule;
499 
500     const auto &binaries = m_context.getBinaryCollection();
501     if (m_params.useTask)
502         taskModule = createShaderModule(vkd, device, binaries.get("task"));
503     meshModule = createShaderModule(vkd, device, binaries.get("mesh"));
504     fragModule = createShaderModule(vkd, device, binaries.get("frag"));
505 
506     const std::vector<VkViewport> viewports(1u, makeViewport(extent));
507     const std::vector<VkRect2D> scissors(1u, makeRect2D(extent));
508 
509     const auto pipeline = makeGraphicsPipeline(vkd, device, pipelineLayout.get(), taskModule.get(), meshModule.get(),
510                                                fragModule.get(), renderPass.get(), viewports, scissors);
511 
512     // Command pool and buffer.
513     const auto cmdPool      = makeCommandPool(vkd, device, queueIndex);
514     const auto cmdBufferPtr = allocateCommandBuffer(vkd, device, cmdPool.get(), VK_COMMAND_BUFFER_LEVEL_PRIMARY);
515     const auto cmdBuffer    = cmdBufferPtr.get();
516 
517     // Indirect and count buffers if needed.
518     BufferWithMemoryPtr indirectBuffer;
519     BufferWithMemoryPtr countBuffer;
520 
521     if (m_params.drawType != DrawType::DRAW)
522     {
523         // Indirect draws.
524         DE_ASSERT(static_cast<bool>(m_params.indirectArgs));
525         const auto &indirectArgs = m_params.indirectArgs.get();
526 
527         // Check stride and offset validity.
528         DE_ASSERT(indirectArgs.offset % 4u == 0u);
529         DE_ASSERT(indirectArgs.stride % 4u == 0u &&
530                   (indirectArgs.stride == 0u ||
531                    indirectArgs.stride >= static_cast<uint32_t>(sizeof(VkDrawMeshTasksIndirectCommandNV))));
532 
533         // Prepare struct vector, which will be converted to a buffer with the proper stride and offset later.
534         std::vector<VkDrawMeshTasksIndirectCommandNV> commands;
535         commands.reserve(blockSizes.size());
536 
537         std::transform(begin(blockSizes), end(blockSizes), std::back_inserter(commands),
538                        [this](uint32_t blockSize) {
539                            return VkDrawMeshTasksIndirectCommandNV{blockSize, this->m_params.firstTask};
540                        });
541 
542         const auto padding = static_cast<uint32_t>(sizeof(VkDrawMeshTasksIndirectCommandNV));
543         indirectBuffer     = makeStridedBuffer(vkd, device, alloc, commands, indirectArgs.offset, indirectArgs.stride,
544                                                VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT, padding);
545 
546         // Prepare count buffer if needed.
547         if (m_params.drawType == DrawType::DRAW_INDIRECT_COUNT)
548         {
549             DE_ASSERT(static_cast<bool>(m_params.indirectCountLimit));
550             DE_ASSERT(static_cast<bool>(m_params.indirectCountOffset));
551 
552             const auto countBufferValue =
553                 ((m_params.indirectCountLimit.get() == IndirectCountLimitType::BUFFER_VALUE) ? m_params.drawCount :
554                                                                                                largeDrawCount);
555 
556             const std::vector<uint32_t> singleCount(1u, countBufferValue);
557             countBuffer =
558                 makeStridedBuffer(vkd, device, alloc, singleCount, m_params.indirectCountOffset.get(),
559                                   static_cast<uint32_t>(sizeof(uint32_t)), VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT, 0u);
560         }
561     }
562 
563     // Submit commands.
564     beginCommandBuffer(vkd, cmdBuffer);
565     beginRenderPass(vkd, cmdBuffer, renderPass.get(), framebuffer.get(), scissors.at(0), clearColor);
566 
567     vkd.cmdBindDescriptorSets(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout.get(), 0u, 1u,
568                               &descriptorSet.get(), 0u, nullptr);
569     {
570         const char *pcDataPtr = reinterpret_cast<const char *>(&pcData);
571         for (const auto &range : pcRanges)
572             vkd.cmdPushConstants(cmdBuffer, pipelineLayout.get(), range.stageFlags, range.offset, range.size,
573                                  pcDataPtr + range.offset);
574     }
575     vkd.cmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.get());
576 
577     if (m_params.drawType == DrawType::DRAW)
578     {
579         vkd.cmdDrawMeshTasksNV(cmdBuffer, m_params.drawCount, m_params.firstTask);
580     }
581     else if (m_params.drawType == DrawType::DRAW_INDIRECT)
582     {
583         const auto &indirectArgs = m_params.indirectArgs.get();
584         vkd.cmdDrawMeshTasksIndirectNV(cmdBuffer, indirectBuffer->get(), indirectArgs.offset, m_params.drawCount,
585                                        indirectArgs.stride);
586     }
587     else if (m_params.drawType == DrawType::DRAW_INDIRECT_COUNT)
588     {
589         const auto &indirectArgs        = m_params.indirectArgs.get();
590         const auto &indirectCountOffset = m_params.indirectCountOffset.get();
591         const auto &indirectCountLimit  = m_params.indirectCountLimit.get();
592 
593         const auto maxCount =
594             ((indirectCountLimit == IndirectCountLimitType::MAX_COUNT) ? m_params.drawCount : largeDrawCount);
595         vkd.cmdDrawMeshTasksIndirectCountNV(cmdBuffer, indirectBuffer->get(), indirectArgs.offset, countBuffer->get(),
596                                             indirectCountOffset, maxCount, indirectArgs.stride);
597     }
598     else
599         DE_ASSERT(false);
600 
601     endRenderPass(vkd, cmdBuffer);
602 
603     // Output buffer to extract the color buffer.
604     BufferWithMemoryPtr outBuffer;
605     void *outBufferData = nullptr;
606     {
607         const auto outBufferSize  = static_cast<VkDeviceSize>(static_cast<uint32_t>(tcu::getPixelSize(tcuFormat)) *
608                                                              extent.width * extent.height);
609         const auto outBufferUsage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
610         const auto outBufferInfo  = makeBufferCreateInfo(outBufferSize, outBufferUsage);
611 
612         outBuffer = BufferWithMemoryPtr(
613             new BufferWithMemory(vkd, device, alloc, outBufferInfo, MemoryRequirement::HostVisible));
614         outBufferData = outBuffer->getAllocation().getHostPtr();
615     }
616 
617     copyImageToBuffer(vkd, cmdBuffer, colorBuffer->get(), outBuffer->get(), iExtent2D);
618     endCommandBuffer(vkd, cmdBuffer);
619     submitCommandsAndWait(vkd, device, queue, cmdBuffer);
620 
621     // Generate reference image and compare.
622     {
623         auto &log            = m_context.getTestContext().getLog();
624         auto &outBufferAlloc = outBuffer->getAllocation();
625         tcu::ConstPixelBufferAccess result(tcuFormat, iExtent3D, outBufferData);
626         tcu::TextureLevel referenceLevel(tcuFormat, iExtent3D.x(), iExtent3D.y());
627         const auto reference = referenceLevel.getAccess();
628         const auto setName   = de::toString(m_params.drawType) + "_draw_count_" + de::toString(m_params.drawCount) +
629                              (m_params.useTask ? "_with_task" : "_no_task");
630         const auto fHeight = static_cast<float>(extent.height);
631         const auto fWidth  = static_cast<float>(extent.width);
632 
633         invalidateAlloc(vkd, device, outBufferAlloc);
634 
635         for (int y = 0; y < iExtent3D.y(); ++y)
636             for (int x = 0; x < iExtent3D.x(); ++x)
637             {
638                 const tcu::Vec4 refColor = ((m_params.drawCount == 0u || (m_params.drawType == DrawType::DRAW &&
639                                                                           y >= static_cast<int>(m_params.drawCount))) ?
640                                                 clearColor :
641                                                 tcu::Vec4(
642                                                     // These match the per-primitive color set by the mesh shader.
643                                                     (static_cast<float>(y) + 0.5f) / fHeight,
644                                                     (static_cast<float>(x) + 0.5f) / fWidth, 0.0f, 1.0f));
645                 reference.setPixel(refColor, x, y);
646             }
647 
648         if (!tcu::floatThresholdCompare(log, setName.c_str(), "", reference, result, threshold,
649                                         tcu::COMPARE_LOG_ON_ERROR))
650             return tcu::TestStatus::fail("Image comparison failed; check log for details");
651     }
652 
653     return tcu::TestStatus::pass("Pass");
654 }
655 
656 } // namespace
657 
createMeshShaderApiTests(tcu::TestContext & testCtx)658 tcu::TestCaseGroup *createMeshShaderApiTests(tcu::TestContext &testCtx)
659 {
660     GroupPtr mainGroup(new tcu::TestCaseGroup(testCtx, "api"));
661 
662     const DrawType drawCases[] = {
663         DrawType::DRAW,
664         DrawType::DRAW_INDIRECT,
665         DrawType::DRAW_INDIRECT_COUNT,
666     };
667 
668     const auto extent               = getExtent();
669     const uint32_t drawCountCases[] = {0u, 1u, 2u, extent.height / 2u, extent.height};
670 
671     const uint32_t normalStride = static_cast<uint32_t>(sizeof(VkDrawMeshTasksIndirectCommandNV));
672     const uint32_t largeStride  = 2u * normalStride + 4u;
673     const uint32_t altOffset    = 20u;
674 
675     const struct
676     {
677         tcu::Maybe<IndirectArgs> indirectArgs;
678         const char *name;
679     } indirectArgsCases[] = {
680         {tcu::nothing<IndirectArgs>(), "no_indirect_args"},
681 
682         // Offset 0, varying strides.
683         {tcu::just(IndirectArgs{0u, 0u}), "offset_0_stride_0"},
684         {tcu::just(IndirectArgs{0u, normalStride}), "offset_0_stride_normal"},
685         {tcu::just(IndirectArgs{0u, largeStride}), "offset_0_stride_large"},
686 
687         // Nonzero offset, varying strides.
688         {tcu::just(IndirectArgs{altOffset, 0u}), "offset_alt_stride_0"},
689         {tcu::just(IndirectArgs{altOffset, normalStride}), "offset_alt_stride_normal"},
690         {tcu::just(IndirectArgs{altOffset, largeStride}), "offset_alt_stride_large"},
691     };
692 
693     const struct
694     {
695         tcu::Maybe<IndirectCountLimitType> limitType;
696         const char *name;
697     } countLimitCases[] = {
698         {tcu::nothing<IndirectCountLimitType>(), "no_count_limit"},
699         {tcu::just(IndirectCountLimitType::BUFFER_VALUE), "count_limit_buffer"},
700         {tcu::just(IndirectCountLimitType::MAX_COUNT), "count_limit_max_count"},
701     };
702 
703     const struct
704     {
705         tcu::Maybe<uint32_t> countOffset;
706         const char *name;
707     } countOffsetCases[] = {
708         {tcu::nothing<uint32_t>(), "no_count_offset"},
709         {tcu::just(uint32_t{0u}), "count_offset_0"},
710         {tcu::just(altOffset), "count_offset_alt"},
711     };
712 
713     const struct
714     {
715         bool useTask;
716         const char *name;
717     } taskCases[] = {
718         {false, "no_task_shader"},
719         {true, "with_task_shader"},
720     };
721 
722     const struct
723     {
724         uint32_t firstTask;
725         const char *name;
726     } firstTaskCases[] = {
727         {0u, "first_task_zero"},
728         {1001u, "first_task_nonzero"},
729     };
730 
731     uint32_t seed = 1628678795u;
732 
733     for (const auto &drawCase : drawCases)
734     {
735         const auto drawCaseName      = de::toString(drawCase);
736         const bool isIndirect        = (drawCase != DrawType::DRAW);
737         const bool isIndirectNoCount = (drawCase == DrawType::DRAW_INDIRECT);
738         const bool isIndirectCount   = (drawCase == DrawType::DRAW_INDIRECT_COUNT);
739 
740         GroupPtr drawGroup(new tcu::TestCaseGroup(testCtx, drawCaseName.c_str()));
741 
742         for (const auto &drawCountCase : drawCountCases)
743         {
744             const auto drawCountName = "draw_count_" + de::toString(drawCountCase);
745             GroupPtr drawCountGroup(new tcu::TestCaseGroup(testCtx, drawCountName.c_str()));
746 
747             for (const auto &indirectArgsCase : indirectArgsCases)
748             {
749                 const bool hasIndirectArgs = static_cast<bool>(indirectArgsCase.indirectArgs);
750                 const bool strideZero      = (hasIndirectArgs && indirectArgsCase.indirectArgs.get().stride == 0u);
751 
752                 if (isIndirect != hasIndirectArgs)
753                     continue;
754 
755                 // VUID-vkCmdDrawMeshTasksIndirectNV-drawCount-02146 and VUID-vkCmdDrawMeshTasksIndirectCountNV-stride-02182.
756                 if (((isIndirectNoCount && drawCountCase > 1u) || isIndirectCount) && strideZero)
757                     continue;
758 
759                 GroupPtr indirectArgsGroup(new tcu::TestCaseGroup(testCtx, indirectArgsCase.name));
760 
761                 for (const auto &countLimitCase : countLimitCases)
762                 {
763                     const bool hasCountLimit = static_cast<bool>(countLimitCase.limitType);
764 
765                     if (isIndirectCount != hasCountLimit)
766                         continue;
767 
768                     GroupPtr countLimitGroup(new tcu::TestCaseGroup(testCtx, countLimitCase.name));
769 
770                     for (const auto &countOffsetCase : countOffsetCases)
771                     {
772                         const bool hasCountOffsetType = static_cast<bool>(countOffsetCase.countOffset);
773 
774                         if (isIndirectCount != hasCountOffsetType)
775                             continue;
776 
777                         GroupPtr countOffsetGroup(new tcu::TestCaseGroup(testCtx, countOffsetCase.name));
778 
779                         for (const auto &taskCase : taskCases)
780                         {
781                             GroupPtr taskCaseGrp(new tcu::TestCaseGroup(testCtx, taskCase.name));
782 
783                             for (const auto &firstTaskCase : firstTaskCases)
784                             {
785                                 const TestParams params = {
786                                     drawCase,                      // DrawType drawType;
787                                     seed++,                        // uint32_t seed;
788                                     drawCountCase,                 // uint32_t drawCount;
789                                     firstTaskCase.firstTask,       // uint32_t firstTask;
790                                     indirectArgsCase.indirectArgs, // tcu::Maybe<IndirectArgs> indirectArgs;
791                                     countLimitCase.limitType, // tcu::Maybe<IndirectCountLimitType> indirectCountLimit;
792                                     countOffsetCase.countOffset, // tcu::Maybe<uint32_t> indirectCountOffset;
793                                     taskCase.useTask,            // bool useTask;
794                                 };
795 
796                                 taskCaseGrp->addChild(new MeshApiCase(testCtx, firstTaskCase.name, params));
797                             }
798 
799                             countOffsetGroup->addChild(taskCaseGrp.release());
800                         }
801 
802                         countLimitGroup->addChild(countOffsetGroup.release());
803                     }
804 
805                     indirectArgsGroup->addChild(countLimitGroup.release());
806                 }
807 
808                 drawCountGroup->addChild(indirectArgsGroup.release());
809             }
810 
811             drawGroup->addChild(drawCountGroup.release());
812         }
813 
814         mainGroup->addChild(drawGroup.release());
815     }
816 
817     return mainGroup.release();
818 }
819 
820 } // namespace MeshShader
821 } // namespace vkt
822