例2-4 getpixel()
/*
* return the pixel value at (x, y)
* note: the surface must be locked before calling this!
*/
uint32 getpixel(sdl_surface *surface, int x, int y)
{
int bpp = surface->format->bytesperpixel;
/* here p is the address to the pixel we want to retrieve */
uint8 *p = (uint8 *)surface->pixels + y * surface->pitch + x * bpp;
switch(bpp) {
case 1:
return *p;
case 2:
return *(uint16 *)p;
case 3:
if(sdl_byteorder == sdl_big_endian)
return p[0] << 16 | p[1] << 8 | p[2];
else
return p[0] | p[1] << 8 | p[2] << 16;
case 4:
return *(uint32 *)p;
default:
return 0; /* shouldn't happen, but avoids warnings */
}
}
例2-5 putpixel()
/*
* set the pixel at (x, y) to the given value
* note: the surface must be locked before calling this!
*/
void putpixel(sdl_surface *surface, int x, int y, uint32 pixel)
{
int bpp = surface->format->bytesperpixel;
/* here p is the address to the pixel we want to set */
uint8 *p = (uint8 *)surface->pixels + y * surface->pitch + x * bpp;
switch(bpp) {
case 1:
*p = pixel;
break;
case 2:
*(uint16 *)p = pixel;
break;
case 3:
if(sdl_byteorder == sdl_big_endian) {
p[0] = (pixel >> 16) & 0xff;
p[1] = (pixel >> 8) & 0xff;
p[2] = pixel & 0xff;
} else {
p[0] = pixel & 0xff;
p[1] = (pixel >> 8) & 0xff;
p[2] = (pixel >> 16) & 0xff;
}
break;
case 4:
*(uint32 *)p = pixel;
break;
}
}
例2-6 使用上面的putpixel()在屏幕中心画一个黄点
/* code to set a yellow pixel at the center of the screen */
int x, y;
uint32 yellow;
/* map the color yellow to this display (r=0xff, g=0xff, b=0x00)
note: if the display is palettized, you must set the palette first.
*/
yellow = sdl_maprgb(screen->format, 0xff, 0xff, 0x00);
x = screen->w / 2;
y = screen->h / 2;
/* lock the screen for direct access to the pixels */
if ( sdl_mustlock(screen) ) {
if ( sdl_locksurface(screen) < 0 ) {
fprintf(stderr, "can't lock screen: %s\n", sdl_geterror());
return;
}
}
putpixel(screen, x, y, yellow);
if ( sdl_mustlock(screen) ) {
sdl_unlocksurface(screen);
}
/* update just the part of the display that we've changed */
sdl_updaterect(screen, x, y, 1, 1);
return;
并用sdl和opengl
sdl可以在多种平台(linux/x11, win32, beos, macos classic/toolbox, macos x, freebsd/x11 and solaris/x11)上创建和使用opengl上下文。这允许你在opengl程序中使用sdl的音频、事件、线程和记时器,而这些通常是glut的任务。
和普通的初始化类似,但有三点不同:必须传sdl_opengl参数给sdl_setvideomode;必须使用sdl_gl_setattribute指定一些gl属性(深度缓冲区位宽,帧缓冲位宽等);如果您想使用双缓冲,必须作为gl属性指定