src/video/SDL_video.c
author Sam Lantinga <slouken@lokigames.com>
Thu, 26 Apr 2001 18:37:24 +0000
changeset 7 2c4a3a759c66
parent 1 cf2af46e9e2a
child 11 7b94b6379341
permissions -rw-r--r--
*** empty log message ***
     1 /*
     2     SDL - Simple DirectMedia Layer
     3     Copyright (C) 1997, 1998, 1999, 2000, 2001  Sam Lantinga
     4 
     5     This library is free software; you can redistribute it and/or
     6     modify it under the terms of the GNU Library General Public
     7     License as published by the Free Software Foundation; either
     8     version 2 of the License, or (at your option) any later version.
     9 
    10     This library is distributed in the hope that it will be useful,
    11     but WITHOUT ANY WARRANTY; without even the implied warranty of
    12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    13     Library General Public License for more details.
    14 
    15     You should have received a copy of the GNU Library General Public
    16     License along with this library; if not, write to the Free
    17     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    18 
    19     Sam Lantinga
    20     slouken@devolution.com
    21 */
    22 
    23 #ifdef SAVE_RCSID
    24 static char rcsid =
    25  "@(#) $Id$";
    26 #endif
    27 
    28 /* The high-level video driver subsystem */
    29 
    30 #include <stdio.h>
    31 #include <stdlib.h>
    32 #include <string.h>
    33 
    34 #include "SDL.h"
    35 #include "SDL_error.h"
    36 #include "SDL_video.h"
    37 #include "SDL_events.h"
    38 #include "SDL_mutex.h"
    39 #include "SDL_sysvideo.h"
    40 #include "SDL_sysevents.h"
    41 #include "SDL_blit.h"
    42 #include "SDL_pixels_c.h"
    43 #include "SDL_events_c.h"
    44 #include "SDL_cursor_c.h"
    45 
    46 /* Available video drivers */
    47 static VideoBootStrap *bootstrap[] = {
    48 #ifdef ENABLE_X11
    49 	&X11_bootstrap,
    50 #endif
    51 #ifdef ENABLE_DGA
    52 	&DGA_bootstrap,
    53 #endif
    54 #ifdef ENABLE_FBCON
    55 	&FBCON_bootstrap,
    56 #endif
    57 #ifdef ENABLE_PS2GS
    58 	&PS2GS_bootstrap,
    59 #endif
    60 #ifdef ENABLE_GGI
    61 	&GGI_bootstrap,
    62 #endif
    63 #ifdef ENABLE_SVGALIB
    64 	&SVGALIB_bootstrap,
    65 #endif
    66 #ifdef ENABLE_AALIB
    67     &AALIB_bootstrap,
    68 #endif
    69 #ifdef ENABLE_DIRECTX
    70 	&DIRECTX_bootstrap,
    71 #endif
    72 #ifdef ENABLE_WINDIB
    73 	&WINDIB_bootstrap,
    74 #endif
    75 #ifdef ENABLE_BWINDOW
    76 	&BWINDOW_bootstrap,
    77 #endif
    78 #ifdef ENABLE_TOOLBOX
    79 	&TOOLBOX_bootstrap,
    80 #endif
    81 #ifdef ENABLE_DRAWSPROCKET
    82 	&DSp_bootstrap,
    83 #endif
    84 #ifdef ENABLE_CYBERGRAPHICS
    85 	&CGX_bootstrap,
    86 #endif
    87 #ifdef ENABLE_DUMMYVIDEO
    88 	&DUMMY_bootstrap,
    89 #endif
    90 	NULL
    91 };
    92 SDL_VideoDevice *current_video = NULL;
    93 
    94 /* Places to store title and icon text for the app */
    95 static char *wm_title = NULL;
    96 static char *wm_icon  = NULL;
    97 
    98 /* Various local functions */
    99 int SDL_VideoInit(const char *driver_name, Uint32 flags);
   100 void SDL_VideoQuit(void);
   101 void SDL_GL_UpdateRectsLock(SDL_VideoDevice* this, int numrects, SDL_Rect* rects);
   102 
   103 static SDL_GrabMode SDL_WM_GrabInputOff(void);
   104 #ifdef HAVE_OPENGL
   105 static int lock_count = 0;
   106 #endif
   107 
   108 
   109 /*
   110  * Initialize the video and event subsystems -- determine native pixel format
   111  */
   112 int SDL_VideoInit (const char *driver_name, Uint32 flags)
   113 {
   114 	SDL_VideoDevice *video;
   115 	int index;
   116 	int i;
   117 	SDL_PixelFormat vformat;
   118 	Uint32 video_flags;
   119 
   120 	/* Toggle the event thread flags, based on OS requirements */
   121 #if defined(MUST_THREAD_EVENTS)
   122 	flags |= SDL_INIT_EVENTTHREAD;
   123 #elif defined(CANT_THREAD_EVENTS)
   124 	if ( (flags & SDL_INIT_EVENTTHREAD) == SDL_INIT_EVENTTHREAD ) {
   125 		SDL_SetError("OS doesn't support threaded events");
   126 		return(-1);
   127 	}
   128 #endif
   129 
   130 	/* Check to make sure we don't overwrite 'current_video' */
   131 	if ( current_video != NULL ) {
   132 		SDL_VideoQuit();
   133 	}
   134 
   135 	/* Select the proper video driver */
   136 	index = 0;
   137 	video = NULL;
   138 	if ( driver_name != NULL ) {
   139 #if 0	/* This will be replaced with a better driver selection API */
   140 		if ( strrchr(driver_name, ':') != NULL ) {
   141 			index = atoi(strrchr(driver_name, ':')+1);
   142 		}
   143 #endif
   144 		for ( i=0; bootstrap[i]; ++i ) {
   145 			if ( strncmp(bootstrap[i]->name, driver_name,
   146 			             strlen(bootstrap[i]->name)) == 0 ) {
   147 				if ( bootstrap[i]->available() ) {
   148 					video = bootstrap[i]->create(index);
   149 					break;
   150 				}
   151 			}
   152 		}
   153 	} else {
   154 		for ( i=0; bootstrap[i]; ++i ) {
   155 			if ( bootstrap[i]->available() ) {
   156 				video = bootstrap[i]->create(index);
   157 				if ( video != NULL ) {
   158 					break;
   159 				}
   160 			}
   161 		}
   162 	}
   163 	if ( video == NULL ) {
   164 		SDL_SetError("No available video device");
   165 		return(-1);
   166 	}
   167 	current_video = video;
   168 	current_video->name = bootstrap[i]->name;
   169 
   170 	/* Do some basic variable initialization */
   171 	video->screen = NULL;
   172 	video->shadow = NULL;
   173 	video->visible = NULL;
   174 	video->physpal = NULL;
   175 	video->gammacols = NULL;
   176 	video->gamma = NULL;
   177 	video->wm_title = NULL;
   178 	video->wm_icon  = NULL;
   179 	video->offset_x = 0;
   180 	video->offset_y = 0;
   181 	memset(&video->info, 0, (sizeof video->info));
   182 
   183 	/* Set some very sane GL defaults */
   184 	video->gl_config.driver_loaded = 0;
   185 	video->gl_config.dll_handle = NULL;
   186 	video->gl_config.red_size = 5;
   187 #if 1 /* This seems to work on more video cards, as a default */
   188 	video->gl_config.green_size = 5;
   189 #else
   190 	video->gl_config.green_size = 6;
   191 #endif
   192 	video->gl_config.blue_size = 5;
   193 	video->gl_config.alpha_size = 0;
   194 	video->gl_config.buffer_size = 0;
   195 	video->gl_config.depth_size = 16;
   196 	video->gl_config.stencil_size = 0;
   197 	video->gl_config.double_buffer = 1;
   198 	video->gl_config.accum_red_size = 0;
   199 	video->gl_config.accum_green_size = 0;
   200 	video->gl_config.accum_blue_size = 0;
   201 	video->gl_config.accum_alpha_size = 0;
   202 	
   203 	/* Initialize the video subsystem */
   204 	memset(&vformat, 0, sizeof(vformat));
   205 	if ( video->VideoInit(video, &vformat) < 0 ) {
   206 		SDL_VideoQuit();
   207 		return(-1);
   208 	}
   209 
   210 	/* Create a zero sized video surface of the appropriate format */
   211 	video_flags = SDL_SWSURFACE;
   212 	SDL_VideoSurface = SDL_CreateRGBSurface(video_flags, 0, 0,
   213 				vformat.BitsPerPixel,
   214 				vformat.Rmask, vformat.Gmask, vformat.Bmask, 0);
   215 	if ( SDL_VideoSurface == NULL ) {
   216 		SDL_VideoQuit();
   217 		return(-1);
   218 	}
   219 	SDL_PublicSurface = NULL;	/* Until SDL_SetVideoMode() */
   220 
   221 #if 0 /* Don't change the current palette - may be used by other programs.
   222        * The application can't do anything with the display surface until
   223        * a video mode has been set anyway. :)
   224        */
   225 	/* If we have a palettized surface, create a default palette */
   226 	if ( SDL_VideoSurface->format->palette ) {
   227 	        SDL_PixelFormat *vf = SDL_VideoSurface->format;
   228 		SDL_DitherColors(vf->palette->colors, vf->BitsPerPixel);
   229 		video->SetColors(video,
   230 				 0, vf->palette->ncolors, vf->palette->colors);
   231 	}
   232 #endif
   233 	video->info.vfmt = SDL_VideoSurface->format;
   234 
   235 	/* Start the event loop */
   236 	if ( SDL_StartEventLoop(flags) < 0 ) {
   237 		SDL_VideoQuit();
   238 		return(-1);
   239 	}
   240 	SDL_CursorInit(flags & SDL_INIT_EVENTTHREAD);
   241 
   242 	/* We're ready to go! */
   243 	return(0);
   244 }
   245 
   246 char *SDL_VideoDriverName(char *namebuf, int maxlen)
   247 {
   248 	if ( current_video != NULL ) {
   249 		strncpy(namebuf, current_video->name, maxlen-1);
   250 		namebuf[maxlen-1] = '\0';
   251 		return(namebuf);
   252 	}
   253 	return(NULL);
   254 }
   255 
   256 /*
   257  * Get the current display surface
   258  */
   259 SDL_Surface *SDL_GetVideoSurface(void)
   260 {
   261 	SDL_Surface *visible;
   262 
   263 	visible = NULL;
   264 	if ( current_video ) {
   265 		visible = current_video->visible;
   266 	}
   267 	return(visible);
   268 }
   269 
   270 /*
   271  * Get the current information about the video hardware
   272  */
   273 const SDL_VideoInfo *SDL_GetVideoInfo(void)
   274 {
   275 	const SDL_VideoInfo *info;
   276 
   277 	info = NULL;
   278 	if ( current_video ) {
   279 		info = &current_video->info;
   280 	}
   281 	return(info);
   282 }
   283 
   284 /*
   285  * Return a pointer to an array of available screen dimensions for the
   286  * given format, sorted largest to smallest.  Returns NULL if there are
   287  * no dimensions available for a particular format, or (SDL_Rect **)-1
   288  * if any dimension is okay for the given format.  If 'format' is NULL,
   289  * the mode list will be for the format given by SDL_GetVideoInfo()->vfmt
   290  */
   291 SDL_Rect ** SDL_ListModes (SDL_PixelFormat *format, Uint32 flags)
   292 {
   293 	SDL_VideoDevice *video = current_video;
   294 	SDL_VideoDevice *this  = current_video;
   295 	SDL_Rect **modes;
   296 
   297 	modes = NULL;
   298 	if ( SDL_VideoSurface ) {
   299 		if ( format == NULL ) {
   300 			format = SDL_VideoSurface->format;
   301 		}
   302 		modes = video->ListModes(this, format, flags);
   303 	}
   304 	return(modes);
   305 }
   306 
   307 /*
   308  * Check to see if a particular video mode is supported.
   309  * It returns 0 if the requested mode is not supported under any bit depth,
   310  * or returns the bits-per-pixel of the closest available mode with the
   311  * given width and height.  If this bits-per-pixel is different from the
   312  * one used when setting the video mode, SDL_SetVideoMode() will succeed,
   313  * but will emulate the requested bits-per-pixel with a shadow surface.
   314  */
   315 static Uint8 SDL_closest_depths[4][8] = {
   316 	/* 8 bit closest depth ordering */
   317 	{ 0, 8, 16, 15, 32, 24, 0, 0 },
   318 	/* 15,16 bit closest depth ordering */
   319 	{ 0, 16, 15, 32, 24, 8, 0, 0 },
   320 	/* 24 bit closest depth ordering */
   321 	{ 0, 24, 32, 16, 15, 8, 0, 0 },
   322 	/* 32 bit closest depth ordering */
   323 	{ 0, 32, 16, 15, 24, 8, 0, 0 }
   324 };
   325 
   326 int SDL_VideoModeOK (int width, int height, int bpp, Uint32 flags) 
   327 {
   328 	int table, b, i;
   329 	int supported;
   330 	SDL_PixelFormat format;
   331 	SDL_Rect **sizes;
   332 
   333 	/* Currently 1 and 4 bpp are not supported */
   334 	if ( bpp < 8 || bpp > 32 ) {
   335 		return(0);
   336 	}
   337 	if ( (width == 0) || (height == 0) ) {
   338 		return(0);
   339 	}
   340 
   341 	/* Search through the list valid of modes */
   342 	memset(&format, 0, sizeof(format));
   343 	supported = 0;
   344 	table = ((bpp+7)/8)-1;
   345 	SDL_closest_depths[table][0] = bpp;
   346 	SDL_closest_depths[table][7] = 0;
   347 	for ( b = 0; !supported && SDL_closest_depths[table][b]; ++b ) {
   348 		format.BitsPerPixel = SDL_closest_depths[table][b];
   349 		sizes = SDL_ListModes(&format, flags);
   350 		if ( sizes == (SDL_Rect **)0 ) {
   351 			/* No sizes supported at this bit-depth */
   352 			continue;
   353 		} else 
   354 #ifdef macintosh /* MPW optimization bug? */
   355 		if ( (sizes == (SDL_Rect **)0xFFFFFFFF) ||
   356 #else
   357 		if ( (sizes == (SDL_Rect **)-1) ||
   358 #endif
   359 		     current_video->handles_any_size ) {
   360 			/* Any size supported at this bit-depth */
   361 			supported = 1;
   362 			continue;
   363 		} else
   364 		for ( i=0; sizes[i]; ++i ) {
   365 			if ((sizes[i]->w == width) && (sizes[i]->h == height)) {
   366 				supported = 1;
   367 				break;
   368 			}
   369 		}
   370 	}
   371 	if ( supported ) {
   372 		--b;
   373 		return(SDL_closest_depths[table][b]);
   374 	} else {
   375 		return(0);
   376 	}
   377 }
   378 
   379 /*
   380  * Get the closest non-emulated video mode to the one requested
   381  */
   382 static int SDL_GetVideoMode (int *w, int *h, int *BitsPerPixel, Uint32 flags)
   383 {
   384 	int table, b, i;
   385 	int supported;
   386 	int native_bpp;
   387 	SDL_PixelFormat format;
   388 	SDL_Rect **sizes;
   389 
   390 	/* Try the original video mode, get the closest depth */
   391 	native_bpp = SDL_VideoModeOK(*w, *h, *BitsPerPixel, flags);
   392 	if ( native_bpp == *BitsPerPixel ) {
   393 		return(1);
   394 	}
   395 	if ( native_bpp > 0 ) {
   396 		*BitsPerPixel = native_bpp;
   397 		return(1);
   398 	}
   399 
   400 	/* No exact size match at any depth, look for closest match */
   401 	memset(&format, 0, sizeof(format));
   402 	supported = 0;
   403 	table = ((*BitsPerPixel+7)/8)-1;
   404 	SDL_closest_depths[table][0] = *BitsPerPixel;
   405 	SDL_closest_depths[table][7] = SDL_VideoSurface->format->BitsPerPixel;
   406 	for ( b = 0; !supported && SDL_closest_depths[table][b]; ++b ) {
   407 		format.BitsPerPixel = SDL_closest_depths[table][b];
   408 		sizes = SDL_ListModes(&format, flags);
   409 		if ( sizes == (SDL_Rect **)0 ) {
   410 			/* No sizes supported at this bit-depth */
   411 			continue;
   412 		}
   413 		for ( i=0; sizes[i]; ++i ) {
   414 			if ((sizes[i]->w < *w) || (sizes[i]->h < *h)) {
   415 				if ( i > 0 ) {
   416 					--i;
   417 					*w = sizes[i]->w;
   418 					*h = sizes[i]->h;
   419 					*BitsPerPixel = SDL_closest_depths[table][b];
   420 					supported = 1;
   421 				} else {
   422 					/* Largest mode too small... */;
   423 				}
   424 				break;
   425 			}
   426 		}
   427 		if ( (i > 0) && ! sizes[i] ) {
   428 			/* The smallest mode was larger than requested, OK */
   429 			--i;
   430 			*w = sizes[i]->w;
   431 			*h = sizes[i]->h;
   432 			*BitsPerPixel = SDL_closest_depths[table][b];
   433 			supported = 1;
   434 		}
   435 	}
   436 	if ( ! supported ) {
   437 		SDL_SetError("No video mode large enough for %dx%d", *w, *h);
   438 	}
   439 	return(supported);
   440 }
   441 
   442 /* This should probably go somewhere else -- like SDL_surface.c */
   443 static void SDL_ClearSurface(SDL_Surface *surface)
   444 {
   445 	Uint32 black;
   446 
   447 	black = SDL_MapRGB(surface->format, 0, 0, 0);
   448 	SDL_FillRect(surface, NULL, black);
   449 	if ((surface->flags&SDL_HWSURFACE) && (surface->flags&SDL_DOUBLEBUF)) {
   450 		SDL_Flip(surface);
   451 		SDL_FillRect(surface, NULL, black);
   452 	}
   453 	SDL_Flip(surface);
   454 }
   455 
   456 /*
   457  * Create a shadow surface suitable for fooling the app. :-)
   458  */
   459 static void SDL_CreateShadowSurface(int depth)
   460 {
   461 	Uint32 Rmask, Gmask, Bmask;
   462 
   463 	/* Allocate the shadow surface */
   464 	if ( depth == (SDL_VideoSurface->format)->BitsPerPixel ) {
   465 		Rmask = (SDL_VideoSurface->format)->Rmask;
   466 		Gmask = (SDL_VideoSurface->format)->Gmask;
   467 		Bmask = (SDL_VideoSurface->format)->Bmask;
   468 	} else {
   469 		Rmask = Gmask = Bmask = 0;
   470 	}
   471 	SDL_ShadowSurface = SDL_CreateRGBSurface(SDL_SWSURFACE,
   472 				SDL_VideoSurface->w, SDL_VideoSurface->h,
   473 						depth, Rmask, Gmask, Bmask, 0);
   474 	if ( SDL_ShadowSurface == NULL ) {
   475 		return;
   476 	}
   477 
   478 	/* 8-bit shadow surfaces report that they have exclusive palette */
   479 	if ( SDL_ShadowSurface->format->palette ) {
   480 		SDL_ShadowSurface->flags |= SDL_HWPALETTE;
   481 		if ( depth == (SDL_VideoSurface->format)->BitsPerPixel ) {
   482 			memcpy(SDL_ShadowSurface->format->palette->colors,
   483 				SDL_VideoSurface->format->palette->colors,
   484 				SDL_VideoSurface->format->palette->ncolors*
   485 							sizeof(SDL_Color));
   486 		} else {
   487 			SDL_DitherColors(
   488 			SDL_ShadowSurface->format->palette->colors, depth);
   489 		}
   490 	}
   491 
   492 	/* If the video surface is resizable, the shadow should say so */
   493 	if ( (SDL_VideoSurface->flags & SDL_RESIZABLE) == SDL_RESIZABLE ) {
   494 		SDL_ShadowSurface->flags |= SDL_RESIZABLE;
   495 	}
   496 	/* If the video surface has no frame, the shadow should say so */
   497 	if ( (SDL_VideoSurface->flags & SDL_NOFRAME) == SDL_NOFRAME ) {
   498 		SDL_ShadowSurface->flags |= SDL_NOFRAME;
   499 	}
   500 	/* If the video surface is fullscreen, the shadow should say so */
   501 	if ( (SDL_VideoSurface->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) {
   502 		SDL_ShadowSurface->flags |= SDL_FULLSCREEN;
   503 	}
   504 	/* If the video surface is flippable, the shadow should say so */
   505 	if ( (SDL_VideoSurface->flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF ) {
   506 		SDL_ShadowSurface->flags |= SDL_DOUBLEBUF;
   507 	}
   508 	return;
   509 }
   510 
   511 /*
   512  * Set the requested video mode, allocating a shadow buffer if necessary.
   513  */
   514 SDL_Surface * SDL_SetVideoMode (int width, int height, int bpp, Uint32 flags)
   515 {
   516 	SDL_VideoDevice *video, *this;
   517 	SDL_Surface *prev_mode, *mode;
   518 	int video_w;
   519 	int video_h;
   520 	int video_bpp;
   521 	int is_opengl;
   522 	SDL_GrabMode saved_grab;
   523 
   524 	/* Start up the video driver, if necessary..
   525 	   WARNING: This is the only function protected this way!
   526 	 */
   527 	if ( ! current_video ) {
   528 		if ( SDL_Init(SDL_INIT_VIDEO|SDL_INIT_NOPARACHUTE) < 0 ) {
   529 			return(NULL);
   530 		}
   531 	}
   532 	this = video = current_video;
   533 
   534 	/* Default to the current video bpp */
   535 	if ( bpp == 0 ) {
   536 		flags |= SDL_ANYFORMAT;
   537 		bpp = SDL_VideoSurface->format->BitsPerPixel;
   538 	}
   539 
   540 	/* Get a good video mode, the closest one possible */
   541 	video_w = width;
   542 	video_h = height;
   543 	video_bpp = bpp;
   544 	if ( ! SDL_GetVideoMode(&video_w, &video_h, &video_bpp, flags) ) {
   545 		return(NULL);
   546 	}
   547 
   548 	/* Check the requested flags */
   549 	/* There's no palette in > 8 bits-per-pixel mode */
   550 	if ( video_bpp > 8 ) {
   551 		flags &= ~SDL_HWPALETTE;
   552 	}
   553 #if 0
   554 	if ( (flags&SDL_FULLSCREEN) != SDL_FULLSCREEN ) {
   555 		/* There's no windowed double-buffering */
   556 		flags &= ~SDL_DOUBLEBUF;
   557 	}
   558 #endif
   559 	if ( (flags&SDL_DOUBLEBUF) == SDL_DOUBLEBUF ) {
   560 		/* Use hardware surfaces when double-buffering */
   561 		flags |= SDL_HWSURFACE;
   562 	}
   563 
   564 	is_opengl = ( ( flags & SDL_OPENGL ) == SDL_OPENGL );
   565 	if ( is_opengl ) {
   566 		/* These flags are for 2D video modes only */
   567 		flags &= ~(SDL_HWSURFACE|SDL_DOUBLEBUF);
   568 	}
   569 
   570 	/* Clean up any previous video mode */
   571 	if ( SDL_PublicSurface != NULL ) {
   572 		SDL_PublicSurface = NULL;
   573 	}
   574 	if ( SDL_ShadowSurface != NULL ) {
   575 		SDL_Surface *ready_to_go;
   576 		ready_to_go = SDL_ShadowSurface;
   577 		SDL_ShadowSurface = NULL;
   578 		SDL_FreeSurface(ready_to_go);
   579 	}
   580 	if ( video->physpal ) {
   581 		free(video->physpal->colors);
   582 		free(video->physpal);
   583 		video->physpal = NULL;
   584 	}
   585 	if( video->gammacols) {
   586 	        free(video->gammacols);
   587 		video->gammacols = NULL;
   588 	}
   589 
   590 	/* Save the previous grab state and turn off grab for mode switch */
   591 	saved_grab = SDL_WM_GrabInputOff();
   592 
   593 	/* Try to set the video mode, along with offset and clipping */
   594 	prev_mode = SDL_VideoSurface;
   595 	SDL_LockCursor();
   596 	SDL_VideoSurface = NULL;	/* In case it's freed by driver */
   597 	mode = video->SetVideoMode(this, prev_mode,video_w,video_h,video_bpp,flags);
   598 	if ( mode ) { /* Prevent resize events from mode change */
   599 	    SDL_PrivateResize(mode->w, mode->h);
   600         }
   601 	/*
   602 	 * rcg11292000
   603 	 * If you try to set an SDL_OPENGL surface, and fail to find a
   604 	 * matching  visual, then the next call to SDL_SetVideoMode()
   605 	 * will segfault, since  we no longer point to a dummy surface,
   606 	 * but rather NULL.
   607 	 * Sam 11/29/00
   608 	 * WARNING, we need to make sure that the previous mode hasn't
   609 	 * already been freed by the video driver.  What do we do in
   610 	 * that case?  Should we call SDL_VideoInit() again?
   611 	 */
   612 	SDL_VideoSurface = (mode != NULL) ? mode : prev_mode;
   613 
   614 	if ( (mode != NULL) && (!is_opengl) ) {
   615 		/* Sanity check */
   616 		if ( (mode->w < width) || (mode->h < height) ) {
   617 			SDL_SetError("Video mode smaller than requested");
   618 			return(NULL);
   619 		}
   620 
   621 		/* If we have a palettized surface, create a default palette */
   622 		if ( mode->format->palette ) {
   623 	        	SDL_PixelFormat *vf = mode->format;
   624 			SDL_DitherColors(vf->palette->colors, vf->BitsPerPixel);
   625 			video->SetColors(this, 0, vf->palette->ncolors,
   626 			                           vf->palette->colors);
   627 		}
   628 
   629 		/* Clear the surface to black */
   630 		video->offset_x = 0;
   631 		video->offset_y = 0;
   632 		mode->offset = 0;
   633 		SDL_SetClipRect(mode, NULL);
   634 		SDL_ClearSurface(mode);
   635 
   636 		/* Now adjust the offsets to match the desired mode */
   637 		video->offset_x = (mode->w-width)/2;
   638 		video->offset_y = (mode->h-height)/2;
   639 		mode->offset = video->offset_y*mode->pitch +
   640 				video->offset_x*mode->format->BytesPerPixel;
   641 #ifdef DEBUG_VIDEO
   642   fprintf(stderr,
   643 	"Requested mode: %dx%dx%d, obtained mode %dx%dx%d (offset %d)\n",
   644 		width, height, bpp,
   645 		mode->w, mode->h, mode->format->BitsPerPixel, mode->offset);
   646 #endif
   647 		mode->w = width;
   648 		mode->h = height;
   649 		SDL_SetClipRect(mode, NULL);
   650 	}
   651 	SDL_ResetCursor();
   652 	SDL_UnlockCursor();
   653 
   654 	/* If we failed setting a video mode, return NULL... (Uh Oh!) */
   655 	if ( mode == NULL ) {
   656 		return(NULL);
   657 	}
   658 
   659 	/* If there is no window manager, set the SDL_NOFRAME flag */
   660 	if ( ! video->info.wm_available ) {
   661 		mode->flags |= SDL_NOFRAME;
   662 	}
   663 
   664 	/* Reset the mouse cursor and grab for new video mode */
   665 	SDL_SetCursor(NULL);
   666 	if ( video->UpdateMouse ) {
   667 		video->UpdateMouse(this);
   668 	}
   669 	SDL_WM_GrabInput(saved_grab);
   670 	SDL_GetRelativeMouseState(NULL, NULL); /* Clear first large delta */
   671 
   672 	/* If we're running OpenGL, make the context current */
   673 	if ( (video->screen->flags & SDL_OPENGL) &&
   674 	      video->GL_MakeCurrent ) {
   675 		if ( video->GL_MakeCurrent(this) < 0 ) {
   676 			return(NULL);
   677 		}
   678 	}
   679 
   680 	/* Set up a fake SDL surface for OpenGL "blitting" */
   681 	if ( (flags & SDL_OPENGLBLIT) == SDL_OPENGLBLIT ) {
   682 		/* Load GL functions for performing the texture updates */
   683 #ifdef HAVE_OPENGL
   684 #define SDL_PROC(ret,func,params) \
   685 do { \
   686 	video->func = SDL_GL_GetProcAddress(#func); \
   687 	if ( ! video->func ) { \
   688 		SDL_SetError("Couldn't load GL function: %s\n", #func); \
   689 		return(NULL); \
   690 	} \
   691 } while ( 0 );
   692 #include "SDL_glfuncs.h"
   693 #undef SDL_PROC	
   694 
   695 		/* Create a software surface for blitting */
   696 #ifdef GL_VERSION_1_2
   697 		/* If the implementation either supports the packed pixels
   698 		   extension, or implements the core OpenGL 1.2 API, it will
   699 		   support the GL_UNSIGNED_SHORT_5_6_5 texture format.
   700 		 */
   701 		if ( (bpp == 16) &&
   702 		     (strstr((const char *)video->glGetString(GL_EXTENSIONS),
   703 		                           "GL_EXT_packed_pixels") ||
   704 		     (strncmp((const char *)video->glGetString(GL_VERSION),
   705 		              "1.2", 3) == 0)) )
   706 		{
   707 			video->is_32bit = 0;
   708 			SDL_VideoSurface = SDL_CreateRGBSurface(
   709 				flags, 
   710 				width, 
   711 				height,  
   712 				16,
   713 				31 << 11,
   714 				63 << 5,
   715 				31,
   716 				0
   717 				);
   718 		}
   719 		else
   720 #endif /* OpenGL 1.2 */
   721 		{
   722 			video->is_32bit = 1;
   723 			SDL_VideoSurface = SDL_CreateRGBSurface(
   724 				flags, 
   725 				width, 
   726 				height, 
   727 				32, 
   728 #if SDL_BYTEORDER == SDL_LIL_ENDIAN
   729 				0x000000FF,
   730 				0x0000FF00,
   731 				0x00FF0000,
   732 				0xFF000000
   733 #else
   734 				0xFF000000,
   735 				0x00FF0000,
   736 				0x0000FF00,
   737 				0x000000FF
   738 #endif
   739 				);
   740 		}
   741 		if ( ! SDL_VideoSurface ) {
   742 			return(NULL);
   743 		}
   744 		SDL_VideoSurface->flags = mode->flags | SDL_OPENGLBLIT;
   745 
   746 		/* Free the original video mode surface (is this safe?) */
   747 		SDL_FreeSurface(mode);
   748 
   749                 /* Set the surface completely opaque & white by default */
   750 		memset( SDL_VideoSurface->pixels, 255, SDL_VideoSurface->h * SDL_VideoSurface->pitch );
   751 		video->glGenTextures( 1, &video->texture );
   752 		video->glBindTexture( GL_TEXTURE_2D, video->texture );
   753 		video->glTexImage2D(
   754 			GL_TEXTURE_2D,
   755 			0,
   756 			video->is_32bit ? GL_RGBA : GL_RGB,
   757 			256,
   758 			256,
   759 			0,
   760 			video->is_32bit ? GL_RGBA : GL_RGB,
   761 #ifdef GL_VERSION_1_2
   762 			video->is_32bit ? GL_UNSIGNED_BYTE : GL_UNSIGNED_SHORT_5_6_5,
   763 #else
   764 			GL_UNSIGNED_BYTE,
   765 #endif
   766 			NULL);
   767 
   768 		video->UpdateRects = SDL_GL_UpdateRectsLock;
   769 #else
   770 		SDL_SetError("Somebody forgot to #define HAVE_OPENGL");
   771 		return(NULL);
   772 #endif
   773 	}
   774 
   775 	/* Create a shadow surface if necessary */
   776 	/* There are three conditions under which we create a shadow surface:
   777 		1.  We need a particular bits-per-pixel that we didn't get.
   778 		2.  We need a hardware palette and didn't get one.
   779 		3.  We need a software surface and got a hardware surface.
   780 	*/
   781 	if ( !(SDL_VideoSurface->flags & SDL_OPENGL) &&
   782 	     (
   783 	     (  !(flags&SDL_ANYFORMAT) &&
   784 			(SDL_VideoSurface->format->BitsPerPixel != bpp)) ||
   785 	     (   (flags&SDL_HWPALETTE) && 
   786 				!(SDL_VideoSurface->flags&SDL_HWPALETTE)) ||
   787 		/* If the surface is in hardware, video writes are visible
   788 		   as soon as they are performed, so we need to buffer them
   789 		 */
   790 	     (   ((flags&SDL_HWSURFACE) == SDL_SWSURFACE) &&
   791 				(SDL_VideoSurface->flags&SDL_HWSURFACE))
   792 	     ) ) {
   793 		SDL_CreateShadowSurface(bpp);
   794 		if ( SDL_ShadowSurface == NULL ) {
   795 			SDL_SetError("Couldn't create shadow surface");
   796 			return(NULL);
   797 		}
   798 		SDL_PublicSurface = SDL_ShadowSurface;
   799 	} else {
   800 		SDL_PublicSurface = SDL_VideoSurface;
   801 	}
   802 	video->info.vfmt = SDL_VideoSurface->format;
   803 
   804 	/* We're done! */
   805 	return(SDL_PublicSurface);
   806 }
   807 
   808 /* 
   809  * Convert a surface into the video pixel format.
   810  */
   811 SDL_Surface * SDL_DisplayFormat (SDL_Surface *surface)
   812 {
   813 	Uint32 flags;
   814 
   815 	if ( ! SDL_PublicSurface ) {
   816 		SDL_SetError("No video mode has been set");
   817 		return(NULL);
   818 	}
   819 	/* Set the flags appropriate for copying to display surface */
   820 	flags  = (SDL_PublicSurface->flags&SDL_HWSURFACE);
   821 #ifdef AUTORLE_DISPLAYFORMAT
   822 	flags |= (surface->flags & (SDL_SRCCOLORKEY|SDL_SRCALPHA));
   823 	flags |= SDL_RLEACCELOK;
   824 #else
   825 	flags |= surface->flags & (SDL_SRCCOLORKEY|SDL_SRCALPHA|SDL_RLEACCELOK);
   826 #endif
   827 	return(SDL_ConvertSurface(surface, SDL_PublicSurface->format, flags));
   828 }
   829 
   830 /*
   831  * Convert a surface into a format that's suitable for blitting to
   832  * the screen, but including an alpha channel.
   833  */
   834 SDL_Surface *SDL_DisplayFormatAlpha(SDL_Surface *surface)
   835 {
   836 	SDL_PixelFormat *vf;
   837 	SDL_PixelFormat *format;
   838 	SDL_Surface *converted;
   839 	Uint32 flags;
   840 	/* default to ARGB8888 */
   841 	Uint32 amask = 0xff000000;
   842 	Uint32 rmask = 0x00ff0000;
   843 	Uint32 gmask = 0x0000ff00;
   844 	Uint32 bmask = 0x000000ff;
   845 
   846 	if ( ! SDL_PublicSurface ) {
   847 		SDL_SetError("No video mode has been set");
   848 		return(NULL);
   849 	}
   850 	vf = SDL_PublicSurface->format;
   851 
   852 	switch(vf->BytesPerPixel) {
   853 	    case 2:
   854 		/* For XGY5[56]5, use, AXGY8888, where {X, Y} = {R, B}.
   855 		   For anything else (like ARGB4444) it doesn't matter
   856 		   since we have no special code for it anyway */
   857 		if ( (vf->Rmask == 0x1f) &&
   858 		     (vf->Bmask == 0xf800 || vf->Bmask == 0x7c00)) {
   859 			rmask = 0xff;
   860 			bmask = 0xff0000;
   861 		}
   862 		break;
   863 
   864 	    case 3:
   865 	    case 4:
   866 		/* Keep the video format, as long as the high 8 bits are
   867 		   unused or alpha */
   868 		if ( (vf->Rmask == 0xff) && (vf->Bmask == 0xff0000) ) {
   869 			rmask = 0xff;
   870 			bmask = 0xff0000;
   871 		}
   872 		break;
   873 
   874 	    default:
   875 		/* We have no other optimised formats right now. When/if a new
   876 		   optimised alpha format is written, add the converter here */
   877 		break;
   878 	}
   879 	format = SDL_AllocFormat(32, rmask, gmask, bmask, amask);
   880 	flags = SDL_PublicSurface->flags & SDL_HWSURFACE;
   881 	flags |= surface->flags & (SDL_SRCALPHA | SDL_RLEACCELOK);
   882 	converted = SDL_ConvertSurface(surface, format, flags);
   883 	SDL_FreeFormat(format);
   884 	return(converted);
   885 }
   886 
   887 /*
   888  * Update a specific portion of the physical screen
   889  */
   890 void SDL_UpdateRect(SDL_Surface *screen, Sint32 x, Sint32 y, Uint32 w, Uint32 h)
   891 {
   892 	if ( screen ) {
   893 		SDL_Rect rect;
   894 
   895 		/* Perform some checking */
   896 		if ( w == 0 )
   897 			w = screen->w;
   898 		if ( h == 0 )
   899 			h = screen->h;
   900 		if ( (int)(x+w) > screen->w )
   901 			return;
   902 		if ( (int)(y+h) > screen->h )
   903 			return;
   904 
   905 		/* Fill the rectangle */
   906 		rect.x = x;
   907 		rect.y = y;
   908 		rect.w = w;
   909 		rect.h = h;
   910 		SDL_UpdateRects(screen, 1, &rect);
   911 	}
   912 }
   913 void SDL_UpdateRects (SDL_Surface *screen, int numrects, SDL_Rect *rects)
   914 {
   915 	int i;
   916 	SDL_VideoDevice *video = current_video;
   917 	SDL_VideoDevice *this = current_video;
   918 
   919 	if ( screen == SDL_ShadowSurface ) {
   920 		/* Blit the shadow surface using saved mapping */
   921 	        SDL_Palette *pal = screen->format->palette;
   922 		SDL_Color *saved_colors = NULL;
   923 	        if ( pal && !(SDL_VideoSurface->flags & SDL_HWPALETTE) ) {
   924 			/* simulated 8bpp, use correct physical palette */
   925 			saved_colors = pal->colors;
   926 			if ( video->gammacols ) {
   927 				/* gamma-corrected palette */
   928 				pal->colors = video->gammacols;
   929 			} else if ( video->physpal ) {
   930 				/* physical palette different from logical */
   931 				pal->colors = video->physpal->colors;
   932 			}
   933 		}
   934 		if ( SHOULD_DRAWCURSOR(SDL_cursorstate) ) {
   935 			SDL_LockCursor();
   936 			SDL_DrawCursor(SDL_ShadowSurface);
   937 			for ( i=0; i<numrects; ++i ) {
   938 				SDL_LowerBlit(SDL_ShadowSurface, &rects[i], 
   939 						SDL_VideoSurface, &rects[i]);
   940 			}
   941 			SDL_EraseCursor(SDL_ShadowSurface);
   942 			SDL_UnlockCursor();
   943 		} else {
   944 			for ( i=0; i<numrects; ++i ) {
   945 				SDL_LowerBlit(SDL_ShadowSurface, &rects[i], 
   946 						SDL_VideoSurface, &rects[i]);
   947 			}
   948 		}
   949 		if ( saved_colors )
   950 			pal->colors = saved_colors;
   951 
   952 		/* Fall through to video surface update */
   953 		screen = SDL_VideoSurface;
   954 	}
   955 	if ( screen == SDL_VideoSurface ) {
   956 		/* Update the video surface */
   957 		if ( screen->offset ) {
   958 			for ( i=0; i<numrects; ++i ) {
   959 				rects[i].x += video->offset_x;
   960 				rects[i].y += video->offset_y;
   961 			}
   962 			video->UpdateRects(this, numrects, rects);
   963 			for ( i=0; i<numrects; ++i ) {
   964 				rects[i].x -= video->offset_x;
   965 				rects[i].y -= video->offset_y;
   966 			}
   967 		} else {
   968 			video->UpdateRects(this, numrects, rects);
   969 		}
   970 	}
   971 }
   972 
   973 /*
   974  * Performs hardware double buffering, if possible, or a full update if not.
   975  */
   976 int SDL_Flip(SDL_Surface *screen)
   977 {
   978 	SDL_VideoDevice *video = current_video;
   979 	/* Copy the shadow surface to the video surface */
   980 	if ( screen == SDL_ShadowSurface ) {
   981 		SDL_Rect rect;
   982 	        SDL_Palette *pal = screen->format->palette;
   983 		SDL_Color *saved_colors = NULL;
   984 	        if ( pal && !(SDL_VideoSurface->flags & SDL_HWPALETTE) ) {
   985 			/* simulated 8bpp, use correct physical palette */
   986 			saved_colors = pal->colors;
   987 			if ( video->gammacols ) {
   988 				/* gamma-corrected palette */
   989 				pal->colors = video->gammacols;
   990 			} else if ( video->physpal ) {
   991 				/* physical palette different from logical */
   992 				pal->colors = video->physpal->colors;
   993 			}
   994 		}
   995 
   996 		rect.x = 0;
   997 		rect.y = 0;
   998 		rect.w = screen->w;
   999 		rect.h = screen->h;
  1000 		SDL_LowerBlit(SDL_ShadowSurface,&rect, SDL_VideoSurface,&rect);
  1001 
  1002 		if ( saved_colors )
  1003 			pal->colors = saved_colors;
  1004 		screen = SDL_VideoSurface;
  1005 	}
  1006 	if ( (screen->flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF ) {
  1007 		SDL_VideoDevice *this  = current_video;
  1008 		return(video->FlipHWSurface(this, SDL_VideoSurface));
  1009 	} else {
  1010 		SDL_UpdateRect(screen, 0, 0, 0, 0);
  1011 	}
  1012 	return(0);
  1013 }
  1014 
  1015 static void SetPalette_logical(SDL_Surface *screen, SDL_Color *colors,
  1016 			       int firstcolor, int ncolors)
  1017 {
  1018         SDL_Palette *pal = screen->format->palette;
  1019 	SDL_Palette *vidpal;
  1020 
  1021 	if ( colors != (pal->colors + firstcolor) ) {
  1022 	        memcpy(pal->colors + firstcolor, colors,
  1023 		       ncolors * sizeof(*colors));
  1024 	}
  1025 
  1026 	vidpal = SDL_VideoSurface->format->palette;
  1027 	if ( (screen == SDL_ShadowSurface) && vidpal ) {
  1028 	        /*
  1029 		 * This is a shadow surface, and the physical
  1030 		 * framebuffer is also indexed. Propagate the
  1031 		 * changes to its logical palette so that
  1032 		 * updates are always identity blits
  1033 		 */
  1034 		memcpy(vidpal->colors + firstcolor, colors,
  1035 		       ncolors * sizeof(*colors));
  1036 	}
  1037 	SDL_FormatChanged(screen);
  1038 }
  1039 
  1040 static int SetPalette_physical(SDL_Surface *screen,
  1041                                SDL_Color *colors, int firstcolor, int ncolors)
  1042 {
  1043 	SDL_VideoDevice *video = current_video;
  1044 	int gotall = 1;
  1045 
  1046 	if ( video->physpal ) {
  1047 		/* We need to copy the new colors, since we haven't
  1048 		 * already done the copy in the logical set above.
  1049 		 */
  1050 		memcpy(video->physpal->colors + firstcolor,
  1051 		       colors, ncolors * sizeof(*colors));
  1052 	}
  1053 	if ( screen == SDL_ShadowSurface ) {
  1054 		if ( SDL_VideoSurface->flags & SDL_HWPALETTE ) {
  1055 			/*
  1056 			 * The real screen is also indexed - set its physical
  1057 			 * palette. The physical palette does not include the
  1058 			 * gamma modification, we apply it directly instead,
  1059 			 * but this only happens if we have hardware palette.
  1060 			 */
  1061 			screen = SDL_VideoSurface;
  1062 		} else {
  1063 			/*
  1064 			 * The video surface is not indexed - invalidate any
  1065 			 * active shadow-to-video blit mappings.
  1066 			 */
  1067 			if ( screen->map->dst == SDL_VideoSurface ) {
  1068 				SDL_InvalidateMap(screen->map);
  1069 			}
  1070 			if ( video->gamma ) {
  1071 				if( ! video->gammacols ) {
  1072 					SDL_Palette *pp = video->physpal;
  1073 					if(!pp)
  1074 						pp = screen->format->palette;
  1075 					video->gammacols = malloc(pp->ncolors
  1076 							  * sizeof(SDL_Color));
  1077 					SDL_ApplyGamma(video->gamma,
  1078 						       pp->colors,
  1079 						       video->gammacols,
  1080 						       pp->ncolors);
  1081 				} else {
  1082 					SDL_ApplyGamma(video->gamma, colors,
  1083 						       video->gammacols
  1084 						       + firstcolor,
  1085 						       ncolors);
  1086 				}
  1087 			}
  1088 			SDL_UpdateRect(screen, 0, 0, 0, 0);
  1089 		}
  1090 	}
  1091 
  1092 	if ( screen == SDL_VideoSurface ) {
  1093 		SDL_Color gcolors[256];
  1094 
  1095 	        if ( video->gamma ) {
  1096 		        SDL_ApplyGamma(video->gamma, colors, gcolors, ncolors);
  1097 			colors = gcolors;
  1098 		}
  1099 		gotall = video->SetColors(video, firstcolor, ncolors, colors);
  1100 		if ( ! gotall ) {
  1101 			/* The video flags shouldn't have SDL_HWPALETTE, and
  1102 			   the video driver is responsible for copying back the
  1103 			   correct colors into the video surface palette.
  1104 			*/
  1105 			;
  1106 		}
  1107 		SDL_CursorPaletteChanged();
  1108 	}
  1109 	return gotall;
  1110 }
  1111 
  1112 /*
  1113  * Set the physical and/or logical colormap of a surface:
  1114  * Only the screen has a physical colormap. It determines what is actually
  1115  * sent to the display.
  1116  * The logical colormap is used to map blits to/from the surface.
  1117  * 'which' is one or both of SDL_LOGPAL, SDL_PHYSPAL
  1118  *
  1119  * Return nonzero if all colours were set as requested, or 0 otherwise.
  1120  */
  1121 int SDL_SetPalette(SDL_Surface *screen, int which,
  1122 		   SDL_Color *colors, int firstcolor, int ncolors)
  1123 {
  1124         SDL_Palette *pal;
  1125 	int gotall;
  1126 	int palsize;
  1127 
  1128 	if ( screen != SDL_PublicSurface ) {
  1129 	        /* only screens have physical palettes */
  1130 	        which &= ~SDL_PHYSPAL;
  1131 	} else if( (screen->flags & SDL_HWPALETTE) != SDL_HWPALETTE ) {
  1132 	        /* hardware palettes required for split colormaps */
  1133 	        which |= SDL_PHYSPAL | SDL_LOGPAL;
  1134 	}
  1135 
  1136 	/* Verify the parameters */
  1137 	pal = screen->format->palette;
  1138 	if( !pal ) {
  1139 	        return 0;	/* not a palettized surface */
  1140 	}
  1141 	gotall = 1;
  1142 	palsize = 1 << screen->format->BitsPerPixel;
  1143 	if ( ncolors > (palsize - firstcolor) ) {
  1144 	        ncolors = (palsize - firstcolor);
  1145 		gotall = 0;
  1146 	}
  1147 
  1148 	if ( which & SDL_LOGPAL ) {
  1149 		/*
  1150 		 * Logical palette change: The actual screen isn't affected,
  1151 		 * but the internal colormap is altered so that the
  1152 		 * interpretation of the pixel values (for blits etc) is
  1153 		 * changed.
  1154 		 */
  1155 	        SetPalette_logical(screen, colors, firstcolor, ncolors);
  1156 	}
  1157 	if ( which & SDL_PHYSPAL ) {
  1158 		SDL_VideoDevice *video = current_video;
  1159 	        /*
  1160 		 * Physical palette change: This doesn't affect the
  1161 		 * program's idea of what the screen looks like, but changes
  1162 		 * its actual appearance.
  1163 		 */
  1164 	        if(!video)
  1165 		        return gotall;	/* video not yet initialized */
  1166 		if(!video->physpal && !(which & SDL_LOGPAL) ) {
  1167 			/* Lazy physical palette allocation */
  1168 		        int size;
  1169 			SDL_Palette *pp = malloc(sizeof(*pp));
  1170 			current_video->physpal = pp;
  1171 			pp->ncolors = pal->ncolors;
  1172 			size = pp->ncolors * sizeof(SDL_Color);
  1173 			pp->colors = malloc(size);
  1174 			memcpy(pp->colors, pal->colors, size);
  1175 		}
  1176 		if ( ! SetPalette_physical(screen,
  1177 		                           colors, firstcolor, ncolors) ) {
  1178 			gotall = 0;
  1179 		}
  1180 	}
  1181 	return gotall;
  1182 }
  1183 
  1184 int SDL_SetColors(SDL_Surface *screen, SDL_Color *colors, int firstcolor,
  1185 		  int ncolors)
  1186 {
  1187         return SDL_SetPalette(screen, SDL_LOGPAL | SDL_PHYSPAL,
  1188 			      colors, firstcolor, ncolors);
  1189 }
  1190 
  1191 /*
  1192  * Clean up the video subsystem
  1193  */
  1194 void SDL_VideoQuit (void)
  1195 {
  1196 	SDL_Surface *ready_to_go;
  1197 
  1198 	if ( current_video ) {
  1199 		SDL_VideoDevice *video = current_video;
  1200 		SDL_VideoDevice *this  = current_video;
  1201 
  1202 		/* Halt event processing before doing anything else */
  1203 		SDL_StopEventLoop();
  1204 
  1205 		/* Clean up allocated window manager items */
  1206 		if ( SDL_PublicSurface ) {
  1207 			SDL_PublicSurface = NULL;
  1208 		}
  1209 		SDL_CursorQuit();
  1210 
  1211 		/* Just in case... */
  1212 		SDL_WM_GrabInputOff();
  1213 
  1214 		/* Clean up the system video */
  1215 		video->VideoQuit(this);
  1216 
  1217 		/* Free any lingering surfaces */
  1218 		ready_to_go = SDL_ShadowSurface;
  1219 		SDL_ShadowSurface = NULL;
  1220 		SDL_FreeSurface(ready_to_go);
  1221 		if ( SDL_VideoSurface != NULL ) {
  1222 			ready_to_go = SDL_VideoSurface;
  1223 			SDL_VideoSurface = NULL;
  1224 			SDL_FreeSurface(ready_to_go);
  1225 		}
  1226 		SDL_PublicSurface = NULL;
  1227 
  1228 		/* Clean up miscellaneous memory */
  1229 		if ( video->physpal ) {
  1230 			free(video->physpal->colors);
  1231 			free(video->physpal);
  1232 			video->physpal = NULL;
  1233 		}
  1234 		if ( video->gammacols ) {
  1235 			free(video->gammacols);
  1236 			video->gammacols = NULL;
  1237 		}
  1238 		if ( video->gamma ) {
  1239 			free(video->gamma);
  1240 			video->gamma = NULL;
  1241 		}
  1242 		if ( wm_title != NULL ) {
  1243 			free(wm_title);
  1244 			wm_title = NULL;
  1245 		}
  1246 		if ( wm_icon != NULL ) {
  1247 			free(wm_icon);
  1248 			wm_icon = NULL;
  1249 		}
  1250 
  1251 		/* Finish cleaning up video subsystem */
  1252 		video->free(this);
  1253 		current_video = NULL;
  1254 	}
  1255 	return;
  1256 }
  1257 
  1258 /* Load the GL driver library */
  1259 int SDL_GL_LoadLibrary(const char *path)
  1260 {
  1261 	SDL_VideoDevice *video = current_video;
  1262 	SDL_VideoDevice *this = current_video;
  1263 	int retval;
  1264 
  1265 	retval = -1;
  1266 	if ( video && video->GL_LoadLibrary ) {
  1267 		retval = video->GL_LoadLibrary(this, path);
  1268 	} else {
  1269 		SDL_SetError("No dynamic GL support in video driver");
  1270 	}
  1271 	return(retval);
  1272 }
  1273 
  1274 void *SDL_GL_GetProcAddress(const char* proc)
  1275 {
  1276 	SDL_VideoDevice *video = current_video;
  1277 	SDL_VideoDevice *this = current_video;
  1278 	void *func;
  1279 
  1280 	func = NULL;
  1281 	if ( video->GL_GetProcAddress ) {
  1282 		if ( video->gl_config.driver_loaded ) {
  1283 			func = video->GL_GetProcAddress(this, proc);
  1284 		} else {
  1285 			SDL_SetError("No GL driver has been loaded");
  1286 		}
  1287 	} else {
  1288 		SDL_SetError("No dynamic GL support in video driver");
  1289 	}
  1290 	return func;
  1291 }
  1292 
  1293 /* Set the specified GL attribute for setting up a GL video mode */
  1294 int SDL_GL_SetAttribute( SDL_GLattr attr, int value )
  1295 {
  1296 	int retval;
  1297 	SDL_VideoDevice *video = current_video;
  1298 
  1299 	retval = 0;
  1300 	switch (attr) {
  1301 		case SDL_GL_RED_SIZE:
  1302 			video->gl_config.red_size = value;
  1303 			break;
  1304 		case SDL_GL_GREEN_SIZE:
  1305 			video->gl_config.green_size = value;
  1306 			break;
  1307 		case SDL_GL_BLUE_SIZE:
  1308 			video->gl_config.blue_size = value;
  1309 			break;
  1310 		case SDL_GL_ALPHA_SIZE:
  1311 			video->gl_config.alpha_size = value;
  1312 			break;
  1313 		case SDL_GL_DOUBLEBUFFER:
  1314 			video->gl_config.double_buffer = value;
  1315 			break;
  1316         	case SDL_GL_BUFFER_SIZE:
  1317 	        	video->gl_config.buffer_size = value;
  1318 			break;
  1319 		case SDL_GL_DEPTH_SIZE:
  1320 			video->gl_config.depth_size = value;
  1321 			break;
  1322 		case SDL_GL_STENCIL_SIZE:
  1323 			video->gl_config.stencil_size = value;
  1324 			break;
  1325 	        case SDL_GL_ACCUM_RED_SIZE:
  1326 			video->gl_config.accum_red_size = value;
  1327 			break;
  1328 	        case SDL_GL_ACCUM_GREEN_SIZE:
  1329 			video->gl_config.accum_green_size = value;
  1330 			break;
  1331 	        case SDL_GL_ACCUM_BLUE_SIZE:
  1332 			video->gl_config.accum_blue_size = value;
  1333 			break;
  1334 	        case SDL_GL_ACCUM_ALPHA_SIZE:
  1335 			video->gl_config.accum_alpha_size = value;
  1336 			break;
  1337 		default:
  1338 			SDL_SetError("Unknown OpenGL attribute");
  1339 			retval = -1;
  1340 			break;
  1341 	}
  1342 	return(retval);
  1343 }
  1344 
  1345 /* Retrieve an attribute value from the windowing system. */
  1346 int SDL_GL_GetAttribute(SDL_GLattr attr, int* value)
  1347 {
  1348 	int retval = -1;
  1349 	SDL_VideoDevice* video = current_video;
  1350 	SDL_VideoDevice* this = current_video;
  1351 
  1352 	if ( video->GL_GetAttribute ) {
  1353 		retval = this->GL_GetAttribute(this, attr, value);
  1354 	}
  1355 
  1356 	return retval;
  1357 }
  1358 
  1359 /* Perform a GL buffer swap on the current GL context */
  1360 void SDL_GL_SwapBuffers(void)
  1361 {
  1362 	SDL_VideoDevice *video = current_video;
  1363 	SDL_VideoDevice *this = current_video;
  1364 
  1365 	if ( video->screen->flags & SDL_OPENGL ) {
  1366 		video->GL_SwapBuffers( this );
  1367 	}
  1368 }
  1369 
  1370 /* Update rects with locking */
  1371 void SDL_GL_UpdateRectsLock(SDL_VideoDevice* this, int numrects, SDL_Rect *rects)
  1372 {
  1373 	SDL_GL_Lock();
  1374  	SDL_GL_UpdateRects(numrects, rects);
  1375 	SDL_GL_Unlock();
  1376 }
  1377 
  1378 /* Update rects without state setting and changing (the caller is responsible for it) */
  1379 void SDL_GL_UpdateRects(int numrects, SDL_Rect *rects)
  1380 {
  1381 #ifdef HAVE_OPENGL
  1382 	SDL_VideoDevice *this = current_video;
  1383 	SDL_Rect update, tmp;
  1384 	int x, y, i;
  1385 
  1386 	for ( i = 0; i < numrects; i++ )
  1387 	{
  1388 		tmp.y = rects[i].y;
  1389 		tmp.h = rects[i].h;
  1390 		for ( y = 0; y <= rects[i].h / 256; y++ )
  1391 		{
  1392 			tmp.x = rects[i].x;
  1393 			tmp.w = rects[i].w;
  1394 			for ( x = 0; x <= rects[i].w / 256; x++ )
  1395 			{
  1396 				update.x = tmp.x;
  1397 				update.y = tmp.y;
  1398 				update.w = tmp.w;
  1399 				update.h = tmp.h;
  1400 
  1401 				if ( update.w > 256 )
  1402 					update.w = 256;
  1403 
  1404 				if ( update.h > 256 )
  1405 					update.h = 256;
  1406 			
  1407 				this->glFlush();
  1408 				this->glTexSubImage2D( 
  1409 					GL_TEXTURE_2D, 
  1410 					0, 
  1411 					0, 
  1412 					0, 
  1413 					update.w, 
  1414 					update.h, 
  1415 					this->is_32bit? GL_RGBA : GL_RGB,
  1416 #ifdef GL_VERSION_1_2
  1417 					this->is_32bit ? GL_UNSIGNED_BYTE : GL_UNSIGNED_SHORT_5_6_5,
  1418 #else
  1419 					GL_UNSIGNED_BYTE,
  1420 #endif
  1421 					(Uint8 *)this->screen->pixels + 
  1422 						this->screen->format->BytesPerPixel * update.x + 
  1423 						update.y * this->screen->pitch );
  1424 	
  1425 				this->glFlush();
  1426 				/*
  1427 				* Note the parens around the function name:
  1428 				* This is because some OpenGL implementations define glTexCoord etc 
  1429 				* as macros, and we don't want them expanded here.
  1430 				*/
  1431 				this->glBegin(GL_TRIANGLE_STRIP);
  1432 					(this->glTexCoord2f)( 0.0, 0.0 );	
  1433 					(this->glVertex2i)( update.x, update.y );
  1434 					(this->glTexCoord2f)( (float)(update.w / 256.0), 0.0 );	
  1435 					(this->glVertex2i)( update.x + update.w, update.y );
  1436 					(this->glTexCoord2f)( 0.0, (float)(update.h / 256.0) );
  1437 					(this->glVertex2i)( update.x, update.y + update.h );
  1438 					(this->glTexCoord2f)( (float)(update.w / 256.0), (float)(update.h / 256.0) );	
  1439 					(this->glVertex2i)( update.x + update.w	, update.y + update.h );
  1440 				this->glEnd();	
  1441 			
  1442 				tmp.x += 256;
  1443 				tmp.w -= 256;
  1444 			}
  1445 			tmp.y += 256;
  1446 			tmp.h -= 256;
  1447 		}
  1448 	}
  1449 #endif
  1450 }
  1451 
  1452 /* Lock == save current state */
  1453 void SDL_GL_Lock()
  1454 {
  1455 #ifdef HAVE_OPENGL
  1456 	lock_count--;
  1457 	if (lock_count==-1)
  1458 	{
  1459 		SDL_VideoDevice *this = current_video;
  1460 
  1461 		this->glPushAttrib( GL_ALL_ATTRIB_BITS );	/* TODO: narrow range of what is saved */
  1462 		this->glPushClientAttrib( GL_CLIENT_PIXEL_STORE_BIT );
  1463 
  1464 		this->glEnable(GL_TEXTURE_2D);
  1465 		this->glEnable(GL_BLEND);
  1466 		this->glDisable(GL_FOG);
  1467 		this->glDisable(GL_ALPHA_TEST);
  1468 		this->glDisable(GL_DEPTH_TEST);
  1469 		this->glDisable(GL_SCISSOR_TEST);	
  1470 		this->glDisable(GL_STENCIL_TEST);
  1471 		this->glDisable(GL_CULL_FACE);
  1472 
  1473 		this->glBindTexture( GL_TEXTURE_2D, this->texture );
  1474 		this->glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
  1475 		this->glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
  1476 		this->glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
  1477 		this->glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
  1478 		this->glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
  1479 
  1480 		this->glPixelStorei( GL_UNPACK_ROW_LENGTH, this->screen->pitch / this->screen->format->BytesPerPixel );
  1481 		this->glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  1482 		(this->glColor4f)(1.0, 1.0, 1.0, 1.0);		/* Solaris workaround */
  1483 
  1484 		this->glViewport(0, 0, this->screen->w, this->screen->h);
  1485 		this->glMatrixMode(GL_PROJECTION);
  1486 		this->glPushMatrix();
  1487 		this->glLoadIdentity();
  1488 
  1489 		this->glOrtho(0.0, (GLdouble) this->screen->w, (GLdouble) this->screen->h, 0.0, 0.0, 1.0);
  1490 
  1491 		this->glMatrixMode(GL_MODELVIEW);
  1492 		this->glPushMatrix();
  1493 		this->glLoadIdentity();
  1494 	}
  1495 #endif
  1496 }
  1497 
  1498 /* Unlock == restore saved state */
  1499 void SDL_GL_Unlock()
  1500 {
  1501 #ifdef HAVE_OPENGL
  1502 	lock_count++;
  1503 	if (lock_count==0)
  1504 	{
  1505 		SDL_VideoDevice *this = current_video;
  1506 
  1507 		this->glPopMatrix();
  1508 		this->glMatrixMode(GL_PROJECTION);
  1509 		this->glPopMatrix();
  1510 
  1511 		this->glPopClientAttrib();
  1512 		this->glPopAttrib();
  1513 	}
  1514 #endif
  1515 }
  1516 
  1517 /*
  1518  * Sets/Gets the title and icon text of the display window, if any.
  1519  */
  1520 void SDL_WM_SetCaption (const char *title, const char *icon)
  1521 {
  1522 	SDL_VideoDevice *video = current_video;
  1523 	SDL_VideoDevice *this  = current_video;
  1524 
  1525 	if ( title ) {
  1526 		if ( wm_title ) {
  1527 			free(wm_title);
  1528 		}
  1529 		wm_title = (char *)malloc(strlen(title)+1);
  1530 		if ( wm_title != NULL ) {
  1531 			strcpy(wm_title, title);
  1532 		}
  1533 	}
  1534 	if ( icon ) {
  1535 		if ( wm_icon ) {
  1536 			free(wm_icon);
  1537 		}
  1538 		wm_icon = (char *)malloc(strlen(icon)+1);
  1539 		if ( wm_icon != NULL ) {
  1540 			strcpy(wm_icon, icon);
  1541 		}
  1542 	}
  1543 	if ( (title || icon) && video && (video->SetCaption != NULL) ) {
  1544 		video->SetCaption(this, wm_title, wm_icon);
  1545 	}
  1546 }
  1547 void SDL_WM_GetCaption (char **title, char **icon)
  1548 {
  1549 	if ( title ) {
  1550 		*title = wm_title;
  1551 	}
  1552 	if ( icon ) {
  1553 		*icon = wm_icon;
  1554 	}
  1555 }
  1556 
  1557 /* Utility function used by SDL_WM_SetIcon() */
  1558 static void CreateMaskFromColorKey(SDL_Surface *icon, Uint8 *mask)
  1559 {
  1560 	int x, y;
  1561 	Uint32 colorkey;
  1562 #define SET_MASKBIT(icon, x, y, mask) \
  1563 	mask[(y*((icon->w+7)/8))+(x/8)] &= ~(0x01<<(7-(x%8)))
  1564 
  1565 	colorkey = icon->format->colorkey;
  1566 	switch (icon->format->BytesPerPixel) {
  1567 		case 1: { Uint8 *pixels;
  1568 			for ( y=0; y<icon->h; ++y ) {
  1569 				pixels = (Uint8 *)icon->pixels + y*icon->pitch;
  1570 				for ( x=0; x<icon->w; ++x ) {
  1571 					if ( *pixels++ == colorkey ) {
  1572 						SET_MASKBIT(icon, x, y, mask);
  1573 					}
  1574 				}
  1575 			}
  1576 		}
  1577 		break;
  1578 
  1579 		case 2: { Uint16 *pixels;
  1580 			for ( y=0; y<icon->h; ++y ) {
  1581 				pixels = (Uint16 *)icon->pixels +
  1582 				                   y*icon->pitch/2;
  1583 				for ( x=0; x<icon->w; ++x ) {
  1584 					if ( *pixels++ == colorkey ) {
  1585 						SET_MASKBIT(icon, x, y, mask);
  1586 					}
  1587 				}
  1588 			}
  1589 		}
  1590 		break;
  1591 
  1592 		case 4: { Uint32 *pixels;
  1593 			for ( y=0; y<icon->h; ++y ) {
  1594 				pixels = (Uint32 *)icon->pixels +
  1595 				                   y*icon->pitch/4;
  1596 				for ( x=0; x<icon->w; ++x ) {
  1597 					if ( *pixels++ == colorkey ) {
  1598 						SET_MASKBIT(icon, x, y, mask);
  1599 					}
  1600 				}
  1601 			}
  1602 		}
  1603 		break;
  1604 	}
  1605 }
  1606 
  1607 /*
  1608  * Sets the window manager icon for the display window.
  1609  */
  1610 void SDL_WM_SetIcon (SDL_Surface *icon, Uint8 *mask)
  1611 {
  1612 	SDL_VideoDevice *video = current_video;
  1613 	SDL_VideoDevice *this  = current_video;
  1614 
  1615 	if ( icon && video->SetIcon ) {
  1616 		/* Generate a mask if necessary, and create the icon! */
  1617 		if ( mask == NULL ) {
  1618 			int mask_len = icon->h*(icon->w+7)/8;
  1619 			mask = (Uint8 *)malloc(mask_len);
  1620 			if ( mask == NULL ) {
  1621 				return;
  1622 			}
  1623 			memset(mask, ~0, mask_len);
  1624 			if ( icon->flags & SDL_SRCCOLORKEY ) {
  1625 				CreateMaskFromColorKey(icon, mask);
  1626 			}
  1627 			video->SetIcon(video, icon, mask);
  1628 			free(mask);
  1629 		} else {
  1630 			video->SetIcon(this, icon, mask);
  1631 		}
  1632 	}
  1633 }
  1634 
  1635 /*
  1636  * Grab or ungrab the keyboard and mouse input.
  1637  * This function returns the final grab mode after calling the
  1638  * driver dependent function.
  1639  */
  1640 static SDL_GrabMode SDL_WM_GrabInputRaw(SDL_GrabMode mode)
  1641 {
  1642 	SDL_VideoDevice *video = current_video;
  1643 	SDL_VideoDevice *this  = current_video;
  1644 
  1645 	/* Only do something if we have support for grabs */
  1646 	if ( video->GrabInput == NULL ) {
  1647 		return(video->input_grab);
  1648 	}
  1649 
  1650 	/* If the final grab mode if off, only then do we actually grab */
  1651 #ifdef DEBUG_GRAB
  1652   printf("SDL_WM_GrabInputRaw(%d) ... ", mode);
  1653 #endif
  1654 	if ( mode == SDL_GRAB_OFF ) {
  1655 		if ( video->input_grab != SDL_GRAB_OFF ) {
  1656 			mode = video->GrabInput(this, mode);
  1657 		}
  1658 	} else {
  1659 		if ( video->input_grab == SDL_GRAB_OFF ) {
  1660 			mode = video->GrabInput(this, mode);
  1661 		}
  1662 	}
  1663 	if ( mode != video->input_grab ) {
  1664 		video->input_grab = mode;
  1665 		if ( video->CheckMouseMode ) {
  1666 			video->CheckMouseMode(this);
  1667 		}
  1668 	}
  1669 #ifdef DEBUG_GRAB
  1670   printf("Final mode %d\n", video->input_grab);
  1671 #endif
  1672 
  1673 	/* Return the final grab state */
  1674 	if ( mode >= SDL_GRAB_FULLSCREEN ) {
  1675 		mode -= SDL_GRAB_FULLSCREEN;
  1676 	}
  1677 	return(mode);
  1678 }
  1679 SDL_GrabMode SDL_WM_GrabInput(SDL_GrabMode mode)
  1680 {
  1681 	SDL_VideoDevice *video = current_video;
  1682 
  1683     /* If the video isn't initialized yet, we can't do anything */
  1684     if ( ! video ) {
  1685         return SDL_GRAB_OFF;
  1686     }
  1687 
  1688 	/* Return the current mode on query */
  1689 	if ( mode == SDL_GRAB_QUERY ) {
  1690 		mode = video->input_grab;
  1691 		if ( mode >= SDL_GRAB_FULLSCREEN ) {
  1692 			mode -= SDL_GRAB_FULLSCREEN;
  1693 		}
  1694 		return(mode);
  1695 	}
  1696 
  1697 #ifdef DEBUG_GRAB
  1698   printf("SDL_WM_GrabInput(%d) ... ", mode);
  1699 #endif
  1700 	/* If the video surface is fullscreen, we always grab */
  1701 	if ( mode >= SDL_GRAB_FULLSCREEN ) {
  1702 		mode -= SDL_GRAB_FULLSCREEN;
  1703 	}
  1704 	if ( SDL_VideoSurface && (SDL_VideoSurface->flags & SDL_FULLSCREEN) ) {
  1705 		mode += SDL_GRAB_FULLSCREEN;
  1706 	}
  1707 	return(SDL_WM_GrabInputRaw(mode));
  1708 }
  1709 static SDL_GrabMode SDL_WM_GrabInputOff(void)
  1710 {
  1711 	SDL_GrabMode mode;
  1712 
  1713 	/* First query the current grab state */
  1714 	mode = SDL_WM_GrabInput(SDL_GRAB_QUERY);
  1715 
  1716 	/* Now explicitly turn off input grab */
  1717 	SDL_WM_GrabInputRaw(SDL_GRAB_OFF);
  1718 
  1719 	/* Return the old state */
  1720 	return(mode);
  1721 }
  1722 
  1723 /*
  1724  * Iconify the window in window managed environments.
  1725  * A successful iconification will result in an SDL_APPACTIVE loss event.
  1726  */
  1727 int SDL_WM_IconifyWindow(void)
  1728 {
  1729 	SDL_VideoDevice *video = current_video;
  1730 	SDL_VideoDevice *this  = current_video;
  1731 	int retval;
  1732 
  1733 	retval = 0;
  1734 	if ( video->IconifyWindow ) {
  1735 		retval = video->IconifyWindow(this);
  1736 	}
  1737 	return(retval);
  1738 }
  1739 
  1740 /*
  1741  * Toggle fullscreen mode
  1742  */
  1743 int SDL_WM_ToggleFullScreen(SDL_Surface *surface)
  1744 {
  1745 	SDL_VideoDevice *video = current_video;
  1746 	SDL_VideoDevice *this  = current_video;
  1747 	int toggled;
  1748 
  1749 	toggled = 0;
  1750 	if ( SDL_PublicSurface && (surface == SDL_PublicSurface) &&
  1751 	     video->ToggleFullScreen ) {
  1752 		if ( surface->flags & SDL_FULLSCREEN ) {
  1753 			toggled = video->ToggleFullScreen(this, 0);
  1754 			if ( toggled ) {
  1755 				SDL_VideoSurface->flags &= ~SDL_FULLSCREEN;
  1756 				SDL_PublicSurface->flags &= ~SDL_FULLSCREEN;
  1757 			}
  1758 		} else {
  1759 			toggled = video->ToggleFullScreen(this, 1);
  1760 			if ( toggled ) {
  1761 				SDL_VideoSurface->flags |= SDL_FULLSCREEN;
  1762 				SDL_PublicSurface->flags |= SDL_FULLSCREEN;
  1763 			}
  1764 		}
  1765 		/* Double-check the grab state inside SDL_WM_GrabInput() */
  1766 		if ( toggled ) {
  1767 			SDL_WM_GrabInput(video->input_grab);
  1768 		}
  1769 	}
  1770 	return(toggled);
  1771 }
  1772 
  1773 /*
  1774  * Get some platform dependent window manager information
  1775  */
  1776 int SDL_GetWMInfo (SDL_SysWMinfo *info)
  1777 {
  1778 	SDL_VideoDevice *video = current_video;
  1779 	SDL_VideoDevice *this  = current_video;
  1780 
  1781 	if ( video && video->GetWMInfo ) {
  1782 		return(video->GetWMInfo(this, info));
  1783 	} else {
  1784 		return(0);
  1785 	}
  1786 }