4792ad83c841445f81b804fe67c3d18fb508e23b
[freeglut] / src / fg_internal.h
1 /*
2  * fg_internal.h
3  *
4  * The freeglut library private include file.
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 #ifndef  FREEGLUT_INTERNAL_H
29 #define  FREEGLUT_INTERNAL_H
30
31 #ifdef HAVE_CONFIG_H
32 #    include "config.h"
33 #endif
34
35 /* Freeglut is intended to function under all Unix/X11 and Win32 platforms. */
36 /* XXX: Don't all MS-Windows compilers (except Cygwin) have _WIN32 defined?
37  * XXX: If so, remove the first set of defined()'s below.
38  */
39 #if !defined(TARGET_HOST_POSIX_X11) && !defined(TARGET_HOST_MS_WINDOWS) && !defined(TARGET_HOST_MAC_OSX) && !defined(TARGET_HOST_SOLARIS)
40 #if defined(_MSC_VER) || defined(__WATCOMC__) || defined(__MINGW32__) \
41     || defined(_WIN32) || defined(_WIN32_WCE) \
42     || ( defined(__CYGWIN__) && defined(X_DISPLAY_MISSING) )
43 #   define  TARGET_HOST_MS_WINDOWS 1
44
45 #elif defined (__ANDROID__)
46 #   define  TARGET_HOST_ANDROID  1
47
48 #elif defined (__QNX__)
49 #   define  TARGET_HOST_BLACKBERRY  1
50
51 #elif defined(__posix__) || defined(__unix__) || defined(__linux__) || defined(__sun)
52 #   define  TARGET_HOST_POSIX_X11  1
53
54 #elif defined(__APPLE__)
55 /* This is a placeholder until we get native OSX support ironed out -- JFF 11/18/09 */
56 #   define  TARGET_HOST_POSIX_X11  1
57 /* #   define  TARGET_HOST_MAC_OSX    1 */
58
59 #else
60 #   error "Unrecognized target host!"
61
62 #endif
63 #endif
64
65 /* Detect both SunPro and gcc compilers on Sun Solaris */
66 #if defined (__SVR4) && defined (__sun)
67 #   define TARGET_HOST_SOLARIS 1
68 #endif
69
70 #ifndef TARGET_HOST_MS_WINDOWS
71 #   define  TARGET_HOST_MS_WINDOWS 0
72 #endif
73
74 #ifndef  TARGET_HOST_POSIX_X11
75 #   define  TARGET_HOST_POSIX_X11  0
76 #endif
77
78 #ifndef  TARGET_HOST_MAC_OSX
79 #   define  TARGET_HOST_MAC_OSX    0
80 #endif
81
82 #ifndef  TARGET_HOST_SOLARIS
83 #   define  TARGET_HOST_SOLARIS    0
84 #endif
85
86 /* -- FIXED CONFIGURATION LIMITS ------------------------------------------- */
87
88 #define  FREEGLUT_MAX_MENUS         3
89
90 /* These files should be available on every platform. */
91 #include <stdio.h>
92 #include <string.h>
93 #include <math.h>
94 #include <stdlib.h>
95 #include <stdarg.h>
96
97 /* These are included based on autoconf directives. */
98 #ifdef HAVE_SYS_TYPES_H
99 #    include <sys/types.h>
100 #endif
101 #ifdef HAVE_UNISTD_H
102 #    include <unistd.h>
103 #endif
104 #ifdef TIME_WITH_SYS_TIME
105 #    include <sys/time.h>
106 #    include <time.h>
107 #elif defined(HAVE_SYS_TIME_H)
108 #    include <sys/time.h>
109 #else
110 #    include <time.h>
111 #endif
112
113 /* -- AUTOCONF HACKS --------------------------------------------------------*/
114
115 /* XXX: Update autoconf to avoid these.
116  * XXX: Are non-POSIX platforms intended not to use autoconf?
117  * If so, perhaps there should be a config_guess.h for them. Alternatively,
118  * config guesses could be placed above, just after the config.h exclusion.
119  */
120 #if defined(__FreeBSD__) || defined(__NetBSD__)
121 #    define HAVE_USB_JS 1
122 #    if defined(__NetBSD__) || ( defined(__FreeBSD__) && __FreeBSD_version >= 500000)
123 #        define HAVE_USBHID_H 1
124 #    endif
125 #endif
126
127 #if defined(_MSC_VER) || defined(__WATCOMC__)
128 /* strdup() is non-standard, for all but POSIX-2001 */
129 #define strdup   _strdup
130 #endif
131
132 /* M_PI is non-standard (defined by BSD, not ISO-C) */
133 #ifndef M_PI
134 #    define  M_PI  3.14159265358979323846
135 #endif
136
137 #ifdef HAVE_STDBOOL_H
138 #    include <stdbool.h>
139 #    ifndef TRUE
140 #        define TRUE true
141 #    endif
142 #    ifndef FALSE
143 #        define FALSE false
144 #    endif
145 #else
146 #    ifndef TRUE
147 #        define  TRUE  1
148 #    endif
149 #    ifndef FALSE
150 #        define  FALSE  0
151 #    endif
152 #endif
153
154 /* General defines */
155 #define INVALID_MODIFIERS 0xffffffff
156
157 /* FreeGLUT internal time type */
158 #if defined(HAVE_STDINT_H)
159 #   include <stdint.h>
160     typedef uint64_t fg_time_t;
161 #elif defined(HAVE_INTTYPES_H)
162 #   include <inttypes.h>
163     typedef uint64_t fg_time_t;
164 #elif defined(HAVE_U__INT64)
165     typedef unsigned __int64 fg_time_t;
166 #elif defined(HAVE_ULONG_LONG)
167     typedef unsigned long long fg_time_t;
168 #else
169     typedef unsigned long fg_time_t;
170 #endif
171
172 #ifndef __fg_unused
173 # ifdef __GNUC__
174 #  define __fg_unused __attribute__((unused))
175 # else
176 #  define __fg_unused
177 # endif
178 #endif
179
180 /* Platform-specific includes */
181 #if TARGET_HOST_POSIX_X11
182 #include "x11/fg_internal_x11.h"
183 #endif
184 #if TARGET_HOST_MS_WINDOWS
185 #include "mswin/fg_internal_mswin.h"
186 #endif
187 #if TARGET_HOST_ANDROID
188 #include "android/fg_internal_android.h"
189 #endif
190 #if TARGET_HOST_BLACKBERRY
191 #include "blackberry/fg_internal_blackberry.h"
192 #endif
193
194
195 /* -- GLOBAL TYPE DEFINITIONS ---------------------------------------------- */
196
197 /* Freeglut callbacks type definitions */
198 typedef void (* FGCBDisplay       )( void );
199 typedef void (* FGCBReshape       )( int, int );
200 typedef void (* FGCBPosition      )( int, int );
201 typedef void (* FGCBVisibility    )( int );
202 typedef void (* FGCBKeyboard      )( unsigned char, int, int );
203 typedef void (* FGCBKeyboardUp    )( unsigned char, int, int );
204 typedef void (* FGCBSpecial       )( int, int, int );
205 typedef void (* FGCBSpecialUp     )( int, int, int );
206 typedef void (* FGCBMouse         )( int, int, int, int );
207 typedef void (* FGCBMouseWheel    )( int, int, int, int );
208 typedef void (* FGCBMotion        )( int, int );
209 typedef void (* FGCBPassive       )( int, int );
210 typedef void (* FGCBEntry         )( int );
211 typedef void (* FGCBWindowStatus  )( int );
212 typedef void (* FGCBJoystick      )( unsigned int, int, int, int );
213 typedef void (* FGCBOverlayDisplay)( void );
214 typedef void (* FGCBSpaceMotion   )( int, int, int );
215 typedef void (* FGCBSpaceRotation )( int, int, int );
216 typedef void (* FGCBSpaceButton   )( int, int );
217 typedef void (* FGCBDials         )( int, int );
218 typedef void (* FGCBButtonBox     )( int, int );
219 typedef void (* FGCBTabletMotion  )( int, int );
220 typedef void (* FGCBTabletButton  )( int, int, int, int );
221 typedef void (* FGCBDestroy       )( void );    /* Used for both window and menu destroy callbacks */
222
223 typedef void (* FGCBMultiEntry   )( int, int );
224 typedef void (* FGCBMultiButton  )( int, int, int, int, int );
225 typedef void (* FGCBMultiMotion  )( int, int, int );
226 typedef void (* FGCBMultiPassive )( int, int, int );
227
228 typedef void (* FGCBInitContext)();
229 typedef void (* FGCBAppStatus)(int);
230
231 /* The global callbacks type definitions */
232 typedef void (* FGCBIdle          )( void );
233 typedef void (* FGCBTimer         )( int );
234 typedef void (* FGCBMenuState     )( int );
235 typedef void (* FGCBMenuStatus    )( int, int, int );
236
237 /* The callback used when creating/using menus */
238 typedef void (* FGCBMenu          )( int );
239
240 /* The FreeGLUT error/warning handler type definition */
241 typedef void (* FGError           ) ( const char *fmt, va_list ap);
242 typedef void (* FGWarning         ) ( const char *fmt, va_list ap);
243
244
245 /* A list structure */
246 typedef struct tagSFG_List SFG_List;
247 struct tagSFG_List
248 {
249     void *First;
250     void *Last;
251 };
252
253 /* A list node structure */
254 typedef struct tagSFG_Node SFG_Node;
255 struct tagSFG_Node
256 {
257     void *Next;
258     void *Prev;
259 };
260
261 /* A helper structure holding two ints and a boolean */
262 typedef struct tagSFG_XYUse SFG_XYUse;
263 struct tagSFG_XYUse
264 {
265     GLint           X, Y;               /* The two integers...               */
266     GLboolean       Use;                /* ...and a single boolean.          */
267 };
268
269 /*
270  * An enumeration containing the state of the GLUT execution:
271  * initializing, running, or stopping
272  */
273 typedef enum
274 {
275   GLUT_EXEC_STATE_INIT,
276   GLUT_EXEC_STATE_RUNNING,
277   GLUT_EXEC_STATE_STOP
278 } fgExecutionState ;
279
280 /* This structure holds different freeglut settings */
281 typedef struct tagSFG_State SFG_State;
282 struct tagSFG_State
283 {
284     SFG_XYUse        Position;             /* The default windows' position  */
285     SFG_XYUse        Size;                 /* The default windows' size      */
286     unsigned int     DisplayMode;          /* Display mode for new windows   */
287
288     GLboolean        Initialised;          /* freeglut has been initialised  */
289
290     int              DirectContext;        /* Direct rendering state         */
291
292     GLboolean        ForceIconic;          /* New top windows are iconified  */
293     GLboolean        UseCurrentContext;    /* New windows share with current */
294
295     GLboolean        GLDebugSwitch;        /* OpenGL state debugging switch  */
296     GLboolean        XSyncSwitch;          /* X11 sync protocol switch       */
297
298     int              KeyRepeat;            /* Global key repeat mode.        */
299     int              Modifiers;            /* Current ALT/SHIFT/CTRL state   */
300
301     GLuint           FPSInterval;          /* Interval between FPS printfs   */
302     GLuint           SwapCount;            /* Count of glutSwapBuffer calls  */
303     GLuint           SwapTime;             /* Time of last SwapBuffers       */
304
305     fg_time_t        Time;                 /* Time that glutInit was called  */
306     SFG_List         Timers;               /* The freeglut timer hooks       */
307     SFG_List         FreeTimers;           /* The unused timer hooks         */
308
309     FGCBIdle         IdleCallback;         /* The global idle callback       */
310
311     int              ActiveMenus;          /* Num. of currently active menus */
312     FGCBMenuState    MenuStateCallback;    /* Menu callbacks are global      */
313     FGCBMenuStatus   MenuStatusCallback;
314     void*            MenuFont;             /* Font to be used for newly created menus */
315
316     SFG_XYUse        GameModeSize;         /* Game mode screen's dimensions  */
317     int              GameModeDepth;        /* The pixel depth for game mode  */
318     int              GameModeRefresh;      /* The refresh rate for game mode */
319
320     int              ActionOnWindowClose; /* Action when user closes window  */
321
322     fgExecutionState ExecState;           /* Used for GLUT termination       */
323     char            *ProgramName;         /* Name of the invoking program    */
324     GLboolean        JoysticksInitialised;  /* Only initialize if application calls for them */
325     int              NumActiveJoysticks;    /* Number of active joysticks (callback defined and positive pollrate) -- if zero, don't poll joysticks */
326     GLboolean        InputDevsInitialised;  /* Only initialize if application calls for them */
327
328         int              MouseWheelTicks;      /* Number of ticks the mouse wheel has turned */
329
330     int              AuxiliaryBufferNumber;  /* Number of auxiliary buffers */
331     int              SampleNumber;         /*  Number of samples per pixel  */
332
333     GLboolean        SkipStaleMotion;      /* skip stale motion events */
334
335     int              MajorVersion;         /* Major OpenGL context version  */
336     int              MinorVersion;         /* Minor OpenGL context version  */
337     int              ContextFlags;         /* OpenGL context flags          */
338     int              ContextProfile;       /* OpenGL context profile        */
339     int              HasOpenGL20;          /* fgInitGL2 could find all OpenGL 2.0 functions */
340     FGError          ErrorFunc;            /* User defined error handler    */
341     FGWarning        WarningFunc;          /* User defined warning handler  */
342 };
343
344 /* The structure used by display initialization in freeglut_init.c */
345 typedef struct tagSFG_Display SFG_Display;
346 struct tagSFG_Display
347 {
348         SFG_PlatformDisplay pDisplay;
349
350     int             ScreenWidth;        /* The screen's width in pixels      */
351     int             ScreenHeight;       /* The screen's height in pixels     */
352     int             ScreenWidthMM;      /* The screen's width in milimeters  */
353     int             ScreenHeightMM;     /* The screen's height in milimeters */
354 };
355
356
357 /* The user can create any number of timer hooks */
358 typedef struct tagSFG_Timer SFG_Timer;
359 struct tagSFG_Timer
360 {
361     SFG_Node        Node;
362     int             ID;                 /* The timer ID integer              */
363     FGCBTimer       Callback;           /* The timer callback                */
364     fg_time_t       TriggerTime;        /* The timer trigger time            */
365 };
366
367 /*
368  * A window and its OpenGL context. The contents of this structure
369  * are highly dependant on the target operating system we aim at...
370  */
371 typedef struct tagSFG_Context SFG_Context;
372 struct tagSFG_Context
373 {
374     SFG_WindowHandleType  Handle;    /* The window's handle                 */
375     SFG_WindowContextType Context;   /* The window's OpenGL/WGL context     */
376
377         SFG_PlatformContext pContext;    /* The window's FBConfig (X11) or device context (Windows) */
378
379     int             DoubleBuffered;  /* Treat the window as double-buffered */
380
381     /* When drawing geometry to vertex attribute buffers, user specifies
382      * the attribute indices for vertices, normals and/or texture coords
383      * to freeglut. Those are stored here
384      */
385     GLint           attribute_v_coord;
386     GLint           attribute_v_normal;
387     GLint           attribute_v_texture;
388 };
389
390
391 /*
392  * Bitmasks indicating the different kinds of
393  * actions that can be scheduled for a window.
394  */
395 #define GLUT_INIT_WORK        (1<<0)
396 #define GLUT_VISIBILITY_WORK  (1<<1)
397 #define GLUT_POSITION_WORK    (1<<2)
398 #define GLUT_SIZE_WORK        (1<<3)
399 #define GLUT_ZORDER_WORK      (1<<4)
400 #define GLUT_FULL_SCREEN_WORK (1<<5)
401 #define GLUT_DISPLAY_WORK     (1<<6)
402
403 /*
404  * An enumeration containing the state of the GLUT execution:
405  * initializing, running, or stopping
406  */
407 typedef enum
408 {
409   DesireHiddenState,
410   DesireIconicState,
411   DesireNormalState
412 } fgDesiredVisibility ;
413
414 /*
415  *  There is considerable confusion about the "right thing to
416  *  do" concerning window  size and position.  GLUT itself is
417  *  not consistent between Windows and UNIX/X11; since
418  *  platform independence is a virtue for "freeglut", we
419  *  decided to break with GLUT's behaviour.
420  *
421  *  Under UNIX/X11, it is apparently not possible to get the
422  *  window border sizes in order to subtract them off the
423  *  window's initial position until some time after the window
424  *  has been created.  Therefore we decided on the following
425  *  behaviour, both under Windows and under UNIX/X11:
426  *  - When you create a window with position (x,y) and size
427  *    (w,h), the upper left hand corner of the outside of the
428  *    window is at (x,y) and the size of the drawable area is
429  *    (w,h).
430  *  - When you query the size and position of the window--as
431  *    is happening here for Windows--"freeglut" will return
432  *    the size of the drawable area--the (w,h) that you
433  *    specified when you created the window--and the coordinates
434  *    of the upper left hand corner of the drawable area, i.e.
435  *    of the client rect--which is NOT the (x,y) you specified.
436  */
437 typedef struct tagSFG_WindowState SFG_WindowState;
438 struct tagSFG_WindowState   /* as per notes above, sizes always refer to the client area (thus without the window decorations) */
439 {
440     /* window state - size, position, look */
441     int             Xpos;               /* Window's top-left of client area, X-coordinate */
442     int             Ypos;               /* Window's top-left of client area, Y-coordinate */
443     int             Width;              /* Window's width in pixels          */
444     int             Height;             /* The same about the height         */
445     GLboolean       Visible;            /* Is the window visible now? Not using fgVisibilityState as we only care if visible or not */
446     int             Cursor;             /* The currently selected cursor style */
447     GLboolean       IsFullscreen;       /* is the window fullscreen?         */
448
449     /* FreeGLUT operations are deferred, that is, window moving, resizing,
450      * Z-order changing, making full screen or not do not happen immediately
451      * upon the user's request, but only in the next iteration of the main
452      * loop, before the display callback is called. This allows multiple
453      * reshape, position, etc requests to be combined into one and is
454      * compatible with the way GLUT does things. Callbacks get triggered
455      * based on the feedback/messages/notifications from the window manager.
456      * Below here we define what work should be done, as well as the relevant
457      * parameters for this work.
458      */
459     unsigned int    WorkMask;           /* work (resize, etc) to be done on the window */
460     int             DesiredXpos;        /* desired X location */
461     int             DesiredYpos;        /* desired Y location */
462     int             DesiredWidth;       /* desired window width */
463     int             DesiredHeight;      /* desired window height */
464     int             DesiredZOrder;      /* desired window Z Order position */
465     fgDesiredVisibility DesiredVisibility;/* desired visibility (hidden, iconic, shown/normal) */
466
467         SFG_PlatformWindowState pWState;    /* Window width/height (X11) or rectangle/style (Windows) from before a resize, and other stuff only needed on specific platforms */
468
469     long            JoystickPollRate;   /* The joystick polling rate         */
470     fg_time_t       JoystickLastPoll;   /* When the last poll happened       */
471
472     int             MouseX, MouseY;     /* The most recent mouse position    */
473
474     GLboolean       IgnoreKeyRepeat;    /* Whether to ignore key repeat.     */
475
476     GLboolean       VisualizeNormals;   /* When drawing objects, draw vectors representing the normals as well? */
477 };
478
479
480 /*
481  * A generic function pointer.  We should really use the GLUTproc type
482  * defined in freeglut_ext.h, but if we include that header in this file
483  * a bunch of other stuff (font-related) blows up!
484  */
485 typedef void (*SFG_Proc)();
486
487
488 /*
489  * SET_WCB() is used as:
490  *
491  *     SET_WCB( window, cbname, func );
492  *
493  * ...where {window} is the freeglut window to set the callback,
494  *          {cbname} is the window-specific callback to set,
495  *          {func} is a function-pointer.
496  *
497  * Originally, {FETCH_WCB( ... ) = func} was rather sloppily used,
498  * but this can cause warnings because the FETCH_WCB() macro type-
499  * casts its result, and a type-cast value shouldn't be an lvalue.
500  *
501  * The {if( FETCH_WCB( ... ) != func )} test is to do type-checking
502  * and for no other reason.  Since it's hidden in the macro, the
503  * ugliness is felt to be rather benign.
504  */
505 #define SET_WCB(window,cbname,func)                            \
506 do                                                             \
507 {                                                              \
508     if( FETCH_WCB( window, cbname ) != (SFG_Proc)(func) )      \
509         (((window).CallBacks[WCB_ ## cbname]) = (SFG_Proc)(func)); \
510 } while( 0 )
511
512 /*
513  * FETCH_WCB() is used as:
514  *
515  *     FETCH_WCB( window, cbname );
516  *
517  * ...where {window} is the freeglut window to fetch the callback from,
518  *          {cbname} is the window-specific callback to fetch.
519  *
520  * The result is correctly type-cast to the callback function pointer
521  * type.
522  */
523 #define FETCH_WCB(window,cbname) \
524     ((window).CallBacks[WCB_ ## cbname])
525
526 /*
527  * INVOKE_WCB() is used as:
528  *
529  *     INVOKE_WCB( window, cbname, ( arg_list ) );
530  *
531  * ...where {window} is the freeglut window,
532  *          {cbname} is the window-specific callback to be invoked,
533  *          {(arg_list)} is the parameter list.
534  *
535  * The callback is invoked as:
536  *
537  *    callback( arg_list );
538  *
539  * ...so the parentheses are REQUIRED in the {arg_list}.
540  *
541  * NOTE that it does a sanity-check and also sets the
542  * current window.
543  *
544  */
545 #if TARGET_HOST_MS_WINDOWS && !defined(_WIN32_WCE) /* FIXME: also WinCE? */
546 #define INVOKE_WCB(window,cbname,arg_list)    \
547 do                                            \
548 {                                             \
549     if( FETCH_WCB( window, cbname ) )         \
550     {                                         \
551         FGCB ## cbname func = (FGCB ## cbname)(FETCH_WCB( window, cbname )); \
552         fgSetWindow( &window );               \
553         func arg_list;                        \
554     }                                         \
555 } while( 0 )
556 #else
557 #define INVOKE_WCB(window,cbname,arg_list)    \
558 do                                            \
559 {                                             \
560     if( FETCH_WCB( window, cbname ) )         \
561     {                                         \
562         fgSetWindow( &window );               \
563         ((FGCB ## cbname)FETCH_WCB( window, cbname )) arg_list; \
564     }                                         \
565 } while( 0 )
566 #endif
567
568 /*
569  * The window callbacks the user can supply us with. Should be kept portable.
570  *
571  * This enumeration provides the freeglut CallBack numbers.
572  * The symbolic constants are indices into a window's array of
573  * function callbacks.  The names are formed by splicing a common
574  * prefix onto the callback's base name.  (This was originally
575  * done so that an early stage of development could live side-by-
576  * side with the old callback code.  The old callback code used
577  * the bare callback's name as a structure member, so I used a
578  * prefix for the array index name.)
579  */
580 enum
581 {
582     WCB_Display,
583     WCB_Reshape,
584     WCB_Position,
585     WCB_Keyboard,
586     WCB_KeyboardUp,
587     WCB_Special,
588     WCB_SpecialUp,
589     WCB_Mouse,
590     WCB_MouseWheel,
591     WCB_Motion,
592     WCB_Passive,
593     WCB_Entry,
594     WCB_Visibility,
595     WCB_WindowStatus,
596     WCB_Joystick,
597     WCB_Destroy,
598
599     /* Multi-Pointer X and touch related */
600     WCB_MultiEntry,
601     WCB_MultiButton,
602     WCB_MultiMotion,
603     WCB_MultiPassive,
604
605     /* Mobile platforms LifeCycle */
606     WCB_InitContext,
607     WCB_AppStatus,
608
609     /* Presently ignored */
610     WCB_Select,
611     WCB_OverlayDisplay,
612     WCB_SpaceMotion,     /* presently implemented only on UNIX/X11 */
613     WCB_SpaceRotation,   /* presently implemented only on UNIX/X11 */
614     WCB_SpaceButton,     /* presently implemented only on UNIX/X11 */
615     WCB_Dials,
616     WCB_ButtonBox,
617     WCB_TabletMotion,
618     WCB_TabletButton,
619
620     /* Always make this the LAST one */
621     TOTAL_CALLBACKS
622 };
623
624
625 /* This structure holds the OpenGL rendering context for all the menu windows */
626 typedef struct tagSFG_MenuContext SFG_MenuContext;
627 struct tagSFG_MenuContext
628 {
629     SFG_WindowContextType MContext;       /* The menu window's WGL context   */
630 };
631
632 /* This structure describes a menu */
633 typedef struct tagSFG_Window SFG_Window;
634 typedef struct tagSFG_MenuEntry SFG_MenuEntry;
635 typedef struct tagSFG_Menu SFG_Menu;
636 struct tagSFG_Menu
637 {
638     SFG_Node            Node;
639     void               *UserData;     /* User data passed back at callback   */
640     int                 ID;           /* The global menu ID                  */
641     SFG_List            Entries;      /* The menu entries list               */
642     FGCBMenu            Callback;     /* The menu callback                   */
643     FGCBDestroy         Destroy;      /* Destruction callback                */
644     GLboolean           IsActive;     /* Is the menu selected?               */
645     void*               Font;         /* Font to be used for displaying this menu */
646     int                 Width;        /* Menu box width in pixels            */
647     int                 Height;       /* Menu box height in pixels           */
648     int                 X, Y;         /* Menu box raster position            */
649
650     SFG_MenuEntry      *ActiveEntry;  /* Currently active entry in the menu  */
651     SFG_Window         *Window;       /* Window for menu                     */
652     SFG_Window         *ParentWindow; /* Window in which the menu is invoked */
653 };
654
655 /* This is a menu entry */
656 struct tagSFG_MenuEntry
657 {
658     SFG_Node            Node;
659     int                 ID;                     /* The menu entry ID (local) */
660     int                 Ordinal;                /* The menu's ordinal number */
661     char*               Text;                   /* The text to be displayed  */
662     SFG_Menu*           SubMenu;                /* Optional sub-menu tree    */
663     GLboolean           IsActive;               /* Is the entry highlighted? */
664     int                 Width;                  /* Label's width in pixels   */
665 };
666
667 /*
668  * A window, making part of freeglut windows hierarchy.
669  * Should be kept portable.
670  *
671  * NOTE that ActiveMenu is set to menu itself if the window is a menu.
672  */
673 struct tagSFG_Window
674 {
675     SFG_Node            Node;
676     int                 ID;                     /* Window's ID number        */
677
678     SFG_Context         Window;                 /* Window and OpenGL context */
679     SFG_WindowState     State;                  /* The window state          */
680     SFG_Proc            CallBacks[ TOTAL_CALLBACKS ]; /* Array of window callbacks */
681     void               *UserData ;              /* For use by user           */
682
683     SFG_Menu*       Menu[ FREEGLUT_MAX_MENUS ]; /* Menus appended to window  */
684     SFG_Menu*       ActiveMenu;                 /* The window's active menu  */
685
686     SFG_Window*         Parent;                 /* The parent to this window */
687     SFG_List            Children;               /* The subwindows d.l. list  */
688
689     GLboolean           IsMenu;                 /* Set to 1 if we are a menu */
690 };
691
692
693 /* A linked list structure of windows */
694 typedef struct tagSFG_WindowList SFG_WindowList ;
695 struct tagSFG_WindowList
696 {
697     SFG_Node node;
698     SFG_Window *window ;
699 };
700
701 /* This holds information about all the windows, menus etc. */
702 typedef struct tagSFG_Structure SFG_Structure;
703 struct tagSFG_Structure
704 {
705     SFG_List        Windows;         /* The global windows list            */
706     SFG_List        Menus;           /* The global menus list              */
707     SFG_List        WindowsToDestroy;
708
709     SFG_Window*     CurrentWindow;   /* The currently set window          */
710     SFG_Menu*       CurrentMenu;     /* Same, but menu...                 */
711
712     SFG_MenuContext* MenuContext;    /* OpenGL rendering context for menus */
713
714     SFG_Window*      GameModeWindow; /* The game mode window               */
715
716     int              WindowID;       /* The window ID for the next window to be created */
717     int              MenuID;         /* The menu ID for the next menu to be created */
718 };
719
720 /*
721  * This structure is used for the enumeration purposes.
722  * You can easily extend its functionalities by declaring
723  * a structure containing enumerator's contents and custom
724  * data, then casting its pointer to (SFG_Enumerator *).
725  */
726 typedef struct tagSFG_Enumerator SFG_Enumerator;
727 struct tagSFG_Enumerator
728 {
729     GLboolean   found;                          /* Used to terminate search  */
730     void*       data;                           /* Custom data pointer       */
731 };
732 typedef void (* FGCBWindowEnumerator  )( SFG_Window *, SFG_Enumerator * );
733 typedef void (* FGCBMenuEnumerator  )( SFG_Menu *, SFG_Enumerator * );
734
735 /* The bitmap font structure */
736 typedef struct tagSFG_Font SFG_Font;
737 struct tagSFG_Font
738 {
739     char*           Name;         /* The source font name             */
740     int             Quantity;     /* Number of chars in font          */
741     int             Height;       /* Height of the characters         */
742     const GLubyte** Characters;   /* The characters mapping           */
743
744     float           xorig, yorig; /* Relative origin of the character */
745 };
746
747 /* The stroke font structures */
748
749 typedef struct tagSFG_StrokeVertex SFG_StrokeVertex;
750 struct tagSFG_StrokeVertex
751 {
752     GLfloat         X, Y;
753 };
754
755 typedef struct tagSFG_StrokeStrip SFG_StrokeStrip;
756 struct tagSFG_StrokeStrip
757 {
758     int             Number;
759     const SFG_StrokeVertex* Vertices;
760 };
761
762 typedef struct tagSFG_StrokeChar SFG_StrokeChar;
763 struct tagSFG_StrokeChar
764 {
765     GLfloat         Right;
766     int             Number;
767     const SFG_StrokeStrip* Strips;
768 };
769
770 typedef struct tagSFG_StrokeFont SFG_StrokeFont;
771 struct tagSFG_StrokeFont
772 {
773     char*           Name;                       /* The source font name      */
774     int             Quantity;                   /* Number of chars in font   */
775     GLfloat         Height;                     /* Height of the characters  */
776     const SFG_StrokeChar** Characters;          /* The characters mapping    */
777 };
778
779
780 /* -- JOYSTICK-SPECIFIC STRUCTURES AND TYPES ------------------------------- */
781 /*
782  * Initial defines from "js.h" starting around line 33 with the existing "freeglut_joystick.c"
783  * interspersed
784  */
785
786 #if TARGET_HOST_MACINTOSH
787 #    include <InputSprocket.h>
788 #endif
789
790 #if TARGET_HOST_MAC_OSX
791 #    include <mach/mach.h>
792 #    include <IOKit/IOkitLib.h>
793 #    include <IOKit/hid/IOHIDLib.h>
794 #endif
795
796 /* XXX It might be better to poll the operating system for the numbers of buttons and
797  * XXX axes and then dynamically allocate the arrays.
798  */
799 #define _JS_MAX_BUTTONS 32
800
801 #if TARGET_HOST_MACINTOSH
802 #    define _JS_MAX_AXES  9
803 typedef struct tagSFG_PlatformJoystick SFG_PlatformJoystick;
804 struct tagSFG_PlatformJoystick
805 {
806 #define  ISP_NUM_AXIS    9
807 #define  ISP_NUM_NEEDS  41
808     ISpElementReference isp_elem  [ ISP_NUM_NEEDS ];
809     ISpNeed             isp_needs [ ISP_NUM_NEEDS ];
810 };
811 #endif
812
813 #if TARGET_HOST_MAC_OSX
814 #    define _JS_MAX_AXES 16
815 typedef struct tagSFG_PlatformJoystick SFG_PlatformJoystick;
816 struct tagSFG_PlatformJoystick
817 {
818     IOHIDDeviceInterface ** hidDev;
819     IOHIDElementCookie buttonCookies[41];
820     IOHIDElementCookie axisCookies[_JS_MAX_AXES];
821 /* The next two variables are not used anywhere */
822 /*    long minReport[_JS_MAX_AXES],
823  *         maxReport[_JS_MAX_AXES];
824  */
825 };
826 #endif
827
828
829 /*
830  * Definition of "SFG_Joystick" structure -- based on JS's "jsJoystick" object class.
831  * See "js.h" lines 80-178.
832  */
833 typedef struct tagSFG_Joystick SFG_Joystick;
834 struct tagSFG_Joystick
835 {
836         SFG_PlatformJoystick pJoystick;
837
838     int          id;
839     GLboolean    error;
840     char         name [ 128 ];
841     int          num_axes;
842     int          num_buttons;
843
844     float dead_band[ _JS_MAX_AXES ];
845     float saturate [ _JS_MAX_AXES ];
846     float center   [ _JS_MAX_AXES ];
847     float max      [ _JS_MAX_AXES ];
848     float min      [ _JS_MAX_AXES ];
849 };
850
851
852
853 /* -- GLOBAL VARIABLES EXPORTS --------------------------------------------- */
854
855 /* Freeglut display related stuff (initialized once per session) */
856 extern SFG_Display fgDisplay;
857
858 /* Freeglut internal structure */
859 extern SFG_Structure fgStructure;
860
861 /* The current freeglut settings */
862 extern SFG_State fgState;
863
864
865 /* -- PRIVATE FUNCTION DECLARATIONS ---------------------------------------- */
866
867 /*
868  * A call to this function makes us sure that the Display and Structure
869  * subsystems have been properly initialized and are ready to be used
870  */
871 #define  FREEGLUT_EXIT_IF_NOT_INITIALISED( string )               \
872   if ( ! fgState.Initialised )                                    \
873   {                                                               \
874     fgError ( " ERROR:  Function <%s> called"                     \
875               " without first calling 'glutInit'.", (string) ) ;  \
876   }
877
878 #define  FREEGLUT_INTERNAL_ERROR_EXIT_IF_NOT_INITIALISED( string )  \
879   if ( ! fgState.Initialised )                                      \
880   {                                                                 \
881     fgError ( " ERROR:  Internal <%s> function called"              \
882               " without first calling 'glutInit'.", (string) ) ;    \
883   }
884
885 #define  FREEGLUT_INTERNAL_ERROR_EXIT( cond, string, function )  \
886   if ( ! ( cond ) )                                              \
887   {                                                              \
888     fgError ( " ERROR:  Internal error <%s> in function %s",     \
889               (string), (function) ) ;                           \
890   }
891
892 /*
893  * Following definitions are somewhat similiar to GLib's,
894  * but do not generate any log messages:
895  */
896 #define  freeglut_return_if_fail( expr ) \
897     if( !(expr) )                        \
898         return;
899 #define  freeglut_return_val_if_fail( expr, val ) \
900     if( !(expr) )                                 \
901         return val ;
902
903 /*
904  * A call to those macros assures us that there is a current
905  * window set, respectively:
906  */
907 #define  FREEGLUT_EXIT_IF_NO_WINDOW( string )                               \
908   if ( ! fgStructure.CurrentWindow &&                                       \
909        ( fgState.ActionOnWindowClose != GLUT_ACTION_CONTINUE_EXECUTION ) )  \
910   {                                                                         \
911     fgError ( " ERROR:  Function <%s> called"                               \
912               " with no current window defined.", (string) ) ;              \
913   }
914
915 /*
916  * The deinitialize function gets called on glutMainLoop() end. It should clean up
917  * everything inside of the freeglut
918  */
919 void fgDeinitialize( void );
920
921 /*
922  * Those two functions are used to create/destroy the freeglut internal
923  * structures. This actually happens when calling glutInit() and when
924  * quitting the glutMainLoop() (which actually happens, when all windows
925  * have been closed).
926  */
927 void fgCreateStructure( void );
928 void fgDestroyStructure( void );
929
930 /*
931  * Window creation, opening, closing and destruction.
932  * Also CallBack clearing/initialization.
933  * Defined in freeglut_structure.c, freeglut_window.c.
934  */
935 SFG_Window* fgCreateWindow( SFG_Window* parent, const char* title,
936                             GLboolean positionUse, int x, int y,
937                             GLboolean sizeUse, int w, int h,
938                             GLboolean gameMode, GLboolean isMenu );
939 void        fgSetWindow ( SFG_Window *window );
940 void        fgOpenWindow( SFG_Window* window, const char* title,
941                           GLboolean positionUse, int x, int y,
942                           GLboolean sizeUse, int w, int h,
943                           GLboolean gameMode, GLboolean isSubWindow );
944 void        fgCloseWindow( SFG_Window* window );
945 void        fgAddToWindowDestroyList ( SFG_Window* window );
946 void        fgCloseWindows ();
947 void        fgDestroyWindow( SFG_Window* window );
948
949 /* Menu creation and destruction. Defined in freeglut_structure.c */
950 SFG_Menu*   fgCreateMenu( FGCBMenu menuCallback );
951 void        fgDestroyMenu( SFG_Menu* menu );
952
953 /* Joystick device management functions, defined in freeglut_joystick.c */
954 int         fgJoystickDetect( void );
955 void        fgInitialiseJoysticks( void );
956 void        fgJoystickClose( void );
957 void        fgJoystickPollWindow( SFG_Window* window );
958
959 /* InputDevice Initialisation and Closure */
960 int         fgInputDeviceDetect( void );
961 void        fgInitialiseInputDevices( void );
962 void        fgInputDeviceClose( void );
963
964 /* spaceball device functions, defined in freeglut_spaceball.c */
965 void        fgInitialiseSpaceball( void );
966 void        fgSpaceballClose( void );
967 void        fgSpaceballSetWindow( SFG_Window *window );
968
969 int         fgHasSpaceball( void );
970 int         fgSpaceballNumButtons( void );
971
972 /* Setting the cursor for a given window */
973 void fgSetCursor ( SFG_Window *window, int cursorID );
974
975 /*
976  * Helper function to enumerate through all registered windows
977  * and one to enumerate all of a window's subwindows...
978  *
979  * The GFunc callback for those functions will be defined as:
980  *
981  *      void enumCallback( gpointer window, gpointer enumerator );
982  *
983  * where window is the enumerated (sub)window pointer (SFG_Window *),
984  * and userData is the a custom user-supplied pointer. Functions
985  * are defined and exported from freeglut_structure.c file.
986  */
987 void fgEnumWindows( FGCBWindowEnumerator enumCallback, SFG_Enumerator* enumerator );
988 void fgEnumSubWindows( SFG_Window* window, FGCBWindowEnumerator enumCallback,
989                        SFG_Enumerator* enumerator );
990
991 /*
992  * fgWindowByHandle returns a (SFG_Window *) value pointing to the
993  * first window in the queue matching the specified window handle.
994  * The function is defined in freeglut_structure.c file.
995  */
996 SFG_Window* fgWindowByHandle( SFG_WindowHandleType hWindow );
997
998 /*
999  * This function is similiar to the previous one, except it is
1000  * looking for a specified (sub)window identifier. The function
1001  * is defined in freeglut_structure.c file.
1002  */
1003 SFG_Window* fgWindowByID( int windowID );
1004
1005 /*
1006  * Looks up a menu given its ID. This is easier than fgWindowByXXX
1007  * as all menus are placed in a single doubly linked list...
1008  */
1009 SFG_Menu* fgMenuByID( int menuID );
1010
1011 /*
1012  * Returns active menu, if any. Assumption: only one menu active throughout application at any one time.
1013  * This is easier than fgWindowByXXX as all menus are placed in one doubly linked list...
1014  */
1015 SFG_Menu* fgGetActiveMenu( );
1016
1017 /*
1018  * The menu activation and deactivation the code. This is the meat
1019  * of the menu user interface handling code...
1020  */
1021 void fgUpdateMenuHighlight ( SFG_Menu *menu );
1022 GLboolean fgCheckActiveMenu ( SFG_Window *window, int button, GLboolean pressed,
1023                               int mouse_x, int mouse_y );
1024 void fgDeactivateMenu( SFG_Window *window );
1025
1026 /*
1027  * This function gets called just before the buffers swap, so that
1028  * freeglut can display the pull-down menus via OpenGL. The function
1029  * is defined in freeglut_menu.c file.
1030  */
1031 void fgDisplayMenu( void );
1032
1033 /* Elapsed time as per glutGet(GLUT_ELAPSED_TIME). */
1034 fg_time_t fgElapsedTime( void );
1035
1036 /* System time in milliseconds */
1037 fg_time_t fgSystemTime(void);
1038
1039 /* List functions */
1040 void fgListInit(SFG_List *list);
1041 void fgListAppend(SFG_List *list, SFG_Node *node);
1042 void fgListRemove(SFG_List *list, SFG_Node *node);
1043 int fgListLength(SFG_List *list);
1044 void fgListInsert(SFG_List *list, SFG_Node *next, SFG_Node *node);
1045
1046 /* Error Message functions */
1047 void fgError( const char *fmt, ... );
1048 void fgWarning( const char *fmt, ... );
1049
1050 SFG_Proc fgPlatformGetProcAddress( const char *procName );
1051
1052 /* pushing attribute/value pairs into an array */
1053 #define ATTRIB(a) attributes[where++]=(a)
1054 #define ATTRIB_VAL(a,v) {ATTRIB(a); ATTRIB(v);}
1055
1056 int fghMapBit( int mask, int from, int to );
1057 int fghIsLegacyContextRequested( void );
1058 void fghContextCreationError( void );
1059 int fghNumberOfAuxBuffersRequested( void );
1060
1061 #endif /* FREEGLUT_INTERNAL_H */
1062
1063 /*** END OF FILE ***/