Fixing game mode in X11 so that it doesn't override unspecified settings per e-mail...
[freeglut] / src / freeglut_gamemode.c
1 /*
2  * freeglut_gamemode.c
3  *
4  * The game mode handling code.
5  *
6  * Copyright (c) 1999-2000 Pawel W. Olszta. All Rights Reserved.
7  * Written by Pawel W. Olszta, <olszta@sourceforge.net>
8  * Creation date: Thu Dec 16 1999
9  *
10  * Permission is hereby granted, free of charge, to any person obtaining a
11  * copy of this software and associated documentation files (the "Software"),
12  * to deal in the Software without restriction, including without limitation
13  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
14  * and/or sell copies of the Software, and to permit persons to whom the
15  * Software is furnished to do so, subject to the following conditions:
16  *
17  * The above copyright notice and this permission notice shall be included
18  * in all copies or substantial portions of the Software.
19  *
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
21  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
23  * PAWEL W. OLSZTA BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
24  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
25  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26  */
27
28 #include <GL/freeglut.h>
29 #include "freeglut_internal.h"
30
31 /*
32  * TODO BEFORE THE STABLE RELEASE:
33  *
34  *  glutGameModeString()    -- missing
35  *  glutEnterGameMode()     -- X11 version
36  *  glutLeaveGameMode()     -- is that correct?
37  *  glutGameModeGet()       -- is that correct?
38  */
39
40
41 /* -- PRIVATE FUNCTIONS ---------------------------------------------------- */
42
43 /*
44  * Remembers the current visual settings, so that
45  * we can change them and restore later...
46  */
47 static void fghRememberState( void )
48 {
49 #if TARGET_HOST_POSIX_X11
50
51     /*
52      * This highly depends on the XFree86 extensions,
53      * not approved as X Consortium standards
54      */
55 #   ifdef X_XF86VidModeGetModeLine
56
57
58     /*
59      * Remember the current ViewPort location of the screen to be able to
60      * restore the ViewPort on LeaveGameMode():
61      */
62     if( !XF86VidModeGetViewPort(
63              fgDisplay.Display,
64              fgDisplay.Screen,
65              &fgDisplay.DisplayViewPortX,
66              &fgDisplay.DisplayViewPortY ) )
67         fgWarning( "XF86VidModeGetViewPort failed" );
68
69     /*
70      * Remember the current pointer location before going fullscreen
71      * for restoring it later:
72      */
73     {
74         Window junk_window;
75         unsigned int mask;
76
77         XQueryPointer(
78             fgDisplay.Display, fgDisplay.RootWindow,
79             &junk_window, &junk_window,
80             &fgDisplay.DisplayPointerX, &fgDisplay.DisplayPointerY,
81             &fgDisplay.DisplayPointerX, &fgDisplay.DisplayPointerY, &mask
82         );
83     }
84
85     /* Query the current display settings: */
86     fgDisplay.DisplayModeValid =
87       XF86VidModeGetModeLine(
88         fgDisplay.Display,
89         fgDisplay.Screen,
90         &fgDisplay.DisplayModeClock,
91         &fgDisplay.DisplayMode
92     );
93
94     if( !fgDisplay.DisplayModeValid )
95             fgWarning( "XF86VidModeGetModeLine failed" );
96
97 #   else
98     /*
99      * XXX warning fghRememberState: missing XFree86 video mode extensions,
100      * XXX game mode will not change screen resolution when activated
101      */
102 #   endif
103
104 #elif TARGET_HOST_MS_WINDOWS
105
106 /*    DEVMODE devMode; */
107
108     /* Grab the current desktop settings... */
109
110 /* hack to get around my stupid cross-gcc headers */
111 #define FREEGLUT_ENUM_CURRENT_SETTINGS -1
112
113     EnumDisplaySettings( fgDisplay.DisplayName, FREEGLUT_ENUM_CURRENT_SETTINGS,
114                          &fgDisplay.DisplayMode );
115
116     /* Make sure we will be restoring all settings needed */
117     fgDisplay.DisplayMode.dmFields |=
118         DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL | DM_DISPLAYFREQUENCY;
119
120 #endif
121 }
122
123 /*
124  * Restores the previously remembered visual settings
125  */
126 static void fghRestoreState( void )
127 {
128 #if TARGET_HOST_POSIX_X11
129
130 #   ifdef X_XF86VidModeGetAllModeLines
131     /* Restore the remembered pointer position: */
132     XWarpPointer(
133         fgDisplay.Display, None, fgDisplay.RootWindow, 0, 0, 0, 0,
134         fgDisplay.DisplayPointerX, fgDisplay.DisplayPointerY
135     );
136
137     /*
138      * This highly depends on the XFree86 extensions,
139      * not approved as X Consortium standards
140      */
141
142     if( fgDisplay.DisplayModeValid )
143     {
144         XF86VidModeModeInfo** displayModes;
145         int i, displayModesCount;
146
147         if( !XF86VidModeGetAllModeLines(
148                  fgDisplay.Display,
149                  fgDisplay.Screen,
150                  &displayModesCount,
151                  &displayModes ) )
152         {
153             fgWarning( "XF86VidModeGetAllModeLines failed" );
154             return;
155         }
156
157
158         /*
159          * Check every of the modes looking for one that matches our demands.
160          * If we find one, switch to it and restore the remembered viewport.
161          */
162         for( i = 0; i < displayModesCount; i++ )
163         {
164             if(displayModes[ i ]->hdisplay == fgDisplay.DisplayMode.hdisplay &&
165                displayModes[ i ]->vdisplay == fgDisplay.DisplayMode.vdisplay &&
166                displayModes[ i ]->dotclock == fgDisplay.DisplayModeClock )
167             {
168                 if( !XF86VidModeSwitchToMode(
169                          fgDisplay.Display,
170                          fgDisplay.Screen,
171                          displayModes[ i ] ) )
172                 {
173                     fgWarning( "XF86VidModeSwitchToMode failed" );
174                     break;
175                 }
176
177                 if( !XF86VidModeSetViewPort(
178                          fgDisplay.Display,
179                          fgDisplay.Screen,
180                          fgDisplay.DisplayViewPortX,
181                          fgDisplay.DisplayViewPortY ) )
182                     fgWarning( "XF86VidModeSetViewPort failed" );
183
184
185                 /*
186                  * For the case this would be the last X11 call the application
187                  * calls exit() we've to flush the X11 output queue to have the
188                  * commands sent to the X server before the application exits.
189                  */
190                 XFlush( fgDisplay.Display );
191
192                 break;
193             }
194         }
195         XFree( displayModes );
196     }
197
198 #   else
199     /*
200      * XXX warning fghRestoreState: missing XFree86 video mode extensions,
201      * XXX game mode will not change screen resolution when activated
202      */
203 #   endif
204
205 #elif TARGET_HOST_MS_WINDOWS
206
207     /* Restore the previously rememebered desktop display settings */
208     ChangeDisplaySettingsEx( fgDisplay.DisplayName,&fgDisplay.DisplayMode, 0,0,0 );
209
210 #endif
211 }
212
213 #if TARGET_HOST_POSIX_X11
214 #ifdef X_XF86VidModeGetAllModeLines
215
216 /*
217  * Checks a single display mode settings against user's preferences.
218  */
219 static GLboolean fghCheckDisplayMode( int width, int height, int depth, int refresh )
220 {
221     /* The desired values should be stored in fgState structure... */
222     return ( width == fgState.GameModeSize.X ) &&
223            ( height == fgState.GameModeSize.Y ) &&
224            ( depth == fgState.GameModeDepth ) &&
225            ( refresh == fgState.GameModeRefresh );
226 }
227
228 /*
229  * Checks all display modes settings against user's preferences.
230  * Returns the mode number found or -1 if none could be found.
231  */
232 static int fghCheckDisplayModes( GLboolean exactMatch, int displayModesCount, XF86VidModeModeInfo** displayModes )
233 {
234     int i;
235     for( i = 0; i < displayModesCount; i++ )
236     {
237         /* Compute the displays refresh rate, dotclock comes in kHz. */
238         int refresh = ( displayModes[ i ]->dotclock * 1000 ) /
239                       ( displayModes[ i ]->htotal * displayModes[ i ]->vtotal );
240
241         if( fghCheckDisplayMode( displayModes[ i ]->hdisplay,
242                                  displayModes[ i ]->vdisplay,
243                                  fgState.GameModeDepth,
244                                  ( exactMatch ? refresh : fgState.GameModeRefresh ) ) ) {
245             return i;
246         }
247     }
248     return -1;
249 }
250
251 #endif
252 #endif
253
254 /*
255  * Changes the current display mode to match user's settings
256  */
257 static GLboolean fghChangeDisplayMode( GLboolean haveToTest )
258 {
259     GLboolean success = GL_FALSE;
260 #if TARGET_HOST_POSIX_X11
261
262     /*
263      * This highly depends on the XFree86 extensions,
264      * not approved as X Consortium standards
265      */
266 #   ifdef X_XF86VidModeGetAllModeLines
267
268     /*
269      * This is also used by applcations which check modes by calling
270      * glutGameModeGet(GLUT_GAME_MODE_POSSIBLE), so allow the check:
271      */
272     if( haveToTest || fgDisplay.DisplayModeValid )
273     {
274         XF86VidModeModeInfo** displayModes;
275         int i, displayModesCount;
276
277         if( !XF86VidModeGetAllModeLines(
278                  fgDisplay.Display,
279                  fgDisplay.Screen,
280                  &displayModesCount,
281                  &displayModes ) )
282         {
283             fgWarning( "XF86VidModeGetAllModeLines failed" );
284             return success;
285         }
286
287
288         /*
289          * Check every of the modes looking for one that matches our demands,
290          * ignoring the refresh rate if no exact match could be found.
291          */
292         i = fghCheckDisplayModes( GL_TRUE, displayModesCount, displayModes );
293         if( i < 0 ) {
294             i = fghCheckDisplayModes( GL_FALSE, displayModesCount, displayModes );
295         }
296         success = ( i < 0 ) ? GL_FALSE : GL_TRUE;
297
298         if( !haveToTest && success ) {
299             if( !XF86VidModeSwitchToMode(
300                      fgDisplay.Display,
301                      fgDisplay.Screen,
302                      displayModes[ i ] ) )
303                 fgWarning( "XF86VidModeSwitchToMode failed" );
304         }
305
306         XFree( displayModes );
307     }
308
309 #   else
310
311     /*
312      * XXX warning fghChangeDisplayMode: missing XFree86 video mode extensions,
313      * XXX game mode will not change screen resolution when activated
314      */
315     success = GL_TRUE;
316
317 #   endif
318
319 #elif TARGET_HOST_MS_WINDOWS
320
321     DEVMODE  devMode;
322     char *fggmstr = NULL;
323
324     success = GL_FALSE;
325
326     EnumDisplaySettings( fgDisplay.DisplayName, -1, &devMode ); 
327     devMode.dmFields = 0;
328
329     if (fgState.GameModeSize.X!=-1)
330     {
331         devMode.dmPelsWidth  = fgState.GameModeSize.X;
332         devMode.dmFields |= DM_PELSWIDTH;
333     }
334     if (fgState.GameModeSize.Y!=-1)
335     {
336         devMode.dmPelsHeight  = fgState.GameModeSize.Y;
337         devMode.dmFields |= DM_PELSHEIGHT;
338     }
339     if (fgState.GameModeDepth!=-1)
340     {
341         devMode.dmBitsPerPel  = fgState.GameModeDepth;
342         devMode.dmFields |= DM_BITSPERPEL;
343     }
344     if (fgState.GameModeRefresh!=-1)
345     {
346         devMode.dmDisplayFrequency  = fgState.GameModeRefresh;
347         devMode.dmFields |= DM_DISPLAYFREQUENCY;
348     }
349
350     switch ( ChangeDisplaySettingsEx(fgDisplay.DisplayName, &devMode, NULL, haveToTest ? CDS_TEST : CDS_FULLSCREEN , NULL) )
351     {
352     case DISP_CHANGE_SUCCESSFUL:
353         success = GL_TRUE;
354
355         /* update vars in case if windows switched to proper mode */
356         EnumDisplaySettings( fgDisplay.DisplayName, FREEGLUT_ENUM_CURRENT_SETTINGS, &devMode );
357         fgState.GameModeSize.X  = devMode.dmPelsWidth;        
358         fgState.GameModeSize.Y  = devMode.dmPelsHeight;
359         fgState.GameModeDepth   = devMode.dmBitsPerPel;
360         fgState.GameModeRefresh = devMode.dmDisplayFrequency;
361                 break;
362     case DISP_CHANGE_RESTART:
363         fggmstr = "The computer must be restarted for the graphics mode to work.";
364         break;
365     case DISP_CHANGE_BADFLAGS:
366         fggmstr = "An invalid set of flags was passed in.";
367         break;
368     case DISP_CHANGE_BADPARAM:
369         fggmstr = "An invalid parameter was passed in. This can include an invalid flag or combination of flags.";
370         break;
371     case DISP_CHANGE_FAILED:
372         fggmstr = "The display driver failed the specified graphics mode.";
373         break;
374     case DISP_CHANGE_BADMODE:
375         fggmstr = "The graphics mode is not supported.";
376         break;
377     default:
378         fggmstr = "Unknown error in graphics mode???"; /* dunno if it is possible,MSDN does not mention any other error */
379         break;
380     }
381
382     if ( !success )
383         fgWarning(fggmstr); /* I'd rather get info whats going on in my program than wonder about */
384                             /* magic happenings behind my back, its lib for devels at last ;) */
385 #endif
386
387     return success;
388 }
389
390
391 /* -- INTERFACE FUNCTIONS -------------------------------------------------- */
392
393 /*
394  * Sets the game mode display string
395  */
396 void FGAPIENTRY glutGameModeString( const char* string )
397 {
398     int width = -1, height = -1, depth = -1, refresh = -1;
399
400     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutGameModeString" );
401
402     /*
403      * This one seems a bit easier than glutInitDisplayString. The bad thing
404      * about it that I was unable to find the game mode string definition, so
405      * that I assumed it is: "[width]x[height]:[depth]@[refresh rate]", which
406      * appears in all GLUT game mode programs I have seen to date.
407      */
408     if( sscanf( string, "%ix%i:%i@%i", &width, &height, &depth, &refresh ) !=
409         4 )
410         if( sscanf( string, "%ix%i:%i", &width, &height, &depth ) != 3 )
411             if( sscanf( string, "%ix%i@%i", &width, &height, &refresh ) != 3 )
412                 if( sscanf( string, "%ix%i", &width, &height ) != 2 )
413                     if( sscanf( string, ":%i@%i", &depth, &refresh ) != 2 )
414                         if( sscanf( string, ":%i", &depth ) != 1 )
415                             if( sscanf( string, "@%i", &refresh ) != 1 )
416                                 fgWarning(
417                                     "unable to parse game mode string `%s'",
418                                     string
419                                 );
420
421     /* Hopefully it worked, and if not, we still have the default values */
422     if ( width   > 0 ) fgState.GameModeSize.X  = width;
423     if ( height  > 0 ) fgState.GameModeSize.Y  = height;
424     if ( depth   > 0 ) fgState.GameModeDepth   = depth;
425     if ( refresh > 0 ) fgState.GameModeRefresh = refresh;
426 }
427
428
429
430 /*
431  * Enters the game mode
432  */
433 int FGAPIENTRY glutEnterGameMode( void )
434 {
435     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutEnterGameMode" );
436
437     if( fgStructure.GameModeWindow )
438         fgAddToWindowDestroyList( fgStructure.GameModeWindow );
439     else
440         fghRememberState( );
441
442     if( ! fghChangeDisplayMode( GL_FALSE ) )
443     {
444         fgWarning( "failed to change screen settings" );
445         return 0;
446     }
447
448     fgStructure.GameModeWindow = fgCreateWindow(
449         NULL, "FREEGLUT", GL_TRUE, 0, 0,
450         GL_TRUE, fgState.GameModeSize.X, fgState.GameModeSize.Y,
451         GL_TRUE, GL_FALSE
452     );
453
454     fgStructure.GameModeWindow->State.Width  = fgState.GameModeSize.X;
455     fgStructure.GameModeWindow->State.Height = fgState.GameModeSize.Y;
456     fgStructure.GameModeWindow->State.NeedToResize = GL_TRUE;
457
458 #if TARGET_HOST_POSIX_X11
459
460     /*
461      * Sync needed to avoid a real race, the Xserver must have really created
462      * the window before we can grab the pointer into it:
463      */
464     XSync( fgDisplay.Display, False );
465
466     /*
467      * Grab the pointer to confine it into the window after the calls to
468      * XWrapPointer() which ensure that the pointer really enters the window.
469      *
470      * We also need to wait here until XGrabPointer() returns GrabSuccess,
471      * otherwise the new window is not viewable yet and if the next function
472      * (XSetInputFocus) is called with a not yet viewable window, it will exit
473      * the application which we have to aviod, so wait until it's viewable:
474      */
475     while( GrabSuccess != XGrabPointer(
476                fgDisplay.Display, fgStructure.GameModeWindow->Window.Handle,
477                TRUE,
478                ButtonPressMask | ButtonReleaseMask | ButtonMotionMask
479                | PointerMotionMask,
480                GrabModeAsync, GrabModeAsync,
481                fgStructure.GameModeWindow->Window.Handle, None, CurrentTime) )
482         usleep( 100 );
483
484     /*
485      * Change input focus to the new window. This will exit the application
486      * if the new window is not viewable yet, see the XGrabPointer loop above.
487      */
488     XSetInputFocus(
489         fgDisplay.Display,
490         fgStructure.GameModeWindow->Window.Handle,
491         RevertToNone,
492         CurrentTime
493     );
494
495     /* Move the Pointer to the middle of the fullscreen window */
496     XWarpPointer(
497         fgDisplay.Display,
498         None,
499         fgDisplay.RootWindow,
500         0, 0, 0, 0,
501         fgState.GameModeSize.X/2, fgState.GameModeSize.Y/2
502     );
503
504 #   ifdef X_XF86VidModeSetViewPort
505
506     if( fgDisplay.DisplayModeValid )
507     {
508         int x, y;
509         Window child;
510
511         /* Change to viewport to the window topleft edge: */
512         if( !XF86VidModeSetViewPort( fgDisplay.Display, fgDisplay.Screen, 0, 0 ) )
513             fgWarning( "XF86VidModeSetViewPort failed" );
514
515         /*
516          * Final window repositioning: It could be avoided using an undecorated
517          * window using override_redirect, but this * would possily require
518          * more changes and investigation.
519          */
520
521         /* Get the current postion of the drawable area on screen */
522         XTranslateCoordinates(
523             fgDisplay.Display,
524             fgStructure.CurrentWindow->Window.Handle,
525             fgDisplay.RootWindow,
526             0, 0, &x, &y,
527             &child
528         );
529
530         /* Move the decorataions out of the topleft corner of the display */
531         XMoveWindow( fgDisplay.Display, fgStructure.CurrentWindow->Window.Handle,
532                      -x, -y);
533     }
534
535 #endif
536
537     /* Grab the keyboard, too */
538     XGrabKeyboard(
539         fgDisplay.Display,
540         fgStructure.GameModeWindow->Window.Handle,
541         FALSE,
542         GrabModeAsync, GrabModeAsync,
543         CurrentTime
544     );
545
546 #endif
547
548     return fgStructure.GameModeWindow->ID;
549 }
550
551 /*
552  * Leaves the game mode
553  */
554 void FGAPIENTRY glutLeaveGameMode( void )
555 {
556     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutLeaveGameMode" );
557
558     freeglut_return_if_fail( fgStructure.GameModeWindow );
559
560     fgAddToWindowDestroyList( fgStructure.GameModeWindow );
561     fgStructure.GameModeWindow = NULL;
562
563 #if TARGET_HOST_POSIX_X11
564
565     XUngrabPointer( fgDisplay.Display, CurrentTime );
566     XUngrabKeyboard( fgDisplay.Display, CurrentTime );
567
568 #endif
569
570     fghRestoreState();
571 }
572
573 /*
574  * Returns information concerning the freeglut game mode
575  */
576 int FGAPIENTRY glutGameModeGet( GLenum eWhat )
577 {
578     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutGameModeGet" );
579
580     switch( eWhat )
581     {
582     case GLUT_GAME_MODE_ACTIVE:
583         return !!fgStructure.GameModeWindow;
584
585     case GLUT_GAME_MODE_POSSIBLE:
586         return fghChangeDisplayMode( GL_TRUE );
587
588     case GLUT_GAME_MODE_WIDTH:
589         return fgState.GameModeSize.X;
590
591     case GLUT_GAME_MODE_HEIGHT:
592         return fgState.GameModeSize.Y;
593
594     case GLUT_GAME_MODE_PIXEL_DEPTH:
595         return fgState.GameModeDepth;
596
597     case GLUT_GAME_MODE_REFRESH_RATE:
598         return fgState.GameModeRefresh;
599
600     case GLUT_GAME_MODE_DISPLAY_CHANGED:
601         /*
602          * This is true if the game mode has been activated successfully..
603          */
604         return !!fgStructure.GameModeWindow;
605     }
606
607     fgWarning( "Unknown gamemode get: %d", eWhat );
608     return -1;
609 }
610
611 /*** END OF FILE ***/