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