user2466382
user2466382

Reputation: 117

Drawing pixels on the screen with SDL in C

I have a project in which i need to draw pixels on the screen with SDL. A bit of code has been supplied to me:

int render_screen(SDL_Surface* screen)
{
  pixel pixel_white;
  pixel_white.r = (Uint8)0xff;
  pixel_white.g = (Uint8)0xff;
  pixel_white.b = (Uint8)0xff;
  pixel_white.alpha = (Uint8)128;


  SDL_LockSurface(screen);
  /*do your rendering here*/


  /*----------------------*/
  SDL_UnlockSurface(screen);

  /*flip buffers*/
  SDL_Flip(screen);
  clear_screen(screen);

  return 0;
}

Also this function:

void put_pixel(SDL_Surface* screen,int x,int y,pixel* p)
{
  Uint32* p_screen = (Uint32*)screen->pixels;
  p_screen += y*screen->w+x;
  *p_screen = SDL_MapRGBA(screen->format,p->r,p->g,p->b,p->alpha);  
}

There is a number of things in this code that i don't really understand. First, i assume the idea is that i should call the function put_pixel from within the render_screen function, but with what arguments? The put_pixel(SDL_Surface* screen,int x,int y,pixel* p) line seems complicated. If x and y is the function draw arguments, why are they then declared in the function indata? I should have to call put_pixel with the command put_pixel(something,x,y,something2). If i use say x=56 and y= 567, aren't they resetted to 0 when declared in the parentesis? And what should i put in something and something2 to make it work?

Upvotes: 1

Views: 8382

Answers (2)

ace_k
ace_k

Reputation: 11

the formal parameterSDL_Surface *screen is simply a pointer to an SDL_Surface structure, in your case you are likely concerned with the one returned by SDL_SetVideoMode().

pixel *p is a pointer to a struct of type pixel, as below.

typedef struct {
    Uint8 r;
    Uint8 g;
    Uint8 b;
    Uint8 alpha;
} pixel;

instead of using screen->w, it's suggested to calculate an offset in bytes from the base pointer using pitch, which is the length of the surface's scanline in bytes.

instead of

    Uint32* p_screen = (Uint32*)screen->pixels;
    p_screen += y*screen->w+x;
    *p_screen = SDL_MapRGBA(screen->format,p->r,p->g,p->b,p->alpha);

try using:

    /* Get a pointer to the video surface's pixels in memory. */
    Uint32 *pixels = (Uint32*) screen->pixels;

    /* Calculate offset to the location we wish to write to */
    int offset = (screen->pitch / sizeof(Uint32)) * y + x;

    /* Compose RGBA values into correct format for video surface and copy to screen */
    *(pixels + offset) = SDL_MapRGBA(screen->format, p->r, p->g, p->b, p->alpha);     

Upvotes: 0

Louis Hugues
Louis Hugues

Reputation: 596

Try:

SDL_LockSurface(screen);
put_pixel(screen,56,567,&pixel_white);
SDL_UnlockSurface(screen);

And as it has been mentioned , maybe take the time to learn a bit more the C language. particularly, taking into account your question, you may focus on function arguments and pointers.

Upvotes: 3

Related Questions