moved some windows only code from common to windows specific
[freeglut] / src / Common / freeglut_main.c
1 /*
2  * freeglut_main.c
3  *
4  * The windows message processing methods.
5  *
6  * Copyright (c) 1999-2000 Pawel W. Olszta. All Rights Reserved.
7  * Written by Pawel W. Olszta, <olszta@sourceforge.net>
8  * Creation date: Fri Dec 3 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 #include <GL/freeglut.h>
29 #include "freeglut_internal.h"
30 #ifdef HAVE_ERRNO_H
31 #    include <errno.h>
32 #endif
33 #include <stdarg.h>
34 #ifdef  HAVE_VFPRINTF
35 #    define VFPRINTF(s,f,a) vfprintf((s),(f),(a))
36 #elif defined(HAVE__DOPRNT)
37 #    define VFPRINTF(s,f,a) _doprnt((f),(a),(s))
38 #else
39 #    define VFPRINTF(s,f,a)
40 #endif
41
42 /*
43  * Try to get the maximum value allowed for ints, falling back to the minimum
44  * guaranteed by ISO C99 if there is no suitable header.
45  */
46 #ifdef HAVE_LIMITS_H
47 #    include <limits.h>
48 #endif
49 #ifndef INT_MAX
50 #    define INT_MAX 32767
51 #endif
52
53 #ifndef MIN
54 #    define MIN(a,b) (((a)<(b)) ? (a) : (b))
55 #endif
56
57 extern void fgPlatformReshapeWindow ( SFG_Window *window, int width, int height );
58 extern void fgPlatformDisplayWindow ( SFG_Window *window );
59 extern unsigned long fgPlatformSystemTime ( void );
60 extern void fgPlatformSleepForEvents( long msec );
61 extern void fgPlatformProcessSingleEvent ( void );
62 extern void fgPlatformMainLoopPreliminaryWork ( void );
63
64
65
66
67 /* -- PRIVATE FUNCTIONS ---------------------------------------------------- */
68
69 static void fghReshapeWindow ( SFG_Window *window, int width, int height )
70 {
71     SFG_Window *current_window = fgStructure.CurrentWindow;
72
73     freeglut_return_if_fail( window != NULL );
74
75         fgPlatformReshapeWindow ( window, width, height );
76
77     if( FETCH_WCB( *window, Reshape ) )
78         INVOKE_WCB( *window, Reshape, ( width, height ) );
79     else
80     {
81         fgSetWindow( window );
82         glViewport( 0, 0, width, height );
83     }
84
85     /*
86      * Force a window redraw.  In Windows at least this is only a partial
87      * solution:  if the window is increasing in size in either dimension,
88      * the already-drawn part does not get drawn again and things look funny.
89      * But without this we get this bad behaviour whenever we resize the
90      * window.
91      */
92     window->State.Redisplay = GL_TRUE;
93
94     if( window->IsMenu )
95         fgSetWindow( current_window );
96 }
97
98 /*
99  * Calls a window's redraw method. This is used when
100  * a redraw is forced by the incoming window messages.
101  */
102 void fghRedrawWindow ( SFG_Window *window )
103 {
104     SFG_Window *current_window = fgStructure.CurrentWindow;
105
106     freeglut_return_if_fail( window );
107     freeglut_return_if_fail( FETCH_WCB ( *window, Display ) );
108
109     window->State.Redisplay = GL_FALSE;
110
111     freeglut_return_if_fail( window->State.Visible );
112
113     fgSetWindow( window );
114
115     if( window->State.NeedToResize )
116     {
117         fghReshapeWindow(
118             window,
119             window->State.Width,
120             window->State.Height
121         );
122
123         window->State.NeedToResize = GL_FALSE;
124     }
125
126     INVOKE_WCB( *window, Display, ( ) );
127
128     fgSetWindow( current_window );
129 }
130
131
132 static void fghcbDisplayWindow( SFG_Window *window,
133                                 SFG_Enumerator *enumerator )
134 {
135     if( window->State.Redisplay &&
136         window->State.Visible )
137     {
138         window->State.Redisplay = GL_FALSE;
139                 fgPlatformDisplayWindow ( window );
140     }
141
142     fgEnumSubWindows( window, fghcbDisplayWindow, enumerator );
143 }
144
145 /*
146  * Make all windows perform a display call
147  */
148 static void fghDisplayAll( void )
149 {
150     SFG_Enumerator enumerator;
151
152     enumerator.found = GL_FALSE;
153     enumerator.data  =  NULL;
154
155     fgEnumWindows( fghcbDisplayWindow, &enumerator );
156 }
157
158 /*
159  * Window enumerator callback to check for the joystick polling code
160  */
161 static void fghcbCheckJoystickPolls( SFG_Window *window,
162                                      SFG_Enumerator *enumerator )
163 {
164     long int checkTime = fgElapsedTime( );
165
166     if( window->State.JoystickLastPoll + window->State.JoystickPollRate <=
167         checkTime )
168     {
169 #if !defined(_WIN32_WCE)
170         fgJoystickPollWindow( window );
171 #endif /* !defined(_WIN32_WCE) */
172         window->State.JoystickLastPoll = checkTime;
173     }
174
175     fgEnumSubWindows( window, fghcbCheckJoystickPolls, enumerator );
176 }
177
178 /*
179  * Check all windows for joystick polling
180  */
181 static void fghCheckJoystickPolls( void )
182 {
183     SFG_Enumerator enumerator;
184
185     enumerator.found = GL_FALSE;
186     enumerator.data  =  NULL;
187
188     fgEnumWindows( fghcbCheckJoystickPolls, &enumerator );
189 }
190
191 /*
192  * Check the global timers
193  */
194 static void fghCheckTimers( void )
195 {
196     long checkTime = fgElapsedTime( );
197
198     while( fgState.Timers.First )
199     {
200         SFG_Timer *timer = fgState.Timers.First;
201
202         if( timer->TriggerTime > checkTime )
203             break;
204
205         fgListRemove( &fgState.Timers, &timer->Node );
206         fgListAppend( &fgState.FreeTimers, &timer->Node );
207
208         timer->Callback( timer->ID );
209     }
210 }
211
212  
213 /* Platform-dependent time in milliseconds, as an unsigned 32-bit integer.
214  * This value wraps every 49.7 days, but integer overflows cancel
215  * when subtracting an initial start time, unless the total time exceeds
216  * 32-bit, where the GLUT API return value is also overflowed.
217  */  
218 unsigned long fgSystemTime(void)
219 {
220         return fgPlatformSystemTime ();
221 }
222   
223 /*
224  * Elapsed Time
225  */
226 long fgElapsedTime( void )
227 {
228     return (long) (fgSystemTime() - fgState.Time);
229 }
230
231 /*
232  * Error Messages.
233  */
234 void fgError( const char *fmt, ... )
235 {
236     va_list ap;
237
238     if (fgState.ErrorFunc) {
239
240         va_start( ap, fmt );
241
242         /* call user set error handler here */
243         fgState.ErrorFunc(fmt, ap);
244
245         va_end( ap );
246
247     } else {
248
249         va_start( ap, fmt );
250
251         fprintf( stderr, "freeglut ");
252         if( fgState.ProgramName )
253             fprintf( stderr, "(%s): ", fgState.ProgramName );
254         VFPRINTF( stderr, fmt, ap );
255         fprintf( stderr, "\n" );
256
257         va_end( ap );
258
259         if ( fgState.Initialised )
260             fgDeinitialize ();
261
262         exit( 1 );
263     }
264 }
265
266 void fgWarning( const char *fmt, ... )
267 {
268     va_list ap;
269
270     if (fgState.WarningFunc) {
271
272         va_start( ap, fmt );
273
274         /* call user set warning handler here */
275         fgState.WarningFunc(fmt, ap);
276
277         va_end( ap );
278
279     } else {
280
281         va_start( ap, fmt );
282
283         fprintf( stderr, "freeglut ");
284         if( fgState.ProgramName )
285             fprintf( stderr, "(%s): ", fgState.ProgramName );
286         VFPRINTF( stderr, fmt, ap );
287         fprintf( stderr, "\n" );
288
289         va_end( ap );
290     }
291 }
292
293
294 /*
295  * Indicates whether Joystick events are being used by ANY window.
296  *
297  * The current mechanism is to walk all of the windows and ask if
298  * there is a joystick callback.  We have a short-circuit early
299  * return if we find any joystick handler registered.
300  *
301  * The real way to do this is to make use of the glutTimer() API
302  * to more cleanly re-implement the joystick API.  Then, this code
303  * and all other "joystick timer" code can be yanked.
304  *
305  */
306 static void fghCheckJoystickCallback( SFG_Window* w, SFG_Enumerator* e)
307 {
308     if( FETCH_WCB( *w, Joystick ) )
309     {
310         e->found = GL_TRUE;
311         e->data = w;
312     }
313     fgEnumSubWindows( w, fghCheckJoystickCallback, e );
314 }
315 static int fghHaveJoystick( void )
316 {
317     SFG_Enumerator enumerator;
318
319     enumerator.found = GL_FALSE;
320     enumerator.data = NULL;
321     fgEnumWindows( fghCheckJoystickCallback, &enumerator );
322     return !!enumerator.data;
323 }
324 static void fghHavePendingRedisplaysCallback( SFG_Window* w, SFG_Enumerator* e)
325 {
326     if( w->State.Redisplay && w->State.Visible )
327     {
328         e->found = GL_TRUE;
329         e->data = w;
330     }
331     fgEnumSubWindows( w, fghHavePendingRedisplaysCallback, e );
332 }
333 static int fghHavePendingRedisplays (void)
334 {
335     SFG_Enumerator enumerator;
336
337     enumerator.found = GL_FALSE;
338     enumerator.data = NULL;
339     fgEnumWindows( fghHavePendingRedisplaysCallback, &enumerator );
340     return !!enumerator.data;
341 }
342 /*
343  * Returns the number of GLUT ticks (milliseconds) till the next timer event.
344  */
345 static long fghNextTimer( void )
346 {
347     long ret = INT_MAX;
348     SFG_Timer *timer = fgState.Timers.First;
349
350     if( timer )
351         ret = timer->TriggerTime - fgElapsedTime();
352     if( ret < 0 )
353         ret = 0;
354
355     return ret;
356 }
357
358 static void fghSleepForEvents( void )
359 {
360     long msec;
361
362     if( fgState.IdleCallback || fghHavePendingRedisplays( ) )
363         return;
364
365     msec = fghNextTimer( );
366     /* XXX Use GLUT timers for joysticks... */
367     /* XXX Dumb; forces granularity to .01sec */
368     if( fghHaveJoystick( ) && ( msec > 10 ) )     
369         msec = 10;
370
371         fgPlatformSleepForEvents ( msec );
372 }
373
374
375 /* -- INTERFACE FUNCTIONS -------------------------------------------------- */
376
377 /*
378  * Executes a single iteration in the freeglut processing loop.
379  */
380 void FGAPIENTRY glutMainLoopEvent( void )
381 {
382         fgPlatformProcessSingleEvent ();
383
384     if( fgState.Timers.First )
385         fghCheckTimers( );
386     fghCheckJoystickPolls( );
387     fghDisplayAll( );
388
389     fgCloseWindows( );
390 }
391
392 /*
393  * Enters the freeglut processing loop.
394  * Stays until the "ExecState" changes to "GLUT_EXEC_STATE_STOP".
395  */
396 void FGAPIENTRY glutMainLoop( void )
397 {
398     int action;
399
400     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutMainLoop" );
401
402         fgPlatformMainLoopPreliminaryWork ();
403
404     fgState.ExecState = GLUT_EXEC_STATE_RUNNING ;
405     while( fgState.ExecState == GLUT_EXEC_STATE_RUNNING )
406     {
407         SFG_Window *window;
408
409         glutMainLoopEvent( );
410         /*
411          * Step through the list of windows, seeing if there are any
412          * that are not menus
413          */
414         for( window = ( SFG_Window * )fgStructure.Windows.First;
415              window;
416              window = ( SFG_Window * )window->Node.Next )
417             if ( ! ( window->IsMenu ) )
418                 break;
419
420         if( ! window )
421             fgState.ExecState = GLUT_EXEC_STATE_STOP;
422         else
423         {
424             if( fgState.IdleCallback )
425             {
426                 if( fgStructure.CurrentWindow &&
427                     fgStructure.CurrentWindow->IsMenu )
428                     /* fail safe */
429                     fgSetWindow( window );
430                 fgState.IdleCallback( );
431             }
432
433             fghSleepForEvents( );
434         }
435     }
436
437     /*
438      * When this loop terminates, destroy the display, state and structure
439      * of a freeglut session, so that another glutInit() call can happen
440      *
441      * Save the "ActionOnWindowClose" because "fgDeinitialize" resets it.
442      */
443     action = fgState.ActionOnWindowClose;
444     fgDeinitialize( );
445     if( action == GLUT_ACTION_EXIT )
446         exit( 0 );
447 }
448
449 /*
450  * Leaves the freeglut processing loop.
451  */
452 void FGAPIENTRY glutLeaveMainLoop( void )
453 {
454     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutLeaveMainLoop" );
455     fgState.ExecState = GLUT_EXEC_STATE_STOP ;
456 }
457
458
459
460 /*** END OF FILE ***/