Is there an efficient way to fill a triangle with SDL2?

35 Views Asked by At

I built a function that takes seven arguments, including x1, y1, x2, y2, x3, y3 and the renderer. It then draws a filled triangle to the screen. It works without any issues except that it's very slow and I assume that this performance problem is due to this line: SDL_RenderDrawPoint(renderer, j, i);, since without it the code is way faster. And if there are any other improvements i could do please let me know.

Here is the function i wrote:

void SDL_RenderFillTriangle(SDL_Renderer *renderer, int x1, int y1, int x2, int y2, int x3, int y3)
{
    int minX = std::min({x1, x2, x3});
    int maxX = std::max({x1, x2, x3});
    int minY = std::min({y1, y2, y3});
    int maxY = std::max({y1, y2, y3});

    const float epsilon = 0.001f;

    float denom = (y2 - y3) * (x1 - x3) + (x3 - x2) * (y1 - y3);

    for (int i = minY; i <= maxY; i++)
    {
        for (int j = minX; j <= maxX; j++)
        {
            float u = ((y2 - y3) * (j - x3) + (x3 - x2) * (i - y3)) / denom;
            float v = ((y3 - y1) * (j - x3) + (x1 - x3) * (i - y3)) / denom;
            float w = 1 - u - v;

            if (-epsilon <= u && u <= 1 + epsilon && -epsilon <= v && v <= 1 + epsilon && -epsilon <= w && w <= 1 + epsilon)
            {
                SDL_RenderDrawPoint(renderer, j, i);
            }
        }
    }
}
0

There are 0 best solutions below