1 /*-------------------------------------------------------------------------
2  * drawElements Quality Program Tester Core
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 Rasterization verifier utils.
22  *//*--------------------------------------------------------------------*/
23 
24 #include "tcuRasterizationVerifier.hpp"
25 #include "tcuVector.hpp"
26 #include "tcuSurface.hpp"
27 #include "tcuTestLog.hpp"
28 #include "tcuTextureUtil.hpp"
29 #include "tcuVectorUtil.hpp"
30 #include "tcuFloat.hpp"
31 
32 #include "deMath.h"
33 #include "deStringUtil.hpp"
34 
35 #include "rrRasterizer.hpp"
36 
37 #include <limits>
38 
39 namespace tcu
40 {
41 namespace
42 {
43 
44 bool verifyLineGroupInterpolationWithProjectedWeights (const tcu::Surface& surface, const LineSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log);
45 
lineLineIntersect(const tcu::Vector<deInt64,2> & line0Beg,const tcu::Vector<deInt64,2> & line0End,const tcu::Vector<deInt64,2> & line1Beg,const tcu::Vector<deInt64,2> & line1End)46 bool lineLineIntersect (const tcu::Vector<deInt64, 2>& line0Beg, const tcu::Vector<deInt64, 2>& line0End, const tcu::Vector<deInt64, 2>& line1Beg, const tcu::Vector<deInt64, 2>& line1End)
47 {
48 	typedef tcu::Vector<deInt64, 2> I64Vec2;
49 
50 	// Lines do not intersect if the other line's endpoints are on the same side
51 	// otherwise, the do intersect
52 
53 	// Test line 0
54 	{
55 		const I64Vec2 line			= line0End - line0Beg;
56 		const I64Vec2 v0			= line1Beg - line0Beg;
57 		const I64Vec2 v1			= line1End - line0Beg;
58 		const deInt64 crossProduct0	= (line.x() * v0.y() - line.y() * v0.x());
59 		const deInt64 crossProduct1	= (line.x() * v1.y() - line.y() * v1.x());
60 
61 		// check signs
62 		if ((crossProduct0 < 0 && crossProduct1 < 0) ||
63 			(crossProduct0 > 0 && crossProduct1 > 0))
64 			return false;
65 	}
66 
67 	// Test line 1
68 	{
69 		const I64Vec2 line			= line1End - line1Beg;
70 		const I64Vec2 v0			= line0Beg - line1Beg;
71 		const I64Vec2 v1			= line0End - line1Beg;
72 		const deInt64 crossProduct0	= (line.x() * v0.y() - line.y() * v0.x());
73 		const deInt64 crossProduct1	= (line.x() * v1.y() - line.y() * v1.x());
74 
75 		// check signs
76 		if ((crossProduct0 < 0 && crossProduct1 < 0) ||
77 			(crossProduct0 > 0 && crossProduct1 > 0))
78 			return false;
79 	}
80 
81 	return true;
82 }
83 
isTriangleClockwise(const tcu::Vec4 & p0,const tcu::Vec4 & p1,const tcu::Vec4 & p2)84 bool isTriangleClockwise (const tcu::Vec4& p0, const tcu::Vec4& p1, const tcu::Vec4& p2)
85 {
86 	const tcu::Vec2	u				(p1.x() / p1.w() - p0.x() / p0.w(), p1.y() / p1.w() - p0.y() / p0.w());
87 	const tcu::Vec2	v				(p2.x() / p2.w() - p0.x() / p0.w(), p2.y() / p2.w() - p0.y() / p0.w());
88 	const float		crossProduct	= (u.x() * v.y() - u.y() * v.x());
89 
90 	return crossProduct > 0.0f;
91 }
92 
compareColors(const tcu::RGBA & colorA,const tcu::RGBA & colorB,int redBits,int greenBits,int blueBits)93 bool compareColors (const tcu::RGBA& colorA, const tcu::RGBA& colorB, int redBits, int greenBits, int blueBits)
94 {
95 	const int thresholdRed		= 1 << (8 - redBits);
96 	const int thresholdGreen	= 1 << (8 - greenBits);
97 	const int thresholdBlue		= 1 << (8 - blueBits);
98 
99 	return	deAbs32(colorA.getRed()   - colorB.getRed())   <= thresholdRed   &&
100 			deAbs32(colorA.getGreen() - colorB.getGreen()) <= thresholdGreen &&
101 			deAbs32(colorA.getBlue()  - colorB.getBlue())  <= thresholdBlue;
102 }
103 
pixelNearLineSegment(const tcu::IVec2 & pixel,const tcu::Vec2 & p0,const tcu::Vec2 & p1)104 bool pixelNearLineSegment (const tcu::IVec2& pixel, const tcu::Vec2& p0, const tcu::Vec2& p1)
105 {
106 	const tcu::Vec2 pixelCenterPosition = tcu::Vec2((float)pixel.x() + 0.5f, (float)pixel.y() + 0.5f);
107 
108 	// "Near" = Distance from the line to the pixel is less than 2 * pixel_max_radius. (pixel_max_radius = sqrt(2) / 2)
109 	const float maxPixelDistance		= 1.414f;
110 	const float maxPixelDistanceSquared	= 2.0f;
111 
112 	// Near the line
113 	{
114 		const tcu::Vec2	line			= p1                  - p0;
115 		const tcu::Vec2	v				= pixelCenterPosition - p0;
116 		const float		crossProduct	= (line.x() * v.y() - line.y() * v.x());
117 
118 		// distance to line: (line x v) / |line|
119 		//     |(line x v) / |line|| > maxPixelDistance
120 		// ==> (line x v)^2 / |line|^2 > maxPixelDistance^2
121 		// ==> (line x v)^2 > maxPixelDistance^2 * |line|^2
122 
123 		if (crossProduct * crossProduct > maxPixelDistanceSquared * tcu::lengthSquared(line))
124 			return false;
125 	}
126 
127 	// Between the endpoints
128 	{
129 		// distance from line endpoint 1 to pixel is less than line length + maxPixelDistance
130 		const float maxDistance = tcu::length(p1 - p0) + maxPixelDistance;
131 
132 		if (tcu::length(pixelCenterPosition - p0) > maxDistance)
133 			return false;
134 		if (tcu::length(pixelCenterPosition - p1) > maxDistance)
135 			return false;
136 	}
137 
138 	return true;
139 }
140 
pixelOnlyOnASharedEdge(const tcu::IVec2 & pixel,const TriangleSceneSpec::SceneTriangle & triangle,const tcu::IVec2 & viewportSize)141 bool pixelOnlyOnASharedEdge (const tcu::IVec2& pixel, const TriangleSceneSpec::SceneTriangle& triangle, const tcu::IVec2& viewportSize)
142 {
143 	if (triangle.sharedEdge[0] || triangle.sharedEdge[1] || triangle.sharedEdge[2])
144 	{
145 		const tcu::Vec2 triangleNormalizedDeviceSpace[3] =
146 		{
147 			tcu::Vec2(triangle.positions[0].x() / triangle.positions[0].w(), triangle.positions[0].y() / triangle.positions[0].w()),
148 			tcu::Vec2(triangle.positions[1].x() / triangle.positions[1].w(), triangle.positions[1].y() / triangle.positions[1].w()),
149 			tcu::Vec2(triangle.positions[2].x() / triangle.positions[2].w(), triangle.positions[2].y() / triangle.positions[2].w()),
150 		};
151 		const tcu::Vec2 triangleScreenSpace[3] =
152 		{
153 			(triangleNormalizedDeviceSpace[0] + tcu::Vec2(1.0f, 1.0f)) * 0.5f * tcu::Vec2((float)viewportSize.x(), (float)viewportSize.y()),
154 			(triangleNormalizedDeviceSpace[1] + tcu::Vec2(1.0f, 1.0f)) * 0.5f * tcu::Vec2((float)viewportSize.x(), (float)viewportSize.y()),
155 			(triangleNormalizedDeviceSpace[2] + tcu::Vec2(1.0f, 1.0f)) * 0.5f * tcu::Vec2((float)viewportSize.x(), (float)viewportSize.y()),
156 		};
157 
158 		const bool pixelOnEdge0 = pixelNearLineSegment(pixel, triangleScreenSpace[0], triangleScreenSpace[1]);
159 		const bool pixelOnEdge1 = pixelNearLineSegment(pixel, triangleScreenSpace[1], triangleScreenSpace[2]);
160 		const bool pixelOnEdge2 = pixelNearLineSegment(pixel, triangleScreenSpace[2], triangleScreenSpace[0]);
161 
162 		// If the pixel is on a multiple edges return false
163 
164 		if (pixelOnEdge0 && !pixelOnEdge1 && !pixelOnEdge2)
165 			return triangle.sharedEdge[0];
166 		if (!pixelOnEdge0 && pixelOnEdge1 && !pixelOnEdge2)
167 			return triangle.sharedEdge[1];
168 		if (!pixelOnEdge0 && !pixelOnEdge1 && pixelOnEdge2)
169 			return triangle.sharedEdge[2];
170 	}
171 
172 	return false;
173 }
174 
triangleArea(const tcu::Vec2 & s0,const tcu::Vec2 & s1,const tcu::Vec2 & s2)175 float triangleArea (const tcu::Vec2& s0, const tcu::Vec2& s1, const tcu::Vec2& s2)
176 {
177 	const tcu::Vec2	u				(s1.x() - s0.x(), s1.y() - s0.y());
178 	const tcu::Vec2	v				(s2.x() - s0.x(), s2.y() - s0.y());
179 	const float		crossProduct	= (u.x() * v.y() - u.y() * v.x());
180 
181 	return crossProduct / 2.0f;
182 }
183 
getTriangleAABB(const TriangleSceneSpec::SceneTriangle & triangle,const tcu::IVec2 & viewportSize)184 tcu::IVec4 getTriangleAABB (const TriangleSceneSpec::SceneTriangle& triangle, const tcu::IVec2& viewportSize)
185 {
186 	const tcu::Vec2 normalizedDeviceSpace[3] =
187 	{
188 		tcu::Vec2(triangle.positions[0].x() / triangle.positions[0].w(), triangle.positions[0].y() / triangle.positions[0].w()),
189 		tcu::Vec2(triangle.positions[1].x() / triangle.positions[1].w(), triangle.positions[1].y() / triangle.positions[1].w()),
190 		tcu::Vec2(triangle.positions[2].x() / triangle.positions[2].w(), triangle.positions[2].y() / triangle.positions[2].w()),
191 	};
192 	const tcu::Vec2 screenSpace[3] =
193 	{
194 		(normalizedDeviceSpace[0] + tcu::Vec2(1.0f, 1.0f)) * 0.5f * tcu::Vec2((float)viewportSize.x(), (float)viewportSize.y()),
195 		(normalizedDeviceSpace[1] + tcu::Vec2(1.0f, 1.0f)) * 0.5f * tcu::Vec2((float)viewportSize.x(), (float)viewportSize.y()),
196 		(normalizedDeviceSpace[2] + tcu::Vec2(1.0f, 1.0f)) * 0.5f * tcu::Vec2((float)viewportSize.x(), (float)viewportSize.y()),
197 	};
198 
199 	tcu::IVec4 aabb;
200 
201 	aabb.x() = (int)deFloatFloor(de::min(de::min(screenSpace[0].x(), screenSpace[1].x()), screenSpace[2].x()));
202 	aabb.y() = (int)deFloatFloor(de::min(de::min(screenSpace[0].y(), screenSpace[1].y()), screenSpace[2].y()));
203 	aabb.z() = (int)deFloatCeil (de::max(de::max(screenSpace[0].x(), screenSpace[1].x()), screenSpace[2].x()));
204 	aabb.w() = (int)deFloatCeil (de::max(de::max(screenSpace[0].y(), screenSpace[1].y()), screenSpace[2].y()));
205 
206 	return aabb;
207 }
208 
getExponentEpsilonFromULP(int valueExponent,deUint32 ulp)209 float getExponentEpsilonFromULP (int valueExponent, deUint32 ulp)
210 {
211 	DE_ASSERT(ulp < (1u<<10));
212 
213 	// assume mediump precision, using ulp as ulps in a 10 bit mantissa
214 	return tcu::Float32::construct(+1, valueExponent, (1u<<23) + (ulp << (23 - 10))).asFloat() - tcu::Float32::construct(+1, valueExponent, (1u<<23)).asFloat();
215 }
216 
getValueEpsilonFromULP(float value,deUint32 ulp)217 float getValueEpsilonFromULP (float value, deUint32 ulp)
218 {
219 	DE_ASSERT(value != std::numeric_limits<float>::infinity() && value != -std::numeric_limits<float>::infinity());
220 
221 	const int exponent = tcu::Float32(value).exponent();
222 	return getExponentEpsilonFromULP(exponent, ulp);
223 }
224 
getMaxValueWithinError(float value,deUint32 ulp)225 float getMaxValueWithinError (float value, deUint32 ulp)
226 {
227 	if (value == std::numeric_limits<float>::infinity() || value == -std::numeric_limits<float>::infinity())
228 		return value;
229 
230 	return value + getValueEpsilonFromULP(value, ulp);
231 }
232 
getMinValueWithinError(float value,deUint32 ulp)233 float getMinValueWithinError (float value, deUint32 ulp)
234 {
235 	if (value == std::numeric_limits<float>::infinity() || value == -std::numeric_limits<float>::infinity())
236 		return value;
237 
238 	return value - getValueEpsilonFromULP(value, ulp);
239 }
240 
getMinFlushToZero(float value)241 float getMinFlushToZero (float value)
242 {
243 	// flush to zero if that decreases the value
244 	// assume mediump precision
245 	if (value > 0.0f && value < tcu::Float32::construct(+1, -14, 1u<<23).asFloat())
246 		return 0.0f;
247 	return value;
248 }
249 
getMaxFlushToZero(float value)250 float getMaxFlushToZero (float value)
251 {
252 	// flush to zero if that increases the value
253 	// assume mediump precision
254 	if (value < 0.0f && value > tcu::Float32::construct(-1, -14, 1u<<23).asFloat())
255 		return 0.0f;
256 	return value;
257 }
258 
convertRGB8ToNativeFormat(const tcu::RGBA & color,const RasterizationArguments & args)259 tcu::IVec3 convertRGB8ToNativeFormat (const tcu::RGBA& color, const RasterizationArguments& args)
260 {
261 	tcu::IVec3 pixelNativeColor;
262 
263 	for (int channelNdx = 0; channelNdx < 3; ++channelNdx)
264 	{
265 		const int channelBitCount	= (channelNdx == 0) ? (args.redBits) : (channelNdx == 1) ? (args.greenBits) : (args.blueBits);
266 		const int channelPixelValue	= (channelNdx == 0) ? (color.getRed()) : (channelNdx == 1) ? (color.getGreen()) : (color.getBlue());
267 
268 		if (channelBitCount <= 8)
269 			pixelNativeColor[channelNdx] = channelPixelValue >> (8 - channelBitCount);
270 		else if (channelBitCount == 8)
271 			pixelNativeColor[channelNdx] = channelPixelValue;
272 		else
273 		{
274 			// just in case someone comes up with 8+ bits framebuffers pixel formats. But as
275 			// we can only read in rgba8, we have to guess the trailing bits. Guessing 0.
276 			pixelNativeColor[channelNdx] = channelPixelValue << (channelBitCount - 8);
277 		}
278 	}
279 
280 	return pixelNativeColor;
281 }
282 
283 /*--------------------------------------------------------------------*//*!
284  * Returns the maximum value of x / y, where x c [minDividend, maxDividend]
285  * and y c [minDivisor, maxDivisor]
286  *//*--------------------------------------------------------------------*/
maximalRangeDivision(float minDividend,float maxDividend,float minDivisor,float maxDivisor)287 float maximalRangeDivision (float minDividend, float maxDividend, float minDivisor, float maxDivisor)
288 {
289 	DE_ASSERT(minDividend <= maxDividend);
290 	DE_ASSERT(minDivisor <= maxDivisor);
291 
292 	// special cases
293 	if (minDividend == 0.0f && maxDividend == 0.0f)
294 		return 0.0f;
295 	if (minDivisor <= 0.0f && maxDivisor >= 0.0f)
296 		return std::numeric_limits<float>::infinity();
297 
298 	return de::max(de::max(minDividend / minDivisor, minDividend / maxDivisor), de::max(maxDividend / minDivisor, maxDividend / maxDivisor));
299 }
300 
301 /*--------------------------------------------------------------------*//*!
302  * Returns the minimum value of x / y, where x c [minDividend, maxDividend]
303  * and y c [minDivisor, maxDivisor]
304  *//*--------------------------------------------------------------------*/
minimalRangeDivision(float minDividend,float maxDividend,float minDivisor,float maxDivisor)305 float minimalRangeDivision (float minDividend, float maxDividend, float minDivisor, float maxDivisor)
306 {
307 	DE_ASSERT(minDividend <= maxDividend);
308 	DE_ASSERT(minDivisor <= maxDivisor);
309 
310 	// special cases
311 	if (minDividend == 0.0f && maxDividend == 0.0f)
312 		return 0.0f;
313 	if (minDivisor <= 0.0f && maxDivisor >= 0.0f)
314 		return -std::numeric_limits<float>::infinity();
315 
316 	return de::min(de::min(minDividend / minDivisor, minDividend / maxDivisor), de::min(maxDividend / minDivisor, maxDividend / maxDivisor));
317 }
318 
isLineXMajor(const tcu::Vec2 & lineScreenSpaceP0,const tcu::Vec2 & lineScreenSpaceP1)319 static bool isLineXMajor (const tcu::Vec2& lineScreenSpaceP0, const tcu::Vec2& lineScreenSpaceP1)
320 {
321 	return de::abs(lineScreenSpaceP1.x() - lineScreenSpaceP0.x()) >= de::abs(lineScreenSpaceP1.y() - lineScreenSpaceP0.y());
322 }
323 
isPackedSSLineXMajor(const tcu::Vec4 & packedLine)324 static bool isPackedSSLineXMajor (const tcu::Vec4& packedLine)
325 {
326 	const tcu::Vec2 lineScreenSpaceP0 = packedLine.swizzle(0, 1);
327 	const tcu::Vec2 lineScreenSpaceP1 = packedLine.swizzle(2, 3);
328 
329 	return isLineXMajor(lineScreenSpaceP0, lineScreenSpaceP1);
330 }
331 
332 struct InterpolationRange
333 {
334 	tcu::Vec3 max;
335 	tcu::Vec3 min;
336 };
337 
338 struct LineInterpolationRange
339 {
340 	tcu::Vec2 max;
341 	tcu::Vec2 min;
342 };
343 
calcTriangleInterpolationWeights(const tcu::Vec4 & p0,const tcu::Vec4 & p1,const tcu::Vec4 & p2,const tcu::Vec2 & ndpixel)344 InterpolationRange calcTriangleInterpolationWeights (const tcu::Vec4& p0, const tcu::Vec4& p1, const tcu::Vec4& p2, const tcu::Vec2& ndpixel)
345 {
346 	const int roundError		= 1;
347 	const int barycentricError	= 3;
348 	const int divError			= 8;
349 
350 	const tcu::Vec2 nd0 = p0.swizzle(0, 1) / p0.w();
351 	const tcu::Vec2 nd1 = p1.swizzle(0, 1) / p1.w();
352 	const tcu::Vec2 nd2 = p2.swizzle(0, 1) / p2.w();
353 
354 	const float ka = triangleArea(ndpixel, nd1, nd2);
355 	const float kb = triangleArea(ndpixel, nd2, nd0);
356 	const float kc = triangleArea(ndpixel, nd0, nd1);
357 
358 	const float kaMax = getMaxFlushToZero(getMaxValueWithinError(ka, barycentricError));
359 	const float kbMax = getMaxFlushToZero(getMaxValueWithinError(kb, barycentricError));
360 	const float kcMax = getMaxFlushToZero(getMaxValueWithinError(kc, barycentricError));
361 	const float kaMin = getMinFlushToZero(getMinValueWithinError(ka, barycentricError));
362 	const float kbMin = getMinFlushToZero(getMinValueWithinError(kb, barycentricError));
363 	const float kcMin = getMinFlushToZero(getMinValueWithinError(kc, barycentricError));
364 	DE_ASSERT(kaMin <= kaMax);
365 	DE_ASSERT(kbMin <= kbMax);
366 	DE_ASSERT(kcMin <= kcMax);
367 
368 	// calculate weights: vec3(ka / p0.w, kb / p1.w, kc / p2.w) / (ka / p0.w + kb / p1.w + kc / p2.w)
369 	const float maxPreDivisionValues[3] =
370 	{
371 		getMaxFlushToZero(getMaxValueWithinError(getMaxFlushToZero(kaMax / p0.w()), divError)),
372 		getMaxFlushToZero(getMaxValueWithinError(getMaxFlushToZero(kbMax / p1.w()), divError)),
373 		getMaxFlushToZero(getMaxValueWithinError(getMaxFlushToZero(kcMax / p2.w()), divError)),
374 	};
375 	const float minPreDivisionValues[3] =
376 	{
377 		getMinFlushToZero(getMinValueWithinError(getMinFlushToZero(kaMin / p0.w()), divError)),
378 		getMinFlushToZero(getMinValueWithinError(getMinFlushToZero(kbMin / p1.w()), divError)),
379 		getMinFlushToZero(getMinValueWithinError(getMinFlushToZero(kcMin / p2.w()), divError)),
380 	};
381 	DE_ASSERT(minPreDivisionValues[0] <= maxPreDivisionValues[0]);
382 	DE_ASSERT(minPreDivisionValues[1] <= maxPreDivisionValues[1]);
383 	DE_ASSERT(minPreDivisionValues[2] <= maxPreDivisionValues[2]);
384 
385 	const float maxDivisor = getMaxFlushToZero(getMaxValueWithinError(maxPreDivisionValues[0] + maxPreDivisionValues[1] + maxPreDivisionValues[2], 2*roundError));
386 	const float minDivisor = getMinFlushToZero(getMinValueWithinError(minPreDivisionValues[0] + minPreDivisionValues[1] + minPreDivisionValues[2], 2*roundError));
387 	DE_ASSERT(minDivisor <= maxDivisor);
388 
389 	InterpolationRange returnValue;
390 
391 	returnValue.max.x() = getMaxFlushToZero(getMaxValueWithinError(getMaxFlushToZero(maximalRangeDivision(minPreDivisionValues[0], maxPreDivisionValues[0], minDivisor, maxDivisor)), divError));
392 	returnValue.max.y() = getMaxFlushToZero(getMaxValueWithinError(getMaxFlushToZero(maximalRangeDivision(minPreDivisionValues[1], maxPreDivisionValues[1], minDivisor, maxDivisor)), divError));
393 	returnValue.max.z() = getMaxFlushToZero(getMaxValueWithinError(getMaxFlushToZero(maximalRangeDivision(minPreDivisionValues[2], maxPreDivisionValues[2], minDivisor, maxDivisor)), divError));
394 	returnValue.min.x() = getMinFlushToZero(getMinValueWithinError(getMinFlushToZero(minimalRangeDivision(minPreDivisionValues[0], maxPreDivisionValues[0], minDivisor, maxDivisor)), divError));
395 	returnValue.min.y() = getMinFlushToZero(getMinValueWithinError(getMinFlushToZero(minimalRangeDivision(minPreDivisionValues[1], maxPreDivisionValues[1], minDivisor, maxDivisor)), divError));
396 	returnValue.min.z() = getMinFlushToZero(getMinValueWithinError(getMinFlushToZero(minimalRangeDivision(minPreDivisionValues[2], maxPreDivisionValues[2], minDivisor, maxDivisor)), divError));
397 
398 	DE_ASSERT(returnValue.min.x() <= returnValue.max.x());
399 	DE_ASSERT(returnValue.min.y() <= returnValue.max.y());
400 	DE_ASSERT(returnValue.min.z() <= returnValue.max.z());
401 
402 	return returnValue;
403 }
404 
calcLineInterpolationWeights(const tcu::Vec2 & pa,float wa,const tcu::Vec2 & pb,float wb,const tcu::Vec2 & pr)405 LineInterpolationRange calcLineInterpolationWeights (const tcu::Vec2& pa, float wa, const tcu::Vec2& pb, float wb, const tcu::Vec2& pr)
406 {
407 	const int roundError	= 1;
408 	const int divError		= 3;
409 
410 	// calc weights:
411 	//			(1-t) / wa					t / wb
412 	//		-------------------	,	-------------------
413 	//		(1-t) / wa + t / wb		(1-t) / wa + t / wb
414 
415 	// Allow 1 ULP
416 	const float		dividend	= tcu::dot(pr - pa, pb - pa);
417 	const float		dividendMax	= getMaxValueWithinError(dividend, 1);
418 	const float		dividendMin	= getMinValueWithinError(dividend, 1);
419 	DE_ASSERT(dividendMin <= dividendMax);
420 
421 	// Assuming lengthSquared will not be implemented as sqrt(x)^2, allow 1 ULP
422 	const float		divisor		= tcu::lengthSquared(pb - pa);
423 	const float		divisorMax	= getMaxValueWithinError(divisor, 1);
424 	const float		divisorMin	= getMinValueWithinError(divisor, 1);
425 	DE_ASSERT(divisorMin <= divisorMax);
426 
427 	// Allow 3 ULP precision for division
428 	const float		tMax		= getMaxValueWithinError(maximalRangeDivision(dividendMin, dividendMax, divisorMin, divisorMax), divError);
429 	const float		tMin		= getMinValueWithinError(minimalRangeDivision(dividendMin, dividendMax, divisorMin, divisorMax), divError);
430 	DE_ASSERT(tMin <= tMax);
431 
432 	const float		perspectiveTMax			= getMaxValueWithinError(maximalRangeDivision(tMin, tMax, wb, wb), divError);
433 	const float		perspectiveTMin			= getMinValueWithinError(minimalRangeDivision(tMin, tMax, wb, wb), divError);
434 	DE_ASSERT(perspectiveTMin <= perspectiveTMax);
435 
436 	const float		perspectiveInvTMax		= getMaxValueWithinError(maximalRangeDivision((1.0f - tMax), (1.0f - tMin), wa, wa), divError);
437 	const float		perspectiveInvTMin		= getMinValueWithinError(minimalRangeDivision((1.0f - tMax), (1.0f - tMin), wa, wa), divError);
438 	DE_ASSERT(perspectiveInvTMin <= perspectiveInvTMax);
439 
440 	const float		perspectiveDivisorMax	= getMaxValueWithinError(perspectiveTMax + perspectiveInvTMax, roundError);
441 	const float		perspectiveDivisorMin	= getMinValueWithinError(perspectiveTMin + perspectiveInvTMin, roundError);
442 	DE_ASSERT(perspectiveDivisorMin <= perspectiveDivisorMax);
443 
444 	LineInterpolationRange returnValue;
445 	returnValue.max.x() = getMaxValueWithinError(maximalRangeDivision(perspectiveInvTMin,	perspectiveInvTMax,	perspectiveDivisorMin, perspectiveDivisorMax), divError);
446 	returnValue.max.y() = getMaxValueWithinError(maximalRangeDivision(perspectiveTMin,		perspectiveTMax,	perspectiveDivisorMin, perspectiveDivisorMax), divError);
447 	returnValue.min.x() = getMinValueWithinError(minimalRangeDivision(perspectiveInvTMin,	perspectiveInvTMax,	perspectiveDivisorMin, perspectiveDivisorMax), divError);
448 	returnValue.min.y() = getMinValueWithinError(minimalRangeDivision(perspectiveTMin,		perspectiveTMax,	perspectiveDivisorMin, perspectiveDivisorMax), divError);
449 
450 	DE_ASSERT(returnValue.min.x() <= returnValue.max.x());
451 	DE_ASSERT(returnValue.min.y() <= returnValue.max.y());
452 
453 	return returnValue;
454 }
455 
calcLineInterpolationWeightsAxisProjected(const tcu::Vec2 & pa,float wa,const tcu::Vec2 & pb,float wb,const tcu::Vec2 & pr)456 LineInterpolationRange calcLineInterpolationWeightsAxisProjected (const tcu::Vec2& pa, float wa, const tcu::Vec2& pb, float wb, const tcu::Vec2& pr)
457 {
458 	const int	roundError		= 1;
459 	const int	divError		= 3;
460 	const bool	isXMajor		= isLineXMajor(pa, pb);
461 	const int	majorAxisNdx	= (isXMajor) ? (0) : (1);
462 
463 	// calc weights:
464 	//			(1-t) / wa					t / wb
465 	//		-------------------	,	-------------------
466 	//		(1-t) / wa + t / wb		(1-t) / wa + t / wb
467 
468 	// Use axis projected (inaccurate) method, i.e. for X-major lines:
469 	//     (xd - xa) * (xb - xa)      xd - xa
470 	// t = ---------------------  ==  -------
471 	//       ( xb - xa ) ^ 2          xb - xa
472 
473 	// Allow 1 ULP
474 	const float		dividend	= (pr[majorAxisNdx] - pa[majorAxisNdx]);
475 	const float		dividendMax	= getMaxValueWithinError(dividend, 1);
476 	const float		dividendMin	= getMinValueWithinError(dividend, 1);
477 	DE_ASSERT(dividendMin <= dividendMax);
478 
479 	// Allow 1 ULP
480 	const float		divisor		= (pb[majorAxisNdx] - pa[majorAxisNdx]);
481 	const float		divisorMax	= getMaxValueWithinError(divisor, 1);
482 	const float		divisorMin	= getMinValueWithinError(divisor, 1);
483 	DE_ASSERT(divisorMin <= divisorMax);
484 
485 	// Allow 3 ULP precision for division
486 	const float		tMax		= getMaxValueWithinError(maximalRangeDivision(dividendMin, dividendMax, divisorMin, divisorMax), divError);
487 	const float		tMin		= getMinValueWithinError(minimalRangeDivision(dividendMin, dividendMax, divisorMin, divisorMax), divError);
488 	DE_ASSERT(tMin <= tMax);
489 
490 	const float		perspectiveTMax			= getMaxValueWithinError(maximalRangeDivision(tMin, tMax, wb, wb), divError);
491 	const float		perspectiveTMin			= getMinValueWithinError(minimalRangeDivision(tMin, tMax, wb, wb), divError);
492 	DE_ASSERT(perspectiveTMin <= perspectiveTMax);
493 
494 	const float		perspectiveInvTMax		= getMaxValueWithinError(maximalRangeDivision((1.0f - tMax), (1.0f - tMin), wa, wa), divError);
495 	const float		perspectiveInvTMin		= getMinValueWithinError(minimalRangeDivision((1.0f - tMax), (1.0f - tMin), wa, wa), divError);
496 	DE_ASSERT(perspectiveInvTMin <= perspectiveInvTMax);
497 
498 	const float		perspectiveDivisorMax	= getMaxValueWithinError(perspectiveTMax + perspectiveInvTMax, roundError);
499 	const float		perspectiveDivisorMin	= getMinValueWithinError(perspectiveTMin + perspectiveInvTMin, roundError);
500 	DE_ASSERT(perspectiveDivisorMin <= perspectiveDivisorMax);
501 
502 	LineInterpolationRange returnValue;
503 	returnValue.max.x() = getMaxValueWithinError(maximalRangeDivision(perspectiveInvTMin,	perspectiveInvTMax,	perspectiveDivisorMin, perspectiveDivisorMax), divError);
504 	returnValue.max.y() = getMaxValueWithinError(maximalRangeDivision(perspectiveTMin,		perspectiveTMax,	perspectiveDivisorMin, perspectiveDivisorMax), divError);
505 	returnValue.min.x() = getMinValueWithinError(minimalRangeDivision(perspectiveInvTMin,	perspectiveInvTMax,	perspectiveDivisorMin, perspectiveDivisorMax), divError);
506 	returnValue.min.y() = getMinValueWithinError(minimalRangeDivision(perspectiveTMin,		perspectiveTMax,	perspectiveDivisorMin, perspectiveDivisorMax), divError);
507 
508 	DE_ASSERT(returnValue.min.x() <= returnValue.max.x());
509 	DE_ASSERT(returnValue.min.y() <= returnValue.max.y());
510 
511 	return returnValue;
512 }
513 
514 template <typename WeightEquation>
calcSingleSampleLineInterpolationRangeWithWeightEquation(const tcu::Vec2 & pa,float wa,const tcu::Vec2 & pb,float wb,const tcu::IVec2 & pixel,int subpixelBits,WeightEquation weightEquation)515 LineInterpolationRange calcSingleSampleLineInterpolationRangeWithWeightEquation (const tcu::Vec2&	pa,
516 																				 float				wa,
517 																				 const tcu::Vec2&	pb,
518 																				 float				wb,
519 																				 const tcu::IVec2&	pixel,
520 																				 int				subpixelBits,
521 																				 WeightEquation		weightEquation)
522 {
523 	// allow interpolation weights anywhere in the central subpixels
524 	const float testSquareSize = (2.0f / (float)(1UL << subpixelBits));
525 	const float testSquarePos  = (0.5f - testSquareSize / 2);
526 
527 	const tcu::Vec2 corners[4] =
528 	{
529 		tcu::Vec2((float)pixel.x() + testSquarePos + 0.0f,				(float)pixel.y() + testSquarePos + 0.0f),
530 		tcu::Vec2((float)pixel.x() + testSquarePos + 0.0f,				(float)pixel.y() + testSquarePos + testSquareSize),
531 		tcu::Vec2((float)pixel.x() + testSquarePos + testSquareSize,	(float)pixel.y() + testSquarePos + testSquareSize),
532 		tcu::Vec2((float)pixel.x() + testSquarePos + testSquareSize,	(float)pixel.y() + testSquarePos + 0.0f),
533 	};
534 
535 	// calculate interpolation as a line
536 	const LineInterpolationRange weights[4] =
537 	{
538 		weightEquation(pa, wa, pb, wb, corners[0]),
539 		weightEquation(pa, wa, pb, wb, corners[1]),
540 		weightEquation(pa, wa, pb, wb, corners[2]),
541 		weightEquation(pa, wa, pb, wb, corners[3]),
542 	};
543 
544 	const tcu::Vec2 minWeights = tcu::min(tcu::min(weights[0].min, weights[1].min), tcu::min(weights[2].min, weights[3].min));
545 	const tcu::Vec2 maxWeights = tcu::max(tcu::max(weights[0].max, weights[1].max), tcu::max(weights[2].max, weights[3].max));
546 
547 	LineInterpolationRange result;
548 	result.min = minWeights;
549 	result.max = maxWeights;
550 	return result;
551 }
552 
calcSingleSampleLineInterpolationRange(const tcu::Vec2 & pa,float wa,const tcu::Vec2 & pb,float wb,const tcu::IVec2 & pixel,int subpixelBits)553 LineInterpolationRange calcSingleSampleLineInterpolationRange (const tcu::Vec2& pa, float wa, const tcu::Vec2& pb, float wb, const tcu::IVec2& pixel, int subpixelBits)
554 {
555 	return calcSingleSampleLineInterpolationRangeWithWeightEquation(pa, wa, pb, wb, pixel, subpixelBits, calcLineInterpolationWeights);
556 }
557 
calcSingleSampleLineInterpolationRangeAxisProjected(const tcu::Vec2 & pa,float wa,const tcu::Vec2 & pb,float wb,const tcu::IVec2 & pixel,int subpixelBits)558 LineInterpolationRange calcSingleSampleLineInterpolationRangeAxisProjected (const tcu::Vec2& pa, float wa, const tcu::Vec2& pb, float wb, const tcu::IVec2& pixel, int subpixelBits)
559 {
560 	return calcSingleSampleLineInterpolationRangeWithWeightEquation(pa, wa, pb, wb, pixel, subpixelBits, calcLineInterpolationWeightsAxisProjected);
561 }
562 
563 struct TriangleInterpolator
564 {
565 	const TriangleSceneSpec& scene;
566 
TriangleInterpolatortcu::__anon958de0670111::TriangleInterpolator567 	TriangleInterpolator (const TriangleSceneSpec& scene_)
568 		: scene(scene_)
569 	{
570 	}
571 
interpolatetcu::__anon958de0670111::TriangleInterpolator572 	InterpolationRange interpolate (int primitiveNdx, const tcu::IVec2 pixel, const tcu::IVec2 viewportSize, bool multisample, int subpixelBits) const
573 	{
574 		// allow anywhere in the pixel area in multisample
575 		// allow only in the center subpixels (4 subpixels) in singlesample
576 		const float testSquareSize = (multisample) ? (1.0f) : (2.0f / (float)(1UL << subpixelBits));
577 		const float testSquarePos  = (multisample) ? (0.0f) : (0.5f - testSquareSize / 2);
578 		const tcu::Vec2 corners[4] =
579 		{
580 			tcu::Vec2(((float)pixel.x() + testSquarePos + 0.0f)           / (float)viewportSize.x() * 2.0f - 1.0f, ((float)pixel.y() + testSquarePos + 0.0f          ) / (float)viewportSize.y() * 2.0f - 1.0f),
581 			tcu::Vec2(((float)pixel.x() + testSquarePos + 0.0f)           / (float)viewportSize.x() * 2.0f - 1.0f, ((float)pixel.y() + testSquarePos + testSquareSize) / (float)viewportSize.y() * 2.0f - 1.0f),
582 			tcu::Vec2(((float)pixel.x() + testSquarePos + testSquareSize) / (float)viewportSize.x() * 2.0f - 1.0f, ((float)pixel.y() + testSquarePos + testSquareSize) / (float)viewportSize.y() * 2.0f - 1.0f),
583 			tcu::Vec2(((float)pixel.x() + testSquarePos + testSquareSize) / (float)viewportSize.x() * 2.0f - 1.0f, ((float)pixel.y() + testSquarePos + 0.0f          ) / (float)viewportSize.y() * 2.0f - 1.0f),
584 		};
585 		const InterpolationRange weights[4] =
586 		{
587 			calcTriangleInterpolationWeights(scene.triangles[primitiveNdx].positions[0], scene.triangles[primitiveNdx].positions[1], scene.triangles[primitiveNdx].positions[2], corners[0]),
588 			calcTriangleInterpolationWeights(scene.triangles[primitiveNdx].positions[0], scene.triangles[primitiveNdx].positions[1], scene.triangles[primitiveNdx].positions[2], corners[1]),
589 			calcTriangleInterpolationWeights(scene.triangles[primitiveNdx].positions[0], scene.triangles[primitiveNdx].positions[1], scene.triangles[primitiveNdx].positions[2], corners[2]),
590 			calcTriangleInterpolationWeights(scene.triangles[primitiveNdx].positions[0], scene.triangles[primitiveNdx].positions[1], scene.triangles[primitiveNdx].positions[2], corners[3]),
591 		};
592 
593 		InterpolationRange result;
594 		result.min = tcu::min(tcu::min(weights[0].min, weights[1].min), tcu::min(weights[2].min, weights[3].min));
595 		result.max = tcu::max(tcu::max(weights[0].max, weights[1].max), tcu::max(weights[2].max, weights[3].max));
596 		return result;
597 	}
598 };
599 
600 /*--------------------------------------------------------------------*//*!
601  * Used only by verifyMultisampleLineGroupInterpolation to calculate
602  * correct line interpolations for the triangulated lines.
603  *//*--------------------------------------------------------------------*/
604 struct MultisampleLineInterpolator
605 {
606 	const LineSceneSpec& scene;
607 
MultisampleLineInterpolatortcu::__anon958de0670111::MultisampleLineInterpolator608 	MultisampleLineInterpolator (const LineSceneSpec& scene_)
609 		: scene(scene_)
610 	{
611 	}
612 
interpolatetcu::__anon958de0670111::MultisampleLineInterpolator613 	InterpolationRange interpolate (int primitiveNdx, const tcu::IVec2 pixel, const tcu::IVec2 viewportSize, bool multisample, int subpixelBits) const
614 	{
615 		DE_UNREF(multisample);
616 		DE_UNREF(subpixelBits);
617 
618 		// in triangulation, one line emits two triangles
619 		const int		lineNdx		= primitiveNdx / 2;
620 
621 		// allow interpolation weights anywhere in the pixel
622 		const tcu::Vec2 corners[4] =
623 		{
624 			tcu::Vec2((float)pixel.x() + 0.0f, (float)pixel.y() + 0.0f),
625 			tcu::Vec2((float)pixel.x() + 0.0f, (float)pixel.y() + 1.0f),
626 			tcu::Vec2((float)pixel.x() + 1.0f, (float)pixel.y() + 1.0f),
627 			tcu::Vec2((float)pixel.x() + 1.0f, (float)pixel.y() + 0.0f),
628 		};
629 
630 		const float		wa = scene.lines[lineNdx].positions[0].w();
631 		const float		wb = scene.lines[lineNdx].positions[1].w();
632 		const tcu::Vec2	pa = tcu::Vec2((scene.lines[lineNdx].positions[0].x() / wa + 1.0f) * 0.5f * (float)viewportSize.x(),
633 									   (scene.lines[lineNdx].positions[0].y() / wa + 1.0f) * 0.5f * (float)viewportSize.y());
634 		const tcu::Vec2	pb = tcu::Vec2((scene.lines[lineNdx].positions[1].x() / wb + 1.0f) * 0.5f * (float)viewportSize.x(),
635 									   (scene.lines[lineNdx].positions[1].y() / wb + 1.0f) * 0.5f * (float)viewportSize.y());
636 
637 		// calculate interpolation as a line
638 		const LineInterpolationRange weights[4] =
639 		{
640 			calcLineInterpolationWeights(pa, wa, pb, wb, corners[0]),
641 			calcLineInterpolationWeights(pa, wa, pb, wb, corners[1]),
642 			calcLineInterpolationWeights(pa, wa, pb, wb, corners[2]),
643 			calcLineInterpolationWeights(pa, wa, pb, wb, corners[3]),
644 		};
645 
646 		const tcu::Vec2 minWeights = tcu::min(tcu::min(weights[0].min, weights[1].min), tcu::min(weights[2].min, weights[3].min));
647 		const tcu::Vec2 maxWeights = tcu::max(tcu::max(weights[0].max, weights[1].max), tcu::max(weights[2].max, weights[3].max));
648 
649 		// convert to three-component form. For all triangles, the vertex 0 is always emitted by the line starting point, and vertex 2 by the ending point
650 		InterpolationRange result;
651 		result.min = tcu::Vec3(minWeights.x(), 0.0f, minWeights.y());
652 		result.max = tcu::Vec3(maxWeights.x(), 0.0f, maxWeights.y());
653 		return result;
654 	}
655 };
656 
657 template <typename Interpolator>
verifyTriangleGroupInterpolationWithInterpolator(const tcu::Surface & surface,const TriangleSceneSpec & scene,const RasterizationArguments & args,VerifyTriangleGroupInterpolationLogStash & logStash,const Interpolator & interpolator)658 bool verifyTriangleGroupInterpolationWithInterpolator (const tcu::Surface&							surface,
659 													   const TriangleSceneSpec&						scene,
660 													   const RasterizationArguments&				args,
661 													   VerifyTriangleGroupInterpolationLogStash&	logStash,
662 													   const Interpolator&							interpolator)
663 {
664 	const tcu::RGBA		invalidPixelColor	= tcu::RGBA(255, 0, 0, 255);
665 	const bool			multisampled		= (args.numSamples != 0);
666 	const tcu::IVec2	viewportSize		= tcu::IVec2(surface.getWidth(), surface.getHeight());
667 	const int			errorFloodThreshold	= 4;
668 	int					errorCount			= 0;
669 	int					invalidPixels		= 0;
670 	int					subPixelBits		= args.subpixelBits;
671 	tcu::Surface		errorMask			(surface.getWidth(), surface.getHeight());
672 
673 	tcu::clear(errorMask.getAccess(), tcu::Vec4(0.0f, 0.0f, 0.0f, 1.0f));
674 
675 	// log format
676 
677 	logStash.messages.push_back(std::string("Verifying rasterization result. Native format is RGB" + de::toString(args.redBits) + de::toString(args.greenBits) + de::toString(args.blueBits)));
678 	if (args.redBits > 8 || args.greenBits > 8 || args.blueBits > 8)
679 		logStash.messages.push_back(std::string("Warning! More than 8 bits in a color channel, this may produce false negatives."));
680 
681 	// subpixel bits in a valid range?
682 
683 	if (subPixelBits < 0)
684 	{
685 		logStash.messages.push_back(std::string("Invalid subpixel count (" + de::toString(subPixelBits) + "), assuming 0"));
686 		subPixelBits = 0;
687 	}
688 	else if (subPixelBits > 16)
689 	{
690 		// At high subpixel bit counts we might overflow. Checking at lower bit count is ok, but is less strict
691 		logStash.messages.push_back(std::string("Subpixel count is greater than 16 (" + de::toString(subPixelBits) + ")."
692 												" Checking results using less strict 16 bit requirements. This may produce false positives."));
693 		subPixelBits = 16;
694 	}
695 
696 	// check pixels
697 
698 	for (int y = 0; y < surface.getHeight(); ++y)
699 	for (int x = 0; x < surface.getWidth();  ++x)
700 	{
701 		const tcu::RGBA		color				= surface.getPixel(x, y);
702 		bool				stackBottomFound	= false;
703 		int					stackSize			= 0;
704 		tcu::Vec4			colorStackMin;
705 		tcu::Vec4			colorStackMax;
706 
707 		// Iterate triangle coverage front to back, find the stack of pontentially contributing fragments
708 		for (int triNdx = (int)scene.triangles.size() - 1; triNdx >= 0; --triNdx)
709 		{
710 			const CoverageType coverage = calculateTriangleCoverage(scene.triangles[triNdx].positions[0],
711 																	scene.triangles[triNdx].positions[1],
712 																	scene.triangles[triNdx].positions[2],
713 																	tcu::IVec2(x, y),
714 																	viewportSize,
715 																	subPixelBits,
716 																	multisampled);
717 
718 			if (coverage == COVERAGE_FULL || coverage == COVERAGE_PARTIAL)
719 			{
720 				// potentially contributes to the result fragment's value
721 				const InterpolationRange weights = interpolator.interpolate(triNdx, tcu::IVec2(x, y), viewportSize, multisampled, subPixelBits);
722 
723 				const tcu::Vec4 fragmentColorMax =	de::clamp(weights.max.x(), 0.0f, 1.0f) * scene.triangles[triNdx].colors[0] +
724 													de::clamp(weights.max.y(), 0.0f, 1.0f) * scene.triangles[triNdx].colors[1] +
725 													de::clamp(weights.max.z(), 0.0f, 1.0f) * scene.triangles[triNdx].colors[2];
726 				const tcu::Vec4 fragmentColorMin =	de::clamp(weights.min.x(), 0.0f, 1.0f) * scene.triangles[triNdx].colors[0] +
727 													de::clamp(weights.min.y(), 0.0f, 1.0f) * scene.triangles[triNdx].colors[1] +
728 													de::clamp(weights.min.z(), 0.0f, 1.0f) * scene.triangles[triNdx].colors[2];
729 
730 				if (stackSize++ == 0)
731 				{
732 					// first triangle, set the values properly
733 					colorStackMin = fragmentColorMin;
734 					colorStackMax = fragmentColorMax;
735 				}
736 				else
737 				{
738 					// contributing triangle
739 					colorStackMin = tcu::min(colorStackMin, fragmentColorMin);
740 					colorStackMax = tcu::max(colorStackMax, fragmentColorMax);
741 				}
742 
743 				if (coverage == COVERAGE_FULL)
744 				{
745 					// loop terminates, this is the bottommost fragment
746 					stackBottomFound = true;
747 					break;
748 				}
749 			}
750 		}
751 
752 		// Partial coverage == background may be visible
753 		if (stackSize != 0 && !stackBottomFound)
754 		{
755 			stackSize++;
756 			colorStackMin = tcu::Vec4(0.0f, 0.0f, 0.0f, 1.0f);
757 		}
758 
759 		// Is the result image color in the valid range.
760 		if (stackSize == 0)
761 		{
762 			// No coverage, allow only background (black, value=0)
763 			const tcu::IVec3	pixelNativeColor	= convertRGB8ToNativeFormat(color, args);
764 			const int			threshold			= 1;
765 
766 			if (pixelNativeColor.x() > threshold ||
767 				pixelNativeColor.y() > threshold ||
768 				pixelNativeColor.z() > threshold)
769 			{
770 				++errorCount;
771 
772 				// don't fill the logs with too much data
773 				if (errorCount < errorFloodThreshold)
774 				{
775 					std::ostringstream str;
776 
777 					str << "Found an invalid pixel at (" << x << "," << y << ")\n"
778 						<< "\tPixel color:\t\t" << color << "\n"
779 						<< "\tExpected background color.\n";
780 
781 					logStash.messages.push_back(str.str());
782 				}
783 
784 				++invalidPixels;
785 				errorMask.setPixel(x, y, invalidPixelColor);
786 			}
787 		}
788 		else
789 		{
790 			DE_ASSERT(stackSize);
791 
792 			// Each additional step in the stack may cause conversion error of 1 bit due to undefined rounding direction
793 			const int			thresholdRed	= stackSize - 1;
794 			const int			thresholdGreen	= stackSize - 1;
795 			const int			thresholdBlue	= stackSize - 1;
796 
797 			const tcu::Vec3		valueRangeMin	= tcu::Vec3(colorStackMin.xyz());
798 			const tcu::Vec3		valueRangeMax	= tcu::Vec3(colorStackMax.xyz());
799 
800 			const tcu::IVec3	formatLimit		((1 << args.redBits) - 1, (1 << args.greenBits) - 1, (1 << args.blueBits) - 1);
801 			const tcu::Vec3		colorMinF		(de::clamp(valueRangeMin.x() * (float)formatLimit.x(), 0.0f, (float)formatLimit.x()),
802 												 de::clamp(valueRangeMin.y() * (float)formatLimit.y(), 0.0f, (float)formatLimit.y()),
803 												 de::clamp(valueRangeMin.z() * (float)formatLimit.z(), 0.0f, (float)formatLimit.z()));
804 			const tcu::Vec3		colorMaxF		(de::clamp(valueRangeMax.x() * (float)formatLimit.x(), 0.0f, (float)formatLimit.x()),
805 												 de::clamp(valueRangeMax.y() * (float)formatLimit.y(), 0.0f, (float)formatLimit.y()),
806 												 de::clamp(valueRangeMax.z() * (float)formatLimit.z(), 0.0f, (float)formatLimit.z()));
807 			const tcu::IVec3	colorMin		((int)deFloatFloor(colorMinF.x()),
808 												 (int)deFloatFloor(colorMinF.y()),
809 												 (int)deFloatFloor(colorMinF.z()));
810 			const tcu::IVec3	colorMax		((int)deFloatCeil (colorMaxF.x()),
811 												 (int)deFloatCeil (colorMaxF.y()),
812 												 (int)deFloatCeil (colorMaxF.z()));
813 
814 			// Convert pixel color from rgba8 to the real pixel format. Usually rgba8 or 565
815 			const tcu::IVec3 pixelNativeColor = convertRGB8ToNativeFormat(color, args);
816 
817 			// Validity check
818 			if (pixelNativeColor.x() < colorMin.x() - thresholdRed   ||
819 				pixelNativeColor.y() < colorMin.y() - thresholdGreen ||
820 				pixelNativeColor.z() < colorMin.z() - thresholdBlue  ||
821 				pixelNativeColor.x() > colorMax.x() + thresholdRed   ||
822 				pixelNativeColor.y() > colorMax.y() + thresholdGreen ||
823 				pixelNativeColor.z() > colorMax.z() + thresholdBlue)
824 			{
825 				++errorCount;
826 
827 				// don't fill the logs with too much data
828 				if (errorCount <= errorFloodThreshold)
829 				{
830 					std::ostringstream str;
831 
832 					str << "Found an invalid pixel at (" << x << "," << y << ")\n"
833 						<< "\tPixel color:\t\t" << color << "\n"
834 						<< "\tNative color:\t\t" << pixelNativeColor << "\n"
835 						<< "\tAllowed error:\t\t" << tcu::IVec3(thresholdRed, thresholdGreen, thresholdBlue) << "\n"
836 						<< "\tReference native color min: " << tcu::clamp(colorMin - tcu::IVec3(thresholdRed, thresholdGreen, thresholdBlue), tcu::IVec3(0,0,0), formatLimit) << "\n"
837 						<< "\tReference native color max: " << tcu::clamp(colorMax + tcu::IVec3(thresholdRed, thresholdGreen, thresholdBlue), tcu::IVec3(0,0,0), formatLimit) << "\n"
838 						<< "\tReference native float min: " << tcu::clamp(colorMinF - tcu::IVec3(thresholdRed, thresholdGreen, thresholdBlue).cast<float>(), tcu::Vec3(0.0f, 0.0f, 0.0f), formatLimit.cast<float>()) << "\n"
839 						<< "\tReference native float max: " << tcu::clamp(colorMaxF + tcu::IVec3(thresholdRed, thresholdGreen, thresholdBlue).cast<float>(), tcu::Vec3(0.0f, 0.0f, 0.0f), formatLimit.cast<float>()) << "\n"
840 						<< "\tFmin:\t" << tcu::clamp(valueRangeMin, tcu::Vec3(0.0f, 0.0f, 0.0f), tcu::Vec3(1.0f, 1.0f, 1.0f)) << "\n"
841 						<< "\tFmax:\t" << tcu::clamp(valueRangeMax, tcu::Vec3(0.0f, 0.0f, 0.0f), tcu::Vec3(1.0f, 1.0f, 1.0f)) << "\n";
842 					logStash.messages.push_back(str.str());
843 				}
844 
845 				++invalidPixels;
846 				errorMask.setPixel(x, y, invalidPixelColor);
847 			}
848 		}
849 	}
850 
851 	// don't just hide failures
852 	if (errorCount > errorFloodThreshold)
853 		logStash.messages.push_back(std::string("Omitted " + de::toString(errorCount - errorFloodThreshold) + " pixel error description(s)."));
854 
855 	logStash.success		= (invalidPixels == 0);
856 	logStash.invalidPixels	= invalidPixels;
857 
858 	// report result
859 	if (!logStash.success)
860 		logStash.errorMask = errorMask;
861 
862 	return logStash.success;
863 }
864 
865 
calculateIntersectionParameter(const tcu::Vec2 line[2],float w,int componentNdx)866 float calculateIntersectionParameter (const tcu::Vec2 line[2], float w, int componentNdx)
867 {
868 	DE_ASSERT(componentNdx < 2);
869 	if (line[1][componentNdx] == line[0][componentNdx])
870 		return -1.0f;
871 
872 	return (w - line[0][componentNdx]) / (line[1][componentNdx] - line[0][componentNdx]);
873 }
874 
875 // Clips the given line with a ((-w, -w), (-w, w), (w, w), (w, -w)) rectangle
applyClippingBox(tcu::Vec2 line[2],float w)876 void applyClippingBox (tcu::Vec2 line[2], float w)
877 {
878 	for (int side = 0; side < 4; ++side)
879 	{
880 		const int	sign		= ((side / 2) * -2) + 1;
881 		const int	component	= side % 2;
882 		const float	t			= calculateIntersectionParameter(line, w * (float)sign, component);
883 
884 		if ((t > 0) && (t < 1))
885 		{
886 			const float newCoord	= t * line[1][1 - component] + (1 - t) * line[0][1 - component];
887 
888 			if (line[1][component] > (w * (float)sign))
889 			{
890 				line[1 - side / 2][component] = w * (float)sign;
891 				line[1 - side / 2][1 - component] = newCoord;
892 			}
893 			else
894 			{
895 				line[side / 2][component] = w * (float)sign;
896 				line[side / 2][1 - component] = newCoord;
897 			}
898 		}
899 	}
900 }
901 
902 enum ClipMode
903 {
904 	CLIPMODE_NO_CLIPPING = 0,
905 	CLIPMODE_USE_CLIPPING_BOX,
906 
907 	CLIPMODE_LAST
908 };
909 
verifyMultisampleLineGroupRasterization(const tcu::Surface & surface,const LineSceneSpec & scene,const RasterizationArguments & args,tcu::TestLog & log,ClipMode clipMode,VerifyTriangleGroupRasterizationLogStash * logStash,const bool vulkanLinesTest,const bool strictMode)910 bool verifyMultisampleLineGroupRasterization (const tcu::Surface&						surface,
911 											  const LineSceneSpec&						scene,
912 											  const RasterizationArguments&				args,
913 											  tcu::TestLog&								log,
914 											  ClipMode									clipMode,
915 											  VerifyTriangleGroupRasterizationLogStash*	logStash,
916 											  const bool								vulkanLinesTest,
917 											  const bool								strictMode)
918 {
919 	// Multisampled line == 2 triangles
920 
921 	const tcu::Vec2		viewportSize	= tcu::Vec2((float)surface.getWidth(), (float)surface.getHeight());
922 	const float			halfLineWidth	= scene.lineWidth * 0.5f;
923 	TriangleSceneSpec	triangleScene;
924 
925 	deUint32			stippleCounter	= 0;
926 	float				leftoverPhase	= 0.0f;
927 
928 	triangleScene.triangles.resize(2 * scene.lines.size());
929 	for (int lineNdx = 0; lineNdx < (int)scene.lines.size(); ++lineNdx)
930 	{
931 
932 		if (!scene.isStrip)
933 		{
934 			// reset stipple at the start of each line segment
935 			stippleCounter = 0;
936 			leftoverPhase = 0;
937 		}
938 
939 		// Transform to screen space, add pixel offsets, convert back to normalized device space, and test as triangles
940 		tcu::Vec2 lineNormalizedDeviceSpace[2] =
941 		{
942 			tcu::Vec2(scene.lines[lineNdx].positions[0].x() / scene.lines[lineNdx].positions[0].w(), scene.lines[lineNdx].positions[0].y() / scene.lines[lineNdx].positions[0].w()),
943 			tcu::Vec2(scene.lines[lineNdx].positions[1].x() / scene.lines[lineNdx].positions[1].w(), scene.lines[lineNdx].positions[1].y() / scene.lines[lineNdx].positions[1].w()),
944 		};
945 
946 		if (clipMode == CLIPMODE_USE_CLIPPING_BOX)
947 		{
948 			applyClippingBox(lineNormalizedDeviceSpace, 1.0f);
949 		}
950 
951 		const tcu::Vec2 lineScreenSpace[2] =
952 		{
953 			(lineNormalizedDeviceSpace[0] + tcu::Vec2(1.0f, 1.0f)) * 0.5f * viewportSize,
954 			(lineNormalizedDeviceSpace[1] + tcu::Vec2(1.0f, 1.0f)) * 0.5f * viewportSize,
955 		};
956 
957 		const tcu::Vec2 lineDir			= tcu::normalize(lineScreenSpace[1] - lineScreenSpace[0]);
958 		const tcu::Vec2 lineNormalDir	= strictMode ? tcu::Vec2(lineDir.y(), -lineDir.x())
959 										: isLineXMajor(lineScreenSpace[0], lineScreenSpace[1]) ? tcu::Vec2(0.0f, 1.0f)
960 										: tcu::Vec2(1.0f, 0.0f);
961 
962 		if (scene.stippleEnable)
963 		{
964 			float lineLength			= tcu::distance(lineScreenSpace[0], lineScreenSpace[1]);
965 			float lineOffset			= 0.0f;
966 
967 			while (lineOffset < lineLength)
968 			{
969 				float d0 = (float)lineOffset;
970 				float d1 = d0 + 1.0f;
971 
972 				// "leftoverPhase" carries over a fractional stipple phase that was "unused"
973 				// by the last line segment in the strip, if it wasn't an integer length.
974 				if (leftoverPhase > lineLength)
975 				{
976 					DE_ASSERT(d0 == 0.0f);
977 					d1 = lineLength;
978 					leftoverPhase -= lineLength;
979 				}
980 				else if (leftoverPhase != 0.0f)
981 				{
982 					DE_ASSERT(d0 == 0.0f);
983 					d1 = leftoverPhase;
984 					leftoverPhase = 0.0f;
985 				}
986 				else
987 				{
988 					if (d0 + 1.0f > lineLength)
989 					{
990 						d1 = lineLength;
991 						leftoverPhase = d0 + 1.0f - lineLength;
992 					}
993 					else
994 						d1 = d0 + 1.0f;
995 				}
996 
997 				// set offset for next iteration
998 				lineOffset = d1;
999 
1000 				int stippleBit = (stippleCounter / scene.stippleFactor) % 16;
1001 				bool stipplePass = (scene.stipplePattern & (1 << stippleBit)) != 0;
1002 
1003 				if (leftoverPhase == 0)
1004 					stippleCounter++;
1005 
1006 				if (!stipplePass)
1007 					continue;
1008 
1009 				d0 /= lineLength;
1010 				d1 /= lineLength;
1011 
1012 				tcu::Vec2 l0 = mix(lineScreenSpace[0], lineScreenSpace[1], d0);
1013 				tcu::Vec2 l1 = mix(lineScreenSpace[0], lineScreenSpace[1], d1);
1014 
1015 				const tcu::Vec2 lineQuadScreenSpace[4] =
1016 				{
1017 					l0 + lineNormalDir * halfLineWidth,
1018 					l0 - lineNormalDir * halfLineWidth,
1019 					l1 - lineNormalDir * halfLineWidth,
1020 					l1 + lineNormalDir * halfLineWidth,
1021 				};
1022 				const tcu::Vec2 lineQuadNormalizedDeviceSpace[4] =
1023 				{
1024 					lineQuadScreenSpace[0] / viewportSize * 2.0f - tcu::Vec2(1.0f, 1.0f),
1025 					lineQuadScreenSpace[1] / viewportSize * 2.0f - tcu::Vec2(1.0f, 1.0f),
1026 					lineQuadScreenSpace[2] / viewportSize * 2.0f - tcu::Vec2(1.0f, 1.0f),
1027 					lineQuadScreenSpace[3] / viewportSize * 2.0f - tcu::Vec2(1.0f, 1.0f),
1028 				};
1029 
1030 				TriangleSceneSpec::SceneTriangle tri;
1031 
1032 				tri.positions[0] = tcu::Vec4(lineQuadNormalizedDeviceSpace[0].x(), lineQuadNormalizedDeviceSpace[0].y(), 0.0f, 1.0f);	tri.sharedEdge[0] = (d0 != 0.0f);
1033 				tri.positions[1] = tcu::Vec4(lineQuadNormalizedDeviceSpace[1].x(), lineQuadNormalizedDeviceSpace[1].y(), 0.0f, 1.0f);	tri.sharedEdge[1] = false;
1034 				tri.positions[2] = tcu::Vec4(lineQuadNormalizedDeviceSpace[2].x(), lineQuadNormalizedDeviceSpace[2].y(), 0.0f, 1.0f);	tri.sharedEdge[2] = true;
1035 
1036 				triangleScene.triangles.push_back(tri);
1037 
1038 				tri.positions[0] = tcu::Vec4(lineQuadNormalizedDeviceSpace[0].x(), lineQuadNormalizedDeviceSpace[0].y(), 0.0f, 1.0f);	tri.sharedEdge[0] = true;
1039 				tri.positions[1] = tcu::Vec4(lineQuadNormalizedDeviceSpace[2].x(), lineQuadNormalizedDeviceSpace[2].y(), 0.0f, 1.0f);	tri.sharedEdge[1] = (d1 != 1.0f);
1040 				tri.positions[2] = tcu::Vec4(lineQuadNormalizedDeviceSpace[3].x(), lineQuadNormalizedDeviceSpace[3].y(), 0.0f, 1.0f);	tri.sharedEdge[2] = false;
1041 
1042 				triangleScene.triangles.push_back(tri);
1043 			}
1044 		}
1045 		else
1046 		{
1047 			const tcu::Vec2 lineQuadScreenSpace[4] =
1048 			{
1049 				lineScreenSpace[0] + lineNormalDir * halfLineWidth,
1050 				lineScreenSpace[0] - lineNormalDir * halfLineWidth,
1051 				lineScreenSpace[1] - lineNormalDir * halfLineWidth,
1052 				lineScreenSpace[1] + lineNormalDir * halfLineWidth,
1053 			};
1054 			const tcu::Vec2 lineQuadNormalizedDeviceSpace[4] =
1055 			{
1056 				lineQuadScreenSpace[0] / viewportSize * 2.0f - tcu::Vec2(1.0f, 1.0f),
1057 				lineQuadScreenSpace[1] / viewportSize * 2.0f - tcu::Vec2(1.0f, 1.0f),
1058 				lineQuadScreenSpace[2] / viewportSize * 2.0f - tcu::Vec2(1.0f, 1.0f),
1059 				lineQuadScreenSpace[3] / viewportSize * 2.0f - tcu::Vec2(1.0f, 1.0f),
1060 			};
1061 
1062 			triangleScene.triangles[lineNdx*2 + 0].positions[0] = tcu::Vec4(lineQuadNormalizedDeviceSpace[0].x(), lineQuadNormalizedDeviceSpace[0].y(), 0.0f, 1.0f);	triangleScene.triangles[lineNdx*2 + 0].sharedEdge[0] = false;
1063 			triangleScene.triangles[lineNdx*2 + 0].positions[1] = tcu::Vec4(lineQuadNormalizedDeviceSpace[1].x(), lineQuadNormalizedDeviceSpace[1].y(), 0.0f, 1.0f);	triangleScene.triangles[lineNdx*2 + 0].sharedEdge[1] = false;
1064 			triangleScene.triangles[lineNdx*2 + 0].positions[2] = tcu::Vec4(lineQuadNormalizedDeviceSpace[2].x(), lineQuadNormalizedDeviceSpace[2].y(), 0.0f, 1.0f);	triangleScene.triangles[lineNdx*2 + 0].sharedEdge[2] = true;
1065 
1066 			triangleScene.triangles[lineNdx*2 + 1].positions[0] = tcu::Vec4(lineQuadNormalizedDeviceSpace[0].x(), lineQuadNormalizedDeviceSpace[0].y(), 0.0f, 1.0f);	triangleScene.triangles[lineNdx*2 + 1].sharedEdge[0] = true;
1067 			triangleScene.triangles[lineNdx*2 + 1].positions[1] = tcu::Vec4(lineQuadNormalizedDeviceSpace[2].x(), lineQuadNormalizedDeviceSpace[2].y(), 0.0f, 1.0f);	triangleScene.triangles[lineNdx*2 + 1].sharedEdge[1] = false;
1068 			triangleScene.triangles[lineNdx*2 + 1].positions[2] = tcu::Vec4(lineQuadNormalizedDeviceSpace[3].x(), lineQuadNormalizedDeviceSpace[3].y(), 0.0f, 1.0f);	triangleScene.triangles[lineNdx*2 + 1].sharedEdge[2] = false;
1069 		}
1070 	}
1071 
1072 	if (logStash != DE_NULL)
1073 	{
1074 		logStash->messages.push_back("Rasterization clipping mode: " + std::string(clipMode == CLIPMODE_USE_CLIPPING_BOX ? "CLIPMODE_USE_CLIPPING_BOX" : "CLIPMODE_NO_CLIPPING") + ".");
1075 		logStash->messages.push_back("Rasterization line draw strictness mode: " + std::string(strictMode ? "strict" : "non-strict") + ".");
1076 	}
1077 
1078 	return verifyTriangleGroupRasterization(surface, triangleScene, args, log, scene.verificationMode, logStash, vulkanLinesTest);
1079 }
1080 
verifyMultisampleLineGroupInterpolationInternal(const tcu::Surface & surface,const LineSceneSpec & scene,const RasterizationArguments & args,VerifyTriangleGroupInterpolationLogStash & logStash,const bool strictMode)1081 static bool verifyMultisampleLineGroupInterpolationInternal (const tcu::Surface&						surface,
1082 													  const LineSceneSpec&						scene,
1083 													  const RasterizationArguments&				args,
1084 													  VerifyTriangleGroupInterpolationLogStash&	logStash,
1085 													  const bool								strictMode)
1086 {
1087 	// Multisampled line == 2 triangles
1088 
1089 	const tcu::Vec2		viewportSize	= tcu::Vec2((float)surface.getWidth(), (float)surface.getHeight());
1090 	const float			halfLineWidth	= scene.lineWidth * 0.5f;
1091 	TriangleSceneSpec	triangleScene;
1092 
1093 	triangleScene.triangles.resize(2 * scene.lines.size());
1094 	for (int lineNdx = 0; lineNdx < (int)scene.lines.size(); ++lineNdx)
1095 	{
1096 		// Need the w-coordinates a couple of times
1097 		const float		wa = scene.lines[lineNdx].positions[0].w();
1098 		const float		wb = scene.lines[lineNdx].positions[1].w();
1099 
1100 		// Transform to screen space, add pixel offsets, convert back to normalized device space, and test as triangles
1101 		const tcu::Vec2 lineNormalizedDeviceSpace[2] =
1102 		{
1103 			tcu::Vec2(scene.lines[lineNdx].positions[0].x() / wa, scene.lines[lineNdx].positions[0].y() / wa),
1104 			tcu::Vec2(scene.lines[lineNdx].positions[1].x() / wb, scene.lines[lineNdx].positions[1].y() / wb),
1105 		};
1106 		const tcu::Vec2 lineScreenSpace[2] =
1107 		{
1108 			(lineNormalizedDeviceSpace[0] + tcu::Vec2(1.0f, 1.0f)) * 0.5f * viewportSize,
1109 			(lineNormalizedDeviceSpace[1] + tcu::Vec2(1.0f, 1.0f)) * 0.5f * viewportSize,
1110 		};
1111 
1112 		const tcu::Vec2 lineDir			= tcu::normalize(lineScreenSpace[1] - lineScreenSpace[0]);
1113 		const tcu::Vec2 lineNormalDir	= strictMode ? tcu::Vec2(lineDir.y(), -lineDir.x())
1114 										: isLineXMajor(lineScreenSpace[0], lineScreenSpace[1]) ? tcu::Vec2(0.0f, 1.0f)
1115 										: tcu::Vec2(1.0f, 0.0f);
1116 
1117 		const tcu::Vec2 lineQuadScreenSpace[4] =
1118 		{
1119 			lineScreenSpace[0] + lineNormalDir * halfLineWidth,
1120 			lineScreenSpace[0] - lineNormalDir * halfLineWidth,
1121 			lineScreenSpace[1] - lineNormalDir * halfLineWidth,
1122 			lineScreenSpace[1] + lineNormalDir * halfLineWidth,
1123 		};
1124 		const tcu::Vec2 lineQuadNormalizedDeviceSpace[4] =
1125 		{
1126 			lineQuadScreenSpace[0] / viewportSize * 2.0f - tcu::Vec2(1.0f, 1.0f),
1127 			lineQuadScreenSpace[1] / viewportSize * 2.0f - tcu::Vec2(1.0f, 1.0f),
1128 			lineQuadScreenSpace[2] / viewportSize * 2.0f - tcu::Vec2(1.0f, 1.0f),
1129 			lineQuadScreenSpace[3] / viewportSize * 2.0f - tcu::Vec2(1.0f, 1.0f),
1130 		};
1131 
1132 		// Re-construct un-projected geometry using the quantised positions
1133 		const tcu::Vec4 lineQuadUnprojected[4] =
1134 		{
1135 			tcu::Vec4(lineQuadNormalizedDeviceSpace[0].x() * wa, lineQuadNormalizedDeviceSpace[0].y() * wa, 0.0f, wa),
1136 			tcu::Vec4(lineQuadNormalizedDeviceSpace[1].x() * wa, lineQuadNormalizedDeviceSpace[1].y() * wa, 0.0f, wa),
1137 			tcu::Vec4(lineQuadNormalizedDeviceSpace[2].x() * wb, lineQuadNormalizedDeviceSpace[2].y() * wb, 0.0f, wb),
1138 			tcu::Vec4(lineQuadNormalizedDeviceSpace[3].x() * wb, lineQuadNormalizedDeviceSpace[3].y() * wb, 0.0f, wb),
1139 		};
1140 
1141 		triangleScene.triangles[lineNdx*2 + 0].positions[0] = lineQuadUnprojected[0];
1142 		triangleScene.triangles[lineNdx*2 + 0].positions[1] = lineQuadUnprojected[1];
1143 		triangleScene.triangles[lineNdx*2 + 0].positions[2] = lineQuadUnprojected[2];
1144 
1145 		triangleScene.triangles[lineNdx*2 + 0].sharedEdge[0] = false;
1146 		triangleScene.triangles[lineNdx*2 + 0].sharedEdge[1] = false;
1147 		triangleScene.triangles[lineNdx*2 + 0].sharedEdge[2] = true;
1148 
1149 		triangleScene.triangles[lineNdx*2 + 0].colors[0] = scene.lines[lineNdx].colors[0];
1150 		triangleScene.triangles[lineNdx*2 + 0].colors[1] = scene.lines[lineNdx].colors[0];
1151 		triangleScene.triangles[lineNdx*2 + 0].colors[2] = scene.lines[lineNdx].colors[1];
1152 
1153 		triangleScene.triangles[lineNdx*2 + 1].positions[0] = lineQuadUnprojected[0];
1154 		triangleScene.triangles[lineNdx*2 + 1].positions[1] = lineQuadUnprojected[2];
1155 		triangleScene.triangles[lineNdx*2 + 1].positions[2] = lineQuadUnprojected[3];
1156 
1157 		triangleScene.triangles[lineNdx*2 + 1].sharedEdge[0] = true;
1158 		triangleScene.triangles[lineNdx*2 + 1].sharedEdge[1] = false;
1159 		triangleScene.triangles[lineNdx*2 + 1].sharedEdge[2] = false;
1160 
1161 		triangleScene.triangles[lineNdx*2 + 1].colors[0] = scene.lines[lineNdx].colors[0];
1162 		triangleScene.triangles[lineNdx*2 + 1].colors[1] = scene.lines[lineNdx].colors[1];
1163 		triangleScene.triangles[lineNdx*2 + 1].colors[2] = scene.lines[lineNdx].colors[1];
1164 	}
1165 
1166 	if (strictMode)
1167 	{
1168 		// Strict mode interpolation should be purely in the direction of the line-segment
1169 		logStash.messages.push_back("Verify using line interpolator");
1170 		return verifyTriangleGroupInterpolationWithInterpolator(surface, triangleScene, args, logStash, MultisampleLineInterpolator(scene));
1171 	}
1172 	else
1173 	{
1174 		// For non-strict lines some allowance needs to be inplace for a few different styles of implementation.
1175 		//
1176 		// Some implementations duplicate the attributes at the endpoints to the corners of the triangle
1177 		// deconstruted parallelogram. Gradients along the line will be seen to travel in the major axis,
1178 		// with values effectively duplicated in the minor axis direction. In other cases, implementations
1179 		// will use the original parameters of the line to calculate attribute interpolation so it will
1180 		// follow the direction of the line-segment.
1181 		logStash.messages.push_back("Verify using triangle interpolator");
1182 		if (!verifyTriangleGroupInterpolationWithInterpolator(surface, triangleScene, args, logStash, TriangleInterpolator(triangleScene)))
1183 		{
1184 			logStash.messages.push_back("Verify using line interpolator");
1185 			return verifyTriangleGroupInterpolationWithInterpolator(surface, triangleScene, args, logStash, MultisampleLineInterpolator(scene));
1186 		}
1187 		return true;
1188 	}
1189 }
1190 
logTriangleGroupnterpolationStash(const tcu::Surface & surface,tcu::TestLog & log,VerifyTriangleGroupInterpolationLogStash & logStash)1191 static void logTriangleGroupnterpolationStash (const tcu::Surface& surface, tcu::TestLog& log, VerifyTriangleGroupInterpolationLogStash& logStash)
1192 {
1193 	// Output results
1194 	log << tcu::TestLog::Message << "Verifying rasterization result." << tcu::TestLog::EndMessage;
1195 
1196 	for (size_t msgNdx = 0; msgNdx < logStash.messages.size(); ++msgNdx)
1197 		log << tcu::TestLog::Message << logStash.messages[msgNdx] << tcu::TestLog::EndMessage;
1198 
1199 	// report result
1200 	if (!logStash.success)
1201 	{
1202 		log << tcu::TestLog::Message << logStash.invalidPixels << " invalid pixel(s) found." << tcu::TestLog::EndMessage;
1203 		log << tcu::TestLog::ImageSet("Verification result", "Result of rendering")
1204 			<< tcu::TestLog::Image("Result", "Result",			surface)
1205 			<< tcu::TestLog::Image("ErrorMask", "ErrorMask",	logStash.errorMask)
1206 			<< tcu::TestLog::EndImageSet;
1207 	}
1208 	else
1209 	{
1210 		log << tcu::TestLog::Message << "No invalid pixels found." << tcu::TestLog::EndMessage;
1211 		log << tcu::TestLog::ImageSet("Verification result", "Result of rendering")
1212 			<< tcu::TestLog::Image("Result", "Result", surface)
1213 			<< tcu::TestLog::EndImageSet;
1214 	}
1215 }
1216 
verifyMultisampleLineGroupInterpolation(const tcu::Surface & surface,const LineSceneSpec & scene,const RasterizationArguments & args,tcu::TestLog & log,const bool strictMode=true,const bool allowBresenhamForNonStrictLines=false)1217 static bool verifyMultisampleLineGroupInterpolation (const tcu::Surface&			surface,
1218 													 const LineSceneSpec&			scene,
1219 													 const RasterizationArguments&	args,
1220 													 tcu::TestLog&					log,
1221 													 const bool						strictMode = true,
1222 													 const bool						allowBresenhamForNonStrictLines = false)
1223 {
1224 	bool										result					= false;
1225 	VerifyTriangleGroupInterpolationLogStash	nonStrictModeLogStash;
1226 	VerifyTriangleGroupInterpolationLogStash	strictModeLogStash;
1227 
1228 	nonStrictModeLogStash.messages.push_back("Non-strict line draw mode.");
1229 	strictModeLogStash.messages.push_back("Strict mode line draw mode.");
1230 
1231 	if (strictMode)
1232 	{
1233 		result = verifyMultisampleLineGroupInterpolationInternal(surface,scene, args, strictModeLogStash, strictMode);
1234 
1235 		logTriangleGroupnterpolationStash(surface, log, strictModeLogStash);
1236 	}
1237 	else
1238 	{
1239 		if (verifyMultisampleLineGroupInterpolationInternal(surface,scene, args, nonStrictModeLogStash, false))
1240 		{
1241 			logTriangleGroupnterpolationStash(surface, log, nonStrictModeLogStash);
1242 
1243 			result	= true;
1244 		}
1245 		else if (verifyMultisampleLineGroupInterpolationInternal(surface,scene, args, strictModeLogStash, true))
1246 		{
1247 			logTriangleGroupnterpolationStash(surface, log, strictModeLogStash);
1248 
1249 			result	= true;
1250 		}
1251 		else
1252 		{
1253 			logTriangleGroupnterpolationStash(surface, log, nonStrictModeLogStash);
1254 			logTriangleGroupnterpolationStash(surface, log, strictModeLogStash);
1255 		}
1256 
1257 		// In the non-strict line case, bresenham is also permissable, though not specified. This is due
1258 		// to a change in how lines are specified in Vulkan versus GLES; in GLES bresenham lines using the
1259 		// diamond-exit rule were the preferred way to draw single pixel non-antialiased lines, and not all
1260 		// GLES implementations are able to disable this behaviour.
1261 		if (result == false)
1262 		{
1263 			log << tcu::TestLog::Message << "Checking line rasterisation using verifySinglesampleNarrowLineGroupInterpolation for nonStrict lines" << tcu::TestLog::EndMessage;
1264 			if (args.numSamples <= 1 &&
1265 				allowBresenhamForNonStrictLines &&
1266 				verifyLineGroupInterpolationWithProjectedWeights(surface, scene, args, log))
1267 			{
1268 				log << tcu::TestLog::Message << "verifySinglesampleNarrowLineGroupInterpolation for nonStrict lines Passed" << tcu::TestLog::EndMessage;
1269 
1270 				result	= true;
1271 			}
1272 		}
1273 
1274 	}
1275 
1276 	return result;
1277 }
1278 
verifyMultisamplePointGroupRasterization(const tcu::Surface & surface,const PointSceneSpec & scene,const RasterizationArguments & args,tcu::TestLog & log)1279 bool verifyMultisamplePointGroupRasterization (const tcu::Surface& surface, const PointSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log)
1280 {
1281 	// Multisampled point == 2 triangles
1282 
1283 	const tcu::Vec2		viewportSize	= tcu::Vec2((float)surface.getWidth(), (float)surface.getHeight());
1284 	TriangleSceneSpec	triangleScene;
1285 
1286 	triangleScene.triangles.resize(2 * scene.points.size());
1287 	for (int pointNdx = 0; pointNdx < (int)scene.points.size(); ++pointNdx)
1288 	{
1289 		// Transform to screen space, add pixel offsets, convert back to normalized device space, and test as triangles
1290 		const tcu::Vec2	pointNormalizedDeviceSpace			= tcu::Vec2(scene.points[pointNdx].position.x() / scene.points[pointNdx].position.w(), scene.points[pointNdx].position.y() / scene.points[pointNdx].position.w());
1291 		const tcu::Vec2	pointScreenSpace					= (pointNormalizedDeviceSpace + tcu::Vec2(1.0f, 1.0f)) * 0.5f * viewportSize;
1292 		const float		offset								= scene.points[pointNdx].pointSize * 0.5f;
1293 		const tcu::Vec2	lineQuadNormalizedDeviceSpace[4]	=
1294 		{
1295 			(pointScreenSpace + tcu::Vec2(-offset, -offset))/ viewportSize * 2.0f - tcu::Vec2(1.0f, 1.0f),
1296 			(pointScreenSpace + tcu::Vec2(-offset,  offset))/ viewportSize * 2.0f - tcu::Vec2(1.0f, 1.0f),
1297 			(pointScreenSpace + tcu::Vec2( offset,  offset))/ viewportSize * 2.0f - tcu::Vec2(1.0f, 1.0f),
1298 			(pointScreenSpace + tcu::Vec2( offset, -offset))/ viewportSize * 2.0f - tcu::Vec2(1.0f, 1.0f),
1299 		};
1300 
1301 		triangleScene.triangles[pointNdx*2 + 0].positions[0] = tcu::Vec4(lineQuadNormalizedDeviceSpace[0].x(), lineQuadNormalizedDeviceSpace[0].y(), 0.0f, 1.0f);	triangleScene.triangles[pointNdx*2 + 0].sharedEdge[0] = false;
1302 		triangleScene.triangles[pointNdx*2 + 0].positions[1] = tcu::Vec4(lineQuadNormalizedDeviceSpace[1].x(), lineQuadNormalizedDeviceSpace[1].y(), 0.0f, 1.0f);	triangleScene.triangles[pointNdx*2 + 0].sharedEdge[1] = false;
1303 		triangleScene.triangles[pointNdx*2 + 0].positions[2] = tcu::Vec4(lineQuadNormalizedDeviceSpace[2].x(), lineQuadNormalizedDeviceSpace[2].y(), 0.0f, 1.0f);	triangleScene.triangles[pointNdx*2 + 0].sharedEdge[2] = true;
1304 
1305 		triangleScene.triangles[pointNdx*2 + 1].positions[0] = tcu::Vec4(lineQuadNormalizedDeviceSpace[0].x(), lineQuadNormalizedDeviceSpace[0].y(), 0.0f, 1.0f);	triangleScene.triangles[pointNdx*2 + 1].sharedEdge[0] = true;
1306 		triangleScene.triangles[pointNdx*2 + 1].positions[1] = tcu::Vec4(lineQuadNormalizedDeviceSpace[2].x(), lineQuadNormalizedDeviceSpace[2].y(), 0.0f, 1.0f);	triangleScene.triangles[pointNdx*2 + 1].sharedEdge[1] = false;
1307 		triangleScene.triangles[pointNdx*2 + 1].positions[2] = tcu::Vec4(lineQuadNormalizedDeviceSpace[3].x(), lineQuadNormalizedDeviceSpace[3].y(), 0.0f, 1.0f);	triangleScene.triangles[pointNdx*2 + 1].sharedEdge[2] = false;
1308 	}
1309 
1310 	return verifyTriangleGroupRasterization(surface, triangleScene, args, log);
1311 }
1312 
genScreenSpaceLines(std::vector<tcu::Vec4> & screenspaceLines,const std::vector<LineSceneSpec::SceneLine> & lines,const tcu::IVec2 & viewportSize)1313 void genScreenSpaceLines (std::vector<tcu::Vec4>& screenspaceLines, const std::vector<LineSceneSpec::SceneLine>& lines, const tcu::IVec2& viewportSize)
1314 {
1315 	DE_ASSERT(screenspaceLines.size() == lines.size());
1316 
1317 	for (int lineNdx = 0; lineNdx < (int)lines.size(); ++lineNdx)
1318 	{
1319 		const tcu::Vec2 lineNormalizedDeviceSpace[2] =
1320 		{
1321 			tcu::Vec2(lines[lineNdx].positions[0].x() / lines[lineNdx].positions[0].w(), lines[lineNdx].positions[0].y() / lines[lineNdx].positions[0].w()),
1322 			tcu::Vec2(lines[lineNdx].positions[1].x() / lines[lineNdx].positions[1].w(), lines[lineNdx].positions[1].y() / lines[lineNdx].positions[1].w()),
1323 		};
1324 		const tcu::Vec4 lineScreenSpace[2] =
1325 		{
1326 			tcu::Vec4((lineNormalizedDeviceSpace[0].x() + 1.0f) * 0.5f * (float)viewportSize.x(), (lineNormalizedDeviceSpace[0].y() + 1.0f) * 0.5f * (float)viewportSize.y(), 0.0f, 1.0f),
1327 			tcu::Vec4((lineNormalizedDeviceSpace[1].x() + 1.0f) * 0.5f * (float)viewportSize.x(), (lineNormalizedDeviceSpace[1].y() + 1.0f) * 0.5f * (float)viewportSize.y(), 0.0f, 1.0f),
1328 		};
1329 
1330 		screenspaceLines[lineNdx] = tcu::Vec4(lineScreenSpace[0].x(), lineScreenSpace[0].y(), lineScreenSpace[1].x(), lineScreenSpace[1].y());
1331 	}
1332 }
1333 
verifySinglesampleLineGroupRasterization(const tcu::Surface & surface,const LineSceneSpec & scene,const RasterizationArguments & args,tcu::TestLog & log)1334 bool verifySinglesampleLineGroupRasterization (const tcu::Surface& surface, const LineSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log)
1335 {
1336 	DE_ASSERT(deFloatFrac(scene.lineWidth) != 0.5f); // rounding direction is not defined, disallow undefined cases
1337 	DE_ASSERT(scene.lines.size() < 255); // indices are stored as unsigned 8-bit ints
1338 
1339 	bool					allOK				= true;
1340 	bool					overdrawInReference	= false;
1341 	int						referenceFragments	= 0;
1342 	int						resultFragments		= 0;
1343 	int						lineWidth			= deFloorFloatToInt32(scene.lineWidth + 0.5f);
1344 	std::vector<bool>		lineIsXMajor		(scene.lines.size());
1345 	std::vector<tcu::Vec4>	screenspaceLines(scene.lines.size());
1346 
1347 	// Reference renderer produces correct fragments using the diamond-rule. Make 2D int array, each cell contains the highest index (first index = 1) of the overlapping lines or 0 if no line intersects the pixel
1348 	tcu::TextureLevel referenceLineMap(tcu::TextureFormat(tcu::TextureFormat::R, tcu::TextureFormat::UNSIGNED_INT8), surface.getWidth(), surface.getHeight());
1349 	tcu::clear(referenceLineMap.getAccess(), tcu::IVec4(0, 0, 0, 0));
1350 
1351 	genScreenSpaceLines(screenspaceLines, scene.lines, tcu::IVec2(surface.getWidth(), surface.getHeight()));
1352 
1353 	rr::SingleSampleLineRasterizer rasterizer(tcu::IVec4(0, 0, surface.getWidth(), surface.getHeight()), args.subpixelBits);
1354 	for (int lineNdx = 0; lineNdx < (int)scene.lines.size(); ++lineNdx)
1355 	{
1356 		rasterizer.init(tcu::Vec4(screenspaceLines[lineNdx][0],
1357 								  screenspaceLines[lineNdx][1],
1358 								  0.0f,
1359 								  1.0f),
1360 						tcu::Vec4(screenspaceLines[lineNdx][2],
1361 								  screenspaceLines[lineNdx][3],
1362 								  0.0f,
1363 								  1.0f),
1364 						scene.lineWidth,
1365 						scene.stippleFactor,
1366 						scene.stipplePattern);
1367 
1368 		if (!scene.isStrip)
1369 			rasterizer.resetStipple();
1370 
1371 		// calculate majority of later use
1372 		lineIsXMajor[lineNdx] = isPackedSSLineXMajor(screenspaceLines[lineNdx]);
1373 
1374 		for (;;)
1375 		{
1376 			const int			maxPackets			= 32;
1377 			int					numRasterized		= 0;
1378 			rr::FragmentPacket	packets[maxPackets];
1379 
1380 			rasterizer.rasterize(packets, DE_NULL, maxPackets, numRasterized);
1381 
1382 			for (int packetNdx = 0; packetNdx < numRasterized; ++packetNdx)
1383 			{
1384 				for (int fragNdx = 0; fragNdx < 4; ++fragNdx)
1385 				{
1386 					if ((deUint32)packets[packetNdx].coverage & (1 << fragNdx))
1387 					{
1388 						const tcu::IVec2 fragPos = packets[packetNdx].position + tcu::IVec2(fragNdx%2, fragNdx/2);
1389 
1390 						// Check for overdraw
1391 						if (!overdrawInReference)
1392 							overdrawInReference = referenceLineMap.getAccess().getPixelInt(fragPos.x(), fragPos.y()).x() != 0;
1393 
1394 						// Output pixel
1395 						referenceLineMap.getAccess().setPixel(tcu::IVec4(lineNdx + 1, 0, 0, 0), fragPos.x(), fragPos.y());
1396 					}
1397 				}
1398 			}
1399 
1400 			if (numRasterized != maxPackets)
1401 				break;
1402 		}
1403 	}
1404 
1405 	// Requirement 1: The coordinates of a fragment produced by the algorithm may not deviate by more than one unit
1406 	{
1407 		tcu::Surface	errorMask			(surface.getWidth(), surface.getHeight());
1408 		bool			missingFragments	= false;
1409 
1410 		tcu::clear(errorMask.getAccess(), tcu::IVec4(0, 255, 0, 255));
1411 
1412 		log << tcu::TestLog::Message << "Searching for deviating fragments." << tcu::TestLog::EndMessage;
1413 
1414 		for (int y = 0; y < referenceLineMap.getHeight(); ++y)
1415 		for (int x = 0; x < referenceLineMap.getWidth(); ++x)
1416 		{
1417 			const bool reference	= referenceLineMap.getAccess().getPixelInt(x, y).x() != 0;
1418 			const bool result		= compareColors(surface.getPixel(x, y), tcu::RGBA::white(), args.redBits, args.greenBits, args.blueBits);
1419 
1420 			if (reference)
1421 				++referenceFragments;
1422 			if (result)
1423 				++resultFragments;
1424 
1425 			if (reference == result)
1426 				continue;
1427 
1428 			// Reference fragment here, matching result fragment must be nearby
1429 			if (reference && !result)
1430 			{
1431 				bool foundFragment = false;
1432 
1433 				if (x == 0 || y == 0 || x == referenceLineMap.getWidth() - 1 || y == referenceLineMap.getHeight() -1)
1434 				{
1435 					// image boundary, missing fragment could be over the image edge
1436 					foundFragment = true;
1437 				}
1438 
1439 				// find nearby fragment
1440 				for (int dy = -1; dy < 2 && !foundFragment; ++dy)
1441 				for (int dx = -1; dx < 2 && !foundFragment; ++dx)
1442 				{
1443 					if (compareColors(surface.getPixel(x+dx, y+dy), tcu::RGBA::white(), args.redBits, args.greenBits, args.blueBits))
1444 						foundFragment = true;
1445 				}
1446 
1447 				if (!foundFragment)
1448 				{
1449 					missingFragments = true;
1450 					errorMask.setPixel(x, y, tcu::RGBA::red());
1451 				}
1452 			}
1453 		}
1454 
1455 		if (missingFragments)
1456 		{
1457 
1458 			allOK = false;
1459 		}
1460 		else
1461 		{
1462 			log << tcu::TestLog::Message << "No invalid deviations found." << tcu::TestLog::EndMessage;
1463 		}
1464 	}
1465 
1466 	// Requirement 2: The total number of fragments produced by the algorithm may differ from
1467 	//                that produced by the diamond-exit rule by no more than one.
1468 	{
1469 		// Check is not valid if the primitives intersect or otherwise share same fragments
1470 		if (!overdrawInReference)
1471 		{
1472 			int allowedDeviation = (int)scene.lines.size() * lineWidth; // one pixel per primitive in the major direction
1473 
1474 			log << tcu::TestLog::Message << "Verifying fragment counts:\n"
1475 				<< "\tDiamond-exit rule: " << referenceFragments << " fragments.\n"
1476 				<< "\tResult image: " << resultFragments << " fragments.\n"
1477 				<< "\tAllowing deviation of " << allowedDeviation << " fragments.\n"
1478 				<< tcu::TestLog::EndMessage;
1479 
1480 			if (deAbs32(referenceFragments - resultFragments) > allowedDeviation)
1481 			{
1482 				tcu::Surface reference(surface.getWidth(), surface.getHeight());
1483 
1484 				// show a helpful reference image
1485 				tcu::clear(reference.getAccess(), tcu::IVec4(0, 0, 0, 255));
1486 				for (int y = 0; y < surface.getHeight(); ++y)
1487 				for (int x = 0; x < surface.getWidth(); ++x)
1488 					if (referenceLineMap.getAccess().getPixelInt(x, y).x())
1489 						reference.setPixel(x, y, tcu::RGBA::white());
1490 
1491 				log << tcu::TestLog::Message << "Invalid fragment count in result image." << tcu::TestLog::EndMessage;
1492 				log << tcu::TestLog::ImageSet("Verification result", "Result of rendering")
1493 					<< tcu::TestLog::Image("Reference", "Reference",	reference)
1494 					<< tcu::TestLog::Image("Result", "Result",			surface)
1495 					<< tcu::TestLog::EndImageSet;
1496 
1497 				allOK = false;
1498 			}
1499 			else
1500 			{
1501 				log << tcu::TestLog::Message << "Fragment count is valid." << tcu::TestLog::EndMessage;
1502 			}
1503 		}
1504 		else
1505 		{
1506 			log << tcu::TestLog::Message << "Overdraw in scene. Fragment count cannot be verified. Skipping fragment count checks." << tcu::TestLog::EndMessage;
1507 		}
1508 	}
1509 
1510 	// Requirement 3: Line width must be constant
1511 	{
1512 		bool invalidWidthFound = false;
1513 
1514 		log << tcu::TestLog::Message << "Verifying line widths of the x-major lines." << tcu::TestLog::EndMessage;
1515 		for (int y = 1; y < referenceLineMap.getHeight() - 1; ++y)
1516 		{
1517 			bool	fullyVisibleLine		= false;
1518 			bool	previousPixelUndefined	= false;
1519 			int		currentLine				= 0;
1520 			int		currentWidth			= 1;
1521 
1522 			for (int x = 1; x < referenceLineMap.getWidth() - 1; ++x)
1523 			{
1524 				const bool	result	= compareColors(surface.getPixel(x, y), tcu::RGBA::white(), args.redBits, args.greenBits, args.blueBits);
1525 				int			lineID	= 0;
1526 
1527 				// Which line does this fragment belong to?
1528 
1529 				if (result)
1530 				{
1531 					bool multipleNearbyLines = false;
1532 					bool renderAtSurfaceEdge = false;
1533 
1534 					renderAtSurfaceEdge = (x == 1) || (x == referenceLineMap.getWidth() - 2);
1535 
1536 					for (int dy = -1; dy < 2; ++dy)
1537 					for (int dx = -1; dx < 2; ++dx)
1538 					{
1539 						const int nearbyID = referenceLineMap.getAccess().getPixelInt(x+dx, y+dy).x();
1540 						if (nearbyID)
1541 						{
1542 							if (lineID && lineID != nearbyID)
1543 								multipleNearbyLines = true;
1544 						}
1545 					}
1546 
1547 					if (multipleNearbyLines || renderAtSurfaceEdge)
1548 					{
1549 						// Another line is too close, don't try to calculate width here
1550 						// Or the render result is outside of surface range
1551 						previousPixelUndefined = true;
1552 						continue;
1553 					}
1554 				}
1555 
1556 				// Only line with id of lineID is nearby
1557 
1558 				if (previousPixelUndefined)
1559 				{
1560 					// The line might have been overdrawn or not
1561 					currentLine = lineID;
1562 					currentWidth = 1;
1563 					fullyVisibleLine = false;
1564 					previousPixelUndefined = false;
1565 				}
1566 				else if (lineID == currentLine)
1567 				{
1568 					// Current line continues
1569 					++currentWidth;
1570 				}
1571 				else if (lineID > currentLine)
1572 				{
1573 					// Another line was drawn over or the line ends
1574 					currentLine = lineID;
1575 					currentWidth = 1;
1576 					fullyVisibleLine = true;
1577 				}
1578 				else
1579 				{
1580 					// The line ends
1581 					if (fullyVisibleLine && !lineIsXMajor[currentLine-1])
1582 					{
1583 						// check width
1584 						if (currentWidth != lineWidth)
1585 						{
1586 							log << tcu::TestLog::Message << "\tInvalid line width at (" << x - currentWidth << ", " << y << ") - (" << x - 1 << ", " << y << "). Detected width of " << currentWidth << ", expected " << lineWidth << tcu::TestLog::EndMessage;
1587 							invalidWidthFound = true;
1588 						}
1589 					}
1590 
1591 					currentLine = lineID;
1592 					currentWidth = 1;
1593 					fullyVisibleLine = false;
1594 				}
1595 			}
1596 		}
1597 
1598 		log << tcu::TestLog::Message << "Verifying line widths of the y-major lines." << tcu::TestLog::EndMessage;
1599 		for (int x = 1; x < referenceLineMap.getWidth() - 1; ++x)
1600 		{
1601 			bool	fullyVisibleLine		= false;
1602 			bool	previousPixelUndefined	= false;
1603 			int		currentLine				= 0;
1604 			int		currentWidth			= 1;
1605 
1606 			for (int y = 1; y < referenceLineMap.getHeight() - 1; ++y)
1607 			{
1608 				const bool	result	= compareColors(surface.getPixel(x, y), tcu::RGBA::white(), args.redBits, args.greenBits, args.blueBits);
1609 				int			lineID	= 0;
1610 
1611 				// Which line does this fragment belong to?
1612 
1613 				if (result)
1614 				{
1615 					bool multipleNearbyLines = false;
1616 					bool renderAtSurfaceEdge = false;
1617 
1618 					renderAtSurfaceEdge = (y == 1) || (y == referenceLineMap.getWidth() - 2);
1619 
1620 					for (int dy = -1; dy < 2; ++dy)
1621 					for (int dx = -1; dx < 2; ++dx)
1622 					{
1623 						const int nearbyID = referenceLineMap.getAccess().getPixelInt(x+dx, y+dy).x();
1624 						if (nearbyID)
1625 						{
1626 							if (lineID && lineID != nearbyID)
1627 								multipleNearbyLines = true;
1628 							lineID = nearbyID;
1629 						}
1630 					}
1631 
1632 					if (multipleNearbyLines || renderAtSurfaceEdge)
1633 					{
1634 						// Another line is too close, don't try to calculate width here
1635 						// Or the render result is outside of surface range
1636 						previousPixelUndefined = true;
1637 						continue;
1638 					}
1639 				}
1640 
1641 				// Only line with id of lineID is nearby
1642 
1643 				if (previousPixelUndefined)
1644 				{
1645 					// The line might have been overdrawn or not
1646 					currentLine = lineID;
1647 					currentWidth = 1;
1648 					fullyVisibleLine = false;
1649 					previousPixelUndefined = false;
1650 				}
1651 				else if (lineID == currentLine)
1652 				{
1653 					// Current line continues
1654 					++currentWidth;
1655 				}
1656 				else if (lineID > currentLine)
1657 				{
1658 					// Another line was drawn over or the line ends
1659 					currentLine = lineID;
1660 					currentWidth = 1;
1661 					fullyVisibleLine = true;
1662 				}
1663 				else
1664 				{
1665 					// The line ends
1666 					if (fullyVisibleLine && lineIsXMajor[currentLine-1])
1667 					{
1668 						// check width
1669 						if (currentWidth != lineWidth)
1670 						{
1671 							log << tcu::TestLog::Message << "\tInvalid line width at (" << x << ", " << y - currentWidth << ") - (" << x  << ", " << y - 1 << "). Detected width of " << currentWidth << ", expected " << lineWidth << tcu::TestLog::EndMessage;
1672 							invalidWidthFound = true;
1673 						}
1674 					}
1675 
1676 					currentLine = lineID;
1677 					currentWidth = 1;
1678 					fullyVisibleLine = false;
1679 				}
1680 			}
1681 		}
1682 
1683 		if (invalidWidthFound)
1684 		{
1685 			log << tcu::TestLog::Message << "Invalid line width found, image is not valid." << tcu::TestLog::EndMessage;
1686 			allOK = false;
1687 		}
1688 		else
1689 		{
1690 			log << tcu::TestLog::Message << "Line widths are valid." << tcu::TestLog::EndMessage;
1691 		}
1692 	}
1693 
1694 	//\todo [2013-10-24 jarkko].
1695 	//Requirement 4. If two line segments share a common endpoint, and both segments are either
1696 	//x-major (both left-to-right or both right-to-left) or y-major (both bottom-totop
1697 	//or both top-to-bottom), then rasterizing both segments may not produce
1698 	//duplicate fragments, nor may any fragments be omitted so as to interrupt
1699 	//continuity of the connected segments.
1700 
1701 	{
1702 		tcu::Surface reference(surface.getWidth(), surface.getHeight());
1703 		tcu::clear(reference.getAccess(), tcu::IVec4(0, 0, 0, 255));
1704 		for (int y = 0; y < surface.getHeight(); ++y)
1705 		for (int x = 0; x < surface.getWidth(); ++x)
1706 			if (referenceLineMap.getAccess().getPixelInt(x, y).x())
1707 				reference.setPixel(x, y, tcu::RGBA::white());
1708 		log << tcu::TestLog::Message << "Invalid fragment count in result image." << tcu::TestLog::EndMessage;
1709 		log << tcu::TestLog::ImageSet("Verification result", "Result of rendering")
1710 			<< tcu::TestLog::Image("Reference", "Reference",	reference)
1711 			<< tcu::TestLog::Image("Result", "Result", surface)
1712 			<< tcu::TestLog::EndImageSet;
1713 	}
1714 
1715 	return allOK;
1716 }
1717 
1718 struct SingleSampleNarrowLineCandidate
1719 {
1720 	int			lineNdx;
1721 	tcu::IVec3	colorMin;
1722 	tcu::IVec3	colorMax;
1723 	tcu::Vec3	colorMinF;
1724 	tcu::Vec3	colorMaxF;
1725 	tcu::Vec3	valueRangeMin;
1726 	tcu::Vec3	valueRangeMax;
1727 };
1728 
setMaskMapCoverageBitForLine(int bitNdx,const tcu::Vec2 & screenSpaceP0,const tcu::Vec2 & screenSpaceP1,float lineWidth,tcu::PixelBufferAccess maskMap,const int subpixelBits)1729 void setMaskMapCoverageBitForLine (int bitNdx, const tcu::Vec2& screenSpaceP0, const tcu::Vec2& screenSpaceP1, float lineWidth, tcu::PixelBufferAccess maskMap, const int subpixelBits)
1730 {
1731 	enum
1732 	{
1733 		MAX_PACKETS = 32,
1734 	};
1735 
1736 	rr::SingleSampleLineRasterizer	rasterizer				(tcu::IVec4(0, 0, maskMap.getWidth(), maskMap.getHeight()), subpixelBits);
1737 	int								numRasterized			= MAX_PACKETS;
1738 	rr::FragmentPacket				packets[MAX_PACKETS];
1739 
1740 	rasterizer.init(tcu::Vec4(screenSpaceP0.x(), screenSpaceP0.y(), 0.0f, 1.0f),
1741 					tcu::Vec4(screenSpaceP1.x(), screenSpaceP1.y(), 0.0f, 1.0f),
1742 					lineWidth,
1743 					1, 0xFFFF);
1744 
1745 	while (numRasterized == MAX_PACKETS)
1746 	{
1747 		rasterizer.rasterize(packets, DE_NULL, MAX_PACKETS, numRasterized);
1748 
1749 		for (int packetNdx = 0; packetNdx < numRasterized; ++packetNdx)
1750 		{
1751 			for (int fragNdx = 0; fragNdx < 4; ++fragNdx)
1752 			{
1753 				if ((deUint32)packets[packetNdx].coverage & (1 << fragNdx))
1754 				{
1755 					const tcu::IVec2	fragPos			= packets[packetNdx].position + tcu::IVec2(fragNdx%2, fragNdx/2);
1756 
1757 					DE_ASSERT(deInBounds32(fragPos.x(), 0, maskMap.getWidth()));
1758 					DE_ASSERT(deInBounds32(fragPos.y(), 0, maskMap.getHeight()));
1759 
1760 					const deUint32		previousMask	= maskMap.getPixelUint(fragPos.x(), fragPos.y()).x();
1761 					const deUint32		newMask			= (previousMask) | ((deUint32)1u << bitNdx);
1762 
1763 					maskMap.setPixel(tcu::UVec4(newMask, 0, 0, 0), fragPos.x(), fragPos.y());
1764 				}
1765 			}
1766 		}
1767 	}
1768 }
1769 
setMaskMapCoverageBitForLines(const std::vector<tcu::Vec4> & screenspaceLines,float lineWidth,tcu::PixelBufferAccess maskMap,const int subpixelBits)1770 void setMaskMapCoverageBitForLines (const std::vector<tcu::Vec4>& screenspaceLines, float lineWidth, tcu::PixelBufferAccess maskMap, const int subpixelBits)
1771 {
1772 	for (int lineNdx = 0; lineNdx < (int)screenspaceLines.size(); ++lineNdx)
1773 	{
1774 		const tcu::Vec2 pa = screenspaceLines[lineNdx].swizzle(0, 1);
1775 		const tcu::Vec2 pb = screenspaceLines[lineNdx].swizzle(2, 3);
1776 
1777 		setMaskMapCoverageBitForLine(lineNdx, pa, pb, lineWidth, maskMap, subpixelBits);
1778 	}
1779 }
1780 
1781 // verify line interpolation assuming line pixels are interpolated independently depending only on screen space location
verifyLineGroupPixelIndependentInterpolation(const tcu::Surface & surface,const LineSceneSpec & scene,const RasterizationArguments & args,tcu::TestLog & log,LineInterpolationMethod interpolationMethod)1782 bool verifyLineGroupPixelIndependentInterpolation (const tcu::Surface&				surface,
1783 												   const LineSceneSpec&				scene,
1784 												   const RasterizationArguments&	args,
1785 												   tcu::TestLog&					log,
1786 												   LineInterpolationMethod			interpolationMethod)
1787 {
1788 	DE_ASSERT(scene.lines.size() < 8); // coverage indices are stored as bitmask in a unsigned 8-bit ints
1789 	DE_ASSERT(interpolationMethod == LINEINTERPOLATION_STRICTLY_CORRECT || interpolationMethod == LINEINTERPOLATION_PROJECTED);
1790 
1791 	const tcu::RGBA			invalidPixelColor	= tcu::RGBA(255, 0, 0, 255);
1792 	const tcu::IVec2		viewportSize		= tcu::IVec2(surface.getWidth(), surface.getHeight());
1793 	const int				errorFloodThreshold	= 4;
1794 	int						errorCount			= 0;
1795 	tcu::Surface			errorMask			(surface.getWidth(), surface.getHeight());
1796 	int						invalidPixels		= 0;
1797 	std::vector<tcu::Vec4>	screenspaceLines	(scene.lines.size()); //!< packed (x0, y0, x1, y1)
1798 
1799 	// Reference renderer produces correct fragments using the diamond-exit-rule. Make 2D int array, store line coverage as a 8-bit bitfield
1800 	// The map is used to find lines with potential coverage to a given pixel
1801 	tcu::TextureLevel		referenceLineMap	(tcu::TextureFormat(tcu::TextureFormat::R, tcu::TextureFormat::UNSIGNED_INT8), surface.getWidth(), surface.getHeight());
1802 
1803 	tcu::clear(referenceLineMap.getAccess(), tcu::IVec4(0, 0, 0, 0));
1804 	tcu::clear(errorMask.getAccess(), tcu::Vec4(0.0f, 0.0f, 0.0f, 1.0f));
1805 
1806 	// log format
1807 
1808 	log << tcu::TestLog::Message << "Verifying rasterization result. Native format is RGB" << args.redBits << args.greenBits << args.blueBits << tcu::TestLog::EndMessage;
1809 	if (args.redBits > 8 || args.greenBits > 8 || args.blueBits > 8)
1810 		log << tcu::TestLog::Message << "Warning! More than 8 bits in a color channel, this may produce false negatives." << tcu::TestLog::EndMessage;
1811 
1812 	// prepare lookup map
1813 
1814 	genScreenSpaceLines(screenspaceLines, scene.lines, viewportSize);
1815 	setMaskMapCoverageBitForLines(screenspaceLines, scene.lineWidth, referenceLineMap.getAccess(), args.subpixelBits);
1816 
1817 	// Find all possible lines with coverage, check pixel color matches one of them
1818 
1819 	for (int y = 1; y < surface.getHeight() - 1; ++y)
1820 	for (int x = 1; x < surface.getWidth()  - 1; ++x)
1821 	{
1822 		const tcu::RGBA		color					= surface.getPixel(x, y);
1823 		const tcu::IVec3	pixelNativeColor		= convertRGB8ToNativeFormat(color, args);	// Convert pixel color from rgba8 to the real pixel format. Usually rgba8 or 565
1824 		int					lineCoverageSet			= 0;										// !< lines that may cover this fragment
1825 		int					lineSurroundingCoverage = 0xFFFF;									// !< lines that will cover this fragment
1826 		bool				matchFound				= false;
1827 		const tcu::IVec3	formatLimit				((1 << args.redBits) - 1, (1 << args.greenBits) - 1, (1 << args.blueBits) - 1);
1828 
1829 		std::vector<SingleSampleNarrowLineCandidate> candidates;
1830 
1831 		// Find lines with possible coverage
1832 
1833 		for (int dy = -1; dy < 2; ++dy)
1834 		for (int dx = -1; dx < 2; ++dx)
1835 		{
1836 			const int coverage = referenceLineMap.getAccess().getPixelInt(x+dx, y+dy).x();
1837 
1838 			lineCoverageSet			|= coverage;
1839 			lineSurroundingCoverage	&= coverage;
1840 		}
1841 
1842 		// background color is possible?
1843 		if (lineSurroundingCoverage == 0 && compareColors(color, tcu::RGBA::black(), args.redBits, args.greenBits, args.blueBits))
1844 			continue;
1845 
1846 		// Check those lines
1847 
1848 		for (int lineNdx = 0; lineNdx < (int)scene.lines.size(); ++lineNdx)
1849 		{
1850 			if (((lineCoverageSet >> lineNdx) & 0x01) != 0)
1851 			{
1852 				const float						wa				= scene.lines[lineNdx].positions[0].w();
1853 				const float						wb				= scene.lines[lineNdx].positions[1].w();
1854 				const tcu::Vec2					pa				= screenspaceLines[lineNdx].swizzle(0, 1);
1855 				const tcu::Vec2					pb				= screenspaceLines[lineNdx].swizzle(2, 3);
1856 
1857 				const LineInterpolationRange	range			= (interpolationMethod == LINEINTERPOLATION_STRICTLY_CORRECT)
1858 																	? (calcSingleSampleLineInterpolationRange(pa, wa, pb, wb, tcu::IVec2(x, y), args.subpixelBits))
1859 																	: (calcSingleSampleLineInterpolationRangeAxisProjected(pa, wa, pb, wb, tcu::IVec2(x, y), args.subpixelBits));
1860 
1861 				const tcu::Vec4					valueMin		= de::clamp(range.min.x(), 0.0f, 1.0f) * scene.lines[lineNdx].colors[0] + de::clamp(range.min.y(), 0.0f, 1.0f) * scene.lines[lineNdx].colors[1];
1862 				const tcu::Vec4					valueMax		= de::clamp(range.max.x(), 0.0f, 1.0f) * scene.lines[lineNdx].colors[0] + de::clamp(range.max.y(), 0.0f, 1.0f) * scene.lines[lineNdx].colors[1];
1863 
1864 				const tcu::Vec3					colorMinF		(de::clamp(valueMin.x() * (float)formatLimit.x(), 0.0f, (float)formatLimit.x()),
1865 																 de::clamp(valueMin.y() * (float)formatLimit.y(), 0.0f, (float)formatLimit.y()),
1866 																 de::clamp(valueMin.z() * (float)formatLimit.z(), 0.0f, (float)formatLimit.z()));
1867 				const tcu::Vec3					colorMaxF		(de::clamp(valueMax.x() * (float)formatLimit.x(), 0.0f, (float)formatLimit.x()),
1868 																 de::clamp(valueMax.y() * (float)formatLimit.y(), 0.0f, (float)formatLimit.y()),
1869 																 de::clamp(valueMax.z() * (float)formatLimit.z(), 0.0f, (float)formatLimit.z()));
1870 				const tcu::IVec3				colorMin		((int)deFloatFloor(colorMinF.x()),
1871 																 (int)deFloatFloor(colorMinF.y()),
1872 																 (int)deFloatFloor(colorMinF.z()));
1873 				const tcu::IVec3				colorMax		((int)deFloatCeil (colorMaxF.x()),
1874 																 (int)deFloatCeil (colorMaxF.y()),
1875 																 (int)deFloatCeil (colorMaxF.z()));
1876 
1877 				// Verify validity
1878 				if (pixelNativeColor.x() < colorMin.x() ||
1879 					pixelNativeColor.y() < colorMin.y() ||
1880 					pixelNativeColor.z() < colorMin.z() ||
1881 					pixelNativeColor.x() > colorMax.x() ||
1882 					pixelNativeColor.y() > colorMax.y() ||
1883 					pixelNativeColor.z() > colorMax.z())
1884 				{
1885 					if (errorCount < errorFloodThreshold)
1886 					{
1887 						// Store candidate information for logging
1888 						SingleSampleNarrowLineCandidate candidate;
1889 
1890 						candidate.lineNdx		= lineNdx;
1891 						candidate.colorMin		= colorMin;
1892 						candidate.colorMax		= colorMax;
1893 						candidate.colorMinF		= colorMinF;
1894 						candidate.colorMaxF		= colorMaxF;
1895 						candidate.valueRangeMin	= valueMin.swizzle(0, 1, 2);
1896 						candidate.valueRangeMax	= valueMax.swizzle(0, 1, 2);
1897 
1898 						candidates.push_back(candidate);
1899 					}
1900 				}
1901 				else
1902 				{
1903 					matchFound = true;
1904 					break;
1905 				}
1906 			}
1907 		}
1908 
1909 		if (matchFound)
1910 			continue;
1911 
1912 		// invalid fragment
1913 		++invalidPixels;
1914 		errorMask.setPixel(x, y, invalidPixelColor);
1915 
1916 		++errorCount;
1917 
1918 		// don't fill the logs with too much data
1919 		if (errorCount < errorFloodThreshold)
1920 		{
1921 			log << tcu::TestLog::Message
1922 				<< "Found an invalid pixel at (" << x << "," << y << "), " << (int)candidates.size() << " candidate reference value(s) found:\n"
1923 				<< "\tPixel color:\t\t" << color << "\n"
1924 				<< "\tNative color:\t\t" << pixelNativeColor << "\n"
1925 				<< tcu::TestLog::EndMessage;
1926 
1927 			for (int candidateNdx = 0; candidateNdx < (int)candidates.size(); ++candidateNdx)
1928 			{
1929 				const SingleSampleNarrowLineCandidate& candidate = candidates[candidateNdx];
1930 
1931 				log << tcu::TestLog::Message << "\tCandidate (line " << candidate.lineNdx << "):\n"
1932 					<< "\t\tReference native color min: " << tcu::clamp(candidate.colorMin, tcu::IVec3(0,0,0), formatLimit) << "\n"
1933 					<< "\t\tReference native color max: " << tcu::clamp(candidate.colorMax, tcu::IVec3(0,0,0), formatLimit) << "\n"
1934 					<< "\t\tReference native float min: " << tcu::clamp(candidate.colorMinF, tcu::Vec3(0.0f, 0.0f, 0.0f), formatLimit.cast<float>()) << "\n"
1935 					<< "\t\tReference native float max: " << tcu::clamp(candidate.colorMaxF, tcu::Vec3(0.0f, 0.0f, 0.0f), formatLimit.cast<float>()) << "\n"
1936 					<< "\t\tFmin:\t" << tcu::clamp(candidate.valueRangeMin, tcu::Vec3(0.0f, 0.0f, 0.0f), tcu::Vec3(1.0f, 1.0f, 1.0f)) << "\n"
1937 					<< "\t\tFmax:\t" << tcu::clamp(candidate.valueRangeMax, tcu::Vec3(0.0f, 0.0f, 0.0f), tcu::Vec3(1.0f, 1.0f, 1.0f)) << "\n"
1938 					<< tcu::TestLog::EndMessage;
1939 			}
1940 		}
1941 	}
1942 
1943 	// don't just hide failures
1944 	if (errorCount > errorFloodThreshold)
1945 		log << tcu::TestLog::Message << "Omitted " << (errorCount-errorFloodThreshold) << " pixel error description(s)." << tcu::TestLog::EndMessage;
1946 
1947 	// report result
1948 	if (invalidPixels)
1949 	{
1950 		log << tcu::TestLog::Message << invalidPixels << " invalid pixel(s) found." << tcu::TestLog::EndMessage;
1951 		log << tcu::TestLog::ImageSet("Verification result", "Result of rendering")
1952 			<< tcu::TestLog::Image("Result", "Result",			surface)
1953 			<< tcu::TestLog::Image("ErrorMask", "ErrorMask",	errorMask)
1954 			<< tcu::TestLog::EndImageSet;
1955 
1956 		return false;
1957 	}
1958 	else
1959 	{
1960 		log << tcu::TestLog::Message << "No invalid pixels found." << tcu::TestLog::EndMessage;
1961 		log << tcu::TestLog::ImageSet("Verification result", "Result of rendering")
1962 			<< tcu::TestLog::Image("Result", "Result", surface)
1963 			<< tcu::TestLog::EndImageSet;
1964 
1965 		return true;
1966 	}
1967 }
1968 
verifySinglesampleNarrowLineGroupInterpolation(const tcu::Surface & surface,const LineSceneSpec & scene,const RasterizationArguments & args,tcu::TestLog & log)1969 bool verifySinglesampleNarrowLineGroupInterpolation (const tcu::Surface& surface, const LineSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log)
1970 {
1971 	DE_ASSERT(scene.lineWidth == 1.0f);
1972 	return verifyLineGroupPixelIndependentInterpolation(surface, scene, args, log, LINEINTERPOLATION_STRICTLY_CORRECT);
1973 }
1974 
verifyLineGroupInterpolationWithProjectedWeights(const tcu::Surface & surface,const LineSceneSpec & scene,const RasterizationArguments & args,tcu::TestLog & log)1975 bool verifyLineGroupInterpolationWithProjectedWeights (const tcu::Surface& surface, const LineSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log)
1976 {
1977 	return verifyLineGroupPixelIndependentInterpolation(surface, scene, args, log, LINEINTERPOLATION_PROJECTED);
1978 }
1979 
1980 struct SingleSampleWideLineCandidate
1981 {
1982 	struct InterpolationPointCandidate
1983 	{
1984 		tcu::IVec2	interpolationPoint;
1985 		tcu::IVec3	colorMin;
1986 		tcu::IVec3	colorMax;
1987 		tcu::Vec3	colorMinF;
1988 		tcu::Vec3	colorMaxF;
1989 		tcu::Vec3	valueRangeMin;
1990 		tcu::Vec3	valueRangeMax;
1991 	};
1992 
1993 	int							lineNdx;
1994 	int							numCandidates;
1995 	InterpolationPointCandidate	interpolationCandidates[3];
1996 };
1997 
1998 // return point on line at a given position on a given axis
getLineCoordAtAxisCoord(const tcu::Vec2 & pa,const tcu::Vec2 & pb,bool isXAxis,float axisCoord)1999 tcu::Vec2 getLineCoordAtAxisCoord (const tcu::Vec2& pa, const tcu::Vec2& pb, bool isXAxis, float axisCoord)
2000 {
2001 	const int	fixedCoordNdx		= (isXAxis) ? (0) : (1);
2002 	const int	varyingCoordNdx		= (isXAxis) ? (1) : (0);
2003 
2004 	const float	fixedDifference		= pb[fixedCoordNdx] - pa[fixedCoordNdx];
2005 	const float	varyingDifference	= pb[varyingCoordNdx] - pa[varyingCoordNdx];
2006 
2007 	DE_ASSERT(fixedDifference != 0.0f);
2008 
2009 	const float	resultFixedCoord	= axisCoord;
2010 	const float	resultVaryingCoord	= pa[varyingCoordNdx] + (axisCoord - pa[fixedCoordNdx]) * (varyingDifference / fixedDifference);
2011 
2012 	return (isXAxis) ? (tcu::Vec2(resultFixedCoord, resultVaryingCoord))
2013 					 : (tcu::Vec2(resultVaryingCoord, resultFixedCoord));
2014 }
2015 
isBlack(const tcu::RGBA & c)2016 bool isBlack (const tcu::RGBA& c)
2017 {
2018 	return c.getRed() == 0 && c.getGreen() == 0 && c.getBlue() == 0;
2019 }
2020 
verifySinglesampleWideLineGroupInterpolation(const tcu::Surface & surface,const LineSceneSpec & scene,const RasterizationArguments & args,tcu::TestLog & log)2021 bool verifySinglesampleWideLineGroupInterpolation (const tcu::Surface& surface, const LineSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log)
2022 {
2023 	DE_ASSERT(deFloatFrac(scene.lineWidth) != 0.5f); // rounding direction is not defined, disallow undefined cases
2024 	DE_ASSERT(scene.lines.size() < 8); // coverage indices are stored as bitmask in a unsigned 8-bit ints
2025 
2026 	enum
2027 	{
2028 		FLAG_ROOT_NOT_SET = (1u << 16)
2029 	};
2030 
2031 	const tcu::RGBA						invalidPixelColor	= tcu::RGBA(255, 0, 0, 255);
2032 	const tcu::IVec2					viewportSize		= tcu::IVec2(surface.getWidth(), surface.getHeight());
2033 	const int							errorFloodThreshold	= 4;
2034 	int									errorCount			= 0;
2035 	tcu::Surface						errorMask			(surface.getWidth(), surface.getHeight());
2036 	int									invalidPixels		= 0;
2037 	std::vector<tcu::Vec4>				effectiveLines		(scene.lines.size()); //!< packed (x0, y0, x1, y1)
2038 	std::vector<bool>					lineIsXMajor		(scene.lines.size());
2039 
2040 	// for each line, for every distinct major direction fragment, store root pixel location (along
2041 	// minor direction);
2042 	std::vector<std::vector<deUint32> >	rootPixelLocation	(scene.lines.size()); //!< packed [16b - flags] [16b - coordinate]
2043 
2044 	// log format
2045 
2046 	log << tcu::TestLog::Message << "Verifying rasterization result. Native format is RGB" << args.redBits << args.greenBits << args.blueBits << tcu::TestLog::EndMessage;
2047 	if (args.redBits > 8 || args.greenBits > 8 || args.blueBits > 8)
2048 		log << tcu::TestLog::Message << "Warning! More than 8 bits in a color channel, this may produce false negatives." << tcu::TestLog::EndMessage;
2049 
2050 	// Reference renderer produces correct fragments using the diamond-exit-rule. Make 2D int array, store line coverage as a 8-bit bitfield
2051 	// The map is used to find lines with potential coverage to a given pixel
2052 	tcu::TextureLevel referenceLineMap(tcu::TextureFormat(tcu::TextureFormat::R, tcu::TextureFormat::UNSIGNED_INT8), surface.getWidth(), surface.getHeight());
2053 	tcu::clear(referenceLineMap.getAccess(), tcu::IVec4(0, 0, 0, 0));
2054 
2055 	tcu::clear(errorMask.getAccess(), tcu::Vec4(0.0f, 0.0f, 0.0f, 1.0f));
2056 
2057 	// calculate mask and effective line coordinates
2058 	{
2059 		std::vector<tcu::Vec4> screenspaceLines(scene.lines.size());
2060 
2061 		genScreenSpaceLines(screenspaceLines, scene.lines, viewportSize);
2062 		setMaskMapCoverageBitForLines(screenspaceLines, scene.lineWidth, referenceLineMap.getAccess(), args.subpixelBits);
2063 
2064 		for (int lineNdx = 0; lineNdx < (int)scene.lines.size(); ++lineNdx)
2065 		{
2066 			const tcu::Vec2	lineScreenSpaceP0	= screenspaceLines[lineNdx].swizzle(0, 1);
2067 			const tcu::Vec2	lineScreenSpaceP1	= screenspaceLines[lineNdx].swizzle(2, 3);
2068 			const bool		isXMajor			= isPackedSSLineXMajor(screenspaceLines[lineNdx]);
2069 
2070 			lineIsXMajor[lineNdx] = isXMajor;
2071 
2072 			// wide line interpolations are calculated for a line moved in minor direction
2073 			{
2074 				const float		offsetLength	= (scene.lineWidth - 1.0f) / 2.0f;
2075 				const tcu::Vec2	offsetDirection	= (isXMajor) ? (tcu::Vec2(0.0f, -1.0f)) : (tcu::Vec2(-1.0f, 0.0f));
2076 				const tcu::Vec2	offset			= offsetDirection * offsetLength;
2077 
2078 				effectiveLines[lineNdx] = tcu::Vec4(lineScreenSpaceP0.x() + offset.x(),
2079 													lineScreenSpaceP0.y() + offset.y(),
2080 													lineScreenSpaceP1.x() + offset.x(),
2081 													lineScreenSpaceP1.y() + offset.y());
2082 			}
2083 		}
2084 	}
2085 
2086 	for (int lineNdx = 0; lineNdx < (int)scene.lines.size(); ++lineNdx)
2087 	{
2088 		// Calculate root pixel lookup table for this line. Since the implementation's fragment
2089 		// major coordinate range might not be a subset of the correct line range (they are allowed
2090 		// to vary by one pixel), we must extend the domain to cover whole viewport along major
2091 		// dimension.
2092 		//
2093 		// Expanding line strip to (effectively) infinite line might result in exit-diamnod set
2094 		// that is not a superset of the exit-diamond set of the line strip. In practice, this
2095 		// won't be an issue, since the allow-one-pixel-variation rule should tolerate this even
2096 		// if the original and extended line would resolve differently a diamond the line just
2097 		// touches (precision lost in expansion changes enter/exit status).
2098 
2099 		{
2100 			const bool						isXMajor			= lineIsXMajor[lineNdx];
2101 			const int						majorSize			= (isXMajor) ? (surface.getWidth()) : (surface.getHeight());
2102 			rr::LineExitDiamondGenerator	diamondGenerator	(args.subpixelBits);
2103 			rr::LineExitDiamond				diamonds[32];
2104 			int								numRasterized		= DE_LENGTH_OF_ARRAY(diamonds);
2105 
2106 			// Expand to effectively infinite line (endpoints are just one pixel over viewport boundaries)
2107 			const tcu::Vec2					expandedP0		= getLineCoordAtAxisCoord(effectiveLines[lineNdx].swizzle(0, 1), effectiveLines[lineNdx].swizzle(2, 3), isXMajor, -1.0f);
2108 			const tcu::Vec2					expandedP1		= getLineCoordAtAxisCoord(effectiveLines[lineNdx].swizzle(0, 1), effectiveLines[lineNdx].swizzle(2, 3), isXMajor, (float)majorSize + 1.0f);
2109 
2110 			diamondGenerator.init(tcu::Vec4(expandedP0.x(), expandedP0.y(), 0.0f, 1.0f),
2111 								  tcu::Vec4(expandedP1.x(), expandedP1.y(), 0.0f, 1.0f));
2112 
2113 			rootPixelLocation[lineNdx].resize(majorSize, FLAG_ROOT_NOT_SET);
2114 
2115 			while (numRasterized == DE_LENGTH_OF_ARRAY(diamonds))
2116 			{
2117 				diamondGenerator.rasterize(diamonds, DE_LENGTH_OF_ARRAY(diamonds), numRasterized);
2118 
2119 				for (int packetNdx = 0; packetNdx < numRasterized; ++packetNdx)
2120 				{
2121 					const tcu::IVec2	fragPos			= diamonds[packetNdx].position;
2122 					const int			majorPos		= (isXMajor) ? (fragPos.x()) : (fragPos.y());
2123 					const int			rootPos			= (isXMajor) ? (fragPos.y()) : (fragPos.x());
2124 					const deUint32		packed			= (deUint32)((deUint16)((deInt16)rootPos));
2125 
2126 					// infinite line will generate some diamonds outside the viewport
2127 					if (deInBounds32(majorPos, 0, majorSize))
2128 					{
2129 						DE_ASSERT((rootPixelLocation[lineNdx][majorPos] & FLAG_ROOT_NOT_SET) != 0u);
2130 						rootPixelLocation[lineNdx][majorPos] = packed;
2131 					}
2132 				}
2133 			}
2134 
2135 			// Filled whole lookup table
2136 			for (int majorPos = 0; majorPos < majorSize; ++majorPos)
2137 				DE_ASSERT((rootPixelLocation[lineNdx][majorPos] & FLAG_ROOT_NOT_SET) == 0u);
2138 		}
2139 	}
2140 
2141 	// Find all possible lines with coverage, check pixel color matches one of them
2142 
2143 	for (int y = 1; y < surface.getHeight() - 1; ++y)
2144 	for (int x = 1; x < surface.getWidth()  - 1; ++x)
2145 	{
2146 		const tcu::RGBA		color					= surface.getPixel(x, y);
2147 		const tcu::IVec3	pixelNativeColor		= convertRGB8ToNativeFormat(color, args);	// Convert pixel color from rgba8 to the real pixel format. Usually rgba8 or 565
2148 		int					lineCoverageSet			= 0;										// !< lines that may cover this fragment
2149 		int					lineSurroundingCoverage = 0xFFFF;									// !< lines that will cover this fragment
2150 		bool				matchFound				= false;
2151 		const tcu::IVec3	formatLimit				((1 << args.redBits) - 1, (1 << args.greenBits) - 1, (1 << args.blueBits) - 1);
2152 
2153 		std::vector<SingleSampleWideLineCandidate> candidates;
2154 
2155 		// Find lines with possible coverage
2156 
2157 		for (int dy = -1; dy < 2; ++dy)
2158 		for (int dx = -1; dx < 2; ++dx)
2159 		{
2160 			const int coverage = referenceLineMap.getAccess().getPixelInt(x+dx, y+dy).x();
2161 
2162 			lineCoverageSet			|= coverage;
2163 			lineSurroundingCoverage	&= coverage;
2164 		}
2165 
2166 		// background color is possible?
2167 		if (lineSurroundingCoverage == 0 && compareColors(color, tcu::RGBA::black(), args.redBits, args.greenBits, args.blueBits))
2168 			continue;
2169 
2170 		// Check those lines
2171 
2172 		for (int lineNdx = 0; lineNdx < (int)scene.lines.size(); ++lineNdx)
2173 		{
2174 			if (((lineCoverageSet >> lineNdx) & 0x01) != 0)
2175 			{
2176 				const float						wa				= scene.lines[lineNdx].positions[0].w();
2177 				const float						wb				= scene.lines[lineNdx].positions[1].w();
2178 				const tcu::Vec2					pa				= effectiveLines[lineNdx].swizzle(0, 1);
2179 				const tcu::Vec2					pb				= effectiveLines[lineNdx].swizzle(2, 3);
2180 
2181 				// \note Wide line fragments are generated by replicating the root fragment for each
2182 				//       fragment column (row for y-major). Calculate interpolation at the root
2183 				//       fragment.
2184 				const bool						isXMajor		= lineIsXMajor[lineNdx];
2185 				const int						majorPosition	= (isXMajor) ? (x) : (y);
2186 				const deUint32					minorInfoPacked	= rootPixelLocation[lineNdx][majorPosition];
2187 				const int						minorPosition	= (int)((deInt16)((deUint16)(minorInfoPacked & 0xFFFFu)));
2188 				const tcu::IVec2				idealRootPos	= (isXMajor) ? (tcu::IVec2(majorPosition, minorPosition)) : (tcu::IVec2(minorPosition, majorPosition));
2189 				const tcu::IVec2				minorDirection	= (isXMajor) ? (tcu::IVec2(0, 1)) : (tcu::IVec2(1, 0));
2190 
2191 				SingleSampleWideLineCandidate	candidate;
2192 
2193 				candidate.lineNdx		= lineNdx;
2194 				candidate.numCandidates	= 0;
2195 				DE_STATIC_ASSERT(DE_LENGTH_OF_ARRAY(candidate.interpolationCandidates) == 3);
2196 
2197 				// Interpolation happens at the root fragment, which is then replicated in minor
2198 				// direction. Search for implementation's root position near accurate root.
2199 				for (int minorOffset = -1; minorOffset < 2; ++minorOffset)
2200 				{
2201 					const tcu::IVec2				rootPosition	= idealRootPos + minorOffset * minorDirection;
2202 
2203 					// A fragment can be root fragment only if it exists
2204 					// \note root fragment can "exist" outside viewport
2205 					// \note no pixel format theshold since in this case allowing only black is more conservative
2206 					if (deInBounds32(rootPosition.x(), 0, surface.getWidth()) &&
2207 						deInBounds32(rootPosition.y(), 0, surface.getHeight()) &&
2208 						isBlack(surface.getPixel(rootPosition.x(), rootPosition.y())))
2209 					{
2210 						continue;
2211 					}
2212 
2213 					const LineInterpolationRange	range			= calcSingleSampleLineInterpolationRange(pa, wa, pb, wb, rootPosition, args.subpixelBits);
2214 
2215 					const tcu::Vec4					valueMin		= de::clamp(range.min.x(), 0.0f, 1.0f) * scene.lines[lineNdx].colors[0] + de::clamp(range.min.y(), 0.0f, 1.0f) * scene.lines[lineNdx].colors[1];
2216 					const tcu::Vec4					valueMax		= de::clamp(range.max.x(), 0.0f, 1.0f) * scene.lines[lineNdx].colors[0] + de::clamp(range.max.y(), 0.0f, 1.0f) * scene.lines[lineNdx].colors[1];
2217 
2218 					const tcu::Vec3					colorMinF		(de::clamp(valueMin.x() * (float)formatLimit.x(), 0.0f, (float)formatLimit.x()),
2219 																	 de::clamp(valueMin.y() * (float)formatLimit.y(), 0.0f, (float)formatLimit.y()),
2220 																	 de::clamp(valueMin.z() * (float)formatLimit.z(), 0.0f, (float)formatLimit.z()));
2221 					const tcu::Vec3					colorMaxF		(de::clamp(valueMax.x() * (float)formatLimit.x(), 0.0f, (float)formatLimit.x()),
2222 																	 de::clamp(valueMax.y() * (float)formatLimit.y(), 0.0f, (float)formatLimit.y()),
2223 																	 de::clamp(valueMax.z() * (float)formatLimit.z(), 0.0f, (float)formatLimit.z()));
2224 					const tcu::IVec3				colorMin		((int)deFloatFloor(colorMinF.x()),
2225 																	 (int)deFloatFloor(colorMinF.y()),
2226 																	 (int)deFloatFloor(colorMinF.z()));
2227 					const tcu::IVec3				colorMax		((int)deFloatCeil (colorMaxF.x()),
2228 																	 (int)deFloatCeil (colorMaxF.y()),
2229 																	 (int)deFloatCeil (colorMaxF.z()));
2230 
2231 					// Verify validity
2232 					if (pixelNativeColor.x() < colorMin.x() ||
2233 						pixelNativeColor.y() < colorMin.y() ||
2234 						pixelNativeColor.z() < colorMin.z() ||
2235 						pixelNativeColor.x() > colorMax.x() ||
2236 						pixelNativeColor.y() > colorMax.y() ||
2237 						pixelNativeColor.z() > colorMax.z())
2238 					{
2239 						if (errorCount < errorFloodThreshold)
2240 						{
2241 							// Store candidate information for logging
2242 							SingleSampleWideLineCandidate::InterpolationPointCandidate& interpolationCandidate = candidate.interpolationCandidates[candidate.numCandidates++];
2243 							DE_ASSERT(candidate.numCandidates <= DE_LENGTH_OF_ARRAY(candidate.interpolationCandidates));
2244 
2245 							interpolationCandidate.interpolationPoint	= rootPosition;
2246 							interpolationCandidate.colorMin				= colorMin;
2247 							interpolationCandidate.colorMax				= colorMax;
2248 							interpolationCandidate.colorMinF			= colorMinF;
2249 							interpolationCandidate.colorMaxF			= colorMaxF;
2250 							interpolationCandidate.valueRangeMin		= valueMin.swizzle(0, 1, 2);
2251 							interpolationCandidate.valueRangeMax		= valueMax.swizzle(0, 1, 2);
2252 						}
2253 					}
2254 					else
2255 					{
2256 						matchFound = true;
2257 						break;
2258 					}
2259 				}
2260 
2261 				if (!matchFound)
2262 				{
2263 					// store info for logging
2264 					if (errorCount < errorFloodThreshold && candidate.numCandidates > 0)
2265 						candidates.push_back(candidate);
2266 				}
2267 				else
2268 				{
2269 					// no need to check other lines
2270 					break;
2271 				}
2272 			}
2273 		}
2274 
2275 		if (matchFound)
2276 			continue;
2277 
2278 		// invalid fragment
2279 		++invalidPixels;
2280 		errorMask.setPixel(x, y, invalidPixelColor);
2281 
2282 		++errorCount;
2283 
2284 		// don't fill the logs with too much data
2285 		if (errorCount < errorFloodThreshold)
2286 		{
2287 			tcu::MessageBuilder msg(&log);
2288 
2289 			msg	<< "Found an invalid pixel at (" << x << "," << y << "), " << (int)candidates.size() << " candidate reference value(s) found:\n"
2290 				<< "\tPixel color:\t\t" << color << "\n"
2291 				<< "\tNative color:\t\t" << pixelNativeColor << "\n";
2292 
2293 			for (int lineCandidateNdx = 0; lineCandidateNdx < (int)candidates.size(); ++lineCandidateNdx)
2294 			{
2295 				const SingleSampleWideLineCandidate& candidate = candidates[lineCandidateNdx];
2296 
2297 				msg << "\tCandidate line (line " << candidate.lineNdx << "):\n";
2298 
2299 				for (int interpolationCandidateNdx = 0; interpolationCandidateNdx < candidate.numCandidates; ++interpolationCandidateNdx)
2300 				{
2301 					const SingleSampleWideLineCandidate::InterpolationPointCandidate& interpolationCandidate = candidate.interpolationCandidates[interpolationCandidateNdx];
2302 
2303 					msg	<< "\t\tCandidate interpolation point (index " << interpolationCandidateNdx << "):\n"
2304 						<< "\t\t\tRoot fragment position (non-replicated fragment): " << interpolationCandidate.interpolationPoint << ":\n"
2305 						<< "\t\t\tReference native color min: " << tcu::clamp(interpolationCandidate.colorMin, tcu::IVec3(0,0,0), formatLimit) << "\n"
2306 						<< "\t\t\tReference native color max: " << tcu::clamp(interpolationCandidate.colorMax, tcu::IVec3(0,0,0), formatLimit) << "\n"
2307 						<< "\t\t\tReference native float min: " << tcu::clamp(interpolationCandidate.colorMinF, tcu::Vec3(0.0f, 0.0f, 0.0f), formatLimit.cast<float>()) << "\n"
2308 						<< "\t\t\tReference native float max: " << tcu::clamp(interpolationCandidate.colorMaxF, tcu::Vec3(0.0f, 0.0f, 0.0f), formatLimit.cast<float>()) << "\n"
2309 						<< "\t\t\tFmin:\t" << tcu::clamp(interpolationCandidate.valueRangeMin, tcu::Vec3(0.0f, 0.0f, 0.0f), tcu::Vec3(1.0f, 1.0f, 1.0f)) << "\n"
2310 						<< "\t\t\tFmax:\t" << tcu::clamp(interpolationCandidate.valueRangeMax, tcu::Vec3(0.0f, 0.0f, 0.0f), tcu::Vec3(1.0f, 1.0f, 1.0f)) << "\n";
2311 				}
2312 			}
2313 
2314 			msg << tcu::TestLog::EndMessage;
2315 		}
2316 	}
2317 
2318 	// don't just hide failures
2319 	if (errorCount > errorFloodThreshold)
2320 		log << tcu::TestLog::Message << "Omitted " << (errorCount-errorFloodThreshold) << " pixel error description(s)." << tcu::TestLog::EndMessage;
2321 
2322 	// report result
2323 	if (invalidPixels)
2324 	{
2325 		log << tcu::TestLog::Message << invalidPixels << " invalid pixel(s) found." << tcu::TestLog::EndMessage;
2326 		log << tcu::TestLog::ImageSet("Verification result", "Result of rendering")
2327 			<< tcu::TestLog::Image("Result", "Result",			surface)
2328 			<< tcu::TestLog::Image("ErrorMask", "ErrorMask",	errorMask)
2329 			<< tcu::TestLog::EndImageSet;
2330 
2331 		return false;
2332 	}
2333 	else
2334 	{
2335 		log << tcu::TestLog::Message << "No invalid pixels found." << tcu::TestLog::EndMessage;
2336 		log << tcu::TestLog::ImageSet("Verification result", "Result of rendering")
2337 			<< tcu::TestLog::Image("Result", "Result", surface)
2338 			<< tcu::TestLog::EndImageSet;
2339 
2340 		return true;
2341 	}
2342 }
2343 
2344 } // anonymous
2345 
calculateTriangleCoverage(const tcu::Vec4 & p0,const tcu::Vec4 & p1,const tcu::Vec4 & p2,const tcu::IVec2 & pixel,const tcu::IVec2 & viewportSize,int subpixelBits,bool multisample)2346 CoverageType calculateTriangleCoverage (const tcu::Vec4& p0, const tcu::Vec4& p1, const tcu::Vec4& p2, const tcu::IVec2& pixel, const tcu::IVec2& viewportSize, int subpixelBits, bool multisample)
2347 {
2348 	typedef tcu::Vector<deInt64, 2> I64Vec2;
2349 
2350 	const deUint64		numSubPixels						= ((deUint64)1) << subpixelBits;
2351 	const deUint64		pixelHitBoxSize						= (multisample) ? (numSubPixels) : 5;		//!< 5 = ceil(6 * sqrt(2) / 2) to account for a 3 subpixel fuzz around pixel center
2352 	const bool			order								= isTriangleClockwise(p0, p1, p2);			//!< clockwise / counter-clockwise
2353 	const tcu::Vec4&	orderedP0							= p0;										//!< vertices of a clockwise triangle
2354 	const tcu::Vec4&	orderedP1							= (order) ? (p1) : (p2);
2355 	const tcu::Vec4&	orderedP2							= (order) ? (p2) : (p1);
2356 	const tcu::Vec2		triangleNormalizedDeviceSpace[3]	=
2357 	{
2358 		tcu::Vec2(orderedP0.x() / orderedP0.w(), orderedP0.y() / orderedP0.w()),
2359 		tcu::Vec2(orderedP1.x() / orderedP1.w(), orderedP1.y() / orderedP1.w()),
2360 		tcu::Vec2(orderedP2.x() / orderedP2.w(), orderedP2.y() / orderedP2.w()),
2361 	};
2362 	const tcu::Vec2		triangleScreenSpace[3]				=
2363 	{
2364 		(triangleNormalizedDeviceSpace[0] + tcu::Vec2(1.0f, 1.0f)) * 0.5f * tcu::Vec2((float)viewportSize.x(), (float)viewportSize.y()),
2365 		(triangleNormalizedDeviceSpace[1] + tcu::Vec2(1.0f, 1.0f)) * 0.5f * tcu::Vec2((float)viewportSize.x(), (float)viewportSize.y()),
2366 		(triangleNormalizedDeviceSpace[2] + tcu::Vec2(1.0f, 1.0f)) * 0.5f * tcu::Vec2((float)viewportSize.x(), (float)viewportSize.y()),
2367 	};
2368 
2369 	// Broad bounding box - pixel check
2370 	{
2371 		const float minX = de::min(de::min(triangleScreenSpace[0].x(), triangleScreenSpace[1].x()), triangleScreenSpace[2].x());
2372 		const float minY = de::min(de::min(triangleScreenSpace[0].y(), triangleScreenSpace[1].y()), triangleScreenSpace[2].y());
2373 		const float maxX = de::max(de::max(triangleScreenSpace[0].x(), triangleScreenSpace[1].x()), triangleScreenSpace[2].x());
2374 		const float maxY = de::max(de::max(triangleScreenSpace[0].y(), triangleScreenSpace[1].y()), triangleScreenSpace[2].y());
2375 
2376 		if ((float)pixel.x() > maxX + 1 ||
2377 			(float)pixel.y() > maxY + 1 ||
2378 			(float)pixel.x() < minX - 1 ||
2379 			(float)pixel.y() < minY - 1)
2380 			return COVERAGE_NONE;
2381 	}
2382 
2383 	// Broad triangle - pixel area intersection
2384 	{
2385 		const DVec2 pixelCenterPosition			=	DVec2((double)pixel.x(), (double)pixel.y()) * DVec2((double)numSubPixels, (double)numSubPixels) +
2386 													DVec2((double)numSubPixels / 2, (double)numSubPixels / 2);
2387 		const DVec2 triangleSubPixelSpace[3]	=
2388 		{
2389 			DVec2(triangleScreenSpace[0].x() * (double)numSubPixels, triangleScreenSpace[0].y() * (double)numSubPixels),
2390 			DVec2(triangleScreenSpace[1].x() * (double)numSubPixels, triangleScreenSpace[1].y() * (double)numSubPixels),
2391 			DVec2(triangleScreenSpace[2].x() * (double)numSubPixels, triangleScreenSpace[2].y() * (double)numSubPixels),
2392 		};
2393 
2394 		// Check (using cross product) if pixel center is
2395 		// a) too far from any edge
2396 		// b) fully inside all edges
2397 		bool insideAllEdges = true;
2398 		for (int vtxNdx = 0; vtxNdx < 3; ++vtxNdx)
2399 		{
2400 			const int		otherVtxNdx				= (vtxNdx + 1) % 3;
2401 			const double	maxPixelDistanceSquared	= (double)(pixelHitBoxSize * pixelHitBoxSize); // Max distance from the pixel center from within the pixel is (sqrt(2) * boxWidth/2). Use 2x value for rounding tolerance
2402 			const DVec2		edge					= triangleSubPixelSpace[otherVtxNdx]	- triangleSubPixelSpace[vtxNdx];
2403 			const DVec2		v						= pixelCenterPosition					- triangleSubPixelSpace[vtxNdx];
2404 			const double	crossProduct			= (edge.x() * v.y() - edge.y() * v.x());
2405 
2406 			// distance from edge: (edge x v) / |edge|
2407 			//     (edge x v) / |edge| > maxPixelDistance
2408 			// ==> (edge x v)^2 / edge^2 > maxPixelDistance^2    | edge x v > 0
2409 			// ==> (edge x v)^2 > maxPixelDistance^2 * edge^2
2410 			if (crossProduct < 0 && crossProduct*crossProduct > maxPixelDistanceSquared * tcu::lengthSquared(edge))
2411 				return COVERAGE_NONE;
2412 			if (crossProduct < 0 || crossProduct*crossProduct < maxPixelDistanceSquared * tcu::lengthSquared(edge))
2413 				insideAllEdges = false;
2414 		}
2415 
2416 		if (insideAllEdges)
2417 			return COVERAGE_FULL;
2418 	}
2419 
2420 	// Accurate intersection for edge pixels
2421 	{
2422 		//  In multisampling, the sample points can be anywhere in the pixel, and in single sampling only in the center.
2423 		const I64Vec2 pixelCorners[4] =
2424 		{
2425 			I64Vec2((pixel.x()+0) * numSubPixels, (pixel.y()+0) * numSubPixels),
2426 			I64Vec2((pixel.x()+1) * numSubPixels, (pixel.y()+0) * numSubPixels),
2427 			I64Vec2((pixel.x()+1) * numSubPixels, (pixel.y()+1) * numSubPixels),
2428 			I64Vec2((pixel.x()+0) * numSubPixels, (pixel.y()+1) * numSubPixels),
2429 		};
2430 
2431 		// 3 subpixel tolerance around pixel center to account for accumulated errors during various line rasterization methods
2432 		const I64Vec2 pixelCenterCorners[4] =
2433 		{
2434 			I64Vec2(pixel.x() * numSubPixels + numSubPixels/2 - 3, pixel.y() * numSubPixels + numSubPixels/2 - 3),
2435 			I64Vec2(pixel.x() * numSubPixels + numSubPixels/2 + 3, pixel.y() * numSubPixels + numSubPixels/2 - 3),
2436 			I64Vec2(pixel.x() * numSubPixels + numSubPixels/2 + 3, pixel.y() * numSubPixels + numSubPixels/2 + 3),
2437 			I64Vec2(pixel.x() * numSubPixels + numSubPixels/2 - 3, pixel.y() * numSubPixels + numSubPixels/2 + 3),
2438 		};
2439 
2440 		// both rounding directions
2441 		const I64Vec2 triangleSubPixelSpaceFloor[3] =
2442 		{
2443 			I64Vec2(deFloorFloatToInt32(triangleScreenSpace[0].x() * (float)numSubPixels), deFloorFloatToInt32(triangleScreenSpace[0].y() * (float)numSubPixels)),
2444 			I64Vec2(deFloorFloatToInt32(triangleScreenSpace[1].x() * (float)numSubPixels), deFloorFloatToInt32(triangleScreenSpace[1].y() * (float)numSubPixels)),
2445 			I64Vec2(deFloorFloatToInt32(triangleScreenSpace[2].x() * (float)numSubPixels), deFloorFloatToInt32(triangleScreenSpace[2].y() * (float)numSubPixels)),
2446 		};
2447 		const I64Vec2 triangleSubPixelSpaceCeil[3] =
2448 		{
2449 			I64Vec2(deCeilFloatToInt32(triangleScreenSpace[0].x() * (float)numSubPixels), deCeilFloatToInt32(triangleScreenSpace[0].y() * (float)numSubPixels)),
2450 			I64Vec2(deCeilFloatToInt32(triangleScreenSpace[1].x() * (float)numSubPixels), deCeilFloatToInt32(triangleScreenSpace[1].y() * (float)numSubPixels)),
2451 			I64Vec2(deCeilFloatToInt32(triangleScreenSpace[2].x() * (float)numSubPixels), deCeilFloatToInt32(triangleScreenSpace[2].y() * (float)numSubPixels)),
2452 		};
2453 		const I64Vec2* const corners = (multisample) ? (pixelCorners) : (pixelCenterCorners);
2454 
2455 		// Test if any edge (with any rounding) intersects the pixel (boundary). If it does => Partial. If not => fully inside or outside
2456 
2457 		for (int edgeNdx = 0; edgeNdx < 3; ++edgeNdx)
2458 		for (int startRounding = 0; startRounding < 4; ++startRounding)
2459 		for (int endRounding = 0; endRounding < 4; ++endRounding)
2460 		{
2461 			const int		nextEdgeNdx	= (edgeNdx+1) % 3;
2462 			const I64Vec2	startPos	((startRounding&0x01)	? (triangleSubPixelSpaceFloor[edgeNdx].x())		: (triangleSubPixelSpaceCeil[edgeNdx].x()),		(startRounding&0x02)	? (triangleSubPixelSpaceFloor[edgeNdx].y())		: (triangleSubPixelSpaceCeil[edgeNdx].y()));
2463 			const I64Vec2	endPos		((endRounding&0x01)		? (triangleSubPixelSpaceFloor[nextEdgeNdx].x())	: (triangleSubPixelSpaceCeil[nextEdgeNdx].x()),	(endRounding&0x02)		? (triangleSubPixelSpaceFloor[nextEdgeNdx].y())	: (triangleSubPixelSpaceCeil[nextEdgeNdx].y()));
2464 
2465 			for (int pixelEdgeNdx = 0; pixelEdgeNdx < 4; ++pixelEdgeNdx)
2466 			{
2467 				const int pixelEdgeEnd = (pixelEdgeNdx + 1) % 4;
2468 
2469 				if (lineLineIntersect(startPos, endPos, corners[pixelEdgeNdx], corners[pixelEdgeEnd]))
2470 					return COVERAGE_PARTIAL;
2471 			}
2472 		}
2473 
2474 		// fully inside or outside
2475 		for (int edgeNdx = 0; edgeNdx < 3; ++edgeNdx)
2476 		{
2477 			const int		nextEdgeNdx		= (edgeNdx+1) % 3;
2478 			const I64Vec2&	startPos		= triangleSubPixelSpaceFloor[edgeNdx];
2479 			const I64Vec2&	endPos			= triangleSubPixelSpaceFloor[nextEdgeNdx];
2480 			const I64Vec2	edge			= endPos - startPos;
2481 			const I64Vec2	v				= corners[0] - endPos;
2482 			const deInt64	crossProduct	= (edge.x() * v.y() - edge.y() * v.x());
2483 
2484 			// a corner of the pixel is outside => "fully inside" option is impossible
2485 			if (crossProduct < 0)
2486 				return COVERAGE_NONE;
2487 		}
2488 
2489 		return COVERAGE_FULL;
2490 	}
2491 }
2492 
calculateUnderestimateLineCoverage(const tcu::Vec4 & p0,const tcu::Vec4 & p1,const float lineWidth,const tcu::IVec2 & pixel,const tcu::IVec2 & viewportSize)2493 CoverageType calculateUnderestimateLineCoverage (const tcu::Vec4& p0, const tcu::Vec4& p1, const float lineWidth, const tcu::IVec2& pixel, const tcu::IVec2& viewportSize)
2494 {
2495 	DE_ASSERT(viewportSize.x() == viewportSize.y() && viewportSize.x() > 0);
2496 	DE_ASSERT(p0.w() == 1.0f && p1.w() == 1.0f);
2497 
2498 	const Vec2		p		= Vec2(p0.x(), p0.y());
2499 	const Vec2		q		= Vec2(p1.x(), p1.y());
2500 	const Vec2		pq		= Vec2(p1.x() - p0.x(), p1.y() - p0.y());
2501 	const Vec2		pqn		= normalize(pq);
2502 	const Vec2		lw		= 0.5f * lineWidth * pqn;
2503 	const Vec2		n		= Vec2(lw.y(), -lw.x());
2504 	const Vec2		vp		= Vec2(float(viewportSize.x()), float(viewportSize.y()));
2505 	const Vec2		a		= 0.5f * (p + Vec2(1.0f, 1.0f)) * vp + n;
2506 	const Vec2		b		= 0.5f * (p + Vec2(1.0f, 1.0f)) * vp - n;
2507 	const Vec2		c		= 0.5f * (q + Vec2(1.0f, 1.0f)) * vp - n;
2508 	const Vec2		ba		= b - a;
2509 	const Vec2		bc		= b - c;
2510 	const float		det		= ba.x() * bc.y() - ba.y() * bc.x();
2511 	int				within	= 0;
2512 
2513 	if (det != 0.0f)
2514 	{
2515 		for (int cornerNdx = 0; cornerNdx < 4; ++cornerNdx)
2516 		{
2517 			const int		pixelCornerOffsetX	= ((cornerNdx & 1) ? 1 : 0);
2518 			const int		pixelCornerOffsetY	= ((cornerNdx & 2) ? 1 : 0);
2519 			const Vec2		f					= Vec2(float(pixel.x() + pixelCornerOffsetX), float(pixel.y() + pixelCornerOffsetY));
2520 			const Vec2		bf					= b - f;
2521 			const float		alpha				= (bf.x() * bc.y() - bc.x() * bf.y()) / det;
2522 			const float		beta				= (ba.x() * bf.y() - bf.x() * ba.y()) / det;
2523 			bool			cornerWithin		= de::inRange(alpha, 0.0f, 1.0f) && de::inRange(beta, 0.0f, 1.0f);
2524 
2525 			if (cornerWithin)
2526 				within++;
2527 		}
2528 	}
2529 
2530 	if (within == 0)
2531 		return COVERAGE_NONE;
2532 	else if (within == 4)
2533 		return COVERAGE_FULL;
2534 	else
2535 		return COVERAGE_PARTIAL;
2536 }
2537 
calculateUnderestimateTriangleCoverage(const tcu::Vec4 & p0,const tcu::Vec4 & p1,const tcu::Vec4 & p2,const tcu::IVec2 & pixel,int subpixelBits,const tcu::IVec2 & viewportSize)2538 CoverageType calculateUnderestimateTriangleCoverage (const tcu::Vec4& p0, const tcu::Vec4& p1, const tcu::Vec4& p2, const tcu::IVec2& pixel, int subpixelBits, const tcu::IVec2& viewportSize)
2539 {
2540 	typedef tcu::Vector<deInt64, 2> I64Vec2;
2541 
2542 	const deUint64		numSubPixels						= ((deUint64)1) << subpixelBits;
2543 	const bool			order								= isTriangleClockwise(p0, p1, p2);			//!< clockwise / counter-clockwise
2544 	const tcu::Vec4&	orderedP0							= p0;										//!< vertices of a clockwise triangle
2545 	const tcu::Vec4&	orderedP1							= (order) ? (p1) : (p2);
2546 	const tcu::Vec4&	orderedP2							= (order) ? (p2) : (p1);
2547 	const tcu::Vec2		triangleNormalizedDeviceSpace[3]	=
2548 	{
2549 		tcu::Vec2(orderedP0.x() / orderedP0.w(), orderedP0.y() / orderedP0.w()),
2550 		tcu::Vec2(orderedP1.x() / orderedP1.w(), orderedP1.y() / orderedP1.w()),
2551 		tcu::Vec2(orderedP2.x() / orderedP2.w(), orderedP2.y() / orderedP2.w()),
2552 	};
2553 	const tcu::Vec2		triangleScreenSpace[3]				=
2554 	{
2555 		(triangleNormalizedDeviceSpace[0] + tcu::Vec2(1.0f, 1.0f)) * 0.5f * tcu::Vec2((float)viewportSize.x(), (float)viewportSize.y()),
2556 		(triangleNormalizedDeviceSpace[1] + tcu::Vec2(1.0f, 1.0f)) * 0.5f * tcu::Vec2((float)viewportSize.x(), (float)viewportSize.y()),
2557 		(triangleNormalizedDeviceSpace[2] + tcu::Vec2(1.0f, 1.0f)) * 0.5f * tcu::Vec2((float)viewportSize.x(), (float)viewportSize.y()),
2558 	};
2559 
2560 	// Broad bounding box - pixel check
2561 	{
2562 		const float minX = de::min(de::min(triangleScreenSpace[0].x(), triangleScreenSpace[1].x()), triangleScreenSpace[2].x());
2563 		const float minY = de::min(de::min(triangleScreenSpace[0].y(), triangleScreenSpace[1].y()), triangleScreenSpace[2].y());
2564 		const float maxX = de::max(de::max(triangleScreenSpace[0].x(), triangleScreenSpace[1].x()), triangleScreenSpace[2].x());
2565 		const float maxY = de::max(de::max(triangleScreenSpace[0].y(), triangleScreenSpace[1].y()), triangleScreenSpace[2].y());
2566 
2567 		if ((float)pixel.x() > maxX + 1 ||
2568 			(float)pixel.y() > maxY + 1 ||
2569 			(float)pixel.x() < minX - 1 ||
2570 			(float)pixel.y() < minY - 1)
2571 			return COVERAGE_NONE;
2572 	}
2573 
2574 	// Accurate intersection for edge pixels
2575 	{
2576 		//  In multisampling, the sample points can be anywhere in the pixel, and in single sampling only in the center.
2577 		const I64Vec2 pixelCorners[4] =
2578 		{
2579 			I64Vec2((pixel.x()+0) * numSubPixels, (pixel.y()+0) * numSubPixels),
2580 			I64Vec2((pixel.x()+1) * numSubPixels, (pixel.y()+0) * numSubPixels),
2581 			I64Vec2((pixel.x()+1) * numSubPixels, (pixel.y()+1) * numSubPixels),
2582 			I64Vec2((pixel.x()+0) * numSubPixels, (pixel.y()+1) * numSubPixels),
2583 		};
2584 		// both rounding directions
2585 		const I64Vec2 triangleSubPixelSpaceFloor[3] =
2586 		{
2587 			I64Vec2(deFloorFloatToInt32(triangleScreenSpace[0].x() * (float)numSubPixels), deFloorFloatToInt32(triangleScreenSpace[0].y() * (float)numSubPixels)),
2588 			I64Vec2(deFloorFloatToInt32(triangleScreenSpace[1].x() * (float)numSubPixels), deFloorFloatToInt32(triangleScreenSpace[1].y() * (float)numSubPixels)),
2589 			I64Vec2(deFloorFloatToInt32(triangleScreenSpace[2].x() * (float)numSubPixels), deFloorFloatToInt32(triangleScreenSpace[2].y() * (float)numSubPixels)),
2590 		};
2591 		const I64Vec2 triangleSubPixelSpaceCeil[3] =
2592 		{
2593 			I64Vec2(deCeilFloatToInt32(triangleScreenSpace[0].x() * (float)numSubPixels), deCeilFloatToInt32(triangleScreenSpace[0].y() * (float)numSubPixels)),
2594 			I64Vec2(deCeilFloatToInt32(triangleScreenSpace[1].x() * (float)numSubPixels), deCeilFloatToInt32(triangleScreenSpace[1].y() * (float)numSubPixels)),
2595 			I64Vec2(deCeilFloatToInt32(triangleScreenSpace[2].x() * (float)numSubPixels), deCeilFloatToInt32(triangleScreenSpace[2].y() * (float)numSubPixels)),
2596 		};
2597 
2598 		// Test if any edge (with any rounding) intersects the pixel (boundary). If it does => Partial. If not => fully inside or outside
2599 
2600 		for (int edgeNdx = 0; edgeNdx < 3; ++edgeNdx)
2601 		for (int startRounding = 0; startRounding < 4; ++startRounding)
2602 		for (int endRounding = 0; endRounding < 4; ++endRounding)
2603 		{
2604 			const int		nextEdgeNdx	= (edgeNdx+1) % 3;
2605 			const I64Vec2	startPos	((startRounding&0x01)	? (triangleSubPixelSpaceFloor[edgeNdx].x())		: (triangleSubPixelSpaceCeil[edgeNdx].x()),		(startRounding&0x02)	? (triangleSubPixelSpaceFloor[edgeNdx].y())		: (triangleSubPixelSpaceCeil[edgeNdx].y()));
2606 			const I64Vec2	endPos		((endRounding&0x01)		? (triangleSubPixelSpaceFloor[nextEdgeNdx].x())	: (triangleSubPixelSpaceCeil[nextEdgeNdx].x()),	(endRounding&0x02)		? (triangleSubPixelSpaceFloor[nextEdgeNdx].y())	: (triangleSubPixelSpaceCeil[nextEdgeNdx].y()));
2607 
2608 			for (int pixelEdgeNdx = 0; pixelEdgeNdx < 4; ++pixelEdgeNdx)
2609 			{
2610 				const int pixelEdgeEnd = (pixelEdgeNdx + 1) % 4;
2611 
2612 				if (lineLineIntersect(startPos, endPos, pixelCorners[pixelEdgeNdx], pixelCorners[pixelEdgeEnd]))
2613 					return COVERAGE_PARTIAL;
2614 			}
2615 		}
2616 
2617 		// fully inside or outside
2618 		for (int edgeNdx = 0; edgeNdx < 3; ++edgeNdx)
2619 		{
2620 			const int		nextEdgeNdx		= (edgeNdx+1) % 3;
2621 			const I64Vec2&	startPos		= triangleSubPixelSpaceFloor[edgeNdx];
2622 			const I64Vec2&	endPos			= triangleSubPixelSpaceFloor[nextEdgeNdx];
2623 			const I64Vec2	edge			= endPos - startPos;
2624 			const I64Vec2	v				= pixelCorners[0] - endPos;
2625 			const deInt64	crossProduct	= (edge.x() * v.y() - edge.y() * v.x());
2626 
2627 			// a corner of the pixel is outside => "fully inside" option is impossible
2628 			if (crossProduct < 0)
2629 				return COVERAGE_NONE;
2630 		}
2631 
2632 		return COVERAGE_FULL;
2633 	}
2634 }
2635 
logTriangleGroupRasterizationStash(const tcu::Surface & surface,tcu::TestLog & log,VerifyTriangleGroupRasterizationLogStash & logStash)2636 static void logTriangleGroupRasterizationStash (const tcu::Surface& surface, tcu::TestLog& log, VerifyTriangleGroupRasterizationLogStash& logStash)
2637 {
2638 	// Output results
2639 	log << tcu::TestLog::Message << "Verifying rasterization result." << tcu::TestLog::EndMessage;
2640 
2641 	for (size_t msgNdx = 0; msgNdx < logStash.messages.size(); ++msgNdx)
2642 		log << tcu::TestLog::Message << logStash.messages[msgNdx] << tcu::TestLog::EndMessage;
2643 
2644 	if (!logStash.result)
2645 	{
2646 		log << tcu::TestLog::Message << "Invalid pixels found:\n\t"
2647 			<< logStash.missingPixels << " missing pixels. (Marked with purple)\n\t"
2648 			<< logStash.unexpectedPixels << " incorrectly filled pixels. (Marked with red)\n\t"
2649 			<< "Unknown (subpixel on edge) pixels are marked with yellow."
2650 			<< tcu::TestLog::EndMessage;
2651 		log << tcu::TestLog::ImageSet("Verification result", "Result of rendering")
2652 			<< tcu::TestLog::Image("Result",	"Result",		surface)
2653 			<< tcu::TestLog::Image("ErrorMask", "ErrorMask",	logStash.errorMask)
2654 			<< tcu::TestLog::EndImageSet;
2655 	}
2656 	else
2657 	{
2658 		log << tcu::TestLog::Message << "No invalid pixels found." << tcu::TestLog::EndMessage;
2659 		log << tcu::TestLog::ImageSet("Verification result", "Result of rendering")
2660 			<< tcu::TestLog::Image("Result", "Result", surface)
2661 			<< tcu::TestLog::EndImageSet;
2662 	}
2663 }
2664 
verifyTriangleGroupRasterization(const tcu::Surface & surface,const TriangleSceneSpec & scene,const RasterizationArguments & args,tcu::TestLog & log,VerificationMode mode,VerifyTriangleGroupRasterizationLogStash * logStash,const bool vulkanLinesTest)2665 bool verifyTriangleGroupRasterization (const tcu::Surface& surface, const TriangleSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log, VerificationMode mode, VerifyTriangleGroupRasterizationLogStash* logStash, const bool vulkanLinesTest)
2666 {
2667 	DE_ASSERT(mode < VERIFICATIONMODE_LAST);
2668 
2669 	const tcu::RGBA		backGroundColor				= tcu::RGBA(0, 0, 0, 255);
2670 	const tcu::RGBA		triangleColor				= tcu::RGBA(255, 255, 255, 255);
2671 	const tcu::RGBA		missingPixelColor			= tcu::RGBA(255, 0, 255, 255);
2672 	const tcu::RGBA		unexpectedPixelColor		= tcu::RGBA(255, 0, 0, 255);
2673 	const tcu::RGBA		partialPixelColor			= tcu::RGBA(255, 255, 0, 255);
2674 	const tcu::RGBA		primitivePixelColor			= tcu::RGBA(30, 30, 30, 255);
2675 	const int			weakVerificationThreshold	= 10;
2676 	const int			weakerVerificationThreshold	= 25;
2677 	const bool			multisampled				= (args.numSamples != 0);
2678 	const tcu::IVec2	viewportSize				= tcu::IVec2(surface.getWidth(), surface.getHeight());
2679 	int					missingPixels				= 0;
2680 	int					unexpectedPixels			= 0;
2681 	int					subPixelBits				= args.subpixelBits;
2682 	tcu::TextureLevel	coverageMap					(tcu::TextureFormat(tcu::TextureFormat::R, tcu::TextureFormat::UNSIGNED_INT8), surface.getWidth(), surface.getHeight());
2683 	tcu::Surface		errorMask					(surface.getWidth(), surface.getHeight());
2684 	bool				result						= false;
2685 
2686 	// subpixel bits in a valid range?
2687 
2688 	if (subPixelBits < 0)
2689 	{
2690 		log << tcu::TestLog::Message << "Invalid subpixel count (" << subPixelBits << "), assuming 0" << tcu::TestLog::EndMessage;
2691 		subPixelBits = 0;
2692 	}
2693 	else if (subPixelBits > 16)
2694 	{
2695 		// At high subpixel bit counts we might overflow. Checking at lower bit count is ok, but is less strict
2696 		log << tcu::TestLog::Message << "Subpixel count is greater than 16 (" << subPixelBits << "). Checking results using less strict 16 bit requirements. This may produce false positives." << tcu::TestLog::EndMessage;
2697 		subPixelBits = 16;
2698 	}
2699 
2700 	// generate coverage map
2701 
2702 	tcu::clear(coverageMap.getAccess(), tcu::IVec4(COVERAGE_NONE, 0, 0, 0));
2703 
2704 	for (int triNdx = 0; triNdx < (int)scene.triangles.size(); ++triNdx)
2705 	{
2706 		const tcu::IVec4 aabb = getTriangleAABB(scene.triangles[triNdx], viewportSize);
2707 
2708 		for (int y = de::max(0, aabb.y()); y <= de::min(aabb.w(), coverageMap.getHeight() - 1); ++y)
2709 		for (int x = de::max(0, aabb.x()); x <= de::min(aabb.z(), coverageMap.getWidth() - 1); ++x)
2710 		{
2711 			if (coverageMap.getAccess().getPixelUint(x, y).x() == COVERAGE_FULL)
2712 				continue;
2713 
2714 			const CoverageType coverage = calculateTriangleCoverage(scene.triangles[triNdx].positions[0],
2715 																	scene.triangles[triNdx].positions[1],
2716 																	scene.triangles[triNdx].positions[2],
2717 																	tcu::IVec2(x, y),
2718 																	viewportSize,
2719 																	subPixelBits,
2720 																	multisampled);
2721 
2722 			if (coverage == COVERAGE_FULL)
2723 			{
2724 				coverageMap.getAccess().setPixel(tcu::IVec4(COVERAGE_FULL, 0, 0, 0), x, y);
2725 			}
2726 			else if (coverage == COVERAGE_PARTIAL)
2727 			{
2728 				CoverageType resultCoverage = COVERAGE_PARTIAL;
2729 
2730 				// Sharing an edge with another triangle?
2731 				// There should always be such a triangle, but the pixel in the other triangle might be
2732 				// on multiple edges, some of which are not shared. In these cases the coverage cannot be determined.
2733 				// Assume full coverage if the pixel is only on a shared edge in shared triangle too.
2734 				if (pixelOnlyOnASharedEdge(tcu::IVec2(x, y), scene.triangles[triNdx], viewportSize))
2735 				{
2736 					bool friendFound = false;
2737 					for (int friendTriNdx = 0; friendTriNdx < (int)scene.triangles.size(); ++friendTriNdx)
2738 					{
2739 						if (friendTriNdx == triNdx)
2740 							continue;
2741 
2742 						const CoverageType friendCoverage	= calculateTriangleCoverage(scene.triangles[friendTriNdx].positions[0],
2743 																						scene.triangles[friendTriNdx].positions[1],
2744 																						scene.triangles[friendTriNdx].positions[2],
2745 																						tcu::IVec2(x, y),
2746 																						viewportSize,
2747 																						subPixelBits,
2748 																						multisampled);
2749 
2750 						if (friendCoverage != COVERAGE_NONE && pixelOnlyOnASharedEdge(tcu::IVec2(x, y), scene.triangles[friendTriNdx], viewportSize))
2751 						{
2752 							friendFound = true;
2753 							break;
2754 						}
2755 					}
2756 
2757 					if (friendFound)
2758 						resultCoverage = COVERAGE_FULL;
2759 				}
2760 
2761 				coverageMap.getAccess().setPixel(tcu::IVec4(resultCoverage, 0, 0, 0), x, y);
2762 			}
2763 		}
2764 	}
2765 
2766 	// check pixels
2767 
2768 	tcu::clear(errorMask.getAccess(), tcu::Vec4(0.0f, 0.0f, 0.0f, 1.0f));
2769 
2770 	// Use these to sanity check there is something drawn when a test expects something else than an empty picture.
2771 	bool referenceEmpty	= true;
2772 	bool resultEmpty	= true;
2773 
2774 	for (int y = 0; y < surface.getHeight(); ++y)
2775 	for (int x = 0; x < surface.getWidth(); ++x)
2776 	{
2777 		const tcu::RGBA		color				= surface.getPixel(x, y);
2778 		const bool			imageNoCoverage		= compareColors(color, backGroundColor, args.redBits, args.greenBits, args.blueBits);
2779 		const bool			imageFullCoverage	= compareColors(color, triangleColor, args.redBits, args.greenBits, args.blueBits);
2780 		CoverageType		referenceCoverage	= (CoverageType)coverageMap.getAccess().getPixelUint(x, y).x();
2781 
2782 		if (!imageNoCoverage)
2783 			resultEmpty = false;
2784 
2785 		switch (referenceCoverage)
2786 		{
2787 			case COVERAGE_NONE:
2788 				if (!imageNoCoverage)
2789 				{
2790 					// coverage where there should not be
2791 					++unexpectedPixels;
2792 					errorMask.setPixel(x, y, unexpectedPixelColor);
2793 				}
2794 				break;
2795 
2796 			case COVERAGE_PARTIAL:
2797 				{
2798 					referenceEmpty = false;
2799 					bool foundFragment = false;
2800 					if (vulkanLinesTest == true)
2801 					{
2802 						for (int dy = -1; dy < 2 && !foundFragment; ++dy)
2803 							for (int dx = -1; dx < 2 && !foundFragment; ++dx)
2804 							{
2805 								if (x + dx >= 0 && x + dx != surface.getWidth() && y + dy >= 0 && y + dy != surface.getHeight()
2806 									&& (CoverageType)coverageMap.getAccess().getPixelUint(x + dx, y + dy).x() != COVERAGE_NONE)
2807 								{
2808 									const tcu::RGBA color2 = surface.getPixel(x + dx , y + dy);
2809 									if (compareColors(color2, triangleColor, args.redBits, args.greenBits, args.blueBits))
2810 										foundFragment = true;
2811 								}
2812 							}
2813 					}
2814 					// anything goes
2815 					if (foundFragment == false)
2816 					{
2817 						errorMask.setPixel(x, y, partialPixelColor);
2818 						if (vulkanLinesTest == true)
2819 							++missingPixels;
2820 					}
2821 				}
2822 				break;
2823 
2824 			case COVERAGE_FULL:
2825 				referenceEmpty = false;
2826 				if (!imageFullCoverage)
2827 				{
2828 					// no coverage where there should be
2829 					++missingPixels;
2830 					errorMask.setPixel(x, y, missingPixelColor);
2831 				}
2832 				else
2833 				{
2834 					errorMask.setPixel(x, y, primitivePixelColor);
2835 				}
2836 				break;
2837 
2838 			default:
2839 				DE_ASSERT(false);
2840 		};
2841 	}
2842 
2843 	if (((mode == VERIFICATIONMODE_STRICT) && (missingPixels + unexpectedPixels > 0)) ||
2844 		((mode == VERIFICATIONMODE_WEAK)   && (missingPixels + unexpectedPixels > weakVerificationThreshold)) ||
2845 		((mode == VERIFICATIONMODE_WEAKER) && (missingPixels + unexpectedPixels > weakerVerificationThreshold)) ||
2846 		((mode == VERIFICATIONMODE_SMOOTH) && (missingPixels > weakVerificationThreshold)) ||
2847 		referenceEmpty != resultEmpty)
2848 	{
2849 		result = false;
2850 	}
2851 	else
2852 	{
2853 		result = true;
2854 	}
2855 
2856 	// Output or stash results
2857 	{
2858 		VerifyTriangleGroupRasterizationLogStash* tempLogStash = (logStash == DE_NULL) ? new VerifyTriangleGroupRasterizationLogStash : logStash;
2859 
2860 		tempLogStash->result			= result;
2861 		tempLogStash->missingPixels		= missingPixels;
2862 		tempLogStash->unexpectedPixels	= unexpectedPixels;
2863 		tempLogStash->errorMask			= errorMask;
2864 
2865 		if (logStash == DE_NULL)
2866 		{
2867 			logTriangleGroupRasterizationStash(surface, log, *tempLogStash);
2868 			delete tempLogStash;
2869 		}
2870 	}
2871 
2872 	return result;
2873 }
2874 
verifyLineGroupRasterization(const tcu::Surface & surface,const LineSceneSpec & scene,const RasterizationArguments & args,tcu::TestLog & log)2875 bool verifyLineGroupRasterization (const tcu::Surface& surface, const LineSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log)
2876 {
2877 	const bool multisampled = args.numSamples != 0;
2878 
2879 	if (multisampled)
2880 		return verifyMultisampleLineGroupRasterization(surface, scene, args, log, CLIPMODE_NO_CLIPPING, DE_NULL, false, true);
2881 	else
2882 		return verifySinglesampleLineGroupRasterization(surface, scene, args, log);
2883 }
2884 
verifyClippedTriangulatedLineGroupRasterization(const tcu::Surface & surface,const LineSceneSpec & scene,const RasterizationArguments & args,tcu::TestLog & log)2885 bool verifyClippedTriangulatedLineGroupRasterization (const tcu::Surface& surface, const LineSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log)
2886 {
2887 	return verifyMultisampleLineGroupRasterization(surface, scene, args, log, CLIPMODE_USE_CLIPPING_BOX, DE_NULL, false, true);
2888 }
2889 
verifyRelaxedLineGroupRasterization(const tcu::Surface & surface,const LineSceneSpec & scene,const RasterizationArguments & args,tcu::TestLog & log,const bool vulkanLinesTest,const bool strict)2890 bool verifyRelaxedLineGroupRasterization (const tcu::Surface& surface, const LineSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log, const bool vulkanLinesTest, const bool strict)
2891 {
2892 	VerifyTriangleGroupRasterizationLogStash useClippingLogStash;
2893 	VerifyTriangleGroupRasterizationLogStash noClippingLogStash;
2894 	VerifyTriangleGroupRasterizationLogStash useClippingForcedStrictLogStash;
2895 	VerifyTriangleGroupRasterizationLogStash noClippingForcedStrictLogStash;
2896 
2897 	if (verifyMultisampleLineGroupRasterization(surface, scene, args, log, CLIPMODE_USE_CLIPPING_BOX, &useClippingLogStash, vulkanLinesTest, strict))
2898 	{
2899 		logTriangleGroupRasterizationStash(surface, log, useClippingLogStash);
2900 
2901 		return true;
2902 	}
2903 	else if (verifyMultisampleLineGroupRasterization(surface, scene, args, log, CLIPMODE_NO_CLIPPING, &noClippingLogStash, vulkanLinesTest, strict))
2904 	{
2905 		logTriangleGroupRasterizationStash(surface, log, noClippingLogStash);
2906 
2907 		return true;
2908 	}
2909 	else if (strict == false && verifyMultisampleLineGroupRasterization(surface, scene, args, log, CLIPMODE_USE_CLIPPING_BOX, &useClippingForcedStrictLogStash, vulkanLinesTest, true))
2910 	{
2911 		logTriangleGroupRasterizationStash(surface, log, useClippingForcedStrictLogStash);
2912 
2913 		return true;
2914 	}
2915 	else if (strict == false && verifyMultisampleLineGroupRasterization(surface, scene, args, log, CLIPMODE_NO_CLIPPING, &noClippingForcedStrictLogStash, vulkanLinesTest, true))
2916 	{
2917 		logTriangleGroupRasterizationStash(surface, log, noClippingForcedStrictLogStash);
2918 
2919 		return true;
2920 	}
2921 	else if (strict == false && args.numSamples == 0 && verifyLineGroupRasterization(surface, scene, args, log))
2922 	{
2923 		return true;
2924 	}
2925 	else
2926 	{
2927 		log << tcu::TestLog::Message << "Relaxed rasterization failed, details follow." << tcu::TestLog::EndMessage;
2928 
2929 		logTriangleGroupRasterizationStash(surface, log, useClippingLogStash);
2930 		logTriangleGroupRasterizationStash(surface, log, noClippingLogStash);
2931 
2932 		if (strict == false)
2933 		{
2934 			logTriangleGroupRasterizationStash(surface, log, useClippingForcedStrictLogStash);
2935 			logTriangleGroupRasterizationStash(surface, log, noClippingForcedStrictLogStash);
2936 		}
2937 
2938 		return false;
2939 	}
2940 }
2941 
verifyPointGroupRasterization(const tcu::Surface & surface,const PointSceneSpec & scene,const RasterizationArguments & args,tcu::TestLog & log)2942 bool verifyPointGroupRasterization (const tcu::Surface& surface, const PointSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log)
2943 {
2944 	// Splitting to triangles is a valid solution in multisampled cases and even in non-multisample cases too.
2945 	return verifyMultisamplePointGroupRasterization(surface, scene, args, log);
2946 }
2947 
verifyTriangleGroupInterpolation(const tcu::Surface & surface,const TriangleSceneSpec & scene,const RasterizationArguments & args,tcu::TestLog & log)2948 bool verifyTriangleGroupInterpolation (const tcu::Surface& surface, const TriangleSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log)
2949 {
2950 	VerifyTriangleGroupInterpolationLogStash	logStash;
2951 	const bool									result		= verifyTriangleGroupInterpolationWithInterpolator(surface, scene, args, logStash, TriangleInterpolator(scene));
2952 
2953 	logTriangleGroupnterpolationStash(surface, log, logStash);
2954 
2955 	return result;
2956 }
2957 
verifyLineGroupInterpolation(const tcu::Surface & surface,const LineSceneSpec & scene,const RasterizationArguments & args,tcu::TestLog & log)2958 LineInterpolationMethod verifyLineGroupInterpolation (const tcu::Surface& surface, const LineSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log)
2959 {
2960 	const bool multisampled = args.numSamples != 0;
2961 
2962 	if (multisampled)
2963 	{
2964 		if (verifyMultisampleLineGroupInterpolation(surface, scene, args, log))
2965 			return LINEINTERPOLATION_STRICTLY_CORRECT;
2966 		return LINEINTERPOLATION_INCORRECT;
2967 	}
2968 	else
2969 	{
2970 		const bool isNarrow = (scene.lineWidth == 1.0f);
2971 
2972 		// accurate interpolation
2973 		if (isNarrow)
2974 		{
2975 			if (verifySinglesampleNarrowLineGroupInterpolation(surface, scene, args, log))
2976 				return LINEINTERPOLATION_STRICTLY_CORRECT;
2977 		}
2978 		else
2979 		{
2980 			if (verifySinglesampleWideLineGroupInterpolation(surface, scene, args, log))
2981 				return LINEINTERPOLATION_STRICTLY_CORRECT;
2982 		}
2983 
2984 		// check with projected (inaccurate) interpolation
2985 		log << tcu::TestLog::Message << "Accurate verification failed, checking with projected weights (inaccurate equation)." << tcu::TestLog::EndMessage;
2986 		if (verifyLineGroupInterpolationWithProjectedWeights(surface, scene, args, log))
2987 			return LINEINTERPOLATION_PROJECTED;
2988 
2989 		return LINEINTERPOLATION_INCORRECT;
2990 	}
2991 }
2992 
verifyTriangulatedLineGroupInterpolation(const tcu::Surface & surface,const LineSceneSpec & scene,const RasterizationArguments & args,tcu::TestLog & log,const bool strictMode,const bool allowBresenhamForNonStrictLines)2993 bool verifyTriangulatedLineGroupInterpolation (const tcu::Surface& surface, const LineSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log, const bool strictMode, const bool allowBresenhamForNonStrictLines)
2994 {
2995 	return verifyMultisampleLineGroupInterpolation(surface, scene, args, log, strictMode, allowBresenhamForNonStrictLines);
2996 }
2997 
2998 } // tcu
2999