Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to optimize rendering of many textures in SDL 2?

I'm using SDL 2 and I have a 2D-array of 8x8 px blocks:

    SDL_RenderClear(renderer);
    SDL_SetRenderDrawColor(renderer, 0xdf, 0xef, 0xff, 0xff);
    for (s32 y = 0, Y = 0; y < worldSize.y; y++, Y += blockSize)
        for (s32 x = 0, X = 0; x < worldSize.x; x++, X += blockSize)
            if (block[x][y].GetMaterial())
            {
                if (block[x][y].IsSolid())
                {
                    SDL_Rect src =
                    {
                        block[x][y].GetTileVariant() * blockSize,
                        block[x][y].GetTile() * blockSize,
                        blockSize,
                        blockSize
                    };
                    SDL_Rect dst =
                    {
                        X + (s32)posX,
                        Y + (s32)posY,
                        blockSize,
                        blockSize
                    };
                    SDL_RenderCopy(renderer, materials[block[x][y].GetMaterial()]->texture, &src, &dst);
                }
            }
    SDL_RenderPresent(renderer);

So here I use a few textures in random order, e.g.: 1, 2, 5, 2, 2, 3, 1, etc. And if it fills all screen (1920x1080), it stars to lag. Not so much, but anyway aloud. So my question is: how to optimize it? What should I use? I need some code example. At last, should I write something on openGL by my own or what to do?

like image 587
Necronomicron Avatar asked Feb 02 '26 06:02

Necronomicron


1 Answers

Try grouping your SDL_RenderCopy() calls by material/texture and hope your OpenGL driver fast-paths redundant glBindTexture()s.

And/or group all your tiles into one large texture atlas.

Or if your tiles aren't actually moving/changing frame-to-frame blit them into one large texture and render that instead.

Longer-term, bug Sam on the mailing list for something like SDL_RenderCopyBatch(), similar to SDL_RenderDrawRects().

like image 140
genpfault Avatar answered Feb 04 '26 20:02

genpfault