11

This is the syntax of the SDL_CreateTextureFromSurface function:

SDL_Texture* SDL_CreateTextureFromSurface(SDL_Renderer* renderer, SDL_Surface*  surface)

However, I'm confused why we need to pass a renderer*? I thought we need a renderer* only when drawing the texture?

Stoatman
  • 758
  • 3
  • 9
  • 22

2 Answers2

11

You need SDL_Renderer to get information about the applicable constraints:

  • maximum supported size
  • pixel format

And probably something more..

plaes
  • 31,788
  • 11
  • 91
  • 89
  • Isn't a resulting texture only usable in a renderer that was passed as an argument to `SDL_CreateTextureFromSurface`? – HolyBlackCat Dec 25 '15 at 22:23
  • A SDL_Texture is stored in the VRAM of your graphics card using whatever API your setup for your renderer(opengl v DX v whatever) so you have to have the renderer to setup and store the texture in the GPU's VRAM. – Matthew Clark Feb 22 '17 at 19:57
5

In addition to the answer by plaes..

Under the hood, SDL_CreateTextureFromSurface calls SDL_CreateTexture, which itself also needs a Renderer, to create a new texture with the same size as the passed in surface.

Then the the SDL_UpdateTexture function is called on the new created texture to load(copy) the pixel data from the surface you passed in to SDL_CreateTextureFromSurface. If the formats between the passed-in surface differ from what the renderer supports, more logic happens to ensure correct behavior.

The Renderer itself is needed for SDL_CreateTexture because its the GPU that handles and stores textures (most of the time) and the Renderer is supposed to be an abstraction over the GPU.

A surface never needs a Renderer since its loaded in RAM and handled by the CPU.

You can find out more about how these calls work if you look at SDL_render.c from the SDL2 source code.

Here is some code inside SDL_CreateTextureFromSurface:

texture = SDL_CreateTexture(renderer, format, SDL_TEXTUREACCESS_STATIC,
                            surface->w, surface->h);
if (!texture) {
    return NULL;
}

if (format == surface->format->format) {
    if (SDL_MUSTLOCK(surface)) {
        SDL_LockSurface(surface);
        SDL_UpdateTexture(texture, NULL, surface->pixels, surface->pitch);
        SDL_UnlockSurface(surface);
    } else {
        SDL_UpdateTexture(texture, NULL, surface->pixels, surface->pitch);
    }
}
taher1992
  • 83
  • 1
  • 6