Improve GLSL source program support
[platform/upstream/VK-GL-CTS.git] / external / vulkancts / modules / vulkan / clipping / vktClippingTests.cpp
1 /*------------------------------------------------------------------------
2  * Vulkan Conformance Tests
3  * ------------------------
4  *
5  * Copyright (c) 2016 The Khronos Group Inc.
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  *//*!
20  * \file
21  * \brief Clipping tests
22  *//*--------------------------------------------------------------------*/
23
24 #include "vktClippingTests.hpp"
25 #include "vktTestCase.hpp"
26 #include "vktTestGroupUtil.hpp"
27 #include "vktTestCaseUtil.hpp"
28 #include "vktClippingUtil.hpp"
29 #include "vkRefUtil.hpp"
30 #include "vkTypeUtil.hpp"
31 #include "vkImageUtil.hpp"
32 #include "tcuTestLog.hpp"
33 #include "deUniquePtr.hpp"
34 #include "deStringUtil.hpp"
35 #include "deRandom.hpp"
36
37 namespace vkt
38 {
39 namespace clipping
40 {
41 namespace
42 {
43 using namespace vk;
44 using de::MovePtr;
45 using tcu::UVec2;
46 using tcu::Vec4;
47 using tcu::IVec2;
48
49 enum Constants
50 {
51         RENDER_SIZE                                                             = 16,
52         RENDER_SIZE_LARGE                                               = 128,
53         NUM_RENDER_PIXELS                                               = RENDER_SIZE * RENDER_SIZE,
54         NUM_PATCH_CONTROL_POINTS                                = 3,
55         MAX_NUM_SHADER_MODULES                                  = 5,
56         MAX_CLIP_DISTANCES                                              = 8,
57         MAX_CULL_DISTANCES                                              = 8,
58         MAX_COMBINED_CLIP_AND_CULL_DISTANCES    = 8,
59 };
60
61 struct Shader
62 {
63         VkShaderStageFlagBits   stage;
64         const ProgramBinary*    binary;
65
66         Shader (const VkShaderStageFlagBits stage_, const ProgramBinary& binary_)
67                 : stage         (stage_)
68                 , binary        (&binary_)
69         {
70         }
71 };
72
73 //! Sets up a graphics pipeline and enables simple draw calls to predefined attachments.
74 //! Clip volume uses wc = 1.0, which gives clip coord ranges: x = [-1, 1], y = [-1, 1], z = [0, 1]
75 //! Clip coords (-1,-1) map to viewport coords (0, 0).
76 class DrawContext
77 {
78 public:
79                                                                         DrawContext             (Context&                                               context,
80                                                                                                          const std::vector<Shader>&             shaders,
81                                                                                                          const std::vector<Vec4>&               vertices,
82                                                                                                          const VkPrimitiveTopology              primitiveTopology,
83                                                                                                          const deUint32                                 renderSize                      = static_cast<deUint32>(RENDER_SIZE),
84                                                                                                          const bool                                             depthClampEnable        = false,
85                                                                                                          const bool                                             blendEnable                     = false,
86                                                                                                          const float                                    lineWidth                       = 1.0f);
87
88         void                                                    draw                    (void);
89         tcu::ConstPixelBufferAccess             getColorPixels  (void) const;
90
91 private:
92         Context&                                                m_context;
93         const VkFormat                                  m_colorFormat;
94         const VkImageSubresourceRange   m_colorSubresourceRange;
95         const UVec2                                             m_renderSize;
96         const VkExtent3D                                m_imageExtent;
97         const VkPrimitiveTopology               m_primitiveTopology;
98         const bool                                              m_depthClampEnable;
99         const bool                                              m_blendEnable;
100         const deUint32                                  m_numVertices;
101         const float                                             m_lineWidth;
102         const deUint32                                  m_numPatchControlPoints;
103         MovePtr<Buffer>                                 m_vertexBuffer;
104         MovePtr<Image>                                  m_colorImage;
105         MovePtr<Buffer>                                 m_colorAttachmentBuffer;
106         Move<VkImageView>                               m_colorImageView;
107         Move<VkRenderPass>                              m_renderPass;
108         Move<VkFramebuffer>                             m_framebuffer;
109         Move<VkPipelineLayout>                  m_pipelineLayout;
110         Move<VkPipeline>                                m_pipeline;
111         Move<VkCommandPool>                             m_cmdPool;
112         Move<VkCommandBuffer>                   m_cmdBuffer;
113         Move<VkShaderModule>                    m_shaderModules[MAX_NUM_SHADER_MODULES];
114
115                                                                         DrawContext             (const DrawContext&);   // "deleted"
116         DrawContext&                                    operator=               (const DrawContext&);   // "deleted"
117 };
118
119 DrawContext::DrawContext (Context&                                              context,
120                                                   const std::vector<Shader>&    shaders,
121                                                   const std::vector<Vec4>&              vertices,
122                                                   const VkPrimitiveTopology             primitiveTopology,
123                                                   const deUint32                                renderSize,
124                                                   const bool                                    depthClampEnable,
125                                                   const bool                                    blendEnable,
126                                                   const float                                   lineWidth)
127         : m_context                                     (context)
128         , m_colorFormat                         (VK_FORMAT_R8G8B8A8_UNORM)
129         , m_colorSubresourceRange       (makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, 1u))
130         , m_renderSize                          (renderSize, renderSize)
131         , m_imageExtent                         (makeExtent3D(m_renderSize.x(), m_renderSize.y(), 1u))
132         , m_primitiveTopology           (primitiveTopology)
133         , m_depthClampEnable            (depthClampEnable)
134         , m_blendEnable                         (blendEnable)
135         , m_numVertices                         (static_cast<deUint32>(vertices.size()))
136         , m_lineWidth                           (lineWidth)
137         , m_numPatchControlPoints       (NUM_PATCH_CONTROL_POINTS)              // we're treating patches as triangles
138 {
139         const DeviceInterface&  vk                      = m_context.getDeviceInterface();
140         const VkDevice                  device          = m_context.getDevice();
141         Allocator&                              allocator       = m_context.getDefaultAllocator();
142
143         // Command buffer
144         {
145                 m_cmdPool       = makeCommandPool(vk, device, m_context.getUniversalQueueFamilyIndex());
146                 m_cmdBuffer     = makeCommandBuffer(vk, device, *m_cmdPool);
147         }
148
149         // Color attachment image
150         {
151                 const VkImageUsageFlags usage                   = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
152                 const VkImageCreateInfo imageCreateInfo =
153                 {
154                         VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,            // VkStructureType          sType;
155                         DE_NULL,                                                                        // const void*              pNext;
156                         (VkImageCreateFlags)0,                                          // VkImageCreateFlags       flags;
157                         VK_IMAGE_TYPE_2D,                                                       // VkImageType              imageType;
158                         m_colorFormat,                                                          // VkFormat                 format;
159                         m_imageExtent,                                                          // VkExtent3D               extent;
160                         1u,                                                                                     // uint32_t                 mipLevels;
161                         1u,                                                                                     // uint32_t                 arrayLayers;
162                         VK_SAMPLE_COUNT_1_BIT,                                          // VkSampleCountFlagBits    samples;
163                         VK_IMAGE_TILING_OPTIMAL,                                        // VkImageTiling            tiling;
164                         usage,                                                                          // VkImageUsageFlags        usage;
165                         VK_SHARING_MODE_EXCLUSIVE,                                      // VkSharingMode            sharingMode;
166                         VK_QUEUE_FAMILY_IGNORED,                                        // uint32_t                 queueFamilyIndexCount;
167                         DE_NULL,                                                                        // const uint32_t*          pQueueFamilyIndices;
168                         VK_IMAGE_LAYOUT_UNDEFINED,                                      // VkImageLayout            initialLayout;
169                 };
170
171                 m_colorImage = MovePtr<Image>(new Image(vk, device, allocator, imageCreateInfo, MemoryRequirement::Any));
172                 m_colorImageView = makeImageView(vk, device, **m_colorImage, VK_IMAGE_VIEW_TYPE_2D, m_colorFormat, m_colorSubresourceRange);
173
174                 // Buffer to copy attachment data after rendering
175
176                 const VkDeviceSize bitmapSize = tcu::getPixelSize(mapVkFormat(m_colorFormat)) * m_renderSize.x() * m_renderSize.y();
177                 m_colorAttachmentBuffer = MovePtr<Buffer>(new Buffer(
178                         vk, device, allocator, makeBufferCreateInfo(bitmapSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT), MemoryRequirement::HostVisible));
179
180                 {
181                         const Allocation& alloc = m_colorAttachmentBuffer->getAllocation();
182                         deMemset(alloc.getHostPtr(), 0, (size_t)bitmapSize);
183                         flushMappedMemoryRange(vk, device, alloc.getMemory(), alloc.getOffset(), bitmapSize);
184                 }
185         }
186
187         // Vertex buffer
188         {
189                 const VkDeviceSize bufferSize = vertices.size() * sizeof(vertices[0]);
190                 m_vertexBuffer = MovePtr<Buffer>(new Buffer(
191                         vk, device, allocator, makeBufferCreateInfo(bufferSize, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT), MemoryRequirement::HostVisible));
192
193                 const Allocation& alloc = m_vertexBuffer->getAllocation();
194                 deMemcpy(alloc.getHostPtr(), &vertices[0], (size_t)bufferSize);
195                 flushMappedMemoryRange(vk, device, alloc.getMemory(), alloc.getOffset(), bufferSize);
196         }
197
198         // Pipeline layout
199         {
200                 m_pipelineLayout = makePipelineLayoutWithoutDescriptors(vk, device);
201         }
202
203         // Renderpass
204         {
205                 const VkAttachmentDescription colorAttachmentDescription =
206                 {
207                         (VkAttachmentDescriptionFlags)0,                                        // VkAttachmentDescriptionFlags         flags;
208                         m_colorFormat,                                                                          // VkFormat                                                     format;
209                         VK_SAMPLE_COUNT_1_BIT,                                                          // VkSampleCountFlagBits                        samples;
210                         VK_ATTACHMENT_LOAD_OP_CLEAR,                                            // VkAttachmentLoadOp                           loadOp;
211                         VK_ATTACHMENT_STORE_OP_STORE,                                           // VkAttachmentStoreOp                          storeOp;
212                         VK_ATTACHMENT_LOAD_OP_DONT_CARE,                                        // VkAttachmentLoadOp                           stencilLoadOp;
213                         VK_ATTACHMENT_STORE_OP_DONT_CARE,                                       // VkAttachmentStoreOp                          stencilStoreOp;
214                         VK_IMAGE_LAYOUT_UNDEFINED,                                                      // VkImageLayout                                        initialLayout;
215                         VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,                       // VkImageLayout                                        finalLayout;
216                 };
217
218                 const VkAttachmentReference colorAttachmentReference =
219                 {
220                         0u,                                                                                                     // deUint32                     attachment;
221                         VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL                        // VkImageLayout        layout;
222                 };
223
224                 const VkAttachmentReference depthAttachmentReference =
225                 {
226                         VK_ATTACHMENT_UNUSED,                                                           // deUint32                     attachment;
227                         VK_IMAGE_LAYOUT_UNDEFINED                                                       // VkImageLayout        layout;
228                 };
229
230                 const VkSubpassDescription subpassDescription =
231                 {
232                         (VkSubpassDescriptionFlags)0,                                           // VkSubpassDescriptionFlags            flags;
233                         VK_PIPELINE_BIND_POINT_GRAPHICS,                                        // VkPipelineBindPoint                          pipelineBindPoint;
234                         0u,                                                                                                     // deUint32                                                     inputAttachmentCount;
235                         DE_NULL,                                                                                        // const VkAttachmentReference*         pInputAttachments;
236                         1u,                                                                                                     // deUint32                                                     colorAttachmentCount;
237                         &colorAttachmentReference,                                                      // const VkAttachmentReference*         pColorAttachments;
238                         DE_NULL,                                                                                        // const VkAttachmentReference*         pResolveAttachments;
239                         &depthAttachmentReference,                                                      // const VkAttachmentReference*         pDepthStencilAttachment;
240                         0u,                                                                                                     // deUint32                                                     preserveAttachmentCount;
241                         DE_NULL                                                                                         // const deUint32*                                      pPreserveAttachments;
242                 };
243
244                 const VkRenderPassCreateInfo renderPassInfo =
245                 {
246                         VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,                      // VkStructureType                                      sType;
247                         DE_NULL,                                                                                        // const void*                                          pNext;
248                         (VkRenderPassCreateFlags)0,                                                     // VkRenderPassCreateFlags                      flags;
249                         1u,                                                                                                     // deUint32                                                     attachmentCount;
250                         &colorAttachmentDescription,                                            // const VkAttachmentDescription*       pAttachments;
251                         1u,                                                                                                     // deUint32                                                     subpassCount;
252                         &subpassDescription,                                                            // const VkSubpassDescription*          pSubpasses;
253                         0u,                                                                                                     // deUint32                                                     dependencyCount;
254                         DE_NULL                                                                                         // const VkSubpassDependency*           pDependencies;
255                 };
256
257                 m_renderPass = createRenderPass(vk, device, &renderPassInfo);
258         }
259
260         // Framebuffer
261         {
262                 const VkFramebufferCreateInfo framebufferInfo = {
263                         VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,              // VkStructureType                             sType;
264                         DE_NULL,                                                                                // const void*                                 pNext;
265                         (VkFramebufferCreateFlags)0,                                    // VkFramebufferCreateFlags                    flags;
266                         *m_renderPass,                                                                  // VkRenderPass                                renderPass;
267                         1u,                                                                                             // uint32_t                                    attachmentCount;
268                         &m_colorImageView.get(),                                                // const VkImageView*                          pAttachments;
269                         m_renderSize.x(),                                                               // uint32_t                                    width;
270                         m_renderSize.y(),                                                               // uint32_t                                    height;
271                         1u,                                                                                             // uint32_t                                    layers;
272                 };
273
274                 m_framebuffer = createFramebuffer(vk, device, &framebufferInfo);
275         }
276
277         // Graphics pipeline
278         {
279                 const deUint32  vertexStride    = sizeof(Vec4);
280                 const VkFormat  vertexFormat    = VK_FORMAT_R32G32B32A32_SFLOAT;
281
282                 const VkVertexInputBindingDescription bindingDesc =
283                 {
284                         0u,                                                                     // uint32_t                             binding;
285                         vertexStride,                                           // uint32_t                             stride;
286                         VK_VERTEX_INPUT_RATE_VERTEX,            // VkVertexInputRate    inputRate;
287                 };
288                 const VkVertexInputAttributeDescription attributeDesc =
289                 {
290                         0u,                                                                     // uint32_t                     location;
291                         0u,                                                                     // uint32_t                     binding;
292                         vertexFormat,                                           // VkFormat                     format;
293                         0u,                                                                     // uint32_t                     offset;
294                 };
295
296                 const VkPipelineVertexInputStateCreateInfo vertexInputStateInfo =
297                 {
298                         VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,              // VkStructureType                             sType;
299                         DE_NULL,                                                                                                                // const void*                                 pNext;
300                         (VkPipelineVertexInputStateCreateFlags)0,                                               // VkPipelineVertexInputStateCreateFlags       flags;
301                         1u,                                                                                                                             // uint32_t                                    vertexBindingDescriptionCount;
302                         &bindingDesc,                                                                                                   // const VkVertexInputBindingDescription*      pVertexBindingDescriptions;
303                         1u,                                                                                                                             // uint32_t                                    vertexAttributeDescriptionCount;
304                         &attributeDesc,                                                                                                 // const VkVertexInputAttributeDescription*    pVertexAttributeDescriptions;
305                 };
306
307                 const VkPipelineInputAssemblyStateCreateInfo pipelineInputAssemblyStateInfo =
308                 {
309                         VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,    // VkStructureType                             sType;
310                         DE_NULL,                                                                                                                // const void*                                 pNext;
311                         (VkPipelineInputAssemblyStateCreateFlags)0,                                             // VkPipelineInputAssemblyStateCreateFlags     flags;
312                         m_primitiveTopology,                                                                                    // VkPrimitiveTopology                         topology;
313                         VK_FALSE,                                                                                                               // VkBool32                                    primitiveRestartEnable;
314                 };
315
316                 const VkPipelineTessellationStateCreateInfo pipelineTessellationStateInfo =
317                 {
318                         VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO,              // VkStructureType                             sType;
319                         DE_NULL,                                                                                                                // const void*                                 pNext;
320                         (VkPipelineTessellationStateCreateFlags)0,                                              // VkPipelineTessellationStateCreateFlags      flags;
321                         m_numPatchControlPoints,                                                                                // uint32_t                                    patchControlPoints;
322                 };
323
324                 const VkViewport viewport = makeViewport(
325                         0.0f, 0.0f,
326                         static_cast<float>(m_renderSize.x()), static_cast<float>(m_renderSize.y()),
327                         0.0f, 1.0f);
328
329                 const VkRect2D scissor = {
330                         makeOffset2D(0, 0),
331                         makeExtent2D(m_renderSize.x(), m_renderSize.y()),
332                 };
333
334                 const VkPipelineViewportStateCreateInfo pipelineViewportStateInfo =
335                 {
336                         VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,  // VkStructureType                             sType;
337                         DE_NULL,                                                                                                // const void*                                 pNext;
338                         (VkPipelineViewportStateCreateFlags)0,                                  // VkPipelineViewportStateCreateFlags          flags;
339                         1u,                                                                                                             // uint32_t                                    viewportCount;
340                         &viewport,                                                                                              // const VkViewport*                           pViewports;
341                         1u,                                                                                                             // uint32_t                                    scissorCount;
342                         &scissor,                                                                                               // const VkRect2D*                             pScissors;
343                 };
344
345                 const VkPipelineRasterizationStateCreateInfo pipelineRasterizationStateInfo =
346                 {
347                         VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,             // VkStructureType                          sType;
348                         DE_NULL,                                                                                                                // const void*                              pNext;
349                         (VkPipelineRasterizationStateCreateFlags)0,                                             // VkPipelineRasterizationStateCreateFlags  flags;
350                         m_depthClampEnable,                                                                                             // VkBool32                                 depthClampEnable;
351                         VK_FALSE,                                                                                                               // VkBool32                                 rasterizerDiscardEnable;
352                         VK_POLYGON_MODE_FILL,                                                                                   // VkPolygonMode                                                        polygonMode;
353                         VK_CULL_MODE_NONE,                                                                                              // VkCullModeFlags                                                      cullMode;
354                         VK_FRONT_FACE_COUNTER_CLOCKWISE,                                                                // VkFrontFace                                                          frontFace;
355                         VK_FALSE,                                                                                                               // VkBool32                                                                     depthBiasEnable;
356                         0.0f,                                                                                                                   // float                                                                        depthBiasConstantFactor;
357                         0.0f,                                                                                                                   // float                                                                        depthBiasClamp;
358                         0.0f,                                                                                                                   // float                                                                        depthBiasSlopeFactor;
359                         m_lineWidth,                                                                                                    // float                                                                        lineWidth;
360                 };
361
362                 const VkPipelineMultisampleStateCreateInfo pipelineMultisampleStateInfo =
363                 {
364                         VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,       // VkStructureType                                                      sType;
365                         DE_NULL,                                                                                                        // const void*                                                          pNext;
366                         (VkPipelineMultisampleStateCreateFlags)0,                                       // VkPipelineMultisampleStateCreateFlags        flags;
367                         VK_SAMPLE_COUNT_1_BIT,                                                                          // VkSampleCountFlagBits                                        rasterizationSamples;
368                         VK_FALSE,                                                                                                       // VkBool32                                                                     sampleShadingEnable;
369                         0.0f,                                                                                                           // float                                                                        minSampleShading;
370                         DE_NULL,                                                                                                        // const VkSampleMask*                                          pSampleMask;
371                         VK_FALSE,                                                                                                       // VkBool32                                                                     alphaToCoverageEnable;
372                         VK_FALSE                                                                                                        // VkBool32                                                                     alphaToOneEnable;
373                 };
374
375                 const VkStencilOpState stencilOpState = makeStencilOpState(
376                         VK_STENCIL_OP_KEEP,             // stencil fail
377                         VK_STENCIL_OP_KEEP,             // depth & stencil pass
378                         VK_STENCIL_OP_KEEP,             // depth only fail
379                         VK_COMPARE_OP_NEVER,    // compare op
380                         0u,                                             // compare mask
381                         0u,                                             // write mask
382                         0u);                                    // reference
383
384                 const VkPipelineDepthStencilStateCreateInfo pipelineDepthStencilStateInfo =
385                 {
386                         VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO,     // VkStructureType                                                      sType;
387                         DE_NULL,                                                                                                        // const void*                                                          pNext;
388                         (VkPipelineDepthStencilStateCreateFlags)0,                                      // VkPipelineDepthStencilStateCreateFlags       flags;
389                         VK_FALSE,                                                                                                       // VkBool32                                                                     depthTestEnable;
390                         VK_FALSE,                                                                                                       // VkBool32                                                                     depthWriteEnable;
391                         VK_COMPARE_OP_LESS,                                                                                     // VkCompareOp                                                          depthCompareOp;
392                         VK_FALSE,                                                                                                       // VkBool32                                                                     depthBoundsTestEnable;
393                         VK_FALSE,                                                                                                       // VkBool32                                                                     stencilTestEnable;
394                         stencilOpState,                                                                                         // VkStencilOpState                                                     front;
395                         stencilOpState,                                                                                         // VkStencilOpState                                                     back;
396                         0.0f,                                                                                                           // float                                                                        minDepthBounds;
397                         1.0f,                                                                                                           // float                                                                        maxDepthBounds;
398                 };
399
400                 const VkColorComponentFlags colorComponentsAll = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
401                 const VkPipelineColorBlendAttachmentState pipelineColorBlendAttachmentState =
402                 {
403                         m_blendEnable,                                          // VkBool32                                     blendEnable;
404                         VK_BLEND_FACTOR_SRC_ALPHA,                      // VkBlendFactor                        srcColorBlendFactor;
405                         VK_BLEND_FACTOR_ONE,                            // VkBlendFactor                        dstColorBlendFactor;
406                         VK_BLEND_OP_ADD,                                        // VkBlendOp                            colorBlendOp;
407                         VK_BLEND_FACTOR_SRC_ALPHA,                      // VkBlendFactor                        srcAlphaBlendFactor;
408                         VK_BLEND_FACTOR_ONE,                            // VkBlendFactor                        dstAlphaBlendFactor;
409                         VK_BLEND_OP_ADD,                                        // VkBlendOp                            alphaBlendOp;
410                         colorComponentsAll,                                     // VkColorComponentFlags        colorWriteMask;
411                 };
412
413                 const VkPipelineColorBlendStateCreateInfo pipelineColorBlendStateInfo =
414                 {
415                         VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,       // VkStructureType                                                              sType;
416                         DE_NULL,                                                                                                        // const void*                                                                  pNext;
417                         (VkPipelineColorBlendStateCreateFlags)0,                                        // VkPipelineColorBlendStateCreateFlags                 flags;
418                         VK_FALSE,                                                                                                       // VkBool32                                                                             logicOpEnable;
419                         VK_LOGIC_OP_COPY,                                                                                       // VkLogicOp                                                                    logicOp;
420                         1u,                                                                                                                     // deUint32                                                                             attachmentCount;
421                         &pipelineColorBlendAttachmentState,                                                     // const VkPipelineColorBlendAttachmentState*   pAttachments;
422                         { 0.0f, 0.0f, 0.0f, 0.0f },                                                                     // float                                                                                blendConstants[4];
423                 };
424
425                 // Create shader stages
426
427                 std::vector<VkPipelineShaderStageCreateInfo>    shaderStages;
428                 VkShaderStageFlags                                                              stageFlags = (VkShaderStageFlags)0;
429
430                 DE_ASSERT(shaders.size() <= MAX_NUM_SHADER_MODULES);
431                 for (deUint32 shaderNdx = 0; shaderNdx < shaders.size(); ++shaderNdx)
432                 {
433                         m_shaderModules[shaderNdx] = createShaderModule(vk, device, *shaders[shaderNdx].binary, (VkShaderModuleCreateFlags)0);
434
435                         const VkPipelineShaderStageCreateInfo pipelineShaderStageInfo =
436                         {
437                                 VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,    // VkStructureType                                              sType;
438                                 DE_NULL,                                                                                                // const void*                                                  pNext;
439                                 (VkPipelineShaderStageCreateFlags)0,                                    // VkPipelineShaderStageCreateFlags             flags;
440                                 shaders[shaderNdx].stage,                                                               // VkShaderStageFlagBits                                stage;
441                                 *m_shaderModules[shaderNdx],                                                    // VkShaderModule                                               module;
442                                 "main",                                                                                                 // const char*                                                  pName;
443                                 DE_NULL,                                                                                                // const VkSpecializationInfo*                  pSpecializationInfo;
444                         };
445
446                         shaderStages.push_back(pipelineShaderStageInfo);
447                         stageFlags |= shaders[shaderNdx].stage;
448                 }
449
450                 DE_ASSERT(
451                         (m_primitiveTopology != VK_PRIMITIVE_TOPOLOGY_PATCH_LIST) ||
452                         (stageFlags & (VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)));
453
454                 const bool tessellationEnabled = (m_primitiveTopology == VK_PRIMITIVE_TOPOLOGY_PATCH_LIST);
455                 const VkGraphicsPipelineCreateInfo graphicsPipelineInfo =
456                 {
457                         VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,                                                // VkStructureType                                                                      sType;
458                         DE_NULL,                                                                                                                                // const void*                                                                          pNext;
459                         (VkPipelineCreateFlags)0,                                                                                               // VkPipelineCreateFlags                                                        flags;
460                         static_cast<deUint32>(shaderStages.size()),                                                             // deUint32                                                                                     stageCount;
461                         &shaderStages[0],                                                                                                               // const VkPipelineShaderStageCreateInfo*                       pStages;
462                         &vertexInputStateInfo,                                                                                                  // const VkPipelineVertexInputStateCreateInfo*          pVertexInputState;
463                         &pipelineInputAssemblyStateInfo,                                                                                // const VkPipelineInputAssemblyStateCreateInfo*        pInputAssemblyState;
464                         (tessellationEnabled ? &pipelineTessellationStateInfo : DE_NULL),               // const VkPipelineTessellationStateCreateInfo*         pTessellationState;
465                         &pipelineViewportStateInfo,                                                                                             // const VkPipelineViewportStateCreateInfo*                     pViewportState;
466                         &pipelineRasterizationStateInfo,                                                                                // const VkPipelineRasterizationStateCreateInfo*        pRasterizationState;
467                         &pipelineMultisampleStateInfo,                                                                                  // const VkPipelineMultisampleStateCreateInfo*          pMultisampleState;
468                         &pipelineDepthStencilStateInfo,                                                                                 // const VkPipelineDepthStencilStateCreateInfo*         pDepthStencilState;
469                         &pipelineColorBlendStateInfo,                                                                                   // const VkPipelineColorBlendStateCreateInfo*           pColorBlendState;
470                         DE_NULL,                                                                                                                                // const VkPipelineDynamicStateCreateInfo*                      pDynamicState;
471                         *m_pipelineLayout,                                                                                                              // VkPipelineLayout                                                                     layout;
472                         *m_renderPass,                                                                                                                  // VkRenderPass                                                                         renderPass;
473                         0u,                                                                                                                                             // deUint32                                                                                     subpass;
474                         DE_NULL,                                                                                                                                // VkPipeline                                                                           basePipelineHandle;
475                         0,                                                                                                                                              // deInt32                                                                                      basePipelineIndex;
476                 };
477
478                 m_pipeline = createGraphicsPipeline(vk, device, DE_NULL, &graphicsPipelineInfo);
479         }
480
481         // Record commands
482         {
483                 const VkDeviceSize zeroOffset = 0ull;
484
485                 beginCommandBuffer(vk, *m_cmdBuffer);
486
487                 // Begin render pass
488                 {
489                         const VkClearValue      clearValue = makeClearValueColor(Vec4(0.0f, 0.0f, 0.0f, 1.0f));
490                         const VkRect2D          renderArea =
491                         {
492                                 makeOffset2D(0, 0),
493                                 makeExtent2D(m_renderSize.x(), m_renderSize.y())
494                         };
495
496                         const VkRenderPassBeginInfo renderPassBeginInfo = {
497                                 VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,               // VkStructureType         sType;
498                                 DE_NULL,                                                                                // const void*             pNext;
499                                 *m_renderPass,                                                                  // VkRenderPass            renderPass;
500                                 *m_framebuffer,                                                                 // VkFramebuffer           framebuffer;
501                                 renderArea,                                                                             // VkRect2D                renderArea;
502                                 1u,                                                                                             // uint32_t                clearValueCount;
503                                 &clearValue,                                                                    // const VkClearValue*     pClearValues;
504                         };
505
506                         vk.cmdBeginRenderPass(*m_cmdBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
507                 }
508
509                 vk.cmdBindPipeline(*m_cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *m_pipeline);
510                 vk.cmdBindVertexBuffers(*m_cmdBuffer, 0u, 1u, &(**m_vertexBuffer), &zeroOffset);
511
512                 vk.cmdDraw(*m_cmdBuffer, m_numVertices, 1u, 0u, 1u);
513                 vk.cmdEndRenderPass(*m_cmdBuffer);
514
515                 // Barrier: draw -> copy from image
516                 {
517                         const VkImageMemoryBarrier barrier = makeImageMemoryBarrier(
518                                 VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT,
519                                 VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
520                                 **m_colorImage, m_colorSubresourceRange);
521
522                         vk.cmdPipelineBarrier(*m_cmdBuffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, (VkDependencyFlags)0,
523                                 0u, DE_NULL, 0u, DE_NULL, 1u, &barrier);
524                 }
525
526                 {
527                         const VkBufferImageCopy copyRegion = makeBufferImageCopy(makeImageSubresourceLayers(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 0u, 1u), m_imageExtent);
528                         vk.cmdCopyImageToBuffer(*m_cmdBuffer, **m_colorImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, **m_colorAttachmentBuffer, 1u, &copyRegion);
529                 }
530
531                 // Barrier: copy to buffer -> host read
532                 {
533                         const VkBufferMemoryBarrier barrier = makeBufferMemoryBarrier(
534                                 VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT,
535                                 **m_colorAttachmentBuffer, 0ull, VK_WHOLE_SIZE);
536
537                         vk.cmdPipelineBarrier(*m_cmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, (VkDependencyFlags)0,
538                                 0u, DE_NULL, 1u, &barrier, 0u, DE_NULL);
539                 }
540
541                 endCommandBuffer(vk, *m_cmdBuffer);
542         }
543 }
544
545 void DrawContext::draw (void)
546 {
547         const DeviceInterface&  vk                      = m_context.getDeviceInterface();
548         const VkDevice                  device          = m_context.getDevice();
549         const VkQueue                   queue           = m_context.getUniversalQueue();
550         tcu::TestLog&                   log                     = m_context.getTestContext().getLog();
551
552         submitCommandsAndWait(vk, device, queue, *m_cmdBuffer);
553
554         log << tcu::LogImageSet("attachments", "") << tcu::LogImage("color0", "", getColorPixels()) << tcu::TestLog::EndImageSet;
555 }
556
557 tcu::ConstPixelBufferAccess DrawContext::getColorPixels (void) const
558 {
559         const DeviceInterface&  vk                      = m_context.getDeviceInterface();
560         const VkDevice                  device          = m_context.getDevice();
561
562         const Allocation& alloc = m_colorAttachmentBuffer->getAllocation();
563         invalidateMappedMemoryRange(vk, device, alloc.getMemory(), alloc.getOffset(), VK_WHOLE_SIZE);
564
565         return tcu::ConstPixelBufferAccess(mapVkFormat(m_colorFormat), m_imageExtent.width, m_imageExtent.height, m_imageExtent.depth, alloc.getHostPtr());
566 }
567
568 std::vector<Vec4> genVertices (const VkPrimitiveTopology topology, const Vec4& offset, const float slope)
569 {
570         const float p  = 1.0f;
571         const float hp = 0.5f;
572         const float z  = 0.0f;
573         const float w  = 1.0f;
574
575         std::vector<Vec4> vertices;
576
577         // We're setting adjacent vertices to zero where needed, as we don't use them in meaningful way.
578
579         switch (topology)
580         {
581                 case VK_PRIMITIVE_TOPOLOGY_POINT_LIST:
582                         vertices.push_back(offset + Vec4(0.0f, 0.0f, slope/2.0f + z, w));
583                         vertices.push_back(offset + Vec4( -hp,  -hp,              z, w));
584                         vertices.push_back(offset + Vec4(  hp,  -hp,      slope + z, w));
585                         vertices.push_back(offset + Vec4( -hp,   hp,              z, w));
586                         vertices.push_back(offset + Vec4(  hp,   hp,      slope + z, w));
587                         break;
588
589                 case VK_PRIMITIVE_TOPOLOGY_LINE_LIST:
590                         vertices.push_back(offset + Vec4(-p, -p,         z, w));
591                         vertices.push_back(offset + Vec4( p,  p, slope + z, w));        // line 0
592                         vertices.push_back(offset + Vec4( p,  p, slope + z, w));
593                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));        // line 1
594                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));
595                         vertices.push_back(offset + Vec4(-p,  p,         z, w));        // line 2
596                         break;
597
598                 case VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY:
599                         vertices.push_back(Vec4());
600                         vertices.push_back(offset + Vec4(-p, -p,         z, w));
601                         vertices.push_back(offset + Vec4( p,  p, slope + z, w));        // line 0
602                         vertices.push_back(Vec4());
603                         vertices.push_back(Vec4());
604                         vertices.push_back(offset + Vec4( p,  p, slope + z, w));
605                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));        // line 1
606                         vertices.push_back(Vec4());
607                         vertices.push_back(Vec4());
608                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));
609                         vertices.push_back(offset + Vec4(-p,  p,         z, w));        // line 2
610                         vertices.push_back(Vec4());
611                         break;
612
613                 case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP:
614                         vertices.push_back(offset + Vec4(-p, -p,         z, w));
615                         vertices.push_back(offset + Vec4( p,  p, slope + z, w));        // line 0
616                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));        // line 1
617                         vertices.push_back(offset + Vec4(-p,  p,         z, w));        // line 2
618                         break;
619
620                 case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY:
621                         vertices.push_back(Vec4());
622                         vertices.push_back(offset + Vec4(-p, -p,         z, w));
623                         vertices.push_back(offset + Vec4( p,  p, slope + z, w));        // line 0
624                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));        // line 1
625                         vertices.push_back(offset + Vec4(-p,  p,         z, w));        // line 2
626                         vertices.push_back(Vec4());
627                         break;
628
629                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST:
630                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));
631                         vertices.push_back(offset + Vec4(-p, -p,         z, w));
632                         vertices.push_back(offset + Vec4(-p,  p,         z, w));        // triangle 0
633                         vertices.push_back(offset + Vec4(-p,  p,         z, w));
634                         vertices.push_back(offset + Vec4( p,  p, slope + z, w));
635                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));        // triangle 1
636                         break;
637
638                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY:
639                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));
640                         vertices.push_back(Vec4());
641                         vertices.push_back(offset + Vec4(-p, -p,         z, w));
642                         vertices.push_back(Vec4());
643                         vertices.push_back(offset + Vec4(-p,  p,         z, w));        // triangle 0
644                         vertices.push_back(Vec4());
645                         vertices.push_back(offset + Vec4(-p,  p,         z, w));
646                         vertices.push_back(Vec4());
647                         vertices.push_back(offset + Vec4( p,  p, slope + z, w));
648                         vertices.push_back(Vec4());
649                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));        // triangle 1
650                         vertices.push_back(Vec4());
651                         break;
652
653                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP:
654                         vertices.push_back(offset + Vec4(-p, -p,         z, w));
655                         vertices.push_back(offset + Vec4(-p,  p,         z, w));
656                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));        // triangle 0
657                         vertices.push_back(offset + Vec4( p,  p, slope + z, w));        // triangle 1
658                         break;
659
660                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY:
661                         vertices.push_back(offset + Vec4(-p, -p,         z, w));
662                         vertices.push_back(Vec4());
663                         vertices.push_back(offset + Vec4(-p,  p,         z, w));
664                         vertices.push_back(Vec4());
665                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));        // triangle 0
666                         vertices.push_back(Vec4());
667                         vertices.push_back(offset + Vec4( p,  p, slope + z, w));        // triangle 1
668                         vertices.push_back(Vec4());
669                         break;
670
671                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN:
672                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));
673                         vertices.push_back(offset + Vec4(-p, -p,         z, w));
674                         vertices.push_back(offset + Vec4(-p,  p,         z, w));        // triangle 0
675                         vertices.push_back(offset + Vec4( p,  p, slope + z, w));        // triangle 1
676                         break;
677
678                 case VK_PRIMITIVE_TOPOLOGY_PATCH_LIST:
679                         DE_ASSERT(0);
680                         break;
681
682                 default:
683                         DE_ASSERT(0);
684                         break;
685         }
686         return vertices;
687 }
688
689 bool inline isColorInRange (const Vec4& color, const Vec4& minColor, const Vec4& maxColor)
690 {
691         return (minColor.x() <= color.x() && color.x() <= maxColor.x())
692                 && (minColor.y() <= color.y() && color.y() <= maxColor.y())
693                 && (minColor.z() <= color.z() && color.z() <= maxColor.z())
694                 && (minColor.w() <= color.w() && color.w() <= maxColor.w());
695 }
696
697 //! Count pixels that match color within threshold, in the specified region.
698 int countPixels (const tcu::ConstPixelBufferAccess pixels, const IVec2& regionOffset, const IVec2& regionSize, const Vec4& color, const Vec4& colorThreshold)
699 {
700         const Vec4      minColor        = color - colorThreshold;
701         const Vec4      maxColor        = color + colorThreshold;
702         const int       xEnd            = regionOffset.x() + regionSize.x();
703         const int       yEnd            = regionOffset.y() + regionSize.y();
704         int                     numPixels       = 0;
705
706         DE_ASSERT(xEnd <= pixels.getWidth());
707         DE_ASSERT(yEnd <= pixels.getHeight());
708
709         for (int y = regionOffset.y(); y < yEnd; ++y)
710         for (int x = regionOffset.x(); x < xEnd; ++x)
711         {
712                 if (isColorInRange(pixels.getPixel(x, y), minColor, maxColor))
713                         ++numPixels;
714         }
715
716         return numPixels;
717 }
718
719 int countPixels (const tcu::ConstPixelBufferAccess pixels, const Vec4& color, const Vec4& colorThreshold)
720 {
721         return countPixels(pixels, IVec2(), IVec2(pixels.getWidth(), pixels.getHeight()), color, colorThreshold);
722 }
723
724 //! Clipping against the default clip volume.
725 namespace ClipVolume
726 {
727
728 //! Used by wide lines test.
729 enum LineOrientation
730 {
731         LINE_ORIENTATION_AXIS_ALIGNED,
732         LINE_ORIENTATION_DIAGONAL,
733 };
734
735 void addSimplePrograms (SourceCollections& programCollection, const float pointSize = 0.0f)
736 {
737         // Vertex shader
738         {
739                 const bool usePointSize = pointSize > 0.0f;
740
741                 std::ostringstream src;
742                 src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n"
743                         << "\n"
744                         << "layout(location = 0) in vec4 v_position;\n"
745                         << "\n"
746                         << "out gl_PerVertex {\n"
747                         << "    vec4  gl_Position;\n"
748                         << (usePointSize ? "    float gl_PointSize;\n" : "")
749                         << "};\n"
750                         << "\n"
751                         << "void main (void)\n"
752                         << "{\n"
753                         << "    gl_Position = v_position;\n"
754                         << (usePointSize ? "    gl_PointSize = " + de::floatToString(pointSize, 1) + ";\n" : "")
755                         << "}\n";
756
757                 programCollection.glslSources.add("vert") << glu::VertexSource(src.str());
758         }
759
760         // Fragment shader
761         {
762                 std::ostringstream src;
763                 src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n"
764                         << "\n"
765                         << "layout(location = 0) out vec4 o_color;\n"
766                         << "\n"
767                         << "void main (void)\n"
768                         << "{\n"
769                         << "    o_color = vec4(1.0, gl_FragCoord.z, 0.0, 1.0);\n"
770                         << "}\n";
771
772                 programCollection.glslSources.add("frag") << glu::FragmentSource(src.str());
773         }
774 }
775
776 void initPrograms (SourceCollections& programCollection, const VkPrimitiveTopology topology)
777 {
778         const float pointSize = (topology == VK_PRIMITIVE_TOPOLOGY_POINT_LIST ? 1.0f : 0.0f);
779         addSimplePrograms(programCollection, pointSize);
780 }
781
782 void initPrograms (SourceCollections& programCollection, const LineOrientation lineOrientation)
783 {
784         DE_UNREF(lineOrientation);
785         addSimplePrograms(programCollection);
786 }
787
788 void initProgramsPointSize (SourceCollections& programCollection)
789 {
790         addSimplePrograms(programCollection, 0.75f * RENDER_SIZE);
791 }
792
793 //! Primitives fully inside the clip volume.
794 tcu::TestStatus testPrimitivesInside (Context& context, const VkPrimitiveTopology topology)
795 {
796         int minExpectedBlackPixels = 0;
797
798         switch (topology)
799         {
800                 case VK_PRIMITIVE_TOPOLOGY_POINT_LIST:
801                         // We draw only 5 points.
802                         minExpectedBlackPixels = NUM_RENDER_PIXELS - 5;
803                         break;
804
805                 case VK_PRIMITIVE_TOPOLOGY_LINE_LIST:
806                 case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP:
807                 case VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY:
808                 case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY:
809                         // Allow for some error.
810                         minExpectedBlackPixels = NUM_RENDER_PIXELS - 3 * RENDER_SIZE;
811                         break;
812
813                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST:
814                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP:
815                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN:
816                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY:
817                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY:
818                         // All render area should be covered.
819                         minExpectedBlackPixels = 0;
820                         break;
821
822                 default:
823                         DE_ASSERT(0);
824                         break;
825         }
826
827         std::vector<Shader> shaders;
828         shaders.push_back(Shader(VK_SHADER_STAGE_VERTEX_BIT,    context.getBinaryCollection().get("vert")));
829         shaders.push_back(Shader(VK_SHADER_STAGE_FRAGMENT_BIT,  context.getBinaryCollection().get("frag")));
830
831         tcu::TestLog&   log                     = context.getTestContext().getLog();
832         int                             numPassed       = 0;
833
834         static const struct
835         {
836                 const char* const       desc;
837                 float                           zPos;
838         } cases[] =
839         {
840                 { "Draw primitives at near clipping plane, z = 0.0",    0.0f, },
841                 { "Draw primitives at z = 0.5",                                                 0.5f, },
842                 { "Draw primitives at far clipping plane, z = 1.0",             1.0f, },
843         };
844
845         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
846         {
847                 log << tcu::TestLog::Message << cases[caseNdx].desc << tcu::TestLog::EndMessage;
848
849                 const std::vector<Vec4> vertices = genVertices(topology, Vec4(0.0f, 0.0f, cases[caseNdx].zPos, 0.0f), 0.0f);
850                 DrawContext drawContext(context, shaders, vertices, topology);
851                 drawContext.draw();
852
853                 const int numBlackPixels = countPixels(drawContext.getColorPixels(), Vec4(0.0f, 0.0f, 0.0f, 1.0f), Vec4());
854                 if (numBlackPixels >= minExpectedBlackPixels)
855                         ++numPassed;
856         }
857
858         return (numPassed == DE_LENGTH_OF_ARRAY(cases) ? tcu::TestStatus::pass("OK") : tcu::TestStatus::fail("Rendered image(s) are incorrect"));
859 }
860
861 //! Primitives fully outside the clip volume.
862 tcu::TestStatus testPrimitivesOutside (Context& context, const VkPrimitiveTopology topology)
863 {
864         std::vector<Shader> shaders;
865         shaders.push_back(Shader(VK_SHADER_STAGE_VERTEX_BIT,    context.getBinaryCollection().get("vert")));
866         shaders.push_back(Shader(VK_SHADER_STAGE_FRAGMENT_BIT,  context.getBinaryCollection().get("frag")));
867
868         tcu::TestLog&   log                     = context.getTestContext().getLog();
869         int                             numPassed       = 0;
870
871         static const struct
872         {
873                 const char* const       desc;
874                 float                           zPos;
875         } cases[] =
876         {
877                 { "Draw primitives in front of the near clipping plane, z < 0.0",       -0.5f, },
878                 { "Draw primitives behind the far clipping plane, z > 1.0",                      1.5f, },
879         };
880
881         log << tcu::TestLog::Message << "Drawing primitives outside the clip volume. Expecting an empty image." << tcu::TestLog::EndMessage;
882
883         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
884         {
885                 log << tcu::TestLog::Message << cases[caseNdx].desc << tcu::TestLog::EndMessage;
886
887                 const std::vector<Vec4> vertices = genVertices(topology, Vec4(0.0f, 0.0f, cases[caseNdx].zPos, 0.0f), 0.0f);
888                 DrawContext drawContext(context, shaders, vertices, topology);
889                 drawContext.draw();
890
891                 // All pixels must be black -- nothing is drawn.
892                 const int numBlackPixels = countPixels(drawContext.getColorPixels(), Vec4(0.0f, 0.0f, 0.0f, 1.0f), Vec4());
893                 if (numBlackPixels == NUM_RENDER_PIXELS)
894                         ++numPassed;
895         }
896
897         return (numPassed == DE_LENGTH_OF_ARRAY(cases) ? tcu::TestStatus::pass("OK") : tcu::TestStatus::fail("Rendered image(s) are incorrect"));
898 }
899
900 //! Primitives partially outside the clip volume, but depth clamped
901 tcu::TestStatus testPrimitivesDepthClamp (Context& context, const VkPrimitiveTopology topology)
902 {
903         requireFeatures(context.getInstanceInterface(), context.getPhysicalDevice(), FEATURE_DEPTH_CLAMP);
904
905         std::vector<Shader> shaders;
906         shaders.push_back(Shader(VK_SHADER_STAGE_VERTEX_BIT,    context.getBinaryCollection().get("vert")));
907         shaders.push_back(Shader(VK_SHADER_STAGE_FRAGMENT_BIT,  context.getBinaryCollection().get("frag")));
908
909         const int               numCases                = 4;
910         const IVec2             regionSize              = IVec2(RENDER_SIZE/2, RENDER_SIZE);    //! size of the clamped region
911         const int               regionPixels    = regionSize.x() * regionSize.y();
912         tcu::TestLog&   log                             = context.getTestContext().getLog();
913         int                             numPassed               = 0;
914
915         static const struct
916         {
917                 const char* const       desc;
918                 float                           zPos;
919                 bool                            depthClampEnable;
920                 IVec2                           regionOffset;
921                 Vec4                            color;
922         } cases[numCases] =
923         {
924                 { "Draw primitives intersecting the near clipping plane, depth clamp disabled", -0.5f,  false,  IVec2(0, 0),                            Vec4(0.0f, 0.0f, 0.0f, 1.0f) },
925                 { "Draw primitives intersecting the near clipping plane, depth clamp enabled",  -0.5f,  true,   IVec2(0, 0),                            Vec4(1.0f, 0.0f, 0.0f, 1.0f) },
926                 { "Draw primitives intersecting the far clipping plane, depth clamp disabled",   0.5f,  false,  IVec2(RENDER_SIZE/2, 0),        Vec4(0.0f, 0.0f, 0.0f, 1.0f) },
927                 { "Draw primitives intersecting the far clipping plane, depth clamp enabled",    0.5f,  true,   IVec2(RENDER_SIZE/2, 0),        Vec4(1.0f, 1.0f, 0.0f, 1.0f) },
928         };
929
930         // Per case minimum number of colored pixels.
931         int caseMinPixels[numCases] = { 0, 0, 0, 0 };
932
933         switch (topology)
934         {
935                 case VK_PRIMITIVE_TOPOLOGY_POINT_LIST:
936                         caseMinPixels[0] = caseMinPixels[2] = regionPixels - 1;
937                         caseMinPixels[1] = caseMinPixels[3] = 2;
938                         break;
939
940                 case VK_PRIMITIVE_TOPOLOGY_LINE_LIST:
941                 case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP:
942                 case VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY:
943                 case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY:
944                         caseMinPixels[0] = regionPixels;
945                         caseMinPixels[1] = RENDER_SIZE - 2;
946                         caseMinPixels[2] = regionPixels;
947                         caseMinPixels[3] = 2 * (RENDER_SIZE - 2);
948                         break;
949
950                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST:
951                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP:
952                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN:
953                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY:
954                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY:
955                         caseMinPixels[0] = caseMinPixels[1] = caseMinPixels[2] = caseMinPixels[3] = regionPixels;
956                         break;
957
958                 default:
959                         DE_ASSERT(0);
960                         break;
961         }
962
963         for (int caseNdx = 0; caseNdx < numCases; ++caseNdx)
964         {
965                 log << tcu::TestLog::Message << cases[caseNdx].desc << tcu::TestLog::EndMessage;
966
967                 const std::vector<Vec4> vertices = genVertices(topology, Vec4(0.0f, 0.0f, cases[caseNdx].zPos, 0.0f), 1.0f);
968                 DrawContext drawContext(context, shaders, vertices, topology, static_cast<deUint32>(RENDER_SIZE), cases[caseNdx].depthClampEnable);
969                 drawContext.draw();
970
971                 const int numPixels = countPixels(drawContext.getColorPixels(), cases[caseNdx].regionOffset, regionSize, cases[caseNdx].color, Vec4());
972
973                 if (numPixels >= caseMinPixels[caseNdx])
974                         ++numPassed;
975         }
976
977         return (numPassed == numCases ? tcu::TestStatus::pass("OK") : tcu::TestStatus::fail("Rendered image(s) are incorrect"));
978 }
979
980 //! Large point clipping
981 //! Spec: If the primitive under consideration is a point, then clipping passes it unchanged if it lies within the clip volume;
982 //!       otherwise, it is discarded.
983 tcu::TestStatus testLargePoints (Context& context)
984 {
985         requireFeatures(context.getInstanceInterface(), context.getPhysicalDevice(), FEATURE_LARGE_POINTS);
986
987         std::vector<Shader> shaders;
988         shaders.push_back(Shader(VK_SHADER_STAGE_VERTEX_BIT,    context.getBinaryCollection().get("vert")));
989         shaders.push_back(Shader(VK_SHADER_STAGE_FRAGMENT_BIT,  context.getBinaryCollection().get("frag")));
990
991         std::vector<Vec4> vertices;
992         {
993                 const float delta       = 0.1f;  // much smaller than the point size
994                 const float p           = 1.0f + delta;
995
996                 vertices.push_back(Vec4(  -p,   -p, 0.1f, 1.0f));
997                 vertices.push_back(Vec4(  -p,    p, 0.2f, 1.0f));
998                 vertices.push_back(Vec4(   p,    p, 0.4f, 1.0f));
999                 vertices.push_back(Vec4(   p,   -p, 0.6f, 1.0f));
1000                 vertices.push_back(Vec4(0.0f,   -p, 0.8f, 1.0f));
1001                 vertices.push_back(Vec4(   p, 0.0f, 0.9f, 1.0f));
1002                 vertices.push_back(Vec4(0.0f,    p, 0.1f, 1.0f));
1003                 vertices.push_back(Vec4(  -p, 0.0f, 0.2f, 1.0f));
1004         }
1005
1006         tcu::TestLog&   log     = context.getTestContext().getLog();
1007
1008         log << tcu::TestLog::Message << "Drawing several large points just outside the clip volume. Expecting an empty image." << tcu::TestLog::EndMessage;
1009
1010         DrawContext drawContext(context, shaders, vertices, VK_PRIMITIVE_TOPOLOGY_POINT_LIST);
1011         drawContext.draw();
1012
1013         // All pixels must be black -- nothing is drawn.
1014         const int numBlackPixels = countPixels(drawContext.getColorPixels(), Vec4(0.0f, 0.0f, 0.0f, 1.0f), Vec4());
1015
1016         return (numBlackPixels == NUM_RENDER_PIXELS ? tcu::TestStatus::pass("OK") : tcu::TestStatus::fail("Rendered image(s) are incorrect"));
1017 }
1018
1019 //! Wide line clipping
1020 //! Spec: If the primitive is a line segment, then clipping does nothing to it if it lies entirely within the clip volume, and discards it
1021 //!       if it lies entirely outside the volume.
1022 tcu::TestStatus testWideLines (Context& context, const LineOrientation lineOrientation)
1023 {
1024         requireFeatures(context.getInstanceInterface(), context.getPhysicalDevice(), FEATURE_WIDE_LINES);
1025
1026         std::vector<Shader> shaders;
1027         shaders.push_back(Shader(VK_SHADER_STAGE_VERTEX_BIT,    context.getBinaryCollection().get("vert")));
1028         shaders.push_back(Shader(VK_SHADER_STAGE_FRAGMENT_BIT,  context.getBinaryCollection().get("frag")));
1029
1030         const float delta = 0.1f;  // much smaller than the line width
1031
1032         std::vector<Vec4> vertices;
1033         if (lineOrientation == LINE_ORIENTATION_AXIS_ALIGNED)
1034         {
1035                 // Axis-aligned lines just outside the clip volume.
1036                 const float p = 1.0f + delta;
1037                 const float q = 0.9f;
1038
1039                 vertices.push_back(Vec4(-p, -q, 0.1f, 1.0f));
1040                 vertices.push_back(Vec4(-p,  q, 0.9f, 1.0f));   // line 0
1041                 vertices.push_back(Vec4(-q,  p, 0.1f, 1.0f));
1042                 vertices.push_back(Vec4( q,  p, 0.9f, 1.0f));   // line 1
1043                 vertices.push_back(Vec4( p,  q, 0.1f, 1.0f));
1044                 vertices.push_back(Vec4( p, -q, 0.9f, 1.0f));   // line 2
1045                 vertices.push_back(Vec4( q, -p, 0.1f, 1.0f));
1046                 vertices.push_back(Vec4(-q, -p, 0.9f, 1.0f));   // line 3
1047         }
1048         else if (lineOrientation == LINE_ORIENTATION_DIAGONAL)
1049         {
1050                 // Diagonal lines just outside the clip volume.
1051                 const float p = 2.0f + delta;
1052
1053                 vertices.push_back(Vec4(  -p, 0.0f, 0.1f, 1.0f));
1054                 vertices.push_back(Vec4(0.0f,   -p, 0.9f, 1.0f));       // line 0
1055                 vertices.push_back(Vec4(0.0f,   -p, 0.1f, 1.0f));
1056                 vertices.push_back(Vec4(   p, 0.0f, 0.9f, 1.0f));       // line 1
1057                 vertices.push_back(Vec4(   p, 0.0f, 0.1f, 1.0f));
1058                 vertices.push_back(Vec4(0.0f,    p, 0.9f, 1.0f));       // line 2
1059                 vertices.push_back(Vec4(0.0f,    p, 0.1f, 1.0f));
1060                 vertices.push_back(Vec4(  -p, 0.0f, 0.9f, 1.0f));       // line 3
1061         }
1062         else
1063                 DE_ASSERT(0);
1064
1065         const VkPhysicalDeviceLimits limits = getPhysicalDeviceProperties(context.getInstanceInterface(), context.getPhysicalDevice()).limits;
1066
1067         const float             lineWidth       = std::min(static_cast<float>(RENDER_SIZE), limits.lineWidthRange[1]);
1068         tcu::TestLog&   log                     = context.getTestContext().getLog();
1069
1070         log << tcu::TestLog::Message << "Drawing several wide lines just outside the clip volume. Expecting an empty image." << tcu::TestLog::EndMessage
1071                 << tcu::TestLog::Message << "Line width is " << lineWidth << "." << tcu::TestLog::EndMessage;
1072
1073         DrawContext drawContext(context, shaders, vertices, VK_PRIMITIVE_TOPOLOGY_LINE_LIST, static_cast<deUint32>(RENDER_SIZE), false, false, lineWidth);
1074         drawContext.draw();
1075
1076         // All pixels must be black -- nothing is drawn.
1077         const int numBlackPixels = countPixels(drawContext.getColorPixels(), Vec4(0.0f, 0.0f, 0.0f, 1.0f), Vec4());
1078
1079         return (numBlackPixels == NUM_RENDER_PIXELS ? tcu::TestStatus::pass("OK") : tcu::TestStatus::fail("Rendered image(s) are incorrect"));
1080 }
1081
1082 } // ClipVolume ns
1083
1084 namespace ClipDistance
1085 {
1086
1087 struct CaseDefinition
1088 {
1089         const VkPrimitiveTopology       topology;
1090         const bool                                      dynamicIndexing;
1091         const bool                                      enableTessellation;
1092         const bool                                      enableGeometry;
1093         const int                                       numClipDistances;
1094         const int                                       numCullDistances;
1095
1096         CaseDefinition (const VkPrimitiveTopology       topology_,
1097                                         const int                                       numClipDistances_,
1098                                         const int                                       numCullDistances_,
1099                                         const bool                                      enableTessellation_,
1100                                         const bool                                      enableGeometry_,
1101                                         const bool                                      dynamicIndexing_)
1102                 : topology                                      (topology_)
1103                 , dynamicIndexing                       (dynamicIndexing_)
1104                 , enableTessellation            (enableTessellation_)
1105                 , enableGeometry                        (enableGeometry_)
1106                 , numClipDistances                      (numClipDistances_)
1107                 , numCullDistances                      (numCullDistances_)
1108         {
1109         }
1110 };
1111
1112 void initPrograms (SourceCollections& programCollection, const CaseDefinition caseDef)
1113 {
1114         DE_ASSERT(caseDef.numClipDistances + caseDef.numCullDistances <= MAX_COMBINED_CLIP_AND_CULL_DISTANCES);
1115
1116         std::string perVertexBlock;
1117         {
1118                 std::ostringstream str;
1119                 str << "gl_PerVertex {\n"
1120                         << "    vec4  gl_Position;\n";
1121                 if (caseDef.numClipDistances > 0)
1122                         str << "    float gl_ClipDistance[" << caseDef.numClipDistances << "];\n";
1123                 if (caseDef.numCullDistances > 0)
1124                         str << "    float gl_CullDistance[" << caseDef.numCullDistances << "];\n";
1125                 str << "}";
1126                 perVertexBlock = str.str();
1127         }
1128
1129         // Vertex shader
1130         {
1131                 std::ostringstream src;
1132                 src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n"
1133                         << "\n"
1134                         << "layout(location = 0) in  vec4 v_position;\n"
1135                         << "layout(location = 0) out vec4 out_color;\n"
1136                         << "\n"
1137                         << "out " << perVertexBlock << ";\n"
1138                         << "\n"
1139                         << "void main (void)\n"
1140                         << "{\n"
1141                         << "    gl_Position = v_position;\n"
1142                         << "    out_color   = vec4(1.0, 0.5 * (v_position.x + 1.0), 0.0, 1.0);\n"
1143                         << "\n"
1144                         << "    const int barNdx = gl_VertexIndex / 6;\n";
1145                 if (caseDef.dynamicIndexing)
1146                 {
1147                         if (caseDef.numClipDistances > 0)
1148                                 src << "    for (int i = 0; i < " << caseDef.numClipDistances << "; ++i)\n"
1149                                         << "        gl_ClipDistance[i] = (barNdx == i ? v_position.y : 0.0);\n";
1150                         if (caseDef.numCullDistances > 0)
1151                                 src << "    for (int i = 0; i < " << caseDef.numCullDistances << "; ++i)\n"
1152                                         << "        gl_CullDistance[i] = 0.0;\n";
1153                 }
1154                 else
1155                 {
1156                         for (int i = 0; i < caseDef.numClipDistances; ++i)
1157                                 src << "    gl_ClipDistance[" << i << "] = (barNdx == " << i << " ? v_position.y : 0.0);\n";
1158                         for (int i = 0; i < caseDef.numCullDistances; ++i)
1159                                 src << "    gl_CullDistance[" << i << "] = 0.0;\n";             // don't cull anything
1160                 }
1161                 src     << "}\n";
1162
1163                 programCollection.glslSources.add("vert") << glu::VertexSource(src.str());
1164         }
1165
1166         if (caseDef.enableTessellation)
1167         {
1168                 std::ostringstream src;
1169                 src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n"
1170                         << "\n"
1171                         << "layout(vertices = " << NUM_PATCH_CONTROL_POINTS << ") out;\n"
1172                         << "\n"
1173                         << "layout(location = 0) in  vec4 in_color[];\n"
1174                         << "layout(location = 0) out vec4 out_color[];\n"
1175                         << "\n"
1176                         << "in " << perVertexBlock << " gl_in[gl_MaxPatchVertices];\n"
1177                         << "\n"
1178                         << "out " << perVertexBlock << " gl_out[];\n"
1179                         << "\n"
1180                         << "void main (void)\n"
1181                         << "{\n"
1182                         << "    gl_TessLevelInner[0] = 1.0;\n"
1183                         << "    gl_TessLevelInner[1] = 1.0;\n"
1184                         << "\n"
1185                         << "    gl_TessLevelOuter[0] = 1.0;\n"
1186                         << "    gl_TessLevelOuter[1] = 1.0;\n"
1187                         << "    gl_TessLevelOuter[2] = 1.0;\n"
1188                         << "    gl_TessLevelOuter[3] = 1.0;\n"
1189                         << "\n"
1190                         << "    gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;\n"
1191                         << "    out_color[gl_InvocationID]          = in_color[gl_InvocationID];\n"
1192                         << "\n";
1193                 if (caseDef.dynamicIndexing)
1194                 {
1195                         if (caseDef.numClipDistances > 0)
1196                                 src << "    for (int i = 0; i < " << caseDef.numClipDistances << "; ++i)\n"
1197                                         << "        gl_out[gl_InvocationID].gl_ClipDistance[i] = gl_in[gl_InvocationID].gl_ClipDistance[i];\n";
1198                         if (caseDef.numCullDistances > 0)
1199                                 src << "    for (int i = 0; i < " << caseDef.numCullDistances << "; ++i)\n"
1200                                         << "        gl_out[gl_InvocationID].gl_CullDistance[i] = gl_in[gl_InvocationID].gl_CullDistance[i];\n";
1201                 }
1202                 else
1203                 {
1204                         for (int i = 0; i < caseDef.numClipDistances; ++i)
1205                                 src << "    gl_out[gl_InvocationID].gl_ClipDistance[" << i << "] = gl_in[gl_InvocationID].gl_ClipDistance[" << i << "];\n";
1206                         for (int i = 0; i < caseDef.numCullDistances; ++i)
1207                                 src << "    gl_out[gl_InvocationID].gl_CullDistance[" << i << "] = gl_in[gl_InvocationID].gl_CullDistance[" << i << "];\n";
1208                 }
1209                 src << "}\n";
1210
1211                 programCollection.glslSources.add("tesc") << glu::TessellationControlSource(src.str());
1212         }
1213
1214         if (caseDef.enableTessellation)
1215         {
1216                 DE_ASSERT(NUM_PATCH_CONTROL_POINTS == 3);  // assumed in shader code
1217
1218                 std::ostringstream src;
1219                 src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n"
1220                         << "\n"
1221                         << "layout(triangles, equal_spacing, ccw) in;\n"
1222                         << "\n"
1223                         << "layout(location = 0) in  vec4 in_color[];\n"
1224                         << "layout(location = 0) out vec4 out_color;\n"
1225                         << "\n"
1226                         << "in " << perVertexBlock << " gl_in[gl_MaxPatchVertices];\n"
1227                         << "\n"
1228                         << "out " << perVertexBlock << ";\n"
1229                         << "\n"
1230                         << "void main (void)\n"
1231                         << "{\n"
1232                         << "    vec3 px     = gl_TessCoord.x * gl_in[0].gl_Position.xyz;\n"
1233                         << "    vec3 py     = gl_TessCoord.y * gl_in[1].gl_Position.xyz;\n"
1234                         << "    vec3 pz     = gl_TessCoord.z * gl_in[2].gl_Position.xyz;\n"
1235                         << "    gl_Position = vec4(px + py + pz, 1.0);\n"
1236                         << "    out_color   = (in_color[0] + in_color[1] + in_color[2]) / 3.0;\n"
1237                         << "\n";
1238                 if (caseDef.dynamicIndexing)
1239                 {
1240                         if (caseDef.numClipDistances > 0)
1241                                 src << "    for (int i = 0; i < " << caseDef.numClipDistances << "; ++i)\n"
1242                                         << "        gl_ClipDistance[i] = gl_TessCoord.x * gl_in[0].gl_ClipDistance[i]\n"
1243                                         << "                           + gl_TessCoord.y * gl_in[1].gl_ClipDistance[i]\n"
1244                                         << "                           + gl_TessCoord.z * gl_in[2].gl_ClipDistance[i];\n";
1245                         if (caseDef.numCullDistances > 0)
1246                                 src << "    for (int i = 0; i < " << caseDef.numCullDistances << "; ++i)\n"
1247                                         << "        gl_CullDistance[i] = gl_TessCoord.x * gl_in[0].gl_CullDistance[i]\n"
1248                                         << "                           + gl_TessCoord.y * gl_in[1].gl_CullDistance[i]\n"
1249                                         << "                           + gl_TessCoord.z * gl_in[2].gl_CullDistance[i];\n";
1250                 }
1251                 else
1252                 {
1253                         for (int i = 0; i < caseDef.numClipDistances; ++i)
1254                                 src << "    gl_ClipDistance[" << i << "] = gl_TessCoord.x * gl_in[0].gl_ClipDistance[" << i << "]\n"
1255                                         << "                       + gl_TessCoord.y * gl_in[1].gl_ClipDistance[" << i << "]\n"
1256                                         << "                       + gl_TessCoord.z * gl_in[2].gl_ClipDistance[" << i << "];\n";
1257                         for (int i = 0; i < caseDef.numCullDistances; ++i)
1258                                 src << "    gl_CullDistance[" << i << "] = gl_TessCoord.x * gl_in[0].gl_CullDistance[" << i << "]\n"
1259                                         << "                       + gl_TessCoord.y * gl_in[1].gl_CullDistance[" << i << "]\n"
1260                                         << "                       + gl_TessCoord.z * gl_in[2].gl_CullDistance[" << i << "];\n";
1261                 }
1262                 src << "}\n";
1263
1264                 programCollection.glslSources.add("tese") << glu::TessellationEvaluationSource(src.str());
1265         }
1266
1267         if (caseDef.enableGeometry)
1268         {
1269                 std::ostringstream src;
1270                 src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n"
1271                         << "\n"
1272                         << "layout(triangles) in;\n"
1273                         << "layout(triangle_strip, max_vertices = 3) out;\n"
1274                         << "\n"
1275                         << "layout(location = 0) in  vec4 in_color[];\n"
1276                         << "layout(location = 0) out vec4 out_color;\n"
1277                         << "\n"
1278                         << "in " << perVertexBlock << " gl_in[];\n"
1279                         << "\n"
1280                         << "out " << perVertexBlock << ";\n"
1281                         << "\n"
1282                         << "void main (void)\n"
1283                         << "{\n";
1284                 for (int vertNdx = 0; vertNdx < 3; ++vertNdx)
1285                 {
1286                         if (vertNdx > 0)
1287                                 src << "\n";
1288                         src << "    gl_Position = gl_in[" << vertNdx << "].gl_Position;\n"
1289                                 << "    out_color   = in_color[" << vertNdx << "];\n";
1290                         if (caseDef.dynamicIndexing)
1291                         {
1292                                 if (caseDef.numClipDistances > 0)
1293                                         src << "    for (int i = 0; i < " << caseDef.numClipDistances << "; ++i)\n"
1294                                                 << "        gl_ClipDistance[i] = gl_in[" << vertNdx << "].gl_ClipDistance[i];\n";
1295                                 if (caseDef.numCullDistances > 0)
1296                                         src << "    for (int i = 0; i < " << caseDef.numCullDistances << "; ++i)\n"
1297                                                 << "        gl_CullDistance[i] = gl_in[" << vertNdx << "].gl_CullDistance[i];\n";
1298                         }
1299                         else
1300                         {
1301                                 for (int i = 0; i < caseDef.numClipDistances; ++i)
1302                                         src << "    gl_ClipDistance[" << i << "] = gl_in[" << vertNdx << "].gl_ClipDistance[" << i << "];\n";
1303                                 for (int i = 0; i < caseDef.numCullDistances; ++i)
1304                                         src << "    gl_CullDistance[" << i << "] = gl_in[" << vertNdx << "].gl_CullDistance[" << i << "];\n";
1305                         }
1306                         src << "    EmitVertex();\n";
1307                 }
1308                 src     << "}\n";
1309
1310                 programCollection.glslSources.add("geom") << glu::GeometrySource(src.str());
1311         }
1312
1313         // Fragment shader
1314         {
1315                 std::ostringstream src;
1316                 src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n"
1317                         << "\n"
1318                         << "layout(location = 0) in flat vec4 in_color;\n"
1319                         << "layout(location = 0) out vec4 o_color;\n"
1320                         << "\n"
1321                         << "void main (void)\n"
1322                         << "{\n"
1323                         << "    o_color = vec4(in_color.rgb + vec3(0.0, 0.0, 0.5), 1.0);\n"  // mix with a constant color in case variable wasn't passed correctly through stages
1324                         << "}\n";
1325
1326                 programCollection.glslSources.add("frag") << glu::FragmentSource(src.str());
1327         }
1328 }
1329
1330 tcu::TestStatus testClipDistance (Context& context, const CaseDefinition caseDef)
1331 {
1332         // Check test requirements
1333         {
1334                 const InstanceInterface&                vki                     = context.getInstanceInterface();
1335                 const VkPhysicalDevice                  physDevice      = context.getPhysicalDevice();
1336                 const VkPhysicalDeviceLimits    limits          = getPhysicalDeviceProperties(vki, physDevice).limits;
1337
1338                 FeatureFlags requirements = (FeatureFlags)0;
1339
1340                 if (caseDef.numClipDistances > 0)
1341                         requirements |= FEATURE_SHADER_CLIP_DISTANCE;
1342                 if (caseDef.numCullDistances > 0)
1343                         requirements |= FEATURE_SHADER_CULL_DISTANCE;
1344                 if (caseDef.enableTessellation)
1345                         requirements |= FEATURE_TESSELLATION_SHADER;
1346                 if (caseDef.enableGeometry)
1347                         requirements |= FEATURE_GEOMETRY_SHADER;
1348
1349                 requireFeatures(vki, physDevice, requirements);
1350
1351                 // Check limits for supported features
1352
1353                 if (caseDef.numClipDistances > 0 && limits.maxClipDistances < MAX_CLIP_DISTANCES)
1354                         return tcu::TestStatus::fail("maxClipDistances smaller than the minimum required by the spec");
1355                 if (caseDef.numCullDistances > 0 && limits.maxCullDistances < MAX_CULL_DISTANCES)
1356                         return tcu::TestStatus::fail("maxCullDistances smaller than the minimum required by the spec");
1357                 if (caseDef.numCullDistances > 0 && limits.maxCombinedClipAndCullDistances < MAX_COMBINED_CLIP_AND_CULL_DISTANCES)
1358                         return tcu::TestStatus::fail("maxCombinedClipAndCullDistances smaller than the minimum required by the spec");
1359         }
1360
1361         std::vector<Shader> shaders;
1362         shaders.push_back(Shader(VK_SHADER_STAGE_VERTEX_BIT,    context.getBinaryCollection().get("vert")));
1363         shaders.push_back(Shader(VK_SHADER_STAGE_FRAGMENT_BIT,  context.getBinaryCollection().get("frag")));
1364         if (caseDef.enableTessellation)
1365         {
1366                 shaders.push_back(Shader(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT,              context.getBinaryCollection().get("tesc")));
1367                 shaders.push_back(Shader(VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT,   context.getBinaryCollection().get("tese")));
1368         }
1369         if (caseDef.enableGeometry)
1370                 shaders.push_back(Shader(VK_SHADER_STAGE_GEOMETRY_BIT,  context.getBinaryCollection().get("geom")));
1371
1372         const int numBars = MAX_COMBINED_CLIP_AND_CULL_DISTANCES;
1373
1374         std::vector<Vec4> vertices;
1375         {
1376                 const float     dx = 2.0f / numBars;
1377                 for (int i = 0; i < numBars; ++i)
1378                 {
1379                         const float x = -1.0f + dx * static_cast<float>(i);
1380
1381                         vertices.push_back(Vec4(x,      -1.0f, 0.0f, 1.0f));
1382                         vertices.push_back(Vec4(x,       1.0f, 0.0f, 1.0f));
1383                         vertices.push_back(Vec4(x + dx, -1.0f, 0.0f, 1.0f));
1384
1385                         vertices.push_back(Vec4(x,       1.0f, 0.0f, 1.0f));
1386                         vertices.push_back(Vec4(x + dx,  1.0f, 0.0f, 1.0f));
1387                         vertices.push_back(Vec4(x + dx, -1.0f, 0.0f, 1.0f));
1388                 }
1389         }
1390
1391         tcu::TestLog& log = context.getTestContext().getLog();
1392
1393         log << tcu::TestLog::Message << "Drawing " << numBars << " colored bars, clipping the first " << caseDef.numClipDistances << tcu::TestLog::EndMessage
1394                 << tcu::TestLog::Message << "Using " << caseDef.numClipDistances << " ClipDistance(s) and " << caseDef.numCullDistances << " CullDistance(s)" << tcu::TestLog::EndMessage
1395                 << tcu::TestLog::Message << "Expecting upper half of the clipped bars to be black." << tcu::TestLog::EndMessage;
1396
1397         DrawContext drawContext(context, shaders, vertices, caseDef.topology);
1398         drawContext.draw();
1399
1400         // Count black pixels in the whole image.
1401         const int numBlackPixels                = countPixels(drawContext.getColorPixels(), Vec4(0.0f, 0.0f, 0.0f, 1.0f), Vec4());
1402         const IVec2     clipRegion                      = IVec2(caseDef.numClipDistances * RENDER_SIZE / numBars, RENDER_SIZE / 2);
1403         const int expectedClippedPixels = clipRegion.x() * clipRegion.y();
1404         // Make sure the bottom half has no black pixels (possible if image became corrupted).
1405         const int guardPixels                   = countPixels(drawContext.getColorPixels(), IVec2(0, RENDER_SIZE/2), clipRegion, Vec4(0.0f, 0.0f, 0.0f, 1.0f), Vec4());
1406
1407         return (numBlackPixels == expectedClippedPixels && guardPixels == 0 ? tcu::TestStatus::pass("OK")
1408                                                                                                                                                 : tcu::TestStatus::fail("Rendered image(s) are incorrect"));
1409 }
1410
1411 } // ClipDistance ns
1412
1413 namespace ClipDistanceComplementarity
1414 {
1415
1416 void initPrograms (SourceCollections& programCollection, const int numClipDistances)
1417 {
1418         // Vertex shader
1419         {
1420                 DE_ASSERT(numClipDistances > 0);
1421                 const int clipDistanceLastNdx = numClipDistances - 1;
1422
1423                 std::ostringstream src;
1424                 src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n"
1425                         << "\n"
1426                         << "layout(location = 0) in vec4 v_position;    // we are passing ClipDistance in w component\n"
1427                         << "\n"
1428                         << "out gl_PerVertex {\n"
1429                         << "    vec4  gl_Position;\n"
1430                         << "    float gl_ClipDistance[" << numClipDistances << "];\n"
1431                         << "};\n"
1432                         << "\n"
1433                         << "void main (void)\n"
1434                         << "{\n"
1435                         << "    gl_Position        = vec4(v_position.xyz, 1.0);\n";
1436                 for (int i = 0; i < clipDistanceLastNdx; ++i)
1437                         src << "    gl_ClipDistance[" << i << "] = 0.0;\n";
1438                 src << "    gl_ClipDistance[" << clipDistanceLastNdx << "] = v_position.w;\n"
1439                         << "}\n";
1440
1441                 programCollection.glslSources.add("vert") << glu::VertexSource(src.str());
1442         }
1443
1444         // Fragment shader
1445         {
1446                 std::ostringstream src;
1447                 src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n"
1448                         << "\n"
1449                         << "layout(location = 0) out vec4 o_color;\n"
1450                         << "\n"
1451                         << "void main (void)\n"
1452                         << "{\n"
1453                         << "    o_color = vec4(1.0, 1.0, 1.0, 0.5);\n"
1454                         << "}\n";
1455
1456                 programCollection.glslSources.add("frag") << glu::FragmentSource(src.str());
1457         }
1458 }
1459
1460 tcu::TestStatus testComplementarity (Context& context, const int numClipDistances)
1461 {
1462         // Check test requirements
1463         {
1464                 const InstanceInterface&                vki                     = context.getInstanceInterface();
1465                 const VkPhysicalDevice                  physDevice      = context.getPhysicalDevice();
1466
1467                 requireFeatures(vki, physDevice, FEATURE_SHADER_CLIP_DISTANCE);
1468         }
1469
1470         std::vector<Shader> shaders;
1471         shaders.push_back(Shader(VK_SHADER_STAGE_VERTEX_BIT,    context.getBinaryCollection().get("vert")));
1472         shaders.push_back(Shader(VK_SHADER_STAGE_FRAGMENT_BIT,  context.getBinaryCollection().get("frag")));
1473
1474         std::vector<Vec4> vertices;
1475         {
1476                 de::Random      rnd                                             (1234);
1477                 const int       numSections                             = 16;
1478                 const int       numVerticesPerSection   = 4;    // logical verticies, due to triangle list topology we actually use 6 per section
1479
1480                 DE_ASSERT(RENDER_SIZE_LARGE % numSections == 0);
1481
1482                 std::vector<float> clipDistances(numVerticesPerSection * numSections);
1483                 for (int i = 0; i < static_cast<int>(clipDistances.size()); ++i)
1484                         clipDistances[i] = rnd.getFloat(-1.0f, 1.0f);
1485
1486                 // Two sets of identical primitives, but with a different ClipDistance sign.
1487                 for (int setNdx = 0; setNdx < 2; ++setNdx)
1488                 {
1489                         const float sign = (setNdx == 0 ? 1.0f : -1.0f);
1490                         const float     dx       = 2.0f / static_cast<float>(numSections);
1491
1492                         for (int i = 0; i < numSections; ++i)
1493                         {
1494                                 const int       ndxBase = numVerticesPerSection * i;
1495                                 const float x           = -1.0f + dx * static_cast<float>(i);
1496                                 const Vec4      p0              = Vec4(x,      -1.0f, 0.0f, sign * clipDistances[ndxBase + 0]);
1497                                 const Vec4      p1              = Vec4(x,       1.0f, 0.0f, sign * clipDistances[ndxBase + 1]);
1498                                 const Vec4      p2              = Vec4(x + dx,  1.0f, 0.0f, sign * clipDistances[ndxBase + 2]);
1499                                 const Vec4      p3              = Vec4(x + dx, -1.0f, 0.0f, sign * clipDistances[ndxBase + 3]);
1500
1501                                 vertices.push_back(p0);
1502                                 vertices.push_back(p1);
1503                                 vertices.push_back(p2);
1504
1505                                 vertices.push_back(p2);
1506                                 vertices.push_back(p3);
1507                                 vertices.push_back(p0);
1508                         }
1509                 }
1510         }
1511
1512         tcu::TestLog& log = context.getTestContext().getLog();
1513
1514         log << tcu::TestLog::Message << "Draw two sets of primitives with blending, differing only with ClipDistance sign." << tcu::TestLog::EndMessage
1515                 << tcu::TestLog::Message << "Using " << numClipDistances << " clipping plane(s), one of them possibly having negative values." << tcu::TestLog::EndMessage
1516                 << tcu::TestLog::Message << "Expecting a uniform gray area, no missing (black) nor overlapped (white) pixels." << tcu::TestLog::EndMessage;
1517
1518         DrawContext drawContext(context, shaders, vertices, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, static_cast<deUint32>(RENDER_SIZE_LARGE), false, true);
1519         drawContext.draw();
1520
1521         const int numGrayPixels         = countPixels(drawContext.getColorPixels(), Vec4(0.5f, 0.5f, 0.5f, 1.0f), Vec4(0.02f, 0.02f, 0.02f, 0.0f));
1522         const int numExpectedPixels     = RENDER_SIZE_LARGE * RENDER_SIZE_LARGE;
1523
1524         return (numGrayPixels == numExpectedPixels ? tcu::TestStatus::pass("OK") : tcu::TestStatus::fail("Rendered image(s) are incorrect"));
1525 }
1526
1527 } // ClipDistanceComplementarity ns
1528
1529 void addClippingTests (tcu::TestCaseGroup* clippingTestsGroup)
1530 {
1531         tcu::TestContext& testCtx = clippingTestsGroup->getTestContext();
1532
1533         // Clipping against the clip volume
1534         {
1535                 using namespace ClipVolume;
1536
1537                 static const VkPrimitiveTopology cases[] =
1538                 {
1539                         VK_PRIMITIVE_TOPOLOGY_POINT_LIST,
1540                         VK_PRIMITIVE_TOPOLOGY_LINE_LIST,
1541                         VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY,
1542                         VK_PRIMITIVE_TOPOLOGY_LINE_STRIP,
1543                         VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY,
1544                         VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
1545                         VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY,
1546                         VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
1547                         VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY,
1548                         VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN,
1549                 };
1550
1551                 MovePtr<tcu::TestCaseGroup> clipVolumeGroup(new tcu::TestCaseGroup(testCtx, "clip_volume", "clipping with the clip volume"));
1552
1553                 // Fully inside the clip volume
1554                 {
1555                         MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "inside", ""));
1556
1557                         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1558                                 addFunctionCaseWithPrograms<VkPrimitiveTopology>(
1559                                         group.get(), getPrimitiveTopologyShortName(cases[caseNdx]), "", initPrograms, testPrimitivesInside, cases[caseNdx]);
1560
1561                         clipVolumeGroup->addChild(group.release());
1562                 }
1563
1564                 // Fully outside the clip volume
1565                 {
1566                         MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "outside", ""));
1567
1568                         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1569                                 addFunctionCaseWithPrograms<VkPrimitiveTopology>(
1570                                         group.get(), getPrimitiveTopologyShortName(cases[caseNdx]), "", initPrograms, testPrimitivesOutside, cases[caseNdx]);
1571
1572                         clipVolumeGroup->addChild(group.release());
1573                 }
1574
1575                 // Depth clamping
1576                 {
1577                         MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "depth_clamp", ""));
1578
1579                         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1580                                 addFunctionCaseWithPrograms<VkPrimitiveTopology>(
1581                                         group.get(), getPrimitiveTopologyShortName(cases[caseNdx]), "", initPrograms, testPrimitivesDepthClamp, cases[caseNdx]);
1582
1583                         clipVolumeGroup->addChild(group.release());
1584                 }
1585
1586                 // Large points and wide lines
1587                 {
1588                         // \note For both points and lines, if an unsupported size/width is selected, the nearest supported size will be chosen.
1589                         //       We do have to check for feature support though.
1590
1591                         MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "clipped", ""));
1592
1593                         addFunctionCaseWithPrograms(group.get(), "large_points", "", initProgramsPointSize, testLargePoints);
1594
1595                         addFunctionCaseWithPrograms<LineOrientation>(group.get(), "wide_lines_axis_aligned", "", initPrograms, testWideLines, LINE_ORIENTATION_AXIS_ALIGNED);
1596                         addFunctionCaseWithPrograms<LineOrientation>(group.get(), "wide_lines_diagonal",         "", initPrograms, testWideLines, LINE_ORIENTATION_DIAGONAL);
1597
1598                         clipVolumeGroup->addChild(group.release());
1599                 }
1600
1601                 clippingTestsGroup->addChild(clipVolumeGroup.release());
1602         }
1603
1604         // User-defined clip planes
1605         {
1606                 MovePtr<tcu::TestCaseGroup> clipDistanceGroup(new tcu::TestCaseGroup(testCtx, "user_defined", "user-defined clip planes"));
1607
1608                 // ClipDistance, CullDistance and maxCombinedClipAndCullDistances usage
1609                 {
1610                         using namespace ClipDistance;
1611
1612                         static const struct
1613                         {
1614                                 const char* const       groupName;
1615                                 const char* const       description;
1616                                 bool                            useCullDistance;
1617                         } caseGroups[] =
1618                         {
1619                                 { "clip_distance",              "use ClipDistance",                                                                             false },
1620                                 { "clip_cull_distance", "use ClipDistance and CullDistance at the same time",   true  },
1621                         };
1622
1623                         const deUint32 flagTessellation = 1u << 0;
1624                         const deUint32 flagGeometry             = 1u << 1;
1625
1626                         for (int groupNdx = 0; groupNdx < DE_LENGTH_OF_ARRAY(caseGroups); ++groupNdx)
1627                         for (int indexingMode = 0; indexingMode < 2; ++indexingMode)
1628                         {
1629                                 const bool                      dynamicIndexing = (indexingMode == 1);
1630                                 const std::string       mainGroupName   = de::toString(caseGroups[groupNdx].groupName) + (dynamicIndexing ? "_dynamic_index" : "");
1631
1632                                 MovePtr<tcu::TestCaseGroup>     mainGroup(new tcu::TestCaseGroup(testCtx, mainGroupName.c_str(), ""));
1633
1634                                 for (deUint32 shaderMask = 0u; shaderMask <= (flagTessellation | flagGeometry); ++shaderMask)
1635                                 {
1636                                         const bool                      useTessellation = (shaderMask & flagTessellation) != 0;
1637                                         const bool                      useGeometry             = (shaderMask & flagGeometry) != 0;
1638                                         const std::string       shaderGroupName = std::string("vert") + (useTessellation ? "_tess" : "") + (useGeometry ? "_geom" : "");
1639
1640                                         MovePtr<tcu::TestCaseGroup>     shaderGroup(new tcu::TestCaseGroup(testCtx, shaderGroupName.c_str(), ""));
1641
1642                                         for (int numClipPlanes = 1; numClipPlanes <= MAX_CLIP_DISTANCES; ++numClipPlanes)
1643                                         {
1644                                                 const int                                       numCullPlanes   = (caseGroups[groupNdx].useCullDistance
1645                                                                                                                                                 ? std::min(static_cast<int>(MAX_CULL_DISTANCES), MAX_COMBINED_CLIP_AND_CULL_DISTANCES - numClipPlanes)
1646                                                                                                                                                 : 0);
1647                                                 const std::string                       caseName                = de::toString(numClipPlanes) + (numCullPlanes > 0 ? "_" + de::toString(numCullPlanes) : "");
1648                                                 const VkPrimitiveTopology       topology                = (useTessellation ? VK_PRIMITIVE_TOPOLOGY_PATCH_LIST : VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST);
1649
1650                                                 addFunctionCaseWithPrograms<CaseDefinition>(
1651                                                         shaderGroup.get(), caseName, caseGroups[groupNdx].description, initPrograms, testClipDistance,
1652                                                         CaseDefinition(topology, numClipPlanes, numCullPlanes, useTessellation, useGeometry, dynamicIndexing));
1653                                         }
1654                                         mainGroup->addChild(shaderGroup.release());
1655                                 }
1656                                 clipDistanceGroup->addChild(mainGroup.release());
1657                         }
1658                 }
1659
1660                 // Complementarity criterion (i.e. clipped and not clipped areas must add up to a complete primitive with no holes nor overlap)
1661                 {
1662                         using namespace ClipDistanceComplementarity;
1663
1664                         MovePtr<tcu::TestCaseGroup>     group(new tcu::TestCaseGroup(testCtx, "complementarity", ""));
1665
1666                         for (int numClipDistances = 1; numClipDistances <= MAX_CLIP_DISTANCES; ++numClipDistances)
1667                                 addFunctionCaseWithPrograms<int>(group.get(), de::toString(numClipDistances).c_str(), "", initPrograms, testComplementarity, numClipDistances);
1668
1669                         clippingTestsGroup->addChild(group.release());
1670                 }
1671
1672                 clippingTestsGroup->addChild(clipDistanceGroup.release());
1673         }
1674 }
1675
1676 } // anonymous
1677
1678 tcu::TestCaseGroup* createTests (tcu::TestContext& testCtx)
1679 {
1680         return createTestGroup(testCtx, "clipping", "Clipping tests", addClippingTests);
1681 }
1682
1683 } // clipping
1684 } // vkt