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