Shaders Derivate Tests: fix threshold
[platform/upstream/VK-GL-CTS.git] / modules / gles3 / functional / es3fShaderDerivateTests.cpp
1 /*-------------------------------------------------------------------------
2  * drawElements Quality Program OpenGL ES 3.0 Module
3  * -------------------------------------------------
4  *
5  * Copyright 2014 The Android Open Source Project
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 Shader derivate function tests.
22  *
23  * \todo [2013-06-25 pyry] Missing features:
24  *  - lines and points
25  *  - projected coordinates
26  *  - continous non-trivial functions (sin, exp)
27  *  - non-continous functions (step)
28  *//*--------------------------------------------------------------------*/
29
30 #include "es3fShaderDerivateTests.hpp"
31 #include "gluShaderProgram.hpp"
32 #include "gluRenderContext.hpp"
33 #include "gluDrawUtil.hpp"
34 #include "gluPixelTransfer.hpp"
35 #include "gluShaderUtil.hpp"
36 #include "gluStrUtil.hpp"
37 #include "gluTextureUtil.hpp"
38 #include "gluTexture.hpp"
39 #include "tcuStringTemplate.hpp"
40 #include "tcuRenderTarget.hpp"
41 #include "tcuSurface.hpp"
42 #include "tcuTestLog.hpp"
43 #include "tcuVectorUtil.hpp"
44 #include "tcuTextureUtil.hpp"
45 #include "tcuRGBA.hpp"
46 #include "tcuFloat.hpp"
47 #include "tcuInterval.hpp"
48 #include "deRandom.hpp"
49 #include "deUniquePtr.hpp"
50 #include "deString.h"
51 #include "glwEnums.hpp"
52 #include "glwFunctions.hpp"
53 #include "glsShaderRenderCase.hpp" // gls::setupDefaultUniforms()
54
55 #include <sstream>
56
57 namespace deqp
58 {
59 namespace gles3
60 {
61 namespace Functional
62 {
63
64 using std::vector;
65 using std::string;
66 using std::map;
67 using tcu::TestLog;
68 using std::ostringstream;
69
70 enum
71 {
72         VIEWPORT_WIDTH          = 167,
73         VIEWPORT_HEIGHT         = 103,
74         FBO_WIDTH                       = 99,
75         FBO_HEIGHT                      = 133,
76         MAX_FAILED_MESSAGES     = 10
77 };
78
79 enum DerivateFunc
80 {
81         DERIVATE_DFDX   = 0,
82         DERIVATE_DFDY,
83         DERIVATE_FWIDTH,
84
85         DERIVATE_LAST
86 };
87
88 enum SurfaceType
89 {
90         SURFACETYPE_DEFAULT_FRAMEBUFFER = 0,
91         SURFACETYPE_UNORM_FBO,
92         SURFACETYPE_FLOAT_FBO,  // \note Uses RGBA32UI fbo actually, since FP rendertargets are not in core spec.
93
94         SURFACETYPE_LAST
95 };
96
97 // Utilities
98
99 namespace
100 {
101
102 class AutoFbo
103 {
104 public:
105         AutoFbo (const glw::Functions& gl)
106                 : m_gl  (gl)
107                 , m_fbo (0)
108         {
109         }
110
111         ~AutoFbo (void)
112         {
113                 if (m_fbo)
114                         m_gl.deleteFramebuffers(1, &m_fbo);
115         }
116
117         void gen (void)
118         {
119                 DE_ASSERT(!m_fbo);
120                 m_gl.genFramebuffers(1, &m_fbo);
121         }
122
123         deUint32 operator* (void) const { return m_fbo; }
124
125 private:
126         const glw::Functions&   m_gl;
127         deUint32                                m_fbo;
128 };
129
130 class AutoRbo
131 {
132 public:
133         AutoRbo (const glw::Functions& gl)
134                 : m_gl  (gl)
135                 , m_rbo (0)
136         {
137         }
138
139         ~AutoRbo (void)
140         {
141                 if (m_rbo)
142                         m_gl.deleteRenderbuffers(1, &m_rbo);
143         }
144
145         void gen (void)
146         {
147                 DE_ASSERT(!m_rbo);
148                 m_gl.genRenderbuffers(1, &m_rbo);
149         }
150
151         deUint32 operator* (void) const { return m_rbo; }
152
153 private:
154         const glw::Functions&   m_gl;
155         deUint32                                m_rbo;
156 };
157
158 } // anonymous
159
160 static const char* getDerivateFuncName (DerivateFunc func)
161 {
162         switch (func)
163         {
164                 case DERIVATE_DFDX:             return "dFdx";
165                 case DERIVATE_DFDY:             return "dFdy";
166                 case DERIVATE_FWIDTH:   return "fwidth";
167                 default:
168                         DE_ASSERT(false);
169                         return DE_NULL;
170         }
171 }
172
173 static const char* getDerivateFuncCaseName (DerivateFunc func)
174 {
175         switch (func)
176         {
177                 case DERIVATE_DFDX:             return "dfdx";
178                 case DERIVATE_DFDY:             return "dfdy";
179                 case DERIVATE_FWIDTH:   return "fwidth";
180                 default:
181                         DE_ASSERT(false);
182                         return DE_NULL;
183         }
184 }
185
186 static inline tcu::BVec4 getDerivateMask (glu::DataType type)
187 {
188         switch (type)
189         {
190                 case glu::TYPE_FLOAT:           return tcu::BVec4(true, false, false, false);
191                 case glu::TYPE_FLOAT_VEC2:      return tcu::BVec4(true, true, false, false);
192                 case glu::TYPE_FLOAT_VEC3:      return tcu::BVec4(true, true, true, false);
193                 case glu::TYPE_FLOAT_VEC4:      return tcu::BVec4(true, true, true, true);
194                 default:
195                         DE_ASSERT(false);
196                         return tcu::BVec4(true);
197         }
198 }
199
200 static inline tcu::Vec4 readDerivate (const tcu::ConstPixelBufferAccess& surface, const tcu::Vec4& derivScale, const tcu::Vec4& derivBias, int x, int y)
201 {
202         return (surface.getPixel(x, y) - derivBias) / derivScale;
203 }
204
205 static inline tcu::UVec4 getCompExpBits (const tcu::Vec4& v)
206 {
207         return tcu::UVec4(tcu::Float32(v[0]).exponentBits(),
208                                           tcu::Float32(v[1]).exponentBits(),
209                                           tcu::Float32(v[2]).exponentBits(),
210                                           tcu::Float32(v[3]).exponentBits());
211 }
212
213 float computeFloatingPointError (const float value, const int numAccurateBits)
214 {
215         const int               numGarbageBits  = 23-numAccurateBits;
216         const deUint32  mask                    = (1u<<numGarbageBits)-1u;
217         const int               exp                             = tcu::Float32(value).exponent();
218
219         return tcu::Float32::construct(+1, exp, (1u<<23) | mask).asFloat() - tcu::Float32::construct(+1, exp, 1u<<23).asFloat();
220 }
221
222 static int getNumMantissaBits (const glu::Precision precision)
223 {
224         switch (precision)
225         {
226                 case glu::PRECISION_HIGHP:              return 23;
227                 case glu::PRECISION_MEDIUMP:    return 10;
228                 case glu::PRECISION_LOWP:               return 6;
229                 default:
230                         DE_ASSERT(false);
231                         return 0;
232         }
233 }
234
235 static int getMinExponent (const glu::Precision precision)
236 {
237         switch (precision)
238         {
239                 case glu::PRECISION_HIGHP:              return -126;
240                 case glu::PRECISION_MEDIUMP:    return -14;
241                 case glu::PRECISION_LOWP:               return -8;
242                 default:
243                         DE_ASSERT(false);
244                         return 0;
245         }
246 }
247
248 static float getSingleULPForExponent (int exp, int numMantissaBits)
249 {
250         if (numMantissaBits > 0)
251         {
252                 DE_ASSERT(numMantissaBits <= 23);
253
254                 const int ulpBitNdx = 23-numMantissaBits;
255                 return tcu::Float32::construct(+1, exp, (1<<23) | (1 << ulpBitNdx)).asFloat() - tcu::Float32::construct(+1, exp, (1<<23)).asFloat();
256         }
257         else
258         {
259                 DE_ASSERT(numMantissaBits == 0);
260                 return tcu::Float32::construct(+1, exp, (1<<23)).asFloat();
261         }
262 }
263
264 static float getSingleULPForValue (float value, int numMantissaBits)
265 {
266         const int exp = tcu::Float32(value).exponent();
267         return getSingleULPForExponent(exp, numMantissaBits);
268 }
269
270 static float convertFloatFlushToZeroRtn (float value, int minExponent, int numAccurateBits)
271 {
272         if (value == 0.0f)
273         {
274                 return 0.0f;
275         }
276         else
277         {
278                 const tcu::Float32      inputFloat                      = tcu::Float32(value);
279                 const int                       numTruncatedBits        = 23-numAccurateBits;
280                 const deUint32          truncMask                       = (1u<<numTruncatedBits)-1u;
281
282                 if (value > 0.0f)
283                 {
284                         if (value > 0.0f && tcu::Float32(value).exponent() < minExponent)
285                         {
286                                 // flush to zero if possible
287                                 return 0.0f;
288                         }
289                         else
290                         {
291                                 // just mask away non-representable bits
292                                 return tcu::Float32::construct(+1, inputFloat.exponent(), inputFloat.mantissa() & ~truncMask).asFloat();
293                         }
294                 }
295                 else
296                 {
297                         if (inputFloat.mantissa() & truncMask)
298                         {
299                                 // decrement one ulp if truncated bits are non-zero (i.e. if value is not representable)
300                                 return tcu::Float32::construct(-1, inputFloat.exponent(), inputFloat.mantissa() & ~truncMask).asFloat() - getSingleULPForExponent(inputFloat.exponent(), numAccurateBits);
301                         }
302                         else
303                         {
304                                 // value is representable, no need to do anything
305                                 return value;
306                         }
307                 }
308         }
309 }
310
311 static float convertFloatFlushToZeroRtp (float value, int minExponent, int numAccurateBits)
312 {
313         return -convertFloatFlushToZeroRtn(-value, minExponent, numAccurateBits);
314 }
315
316 static float addErrorUlp (float value, float numUlps, int numMantissaBits)
317 {
318         return value + numUlps * getSingleULPForValue(value, numMantissaBits);
319 }
320
321 enum
322 {
323         INTERPOLATION_LOST_BITS = 3, // number mantissa of bits allowed to be lost in varying interpolation
324 };
325
326 static inline tcu::Vec4 getDerivateThreshold (const glu::Precision precision, const tcu::Vec4& valueMin, const tcu::Vec4& valueMax, const tcu::Vec4& expectedDerivate)
327 {
328         const int                       baseBits                = getNumMantissaBits(precision);
329         const tcu::UVec4        derivExp                = getCompExpBits(expectedDerivate);
330         const tcu::UVec4        maxValueExp             = max(getCompExpBits(valueMin), getCompExpBits(valueMax));
331         const tcu::UVec4        numBitsLost             = maxValueExp - min(maxValueExp, derivExp);
332         const tcu::IVec4        numAccurateBits = max(baseBits - numBitsLost.asInt() - (int)INTERPOLATION_LOST_BITS, tcu::IVec4(0));
333
334         return tcu::Vec4(computeFloatingPointError(expectedDerivate[0], numAccurateBits[0]),
335                                          computeFloatingPointError(expectedDerivate[1], numAccurateBits[1]),
336                                          computeFloatingPointError(expectedDerivate[2], numAccurateBits[2]),
337                                          computeFloatingPointError(expectedDerivate[3], numAccurateBits[3]));
338 }
339
340 namespace
341 {
342
343 struct LogVecComps
344 {
345         const tcu::Vec4&        v;
346         int                                     numComps;
347
348         LogVecComps (const tcu::Vec4& v_, int numComps_)
349                 : v                     (v_)
350                 , numComps      (numComps_)
351         {
352         }
353 };
354
355 std::ostream& operator<< (std::ostream& str, const LogVecComps& v)
356 {
357         DE_ASSERT(de::inRange(v.numComps, 1, 4));
358         if (v.numComps == 1)            return str << v.v[0];
359         else if (v.numComps == 2)       return str << v.v.toWidth<2>();
360         else if (v.numComps == 3)       return str << v.v.toWidth<3>();
361         else                                            return str << v.v;
362 }
363
364 } // anonymous
365
366 enum VerificationLogging
367 {
368         LOG_ALL = 0,
369         LOG_NOTHING
370 };
371
372 static bool verifyConstantDerivate (tcu::TestLog&                                               log,
373                                                                         const tcu::ConstPixelBufferAccess&      result,
374                                                                         const tcu::PixelBufferAccess&           errorMask,
375                                                                         glu::DataType                                           dataType,
376                                                                         const tcu::Vec4&                                        reference,
377                                                                         const tcu::Vec4&                                        threshold,
378                                                                         const tcu::Vec4&                                        scale,
379                                                                         const tcu::Vec4&                                        bias,
380                                                                         VerificationLogging                                     logPolicy = LOG_ALL)
381 {
382         const int                       numComps                = glu::getDataTypeFloatScalars(dataType);
383         const tcu::BVec4        mask                    = tcu::logicalNot(getDerivateMask(dataType));
384         int                                     numFailedPixels = 0;
385
386         if (logPolicy == LOG_ALL)
387                 log << TestLog::Message << "Expecting " << LogVecComps(reference, numComps) << " with threshold " << LogVecComps(threshold, numComps) << TestLog::EndMessage;
388
389         for (int y = 0; y < result.getHeight(); y++)
390         {
391                 for (int x = 0; x < result.getWidth(); x++)
392                 {
393                         const tcu::Vec4         resDerivate             = readDerivate(result, scale, bias, x, y);
394                         const bool                      isOk                    = tcu::allEqual(tcu::logicalOr(tcu::lessThanEqual(tcu::abs(reference - resDerivate), threshold), mask), tcu::BVec4(true));
395
396                         if (!isOk)
397                         {
398                                 if (numFailedPixels < MAX_FAILED_MESSAGES && logPolicy == LOG_ALL)
399                                         log << TestLog::Message << "FAIL: got " << LogVecComps(resDerivate, numComps)
400                                                                                         << ", diff = " << LogVecComps(tcu::abs(reference - resDerivate), numComps)
401                                                                                         << ", at x = " << x << ", y = " << y
402                                                 << TestLog::EndMessage;
403                                 numFailedPixels += 1;
404                                 errorMask.setPixel(tcu::RGBA::red().toVec(), x, y);
405                         }
406                 }
407         }
408
409         if (numFailedPixels >= MAX_FAILED_MESSAGES && logPolicy == LOG_ALL)
410                 log << TestLog::Message << "..." << TestLog::EndMessage;
411
412         if (numFailedPixels > 0 && logPolicy == LOG_ALL)
413                 log << TestLog::Message << "FAIL: found " << numFailedPixels << " failed pixels" << TestLog::EndMessage;
414
415         return numFailedPixels == 0;
416 }
417
418 struct Linear2DFunctionEvaluator
419 {
420         tcu::Matrix<float, 4, 3> matrix;
421
422         //      .-----.
423         //      | s_x |
424         //  M x | s_y |
425         //      | 1.0 |
426         //      '-----'
427         tcu::Vec4 evaluateAt (float screenX, float screenY) const;
428 };
429
430 tcu::Vec4 Linear2DFunctionEvaluator::evaluateAt (float screenX, float screenY) const
431 {
432         const tcu::Vec3 position(screenX, screenY, 1.0f);
433         return matrix * position;
434 }
435
436 static bool reverifyConstantDerivateWithFlushRelaxations (tcu::TestLog&                                                 log,
437                                                                                                                   const tcu::ConstPixelBufferAccess&    result,
438                                                                                                                   const tcu::PixelBufferAccess&                 errorMask,
439                                                                                                                   glu::DataType                                                 dataType,
440                                                                                                                   glu::Precision                                                precision,
441                                                                                                                   const tcu::Vec4&                                              derivScale,
442                                                                                                                   const tcu::Vec4&                                              derivBias,
443                                                                                                                   const tcu::Vec4&                                              surfaceThreshold,
444                                                                                                                   DerivateFunc                                                  derivateFunc,
445                                                                                                                   const Linear2DFunctionEvaluator&              function)
446 {
447         DE_ASSERT(result.getWidth() == errorMask.getWidth());
448         DE_ASSERT(result.getHeight() == errorMask.getHeight());
449         DE_ASSERT(derivateFunc == DERIVATE_DFDX || derivateFunc == DERIVATE_DFDY);
450
451         const tcu::IVec4        red                                             (255, 0, 0, 255);
452         const tcu::IVec4        green                                   (0, 255, 0, 255);
453         const float                     divisionErrorUlps               = 2.5f;
454
455         const int                       numComponents                   = glu::getDataTypeFloatScalars(dataType);
456         const int                       numBits                                 = getNumMantissaBits(precision);
457         const int                       minExponent                             = getMinExponent(precision);
458
459         const int                       numVaryingSampleBits    = numBits - INTERPOLATION_LOST_BITS;
460         int                                     numFailedPixels                 = 0;
461
462         tcu::clear(errorMask, green);
463
464         // search for failed pixels
465         for (int y = 0; y < result.getHeight(); ++y)
466         for (int x = 0; x < result.getWidth(); ++x)
467         {
468                 //                 flushToZero?(f2z?(functionValueCurrent) - f2z?(functionValueBefore))
469                 // flushToZero? ( ------------------------------------------------------------------------ +- 2.5 ULP )
470                 //                                                  dx
471
472                 const tcu::Vec4 resultDerivative                = readDerivate(result, derivScale, derivBias, x, y);
473
474                 // sample at the front of the back pixel and the back of the front pixel to cover the whole area of
475                 // legal sample positions. In general case this is NOT OK, but we know that the target funtion is
476                 // (mostly*) linear which allows us to take the sample points at arbitrary points. This gets us the
477                 // maximum difference possible in exponents which are used in error bound calculations.
478                 // * non-linearity may happen around zero or with very high function values due to subnorms not
479                 //   behaving well.
480                 const tcu::Vec4 functionValueForward    = (derivateFunc == DERIVATE_DFDX)
481                                                                                                         ? (function.evaluateAt((float)x + 2.0f, (float)y + 0.5f))
482                                                                                                         : (function.evaluateAt((float)x + 0.5f, (float)y + 2.0f));
483                 const tcu::Vec4 functionValueBackward   = (derivateFunc == DERIVATE_DFDX)
484                                                                                                         ? (function.evaluateAt((float)x - 1.0f, (float)y + 0.5f))
485                                                                                                         : (function.evaluateAt((float)x + 0.5f, (float)y - 1.0f));
486
487                 bool    anyComponentFailed                              = false;
488
489                 // check components separately
490                 for (int c = 0; c < numComponents; ++c)
491                 {
492                         // Simulate interpolation. Add allowed interpolation error and round to target precision. Allow one half ULP (i.e. correct rounding)
493                         const tcu::Interval     forwardComponent                (convertFloatFlushToZeroRtn(addErrorUlp((float)functionValueForward[c],  -0.5f, numVaryingSampleBits), minExponent, numBits),
494                                                                                                                  convertFloatFlushToZeroRtp(addErrorUlp((float)functionValueForward[c],  +0.5f, numVaryingSampleBits), minExponent, numBits));
495                         const tcu::Interval     backwardComponent               (convertFloatFlushToZeroRtn(addErrorUlp((float)functionValueBackward[c], -0.5f, numVaryingSampleBits), minExponent, numBits),
496                                                                                                                  convertFloatFlushToZeroRtp(addErrorUlp((float)functionValueBackward[c], +0.5f, numVaryingSampleBits), minExponent, numBits));
497                         const int                       maxValueExp                             = de::max(de::max(tcu::Float32(forwardComponent.lo()).exponent(),   tcu::Float32(forwardComponent.hi()).exponent()),
498                                                                                                                                   de::max(tcu::Float32(backwardComponent.lo()).exponent(),  tcu::Float32(backwardComponent.hi()).exponent()));
499
500                         // subtraction in numerator will likely cause a cancellation of the most
501                         // significant bits. Apply error bounds.
502
503                         const tcu::Interval     numerator                               (forwardComponent - backwardComponent);
504                         const int                       numeratorLoExp                  = tcu::Float32(numerator.lo()).exponent();
505                         const int                       numeratorHiExp                  = tcu::Float32(numerator.hi()).exponent();
506                         const int                       numeratorLoBitsLost             = de::max(0, maxValueExp - numeratorLoExp); //!< must clamp to zero since if forward and backward components have different
507                         const int                       numeratorHiBitsLost             = de::max(0, maxValueExp - numeratorHiExp); //!< sign, numerator might have larger exponent than its operands.
508                         const int                       numeratorLoBits                 = de::max(0, numBits - numeratorLoBitsLost);
509                         const int                       numeratorHiBits                 = de::max(0, numBits - numeratorHiBitsLost);
510
511                         const tcu::Interval     numeratorRange                  (convertFloatFlushToZeroRtn((float)numerator.lo(), minExponent, numeratorLoBits),
512                                                                                                                  convertFloatFlushToZeroRtp((float)numerator.hi(), minExponent, numeratorHiBits));
513
514                         const tcu::Interval     divisionRange                   = numeratorRange / 3.0f; // legal sample area is anywhere within this and neighboring pixels (i.e. size = 3)
515                         const tcu::Interval     divisionResultRange             (convertFloatFlushToZeroRtn(addErrorUlp((float)divisionRange.lo(), -divisionErrorUlps, numBits), minExponent, numBits),
516                                                                                                                  convertFloatFlushToZeroRtp(addErrorUlp((float)divisionRange.hi(), +divisionErrorUlps, numBits), minExponent, numBits));
517                         const tcu::Interval     finalResultRange                (divisionResultRange.lo() - surfaceThreshold[c], divisionResultRange.hi() + surfaceThreshold[c]);
518
519                         if (resultDerivative[c] >= finalResultRange.lo() && resultDerivative[c] <= finalResultRange.hi())
520                         {
521                                 // value ok
522                         }
523                         else
524                         {
525                                 if (numFailedPixels < MAX_FAILED_MESSAGES)
526                                         log << tcu::TestLog::Message
527                                                 << "Error in pixel at " << x << ", " << y << " with component " << c << " (channel " << ("rgba"[c]) << ")\n"
528                                                 << "\tGot pixel value " << result.getPixelInt(x, y) << "\n"
529                                                 << "\t\tdFd" << ((derivateFunc == DERIVATE_DFDX) ? ('x') : ('y')) << " ~= " << resultDerivative[c] << "\n"
530                                                 << "\t\tdifference to a valid range: "
531                                                         << ((resultDerivative[c] < finalResultRange.lo()) ? ("-") : ("+"))
532                                                         << ((resultDerivative[c] < finalResultRange.lo()) ? (finalResultRange.lo() - resultDerivative[c]) : (resultDerivative[c] - finalResultRange.hi()))
533                                                         << "\n"
534                                                 << "\tDerivative value range:\n"
535                                                 << "\t\tMin: " << finalResultRange.lo() << "\n"
536                                                 << "\t\tMax: " << finalResultRange.hi() << "\n"
537                                                 << tcu::TestLog::EndMessage;
538
539                                 ++numFailedPixels;
540                                 anyComponentFailed = true;
541                         }
542                 }
543
544                 if (anyComponentFailed)
545                         errorMask.setPixel(red, x, y);
546         }
547
548         if (numFailedPixels >= MAX_FAILED_MESSAGES)
549                 log << TestLog::Message << "..." << TestLog::EndMessage;
550
551         if (numFailedPixels > 0)
552                 log << TestLog::Message << "FAIL: found " << numFailedPixels << " failed pixels" << TestLog::EndMessage;
553
554         return numFailedPixels == 0;
555 }
556
557 // TriangleDerivateCase
558
559 class TriangleDerivateCase : public TestCase
560 {
561 public:
562                                                 TriangleDerivateCase    (Context& context, const char* name, const char* description);
563                                                 ~TriangleDerivateCase   (void);
564
565         IterateResult           iterate                                 (void);
566
567 protected:
568         virtual void            setupRenderState                (deUint32 program) { DE_UNREF(program); }
569         virtual bool            verify                                  (const tcu::ConstPixelBufferAccess& result, const tcu::PixelBufferAccess& errorMask) = DE_NULL;
570
571         tcu::IVec2                      getViewportSize                 (void) const;
572         tcu::Vec4                       getSurfaceThreshold             (void) const;
573
574         glu::DataType           m_dataType;
575         glu::Precision          m_precision;
576
577         glu::DataType           m_coordDataType;
578         glu::Precision          m_coordPrecision;
579
580         std::string                     m_fragmentSrc;
581
582         tcu::Vec4                       m_coordMin;
583         tcu::Vec4                       m_coordMax;
584         tcu::Vec4                       m_derivScale;
585         tcu::Vec4                       m_derivBias;
586
587         SurfaceType                     m_surfaceType;
588         int                                     m_numSamples;
589         deUint32                        m_hint;
590 };
591
592 TriangleDerivateCase::TriangleDerivateCase (Context& context, const char* name, const char* description)
593         : TestCase                      (context, name, description)
594         , m_dataType            (glu::TYPE_LAST)
595         , m_precision           (glu::PRECISION_LAST)
596         , m_coordDataType       (glu::TYPE_LAST)
597         , m_coordPrecision      (glu::PRECISION_LAST)
598         , m_surfaceType         (SURFACETYPE_DEFAULT_FRAMEBUFFER)
599         , m_numSamples          (0)
600         , m_hint                        (GL_DONT_CARE)
601 {
602         DE_ASSERT(m_surfaceType != SURFACETYPE_DEFAULT_FRAMEBUFFER || m_numSamples == 0);
603 }
604
605 TriangleDerivateCase::~TriangleDerivateCase (void)
606 {
607         TriangleDerivateCase::deinit();
608 }
609
610 static std::string genVertexSource (glu::DataType coordType, glu::Precision precision)
611 {
612         DE_ASSERT(glu::isDataTypeFloatOrVec(coordType));
613
614         const char* vertexTmpl =
615                 "#version 300 es\n"
616                 "in highp vec4 a_position;\n"
617                 "in ${PRECISION} ${DATATYPE} a_coord;\n"
618                 "out ${PRECISION} ${DATATYPE} v_coord;\n"
619                 "void main (void)\n"
620                 "{\n"
621                 "       gl_Position = a_position;\n"
622                 "       v_coord = a_coord;\n"
623                 "}\n";
624
625         map<string, string> vertexParams;
626
627         vertexParams["PRECISION"]       = glu::getPrecisionName(precision);
628         vertexParams["DATATYPE"]        = glu::getDataTypeName(coordType);
629
630         return tcu::StringTemplate(vertexTmpl).specialize(vertexParams);
631 }
632
633 inline tcu::IVec2 TriangleDerivateCase::getViewportSize (void) const
634 {
635         if (m_surfaceType == SURFACETYPE_DEFAULT_FRAMEBUFFER)
636         {
637                 const int       width   = de::min<int>(m_context.getRenderTarget().getWidth(),  VIEWPORT_WIDTH);
638                 const int       height  = de::min<int>(m_context.getRenderTarget().getHeight(), VIEWPORT_HEIGHT);
639                 return tcu::IVec2(width, height);
640         }
641         else
642                 return tcu::IVec2(FBO_WIDTH, FBO_HEIGHT);
643 }
644
645 TriangleDerivateCase::IterateResult TriangleDerivateCase::iterate (void)
646 {
647         const glw::Functions&           gl                              = m_context.getRenderContext().getFunctions();
648         const glu::ShaderProgram        program                 (m_context.getRenderContext(), glu::makeVtxFragSources(genVertexSource(m_coordDataType, m_coordPrecision), m_fragmentSrc));
649         de::Random                                      rnd                             (deStringHash(getName()) ^ 0xbbc24);
650         const bool                                      useFbo                  = m_surfaceType != SURFACETYPE_DEFAULT_FRAMEBUFFER;
651         const deUint32                          fboFormat               = m_surfaceType == SURFACETYPE_FLOAT_FBO ? GL_RGBA32UI : GL_RGBA8;
652         const tcu::IVec2                        viewportSize    = getViewportSize();
653         const int                                       viewportX               = useFbo ? 0 : rnd.getInt(0, m_context.getRenderTarget().getWidth()             - viewportSize.x());
654         const int                                       viewportY               = useFbo ? 0 : rnd.getInt(0, m_context.getRenderTarget().getHeight()    - viewportSize.y());
655         AutoFbo                                         fbo                             (gl);
656         AutoRbo                                         rbo                             (gl);
657         tcu::TextureLevel                       result;
658
659         m_testCtx.getLog() << program;
660
661         if (!program.isOk())
662                 TCU_FAIL("Compile failed");
663
664         if (useFbo)
665         {
666                 m_testCtx.getLog() << TestLog::Message
667                                                    << "Rendering to FBO, format = " << glu::getTextureFormatStr(fboFormat)
668                                                    << ", samples = " << m_numSamples
669                                                    << TestLog::EndMessage;
670
671                 fbo.gen();
672                 rbo.gen();
673
674                 gl.bindRenderbuffer(GL_RENDERBUFFER, *rbo);
675                 gl.renderbufferStorageMultisample(GL_RENDERBUFFER, m_numSamples, fboFormat, viewportSize.x(), viewportSize.y());
676                 gl.bindFramebuffer(GL_FRAMEBUFFER, *fbo);
677                 gl.framebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, *rbo);
678                 TCU_CHECK(gl.checkFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
679         }
680         else
681         {
682                 const tcu::PixelFormat pixelFormat = m_context.getRenderTarget().getPixelFormat();
683
684                 m_testCtx.getLog()
685                         << TestLog::Message
686                         << "Rendering to default framebuffer\n"
687                         << "\tColor depth: R=" << pixelFormat.redBits << ", G=" << pixelFormat.greenBits << ", B=" << pixelFormat.blueBits << ", A=" << pixelFormat.alphaBits
688                         << TestLog::EndMessage;
689         }
690
691         m_testCtx.getLog() << TestLog::Message << "in: " << m_coordMin << " -> " << m_coordMax << "\n"
692                                                                                    << "v_coord.x = in.x * x\n"
693                                                                                    << "v_coord.y = in.y * y\n"
694                                                                                    << "v_coord.z = in.z * (x+y)/2\n"
695                                                                                    << "v_coord.w = in.w * (1 - (x+y)/2)\n"
696                                            << TestLog::EndMessage
697                                            << TestLog::Message << "u_scale: " << m_derivScale << ", u_bias: " << m_derivBias << " (displayed values have scale/bias removed)" << TestLog::EndMessage
698                                            << TestLog::Message << "Viewport: " << viewportSize.x() << "x" << viewportSize.y() << TestLog::EndMessage
699                                            << TestLog::Message << "GL_FRAGMENT_SHADER_DERIVATE_HINT: " << glu::getHintModeStr(m_hint) << TestLog::EndMessage;
700
701         // Draw
702         {
703                 const float positions[] =
704                 {
705                         -1.0f, -1.0f, 0.0f, 1.0f,
706                         -1.0f,  1.0f, 0.0f, 1.0f,
707                          1.0f, -1.0f, 0.0f, 1.0f,
708                          1.0f,  1.0f, 0.0f, 1.0f
709                 };
710                 const float coords[] =
711                 {
712                         m_coordMin.x(), m_coordMin.y(), m_coordMin.z(),                                                 m_coordMax.w(),
713                         m_coordMin.x(), m_coordMax.y(), (m_coordMin.z()+m_coordMax.z())*0.5f,   (m_coordMin.w()+m_coordMax.w())*0.5f,
714                         m_coordMax.x(), m_coordMin.y(), (m_coordMin.z()+m_coordMax.z())*0.5f,   (m_coordMin.w()+m_coordMax.w())*0.5f,
715                         m_coordMax.x(), m_coordMax.y(), m_coordMax.z(),                                                 m_coordMin.w()
716                 };
717                 const glu::VertexArrayBinding vertexArrays[] =
718                 {
719                         glu::va::Float("a_position",    4, 4, 0, &positions[0]),
720                         glu::va::Float("a_coord",               4, 4, 0, &coords[0])
721                 };
722                 const deUint16 indices[] = { 0, 2, 1, 2, 3, 1 };
723
724                 gl.clearColor(0.125f, 0.25f, 0.5f, 1.0f);
725                 gl.clear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT);
726                 gl.disable(GL_DITHER);
727
728                 gl.useProgram(program.getProgram());
729
730                 {
731                         const int       scaleLoc        = gl.getUniformLocation(program.getProgram(), "u_scale");
732                         const int       biasLoc         = gl.getUniformLocation(program.getProgram(), "u_bias");
733
734                         switch (m_dataType)
735                         {
736                                 case glu::TYPE_FLOAT:
737                                         gl.uniform1f(scaleLoc, m_derivScale.x());
738                                         gl.uniform1f(biasLoc, m_derivBias.x());
739                                         break;
740
741                                 case glu::TYPE_FLOAT_VEC2:
742                                         gl.uniform2fv(scaleLoc, 1, m_derivScale.getPtr());
743                                         gl.uniform2fv(biasLoc, 1, m_derivBias.getPtr());
744                                         break;
745
746                                 case glu::TYPE_FLOAT_VEC3:
747                                         gl.uniform3fv(scaleLoc, 1, m_derivScale.getPtr());
748                                         gl.uniform3fv(biasLoc, 1, m_derivBias.getPtr());
749                                         break;
750
751                                 case glu::TYPE_FLOAT_VEC4:
752                                         gl.uniform4fv(scaleLoc, 1, m_derivScale.getPtr());
753                                         gl.uniform4fv(biasLoc, 1, m_derivBias.getPtr());
754                                         break;
755
756                                 default:
757                                         DE_ASSERT(false);
758                         }
759                 }
760
761                 gls::setupDefaultUniforms(m_context.getRenderContext(), program.getProgram());
762                 setupRenderState(program.getProgram());
763
764                 gl.hint(GL_FRAGMENT_SHADER_DERIVATIVE_HINT, m_hint);
765                 GLU_EXPECT_NO_ERROR(gl.getError(), "Setup program state");
766
767                 gl.viewport(viewportX, viewportY, viewportSize.x(), viewportSize.y());
768                 glu::draw(m_context.getRenderContext(), program.getProgram(), DE_LENGTH_OF_ARRAY(vertexArrays), &vertexArrays[0],
769                                   glu::pr::Triangles(DE_LENGTH_OF_ARRAY(indices), &indices[0]));
770                 GLU_EXPECT_NO_ERROR(gl.getError(), "Draw");
771         }
772
773         // Read back results
774         {
775                 const bool              isMSAA          = useFbo && m_numSamples > 0;
776                 AutoFbo                 resFbo          (gl);
777                 AutoRbo                 resRbo          (gl);
778
779                 // Resolve if necessary
780                 if (isMSAA)
781                 {
782                         resFbo.gen();
783                         resRbo.gen();
784
785                         gl.bindRenderbuffer(GL_RENDERBUFFER, *resRbo);
786                         gl.renderbufferStorageMultisample(GL_RENDERBUFFER, 0, fboFormat, viewportSize.x(), viewportSize.y());
787                         gl.bindFramebuffer(GL_DRAW_FRAMEBUFFER, *resFbo);
788                         gl.framebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, *resRbo);
789                         TCU_CHECK(gl.checkFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
790
791                         gl.blitFramebuffer(0, 0, viewportSize.x(), viewportSize.y(), 0, 0, viewportSize.x(), viewportSize.y(), GL_COLOR_BUFFER_BIT, GL_NEAREST);
792                         GLU_EXPECT_NO_ERROR(gl.getError(), "Resolve blit");
793
794                         gl.bindFramebuffer(GL_READ_FRAMEBUFFER, *resFbo);
795                 }
796
797                 switch (m_surfaceType)
798                 {
799                         case SURFACETYPE_DEFAULT_FRAMEBUFFER:
800                         case SURFACETYPE_UNORM_FBO:
801                                 result.setStorage(tcu::TextureFormat(tcu::TextureFormat::RGBA, tcu::TextureFormat::UNORM_INT8), viewportSize.x(), viewportSize.y());
802                                 glu::readPixels(m_context.getRenderContext(), viewportX, viewportY, result);
803                                 break;
804
805                         case SURFACETYPE_FLOAT_FBO:
806                         {
807                                 const tcu::TextureFormat        dataFormat              (tcu::TextureFormat::RGBA, tcu::TextureFormat::FLOAT);
808                                 const tcu::TextureFormat        transferFormat  (tcu::TextureFormat::RGBA, tcu::TextureFormat::UNSIGNED_INT32);
809
810                                 result.setStorage(dataFormat, viewportSize.x(), viewportSize.y());
811                                 glu::readPixels(m_context.getRenderContext(), viewportX, viewportY,
812                                                                 tcu::PixelBufferAccess(transferFormat, result.getWidth(), result.getHeight(), result.getDepth(), result.getAccess().getDataPtr()));
813                                 break;
814                         }
815
816                         default:
817                                 DE_ASSERT(false);
818                 }
819
820                 GLU_EXPECT_NO_ERROR(gl.getError(), "Read pixels");
821         }
822
823         // Verify
824         {
825                 tcu::Surface errorMask(result.getWidth(), result.getHeight());
826                 tcu::clear(errorMask.getAccess(), tcu::RGBA::green().toVec());
827
828                 const bool isOk = verify(result.getAccess(), errorMask.getAccess());
829
830                 m_testCtx.getLog() << TestLog::ImageSet("Result", "Result images")
831                                                    << TestLog::Image("Rendered", "Rendered image", result);
832
833                 if (!isOk)
834                         m_testCtx.getLog() << TestLog::Image("ErrorMask", "Error mask", errorMask);
835
836                 m_testCtx.getLog() << TestLog::EndImageSet;
837
838                 m_testCtx.setTestResult(isOk ? QP_TEST_RESULT_PASS      : QP_TEST_RESULT_FAIL,
839                                                                 isOk ? "Pass"                           : "Image comparison failed");
840         }
841
842         return STOP;
843 }
844
845 tcu::Vec4 TriangleDerivateCase::getSurfaceThreshold (void) const
846 {
847         switch (m_surfaceType)
848         {
849                 case SURFACETYPE_DEFAULT_FRAMEBUFFER:
850                 {
851                         const tcu::PixelFormat  pixelFormat             = m_context.getRenderTarget().getPixelFormat();
852                         const tcu::IVec4                channelBits             (pixelFormat.redBits, pixelFormat.greenBits, pixelFormat.blueBits, pixelFormat.alphaBits);
853                         const tcu::IVec4                intThreshold    = tcu::IVec4(1) << (8 - channelBits);
854                         const tcu::Vec4                 normThreshold   = intThreshold.asFloat() / 255.0f;
855
856                         return normThreshold;
857                 }
858
859                 case SURFACETYPE_UNORM_FBO:                             return tcu::IVec4(1).asFloat() / 255.0f;
860                 case SURFACETYPE_FLOAT_FBO:                             return tcu::Vec4(0.0f);
861                 default:
862                         DE_ASSERT(false);
863                         return tcu::Vec4(0.0f);
864         }
865 }
866
867 // ConstantDerivateCase
868
869 class ConstantDerivateCase : public TriangleDerivateCase
870 {
871 public:
872                                                 ConstantDerivateCase            (Context& context, const char* name, const char* description, DerivateFunc func, glu::DataType type);
873                                                 ~ConstantDerivateCase           (void) {}
874
875         void                            init                                            (void);
876
877 protected:
878         bool                            verify                                          (const tcu::ConstPixelBufferAccess& result, const tcu::PixelBufferAccess& errorMask);
879
880 private:
881         DerivateFunc            m_func;
882 };
883
884 ConstantDerivateCase::ConstantDerivateCase (Context& context, const char* name, const char* description, DerivateFunc func, glu::DataType type)
885         : TriangleDerivateCase  (context, name, description)
886         , m_func                                (func)
887 {
888         m_dataType                      = type;
889         m_precision                     = glu::PRECISION_HIGHP;
890         m_coordDataType         = m_dataType;
891         m_coordPrecision        = m_precision;
892 }
893
894 void ConstantDerivateCase::init (void)
895 {
896         const char* fragmentTmpl =
897                 "#version 300 es\n"
898                 "layout(location = 0) out mediump vec4 o_color;\n"
899                 "uniform ${PRECISION} ${DATATYPE} u_scale;\n"
900                 "uniform ${PRECISION} ${DATATYPE} u_bias;\n"
901                 "void main (void)\n"
902                 "{\n"
903                 "       ${PRECISION} ${DATATYPE} res = ${FUNC}(${VALUE}) * u_scale + u_bias;\n"
904                 "       o_color = ${CAST_TO_OUTPUT};\n"
905                 "}\n";
906         map<string, string> fragmentParams;
907         fragmentParams["PRECISION"]                     = glu::getPrecisionName(m_precision);
908         fragmentParams["DATATYPE"]                      = glu::getDataTypeName(m_dataType);
909         fragmentParams["FUNC"]                          = getDerivateFuncName(m_func);
910         fragmentParams["VALUE"]                         = m_dataType == glu::TYPE_FLOAT_VEC4 ? "vec4(1.0, 7.2, -1e5, 0.0)" :
911                                                                                   m_dataType == glu::TYPE_FLOAT_VEC3 ? "vec3(1e2, 8.0, 0.01)" :
912                                                                                   m_dataType == glu::TYPE_FLOAT_VEC2 ? "vec2(-0.0, 2.7)" :
913                                                                                   /* TYPE_FLOAT */                                         "7.7";
914         fragmentParams["CAST_TO_OUTPUT"]        = m_dataType == glu::TYPE_FLOAT_VEC4 ? "res" :
915                                                                                   m_dataType == glu::TYPE_FLOAT_VEC3 ? "vec4(res, 1.0)" :
916                                                                                   m_dataType == glu::TYPE_FLOAT_VEC2 ? "vec4(res, 0.0, 1.0)" :
917                                                                                   /* TYPE_FLOAT */                                         "vec4(res, 0.0, 0.0, 1.0)";
918
919         m_fragmentSrc = tcu::StringTemplate(fragmentTmpl).specialize(fragmentParams);
920
921         m_derivScale    = tcu::Vec4(1e3f, 1e3f, 1e3f, 1e3f);
922         m_derivBias             = tcu::Vec4(0.5f, 0.5f, 0.5f, 0.5f);
923 }
924
925 bool ConstantDerivateCase::verify (const tcu::ConstPixelBufferAccess& result, const tcu::PixelBufferAccess& errorMask)
926 {
927         const tcu::Vec4 reference       (0.0f); // Derivate of constant argument should always be 0
928         const tcu::Vec4 threshold       = getSurfaceThreshold() / abs(m_derivScale);
929
930         return verifyConstantDerivate(m_testCtx.getLog(), result, errorMask, m_dataType,
931                                                                   reference, threshold, m_derivScale, m_derivBias);
932 }
933
934 // LinearDerivateCase
935
936 class LinearDerivateCase : public TriangleDerivateCase
937 {
938 public:
939                                                 LinearDerivateCase              (Context& context, const char* name, const char* description, DerivateFunc func, glu::DataType type, glu::Precision precision, deUint32 hint, SurfaceType surfaceType, int numSamples, const char* fragmentSrcTmpl);
940                                                 ~LinearDerivateCase             (void) {}
941
942         void                            init                                    (void);
943
944 protected:
945         bool                            verify                                  (const tcu::ConstPixelBufferAccess& result, const tcu::PixelBufferAccess& errorMask);
946
947 private:
948         DerivateFunc            m_func;
949         std::string                     m_fragmentTmpl;
950 };
951
952 LinearDerivateCase::LinearDerivateCase (Context& context, const char* name, const char* description, DerivateFunc func, glu::DataType type, glu::Precision precision, deUint32 hint, SurfaceType surfaceType, int numSamples, const char* fragmentSrcTmpl)
953         : TriangleDerivateCase  (context, name, description)
954         , m_func                                (func)
955         , m_fragmentTmpl                (fragmentSrcTmpl)
956 {
957         m_dataType                      = type;
958         m_precision                     = precision;
959         m_coordDataType         = m_dataType;
960         m_coordPrecision        = m_precision;
961         m_hint                          = hint;
962         m_surfaceType           = surfaceType;
963         m_numSamples            = numSamples;
964 }
965
966 void LinearDerivateCase::init (void)
967 {
968         const tcu::IVec2        viewportSize    = getViewportSize();
969         const float                     w                               = float(viewportSize.x());
970         const float                     h                               = float(viewportSize.y());
971         const bool                      packToInt               = m_surfaceType == SURFACETYPE_FLOAT_FBO;
972         map<string, string>     fragmentParams;
973
974         fragmentParams["OUTPUT_TYPE"]           = glu::getDataTypeName(packToInt ? glu::TYPE_UINT_VEC4 : glu::TYPE_FLOAT_VEC4);
975         fragmentParams["OUTPUT_PREC"]           = glu::getPrecisionName(packToInt ? glu::PRECISION_HIGHP : m_precision);
976         fragmentParams["PRECISION"]                     = glu::getPrecisionName(m_precision);
977         fragmentParams["DATATYPE"]                      = glu::getDataTypeName(m_dataType);
978         fragmentParams["FUNC"]                          = getDerivateFuncName(m_func);
979
980         if (packToInt)
981         {
982                 fragmentParams["CAST_TO_OUTPUT"]        = m_dataType == glu::TYPE_FLOAT_VEC4 ? "floatBitsToUint(res)" :
983                                                                                           m_dataType == glu::TYPE_FLOAT_VEC3 ? "floatBitsToUint(vec4(res, 1.0))" :
984                                                                                           m_dataType == glu::TYPE_FLOAT_VEC2 ? "floatBitsToUint(vec4(res, 0.0, 1.0))" :
985                                                                                           /* TYPE_FLOAT */                                         "floatBitsToUint(vec4(res, 0.0, 0.0, 1.0))";
986         }
987         else
988         {
989                 fragmentParams["CAST_TO_OUTPUT"]        = m_dataType == glu::TYPE_FLOAT_VEC4 ? "res" :
990                                                                                           m_dataType == glu::TYPE_FLOAT_VEC3 ? "vec4(res, 1.0)" :
991                                                                                           m_dataType == glu::TYPE_FLOAT_VEC2 ? "vec4(res, 0.0, 1.0)" :
992                                                                                           /* TYPE_FLOAT */                                         "vec4(res, 0.0, 0.0, 1.0)";
993         }
994
995         m_fragmentSrc = tcu::StringTemplate(m_fragmentTmpl.c_str()).specialize(fragmentParams);
996
997         switch (m_precision)
998         {
999                 case glu::PRECISION_HIGHP:
1000                         m_coordMin = tcu::Vec4(-97.f, 0.2f, 71.f, 74.f);
1001                         m_coordMax = tcu::Vec4(-13.2f, -77.f, 44.f, 76.f);
1002                         break;
1003
1004                 case glu::PRECISION_MEDIUMP:
1005                         m_coordMin = tcu::Vec4(-37.0f, 47.f, -7.f, 0.0f);
1006                         m_coordMax = tcu::Vec4(-1.0f, 12.f, 7.f, 19.f);
1007                         break;
1008
1009                 case glu::PRECISION_LOWP:
1010                         m_coordMin = tcu::Vec4(0.0f, -1.0f, 0.0f, 1.0f);
1011                         m_coordMax = tcu::Vec4(1.0f, 1.0f, -1.0f, -1.0f);
1012                         break;
1013
1014                 default:
1015                         DE_ASSERT(false);
1016         }
1017
1018         if (m_surfaceType == SURFACETYPE_FLOAT_FBO)
1019         {
1020                 // No scale or bias used for accuracy.
1021                 m_derivScale    = tcu::Vec4(1.0f);
1022                 m_derivBias             = tcu::Vec4(0.0f);
1023         }
1024         else
1025         {
1026                 // Compute scale - bias that normalizes to 0..1 range.
1027                 const tcu::Vec4 dx = (m_coordMax - m_coordMin) / tcu::Vec4(w, w, w*0.5f, -w*0.5f);
1028                 const tcu::Vec4 dy = (m_coordMax - m_coordMin) / tcu::Vec4(h, h, h*0.5f, -h*0.5f);
1029
1030                 switch (m_func)
1031                 {
1032                         case DERIVATE_DFDX:
1033                                 m_derivScale = 0.5f / dx;
1034                                 break;
1035
1036                         case DERIVATE_DFDY:
1037                                 m_derivScale = 0.5f / dy;
1038                                 break;
1039
1040                         case DERIVATE_FWIDTH:
1041                                 m_derivScale = 0.5f / (tcu::abs(dx) + tcu::abs(dy));
1042                                 break;
1043
1044                         default:
1045                                 DE_ASSERT(false);
1046                 }
1047
1048                 m_derivBias = tcu::Vec4(0.0f, 0.0f, 0.0f, 0.0f);
1049         }
1050 }
1051
1052 bool LinearDerivateCase::verify (const tcu::ConstPixelBufferAccess& result, const tcu::PixelBufferAccess& errorMask)
1053 {
1054         const tcu::Vec4         xScale                          = tcu::Vec4(1.0f, 0.0f, 0.5f, -0.5f);
1055         const tcu::Vec4         yScale                          = tcu::Vec4(0.0f, 1.0f, 0.5f, -0.5f);
1056         const tcu::Vec4         surfaceThreshold        = getSurfaceThreshold() / abs(m_derivScale);
1057
1058         if (m_func == DERIVATE_DFDX || m_func == DERIVATE_DFDY)
1059         {
1060                 const bool                      isX                     = m_func == DERIVATE_DFDX;
1061                 const float                     div                     = isX ? float(result.getWidth()) : float(result.getHeight());
1062                 const tcu::Vec4         scale           = isX ? xScale : yScale;
1063                 tcu::Vec4                       reference       = ((m_coordMax - m_coordMin) / div);
1064                 const tcu::Vec4         opThreshold     = getDerivateThreshold(m_precision, m_coordMin, m_coordMax, reference);
1065                 const tcu::Vec4         threshold       = max(surfaceThreshold, opThreshold);
1066                 const int                       numComps        = glu::getDataTypeFloatScalars(m_dataType);
1067
1068                 /* adjust the reference value for the correct dfdx or dfdy sample adjacency */
1069                 reference       = reference * scale;
1070
1071                 m_testCtx.getLog()
1072                         << tcu::TestLog::Message
1073                         << "Verifying result image.\n"
1074                         << "\tValid derivative is " << LogVecComps(reference, numComps) << " with threshold " << LogVecComps(threshold, numComps)
1075                         << tcu::TestLog::EndMessage;
1076
1077                 // short circuit if result is strictly within the normal value error bounds.
1078                 // This improves performance significantly.
1079                 if (verifyConstantDerivate(m_testCtx.getLog(), result, errorMask, m_dataType,
1080                                                                    reference, threshold, m_derivScale, m_derivBias,
1081                                                                    LOG_NOTHING))
1082                 {
1083                         m_testCtx.getLog()
1084                                 << tcu::TestLog::Message
1085                                 << "No incorrect derivatives found, result valid."
1086                                 << tcu::TestLog::EndMessage;
1087
1088                         return true;
1089                 }
1090
1091                 // some pixels exceed error bounds calculated for normal values. Verify that these
1092                 // potentially invalid pixels are in fact valid due to (for example) subnorm flushing.
1093
1094                 m_testCtx.getLog()
1095                         << tcu::TestLog::Message
1096                         << "Initial verification failed, verifying image by calculating accurate error bounds for each result pixel.\n"
1097                         << "\tVerifying each result derivative is within its range of legal result values."
1098                         << tcu::TestLog::EndMessage;
1099
1100                 {
1101                         const tcu::IVec2                        viewportSize    = getViewportSize();
1102                         const float                                     w                               = float(viewportSize.x());
1103                         const float                                     h                               = float(viewportSize.y());
1104                         const tcu::Vec4                         valueRamp               = (m_coordMax - m_coordMin);
1105                         Linear2DFunctionEvaluator       function;
1106
1107                         function.matrix.setRow(0, tcu::Vec3(valueRamp.x() / w, 0.0f, m_coordMin.x()));
1108                         function.matrix.setRow(1, tcu::Vec3(0.0f, valueRamp.y() / h, m_coordMin.y()));
1109                         function.matrix.setRow(2, tcu::Vec3(valueRamp.z() / w, valueRamp.z() / h, m_coordMin.z() + m_coordMin.z()) / 2.0f);
1110                         function.matrix.setRow(3, tcu::Vec3(-valueRamp.w() / w, -valueRamp.w() / h, m_coordMax.w() + m_coordMax.w()) / 2.0f);
1111
1112                         return reverifyConstantDerivateWithFlushRelaxations(m_testCtx.getLog(), result, errorMask,
1113                                                                                                                                 m_dataType, m_precision, m_derivScale,
1114                                                                                                                                 m_derivBias, surfaceThreshold, m_func,
1115                                                                                                                                 function);
1116                 }
1117         }
1118         else
1119         {
1120                 DE_ASSERT(m_func == DERIVATE_FWIDTH);
1121                 const float                     w                       = float(result.getWidth());
1122                 const float                     h                       = float(result.getHeight());
1123
1124                 const tcu::Vec4         dx                      = ((m_coordMax - m_coordMin) / w) * xScale;
1125                 const tcu::Vec4         dy                      = ((m_coordMax - m_coordMin) / h) * yScale;
1126                 const tcu::Vec4         reference       = tcu::abs(dx) + tcu::abs(dy);
1127                 const tcu::Vec4         dxThreshold     = getDerivateThreshold(m_precision, m_coordMin*xScale, m_coordMax*xScale, dx);
1128                 const tcu::Vec4         dyThreshold     = getDerivateThreshold(m_precision, m_coordMin*yScale, m_coordMax*yScale, dy);
1129                 const tcu::Vec4         threshold       = max(surfaceThreshold, max(dxThreshold, dyThreshold));
1130
1131                 return verifyConstantDerivate(m_testCtx.getLog(), result, errorMask, m_dataType,
1132                                                                           reference, threshold, m_derivScale, m_derivBias);
1133         }
1134 }
1135
1136 // TextureDerivateCase
1137
1138 class TextureDerivateCase : public TriangleDerivateCase
1139 {
1140 public:
1141                                                 TextureDerivateCase             (Context& context, const char* name, const char* description, DerivateFunc func, glu::DataType type, glu::Precision precision, deUint32 hint, SurfaceType surfaceType, int numSamples);
1142                                                 ~TextureDerivateCase    (void);
1143
1144         void                            init                                    (void);
1145         void                            deinit                                  (void);
1146
1147 protected:
1148         void                            setupRenderState                (deUint32 program);
1149         bool                            verify                                  (const tcu::ConstPixelBufferAccess& result, const tcu::PixelBufferAccess& errorMask);
1150
1151 private:
1152         DerivateFunc            m_func;
1153
1154         tcu::Vec4                       m_texValueMin;
1155         tcu::Vec4                       m_texValueMax;
1156         glu::Texture2D*         m_texture;
1157 };
1158
1159 TextureDerivateCase::TextureDerivateCase (Context& context, const char* name, const char* description, DerivateFunc func, glu::DataType type, glu::Precision precision, deUint32 hint, SurfaceType surfaceType, int numSamples)
1160         : TriangleDerivateCase  (context, name, description)
1161         , m_func                                (func)
1162         , m_texture                             (DE_NULL)
1163 {
1164         m_dataType                      = type;
1165         m_precision                     = precision;
1166         m_coordDataType         = glu::TYPE_FLOAT_VEC2;
1167         m_coordPrecision        = glu::PRECISION_HIGHP;
1168         m_hint                          = hint;
1169         m_surfaceType           = surfaceType;
1170         m_numSamples            = numSamples;
1171 }
1172
1173 TextureDerivateCase::~TextureDerivateCase (void)
1174 {
1175         delete m_texture;
1176 }
1177
1178 void TextureDerivateCase::init (void)
1179 {
1180         // Generate shader
1181         {
1182                 const char* fragmentTmpl =
1183                         "#version 300 es\n"
1184                         "in highp vec2 v_coord;\n"
1185                         "layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
1186                         "uniform ${PRECISION} sampler2D u_sampler;\n"
1187                         "uniform ${PRECISION} ${DATATYPE} u_scale;\n"
1188                         "uniform ${PRECISION} ${DATATYPE} u_bias;\n"
1189                         "void main (void)\n"
1190                         "{\n"
1191                         "       ${PRECISION} vec4 tex = texture(u_sampler, v_coord);\n"
1192                         "       ${PRECISION} ${DATATYPE} res = ${FUNC}(tex${SWIZZLE}) * u_scale + u_bias;\n"
1193                         "       o_color = ${CAST_TO_OUTPUT};\n"
1194                         "}\n";
1195
1196                 const bool                      packToInt               = m_surfaceType == SURFACETYPE_FLOAT_FBO;
1197                 map<string, string> fragmentParams;
1198
1199                 fragmentParams["OUTPUT_TYPE"]           = glu::getDataTypeName(packToInt ? glu::TYPE_UINT_VEC4 : glu::TYPE_FLOAT_VEC4);
1200                 fragmentParams["OUTPUT_PREC"]           = glu::getPrecisionName(packToInt ? glu::PRECISION_HIGHP : m_precision);
1201                 fragmentParams["PRECISION"]                     = glu::getPrecisionName(m_precision);
1202                 fragmentParams["DATATYPE"]                      = glu::getDataTypeName(m_dataType);
1203                 fragmentParams["FUNC"]                          = getDerivateFuncName(m_func);
1204                 fragmentParams["SWIZZLE"]                       = m_dataType == glu::TYPE_FLOAT_VEC4 ? "" :
1205                                                                                           m_dataType == glu::TYPE_FLOAT_VEC3 ? ".xyz" :
1206                                                                                           m_dataType == glu::TYPE_FLOAT_VEC2 ? ".xy" :
1207                                                                                           /* TYPE_FLOAT */                                         ".x";
1208
1209                 if (packToInt)
1210                 {
1211                         fragmentParams["CAST_TO_OUTPUT"]        = m_dataType == glu::TYPE_FLOAT_VEC4 ? "floatBitsToUint(res)" :
1212                                                                                                   m_dataType == glu::TYPE_FLOAT_VEC3 ? "floatBitsToUint(vec4(res, 1.0))" :
1213                                                                                                   m_dataType == glu::TYPE_FLOAT_VEC2 ? "floatBitsToUint(vec4(res, 0.0, 1.0))" :
1214                                                                                                   /* TYPE_FLOAT */                                         "floatBitsToUint(vec4(res, 0.0, 0.0, 1.0))";
1215                 }
1216                 else
1217                 {
1218                         fragmentParams["CAST_TO_OUTPUT"]        = m_dataType == glu::TYPE_FLOAT_VEC4 ? "res" :
1219                                                                                                   m_dataType == glu::TYPE_FLOAT_VEC3 ? "vec4(res, 1.0)" :
1220                                                                                                   m_dataType == glu::TYPE_FLOAT_VEC2 ? "vec4(res, 0.0, 1.0)" :
1221                                                                                                   /* TYPE_FLOAT */                                         "vec4(res, 0.0, 0.0, 1.0)";
1222                 }
1223
1224                 m_fragmentSrc = tcu::StringTemplate(fragmentTmpl).specialize(fragmentParams);
1225         }
1226
1227         // Texture size matches viewport and nearest sampling is used. Thus texture sampling
1228         // is equal to just interpolating the texture value range.
1229
1230         // Determine value range for texture.
1231
1232         switch (m_precision)
1233         {
1234                 case glu::PRECISION_HIGHP:
1235                         m_texValueMin = tcu::Vec4(-97.f, 0.2f, 71.f, 74.f);
1236                         m_texValueMax = tcu::Vec4(-13.2f, -77.f, 44.f, 76.f);
1237                         break;
1238
1239                 case glu::PRECISION_MEDIUMP:
1240                         m_texValueMin = tcu::Vec4(-37.0f, 47.f, -7.f, 0.0f);
1241                         m_texValueMax = tcu::Vec4(-1.0f, 12.f, 7.f, 19.f);
1242                         break;
1243
1244                 case glu::PRECISION_LOWP:
1245                         m_texValueMin = tcu::Vec4(0.0f, -1.0f, 0.0f, 1.0f);
1246                         m_texValueMax = tcu::Vec4(1.0f, 1.0f, -1.0f, -1.0f);
1247                         break;
1248
1249                 default:
1250                         DE_ASSERT(false);
1251         }
1252
1253         // Lowp and mediump cases use RGBA16F format, while highp uses RGBA32F.
1254         {
1255                 const tcu::IVec2 viewportSize = getViewportSize();
1256                 DE_ASSERT(!m_texture);
1257                 m_texture = new glu::Texture2D(m_context.getRenderContext(), m_precision == glu::PRECISION_HIGHP ? GL_RGBA32F : GL_RGBA16F, viewportSize.x(), viewportSize.y());
1258                 m_texture->getRefTexture().allocLevel(0);
1259         }
1260
1261         // Texture coordinates
1262         m_coordMin = tcu::Vec4(0.0f);
1263         m_coordMax = tcu::Vec4(1.0f);
1264
1265         // Fill with gradients.
1266         {
1267                 const tcu::PixelBufferAccess level0 = m_texture->getRefTexture().getLevel(0);
1268                 for (int y = 0; y < level0.getHeight(); y++)
1269                 {
1270                         for (int x = 0; x < level0.getWidth(); x++)
1271                         {
1272                                 const float             xf              = (float(x)+0.5f) / float(level0.getWidth());
1273                                 const float             yf              = (float(y)+0.5f) / float(level0.getHeight());
1274                                 const tcu::Vec4 s               = tcu::Vec4(xf, yf, (xf+yf)/2.0f, 1.0f - (xf+yf)/2.0f);
1275
1276                                 level0.setPixel(m_texValueMin + (m_texValueMax - m_texValueMin)*s, x, y);
1277                         }
1278                 }
1279         }
1280
1281         m_texture->upload();
1282
1283         if (m_surfaceType == SURFACETYPE_FLOAT_FBO)
1284         {
1285                 // No scale or bias used for accuracy.
1286                 m_derivScale    = tcu::Vec4(1.0f);
1287                 m_derivBias             = tcu::Vec4(0.0f);
1288         }
1289         else
1290         {
1291                 // Compute scale - bias that normalizes to 0..1 range.
1292                 const tcu::IVec2        viewportSize    = getViewportSize();
1293                 const float                     w                               = float(viewportSize.x());
1294                 const float                     h                               = float(viewportSize.y());
1295                 const tcu::Vec4         dx                              = (m_texValueMax - m_texValueMin) / tcu::Vec4(w, w, w*0.5f, -w*0.5f);
1296                 const tcu::Vec4         dy                              = (m_texValueMax - m_texValueMin) / tcu::Vec4(h, h, h*0.5f, -h*0.5f);
1297
1298                 switch (m_func)
1299                 {
1300                         case DERIVATE_DFDX:
1301                                 m_derivScale = 0.5f / dx;
1302                                 break;
1303
1304                         case DERIVATE_DFDY:
1305                                 m_derivScale = 0.5f / dy;
1306                                 break;
1307
1308                         case DERIVATE_FWIDTH:
1309                                 m_derivScale = 0.5f / (tcu::abs(dx) + tcu::abs(dy));
1310                                 break;
1311
1312                         default:
1313                                 DE_ASSERT(false);
1314                 }
1315
1316                 m_derivBias = tcu::Vec4(0.0f, 0.0f, 0.0f, 0.0f);
1317         }
1318 }
1319
1320 void TextureDerivateCase::deinit (void)
1321 {
1322         delete m_texture;
1323         m_texture = DE_NULL;
1324 }
1325
1326 void TextureDerivateCase::setupRenderState (deUint32 program)
1327 {
1328         const glw::Functions&   gl                      = m_context.getRenderContext().getFunctions();
1329         const int                               texUnit         = 1;
1330
1331         gl.activeTexture        (GL_TEXTURE0+texUnit);
1332         gl.bindTexture          (GL_TEXTURE_2D, m_texture->getGLTexture());
1333         gl.texParameteri        (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,  GL_NEAREST);
1334         gl.texParameteri        (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,  GL_NEAREST);
1335         gl.texParameteri        (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,              GL_CLAMP_TO_EDGE);
1336         gl.texParameteri        (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,              GL_CLAMP_TO_EDGE);
1337
1338         gl.uniform1i            (gl.getUniformLocation(program, "u_sampler"), texUnit);
1339 }
1340
1341 bool TextureDerivateCase::verify (const tcu::ConstPixelBufferAccess& result, const tcu::PixelBufferAccess& errorMask)
1342 {
1343         // \note Edges are ignored in comparison
1344         if (result.getWidth() < 2 || result.getHeight() < 2)
1345                 throw tcu::NotSupportedError("Too small viewport");
1346
1347         tcu::ConstPixelBufferAccess     compareArea                     = tcu::getSubregion(result, 1, 1, result.getWidth()-2, result.getHeight()-2);
1348         tcu::PixelBufferAccess          maskArea                        = tcu::getSubregion(errorMask, 1, 1, errorMask.getWidth()-2, errorMask.getHeight()-2);
1349         const tcu::Vec4                         xScale                          = tcu::Vec4(1.0f, 0.0f, 0.5f, -0.5f);
1350         const tcu::Vec4                         yScale                          = tcu::Vec4(0.0f, 1.0f, 0.5f, -0.5f);
1351         const float                                     w                                       = float(result.getWidth());
1352         const float                                     h                                       = float(result.getHeight());
1353
1354         const tcu::Vec4                         surfaceThreshold        = getSurfaceThreshold() / abs(m_derivScale);
1355
1356         if (m_func == DERIVATE_DFDX || m_func == DERIVATE_DFDY)
1357         {
1358                 const bool                      isX                     = m_func == DERIVATE_DFDX;
1359                 const float                     div                     = isX ? w : h;
1360                 const tcu::Vec4         scale           = isX ? xScale : yScale;
1361                 tcu::Vec4                       reference       = ((m_texValueMax - m_texValueMin) / div);
1362                 const tcu::Vec4         opThreshold     = getDerivateThreshold(m_precision, m_texValueMin, m_texValueMax, reference);
1363                 const tcu::Vec4         threshold       = max(surfaceThreshold, opThreshold);
1364                 const int                       numComps        = glu::getDataTypeFloatScalars(m_dataType);
1365
1366                 /* adjust the reference value for the correct dfdx or dfdy sample adjacency */
1367                 reference       = reference * scale;
1368
1369                 m_testCtx.getLog()
1370                         << tcu::TestLog::Message
1371                         << "Verifying result image.\n"
1372                         << "\tValid derivative is " << LogVecComps(reference, numComps) << " with threshold " << LogVecComps(threshold, numComps)
1373                         << tcu::TestLog::EndMessage;
1374
1375                 // short circuit if result is strictly within the normal value error bounds.
1376                 // This improves performance significantly.
1377                 if (verifyConstantDerivate(m_testCtx.getLog(), compareArea, maskArea, m_dataType,
1378                                                                    reference, threshold, m_derivScale, m_derivBias,
1379                                                                    LOG_NOTHING))
1380                 {
1381                         m_testCtx.getLog()
1382                                 << tcu::TestLog::Message
1383                                 << "No incorrect derivatives found, result valid."
1384                                 << tcu::TestLog::EndMessage;
1385
1386                         return true;
1387                 }
1388
1389                 // some pixels exceed error bounds calculated for normal values. Verify that these
1390                 // potentially invalid pixels are in fact valid due to (for example) subnorm flushing.
1391
1392                 m_testCtx.getLog()
1393                         << tcu::TestLog::Message
1394                         << "Initial verification failed, verifying image by calculating accurate error bounds for each result pixel.\n"
1395                         << "\tVerifying each result derivative is within its range of legal result values."
1396                         << tcu::TestLog::EndMessage;
1397
1398                 {
1399                         const tcu::Vec4                         valueRamp               = (m_texValueMax - m_texValueMin);
1400                         Linear2DFunctionEvaluator       function;
1401
1402                         function.matrix.setRow(0, tcu::Vec3(valueRamp.x() / w, 0.0f, m_texValueMin.x()));
1403                         function.matrix.setRow(1, tcu::Vec3(0.0f, valueRamp.y() / h, m_texValueMin.y()));
1404                         function.matrix.setRow(2, tcu::Vec3(valueRamp.z() / w, valueRamp.z() / h, m_texValueMin.z() + m_texValueMin.z()) / 2.0f);
1405                         function.matrix.setRow(3, tcu::Vec3(-valueRamp.w() / w, -valueRamp.w() / h, m_texValueMax.w() + m_texValueMax.w()) / 2.0f);
1406
1407                         return reverifyConstantDerivateWithFlushRelaxations(m_testCtx.getLog(), compareArea, maskArea,
1408                                                                                                                                 m_dataType, m_precision, m_derivScale,
1409                                                                                                                                 m_derivBias, surfaceThreshold, m_func,
1410                                                                                                                                 function);
1411                 }
1412         }
1413         else
1414         {
1415                 DE_ASSERT(m_func == DERIVATE_FWIDTH);
1416                 const tcu::Vec4 dx                      = ((m_texValueMax - m_texValueMin) / w) * xScale;
1417                 const tcu::Vec4 dy                      = ((m_texValueMax - m_texValueMin) / h) * yScale;
1418                 const tcu::Vec4 reference       = tcu::abs(dx) + tcu::abs(dy);
1419                 const tcu::Vec4 dxThreshold     = getDerivateThreshold(m_precision, m_texValueMin*xScale, m_texValueMax*xScale, dx);
1420                 const tcu::Vec4 dyThreshold     = getDerivateThreshold(m_precision, m_texValueMin*yScale, m_texValueMax*yScale, dy);
1421                 const tcu::Vec4 threshold       = max(surfaceThreshold, max(dxThreshold, dyThreshold));
1422
1423                 return verifyConstantDerivate(m_testCtx.getLog(), compareArea, maskArea, m_dataType,
1424                                                                           reference, threshold, m_derivScale, m_derivBias);
1425         }
1426 }
1427
1428 ShaderDerivateTests::ShaderDerivateTests (Context& context)
1429         : TestCaseGroup(context, "derivate", "Derivate Function Tests")
1430 {
1431 }
1432
1433 ShaderDerivateTests::~ShaderDerivateTests (void)
1434 {
1435 }
1436
1437 struct FunctionSpec
1438 {
1439         std::string             name;
1440         DerivateFunc    function;
1441         glu::DataType   dataType;
1442         glu::Precision  precision;
1443
1444         FunctionSpec (const std::string& name_, DerivateFunc function_, glu::DataType dataType_, glu::Precision precision_)
1445                 : name          (name_)
1446                 , function      (function_)
1447                 , dataType      (dataType_)
1448                 , precision     (precision_)
1449         {
1450         }
1451 };
1452
1453 void ShaderDerivateTests::init (void)
1454 {
1455         static const struct
1456         {
1457                 const char*             name;
1458                 const char*             description;
1459                 const char*             source;
1460         } s_linearDerivateCases[] =
1461         {
1462                 {
1463                         "linear",
1464                         "Basic derivate of linearly interpolated argument",
1465
1466                         "#version 300 es\n"
1467                         "in ${PRECISION} ${DATATYPE} v_coord;\n"
1468                         "layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
1469                         "uniform ${PRECISION} ${DATATYPE} u_scale;\n"
1470                         "uniform ${PRECISION} ${DATATYPE} u_bias;\n"
1471                         "void main (void)\n"
1472                         "{\n"
1473                         "       ${PRECISION} ${DATATYPE} res = ${FUNC}(v_coord) * u_scale + u_bias;\n"
1474                         "       o_color = ${CAST_TO_OUTPUT};\n"
1475                         "}\n"
1476                 },
1477                 {
1478                         "in_function",
1479                         "Derivate of linear function argument",
1480
1481                         "#version 300 es\n"
1482                         "in ${PRECISION} ${DATATYPE} v_coord;\n"
1483                         "layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
1484                         "uniform ${PRECISION} ${DATATYPE} u_scale;\n"
1485                         "uniform ${PRECISION} ${DATATYPE} u_bias;\n"
1486                         "\n"
1487                         "${PRECISION} ${DATATYPE} computeRes (${PRECISION} ${DATATYPE} value)\n"
1488                         "{\n"
1489                         "       return ${FUNC}(v_coord) * u_scale + u_bias;\n"
1490                         "}\n"
1491                         "\n"
1492                         "void main (void)\n"
1493                         "{\n"
1494                         "       ${PRECISION} ${DATATYPE} res = computeRes(v_coord);\n"
1495                         "       o_color = ${CAST_TO_OUTPUT};\n"
1496                         "}\n"
1497                 },
1498                 {
1499                         "static_if",
1500                         "Derivate of linearly interpolated value in static if",
1501
1502                         "#version 300 es\n"
1503                         "in ${PRECISION} ${DATATYPE} v_coord;\n"
1504                         "layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
1505                         "uniform ${PRECISION} ${DATATYPE} u_scale;\n"
1506                         "uniform ${PRECISION} ${DATATYPE} u_bias;\n"
1507                         "void main (void)\n"
1508                         "{\n"
1509                         "       ${PRECISION} ${DATATYPE} res;\n"
1510                         "       if (false)\n"
1511                         "               res = ${FUNC}(-v_coord) * u_scale + u_bias;\n"
1512                         "       else\n"
1513                         "               res = ${FUNC}(v_coord) * u_scale + u_bias;\n"
1514                         "       o_color = ${CAST_TO_OUTPUT};\n"
1515                         "}\n"
1516                 },
1517                 {
1518                         "static_loop",
1519                         "Derivate of linearly interpolated value in static loop",
1520
1521                         "#version 300 es\n"
1522                         "in ${PRECISION} ${DATATYPE} v_coord;\n"
1523                         "layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
1524                         "uniform ${PRECISION} ${DATATYPE} u_scale;\n"
1525                         "uniform ${PRECISION} ${DATATYPE} u_bias;\n"
1526                         "void main (void)\n"
1527                         "{\n"
1528                         "       ${PRECISION} ${DATATYPE} res = ${DATATYPE}(0.0);\n"
1529                         "       for (int i = 0; i < 2; i++)\n"
1530                         "               res += ${FUNC}(v_coord * float(i));\n"
1531                         "       res = res * u_scale + u_bias;\n"
1532                         "       o_color = ${CAST_TO_OUTPUT};\n"
1533                         "}\n"
1534                 },
1535                 {
1536                         "static_switch",
1537                         "Derivate of linearly interpolated value in static switch",
1538
1539                         "#version 300 es\n"
1540                         "in ${PRECISION} ${DATATYPE} v_coord;\n"
1541                         "layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
1542                         "uniform ${PRECISION} ${DATATYPE} u_scale;\n"
1543                         "uniform ${PRECISION} ${DATATYPE} u_bias;\n"
1544                         "void main (void)\n"
1545                         "{\n"
1546                         "       ${PRECISION} ${DATATYPE} res;\n"
1547                         "       switch (1)\n"
1548                         "       {\n"
1549                         "               case 0: res = ${FUNC}(-v_coord) * u_scale + u_bias;     break;\n"
1550                         "               case 1: res = ${FUNC}(v_coord) * u_scale + u_bias;      break;\n"
1551                         "       }\n"
1552                         "       o_color = ${CAST_TO_OUTPUT};\n"
1553                         "}\n"
1554                 },
1555                 {
1556                         "uniform_if",
1557                         "Derivate of linearly interpolated value in uniform if",
1558
1559                         "#version 300 es\n"
1560                         "in ${PRECISION} ${DATATYPE} v_coord;\n"
1561                         "layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
1562                         "uniform ${PRECISION} ${DATATYPE} u_scale;\n"
1563                         "uniform ${PRECISION} ${DATATYPE} u_bias;\n"
1564                         "uniform bool ub_true;\n"
1565                         "void main (void)\n"
1566                         "{\n"
1567                         "       ${PRECISION} ${DATATYPE} res;\n"
1568                         "       if (ub_true)"
1569                         "               res = ${FUNC}(v_coord) * u_scale + u_bias;\n"
1570                         "       else\n"
1571                         "               res = ${FUNC}(-v_coord) * u_scale + u_bias;\n"
1572                         "       o_color = ${CAST_TO_OUTPUT};\n"
1573                         "}\n"
1574                 },
1575                 {
1576                         "uniform_loop",
1577                         "Derivate of linearly interpolated value in uniform loop",
1578
1579                         "#version 300 es\n"
1580                         "in ${PRECISION} ${DATATYPE} v_coord;\n"
1581                         "layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
1582                         "uniform ${PRECISION} ${DATATYPE} u_scale;\n"
1583                         "uniform ${PRECISION} ${DATATYPE} u_bias;\n"
1584                         "uniform int ui_two;\n"
1585                         "void main (void)\n"
1586                         "{\n"
1587                         "       ${PRECISION} ${DATATYPE} res = ${DATATYPE}(0.0);\n"
1588                         "       for (int i = 0; i < ui_two; i++)\n"
1589                         "               res += ${FUNC}(v_coord * float(i));\n"
1590                         "       res = res * u_scale + u_bias;\n"
1591                         "       o_color = ${CAST_TO_OUTPUT};\n"
1592                         "}\n"
1593                 },
1594                 {
1595                         "uniform_switch",
1596                         "Derivate of linearly interpolated value in uniform switch",
1597
1598                         "#version 300 es\n"
1599                         "in ${PRECISION} ${DATATYPE} v_coord;\n"
1600                         "layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
1601                         "uniform ${PRECISION} ${DATATYPE} u_scale;\n"
1602                         "uniform ${PRECISION} ${DATATYPE} u_bias;\n"
1603                         "uniform int ui_one;\n"
1604                         "void main (void)\n"
1605                         "{\n"
1606                         "       ${PRECISION} ${DATATYPE} res;\n"
1607                         "       switch (ui_one)\n"
1608                         "       {\n"
1609                         "               case 0: res = ${FUNC}(-v_coord) * u_scale + u_bias;     break;\n"
1610                         "               case 1: res = ${FUNC}(v_coord) * u_scale + u_bias;      break;\n"
1611                         "       }\n"
1612                         "       o_color = ${CAST_TO_OUTPUT};\n"
1613                         "}\n"
1614                 },
1615         };
1616
1617         static const struct
1618         {
1619                 const char*             name;
1620                 SurfaceType             surfaceType;
1621                 int                             numSamples;
1622         } s_fboConfigs[] =
1623         {
1624                 { "fbo",                SURFACETYPE_DEFAULT_FRAMEBUFFER,        0 },
1625                 { "fbo_msaa2",  SURFACETYPE_UNORM_FBO,                          2 },
1626                 { "fbo_msaa4",  SURFACETYPE_UNORM_FBO,                          4 },
1627                 { "fbo_float",  SURFACETYPE_FLOAT_FBO,                          0 },
1628         };
1629
1630         static const struct
1631         {
1632                 const char*             name;
1633                 deUint32                hint;
1634         } s_hints[] =
1635         {
1636                 { "fastest",    GL_FASTEST      },
1637                 { "nicest",             GL_NICEST       },
1638         };
1639
1640         static const struct
1641         {
1642                 const char*             name;
1643                 SurfaceType             surfaceType;
1644                 int                             numSamples;
1645         } s_hintFboConfigs[] =
1646         {
1647                 { "default",            SURFACETYPE_DEFAULT_FRAMEBUFFER,        0 },
1648                 { "fbo_msaa4",          SURFACETYPE_UNORM_FBO,                          4 },
1649                 { "fbo_float",          SURFACETYPE_FLOAT_FBO,                          0 }
1650         };
1651
1652         static const struct
1653         {
1654                 const char*             name;
1655                 SurfaceType             surfaceType;
1656                 int                             numSamples;
1657                 deUint32                hint;
1658         } s_textureConfigs[] =
1659         {
1660                 { "basic",                      SURFACETYPE_DEFAULT_FRAMEBUFFER,        0,      GL_DONT_CARE    },
1661                 { "msaa4",                      SURFACETYPE_UNORM_FBO,                          4,      GL_DONT_CARE    },
1662                 { "float_fastest",      SURFACETYPE_FLOAT_FBO,                          0,      GL_FASTEST              },
1663                 { "float_nicest",       SURFACETYPE_FLOAT_FBO,                          0,      GL_NICEST               },
1664         };
1665
1666         // .dfdx, .dfdy, .fwidth
1667         for (int funcNdx = 0; funcNdx < DERIVATE_LAST; funcNdx++)
1668         {
1669                 const DerivateFunc                      function                = DerivateFunc(funcNdx);
1670                 tcu::TestCaseGroup* const       functionGroup   = new tcu::TestCaseGroup(m_testCtx, getDerivateFuncCaseName(function), getDerivateFuncName(function));
1671                 addChild(functionGroup);
1672
1673                 // .constant - no precision variants, checks that derivate of constant arguments is 0
1674                 {
1675                         tcu::TestCaseGroup* const constantGroup = new tcu::TestCaseGroup(m_testCtx, "constant", "Derivate of constant argument");
1676                         functionGroup->addChild(constantGroup);
1677
1678                         for (int vecSize = 1; vecSize <= 4; vecSize++)
1679                         {
1680                                 const glu::DataType dataType = vecSize > 1 ? glu::getDataTypeFloatVec(vecSize) : glu::TYPE_FLOAT;
1681                                 constantGroup->addChild(new ConstantDerivateCase(m_context, glu::getDataTypeName(dataType), "", function, dataType));
1682                         }
1683                 }
1684
1685                 // Cases based on LinearDerivateCase
1686                 for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(s_linearDerivateCases); caseNdx++)
1687                 {
1688                         tcu::TestCaseGroup* const linearCaseGroup       = new tcu::TestCaseGroup(m_testCtx, s_linearDerivateCases[caseNdx].name, s_linearDerivateCases[caseNdx].description);
1689                         const char*                     source                                  = s_linearDerivateCases[caseNdx].source;
1690                         functionGroup->addChild(linearCaseGroup);
1691
1692                         for (int vecSize = 1; vecSize <= 4; vecSize++)
1693                         {
1694                                 for (int precNdx = 0; precNdx < glu::PRECISION_LAST; precNdx++)
1695                                 {
1696                                         const glu::DataType             dataType                = vecSize > 1 ? glu::getDataTypeFloatVec(vecSize) : glu::TYPE_FLOAT;
1697                                         const glu::Precision    precision               = glu::Precision(precNdx);
1698                                         const SurfaceType               surfaceType             = SURFACETYPE_DEFAULT_FRAMEBUFFER;
1699                                         const int                               numSamples              = 0;
1700                                         const deUint32                  hint                    = GL_DONT_CARE;
1701                                         ostringstream                   caseName;
1702
1703                                         if (caseNdx != 0 && precision == glu::PRECISION_LOWP)
1704                                                 continue; // Skip as lowp doesn't actually produce any bits when rendered to default FB.
1705
1706                                         caseName << glu::getDataTypeName(dataType) << "_" << glu::getPrecisionName(precision);
1707
1708                                         linearCaseGroup->addChild(new LinearDerivateCase(m_context, caseName.str().c_str(), "", function, dataType, precision, hint, surfaceType, numSamples, source));
1709                                 }
1710                         }
1711                 }
1712
1713                 // Fbo cases
1714                 for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(s_fboConfigs); caseNdx++)
1715                 {
1716                         tcu::TestCaseGroup*     const   fboGroup                = new tcu::TestCaseGroup(m_testCtx, s_fboConfigs[caseNdx].name, "Derivate usage when rendering into FBO");
1717                         const char*                                     source                  = s_linearDerivateCases[0].source; // use source from .linear group
1718                         const SurfaceType                       surfaceType             = s_fboConfigs[caseNdx].surfaceType;
1719                         const int                                       numSamples              = s_fboConfigs[caseNdx].numSamples;
1720                         functionGroup->addChild(fboGroup);
1721
1722                         for (int vecSize = 1; vecSize <= 4; vecSize++)
1723                         {
1724                                 for (int precNdx = 0; precNdx < glu::PRECISION_LAST; precNdx++)
1725                                 {
1726                                         const glu::DataType             dataType                = vecSize > 1 ? glu::getDataTypeFloatVec(vecSize) : glu::TYPE_FLOAT;
1727                                         const glu::Precision    precision               = glu::Precision(precNdx);
1728                                         const deUint32                  hint                    = GL_DONT_CARE;
1729                                         ostringstream                   caseName;
1730
1731                                         if (surfaceType != SURFACETYPE_FLOAT_FBO && precision == glu::PRECISION_LOWP)
1732                                                 continue; // Skip as lowp doesn't actually produce any bits when rendered to U8 RT.
1733
1734                                         caseName << glu::getDataTypeName(dataType) << "_" << glu::getPrecisionName(precision);
1735
1736                                         fboGroup->addChild(new LinearDerivateCase(m_context, caseName.str().c_str(), "", function, dataType, precision, hint, surfaceType, numSamples, source));
1737                                 }
1738                         }
1739                 }
1740
1741                 // .fastest, .nicest
1742                 for (int hintCaseNdx = 0; hintCaseNdx < DE_LENGTH_OF_ARRAY(s_hints); hintCaseNdx++)
1743                 {
1744                         tcu::TestCaseGroup* const       hintGroup               = new tcu::TestCaseGroup(m_testCtx, s_hints[hintCaseNdx].name, "Shader derivate hints");
1745                         const char*                                     source                  = s_linearDerivateCases[0].source; // use source from .linear group
1746                         const deUint32                          hint                    = s_hints[hintCaseNdx].hint;
1747                         functionGroup->addChild(hintGroup);
1748
1749                         for (int fboCaseNdx = 0; fboCaseNdx < DE_LENGTH_OF_ARRAY(s_hintFboConfigs); fboCaseNdx++)
1750                         {
1751                                 tcu::TestCaseGroup*     const   fboGroup                = new tcu::TestCaseGroup(m_testCtx, s_hintFboConfigs[fboCaseNdx].name, "");
1752                                 const SurfaceType                       surfaceType             = s_hintFboConfigs[fboCaseNdx].surfaceType;
1753                                 const int                                       numSamples              = s_hintFboConfigs[fboCaseNdx].numSamples;
1754                                 hintGroup->addChild(fboGroup);
1755
1756                                 for (int vecSize = 1; vecSize <= 4; vecSize++)
1757                                 {
1758                                         for (int precNdx = 0; precNdx < glu::PRECISION_LAST; precNdx++)
1759                                         {
1760                                                 const glu::DataType             dataType                = vecSize > 1 ? glu::getDataTypeFloatVec(vecSize) : glu::TYPE_FLOAT;
1761                                                 const glu::Precision    precision               = glu::Precision(precNdx);
1762                                                 ostringstream                   caseName;
1763
1764                                                 if (surfaceType != SURFACETYPE_FLOAT_FBO && precision == glu::PRECISION_LOWP)
1765                                                         continue; // Skip as lowp doesn't actually produce any bits when rendered to U8 RT.
1766
1767                                                 caseName << glu::getDataTypeName(dataType) << "_" << glu::getPrecisionName(precision);
1768
1769                                                 fboGroup->addChild(new LinearDerivateCase(m_context, caseName.str().c_str(), "", function, dataType, precision, hint, surfaceType, numSamples, source));
1770                                         }
1771                                 }
1772                         }
1773                 }
1774
1775                 // .texture
1776                 {
1777                         tcu::TestCaseGroup* const textureGroup = new tcu::TestCaseGroup(m_testCtx, "texture", "Derivate of texture lookup result");
1778                         functionGroup->addChild(textureGroup);
1779
1780                         for (int texCaseNdx = 0; texCaseNdx < DE_LENGTH_OF_ARRAY(s_textureConfigs); texCaseNdx++)
1781                         {
1782                                 tcu::TestCaseGroup*     const   caseGroup               = new tcu::TestCaseGroup(m_testCtx, s_textureConfigs[texCaseNdx].name, "");
1783                                 const SurfaceType                       surfaceType             = s_textureConfigs[texCaseNdx].surfaceType;
1784                                 const int                                       numSamples              = s_textureConfigs[texCaseNdx].numSamples;
1785                                 const deUint32                          hint                    = s_textureConfigs[texCaseNdx].hint;
1786                                 textureGroup->addChild(caseGroup);
1787
1788                                 for (int vecSize = 1; vecSize <= 4; vecSize++)
1789                                 {
1790                                         for (int precNdx = 0; precNdx < glu::PRECISION_LAST; precNdx++)
1791                                         {
1792                                                 const glu::DataType             dataType                = vecSize > 1 ? glu::getDataTypeFloatVec(vecSize) : glu::TYPE_FLOAT;
1793                                                 const glu::Precision    precision               = glu::Precision(precNdx);
1794                                                 ostringstream                   caseName;
1795
1796                                                 if (surfaceType != SURFACETYPE_FLOAT_FBO && precision == glu::PRECISION_LOWP)
1797                                                         continue; // Skip as lowp doesn't actually produce any bits when rendered to U8 RT.
1798
1799                                                 caseName << glu::getDataTypeName(dataType) << "_" << glu::getPrecisionName(precision);
1800
1801                                                 caseGroup->addChild(new TextureDerivateCase(m_context, caseName.str().c_str(), "", function, dataType, precision, hint, surfaceType, numSamples));
1802                                         }
1803                                 }
1804                         }
1805                 }
1806         }
1807 }
1808
1809 } // Functional
1810 } // gles3
1811 } // deqp