11c24e6150762c32877ec2f1a2d31bb6bc829a25
[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 #ifdef HAVE_CONFIG_H
29 #include "config.h"
30 #endif
31
32 #include <GL/freeglut.h>
33 #include "freeglut_internal.h"
34
35 /*
36  * TODO BEFORE THE STABLE RELEASE:
37  *
38  *  glutGameModeString()    -- missing
39  *  glutEnterGameMode()     -- X11 version
40  *  glutLeaveGameMode()     -- is that correct?
41  *  glutGameModeGet()       -- is that correct?
42  */
43
44
45 /* -- PRIVATE FUNCTIONS ---------------------------------------------------- */
46
47 /*
48  * Remembers the current visual settings, so that
49  * we can change them and restore later...
50  */
51 static void fghRememberState( void )
52 {
53 #if TARGET_HOST_UNIX_X11
54
55     /*
56      * This highly depends on the XFree86 extensions,
57      * not approved as X Consortium standards
58      */
59 #   ifdef X_XF86VidModeGetModeLine
60
61
62     /*
63      * Remember the current ViewPort location of the screen to be able to
64      * restore the ViewPort on LeaveGameMode():
65      */
66     XF86VidModeGetViewPort(
67         fgDisplay.Display,
68         fgDisplay.Screen,
69         &fgDisplay.DisplayViewPortX,
70         &fgDisplay.DisplayViewPortY
71     );
72
73     /*
74      * Remember the current pointer location before going fullscreen
75      * for restoring it later:
76      */
77     {
78         Window junk_window;
79         unsigned int mask;
80
81         XQueryPointer(
82             fgDisplay.Display, fgDisplay.RootWindow,
83             &junk_window, &junk_window,
84             &fgDisplay.DisplayPointerX, &fgDisplay.DisplayPointerY,
85             &fgDisplay.DisplayPointerX, &fgDisplay.DisplayPointerY, &mask
86         );
87     }
88
89     /* Query the current display settings: */
90     fgDisplay.DisplayModeValid =
91       XF86VidModeGetModeLine(
92         fgDisplay.Display,
93         fgDisplay.Screen,
94         &fgDisplay.DisplayModeClock,
95         &fgDisplay.DisplayMode
96     );
97
98     if( !fgDisplay.DisplayModeValid )
99             fgWarning( "Runtime use of XF86VidModeGetModeLine failed." );
100
101 #   else
102     /*
103      * XXX warning fghRememberState: missing XFree86 video mode extensions,
104      * XXX game mode will not change screen resolution when activated
105      */
106 #   endif
107
108 #elif TARGET_HOST_WIN32 || TARGET_HOST_WINCE
109
110 /*    DEVMODE devMode; */
111
112     /* Grab the current desktop settings... */
113
114 /* hack to get around my stupid cross-gcc headers */
115 #define FREEGLUT_ENUM_CURRENT_SETTINGS -1
116
117     EnumDisplaySettings( NULL, FREEGLUT_ENUM_CURRENT_SETTINGS,
118                          &fgDisplay.DisplayMode );
119
120     /* Make sure we will be restoring all settings needed */
121     fgDisplay.DisplayMode.dmFields |=
122         DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL | DM_DISPLAYFREQUENCY;
123
124 #endif
125 }
126
127 /*
128  * Restores the previously remembered visual settings
129  */
130 static void fghRestoreState( void )
131 {
132 #if TARGET_HOST_UNIX_X11
133
134 #   ifdef X_XF86VidModeGetAllModeLines
135     /* Restore the remembered pointer position: */
136     XWarpPointer(
137         fgDisplay.Display, None, fgDisplay.RootWindow, 0, 0, 0, 0,
138         fgDisplay.DisplayPointerX, fgDisplay.DisplayPointerY
139     );
140
141     /*
142      * This highly depends on the XFree86 extensions,
143      * not approved as X Consortium standards
144      */
145
146     if( fgDisplay.DisplayModeValid )
147     {
148         XF86VidModeModeInfo** displayModes;
149         int i, displayModesCount;
150
151         XF86VidModeGetAllModeLines(
152             fgDisplay.Display,
153             fgDisplay.Screen,
154             &displayModesCount,
155             &displayModes
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                 XF86VidModeSwitchToMode(
169                     fgDisplay.Display,
170                     fgDisplay.Screen,
171                     displayModes[ i ]
172                 );
173                 XF86VidModeSetViewPort(
174                      fgDisplay.Display,
175                      fgDisplay.Screen,
176                      fgDisplay.DisplayViewPortX,
177                      fgDisplay.DisplayViewPortY
178                 );
179
180                 /*
181                  * For the case this would be the last X11 call the application
182                  * calls exit() we've to flush the X11 output queue to have the
183                  * commands sent to the X server before the application exits.
184                  */
185                 XFlush( fgDisplay.Display );
186
187                 return;
188             }
189         }
190     }
191
192 #   else
193     /*
194      * XXX warning fghRestoreState: missing XFree86 video mode extensions,
195      * XXX game mode will not change screen resolution when activated
196      */
197 #   endif
198
199 #elif TARGET_HOST_WIN32 || TARGET_HOST_WINCE
200
201     /* Restore the previously rememebered desktop display settings */
202     ChangeDisplaySettings( &fgDisplay.DisplayMode, 0 );
203
204 #endif
205 }
206
207 /*
208  * Checks the display mode settings against user's preferences
209  */
210 static GLboolean fghCheckDisplayMode( int width, int height, int depth, int refresh )
211 {
212     /* The desired values should be stored in fgState structure... */
213     return ( width == fgState.GameModeSize.X ) &&
214            ( height == fgState.GameModeSize.Y ) &&
215            ( depth == fgState.GameModeDepth ) &&
216            (refresh == fgState.GameModeRefresh );
217 }
218
219 /*
220  * Changes the current display mode to match user's settings
221  */
222 static GLboolean fghChangeDisplayMode( GLboolean haveToTest )
223 {
224 #if TARGET_HOST_UNIX_X11
225
226     /*
227      * This highly depends on the XFree86 extensions,
228      * not approved as X Consortium standards
229      */
230 #   ifdef X_XF86VidModeGetAllModeLines
231
232     /*
233      * This is also used by applcations which check modes by calling
234      * glutGameModeGet(GLUT_GAME_MODE_POSSIBLE), so allow the check:
235      */
236     if( haveToTest || fgDisplay.DisplayModeValid )
237     {
238         XF86VidModeModeInfo** displayModes;
239         int i, displayModesCount;
240
241         XF86VidModeGetAllModeLines(
242             fgDisplay.Display,
243             fgDisplay.Screen,
244             &displayModesCount,
245             &displayModes
246         );
247
248         /* Check every of the modes looking for one that matches our demands */
249         for( i = 0; i < displayModesCount; i++ )
250         {
251             if( fghCheckDisplayMode( displayModes[ i ]->hdisplay,
252                                      displayModes[ i ]->vdisplay,
253                                      fgState.GameModeDepth,
254                                      fgState.GameModeRefresh ) )
255             {
256                 if( haveToTest )
257                     return GL_TRUE;
258                 /* OKi, this is the display mode we have been looking for... */
259                 XF86VidModeSwitchToMode(
260                     fgDisplay.Display,
261                     fgDisplay.Screen,
262                     displayModes[ i ]
263                 );
264                 return GL_TRUE;
265             }
266         }
267     }
268
269     /* Something must have gone wrong */
270     return GL_FALSE;
271
272 #   else
273     /*
274      * XXX warning fghChangeDisplayMode: missing XFree86 video mode extensions,
275      * XXX game mode will not change screen resolution when activated
276      */
277 #   endif
278
279 #elif TARGET_HOST_WIN32 || TARGET_HOST_WINCE
280
281     unsigned int    displayModes = 0, mode = 0xffffffff;
282     GLboolean success = GL_FALSE;
283     /* HDC      desktopDC; */
284     DEVMODE  devMode;
285
286     /*
287      * Enumerate the available display modes
288      * Try to get a complete match
289      */
290     while( EnumDisplaySettings( NULL, displayModes, &devMode ) )
291     {
292         /* Does the enumerated display mode match the user's preferences? */
293         if( fghCheckDisplayMode( devMode.dmPelsWidth,  devMode.dmPelsHeight,
294                                  devMode.dmBitsPerPel,
295                                  devMode.dmDisplayFrequency ) )
296         {
297             mode = displayModes;
298             break;
299         }
300         displayModes++;
301     }
302
303     if( mode == 0xffffffff )
304     {
305         /* then try without Display Frequency */
306         displayModes = 0;
307
308         /* Enumerate the available display modes */
309         while( EnumDisplaySettings( NULL, displayModes, &devMode ) )
310         {
311             /* then try without Display Frequency */
312             if( fghCheckDisplayMode( devMode.dmPelsWidth,
313                                      devMode.dmPelsHeight,
314                                      devMode.dmBitsPerPel,
315                                      fgState.GameModeRefresh ) )
316             {
317                 mode = displayModes;
318                 break;
319             }
320             displayModes++;
321         }
322     }
323
324     /* Did we find a matching display mode? */
325     if( mode != 0xffffffff )
326     {
327         int retVal = DISP_CHANGE_SUCCESSFUL;
328
329         /* Mark the values we want to modify in the display change call */
330         devMode.dmFields |=
331             DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL | DM_DISPLAYFREQUENCY;
332
333         retVal = ChangeDisplaySettings( &devMode, haveToTest ? CDS_TEST : 0 );
334
335         /* I don't know if it's really needed, but looks nice: */
336         success = (retVal == DISP_CHANGE_SUCCESSFUL) ||
337             (retVal == DISP_CHANGE_NOTUPDATED);
338
339         if( !haveToTest && success )
340         {
341             fgState.GameModeSize.X  = devMode.dmPelsWidth;
342             fgState.GameModeSize.Y  = devMode.dmPelsHeight;
343             fgState.GameModeDepth   = devMode.dmBitsPerPel;
344             fgState.GameModeRefresh = devMode.dmDisplayFrequency;
345         }
346     }
347
348     return success;
349
350 #endif
351 }
352
353
354 /* -- INTERFACE FUNCTIONS -------------------------------------------------- */
355
356 /*
357  * Sets the game mode display string
358  */
359 void FGAPIENTRY glutGameModeString( const char* string )
360 {
361     int width = 640, height = 480, depth = 16, refresh = 72;
362
363     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutGameModeString" );
364
365     /*
366      * This one seems a bit easier than glutInitDisplayString. The bad thing
367      * about it that I was unable to find the game mode string definition, so
368      * that I assumed it is: "[width]x[height]:[depth]@[refresh rate]", which
369      * appears in all GLUT game mode programs I have seen to date.
370      */
371     if( sscanf( string, "%ix%i:%i@%i", &width, &height, &depth, &refresh ) !=
372         4 )
373         if( sscanf( string, "%ix%i:%i", &width, &height, &depth ) != 3 )
374             if( sscanf( string, "%ix%i@%i", &width, &height, &refresh ) != 3 )
375                 if( sscanf( string, "%ix%i", &width, &height ) != 2 )
376                     if( sscanf( string, ":%i@%i", &depth, &refresh ) != 2 )
377                         if( sscanf( string, ":%i", &depth ) != 1 )
378                             if( sscanf( string, "@%i", &refresh ) != 1 )
379                                 fgWarning(
380                                     "unable to parse game mode string `%s'",
381                                     string
382                                 );
383
384     /* Hopefully it worked, and if not, we still have the default values */
385     fgState.GameModeSize.X  = width;
386     fgState.GameModeSize.Y  = height;
387     fgState.GameModeDepth   = depth;
388     fgState.GameModeRefresh = refresh;
389 }
390
391 /*
392  * Enters the game mode
393  */
394 int FGAPIENTRY glutEnterGameMode( void )
395 {
396     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutEnterGameMode" );
397
398     if( fgStructure.GameMode )
399         fgAddToWindowDestroyList( fgStructure.GameMode );
400     else
401         fghRememberState( );
402
403     if( ! fghChangeDisplayMode( GL_FALSE ) )
404     {
405         fgWarning( "failed to change screen settings" );
406         return FALSE;
407     }
408
409     fgStructure.GameMode = fgCreateWindow(
410         NULL, "FREEGLUT", 0, 0,
411         fgState.GameModeSize.X, fgState.GameModeSize.Y, GL_TRUE, GL_FALSE
412     );
413
414     fgStructure.GameMode->State.IsGameMode = GL_TRUE;
415
416 #if TARGET_HOST_UNIX_X11
417
418     /* Move the window up to the topleft corner */
419     XMoveWindow( fgDisplay.Display, fgStructure.Window->Window.Handle, 0, 0 );
420
421     /*
422      * Sync needed to avoid a real race, the Xserver must have really created
423      * the window before we can grab the pointer into it:
424      */
425     XSync( fgDisplay.Display, False );
426
427     /* Move the Pointer to the middle of the fullscreen window */
428     XWarpPointer(
429         fgDisplay.Display,
430         None,
431         fgDisplay.RootWindow,
432         0, 0, 0, 0,
433         fgState.GameModeSize.X/2, fgState.GameModeSize.Y/2
434     );
435
436     /*
437      * Grab the pointer to confine it into the window after the calls to
438      * XWrapPointer() which ensure that the pointer really enters the window.
439      *
440      * We also need to wait here until XGrabPointer() returns GrabSuccess,
441      * otherwise the new window is not viewable yet and if the next function
442      * (XSetInputFocus) is called with a not yet viewable window, it will exit
443      * the application which we have to aviod, so wait until it's viewable:
444      */
445     while( GrabSuccess != XGrabPointer(
446                fgDisplay.Display, fgStructure.GameMode->Window.Handle,
447                TRUE,
448                ButtonPressMask | ButtonReleaseMask | ButtonMotionMask
449                | PointerMotionMask,
450                GrabModeAsync, GrabModeAsync,
451                fgStructure.GameMode->Window.Handle, None, CurrentTime) )
452         usleep( 100 );
453
454     /*
455      * Change input focus to the new window. This will exit the application
456      * if the new window is not viewable yet, see the XGrabPointer loop above.
457      */
458     XSetInputFocus(
459         fgDisplay.Display,
460         fgStructure.GameMode->Window.Handle,
461         RevertToNone,
462         CurrentTime
463     );
464
465 #   ifdef X_XF86VidModeSetViewPort
466
467     if( fgDisplay.DisplayModeValid )
468     {
469         int x, y;
470         Window child;
471
472         /* Change to viewport to the window topleft edge: */
473         XF86VidModeSetViewPort( fgDisplay.Display, fgDisplay.Screen, 0, 0 );
474
475         /*
476          * Final window repositioning: It could be avoided using an undecorated
477          * window using override_redirect, but this * would possily require
478          * more changes and investigation.
479          */
480
481         /* Get the current postion of the drawable area on screen */
482         XTranslateCoordinates(
483             fgDisplay.Display,
484             fgStructure.Window->Window.Handle,
485             fgDisplay.RootWindow,
486             0, 0, &x, &y,
487             &child
488         );
489
490         /* Move the decorataions out of the topleft corner of the display */
491         XMoveWindow( fgDisplay.Display, fgStructure.Window->Window.Handle,
492                      -x, -y);
493     }
494
495 #endif
496
497     /* Grab the keyboard, too */
498     XGrabKeyboard(
499         fgDisplay.Display,
500         fgStructure.GameMode->Window.Handle,
501         FALSE,
502         GrabModeAsync, GrabModeAsync,
503         CurrentTime
504     );
505
506 #endif
507
508     return TRUE;
509 }
510
511 /*
512  * Leaves the game mode
513  */
514 void FGAPIENTRY glutLeaveGameMode( void )
515 {
516     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutLeaveGameMode" );
517
518     freeglut_return_if_fail( fgStructure.GameMode );
519
520     fgStructure.GameMode->State.IsGameMode = GL_FALSE;
521
522     fgAddToWindowDestroyList( fgStructure.GameMode );
523     fgStructure.GameMode = NULL;
524
525 #if TARGET_HOST_UNIX_X11
526
527     XUngrabPointer( fgDisplay.Display, CurrentTime );
528     XUngrabKeyboard( fgDisplay.Display, CurrentTime );
529
530 #endif
531
532     fghRestoreState();
533 }
534
535 /*
536  * Returns information concerning the freeglut game mode
537  */
538 int FGAPIENTRY glutGameModeGet( GLenum eWhat )
539 {
540     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutGameModeGet" );
541
542     switch( eWhat )
543     {
544     case GLUT_GAME_MODE_ACTIVE:
545         return !!fgStructure.GameMode;
546
547     case GLUT_GAME_MODE_POSSIBLE:
548         return fghChangeDisplayMode( GL_TRUE );
549
550     case GLUT_GAME_MODE_WIDTH:
551         return fgState.GameModeSize.X;
552
553     case GLUT_GAME_MODE_HEIGHT:
554         return fgState.GameModeSize.Y;
555
556     case GLUT_GAME_MODE_PIXEL_DEPTH:
557         return fgState.GameModeDepth;
558
559     case GLUT_GAME_MODE_REFRESH_RATE:
560         return fgState.GameModeRefresh;
561
562     case GLUT_GAME_MODE_DISPLAY_CHANGED:
563         /*
564          * This is true if the game mode has been activated successfully..
565          */
566         return !!fgStructure.GameMode;
567     }
568
569     fgWarning( "Unknown gamemode get: %d", eWhat );
570     return -1;
571 }
572
573 /*** END OF FILE ***/