Add Vulkan DrawContext utility class
[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 "vktDrawUtil.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 using namespace drawutil;
49
50 enum FeatureFlagBits
51 {
52         FEATURE_TESSELLATION_SHADER                                                     = 1u << 0,
53         FEATURE_GEOMETRY_SHADER                                                         = 1u << 1,
54         FEATURE_SHADER_FLOAT_64                                                         = 1u << 2,
55         FEATURE_VERTEX_PIPELINE_STORES_AND_ATOMICS                      = 1u << 3,
56         FEATURE_FRAGMENT_STORES_AND_ATOMICS                                     = 1u << 4,
57         FEATURE_SHADER_TESSELLATION_AND_GEOMETRY_POINT_SIZE     = 1u << 5,
58         FEATURE_DEPTH_CLAMP                                                                     = 1u << 6,
59         FEATURE_LARGE_POINTS                                                            = 1u << 7,
60         FEATURE_WIDE_LINES                                                                      = 1u << 8,
61         FEATURE_SHADER_CLIP_DISTANCE                                            = 1u << 9,
62         FEATURE_SHADER_CULL_DISTANCE                                            = 1u << 10,
63 };
64 typedef deUint32 FeatureFlags;
65
66 void requireFeatures (const InstanceInterface& vki, const VkPhysicalDevice physDevice, const FeatureFlags flags)
67 {
68         const VkPhysicalDeviceFeatures features = getPhysicalDeviceFeatures(vki, physDevice);
69
70         if (((flags & FEATURE_TESSELLATION_SHADER) != 0) && !features.tessellationShader)
71                 throw tcu::NotSupportedError("Tessellation shader not supported");
72
73         if (((flags & FEATURE_GEOMETRY_SHADER) != 0) && !features.geometryShader)
74                 throw tcu::NotSupportedError("Geometry shader not supported");
75
76         if (((flags & FEATURE_SHADER_FLOAT_64) != 0) && !features.shaderFloat64)
77                 throw tcu::NotSupportedError("Double-precision floats not supported");
78
79         if (((flags & FEATURE_VERTEX_PIPELINE_STORES_AND_ATOMICS) != 0) && !features.vertexPipelineStoresAndAtomics)
80                 throw tcu::NotSupportedError("SSBO and image writes not supported in vertex pipeline");
81
82         if (((flags & FEATURE_FRAGMENT_STORES_AND_ATOMICS) != 0) && !features.fragmentStoresAndAtomics)
83                 throw tcu::NotSupportedError("SSBO and image writes not supported in fragment shader");
84
85         if (((flags & FEATURE_SHADER_TESSELLATION_AND_GEOMETRY_POINT_SIZE) != 0) && !features.shaderTessellationAndGeometryPointSize)
86                 throw tcu::NotSupportedError("Tessellation and geometry shaders don't support PointSize built-in");
87
88         if (((flags & FEATURE_DEPTH_CLAMP) != 0) && !features.depthClamp)
89                 throw tcu::NotSupportedError("Depth clamp not supported");
90
91         if (((flags & FEATURE_LARGE_POINTS) != 0) && !features.largePoints)
92                 throw tcu::NotSupportedError("Large points not supported");
93
94         if (((flags & FEATURE_WIDE_LINES) != 0) && !features.wideLines)
95                 throw tcu::NotSupportedError("Wide lines not supported");
96
97         if (((flags & FEATURE_SHADER_CLIP_DISTANCE) != 0) && !features.shaderClipDistance)
98                 throw tcu::NotSupportedError("Shader ClipDistance not supported");
99
100         if (((flags & FEATURE_SHADER_CULL_DISTANCE) != 0) && !features.shaderCullDistance)
101                 throw tcu::NotSupportedError("Shader CullDistance not supported");
102 }
103
104 std::vector<Vec4> genVertices (const VkPrimitiveTopology topology, const Vec4& offset, const float slope)
105 {
106         const float p  = 1.0f;
107         const float hp = 0.5f;
108         const float z  = 0.0f;
109         const float w  = 1.0f;
110
111         std::vector<Vec4> vertices;
112
113         // We're setting adjacent vertices to zero where needed, as we don't use them in meaningful way.
114
115         switch (topology)
116         {
117                 case VK_PRIMITIVE_TOPOLOGY_POINT_LIST:
118                         vertices.push_back(offset + Vec4(0.0f, 0.0f, slope/2.0f + z, w));
119                         vertices.push_back(offset + Vec4( -hp,  -hp,              z, w));
120                         vertices.push_back(offset + Vec4(  hp,  -hp,      slope + z, w));
121                         vertices.push_back(offset + Vec4( -hp,   hp,              z, w));
122                         vertices.push_back(offset + Vec4(  hp,   hp,      slope + z, w));
123                         break;
124
125                 case VK_PRIMITIVE_TOPOLOGY_LINE_LIST:
126                         vertices.push_back(offset + Vec4(-p, -p,         z, w));
127                         vertices.push_back(offset + Vec4( p,  p, slope + z, w));        // line 0
128                         vertices.push_back(offset + Vec4( p,  p, slope + z, w));
129                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));        // line 1
130                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));
131                         vertices.push_back(offset + Vec4(-p,  p,         z, w));        // line 2
132                         break;
133
134                 case VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY:
135                         vertices.push_back(Vec4());
136                         vertices.push_back(offset + Vec4(-p, -p,         z, w));
137                         vertices.push_back(offset + Vec4( p,  p, slope + z, w));        // line 0
138                         vertices.push_back(Vec4());
139                         vertices.push_back(Vec4());
140                         vertices.push_back(offset + Vec4( p,  p, slope + z, w));
141                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));        // line 1
142                         vertices.push_back(Vec4());
143                         vertices.push_back(Vec4());
144                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));
145                         vertices.push_back(offset + Vec4(-p,  p,         z, w));        // line 2
146                         vertices.push_back(Vec4());
147                         break;
148
149                 case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP:
150                         vertices.push_back(offset + Vec4(-p, -p,         z, w));
151                         vertices.push_back(offset + Vec4( p,  p, slope + z, w));        // line 0
152                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));        // line 1
153                         vertices.push_back(offset + Vec4(-p,  p,         z, w));        // line 2
154                         break;
155
156                 case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY:
157                         vertices.push_back(Vec4());
158                         vertices.push_back(offset + Vec4(-p, -p,         z, w));
159                         vertices.push_back(offset + Vec4( p,  p, slope + z, w));        // line 0
160                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));        // line 1
161                         vertices.push_back(offset + Vec4(-p,  p,         z, w));        // line 2
162                         vertices.push_back(Vec4());
163                         break;
164
165                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST:
166                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));
167                         vertices.push_back(offset + Vec4(-p, -p,         z, w));
168                         vertices.push_back(offset + Vec4(-p,  p,         z, w));        // triangle 0
169                         vertices.push_back(offset + Vec4(-p,  p,         z, w));
170                         vertices.push_back(offset + Vec4( p,  p, slope + z, w));
171                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));        // triangle 1
172                         break;
173
174                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY:
175                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));
176                         vertices.push_back(Vec4());
177                         vertices.push_back(offset + Vec4(-p, -p,         z, w));
178                         vertices.push_back(Vec4());
179                         vertices.push_back(offset + Vec4(-p,  p,         z, w));        // triangle 0
180                         vertices.push_back(Vec4());
181                         vertices.push_back(offset + Vec4(-p,  p,         z, w));
182                         vertices.push_back(Vec4());
183                         vertices.push_back(offset + Vec4( p,  p, slope + z, w));
184                         vertices.push_back(Vec4());
185                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));        // triangle 1
186                         vertices.push_back(Vec4());
187                         break;
188
189                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP:
190                         vertices.push_back(offset + Vec4(-p, -p,         z, w));
191                         vertices.push_back(offset + Vec4(-p,  p,         z, w));
192                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));        // triangle 0
193                         vertices.push_back(offset + Vec4( p,  p, slope + z, w));        // triangle 1
194                         break;
195
196                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY:
197                         vertices.push_back(offset + Vec4(-p, -p,         z, w));
198                         vertices.push_back(Vec4());
199                         vertices.push_back(offset + Vec4(-p,  p,         z, w));
200                         vertices.push_back(Vec4());
201                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));        // triangle 0
202                         vertices.push_back(Vec4());
203                         vertices.push_back(offset + Vec4( p,  p, slope + z, w));        // triangle 1
204                         vertices.push_back(Vec4());
205                         break;
206
207                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN:
208                         vertices.push_back(offset + Vec4( p, -p, slope + z, w));
209                         vertices.push_back(offset + Vec4(-p, -p,         z, w));
210                         vertices.push_back(offset + Vec4(-p,  p,         z, w));        // triangle 0
211                         vertices.push_back(offset + Vec4( p,  p, slope + z, w));        // triangle 1
212                         break;
213
214                 case VK_PRIMITIVE_TOPOLOGY_PATCH_LIST:
215                         DE_ASSERT(0);
216                         break;
217
218                 default:
219                         DE_ASSERT(0);
220                         break;
221         }
222         return vertices;
223 }
224
225 bool inline isColorInRange (const Vec4& color, const Vec4& minColor, const Vec4& maxColor)
226 {
227         return (minColor.x() <= color.x() && color.x() <= maxColor.x())
228                 && (minColor.y() <= color.y() && color.y() <= maxColor.y())
229                 && (minColor.z() <= color.z() && color.z() <= maxColor.z())
230                 && (minColor.w() <= color.w() && color.w() <= maxColor.w());
231 }
232
233 //! Count pixels that match color within threshold, in the specified region.
234 int countPixels (const tcu::ConstPixelBufferAccess pixels, const IVec2& regionOffset, const IVec2& regionSize, const Vec4& color, const Vec4& colorThreshold)
235 {
236         const Vec4      minColor        = color - colorThreshold;
237         const Vec4      maxColor        = color + colorThreshold;
238         const int       xEnd            = regionOffset.x() + regionSize.x();
239         const int       yEnd            = regionOffset.y() + regionSize.y();
240         int                     numPixels       = 0;
241
242         DE_ASSERT(xEnd <= pixels.getWidth());
243         DE_ASSERT(yEnd <= pixels.getHeight());
244
245         for (int y = regionOffset.y(); y < yEnd; ++y)
246         for (int x = regionOffset.x(); x < xEnd; ++x)
247         {
248                 if (isColorInRange(pixels.getPixel(x, y), minColor, maxColor))
249                         ++numPixels;
250         }
251
252         return numPixels;
253 }
254
255 int countPixels (const tcu::ConstPixelBufferAccess pixels, const Vec4& color, const Vec4& colorThreshold)
256 {
257         return countPixels(pixels, IVec2(), IVec2(pixels.getWidth(), pixels.getHeight()), color, colorThreshold);
258 }
259
260 //! Clipping against the default clip volume.
261 namespace ClipVolume
262 {
263
264 //! Used by wide lines test.
265 enum LineOrientation
266 {
267         LINE_ORIENTATION_AXIS_ALIGNED,
268         LINE_ORIENTATION_DIAGONAL,
269 };
270
271 const VkPointClippingBehaviorKHR invalidClippingBehavior = VK_POINT_CLIPPING_BEHAVIOR_KHR_LAST;
272
273 VkPointClippingBehaviorKHR getClippingBehavior (const InstanceInterface& vk, VkPhysicalDevice physicalDevice)
274 {
275         VkPhysicalDevicePointClippingPropertiesKHR      behaviorProperties      =
276         {
277                 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES_KHR,        // VkStructureType                              sType
278                 DE_NULL,                                                                                                                        // void*                                                pNext
279                 invalidClippingBehavior                                                                                         // VkPointClippingBehaviorKHR   pointClippingBehavior
280         };
281         VkPhysicalDeviceProperties2KHR                          properties2;
282
283         DE_ASSERT(getPointClippingBehaviorKHRName(invalidClippingBehavior) == DE_NULL);
284
285         deMemset(&properties2, 0, sizeof(properties2));
286
287         properties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2_KHR;
288         properties2.pNext = &behaviorProperties;
289
290         vk.getPhysicalDeviceProperties2KHR(physicalDevice, &properties2);
291
292         return behaviorProperties.pointClippingBehavior;
293 }
294
295 void addSimplePrograms (SourceCollections& programCollection, const float pointSize = 0.0f)
296 {
297         // Vertex shader
298         {
299                 const bool usePointSize = pointSize > 0.0f;
300
301                 std::ostringstream src;
302                 src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n"
303                         << "\n"
304                         << "layout(location = 0) in vec4 v_position;\n"
305                         << "\n"
306                         << "out gl_PerVertex {\n"
307                         << "    vec4  gl_Position;\n"
308                         << (usePointSize ? "    float gl_PointSize;\n" : "")
309                         << "};\n"
310                         << "\n"
311                         << "void main (void)\n"
312                         << "{\n"
313                         << "    gl_Position = v_position;\n"
314                         << (usePointSize ? "    gl_PointSize = " + de::floatToString(pointSize, 1) + ";\n" : "")
315                         << "}\n";
316
317                 programCollection.glslSources.add("vert") << glu::VertexSource(src.str());
318         }
319
320         // Fragment shader
321         {
322                 std::ostringstream src;
323                 src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n"
324                         << "\n"
325                         << "layout(location = 0) out vec4 o_color;\n"
326                         << "\n"
327                         << "void main (void)\n"
328                         << "{\n"
329                         << "    o_color = vec4(1.0, gl_FragCoord.z, 0.0, 1.0);\n"
330                         << "}\n";
331
332                 programCollection.glslSources.add("frag") << glu::FragmentSource(src.str());
333         }
334 }
335
336 void initPrograms (SourceCollections& programCollection, const VkPrimitiveTopology topology)
337 {
338         const float pointSize = (topology == VK_PRIMITIVE_TOPOLOGY_POINT_LIST ? 1.0f : 0.0f);
339         addSimplePrograms(programCollection, pointSize);
340 }
341
342 void initPrograms (SourceCollections& programCollection, const LineOrientation lineOrientation)
343 {
344         DE_UNREF(lineOrientation);
345         addSimplePrograms(programCollection);
346 }
347
348 void initProgramsPointSize (SourceCollections& programCollection)
349 {
350         addSimplePrograms(programCollection, 0.75f * RENDER_SIZE);
351 }
352
353 //! Primitives fully inside the clip volume.
354 tcu::TestStatus testPrimitivesInside (Context& context, const VkPrimitiveTopology topology)
355 {
356         int minExpectedBlackPixels = 0;
357
358         switch (topology)
359         {
360                 case VK_PRIMITIVE_TOPOLOGY_POINT_LIST:
361                         // We draw only 5 points.
362                         minExpectedBlackPixels = NUM_RENDER_PIXELS - 5;
363                         break;
364
365                 case VK_PRIMITIVE_TOPOLOGY_LINE_LIST:
366                 case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP:
367                 case VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY:
368                 case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY:
369                         // Allow for some error.
370                         minExpectedBlackPixels = NUM_RENDER_PIXELS - 3 * RENDER_SIZE;
371                         break;
372
373                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST:
374                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP:
375                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN:
376                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY:
377                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY:
378                         // All render area should be covered.
379                         minExpectedBlackPixels = 0;
380                         break;
381
382                 default:
383                         DE_ASSERT(0);
384                         break;
385         }
386
387         std::vector<Shader> shaders;
388         shaders.push_back(Shader(VK_SHADER_STAGE_VERTEX_BIT,    context.getBinaryCollection().get("vert")));
389         shaders.push_back(Shader(VK_SHADER_STAGE_FRAGMENT_BIT,  context.getBinaryCollection().get("frag")));
390
391         tcu::TestLog&   log                     = context.getTestContext().getLog();
392         int                             numPassed       = 0;
393
394         static const struct
395         {
396                 const char* const       desc;
397                 float                           zPos;
398         } cases[] =
399         {
400                 { "Draw primitives at near clipping plane, z = 0.0",    0.0f, },
401                 { "Draw primitives at z = 0.5",                                                 0.5f, },
402                 { "Draw primitives at far clipping plane, z = 1.0",             1.0f, },
403         };
404
405         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
406         {
407                 log << tcu::TestLog::Message << cases[caseNdx].desc << tcu::TestLog::EndMessage;
408
409                 const std::vector<Vec4> vertices = genVertices(topology, Vec4(0.0f, 0.0f, cases[caseNdx].zPos, 0.0f), 0.0f);
410                 DrawContext drawContext(context, shaders, vertices, topology);
411                 drawContext.draw();
412
413                 const int numBlackPixels = countPixels(drawContext.getColorPixels(), Vec4(0.0f, 0.0f, 0.0f, 1.0f), Vec4());
414                 if (numBlackPixels >= minExpectedBlackPixels)
415                         ++numPassed;
416         }
417
418         return (numPassed == DE_LENGTH_OF_ARRAY(cases) ? tcu::TestStatus::pass("OK") : tcu::TestStatus::fail("Rendered image(s) are incorrect"));
419 }
420
421 //! Primitives fully outside the clip volume.
422 tcu::TestStatus testPrimitivesOutside (Context& context, const VkPrimitiveTopology topology)
423 {
424         std::vector<Shader> shaders;
425         shaders.push_back(Shader(VK_SHADER_STAGE_VERTEX_BIT,    context.getBinaryCollection().get("vert")));
426         shaders.push_back(Shader(VK_SHADER_STAGE_FRAGMENT_BIT,  context.getBinaryCollection().get("frag")));
427
428         tcu::TestLog&   log                     = context.getTestContext().getLog();
429         int                             numPassed       = 0;
430
431         static const struct
432         {
433                 const char* const       desc;
434                 float                           zPos;
435         } cases[] =
436         {
437                 { "Draw primitives in front of the near clipping plane, z < 0.0",       -0.5f, },
438                 { "Draw primitives behind the far clipping plane, z > 1.0",                      1.5f, },
439         };
440
441         log << tcu::TestLog::Message << "Drawing primitives outside the clip volume. Expecting an empty image." << tcu::TestLog::EndMessage;
442
443         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
444         {
445                 log << tcu::TestLog::Message << cases[caseNdx].desc << tcu::TestLog::EndMessage;
446
447                 const std::vector<Vec4> vertices = genVertices(topology, Vec4(0.0f, 0.0f, cases[caseNdx].zPos, 0.0f), 0.0f);
448                 DrawContext drawContext(context, shaders, vertices, topology);
449                 drawContext.draw();
450
451                 // All pixels must be black -- nothing is drawn.
452                 const int numBlackPixels = countPixels(drawContext.getColorPixels(), Vec4(0.0f, 0.0f, 0.0f, 1.0f), Vec4());
453                 if (numBlackPixels == NUM_RENDER_PIXELS)
454                         ++numPassed;
455         }
456
457         return (numPassed == DE_LENGTH_OF_ARRAY(cases) ? tcu::TestStatus::pass("OK") : tcu::TestStatus::fail("Rendered image(s) are incorrect"));
458 }
459
460 //! Primitives partially outside the clip volume, but depth clamped
461 tcu::TestStatus testPrimitivesDepthClamp (Context& context, const VkPrimitiveTopology topology)
462 {
463         requireFeatures(context.getInstanceInterface(), context.getPhysicalDevice(), FEATURE_DEPTH_CLAMP);
464
465         std::vector<Shader> shaders;
466         shaders.push_back(Shader(VK_SHADER_STAGE_VERTEX_BIT,    context.getBinaryCollection().get("vert")));
467         shaders.push_back(Shader(VK_SHADER_STAGE_FRAGMENT_BIT,  context.getBinaryCollection().get("frag")));
468
469         const int               numCases                = 4;
470         const IVec2             regionSize              = IVec2(RENDER_SIZE/2, RENDER_SIZE);    //! size of the clamped region
471         const int               regionPixels    = regionSize.x() * regionSize.y();
472         tcu::TestLog&   log                             = context.getTestContext().getLog();
473         int                             numPassed               = 0;
474
475         static const struct
476         {
477                 const char* const       desc;
478                 float                           zPos;
479                 bool                            depthClampEnable;
480                 IVec2                           regionOffset;
481                 Vec4                            color;
482         } cases[numCases] =
483         {
484                 { "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) },
485                 { "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) },
486                 { "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) },
487                 { "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) },
488         };
489
490         // Per case minimum number of colored pixels.
491         int caseMinPixels[numCases] = { 0, 0, 0, 0 };
492
493         switch (topology)
494         {
495                 case VK_PRIMITIVE_TOPOLOGY_POINT_LIST:
496                         caseMinPixels[0] = caseMinPixels[2] = regionPixels - 1;
497                         caseMinPixels[1] = caseMinPixels[3] = 2;
498                         break;
499
500                 case VK_PRIMITIVE_TOPOLOGY_LINE_LIST:
501                 case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP:
502                 case VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY:
503                 case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY:
504                         caseMinPixels[0] = regionPixels;
505                         caseMinPixels[1] = RENDER_SIZE - 2;
506                         caseMinPixels[2] = regionPixels;
507                         caseMinPixels[3] = 2 * (RENDER_SIZE - 2);
508                         break;
509
510                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST:
511                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP:
512                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN:
513                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY:
514                 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY:
515                         caseMinPixels[0] = caseMinPixels[1] = caseMinPixels[2] = caseMinPixels[3] = regionPixels;
516                         break;
517
518                 default:
519                         DE_ASSERT(0);
520                         break;
521         }
522
523         for (int caseNdx = 0; caseNdx < numCases; ++caseNdx)
524         {
525                 log << tcu::TestLog::Message << cases[caseNdx].desc << tcu::TestLog::EndMessage;
526
527                 const std::vector<Vec4> vertices = genVertices(topology, Vec4(0.0f, 0.0f, cases[caseNdx].zPos, 0.0f), 1.0f);
528                 DrawContext drawContext(context, shaders, vertices, topology, static_cast<deUint32>(RENDER_SIZE), cases[caseNdx].depthClampEnable);
529                 drawContext.draw();
530
531                 const int numPixels = countPixels(drawContext.getColorPixels(), cases[caseNdx].regionOffset, regionSize, cases[caseNdx].color, Vec4());
532
533                 if (numPixels >= caseMinPixels[caseNdx])
534                         ++numPassed;
535         }
536
537         return (numPassed == numCases ? tcu::TestStatus::pass("OK") : tcu::TestStatus::fail("Rendered image(s) are incorrect"));
538 }
539
540 //! Large point clipping
541 //! Spec: If the primitive under consideration is a point, then clipping passes it unchanged if it lies within the clip volume;
542 //!       otherwise, it is discarded.
543 tcu::TestStatus testLargePoints (Context& context)
544 {
545         requireFeatures(context.getInstanceInterface(), context.getPhysicalDevice(), FEATURE_LARGE_POINTS);
546
547         bool pointClippingOutside = true;
548
549         if (de::contains(context.getDeviceExtensions().begin(), context.getDeviceExtensions().end(), "VK_KHR_maintenance2"))
550         {
551                 VkPointClippingBehaviorKHR clippingBehavior = getClippingBehavior(context.getInstanceInterface(), context.getPhysicalDevice());
552
553                 switch (clippingBehavior)
554                 {
555                         case VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES_KHR:            pointClippingOutside = true;                            break;
556                         case VK_POINT_CLIPPING_BEHAVIOR_USER_CLIP_PLANES_ONLY_KHR:      pointClippingOutside = false;                           break;
557                         case invalidClippingBehavior:                                                           TCU_FAIL("Clipping behavior read failure");     break;
558                         default:
559                         {
560                                 TCU_FAIL("Unexpected clipping behavior reported");
561                         }
562                 }
563         }
564         else
565         {
566                 //TODO: Now we have 2 cases {some-points-drawn|nothing}, we should have {all-points-drawn|some-points-drawn|nothing}
567                 return tcu::TestStatus::pass("OK");
568         }
569
570         std::vector<Shader> shaders;
571         shaders.push_back(Shader(VK_SHADER_STAGE_VERTEX_BIT,    context.getBinaryCollection().get("vert")));
572         shaders.push_back(Shader(VK_SHADER_STAGE_FRAGMENT_BIT,  context.getBinaryCollection().get("frag")));
573
574         std::vector<Vec4> vertices;
575         {
576                 const float delta       = 0.1f;  // much smaller than the point size
577                 const float p           = 1.0f + delta;
578
579                 vertices.push_back(Vec4(  -p,   -p, 0.1f, 1.0f));
580                 vertices.push_back(Vec4(  -p,    p, 0.2f, 1.0f));
581                 vertices.push_back(Vec4(   p,    p, 0.4f, 1.0f));
582                 vertices.push_back(Vec4(   p,   -p, 0.6f, 1.0f));
583                 vertices.push_back(Vec4(0.0f,   -p, 0.8f, 1.0f));
584                 vertices.push_back(Vec4(   p, 0.0f, 0.9f, 1.0f));
585                 vertices.push_back(Vec4(0.0f,    p, 0.1f, 1.0f));
586                 vertices.push_back(Vec4(  -p, 0.0f, 0.2f, 1.0f));
587         }
588
589         tcu::TestLog&   log     = context.getTestContext().getLog();
590
591         log << tcu::TestLog::Message << "Drawing several large points just outside the clip volume. Expecting an empty image." << tcu::TestLog::EndMessage;
592
593         DrawContext drawContext(context, shaders, vertices, VK_PRIMITIVE_TOPOLOGY_POINT_LIST);
594         drawContext.draw();
595
596         const int       numBlackPixels  = countPixels(drawContext.getColorPixels(), Vec4(0.0f, 0.0f, 0.0f, 1.0f), Vec4());
597         bool            result                  = false;
598
599         if (pointClippingOutside)
600         {
601                 // All pixels must be black -- nothing is drawn.
602                 result = (numBlackPixels == NUM_RENDER_PIXELS);
603         }
604         else
605         {
606                 // Rendering pixels without clipping: some pixels should not be black -- something is drawn.
607                 result = (numBlackPixels < NUM_RENDER_PIXELS);
608         }
609
610         return (result ? tcu::TestStatus::pass("OK") : tcu::TestStatus::fail("Rendered image(s) are incorrect"));
611 }
612
613 //! Wide line clipping
614 //! 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
615 //!       if it lies entirely outside the volume.
616 tcu::TestStatus testWideLines (Context& context, const LineOrientation lineOrientation)
617 {
618         requireFeatures(context.getInstanceInterface(), context.getPhysicalDevice(), FEATURE_WIDE_LINES);
619
620         std::vector<Shader> shaders;
621         shaders.push_back(Shader(VK_SHADER_STAGE_VERTEX_BIT,    context.getBinaryCollection().get("vert")));
622         shaders.push_back(Shader(VK_SHADER_STAGE_FRAGMENT_BIT,  context.getBinaryCollection().get("frag")));
623
624         const float delta = 0.1f;  // much smaller than the line width
625
626         std::vector<Vec4> vertices;
627         if (lineOrientation == LINE_ORIENTATION_AXIS_ALIGNED)
628         {
629                 // Axis-aligned lines just outside the clip volume.
630                 const float p = 1.0f + delta;
631                 const float q = 0.9f;
632
633                 vertices.push_back(Vec4(-p, -q, 0.1f, 1.0f));
634                 vertices.push_back(Vec4(-p,  q, 0.9f, 1.0f));   // line 0
635                 vertices.push_back(Vec4(-q,  p, 0.1f, 1.0f));
636                 vertices.push_back(Vec4( q,  p, 0.9f, 1.0f));   // line 1
637                 vertices.push_back(Vec4( p,  q, 0.1f, 1.0f));
638                 vertices.push_back(Vec4( p, -q, 0.9f, 1.0f));   // line 2
639                 vertices.push_back(Vec4( q, -p, 0.1f, 1.0f));
640                 vertices.push_back(Vec4(-q, -p, 0.9f, 1.0f));   // line 3
641         }
642         else if (lineOrientation == LINE_ORIENTATION_DIAGONAL)
643         {
644                 // Diagonal lines just outside the clip volume.
645                 const float p = 2.0f + delta;
646
647                 vertices.push_back(Vec4(  -p, 0.0f, 0.1f, 1.0f));
648                 vertices.push_back(Vec4(0.0f,   -p, 0.9f, 1.0f));       // line 0
649                 vertices.push_back(Vec4(0.0f,   -p, 0.1f, 1.0f));
650                 vertices.push_back(Vec4(   p, 0.0f, 0.9f, 1.0f));       // line 1
651                 vertices.push_back(Vec4(   p, 0.0f, 0.1f, 1.0f));
652                 vertices.push_back(Vec4(0.0f,    p, 0.9f, 1.0f));       // line 2
653                 vertices.push_back(Vec4(0.0f,    p, 0.1f, 1.0f));
654                 vertices.push_back(Vec4(  -p, 0.0f, 0.9f, 1.0f));       // line 3
655         }
656         else
657                 DE_ASSERT(0);
658
659         const VkPhysicalDeviceLimits limits = getPhysicalDeviceProperties(context.getInstanceInterface(), context.getPhysicalDevice()).limits;
660
661         const float             lineWidth       = std::min(static_cast<float>(RENDER_SIZE), limits.lineWidthRange[1]);
662         tcu::TestLog&   log                     = context.getTestContext().getLog();
663
664         log << tcu::TestLog::Message << "Drawing several wide lines just outside the clip volume. Expecting an empty image." << tcu::TestLog::EndMessage
665                 << tcu::TestLog::Message << "Line width is " << lineWidth << "." << tcu::TestLog::EndMessage;
666
667         DrawContext drawContext(context, shaders, vertices, VK_PRIMITIVE_TOPOLOGY_LINE_LIST, static_cast<deUint32>(RENDER_SIZE), false, false, lineWidth);
668         drawContext.draw();
669
670         // All pixels must be black -- nothing is drawn.
671         const int numBlackPixels = countPixels(drawContext.getColorPixels(), Vec4(0.0f, 0.0f, 0.0f, 1.0f), Vec4());
672
673         return (numBlackPixels == NUM_RENDER_PIXELS ? tcu::TestStatus::pass("OK") : tcu::TestStatus::fail("Rendered image(s) are incorrect"));
674 }
675
676 } // ClipVolume ns
677
678 namespace ClipDistance
679 {
680
681 struct CaseDefinition
682 {
683         const VkPrimitiveTopology       topology;
684         const bool                                      dynamicIndexing;
685         const bool                                      enableTessellation;
686         const bool                                      enableGeometry;
687         const int                                       numClipDistances;
688         const int                                       numCullDistances;
689
690         CaseDefinition (const VkPrimitiveTopology       topology_,
691                                         const int                                       numClipDistances_,
692                                         const int                                       numCullDistances_,
693                                         const bool                                      enableTessellation_,
694                                         const bool                                      enableGeometry_,
695                                         const bool                                      dynamicIndexing_)
696                 : topology                                      (topology_)
697                 , dynamicIndexing                       (dynamicIndexing_)
698                 , enableTessellation            (enableTessellation_)
699                 , enableGeometry                        (enableGeometry_)
700                 , numClipDistances                      (numClipDistances_)
701                 , numCullDistances                      (numCullDistances_)
702         {
703         }
704 };
705
706 void initPrograms (SourceCollections& programCollection, const CaseDefinition caseDef)
707 {
708         DE_ASSERT(caseDef.numClipDistances + caseDef.numCullDistances <= MAX_COMBINED_CLIP_AND_CULL_DISTANCES);
709
710         std::string perVertexBlock;
711         {
712                 std::ostringstream str;
713                 str << "gl_PerVertex {\n"
714                         << "    vec4  gl_Position;\n";
715                 if (caseDef.numClipDistances > 0)
716                         str << "    float gl_ClipDistance[" << caseDef.numClipDistances << "];\n";
717                 if (caseDef.numCullDistances > 0)
718                         str << "    float gl_CullDistance[" << caseDef.numCullDistances << "];\n";
719                 str << "}";
720                 perVertexBlock = str.str();
721         }
722
723         // Vertex shader
724         {
725                 std::ostringstream src;
726                 src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n"
727                         << "\n"
728                         << "layout(location = 0) in  vec4 v_position;\n"
729                         << "layout(location = 0) out vec4 out_color;\n"
730                         << "\n"
731                         << "out " << perVertexBlock << ";\n"
732                         << "\n"
733                         << "void main (void)\n"
734                         << "{\n"
735                         << "    gl_Position = v_position;\n"
736                         << "    out_color   = vec4(1.0, 0.5 * (v_position.x + 1.0), 0.0, 1.0);\n"
737                         << "\n"
738                         << "    const int barNdx = gl_VertexIndex / 6;\n";
739                 if (caseDef.dynamicIndexing)
740                 {
741                         if (caseDef.numClipDistances > 0)
742                                 src << "    for (int i = 0; i < " << caseDef.numClipDistances << "; ++i)\n"
743                                         << "        gl_ClipDistance[i] = (barNdx == i ? v_position.y : 0.0);\n";
744                         if (caseDef.numCullDistances > 0)
745                                 src << "    for (int i = 0; i < " << caseDef.numCullDistances << "; ++i)\n"
746                                         << "        gl_CullDistance[i] = 0.0;\n";
747                 }
748                 else
749                 {
750                         for (int i = 0; i < caseDef.numClipDistances; ++i)
751                                 src << "    gl_ClipDistance[" << i << "] = (barNdx == " << i << " ? v_position.y : 0.0);\n";
752                         for (int i = 0; i < caseDef.numCullDistances; ++i)
753                                 src << "    gl_CullDistance[" << i << "] = 0.0;\n";             // don't cull anything
754                 }
755                 src     << "}\n";
756
757                 programCollection.glslSources.add("vert") << glu::VertexSource(src.str());
758         }
759
760         if (caseDef.enableTessellation)
761         {
762                 std::ostringstream src;
763                 src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n"
764                         << "\n"
765                         << "layout(vertices = " << NUM_PATCH_CONTROL_POINTS << ") out;\n"
766                         << "\n"
767                         << "layout(location = 0) in  vec4 in_color[];\n"
768                         << "layout(location = 0) out vec4 out_color[];\n"
769                         << "\n"
770                         << "in " << perVertexBlock << " gl_in[gl_MaxPatchVertices];\n"
771                         << "\n"
772                         << "out " << perVertexBlock << " gl_out[];\n"
773                         << "\n"
774                         << "void main (void)\n"
775                         << "{\n"
776                         << "    gl_TessLevelInner[0] = 1.0;\n"
777                         << "    gl_TessLevelInner[1] = 1.0;\n"
778                         << "\n"
779                         << "    gl_TessLevelOuter[0] = 1.0;\n"
780                         << "    gl_TessLevelOuter[1] = 1.0;\n"
781                         << "    gl_TessLevelOuter[2] = 1.0;\n"
782                         << "    gl_TessLevelOuter[3] = 1.0;\n"
783                         << "\n"
784                         << "    gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;\n"
785                         << "    out_color[gl_InvocationID]          = in_color[gl_InvocationID];\n"
786                         << "\n";
787                 if (caseDef.dynamicIndexing)
788                 {
789                         if (caseDef.numClipDistances > 0)
790                                 src << "    for (int i = 0; i < " << caseDef.numClipDistances << "; ++i)\n"
791                                         << "        gl_out[gl_InvocationID].gl_ClipDistance[i] = gl_in[gl_InvocationID].gl_ClipDistance[i];\n";
792                         if (caseDef.numCullDistances > 0)
793                                 src << "    for (int i = 0; i < " << caseDef.numCullDistances << "; ++i)\n"
794                                         << "        gl_out[gl_InvocationID].gl_CullDistance[i] = gl_in[gl_InvocationID].gl_CullDistance[i];\n";
795                 }
796                 else
797                 {
798                         for (int i = 0; i < caseDef.numClipDistances; ++i)
799                                 src << "    gl_out[gl_InvocationID].gl_ClipDistance[" << i << "] = gl_in[gl_InvocationID].gl_ClipDistance[" << i << "];\n";
800                         for (int i = 0; i < caseDef.numCullDistances; ++i)
801                                 src << "    gl_out[gl_InvocationID].gl_CullDistance[" << i << "] = gl_in[gl_InvocationID].gl_CullDistance[" << i << "];\n";
802                 }
803                 src << "}\n";
804
805                 programCollection.glslSources.add("tesc") << glu::TessellationControlSource(src.str());
806         }
807
808         if (caseDef.enableTessellation)
809         {
810                 DE_ASSERT(NUM_PATCH_CONTROL_POINTS == 3);  // assumed in shader code
811
812                 std::ostringstream src;
813                 src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n"
814                         << "\n"
815                         << "layout(triangles, equal_spacing, ccw) in;\n"
816                         << "\n"
817                         << "layout(location = 0) in  vec4 in_color[];\n"
818                         << "layout(location = 0) out vec4 out_color;\n"
819                         << "\n"
820                         << "in " << perVertexBlock << " gl_in[gl_MaxPatchVertices];\n"
821                         << "\n"
822                         << "out " << perVertexBlock << ";\n"
823                         << "\n"
824                         << "void main (void)\n"
825                         << "{\n"
826                         << "    vec3 px     = gl_TessCoord.x * gl_in[0].gl_Position.xyz;\n"
827                         << "    vec3 py     = gl_TessCoord.y * gl_in[1].gl_Position.xyz;\n"
828                         << "    vec3 pz     = gl_TessCoord.z * gl_in[2].gl_Position.xyz;\n"
829                         << "    gl_Position = vec4(px + py + pz, 1.0);\n"
830                         << "    out_color   = (in_color[0] + in_color[1] + in_color[2]) / 3.0;\n"
831                         << "\n";
832                 if (caseDef.dynamicIndexing)
833                 {
834                         if (caseDef.numClipDistances > 0)
835                                 src << "    for (int i = 0; i < " << caseDef.numClipDistances << "; ++i)\n"
836                                         << "        gl_ClipDistance[i] = gl_TessCoord.x * gl_in[0].gl_ClipDistance[i]\n"
837                                         << "                           + gl_TessCoord.y * gl_in[1].gl_ClipDistance[i]\n"
838                                         << "                           + gl_TessCoord.z * gl_in[2].gl_ClipDistance[i];\n";
839                         if (caseDef.numCullDistances > 0)
840                                 src << "    for (int i = 0; i < " << caseDef.numCullDistances << "; ++i)\n"
841                                         << "        gl_CullDistance[i] = gl_TessCoord.x * gl_in[0].gl_CullDistance[i]\n"
842                                         << "                           + gl_TessCoord.y * gl_in[1].gl_CullDistance[i]\n"
843                                         << "                           + gl_TessCoord.z * gl_in[2].gl_CullDistance[i];\n";
844                 }
845                 else
846                 {
847                         for (int i = 0; i < caseDef.numClipDistances; ++i)
848                                 src << "    gl_ClipDistance[" << i << "] = gl_TessCoord.x * gl_in[0].gl_ClipDistance[" << i << "]\n"
849                                         << "                       + gl_TessCoord.y * gl_in[1].gl_ClipDistance[" << i << "]\n"
850                                         << "                       + gl_TessCoord.z * gl_in[2].gl_ClipDistance[" << i << "];\n";
851                         for (int i = 0; i < caseDef.numCullDistances; ++i)
852                                 src << "    gl_CullDistance[" << i << "] = gl_TessCoord.x * gl_in[0].gl_CullDistance[" << i << "]\n"
853                                         << "                       + gl_TessCoord.y * gl_in[1].gl_CullDistance[" << i << "]\n"
854                                         << "                       + gl_TessCoord.z * gl_in[2].gl_CullDistance[" << i << "];\n";
855                 }
856                 src << "}\n";
857
858                 programCollection.glslSources.add("tese") << glu::TessellationEvaluationSource(src.str());
859         }
860
861         if (caseDef.enableGeometry)
862         {
863                 std::ostringstream src;
864                 src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n"
865                         << "\n"
866                         << "layout(triangles) in;\n"
867                         << "layout(triangle_strip, max_vertices = 3) out;\n"
868                         << "\n"
869                         << "layout(location = 0) in  vec4 in_color[];\n"
870                         << "layout(location = 0) out vec4 out_color;\n"
871                         << "\n"
872                         << "in " << perVertexBlock << " gl_in[];\n"
873                         << "\n"
874                         << "out " << perVertexBlock << ";\n"
875                         << "\n"
876                         << "void main (void)\n"
877                         << "{\n";
878                 for (int vertNdx = 0; vertNdx < 3; ++vertNdx)
879                 {
880                         if (vertNdx > 0)
881                                 src << "\n";
882                         src << "    gl_Position = gl_in[" << vertNdx << "].gl_Position;\n"
883                                 << "    out_color   = in_color[" << vertNdx << "];\n";
884                         if (caseDef.dynamicIndexing)
885                         {
886                                 if (caseDef.numClipDistances > 0)
887                                         src << "    for (int i = 0; i < " << caseDef.numClipDistances << "; ++i)\n"
888                                                 << "        gl_ClipDistance[i] = gl_in[" << vertNdx << "].gl_ClipDistance[i];\n";
889                                 if (caseDef.numCullDistances > 0)
890                                         src << "    for (int i = 0; i < " << caseDef.numCullDistances << "; ++i)\n"
891                                                 << "        gl_CullDistance[i] = gl_in[" << vertNdx << "].gl_CullDistance[i];\n";
892                         }
893                         else
894                         {
895                                 for (int i = 0; i < caseDef.numClipDistances; ++i)
896                                         src << "    gl_ClipDistance[" << i << "] = gl_in[" << vertNdx << "].gl_ClipDistance[" << i << "];\n";
897                                 for (int i = 0; i < caseDef.numCullDistances; ++i)
898                                         src << "    gl_CullDistance[" << i << "] = gl_in[" << vertNdx << "].gl_CullDistance[" << i << "];\n";
899                         }
900                         src << "    EmitVertex();\n";
901                 }
902                 src     << "}\n";
903
904                 programCollection.glslSources.add("geom") << glu::GeometrySource(src.str());
905         }
906
907         // Fragment shader
908         {
909                 std::ostringstream src;
910                 src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n"
911                         << "\n"
912                         << "layout(location = 0) in flat vec4 in_color;\n"
913                         << "layout(location = 0) out vec4 o_color;\n"
914                         << "\n"
915                         << "void main (void)\n"
916                         << "{\n"
917                         << "    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
918                         << "}\n";
919
920                 programCollection.glslSources.add("frag") << glu::FragmentSource(src.str());
921         }
922 }
923
924 tcu::TestStatus testClipDistance (Context& context, const CaseDefinition caseDef)
925 {
926         // Check test requirements
927         {
928                 const InstanceInterface&                vki                     = context.getInstanceInterface();
929                 const VkPhysicalDevice                  physDevice      = context.getPhysicalDevice();
930                 const VkPhysicalDeviceLimits    limits          = getPhysicalDeviceProperties(vki, physDevice).limits;
931
932                 FeatureFlags requirements = (FeatureFlags)0;
933
934                 if (caseDef.numClipDistances > 0)
935                         requirements |= FEATURE_SHADER_CLIP_DISTANCE;
936                 if (caseDef.numCullDistances > 0)
937                         requirements |= FEATURE_SHADER_CULL_DISTANCE;
938                 if (caseDef.enableTessellation)
939                         requirements |= FEATURE_TESSELLATION_SHADER;
940                 if (caseDef.enableGeometry)
941                         requirements |= FEATURE_GEOMETRY_SHADER;
942
943                 requireFeatures(vki, physDevice, requirements);
944
945                 // Check limits for supported features
946
947                 if (caseDef.numClipDistances > 0 && limits.maxClipDistances < MAX_CLIP_DISTANCES)
948                         return tcu::TestStatus::fail("maxClipDistances smaller than the minimum required by the spec");
949                 if (caseDef.numCullDistances > 0 && limits.maxCullDistances < MAX_CULL_DISTANCES)
950                         return tcu::TestStatus::fail("maxCullDistances smaller than the minimum required by the spec");
951                 if (caseDef.numCullDistances > 0 && limits.maxCombinedClipAndCullDistances < MAX_COMBINED_CLIP_AND_CULL_DISTANCES)
952                         return tcu::TestStatus::fail("maxCombinedClipAndCullDistances smaller than the minimum required by the spec");
953         }
954
955         std::vector<Shader> shaders;
956         shaders.push_back(Shader(VK_SHADER_STAGE_VERTEX_BIT,    context.getBinaryCollection().get("vert")));
957         shaders.push_back(Shader(VK_SHADER_STAGE_FRAGMENT_BIT,  context.getBinaryCollection().get("frag")));
958         if (caseDef.enableTessellation)
959         {
960                 shaders.push_back(Shader(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT,              context.getBinaryCollection().get("tesc")));
961                 shaders.push_back(Shader(VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT,   context.getBinaryCollection().get("tese")));
962         }
963         if (caseDef.enableGeometry)
964                 shaders.push_back(Shader(VK_SHADER_STAGE_GEOMETRY_BIT,  context.getBinaryCollection().get("geom")));
965
966         const int numBars = MAX_COMBINED_CLIP_AND_CULL_DISTANCES;
967
968         std::vector<Vec4> vertices;
969         {
970                 const float     dx = 2.0f / numBars;
971                 for (int i = 0; i < numBars; ++i)
972                 {
973                         const float x = -1.0f + dx * static_cast<float>(i);
974
975                         vertices.push_back(Vec4(x,      -1.0f, 0.0f, 1.0f));
976                         vertices.push_back(Vec4(x,       1.0f, 0.0f, 1.0f));
977                         vertices.push_back(Vec4(x + dx, -1.0f, 0.0f, 1.0f));
978
979                         vertices.push_back(Vec4(x,       1.0f, 0.0f, 1.0f));
980                         vertices.push_back(Vec4(x + dx,  1.0f, 0.0f, 1.0f));
981                         vertices.push_back(Vec4(x + dx, -1.0f, 0.0f, 1.0f));
982                 }
983         }
984
985         tcu::TestLog& log = context.getTestContext().getLog();
986
987         log << tcu::TestLog::Message << "Drawing " << numBars << " colored bars, clipping the first " << caseDef.numClipDistances << tcu::TestLog::EndMessage
988                 << tcu::TestLog::Message << "Using " << caseDef.numClipDistances << " ClipDistance(s) and " << caseDef.numCullDistances << " CullDistance(s)" << tcu::TestLog::EndMessage
989                 << tcu::TestLog::Message << "Expecting upper half of the clipped bars to be black." << tcu::TestLog::EndMessage;
990
991         DrawContext drawContext(context, shaders, vertices, caseDef.topology);
992         drawContext.draw();
993
994         // Count black pixels in the whole image.
995         const int numBlackPixels                = countPixels(drawContext.getColorPixels(), Vec4(0.0f, 0.0f, 0.0f, 1.0f), Vec4());
996         const IVec2     clipRegion                      = IVec2(caseDef.numClipDistances * RENDER_SIZE / numBars, RENDER_SIZE / 2);
997         const int expectedClippedPixels = clipRegion.x() * clipRegion.y();
998         // Make sure the bottom half has no black pixels (possible if image became corrupted).
999         const int guardPixels                   = countPixels(drawContext.getColorPixels(), IVec2(0, RENDER_SIZE/2), clipRegion, Vec4(0.0f, 0.0f, 0.0f, 1.0f), Vec4());
1000
1001         return (numBlackPixels == expectedClippedPixels && guardPixels == 0 ? tcu::TestStatus::pass("OK")
1002                                                                                                                                                 : tcu::TestStatus::fail("Rendered image(s) are incorrect"));
1003 }
1004
1005 } // ClipDistance ns
1006
1007 namespace ClipDistanceComplementarity
1008 {
1009
1010 void initPrograms (SourceCollections& programCollection, const int numClipDistances)
1011 {
1012         // Vertex shader
1013         {
1014                 DE_ASSERT(numClipDistances > 0);
1015                 const int clipDistanceLastNdx = numClipDistances - 1;
1016
1017                 std::ostringstream src;
1018                 src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n"
1019                         << "\n"
1020                         << "layout(location = 0) in vec4 v_position;    // we are passing ClipDistance in w component\n"
1021                         << "\n"
1022                         << "out gl_PerVertex {\n"
1023                         << "    vec4  gl_Position;\n"
1024                         << "    float gl_ClipDistance[" << numClipDistances << "];\n"
1025                         << "};\n"
1026                         << "\n"
1027                         << "void main (void)\n"
1028                         << "{\n"
1029                         << "    gl_Position        = vec4(v_position.xyz, 1.0);\n";
1030                 for (int i = 0; i < clipDistanceLastNdx; ++i)
1031                         src << "    gl_ClipDistance[" << i << "] = 0.0;\n";
1032                 src << "    gl_ClipDistance[" << clipDistanceLastNdx << "] = v_position.w;\n"
1033                         << "}\n";
1034
1035                 programCollection.glslSources.add("vert") << glu::VertexSource(src.str());
1036         }
1037
1038         // Fragment shader
1039         {
1040                 std::ostringstream src;
1041                 src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n"
1042                         << "\n"
1043                         << "layout(location = 0) out vec4 o_color;\n"
1044                         << "\n"
1045                         << "void main (void)\n"
1046                         << "{\n"
1047                         << "    o_color = vec4(1.0, 1.0, 1.0, 0.5);\n"
1048                         << "}\n";
1049
1050                 programCollection.glslSources.add("frag") << glu::FragmentSource(src.str());
1051         }
1052 }
1053
1054 tcu::TestStatus testComplementarity (Context& context, const int numClipDistances)
1055 {
1056         // Check test requirements
1057         {
1058                 const InstanceInterface&                vki                     = context.getInstanceInterface();
1059                 const VkPhysicalDevice                  physDevice      = context.getPhysicalDevice();
1060
1061                 requireFeatures(vki, physDevice, FEATURE_SHADER_CLIP_DISTANCE);
1062         }
1063
1064         std::vector<Shader> shaders;
1065         shaders.push_back(Shader(VK_SHADER_STAGE_VERTEX_BIT,    context.getBinaryCollection().get("vert")));
1066         shaders.push_back(Shader(VK_SHADER_STAGE_FRAGMENT_BIT,  context.getBinaryCollection().get("frag")));
1067
1068         std::vector<Vec4> vertices;
1069         {
1070                 de::Random      rnd                                             (1234);
1071                 const int       numSections                             = 16;
1072                 const int       numVerticesPerSection   = 4;    // logical verticies, due to triangle list topology we actually use 6 per section
1073
1074                 DE_ASSERT(RENDER_SIZE_LARGE % numSections == 0);
1075
1076                 std::vector<float> clipDistances(numVerticesPerSection * numSections);
1077                 for (int i = 0; i < static_cast<int>(clipDistances.size()); ++i)
1078                         clipDistances[i] = rnd.getFloat(-1.0f, 1.0f);
1079
1080                 // Two sets of identical primitives, but with a different ClipDistance sign.
1081                 for (int setNdx = 0; setNdx < 2; ++setNdx)
1082                 {
1083                         const float sign = (setNdx == 0 ? 1.0f : -1.0f);
1084                         const float     dx       = 2.0f / static_cast<float>(numSections);
1085
1086                         for (int i = 0; i < numSections; ++i)
1087                         {
1088                                 const int       ndxBase = numVerticesPerSection * i;
1089                                 const float x           = -1.0f + dx * static_cast<float>(i);
1090                                 const Vec4      p0              = Vec4(x,      -1.0f, 0.0f, sign * clipDistances[ndxBase + 0]);
1091                                 const Vec4      p1              = Vec4(x,       1.0f, 0.0f, sign * clipDistances[ndxBase + 1]);
1092                                 const Vec4      p2              = Vec4(x + dx,  1.0f, 0.0f, sign * clipDistances[ndxBase + 2]);
1093                                 const Vec4      p3              = Vec4(x + dx, -1.0f, 0.0f, sign * clipDistances[ndxBase + 3]);
1094
1095                                 vertices.push_back(p0);
1096                                 vertices.push_back(p1);
1097                                 vertices.push_back(p2);
1098
1099                                 vertices.push_back(p2);
1100                                 vertices.push_back(p3);
1101                                 vertices.push_back(p0);
1102                         }
1103                 }
1104         }
1105
1106         tcu::TestLog& log = context.getTestContext().getLog();
1107
1108         log << tcu::TestLog::Message << "Draw two sets of primitives with blending, differing only with ClipDistance sign." << tcu::TestLog::EndMessage
1109                 << tcu::TestLog::Message << "Using " << numClipDistances << " clipping plane(s), one of them possibly having negative values." << tcu::TestLog::EndMessage
1110                 << tcu::TestLog::Message << "Expecting a uniform gray area, no missing (black) nor overlapped (white) pixels." << tcu::TestLog::EndMessage;
1111
1112         DrawContext drawContext(context, shaders, vertices, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, static_cast<deUint32>(RENDER_SIZE_LARGE), false, true);
1113         drawContext.draw();
1114
1115         const int numGrayPixels         = countPixels(drawContext.getColorPixels(), Vec4(0.5f, 0.5f, 0.5f, 1.0f), Vec4(0.02f, 0.02f, 0.02f, 0.0f));
1116         const int numExpectedPixels     = RENDER_SIZE_LARGE * RENDER_SIZE_LARGE;
1117
1118         return (numGrayPixels == numExpectedPixels ? tcu::TestStatus::pass("OK") : tcu::TestStatus::fail("Rendered image(s) are incorrect"));
1119 }
1120
1121 } // ClipDistanceComplementarity ns
1122
1123 void addClippingTests (tcu::TestCaseGroup* clippingTestsGroup)
1124 {
1125         tcu::TestContext& testCtx = clippingTestsGroup->getTestContext();
1126
1127         // Clipping against the clip volume
1128         {
1129                 using namespace ClipVolume;
1130
1131                 static const VkPrimitiveTopology cases[] =
1132                 {
1133                         VK_PRIMITIVE_TOPOLOGY_POINT_LIST,
1134                         VK_PRIMITIVE_TOPOLOGY_LINE_LIST,
1135                         VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY,
1136                         VK_PRIMITIVE_TOPOLOGY_LINE_STRIP,
1137                         VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY,
1138                         VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
1139                         VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY,
1140                         VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
1141                         VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY,
1142                         VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN,
1143                 };
1144
1145                 MovePtr<tcu::TestCaseGroup> clipVolumeGroup(new tcu::TestCaseGroup(testCtx, "clip_volume", "clipping with the clip volume"));
1146
1147                 // Fully inside the clip volume
1148                 {
1149                         MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "inside", ""));
1150
1151                         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1152                                 addFunctionCaseWithPrograms<VkPrimitiveTopology>(
1153                                         group.get(), getPrimitiveTopologyShortName(cases[caseNdx]), "", initPrograms, testPrimitivesInside, cases[caseNdx]);
1154
1155                         clipVolumeGroup->addChild(group.release());
1156                 }
1157
1158                 // Fully outside the clip volume
1159                 {
1160                         MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "outside", ""));
1161
1162                         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1163                                 addFunctionCaseWithPrograms<VkPrimitiveTopology>(
1164                                         group.get(), getPrimitiveTopologyShortName(cases[caseNdx]), "", initPrograms, testPrimitivesOutside, cases[caseNdx]);
1165
1166                         clipVolumeGroup->addChild(group.release());
1167                 }
1168
1169                 // Depth clamping
1170                 {
1171                         MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "depth_clamp", ""));
1172
1173                         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1174                                 addFunctionCaseWithPrograms<VkPrimitiveTopology>(
1175                                         group.get(), getPrimitiveTopologyShortName(cases[caseNdx]), "", initPrograms, testPrimitivesDepthClamp, cases[caseNdx]);
1176
1177                         clipVolumeGroup->addChild(group.release());
1178                 }
1179
1180                 // Large points and wide lines
1181                 {
1182                         // \note For both points and lines, if an unsupported size/width is selected, the nearest supported size will be chosen.
1183                         //       We do have to check for feature support though.
1184
1185                         MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "clipped", ""));
1186
1187                         addFunctionCaseWithPrograms(group.get(), "large_points", "", initProgramsPointSize, testLargePoints);
1188
1189                         addFunctionCaseWithPrograms<LineOrientation>(group.get(), "wide_lines_axis_aligned", "", initPrograms, testWideLines, LINE_ORIENTATION_AXIS_ALIGNED);
1190                         addFunctionCaseWithPrograms<LineOrientation>(group.get(), "wide_lines_diagonal",         "", initPrograms, testWideLines, LINE_ORIENTATION_DIAGONAL);
1191
1192                         clipVolumeGroup->addChild(group.release());
1193                 }
1194
1195                 clippingTestsGroup->addChild(clipVolumeGroup.release());
1196         }
1197
1198         // User-defined clip planes
1199         {
1200                 MovePtr<tcu::TestCaseGroup> clipDistanceGroup(new tcu::TestCaseGroup(testCtx, "user_defined", "user-defined clip planes"));
1201
1202                 // ClipDistance, CullDistance and maxCombinedClipAndCullDistances usage
1203                 {
1204                         using namespace ClipDistance;
1205
1206                         static const struct
1207                         {
1208                                 const char* const       groupName;
1209                                 const char* const       description;
1210                                 bool                            useCullDistance;
1211                         } caseGroups[] =
1212                         {
1213                                 { "clip_distance",              "use ClipDistance",                                                                             false },
1214                                 { "clip_cull_distance", "use ClipDistance and CullDistance at the same time",   true  },
1215                         };
1216
1217                         const deUint32 flagTessellation = 1u << 0;
1218                         const deUint32 flagGeometry             = 1u << 1;
1219
1220                         for (int groupNdx = 0; groupNdx < DE_LENGTH_OF_ARRAY(caseGroups); ++groupNdx)
1221                         for (int indexingMode = 0; indexingMode < 2; ++indexingMode)
1222                         {
1223                                 const bool                      dynamicIndexing = (indexingMode == 1);
1224                                 const std::string       mainGroupName   = de::toString(caseGroups[groupNdx].groupName) + (dynamicIndexing ? "_dynamic_index" : "");
1225
1226                                 MovePtr<tcu::TestCaseGroup>     mainGroup(new tcu::TestCaseGroup(testCtx, mainGroupName.c_str(), ""));
1227
1228                                 for (deUint32 shaderMask = 0u; shaderMask <= (flagTessellation | flagGeometry); ++shaderMask)
1229                                 {
1230                                         const bool                      useTessellation = (shaderMask & flagTessellation) != 0;
1231                                         const bool                      useGeometry             = (shaderMask & flagGeometry) != 0;
1232                                         const std::string       shaderGroupName = std::string("vert") + (useTessellation ? "_tess" : "") + (useGeometry ? "_geom" : "");
1233
1234                                         MovePtr<tcu::TestCaseGroup>     shaderGroup(new tcu::TestCaseGroup(testCtx, shaderGroupName.c_str(), ""));
1235
1236                                         for (int numClipPlanes = 1; numClipPlanes <= MAX_CLIP_DISTANCES; ++numClipPlanes)
1237                                         {
1238                                                 const int                                       numCullPlanes   = (caseGroups[groupNdx].useCullDistance
1239                                                                                                                                                 ? std::min(static_cast<int>(MAX_CULL_DISTANCES), MAX_COMBINED_CLIP_AND_CULL_DISTANCES - numClipPlanes)
1240                                                                                                                                                 : 0);
1241                                                 const std::string                       caseName                = de::toString(numClipPlanes) + (numCullPlanes > 0 ? "_" + de::toString(numCullPlanes) : "");
1242                                                 const VkPrimitiveTopology       topology                = (useTessellation ? VK_PRIMITIVE_TOPOLOGY_PATCH_LIST : VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST);
1243
1244                                                 addFunctionCaseWithPrograms<CaseDefinition>(
1245                                                         shaderGroup.get(), caseName, caseGroups[groupNdx].description, initPrograms, testClipDistance,
1246                                                         CaseDefinition(topology, numClipPlanes, numCullPlanes, useTessellation, useGeometry, dynamicIndexing));
1247                                         }
1248                                         mainGroup->addChild(shaderGroup.release());
1249                                 }
1250                                 clipDistanceGroup->addChild(mainGroup.release());
1251                         }
1252                 }
1253
1254                 // Complementarity criterion (i.e. clipped and not clipped areas must add up to a complete primitive with no holes nor overlap)
1255                 {
1256                         using namespace ClipDistanceComplementarity;
1257
1258                         MovePtr<tcu::TestCaseGroup>     group(new tcu::TestCaseGroup(testCtx, "complementarity", ""));
1259
1260                         for (int numClipDistances = 1; numClipDistances <= MAX_CLIP_DISTANCES; ++numClipDistances)
1261                                 addFunctionCaseWithPrograms<int>(group.get(), de::toString(numClipDistances).c_str(), "", initPrograms, testComplementarity, numClipDistances);
1262
1263                         clippingTestsGroup->addChild(group.release());
1264                 }
1265
1266                 clippingTestsGroup->addChild(clipDistanceGroup.release());
1267         }
1268 }
1269
1270 } // anonymous
1271
1272 tcu::TestCaseGroup* createTests (tcu::TestContext& testCtx)
1273 {
1274         return createTestGroup(testCtx, "clipping", "Clipping tests", addClippingTests);
1275 }
1276
1277 } // clipping
1278 } // vkt