Implementing John Tsiombikas' game mode patch per e-mail dated 3/15/11 8:04 PM
[freeglut] / src / freeglut_init.c
1 /*
2  * freeglut_init.c
3  *
4  * Various freeglut initialization functions.
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 2 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 #define FREEGLUT_BUILDING_LIB
29 #include <GL/freeglut.h>
30 #include "freeglut_internal.h"
31
32 #if TARGET_HOST_POSIX_X11
33 #include <limits.h>  /* LONG_MAX */
34 #endif
35
36 /*
37  * TODO BEFORE THE STABLE RELEASE:
38  *
39  *  fgDeinitialize()        -- Win32's OK, X11 needs the OS-specific
40  *                             deinitialization done
41  *  glutInitDisplayString() -- display mode string parsing
42  *
43  * Wouldn't it be cool to use gettext() for error messages? I just love
44  * bash saying  "nie znaleziono pliku" instead of "file not found" :)
45  * Is gettext easily portable?
46  */
47
48 /* -- GLOBAL VARIABLES ----------------------------------------------------- */
49
50 /*
51  * A structure pointed by g_pDisplay holds all information
52  * regarding the display, screen, root window etc.
53  */
54 SFG_Display fgDisplay;
55
56 /*
57  * The settings for the current freeglut session
58  */
59 SFG_State fgState = { { -1, -1, GL_FALSE },  /* Position */
60                       { 300, 300, GL_TRUE }, /* Size */
61                       GLUT_RGBA | GLUT_SINGLE | GLUT_DEPTH,  /* DisplayMode */
62                       GL_FALSE,              /* Initialised */
63                       GLUT_TRY_DIRECT_CONTEXT,  /* DirectContext */
64                       GL_FALSE,              /* ForceIconic */
65                       GL_FALSE,              /* UseCurrentContext */
66                       GL_FALSE,              /* GLDebugSwitch */
67                       GL_FALSE,              /* XSyncSwitch */
68                       GLUT_KEY_REPEAT_ON,    /* KeyRepeat */
69                       INVALID_MODIFIERS,     /* Modifiers */
70                       0,                     /* FPSInterval */
71                       0,                     /* SwapCount */
72                       0,                     /* SwapTime */
73                       0,                     /* Time */
74                       { NULL, NULL },         /* Timers */
75                       { NULL, NULL },         /* FreeTimers */
76                       NULL,                   /* IdleCallback */
77                       0,                      /* ActiveMenus */
78                       NULL,                   /* MenuStateCallback */
79                       NULL,                   /* MenuStatusCallback */
80                       { 640, 480, GL_TRUE },  /* GameModeSize */
81                       16,                     /* GameModeDepth */
82                       72,                     /* GameModeRefresh */
83                       GLUT_ACTION_EXIT,       /* ActionOnWindowClose */
84                       GLUT_EXEC_STATE_INIT,   /* ExecState */
85                       NULL,                   /* ProgramName */
86                       GL_FALSE,               /* JoysticksInitialised */
87                       0,                      /* NumActiveJoysticks */
88                       GL_FALSE,               /* InputDevsInitialised */
89                       1,                      /* AuxiliaryBufferNumber */
90                       4,                      /* SampleNumber */
91                       1,                      /* MajorVersion */
92                       0,                      /* MinorVersion */
93                       0,                      /* ContextFlags */
94                       0,                      /* ContextProfile */
95                       NULL,                   /* ErrorFunc */
96                       NULL                    /* WarningFunc */
97 };
98
99
100 /* -- PRIVATE FUNCTIONS ---------------------------------------------------- */
101
102 #if TARGET_HOST_POSIX_X11
103
104 /* Return the atom associated with "name". */
105 static Atom fghGetAtom(const char * name)
106 {
107   return XInternAtom(fgDisplay.Display, name, False);
108 }
109
110 /*
111  * Check if "property" is set on "window".  The property's values are returned
112  * through "data".  If the property is set and is of type "type", return the
113  * number of elements in "data".  Return zero otherwise.  In both cases, use
114  * "Xfree()" to free "data".
115  */
116 static int fghGetWindowProperty(Window window,
117                                 Atom property,
118                                 Atom type,
119                                 unsigned char ** data)
120 {
121   /*
122    * Caller always has to use "Xfree()" to free "data", since
123    * "XGetWindowProperty() always allocates one extra byte in prop_return
124    * [i.e. "data"] (even if the property is zero length) [..]".
125    */
126
127   int status;  /*  Returned by "XGetWindowProperty". */
128
129   Atom          type_returned;
130   int           temp_format;             /*  Not used. */
131   unsigned long number_of_elements;
132   unsigned long temp_bytes_after;        /*  Not used. */
133
134
135   status = XGetWindowProperty(fgDisplay.Display,
136                               window,
137                               property,
138                               0,
139                               LONG_MAX,
140                               False,
141                               type,
142                               &type_returned,
143                               &temp_format,
144                               &number_of_elements,
145                               &temp_bytes_after,
146                               data);
147
148   FREEGLUT_INTERNAL_ERROR_EXIT(status == Success,
149                                "XGetWindowProperty failled",
150                                "fghGetWindowProperty");
151
152   if (type_returned != type)
153     {
154       number_of_elements = 0;
155     }
156
157   return number_of_elements;
158 }
159
160 /*  Check if the window manager is NET WM compliant. */
161 static int fghNetWMSupported(void)
162 {
163   Atom wm_check;
164   Window ** window_ptr_1;
165
166   int number_of_windows;
167   int net_wm_supported;
168
169
170   net_wm_supported = 0;
171
172   wm_check = fghGetAtom("_NET_SUPPORTING_WM_CHECK");
173   window_ptr_1 = malloc(sizeof(Window *));
174
175   /*
176    * Check that the window manager has set this property on the root window.
177    * The property must be the ID of a child window.
178    */
179   number_of_windows = fghGetWindowProperty(fgDisplay.RootWindow,
180                                            wm_check,
181                                            XA_WINDOW,
182                                            (unsigned char **) window_ptr_1);
183   if (number_of_windows == 1)
184     {
185       Window ** window_ptr_2;
186
187       window_ptr_2 = malloc(sizeof(Window *));
188
189       /* Check that the window has the same property set to the same value. */
190       number_of_windows = fghGetWindowProperty(**window_ptr_1,
191                                                wm_check,
192                                                XA_WINDOW,
193                                                (unsigned char **) window_ptr_2);
194       if ((number_of_windows == 1) && (**window_ptr_1 == **window_ptr_2))
195       {
196         /* NET WM compliant */
197         net_wm_supported = 1;
198       }
199
200       XFree(*window_ptr_2);
201       free(window_ptr_2);
202     }
203
204         XFree(*window_ptr_1);
205         free(window_ptr_1);
206
207         return net_wm_supported;
208 }
209
210 /*  Check if "hint" is present in "property" for "window". */
211 int fgHintPresent(Window window, Atom property, Atom hint)
212 {
213   Atom ** atoms_ptr;
214   int number_of_atoms;
215   int supported;
216   int i;
217
218   supported = 0;
219
220   atoms_ptr = malloc(sizeof(Atom *));
221   number_of_atoms = fghGetWindowProperty(window,
222                                          property,
223                                          XA_ATOM,
224                                          (unsigned char **) atoms_ptr);
225   for (i = 0; i < number_of_atoms; i++)
226     {
227       if ((*atoms_ptr)[i] == hint)
228       {
229           supported = 1;
230           break;
231       }
232     }
233
234   return supported;
235 }
236
237 #endif /*  TARGET_HOST_POSIX_X11  */
238
239
240 /*
241  * A call to this function should initialize all the display stuff...
242  */
243 static void fghInitialize( const char* displayName )
244 {
245 #if TARGET_HOST_POSIX_X11
246     fgDisplay.Display = XOpenDisplay( displayName );
247
248     if( fgDisplay.Display == NULL )
249         fgError( "failed to open display '%s'", XDisplayName( displayName ) );
250
251     if( !glXQueryExtension( fgDisplay.Display, NULL, NULL ) )
252         fgError( "OpenGL GLX extension not supported by display '%s'",
253             XDisplayName( displayName ) );
254
255     fgDisplay.Screen = DefaultScreen( fgDisplay.Display );
256     fgDisplay.RootWindow = RootWindow(
257         fgDisplay.Display,
258         fgDisplay.Screen
259     );
260
261     fgDisplay.ScreenWidth  = DisplayWidth(
262         fgDisplay.Display,
263         fgDisplay.Screen
264     );
265     fgDisplay.ScreenHeight = DisplayHeight(
266         fgDisplay.Display,
267         fgDisplay.Screen
268     );
269
270     fgDisplay.ScreenWidthMM = DisplayWidthMM(
271         fgDisplay.Display,
272         fgDisplay.Screen
273     );
274     fgDisplay.ScreenHeightMM = DisplayHeightMM(
275         fgDisplay.Display,
276         fgDisplay.Screen
277     );
278
279     fgDisplay.Connection = ConnectionNumber( fgDisplay.Display );
280
281     /* Create the window deletion atom */
282     fgDisplay.DeleteWindow = fghGetAtom("WM_DELETE_WINDOW");
283
284     /* Create the state and full screen atoms */
285     fgDisplay.State           = None;
286     fgDisplay.StateFullScreen = None;
287
288     if (fghNetWMSupported())
289     {
290       const Atom supported = fghGetAtom("_NET_SUPPORTED");
291       const Atom state     = fghGetAtom("_NET_WM_STATE");
292       
293       /* Check if the state hint is supported. */
294       if (fgHintPresent(fgDisplay.RootWindow, supported, state))
295       {
296         const Atom full_screen = fghGetAtom("_NET_WM_STATE_FULLSCREEN");
297         
298         fgDisplay.State = state;
299         
300         /* Check if the window manager supports full screen. */
301         /**  Check "_NET_WM_ALLOWED_ACTIONS" on our window instead? **/
302         if (fgHintPresent(fgDisplay.RootWindow, supported, full_screen))
303         {
304           fgDisplay.StateFullScreen = full_screen;
305         }
306       }
307     }
308
309 #elif TARGET_HOST_MS_WINDOWS
310
311     WNDCLASS wc;
312     ATOM atom;
313
314     /* What we need to do is to initialize the fgDisplay global structure here. */
315     fgDisplay.Instance = GetModuleHandle( NULL );
316     fgDisplay.DisplayName=strdup(displayName);
317     atom = GetClassInfo( fgDisplay.Instance, _T("FREEGLUT"), &wc );
318
319     if( atom == 0 )
320     {
321         ZeroMemory( &wc, sizeof(WNDCLASS) );
322
323         /*
324          * Each of the windows should have its own device context, and we
325          * want redraw events during Vertical and Horizontal Resizes by
326          * the user.
327          *
328          * XXX Old code had "| CS_DBCLCKS" commented out.  Plans for the
329          * XXX future?  Dead-end idea?
330          */
331         wc.lpfnWndProc    = fgWindowProc;
332         wc.cbClsExtra     = 0;
333         wc.cbWndExtra     = 0;
334         wc.hInstance      = fgDisplay.Instance;
335         wc.hIcon          = LoadIcon( fgDisplay.Instance, _T("GLUT_ICON") );
336
337 #if defined(_WIN32_WCE)
338         wc.style          = CS_HREDRAW | CS_VREDRAW;
339 #else
340         wc.style          = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
341         if (!wc.hIcon)
342           wc.hIcon        = LoadIcon( NULL, IDI_WINLOGO );
343 #endif
344
345         wc.hCursor        = LoadCursor( NULL, IDC_ARROW );
346         wc.hbrBackground  = NULL;
347         wc.lpszMenuName   = NULL;
348         wc.lpszClassName  = _T("FREEGLUT");
349
350         /* Register the window class */
351         atom = RegisterClass( &wc );
352         FREEGLUT_INTERNAL_ERROR_EXIT ( atom, "Window Class Not Registered", "fghInitialize" );
353     }
354
355     /* The screen dimensions can be obtained via GetSystemMetrics() calls */
356     fgDisplay.ScreenWidth  = GetSystemMetrics( SM_CXSCREEN );
357     fgDisplay.ScreenHeight = GetSystemMetrics( SM_CYSCREEN );
358
359     {
360         HWND desktop = GetDesktopWindow( );
361         HDC  context = GetDC( desktop );
362
363         fgDisplay.ScreenWidthMM  = GetDeviceCaps( context, HORZSIZE );
364         fgDisplay.ScreenHeightMM = GetDeviceCaps( context, VERTSIZE );
365
366         ReleaseDC( desktop, context );
367     }
368     /* If we have a DisplayName try to use it for metrics */
369     if( fgDisplay.DisplayName )
370     {
371         HDC context = CreateDC(fgDisplay.DisplayName,0,0,0);
372         if( context )
373         {
374             fgDisplay.ScreenWidth  = GetDeviceCaps( context, HORZRES );
375             fgDisplay.ScreenHeight = GetDeviceCaps( context, VERTRES );
376             fgDisplay.ScreenWidthMM  = GetDeviceCaps( context, HORZSIZE );
377             fgDisplay.ScreenHeightMM = GetDeviceCaps( context, VERTSIZE );
378             DeleteDC(context);
379         }
380         else
381             fgWarning("fghInitialize: "
382                       "CreateDC failed, Screen size info may be incorrect\n"
383           "This is quite likely caused by a bad '-display' parameter");
384       
385     }
386     /* Set the timer granularity to 1 ms */
387     timeBeginPeriod ( 1 );
388
389 #endif
390
391     fgState.Initialised = GL_TRUE;
392     atexit(fgDeinitialize);
393
394     /* InputDevice uses GlutTimerFunc(), so fgState.Initialised must be TRUE */
395     fgInitialiseInputDevices();
396 }
397
398 /*
399  * Perform the freeglut deinitialization...
400  */
401 void fgDeinitialize( void )
402 {
403     SFG_Timer *timer;
404
405     if( !fgState.Initialised )
406     {
407         return;
408     }
409
410     /* If there was a menu created, destroy the rendering context */
411     if( fgStructure.MenuContext )
412     {
413 #if TARGET_HOST_POSIX_X11
414         /* Note that the MVisualInfo is not owned by the MenuContext! */
415         glXDestroyContext( fgDisplay.Display, fgStructure.MenuContext->MContext );
416 #endif
417         free( fgStructure.MenuContext );
418         fgStructure.MenuContext = NULL;
419     }
420
421     fgDestroyStructure( );
422
423     while( ( timer = fgState.Timers.First) )
424     {
425         fgListRemove( &fgState.Timers, &timer->Node );
426         free( timer );
427     }
428
429     while( ( timer = fgState.FreeTimers.First) )
430     {
431         fgListRemove( &fgState.FreeTimers, &timer->Node );
432         free( timer );
433     }
434
435 #if !defined(_WIN32_WCE)
436     if ( fgState.JoysticksInitialised )
437         fgJoystickClose( );
438
439     if ( fgState.InputDevsInitialised )
440         fgInputDeviceClose( );
441 #endif /* !defined(_WIN32_WCE) */
442     fgState.JoysticksInitialised = GL_FALSE;
443     fgState.InputDevsInitialised = GL_FALSE;
444
445     fgState.MajorVersion = 1;
446     fgState.MinorVersion = 0;
447     fgState.ContextFlags = 0;
448     fgState.ContextProfile = 0;
449
450     fgState.Initialised = GL_FALSE;
451
452     fgState.Position.X = -1;
453     fgState.Position.Y = -1;
454     fgState.Position.Use = GL_FALSE;
455
456     fgState.Size.X = 300;
457     fgState.Size.Y = 300;
458     fgState.Size.Use = GL_TRUE;
459
460     fgState.DisplayMode = GLUT_RGBA | GLUT_SINGLE | GLUT_DEPTH;
461
462     fgState.DirectContext  = GLUT_TRY_DIRECT_CONTEXT;
463     fgState.ForceIconic         = GL_FALSE;
464     fgState.UseCurrentContext   = GL_FALSE;
465     fgState.GLDebugSwitch       = GL_FALSE;
466     fgState.XSyncSwitch         = GL_FALSE;
467     fgState.ActionOnWindowClose = GLUT_ACTION_EXIT;
468     fgState.ExecState           = GLUT_EXEC_STATE_INIT;
469
470     fgState.KeyRepeat       = GLUT_KEY_REPEAT_ON;
471     fgState.Modifiers       = INVALID_MODIFIERS;
472
473     fgState.GameModeSize.X  = 640;
474     fgState.GameModeSize.Y  = 480;
475     fgState.GameModeDepth   =  16;
476     fgState.GameModeRefresh =  72;
477
478     fgListInit( &fgState.Timers );
479     fgListInit( &fgState.FreeTimers );
480
481     fgState.IdleCallback = NULL;
482     fgState.MenuStateCallback = ( FGCBMenuState )NULL;
483     fgState.MenuStatusCallback = ( FGCBMenuStatus )NULL;
484
485     fgState.SwapCount   = 0;
486     fgState.SwapTime    = 0;
487     fgState.FPSInterval = 0;
488
489     if( fgState.ProgramName )
490     {
491         free( fgState.ProgramName );
492         fgState.ProgramName = NULL;
493     }
494
495 #if TARGET_HOST_POSIX_X11
496
497     /*
498      * Make sure all X-client data we have created will be destroyed on
499      * display closing
500      */
501     XSetCloseDownMode( fgDisplay.Display, DestroyAll );
502
503     /*
504      * Close the display connection, destroying all windows we have
505      * created so far
506      */
507     XCloseDisplay( fgDisplay.Display );
508
509 #elif TARGET_HOST_MS_WINDOWS
510     if( fgDisplay.DisplayName )
511     {
512         free( fgDisplay.DisplayName );
513         fgDisplay.DisplayName = NULL;
514     }
515
516     /* Reset the timer granularity */
517     timeEndPeriod ( 1 );
518
519 #endif
520
521     fgState.Initialised = GL_FALSE;
522 }
523
524 /*
525  * Everything inside the following #ifndef is copied from the X sources.
526  */
527
528 #if TARGET_HOST_MS_WINDOWS
529
530 /*
531
532 Copyright 1985, 1986, 1987,1998  The Open Group
533
534 Permission to use, copy, modify, distribute, and sell this software and its
535 documentation for any purpose is hereby granted without fee, provided that
536 the above copyright notice appear in all copies and that both that
537 copyright notice and this permission notice appear in supporting
538 documentation.
539
540 The above copyright notice and this permission notice shall be included
541 in all copies or substantial portions of the Software.
542
543 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
544 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
545 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
546 IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
547 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
548 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
549 OTHER DEALINGS IN THE SOFTWARE.
550
551 Except as contained in this notice, the name of The Open Group shall
552 not be used in advertising or otherwise to promote the sale, use or
553 other dealings in this Software without prior written authorization
554 from The Open Group.
555
556 */
557
558 #define NoValue         0x0000
559 #define XValue          0x0001
560 #define YValue          0x0002
561 #define WidthValue      0x0004
562 #define HeightValue     0x0008
563 #define AllValues       0x000F
564 #define XNegative       0x0010
565 #define YNegative       0x0020
566
567 /*
568  *    XParseGeometry parses strings of the form
569  *   "=<width>x<height>{+-}<xoffset>{+-}<yoffset>", where
570  *   width, height, xoffset, and yoffset are unsigned integers.
571  *   Example:  "=80x24+300-49"
572  *   The equal sign is optional.
573  *   It returns a bitmask that indicates which of the four values
574  *   were actually found in the string.  For each value found,
575  *   the corresponding argument is updated;  for each value
576  *   not found, the corresponding argument is left unchanged.
577  */
578
579 static int
580 ReadInteger(char *string, char **NextString)
581 {
582     register int Result = 0;
583     int Sign = 1;
584
585     if (*string == '+')
586         string++;
587     else if (*string == '-')
588     {
589         string++;
590         Sign = -1;
591     }
592     for (; (*string >= '0') && (*string <= '9'); string++)
593     {
594         Result = (Result * 10) + (*string - '0');
595     }
596     *NextString = string;
597     if (Sign >= 0)
598         return Result;
599     else
600         return -Result;
601 }
602
603 static int XParseGeometry (
604     const char *string,
605     int *x,
606     int *y,
607     unsigned int *width,    /* RETURN */
608     unsigned int *height)    /* RETURN */
609 {
610     int mask = NoValue;
611     register char *strind;
612     unsigned int tempWidth = 0, tempHeight = 0;
613     int tempX = 0, tempY = 0;
614     char *nextCharacter;
615
616     if ( (string == NULL) || (*string == '\0'))
617       return mask;
618     if (*string == '=')
619         string++;  /* ignore possible '=' at beg of geometry spec */
620
621     strind = (char *)string;
622     if (*strind != '+' && *strind != '-' && *strind != 'x') {
623         tempWidth = ReadInteger(strind, &nextCharacter);
624         if (strind == nextCharacter)
625             return 0;
626         strind = nextCharacter;
627         mask |= WidthValue;
628     }
629
630     if (*strind == 'x' || *strind == 'X') {
631         strind++;
632         tempHeight = ReadInteger(strind, &nextCharacter);
633         if (strind == nextCharacter)
634             return 0;
635         strind = nextCharacter;
636         mask |= HeightValue;
637     }
638
639     if ((*strind == '+') || (*strind == '-')) {
640         if (*strind == '-') {
641             strind++;
642             tempX = -ReadInteger(strind, &nextCharacter);
643             if (strind == nextCharacter)
644                 return 0;
645             strind = nextCharacter;
646             mask |= XNegative;
647         }
648         else
649         {
650             strind++;
651             tempX = ReadInteger(strind, &nextCharacter);
652             if (strind == nextCharacter)
653                 return 0;
654             strind = nextCharacter;
655         }
656         mask |= XValue;
657         if ((*strind == '+') || (*strind == '-')) {
658             if (*strind == '-') {
659                 strind++;
660                 tempY = -ReadInteger(strind, &nextCharacter);
661                 if (strind == nextCharacter)
662                     return 0;
663                 strind = nextCharacter;
664                 mask |= YNegative;
665             }
666             else
667             {
668                 strind++;
669                 tempY = ReadInteger(strind, &nextCharacter);
670                 if (strind == nextCharacter)
671                     return 0;
672                 strind = nextCharacter;
673             }
674             mask |= YValue;
675         }
676     }
677
678     /* If strind isn't at the end of the string the it's an invalid
679        geometry specification. */
680
681     if (*strind != '\0') return 0;
682
683     if (mask & XValue)
684         *x = tempX;
685     if (mask & YValue)
686         *y = tempY;
687     if (mask & WidthValue)
688         *width = tempWidth;
689     if (mask & HeightValue)
690         *height = tempHeight;
691     return mask;
692 }
693 #endif
694
695 /* -- INTERFACE FUNCTIONS -------------------------------------------------- */
696
697 /*
698  * Perform initialization. This usually happens on the program startup
699  * and restarting after glutMainLoop termination...
700  */
701 void FGAPIENTRY glutInit( int* pargc, char** argv )
702 {
703     char* displayName = NULL;
704     char* geometry = NULL;
705     int i, j, argc = *pargc;
706
707     if( fgState.Initialised )
708         fgError( "illegal glutInit() reinitialization attempt" );
709
710     if (pargc && *pargc && argv && *argv && **argv)
711     {
712         fgState.ProgramName = strdup (*argv);
713
714         if( !fgState.ProgramName )
715             fgError ("Could not allocate space for the program's name.");
716     }
717
718     fgCreateStructure( );
719
720     /* Get start time */
721     fgState.Time = fgSystemTime();
722
723     /* check if GLUT_FPS env var is set */
724 #ifndef _WIN32_WCE
725     {
726         const char *fps = getenv( "GLUT_FPS" );
727
728         if( fps )
729         {
730             int interval;
731             sscanf( fps, "%d", &interval );
732
733             if( interval <= 0 )
734                 fgState.FPSInterval = 5000;  /* 5000 millisecond default */
735             else
736                 fgState.FPSInterval = interval;
737         }
738     }
739
740     displayName = getenv( "DISPLAY" );
741
742     for( i = 1; i < argc; i++ )
743     {
744         if( strcmp( argv[ i ], "-display" ) == 0 )
745         {
746             if( ++i >= argc )
747                 fgError( "-display parameter must be followed by display name" );
748
749             displayName = argv[ i ];
750
751             argv[ i - 1 ] = NULL;
752             argv[ i     ] = NULL;
753             ( *pargc ) -= 2;
754         }
755         else if( strcmp( argv[ i ], "-geometry" ) == 0 )
756         {
757             if( ++i >= argc )
758                 fgError( "-geometry parameter must be followed by window "
759                          "geometry settings" );
760
761             geometry = argv[ i ];
762
763             argv[ i - 1 ] = NULL;
764             argv[ i     ] = NULL;
765             ( *pargc ) -= 2;
766         }
767         else if( strcmp( argv[ i ], "-direct" ) == 0)
768         {
769             if( fgState.DirectContext == GLUT_FORCE_INDIRECT_CONTEXT )
770                 fgError( "parameters ambiguity, -direct and -indirect "
771                     "cannot be both specified" );
772
773             fgState.DirectContext = GLUT_FORCE_DIRECT_CONTEXT;
774             argv[ i ] = NULL;
775             ( *pargc )--;
776         }
777         else if( strcmp( argv[ i ], "-indirect" ) == 0 )
778         {
779             if( fgState.DirectContext == GLUT_FORCE_DIRECT_CONTEXT )
780                 fgError( "parameters ambiguity, -direct and -indirect "
781                     "cannot be both specified" );
782
783             fgState.DirectContext = GLUT_FORCE_INDIRECT_CONTEXT;
784             argv[ i ] = NULL;
785             (*pargc)--;
786         }
787         else if( strcmp( argv[ i ], "-iconic" ) == 0 )
788         {
789             fgState.ForceIconic = GL_TRUE;
790             argv[ i ] = NULL;
791             ( *pargc )--;
792         }
793         else if( strcmp( argv[ i ], "-gldebug" ) == 0 )
794         {
795             fgState.GLDebugSwitch = GL_TRUE;
796             argv[ i ] = NULL;
797             ( *pargc )--;
798         }
799         else if( strcmp( argv[ i ], "-sync" ) == 0 )
800         {
801             fgState.XSyncSwitch = GL_TRUE;
802             argv[ i ] = NULL;
803             ( *pargc )--;
804         }
805     }
806
807     /* Compact {argv}. */
808     for( i = j = 1; i < *pargc; i++, j++ )
809     {
810         /* Guaranteed to end because there are "*pargc" arguments left */
811         while ( argv[ j ] == NULL )
812             j++;
813         if ( i != j )
814             argv[ i ] = argv[ j ];
815     }
816
817 #endif /* _WIN32_WCE */
818
819     /*
820      * Have the display created now. If there wasn't a "-display"
821      * in the program arguments, we will use the DISPLAY environment
822      * variable for opening the X display (see code above):
823      */
824     fghInitialize( displayName );
825
826     /*
827      * Geometry parsing deffered until here because we may need the screen
828      * size.
829      */
830
831     if (geometry )
832     {
833         unsigned int parsedWidth, parsedHeight;
834         int mask = XParseGeometry( geometry,
835                                    &fgState.Position.X, &fgState.Position.Y,
836                                    &parsedWidth, &parsedHeight );
837         /* TODO: Check for overflow? */
838         fgState.Size.X = parsedWidth;
839         fgState.Size.Y = parsedHeight;
840
841         if( (mask & (WidthValue|HeightValue)) == (WidthValue|HeightValue) )
842             fgState.Size.Use = GL_TRUE;
843
844         if( mask & XNegative )
845             fgState.Position.X += fgDisplay.ScreenWidth - fgState.Size.X;
846
847         if( mask & YNegative )
848             fgState.Position.Y += fgDisplay.ScreenHeight - fgState.Size.Y;
849
850         if( (mask & (XValue|YValue)) == (XValue|YValue) )
851             fgState.Position.Use = GL_TRUE;
852     }
853 }
854
855 #if TARGET_HOST_MS_WINDOWS
856 void (__cdecl *__glutExitFunc)( int return_value ) = NULL;
857
858 void FGAPIENTRY __glutInitWithExit( int *pargc, char **argv, void (__cdecl *exit_function)(int) )
859 {
860   __glutExitFunc = exit_function;
861   glutInit(pargc, argv);
862 }
863 #endif
864
865 /*
866  * Undoes all the "glutInit" stuff
867  */
868 void FGAPIENTRY glutExit ( void )
869 {
870   fgDeinitialize ();
871 }
872
873 /*
874  * Sets the default initial window position for new windows
875  */
876 void FGAPIENTRY glutInitWindowPosition( int x, int y )
877 {
878     fgState.Position.X = x;
879     fgState.Position.Y = y;
880
881     if( ( x >= 0 ) && ( y >= 0 ) )
882         fgState.Position.Use = GL_TRUE;
883     else
884         fgState.Position.Use = GL_FALSE;
885 }
886
887 /*
888  * Sets the default initial window size for new windows
889  */
890 void FGAPIENTRY glutInitWindowSize( int width, int height )
891 {
892     fgState.Size.X = width;
893     fgState.Size.Y = height;
894
895     if( ( width > 0 ) && ( height > 0 ) )
896         fgState.Size.Use = GL_TRUE;
897     else
898         fgState.Size.Use = GL_FALSE;
899 }
900
901 /*
902  * Sets the default display mode for all new windows
903  */
904 void FGAPIENTRY glutInitDisplayMode( unsigned int displayMode )
905 {
906     /* We will make use of this value when creating a new OpenGL context... */
907     fgState.DisplayMode = displayMode;
908 }
909
910
911 /* -- INIT DISPLAY STRING PARSING ------------------------------------------ */
912
913 static char* Tokens[] =
914 {
915     "alpha", "acca", "acc", "blue", "buffer", "conformant", "depth", "double",
916     "green", "index", "num", "red", "rgba", "rgb", "luminance", "stencil",
917     "single", "stereo", "samples", "slow", "win32pdf", "win32pfd", "xvisual",
918     "xstaticgray", "xgrayscale", "xstaticcolor", "xpseudocolor",
919     "xtruecolor", "xdirectcolor",
920     "xstaticgrey", "xgreyscale", "xstaticcolour", "xpseudocolour",
921     "xtruecolour", "xdirectcolour", "borderless", "aux"
922 };
923 #define NUM_TOKENS             (sizeof(Tokens) / sizeof(*Tokens))
924
925 void FGAPIENTRY glutInitDisplayString( const char* displayMode )
926 {
927     int glut_state_flag = 0 ;
928     /*
929      * Unpack a lot of options from a character string.  The options are
930      * delimited by blanks or tabs.
931      */
932     char *token ;
933     size_t len = strlen ( displayMode );
934     char *buffer = (char *)malloc ( (len+1) * sizeof(char) );
935     memcpy ( buffer, displayMode, len );
936     buffer[len] = '\0';
937
938     token = strtok ( buffer, " \t" );
939
940     while ( token )
941     {
942         /* Process this token */
943         int i ;
944
945         /* Temporary fix:  Ignore any length specifications and at least
946          * process the basic token
947          * TODO:  Fix this permanently
948          */
949         size_t cleanlength = strcspn ( token, "=<>~!" );
950
951         for ( i = 0; i < NUM_TOKENS; i++ )
952         {
953             if ( strncmp ( token, Tokens[i], cleanlength ) == 0 ) break ;
954         }
955
956         switch ( i )
957         {
958         case 0 :  /* "alpha":  Alpha color buffer precision in bits */
959             glut_state_flag |= GLUT_ALPHA ;  /* Somebody fix this for me! */
960             break ;
961
962         case 1 :  /* "acca":  Red, green, blue, and alpha accumulation buffer
963                      precision in bits */
964             break ;
965
966         case 2 :  /* "acc":  Red, green, and blue accumulation buffer precision
967                      in bits with zero bits alpha */
968             glut_state_flag |= GLUT_ACCUM ;  /* Somebody fix this for me! */
969             break ;
970
971         case 3 :  /* "blue":  Blue color buffer precision in bits */
972             break ;
973
974         case 4 :  /* "buffer":  Number of bits in the color index color buffer
975                    */
976             break ;
977
978         case 5 :  /* "conformant":  Boolean indicating if the frame buffer
979                      configuration is conformant or not */
980             break ;
981
982         case 6 : /* "depth":  Number of bits of precsion in the depth buffer */
983             glut_state_flag |= GLUT_DEPTH ;  /* Somebody fix this for me! */
984             break ;
985
986         case 7 :  /* "double":  Boolean indicating if the color buffer is
987                      double buffered */
988             glut_state_flag |= GLUT_DOUBLE ;
989             break ;
990
991         case 8 :  /* "green":  Green color buffer precision in bits */
992             break ;
993
994         case 9 :  /* "index":  Boolean if the color model is color index or not
995                    */
996             glut_state_flag |= GLUT_INDEX ;
997             break ;
998
999         case 10 :  /* "num":  A special capability  name indicating where the
1000                       value represents the Nth frame buffer configuration
1001                       matching the description string */
1002             break ;
1003
1004         case 11 :  /* "red":  Red color buffer precision in bits */
1005             break ;
1006
1007         case 12 :  /* "rgba":  Number of bits of red, green, blue, and alpha in
1008                       the RGBA color buffer */
1009             glut_state_flag |= GLUT_RGBA ;  /* Somebody fix this for me! */
1010             break ;
1011
1012         case 13 :  /* "rgb":  Number of bits of red, green, and blue in the
1013                       RGBA color buffer with zero bits alpha */
1014             glut_state_flag |= GLUT_RGB ;  /* Somebody fix this for me! */
1015             break ;
1016
1017         case 14 :  /* "luminance":  Number of bits of red in the RGBA and zero
1018                       bits of green, blue (alpha not specified) of color buffer
1019                       precision */
1020             glut_state_flag |= GLUT_LUMINANCE ; /* Somebody fix this for me! */
1021             break ;
1022
1023         case 15 :  /* "stencil":  Number of bits in the stencil buffer */
1024             glut_state_flag |= GLUT_STENCIL;  /* Somebody fix this for me! */
1025             break ;
1026
1027         case 16 :  /* "single":  Boolean indicate the color buffer is single
1028                       buffered */
1029             glut_state_flag |= GLUT_SINGLE ;
1030             break ;
1031
1032         case 17 :  /* "stereo":  Boolean indicating the color buffer supports
1033                       OpenGL-style stereo */
1034             glut_state_flag |= GLUT_STEREO ;
1035             break ;
1036
1037         case 18 :  /* "samples":  Indicates the number of multisamples to use
1038                       based on GLX's SGIS_multisample extension (for
1039                       antialiasing) */
1040             glut_state_flag |= GLUT_MULTISAMPLE ; /*Somebody fix this for me!*/
1041             break ;
1042
1043         case 19 :  /* "slow":  Boolean indicating if the frame buffer
1044                       configuration is slow or not */
1045             break ;
1046
1047         case 20 :  /* "win32pdf": (incorrect spelling but was there before */
1048         case 21 :  /* "win32pfd":  matches the Win32 Pixel Format Descriptor by
1049                       number */
1050 #if TARGET_HOST_MS_WINDOWS
1051 #endif
1052             break ;
1053
1054         case 22 :  /* "xvisual":  matches the X visual ID by number */
1055 #if TARGET_HOST_POSIX_X11
1056 #endif
1057             break ;
1058
1059         case 23 :  /* "xstaticgray": */
1060         case 29 :  /* "xstaticgrey":  boolean indicating if the frame buffer
1061                       configuration's X visual is of type StaticGray */
1062 #if TARGET_HOST_POSIX_X11
1063 #endif
1064             break ;
1065
1066         case 24 :  /* "xgrayscale": */
1067         case 30 :  /* "xgreyscale":  boolean indicating if the frame buffer
1068                       configuration's X visual is of type GrayScale */
1069 #if TARGET_HOST_POSIX_X11
1070 #endif
1071             break ;
1072
1073         case 25 :  /* "xstaticcolor": */
1074         case 31 :  /* "xstaticcolour":  boolean indicating if the frame buffer
1075                       configuration's X visual is of type StaticColor */
1076 #if TARGET_HOST_POSIX_X11
1077 #endif
1078             break ;
1079
1080         case 26 :  /* "xpseudocolor": */
1081         case 32 :  /* "xpseudocolour":  boolean indicating if the frame buffer
1082                       configuration's X visual is of type PseudoColor */
1083 #if TARGET_HOST_POSIX_X11
1084 #endif
1085             break ;
1086
1087         case 27 :  /* "xtruecolor": */
1088         case 33 :  /* "xtruecolour":  boolean indicating if the frame buffer
1089                       configuration's X visual is of type TrueColor */
1090 #if TARGET_HOST_POSIX_X11
1091 #endif
1092             break ;
1093
1094         case 28 :  /* "xdirectcolor": */
1095         case 34 :  /* "xdirectcolour":  boolean indicating if the frame buffer
1096                       configuration's X visual is of type DirectColor */
1097 #if TARGET_HOST_POSIX_X11
1098 #endif
1099             break ;
1100
1101         case 35 :  /* "borderless":  windows should not have borders */
1102 #if TARGET_HOST_POSIX_X11
1103 #endif
1104             break ;
1105
1106         case 36 :  /* "aux":  some number of aux buffers */
1107             glut_state_flag |= GLUT_AUX;
1108             break ;
1109
1110         case 37 :  /* Unrecognized */
1111             fgWarning ( "WARNING - Display string token not recognized:  %s",
1112                         token );
1113             break ;
1114         }
1115
1116         token = strtok ( NULL, " \t" );
1117     }
1118
1119     free ( buffer );
1120
1121     /* We will make use of this value when creating a new OpenGL context... */
1122     fgState.DisplayMode = glut_state_flag;
1123 }
1124
1125 /* -- SETTING OPENGL 3.0 CONTEXT CREATION PARAMETERS ---------------------- */
1126
1127 void FGAPIENTRY glutInitContextVersion( int majorVersion, int minorVersion )
1128 {
1129     /* We will make use of these valuse when creating a new OpenGL context... */
1130     fgState.MajorVersion = majorVersion;
1131     fgState.MinorVersion = minorVersion;
1132 }
1133
1134
1135 void FGAPIENTRY glutInitContextFlags( int flags )
1136 {
1137     /* We will make use of this value when creating a new OpenGL context... */
1138     fgState.ContextFlags = flags;
1139 }
1140
1141 void FGAPIENTRY glutInitContextProfile( int profile )
1142 {
1143     /* We will make use of this value when creating a new OpenGL context... */
1144     fgState.ContextProfile = profile;
1145 }
1146
1147 /* -------------- User Defined Error/Warning Handler Support -------------- */
1148
1149 /*
1150  * Sets the user error handler (note the use of va_list for the args to the fmt)
1151  */
1152 void FGAPIENTRY glutInitErrorFunc( void (* vfgError) ( const char *fmt, va_list ap ) )
1153 {
1154     /* This allows user programs to handle freeglut errors */
1155     fgState.ErrorFunc = vfgError;
1156 }
1157
1158 /*
1159  * Sets the user warning handler (note the use of va_list for the args to the fmt)
1160  */
1161 void FGAPIENTRY glutInitWarningFunc( void (* vfgWarning) ( const char *fmt, va_list ap ) )
1162 {
1163     /* This allows user programs to handle freeglut warnings */
1164     fgState.WarningFunc = vfgWarning;
1165 }
1166
1167 /*** END OF FILE ***/