views:

371

answers:

1

I wrote up this simple C program to test basic SDL 1.3 functionality. Everything works, with one minor problem. The colorkey doesn't get converted. I'm loading an 8-bit PNG sprite file where palette index #0 is the background color. I'd expect to see only the sprites displayed, but what I get is the entire image, including the background color.

Any idea what's going on or how to fix it? This was written in Visual C++ 2005.

// SDL test.c : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "sdl.h"
#include "sdl_image.h"
#include <stdio.h>

int _tmain(int argc, _TCHAR* argv[])
{
    int windowID;
    int textureID;
    SDL_Surface* surface;
    char* dummy = "";
    SDL_Color color;

    SDL_Init(SDL_INIT_VIDEO);

    windowID = SDL_CreateWindow("SDL Test", 400, 400, 320, 240, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
    if (windowID == 0)
    {
        printf("Unable to create window: %s\n", SDL_GetError());
    }
    else printf("Window created: %d\n", windowID);

    if (SDL_CreateRenderer(windowID, -1, SDL_RENDERER_PRESENTFLIP2) != 0)
    {
        printf("Unable to create renderer: %s\n", SDL_GetError());
    }
    else printf("Renderer created successfully.\n");

    if (SDL_SelectRenderer(windowID) != 0)
    {
        printf("Unable to select renderer: %s\n", SDL_GetError());
    }
    else printf("Renderer selected successfully\n");

    SDL_RenderPresent();

    surface = IMG_Load("<INSERT FILENAME HERE>");
    if (!surface)
    {
        printf("Unable to load image!\n");
    }
    else printf("Image Loaded\n");

    color = surface->format->palette->colors[0];
    SDL_SetColorKey(surface, 1, SDL_MapRGB(surface->format, color.r, color.g, color.b));

    textureID = SDL_CreateTextureFromSurface(0, surface);
    if (textureID == 0)
    {
        printf("Unable to create texture: %s\n", SDL_GetError());
    }
    else printf("Texture created: %d\n", textureID);

    SDL_FreeSurface(surface);

    if (SDL_RenderCopy(textureID, NULL, NULL) != 0)
    {
        printf("Unable to render texture: %s", SDL_GetError());
    }

    SDL_RenderPresent();

    scanf_s("%s", dummy);
    return 0;
}

EDIT: This turned out to be due to a bug in SDL_CreateTextureFromSurface, which I ended up submitting a patch for.

A: 

You should probably convert the surface to the display format before use.

...
surface = IMG_Load("<INSERT FILENAME HERE>");
SDL_DisplayFormat(surface);
SDL_SetColorKey(surface, 1, SDL_MapRGB(surface->format, color.r, color.g, color.b));
...

Always a good idea to do this so you're absolutely sure that all images has the same format and gives the right results when using the SDL functions.

Although I'm only familiar with the 1.2 version and don't have a clue what's been changed in the 1.3.

Sir Oddfellow
I eventually found the problem. It was a bug in the conversion routine.
Mason Wheeler