tinyrenderer icon indicating copy to clipboard operation
tinyrenderer copied to clipboard

An error in triangle rasterisation

Open DaveBy opened this issue 6 years ago • 1 comments

Hi. I used your triangle rasterisation code and found a problem when drawing two adjacent triangles. Sometimes there are missing pixels between them. image I found that the problem is how you calculate int segment_height = t1.y - t0.y + 1 the "+1" leads to the error. I assume you made it to avoid division by zero, but it's wrong. Here is how a did it:

	auto addTriangle = [ & ]( Vec2i t0, Vec2i t1, Vec2i t2 )
	{
		if ( t0.y > t1.y ) std::swap( t0, t1 );
		if ( t0.y > t2.y ) std::swap( t0, t2 );
		if ( t1.y > t2.y ) std::swap( t1, t2 );
		int total_height = t2.y - t0.y;

		if ( t0.y != t1.y )
		{
			int segment_height = t1.y - t0.y;
			for ( int y = t0.y; y <= t1.y; y++ )
			{
				int A = t0.x + ( t2.x - t0.x ) * ( y - t0.y ) / total_height;
				int B = t0.x + ( t1.x - t0.x ) * ( y - t0.y ) / segment_height;
				drawLine( y, A, B ); // draws a horisontal line
			}
		}

		if ( t1.y != t2.y )
		{
			int segment_height = t2.y - t1.y;
			for ( int y = t1.y; y <= t2.y; y++ )
			{
				int A = t0.x + ( t2.x - t0.x ) * ( y - t0.y ) / total_height;
				int B = t1.x + ( t2.x - t1.x ) * ( y - t1.y ) / segment_height;
				drawLine( y, A, B );
			}
		}
	};

DaveBy avatar Mar 31 '19 13:03 DaveBy

Thank you, nice catch.

ssloy avatar Mar 31 '19 14:03 ssloy