Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SDL2 - Why does SDL_CreateTextureFromSurface() need a renderer*?

Tags:

c++

sdl

sdl-2

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?

like image 312
Stoatman Avatar asked Dec 23 '15 05:12

Stoatman


2 Answers

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);
    }
}
like image 145
taher1992 Avatar answered Nov 15 '22 18:11

taher1992


You need SDL_Renderer to get information about the applicable constraints:

  • maximum supported size
  • pixel format

And probably something more..

like image 35
plaes Avatar answered Nov 15 '22 17:11

plaes