Video Events OpenGL Audio CD-ROM Threads Time

OpenGL Context Manager Examples


Introduction Function List Function Reference Examples


Initializing an OpenGL video mode

	int video_flags;
	int w, h, bpp;

        /* Initialize SDL with SDL_Init() */

	w = 640;
	h = 480;
	bpp = 16;

	video_flags = SDL_OPENGL;
/*	video_flags = SDL_OPENGL | SDL_FULLSCREEN; */

	SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );
	SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );
	SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );
	SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
	SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
	if ( SDL_SetVideoMode( w, h, bpp, video_flags ) == NULL ) 
	{
		fprintf(stderr, "Couldn't set GL mode: %s\n",
		SDL_GetError());
		SDL_Quit();
		exit(1);
	}

        /* Use GL functions normally, followed by SDL_GL_SwapBuffers() ... */

        /* Clean up SDL with SDL_Quit() */

Taking a screenshot and saving it

Since OpenGL uses "mathematically correct" screen coordinates (+y is top of the graph, -y is bottom), and SDL uses "memory-correct" screen coordinates (+y is at the bottom of the frame buffer, hence the bottom of the screen), we need to convert from one format to the other. One way of doing so is presented here.

	SDL_Surface *image;
	SDL_Surface *temp;
	int idx;
	image = SDL_CreateRGBSurface(SDL_SWSURFACE, screenWidth, screenHeight,
                                     24, 0x0000FF, 0x00FF00, 0xFF0000);
	temp = SDL_CreateRGBSurface(SDL_SWSURFACE, screenWidth, screenHeight,
				     24, 0x0000FF, 0x00FF00, 0xFF0000);

	glReadPixels(0, 0, screenWidth, screenHeight, GL_RGB,
	             GL_UNSIGNED_BYTE, image->pixels);
	for (idx = 0; idx < screenHeight; idx++)
	{
		memcpy(temp->pixels + 3 * screenWidth * idx,
			(char *)foo->pixels + 3
			* screenWidth*(screenHeight - idx),
			3*screenWidth);
	}
	memcpy(foo->pixels,temp->pixels,screenWidth * screenHeight * 3);
	SDL_SaveBMP(image, "screenshot.bmp");
	SDL_FreeSurface(image);

Using a surface as a texture

This only covers RGB and RGBA textures, but why would you want to use anything else? :-)

	GLuint textureHandle;
	SDL_Surface *image;
	image = SDL_LoadBMP("test.bmp");

	glPixelStorei(GL_UNPACK_ALIGNMENT,1);
	glBindTexture(GL_TEXTURE_2D,textureHandle);

/* change these settings to your choice */

	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,
		GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,
		GL_NEAREST);

	if (image->format->BytesPerPixel == 3) 
	{
		glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,
		image->w,
		image->h,
		0, GL_RGB, GL_UNSIGNED_BYTE,
		image->pixels);
	}
	else
	{
		glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,
		image->w,
		image->h,
		0, GL_RGBA, GL_UNSIGNED_BYTE,
		image->pixels);
	}
	
	...