Search code examples
c++sdlrenderersdl-image

SDL Error: Invalid Renderer on SDL_CreateTextureFromSurface


Alrighty, from what I have researched, it appears that the Invalid Renderer error applies to a variety of cases and I'm lost onto why my code is creating it. I have narrowed it down to a specific area of code

//If existing texture is there, free's and sets to NULL. Along with iWidth & iHeight = 0;
freetexture();

//final image texture
SDL_Texture* niTexture = NULL;

//Loads image at specified path
SDL_Surface* loadedSurface = IMG_Load(path.c_str());
if (loadedSurface == NULL)
{
    printf("Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError());
}
else
{
    printf("SpriteSheet :: Loaded\n");
    Init mkey;
    //Color key DOUBLE CHECK IF ERROR CHANGE TO ORIGINAL 0, 0xFF, 0xFF
    SDL_SetColorKey(loadedSurface, SDL_TRUE, SDL_MapRGB(loadedSurface->format, 50, 96, 166));

    //create texture from surface pixels
    niTexture = SDL_CreateTextureFromSurface(mkey.Renderer, loadedSurface);
    if (niTexture == NULL)
    {
        printf("Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError());
    }

Specifically at the line,

niTexture = SDL_CreateTextureFromSurface(mkey.Renderer, loadedSurface);

is causing SDL to return an Invalid renderer error. In my init class, the renderer initializes perfectly, only when I attempt to use it to load an image am I getting the Invalid Renderer error. Any help on how to fix this error is appreciated.

Edit:: Here's some code from the Init Class relating to the renderer,

printf("Linear Texture Filtering :: Enabled\n");
        //Create Window
        Window = SDL_CreateWindow("Test", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, sw, sh, SDL_WINDOW_SHOWN);
        if (Window == NULL)
        {
            printf("Window failed to be created\n");
            SDLSuccess = false;
        }
        else
        {
            printf("Window :: Created\n");
            //Create VYNC'd renderer for the window
            Renderer = SDL_CreateRenderer(Window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
            if (Renderer == NULL)
            {
                printf("Renderer failed to be created\n");
                SDLSuccess = false;

            }

Hope this helps with finding the issue.


Solution

  • It looks like your Renderer isn't initialized, unless the code you posted is in the constructor of your Init class.

    Do you already have an instance of Init somewhere in your code that you mean to be referencing in your texture method? Check the value of your Renderer before you try to use it, something like:

    if (mkey.Renderer) {
        niTexture = SDL_CreateTextureFromSurface(mkey.Renderer, loadedSurface);
        if (niTexture == NULL)
        {
            printf("Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError());
        }
    } else {
        printf("Renderer is not initialized");
    }