I have a problem with SDL2, I'm trying to render a fully red surface with SDL2 but it doesn't work, the window closes immediately, it seems like the program exits in SDL_RenderPresent() function, I think the wrong part is my fillSurface function but I don't see what I did wrong (I'm trying to fill a SDL_Surface in red pixel by pixel then display it on screen), thanks for the help.
Here's my code:
#include <header.h>
int fillSurface(SDL_Surface *surface, unsigned char r, unsigned char g, unsigned char b, unsigned char a)
{
uint32_t color;
uint32_t *pixels;
int i;
if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
color = a + (((uint32_t)b) << 8) + (((uint32_t)g) << 16) + (((uint32_t)r) << 24);
else
color = r + (((uint32_t)g) << 8) + (((uint32_t)b) << 16) + (((uint32_t)a) << 24);
if (SDL_LockSurface(surface))
return (-1);
pixels = (uint32_t*)surface->pixels;
i = 0;
while (i < surface->w * surface->h)
pixels[i++] = color;
SDL_UnlockSurface(surface);
return (0);
}
int exitFailure(t_sdlVar *sdl)
{
if (sdl->renderer)
SDL_DestroyRenderer(sdl->renderer);
if (sdl->screenSurface)
SDL_FreeSurface(sdl->screenSurface);
if (sdl->screenTexture)
SDL_DestroyTexture(sdl->screenTexture);
if (sdl->window)
SDL_DestroyWindow(sdl->window);
sdl->renderer = NULL;
sdl->screenSurface = NULL;
sdl->screenTexture = NULL;
sdl->window = NULL;
SDL_Quit();
return (-1);
}
int main(void)
{
t_sdlVar sdl;
sdl.renderer = NULL;
sdl.screenSurface = NULL;
sdl.screenTexture = NULL;
sdl.window = NULL;
if (SDL_Init(SDL_INIT_VIDEO)
|| !(sdl.screenSurface = SDL_CreateRGBSurface(0, 800, 600, 32, RMASK, GMASK, BMASK, AMASK))
|| SDL_CreateWindowAndRenderer(800, 600, 0, &sdl.window, &sdl.renderer)
|| fillSurface(sdl.screenSurface, 255, 0, 0, 255)
|| !(sdl.screenTexture = SDL_CreateTextureFromSurface(sdl.renderer, sdl.screenSurface))
|| SDL_RenderCopy(sdl.renderer, sdl.screenTexture, NULL, NULL))
return (exitFailure(&sdl));
SDL_RenderPresent(sdl.renderer);
SDL_Delay(1000);
return (0);
}
Header:
#ifndef HEADER_H
# define HEADER_H
# include <math.h>
# include <unistd.h>
# include <stdlib.h>
# include <SDL.h>
# include <SDL_image.h>
# if SDL_BYTEORDER == SDL_BIG_ENDIAN
# define RMASK 0xff000000
# define GMASK 0x00ff0000
# define BMASK 0x0000ff00
# define AMASK 0x000000ff
# else
# define RMASK 0x000000ff
# define GMASK 0x0000ff00
# define BMASK 0x00ff0000
# define AMASK 0xff000000
# endif
typedef struct s_sdlVar
{
SDL_Surface *screenSurface;
SDL_Texture *screenTexture;
SDL_Renderer *renderer;
SDL_Window *window;
} t_sdlVar;
#endif
User contributions licensed under CC BY-SA 3.0