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