manudicri
manudicri

Reputation: 173

differences between drawing a line or many points

I'm using C++ with SDL2 engine.

I don't understand why drawing a line with width:10000 is faster than make a loop of 10000 iterations and draw all the points that make up the line.

Drawing a line:

SDL_RenderDrawLine(Renderer, 0, 100, 10000, 100);

Drawing 10000 points:

for(unsigned k=0; k<10000; k++) {
    SDL_RenderDrawPoint(Renderer, 0+k, 100);
}

Why drawing all the points kills the program performance? I think the draw_line function does the same...

I'd like to know why this because i'm trying to create some functions about shaders..

Upvotes: 4

Views: 1707

Answers (1)

genpfault
genpfault

Reputation: 52084

Driver function-call overhead. SDL_Renderer (or at least the OpenGL backend) makes no attempt to batch together multiple non-s calls (SDL_RenderDrawLine()/SDL_RenderDrawPoint()/SDL_RenderDrawRect()/SDL_RenderFillRect()) together, it just calls the s variants with count = 1:

// src/render/SDL_render.c#l1558
int
SDL_RenderDrawPoint(SDL_Renderer * renderer, int x, int y)
{
    SDL_Point point;

    point.x = x;
    point.y = y;
    return SDL_RenderDrawPoints(renderer, &point, 1);
}

And the s functions (SDL_RenderDrawLines()/SDL_RenderDrawPoints()/SDL_RenderDrawRects()/SDL_RenderFillRects()) generally just splat out their draws to the driver right then and there:

// src/render/opengl/SDL_render_gl.c#l1220
static int
GL_RenderDrawPoints(SDL_Renderer * renderer, const SDL_FPoint * points,
                    int count)
{
    GL_RenderData *data = (GL_RenderData *) renderer->driverdata;
    int i;

    GL_SetDrawingState(renderer);

    data->glBegin(GL_POINTS);
    for (i = 0; i < count; ++i) {
        data->glVertex2f(0.5f + points[i].x, 0.5f + points[i].y);
    }
    data->glEnd();

    return 0;
}

A more sophisticated backend could collect geometry into larger buffers and only issue actual draw-calls to the driver when absolutely required by the API's ordering semantics. Batching geometry and draw-calls together like that generally gives you much greater throughput.

Upvotes: 5

Related Questions