4365b8c6a243c553154f3d6d8ff52cf8c5bcb9bc
[freeglut] / src / mswin / fg_window_mswin.c
1 /*
2  * freeglut_window_mswin.c
3  *
4  * The Windows-specific mouse cursor related stuff.
5  *
6  * Copyright (c) 2012 Stephen J. Baker. All Rights Reserved.
7  * Written by John F. Fay, <fayjf@sourceforge.net>
8  * Creation date: Sun Jan 22, 2012
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 "../fg_internal.h"
31
32
33 /* The following include file is available from SGI but is not standard:
34  *   #include <GL/wglext.h>
35  * So we copy the necessary parts out of it.
36  * XXX: should local definitions for extensions be put in a separate include file?
37  */
38 typedef const char * (WINAPI * PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
39
40 typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
41
42 #define WGL_DRAW_TO_WINDOW_ARB         0x2001
43 #define WGL_ACCELERATION_ARB           0x2003
44 #define WGL_SUPPORT_OPENGL_ARB         0x2010
45 #define WGL_DOUBLE_BUFFER_ARB          0x2011
46 #define WGL_COLOR_BITS_ARB             0x2014
47 #define WGL_ALPHA_BITS_ARB             0x201B
48 #define WGL_DEPTH_BITS_ARB             0x2022
49 #define WGL_STENCIL_BITS_ARB           0x2023
50 #define WGL_FULL_ACCELERATION_ARB      0x2027
51
52 #define WGL_SAMPLE_BUFFERS_ARB         0x2041
53 #define WGL_SAMPLES_ARB                0x2042
54
55 #define WGL_TYPE_RGBA_FLOAT_ARB        0x21A0
56
57 #define WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20A9
58
59 #ifndef WGL_ARB_create_context
60 #define WGL_ARB_create_context 1
61 #ifdef WGL_WGLEXT_PROTOTYPES
62 extern HGLRC WINAPI wglCreateContextAttribsARB (HDC, HGLRC, const int *);
63 #endif /* WGL_WGLEXT_PROTOTYPES */
64 typedef HGLRC (WINAPI * PFNWGLCREATECONTEXTATTRIBSARBPROC) (HDC hDC, HGLRC hShareContext, const int *attribList);
65
66 #define WGL_CONTEXT_MAJOR_VERSION_ARB  0x2091
67 #define WGL_CONTEXT_MINOR_VERSION_ARB  0x2092
68 #define WGL_CONTEXT_LAYER_PLANE_ARB    0x2093
69 #define WGL_CONTEXT_FLAGS_ARB          0x2094
70 #define WGL_CONTEXT_PROFILE_MASK_ARB   0x9126
71
72 #define WGL_CONTEXT_DEBUG_BIT_ARB      0x0001
73 #define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x0002
74
75 #define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
76 #define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
77
78 #define ERROR_INVALID_VERSION_ARB      0x2095
79 #define ERROR_INVALID_PROFILE_ARB      0x2096
80 #endif
81 /* End of copying the necessary parts out of it. */
82
83 #ifdef WM_TOUCH
84 typedef BOOL (WINAPI *pRegisterTouchWindow)(HWND,ULONG);
85 static pRegisterTouchWindow fghRegisterTouchWindow = (pRegisterTouchWindow)0xDEADBEEF;
86 #endif
87 extern void fghNotifyWindowStatus(SFG_Window *window);
88
89
90 /*
91  * Setup the pixel format for a Win32 window
92  */
93
94 #if defined(_WIN32_WCE)
95 static wchar_t* fghWstrFromStr(const char* str)
96 {
97     int i,len=strlen(str);
98     wchar_t* wstr = (wchar_t*)malloc(2*len+2);
99     for(i=0; i<len; i++)
100         wstr[i] = str[i];
101     wstr[len] = 0;
102     return wstr;
103 }
104 #endif /* defined(_WIN32_WCE) */
105
106
107 static void fghFillContextAttributes( int *attributes ) {
108   int where = 0, contextFlags, contextProfile;
109
110   ATTRIB_VAL( WGL_CONTEXT_MAJOR_VERSION_ARB, fgState.MajorVersion );
111   ATTRIB_VAL( WGL_CONTEXT_MINOR_VERSION_ARB, fgState.MinorVersion );
112
113   contextFlags =
114     fghMapBit( fgState.ContextFlags, GLUT_DEBUG, WGL_CONTEXT_DEBUG_BIT_ARB ) |
115     fghMapBit( fgState.ContextFlags, GLUT_FORWARD_COMPATIBLE, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB );
116   if ( contextFlags != 0 ) {
117     ATTRIB_VAL( WGL_CONTEXT_FLAGS_ARB, contextFlags );
118   }
119
120   contextProfile =
121     fghMapBit( fgState.ContextProfile, GLUT_CORE_PROFILE, WGL_CONTEXT_CORE_PROFILE_BIT_ARB ) |
122     fghMapBit( fgState.ContextProfile, GLUT_COMPATIBILITY_PROFILE, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB );
123   if ( contextProfile != 0 ) {
124     ATTRIB_VAL( WGL_CONTEXT_PROFILE_MASK_ARB, contextProfile );
125   }
126
127   ATTRIB( 0 );
128 }
129
130 static int fghIsExtensionSupported( HDC hdc, const char *extension ) {
131     const char *pWglExtString;
132     PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetEntensionsStringARB =
133       (PFNWGLGETEXTENSIONSSTRINGARBPROC) wglGetProcAddress("wglGetExtensionsStringARB");
134     if ( wglGetEntensionsStringARB == NULL )
135     {
136       return FALSE;
137     }
138     pWglExtString = wglGetEntensionsStringARB( hdc );
139     return ( pWglExtString != NULL ) && ( strstr(pWglExtString, extension) != NULL );
140 }
141
142 void fgNewWGLCreateContext( SFG_Window* window )
143 {
144     HGLRC context;
145     int attributes[9];
146     PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB;
147
148     /* If nothing fancy has been required, leave the context as it is */
149     if ( fghIsLegacyContextRequested() )
150     {
151         return;
152     }
153
154     wglMakeCurrent( window->Window.pContext.Device, window->Window.Context );
155
156     if ( !fghIsExtensionSupported( window->Window.pContext.Device, "WGL_ARB_create_context" ) )
157     {
158         /* wglCreateContextAttribsARB not found, yet the user has requested the new context creation */
159         fgWarning( "OpenGL >2.1 context requested but wglCreateContextAttribsARB is not available! Falling back to legacy context creation" );
160         /* Legacy context already created at this point in WM_CREATE path of fgPlatformWindowProc, just return */
161         return;
162     }
163
164     /* new context creation */
165     fghFillContextAttributes( attributes );
166
167     wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC) wglGetProcAddress( "wglCreateContextAttribsARB" );
168     if ( wglCreateContextAttribsARB == NULL )
169     {
170         /* wglCreateContextAttribsARB not found, yet the user has requested the new context creation */
171         fgWarning( "OpenGL >2.1 context requested but wglCreateContextAttribsARB is not available! Falling back to legacy context creation" );
172         /* Legacy context already created at this point in WM_CREATE path of fgPlatformWindowProc, just return */
173         return;
174     }
175
176     context = wglCreateContextAttribsARB( window->Window.pContext.Device, 0, attributes );
177     if ( context == NULL )
178     {
179         fghContextCreationError();
180     }
181
182     wglMakeCurrent( NULL, NULL );
183     wglDeleteContext( window->Window.Context );
184     window->Window.Context = context;
185 }
186
187 #if !defined(_WIN32_WCE)
188
189 static void fghFillPFD( PIXELFORMATDESCRIPTOR *ppfd, HDC hdc, unsigned char layer_type )
190 {
191   int flags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL;
192   if ( fgState.DisplayMode & GLUT_DOUBLE ) {
193         flags |= PFD_DOUBLEBUFFER;
194   }
195   if ( fgState.DisplayMode & GLUT_STEREO ) {
196     flags |= PFD_STEREO;
197   }
198
199 #if defined(_MSC_VER)
200 #pragma message( "fgSetupPixelFormat(): there is still some work to do here!" )
201 #endif
202
203   /* Specify which pixel format do we opt for... */
204   ppfd->nSize = sizeof(PIXELFORMATDESCRIPTOR);
205   ppfd->nVersion = 1;
206   ppfd->dwFlags = flags;
207
208   if( fgState.DisplayMode & GLUT_INDEX ) {
209     ppfd->iPixelType = PFD_TYPE_COLORINDEX;
210     ppfd->cRedBits = 0;
211     ppfd->cGreenBits = 0;
212     ppfd->cBlueBits = 0;
213     ppfd->cAlphaBits = 0;
214   } else {
215     ppfd->iPixelType = PFD_TYPE_RGBA;
216     ppfd->cRedBits = 8;
217     ppfd->cGreenBits = 8;
218     ppfd->cBlueBits = 8;
219     ppfd->cAlphaBits = ( fgState.DisplayMode & GLUT_ALPHA ) ? 8 : 0;
220   }
221
222   ppfd->cColorBits = 24;
223   ppfd->cRedShift = 0;
224   ppfd->cGreenShift = 0;
225   ppfd->cBlueShift = 0;
226   ppfd->cAlphaShift = 0;
227   ppfd->cAccumBits = ( fgState.DisplayMode & GLUT_ACCUM ) ? 1 : 0;
228   ppfd->cAccumRedBits = 0;
229   ppfd->cAccumGreenBits = 0;
230   ppfd->cAccumBlueBits = 0;
231   ppfd->cAccumAlphaBits = 0;
232
233   /* Hmmm, or 32/0 instead of 24/8? */
234   ppfd->cDepthBits = 24;
235   ppfd->cStencilBits = 8;
236
237   ppfd->cAuxBuffers = fghNumberOfAuxBuffersRequested();
238   ppfd->iLayerType = layer_type;
239   ppfd->bReserved = 0;
240   ppfd->dwLayerMask = 0;
241   ppfd->dwVisibleMask = 0;
242   ppfd->dwDamageMask = 0;
243   
244   ppfd->cColorBits = (BYTE) GetDeviceCaps( hdc, BITSPIXEL );
245 }
246
247 static void fghFillPixelFormatAttributes( int *attributes, const PIXELFORMATDESCRIPTOR *ppfd )
248 {
249   int where = 0;
250
251   ATTRIB_VAL( WGL_DRAW_TO_WINDOW_ARB, GL_TRUE );
252   ATTRIB_VAL( WGL_SUPPORT_OPENGL_ARB, GL_TRUE );
253   ATTRIB_VAL( WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB );
254
255   ATTRIB_VAL( WGL_COLOR_BITS_ARB, ppfd->cColorBits );
256   ATTRIB_VAL( WGL_ALPHA_BITS_ARB, ppfd->cAlphaBits );
257   ATTRIB_VAL( WGL_DEPTH_BITS_ARB, ppfd->cDepthBits );
258   ATTRIB_VAL( WGL_STENCIL_BITS_ARB, ppfd->cStencilBits );
259
260   ATTRIB_VAL( WGL_DOUBLE_BUFFER_ARB, ( fgState.DisplayMode & GLUT_DOUBLE ) != 0 );
261
262   if ( fgState.DisplayMode & GLUT_SRGB ) {
263     ATTRIB_VAL( WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB, TRUE );
264   }
265
266   ATTRIB_VAL( WGL_SAMPLE_BUFFERS_ARB, GL_TRUE );
267   ATTRIB_VAL( WGL_SAMPLES_ARB, fgState.SampleNumber );
268   ATTRIB( 0 );
269 }
270 #endif
271
272 GLboolean fgSetupPixelFormat( SFG_Window* window, GLboolean checkOnly,
273                               unsigned char layer_type )
274 {
275 #if defined(_WIN32_WCE)
276     return GL_TRUE;
277 #else
278     PIXELFORMATDESCRIPTOR pfd;
279     PIXELFORMATDESCRIPTOR* ppfd = &pfd;
280     int pixelformat;
281     HDC current_hDC;
282     GLboolean success;
283
284     if (checkOnly)
285       current_hDC = CreateDC(TEXT("DISPLAY"), NULL ,NULL ,NULL);
286     else
287       current_hDC = window->Window.pContext.Device;
288
289     fghFillPFD( ppfd, current_hDC, layer_type );
290     pixelformat = ChoosePixelFormat( current_hDC, ppfd );
291
292     /* windows hack for multismapling/sRGB */
293     if ( ( fgState.DisplayMode & GLUT_MULTISAMPLE ) ||
294          ( fgState.DisplayMode & GLUT_SRGB ) )
295     {        
296         HGLRC rc, rc_before=wglGetCurrentContext();
297         HWND hWnd;
298         HDC hDC, hDC_before=wglGetCurrentDC();
299         WNDCLASS wndCls;
300
301         /* create a dummy window */
302         ZeroMemory(&wndCls, sizeof(wndCls));
303         wndCls.lpfnWndProc = DefWindowProc;
304         wndCls.hInstance = fgDisplay.pDisplay.Instance;
305         wndCls.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
306         wndCls.lpszClassName = _T("FREEGLUT_dummy");
307         RegisterClass( &wndCls );
308
309         hWnd=CreateWindow(_T("FREEGLUT_dummy"), _T(""), WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW , 0,0,0,0, 0, 0, fgDisplay.pDisplay.Instance, 0 );
310         hDC=GetDC(hWnd);
311         SetPixelFormat( hDC, pixelformat, ppfd );
312
313         rc = wglCreateContext( hDC );
314         wglMakeCurrent(hDC, rc);
315
316         if ( fghIsExtensionSupported( hDC, "WGL_ARB_multisample" ) )
317         {
318             PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARBProc =
319               (PFNWGLCHOOSEPIXELFORMATARBPROC) wglGetProcAddress("wglChoosePixelFormatARB");
320             if ( wglChoosePixelFormatARBProc )
321             {
322                 int attributes[100];
323                 int iPixelFormat;
324                 BOOL bValid;
325                 float fAttributes[] = { 0, 0 };
326                 UINT numFormats;
327                 fghFillPixelFormatAttributes( attributes, ppfd );
328                 bValid = wglChoosePixelFormatARBProc(hDC, attributes, fAttributes, 1, &iPixelFormat, &numFormats);
329
330                 if ( bValid && numFormats > 0 )
331                 {
332                     pixelformat = iPixelFormat;
333                 }
334             }
335         }
336
337         wglMakeCurrent( hDC_before, rc_before);
338         wglDeleteContext(rc);
339         ReleaseDC(hWnd, hDC);
340         DestroyWindow(hWnd);
341         UnregisterClass(_T("FREEGLUT_dummy"), fgDisplay.pDisplay.Instance);
342     }
343
344     success = ( pixelformat != 0 ) && ( checkOnly || SetPixelFormat( current_hDC, pixelformat, ppfd ) );
345
346     if (checkOnly)
347         DeleteDC(current_hDC);
348
349     return success;
350 #endif /* defined(_WIN32_WCE) */
351 }
352
353
354
355 void fgPlatformSetWindow ( SFG_Window *window )
356 {
357     if ( window != fgStructure.CurrentWindow )
358     {
359         if( fgStructure.CurrentWindow )
360             ReleaseDC( fgStructure.CurrentWindow->Window.Handle,
361                        fgStructure.CurrentWindow->Window.pContext.Device );
362
363         if ( window )
364         {
365             window->Window.pContext.Device = GetDC( window->Window.Handle );
366             wglMakeCurrent(
367                 window->Window.pContext.Device,
368                 window->Window.Context
369             );
370         }
371     }
372 }
373
374
375 void fghGetDefaultWindowStyle(DWORD *flags)
376 {
377     if ( fgState.DisplayMode & GLUT_BORDERLESS )
378     {
379         /* no window decorations needed, no-op */
380     }
381     else if ( fgState.DisplayMode & GLUT_CAPTIONLESS )
382         /* only window decoration is a border, no title bar or buttons */
383         (*flags) |= WS_DLGFRAME;
384     else
385         /* window decoration are a border, title bar and buttons. */
386         (*flags) |= WS_OVERLAPPEDWINDOW;
387 }
388
389 /* Get window style and extended window style of a FreeGLUT window
390  * If the window pointer or the window handle is NULL, a fully
391  * decorated window (caption and border) is assumed.
392  */
393 void fghGetStyleFromWindow( const SFG_Window *window, DWORD *windowStyle, DWORD *windowExStyle )
394 {
395     if (window && window->Window.Handle)
396     {
397         *windowStyle   = GetWindowLong(window->Window.Handle, GWL_STYLE);
398         *windowExStyle = GetWindowLong(window->Window.Handle, GWL_EXSTYLE);
399     }
400     else
401     {
402         *windowStyle   = 0;
403         fghGetDefaultWindowStyle(windowStyle);
404         /* WindowExStyle==0 is fine/default, exStyle is currently only used for menu windows */
405         *windowExStyle = 0;
406     }
407 }
408
409 /* Computes position of corners of window Rect (outer position including
410  * decorations) based on the provided client rect and based on the style
411  * of the window in question.
412  * If posIsOutside is set to true, the input client Rect is taken to follow
413  * freeGLUT's window specification convention in which the top-left corner
414  * is at the outside of the window, while the size
415  * (rect.right-rect.left,rect.bottom-rect.top) is the size of the drawable
416  * area.
417  */
418 void fghComputeWindowRectFromClientArea_UseStyle( RECT *clientRect, const DWORD windowStyle, const DWORD windowExStyle, BOOL posIsOutside )
419 {
420     RECT windowRect   = {0,0,0,0};
421     CopyRect(&windowRect,clientRect);
422
423     /* Get rect including non-client area */
424     AdjustWindowRectEx(&windowRect,windowStyle,FALSE,windowExStyle);
425
426     /* Move window right and down by non-client area extent on left and top, if wanted */
427     if (posIsOutside)
428     {
429         windowRect.right   += clientRect->left-windowRect.left;
430         windowRect.bottom  += clientRect->top -windowRect.top;
431         windowRect.left     = clientRect->left;
432         windowRect.top      = clientRect->top;
433     }
434     
435     /* done, copy windowRect to output */
436     CopyRect(clientRect,&windowRect);
437 }
438
439 /* Computes position of corners of window Rect (outer position including
440  * decorations) based on the provided client rect and based on the style
441  * of the window in question. If the window pointer or the window handle
442  * is NULL, a fully decorated window (caption and border) is assumed.
443  * Furthermore, if posIsOutside is set to true, the input client Rect is
444  * taken to follow freeGLUT's window specification convention in which the
445  * top-left corner is at the outside of the window, while the size
446  * (rect.right-rect.left,rect.bottom-rect.top) is the size of the drawable
447  * area.
448 */
449 void fghComputeWindowRectFromClientArea_QueryWindow( RECT *clientRect, const SFG_Window *window, BOOL posIsOutside )
450 {
451     DWORD windowStyle = 0, windowExStyle = 0;
452     fghGetStyleFromWindow(window,&windowStyle,&windowExStyle);
453
454     fghComputeWindowRectFromClientArea_UseStyle(clientRect, windowStyle, windowExStyle, posIsOutside);
455 }
456
457 /* Gets the rect describing the client area (drawable area) of the
458  * specified window. Output is position of corners of client area (drawable area) on the screen.
459  * Does not touch clientRect if window pointer or window handle is NULL.
460  * (rect.right-rect.left,rect.bottom-rect.top) is the size of the drawable area.
461  */
462 void fghGetClientArea( RECT *clientRect, const SFG_Window *window )
463 {
464     POINT topLeftClient = {0,0};
465
466     freeglut_return_if_fail((window && window->Window.Handle));
467     
468     /* Get size of client rect */
469     GetClientRect(window->Window.Handle, clientRect);
470     /* Get position of top-left of client area on the screen */
471     ClientToScreen(window->Window.Handle,&topLeftClient);
472     /* Add top-left offset */
473     OffsetRect(clientRect,topLeftClient.x,topLeftClient.y);
474 }
475
476
477 #if(WINVER >= 0x500)
478 typedef struct
479 {
480       int *x;
481       int *y;
482       const char *name;
483 } m_proc_t;
484
485 static BOOL CALLBACK m_proc(HMONITOR mon,
486                             HDC hdc,
487                             LPRECT rect,
488                             LPARAM data)
489 {
490       m_proc_t *dp=(m_proc_t *)data;
491       MONITORINFOEX info;
492       BOOL res;
493       info.cbSize=sizeof(info);
494       res=GetMonitorInfo(mon,(LPMONITORINFO)&info);
495       if( res )
496       {
497           if( strcmp(dp->name,info.szDevice)==0 )
498           {
499               *(dp->x)=info.rcMonitor.left;
500               *(dp->y)=info.rcMonitor.top;
501               return FALSE;
502           }
503       }
504       return TRUE;
505 }
506
507 /* 
508  * this function returns the origin of the screen identified by
509  * fgDisplay.pDisplay.DisplayName, and 0 otherwise.
510  * This is used in fgOpenWindow to open the gamemode window on the screen
511  * identified by the -display command line argument. The function should
512  * not be called otherwise.
513  */
514
515 static void get_display_origin(int *xp,int *yp)
516 {
517     *xp = 0;
518     *yp = 0;
519
520     if( fgDisplay.pDisplay.DisplayName )
521     {
522         m_proc_t st;
523         st.x=xp;
524         st.y=yp;
525         st.name=fgDisplay.pDisplay.DisplayName;
526         EnumDisplayMonitors(0,0,m_proc,(LPARAM)&st);
527     }
528 }
529 #else
530 #pragma message( "-display parameter only works if compiled with WINVER >= 0x0500")
531
532 static void get_display_origin(int *xp,int *yp)
533 {
534     *xp = 0;
535     *yp = 0;
536
537     if( fgDisplay.pDisplay.DisplayName )
538     {
539         fgWarning( "for working -display support FreeGLUT must be compiled with WINVER >= 0x0500");
540     }
541 }
542 #endif
543
544
545
546 /*
547  * Opens a window. Requires a SFG_Window object created and attached
548  * to the freeglut structure. OpenGL context is created here.
549  */
550 void fgPlatformOpenWindow( SFG_Window* window, const char* title,
551                            GLboolean positionUse, int x, int y,
552                            GLboolean sizeUse, int w, int h,
553                            GLboolean gameMode, GLboolean isSubWindow )
554 {
555
556     WNDCLASS wc;
557     DWORD flags   = 0;
558     DWORD exFlags = 0;
559     ATOM atom;
560
561     /* Grab the window class we have registered on glutInit(): */
562     atom = GetClassInfo( fgDisplay.pDisplay.Instance, _T("FREEGLUT"), &wc );
563     FREEGLUT_INTERNAL_ERROR_EXIT ( atom, "Window Class Info Not Found",
564                                    "fgOpenWindow" );
565
566     /* Determine window style flags*/
567     if( gameMode )
568     {
569         FREEGLUT_INTERNAL_ERROR_EXIT ( window->Parent == NULL,
570                                        "Game mode being invoked on a subwindow",
571                                        "fgOpenWindow" );
572
573         /*
574          * Set the window creation flags appropriately to make the window
575          * entirely visible:
576          */
577         flags = WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_VISIBLE;
578     }
579     else
580     {
581         flags = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
582
583         /*
584          * There's a small difference between creating the top, child and
585          * menu windows
586          */
587         if ( window->IsMenu )
588         {
589             flags |= WS_POPUP;
590             exFlags |= WS_EX_TOOLWINDOW;
591         }
592 #if defined(_WIN32_WCE)
593         /* no decorations for windows CE */
594 #else
595         /* if this is not a subwindow (child), set its style based on the requested window decorations */
596         else if( window->Parent == NULL )
597             fghGetDefaultWindowStyle(&flags);
598 #endif
599         else
600             /* subwindows always have no decoration, but are marked as a child window to the OS */
601             flags |= WS_CHILD;
602     }
603
604     /* determine window size and position */
605     if( gameMode )
606     {
607         /* if in gamemode, query the origin of specified by the -display
608          * command line parameter (if any) and offset the upper-left corner
609          * of the window so we create the window on that screen.
610          * The -display argument doesn't do anything if not trying to enter
611          * gamemode.
612          */
613         int xoff=0, yoff=0;
614         get_display_origin(&xoff,&yoff);
615         x += xoff;
616         y += yoff;
617     }
618     if( !positionUse )
619     {
620         x = CW_USEDEFAULT;
621         y = CW_USEDEFAULT;
622     }
623     if( !sizeUse )
624     {
625         if( ! window->IsMenu )
626         {
627             w = CW_USEDEFAULT;
628             h = CW_USEDEFAULT;
629         }
630         else /* fail safe - Windows can make a window of size (0, 0) */
631             w = h = 300; /* default window size */
632     }
633     /* store requested client area width and height */
634     window->State.Width = w;
635     window->State.Height = h;
636
637 #if !defined(_WIN32_WCE)    /* no decorations for windows CE */
638     if( sizeUse )
639     {
640         RECT windowRect;
641         /*
642          * Update the window dimensions, taking the window decorations
643          * into account.  FreeGLUT is to create the window with the
644          * topleft outside corner at (x,y) and with client area
645          * dimensions (w,h).
646          * note: don't need to do this when w=h=CW_USEDEFAULT, so in the
647          * if( sizeUse ) here is convenient.
648          */
649         windowRect.left     = x;
650         windowRect.top      = y;
651         windowRect.right    = x+w;
652         windowRect.bottom   = y+h;
653
654         fghComputeWindowRectFromClientArea_UseStyle(&windowRect,flags,exFlags,TRUE);
655
656         /* NB: w and h are now width and height of window including non-client area! */
657         w = windowRect.right - windowRect.left;
658         h = windowRect.bottom- windowRect.top;
659     }
660 #endif /* !defined(_WIN32_WCE) */
661
662 #if defined(_WIN32_WCE)
663     {
664         wchar_t* wstr = fghWstrFromStr(title);
665
666         window->Window.Handle = CreateWindow(
667             _T("FREEGLUT"),
668             wstr,
669             WS_VISIBLE | WS_POPUP,
670             0,0, 240,320,
671             NULL,
672             NULL,
673             fgDisplay.pDisplay.Instance,
674             (LPVOID) window
675         );
676
677         free(wstr);
678
679         SHFullScreen(window->Window.Handle, SHFS_HIDESTARTICON);
680         SHFullScreen(window->Window.Handle, SHFS_HIDESIPBUTTON);
681         SHFullScreen(window->Window.Handle, SHFS_HIDETASKBAR);
682         MoveWindow(window->Window.Handle, 0, 0, 240, 320, TRUE);
683         ShowWindow(window->Window.Handle, SW_SHOW);
684         UpdateWindow(window->Window.Handle);
685     }
686 #else
687     window->Window.Handle = CreateWindowEx(
688         exFlags,
689         _T("FREEGLUT"),
690         title,
691         flags,
692         x, y, w, h,
693         (HWND) window->Parent == NULL ? NULL : window->Parent->Window.Handle,
694         (HMENU) NULL,
695         fgDisplay.pDisplay.Instance,
696         (LPVOID) window
697     );
698 #endif /* defined(_WIN32_WCE) */
699
700     if( !( window->Window.Handle ) )
701         fgError( "Failed to create a window (%s)!", title );
702
703     /* Store title */
704     {
705         window->State.pWState.WindowTitle = malloc (strlen(title) + 1);
706         strcpy(window->State.pWState.WindowTitle, title);
707     }
708
709 #if !defined(_WIN32_WCE)
710     /* Need to set requested style again, apparently Windows doesn't listen when requesting windows without title bar or borders */
711     SetWindowLong(window->Window.Handle, GWL_STYLE, flags);
712     SetWindowPos(window->Window.Handle, HWND_TOP, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
713 #endif /* defined(_WIN32_WCE) */
714
715     /* Make a menu window always on top - fix Feature Request 947118 */
716     if( window->IsMenu || gameMode )
717         SetWindowPos(
718                         window->Window.Handle,
719                         HWND_TOPMOST,
720                         0, 0, 0, 0,
721                         SWP_NOMOVE | SWP_NOSIZE
722                     );
723
724     /* Enable multitouch: additional flag TWF_FINETOUCH, TWF_WANTPALM */
725     #ifdef WM_TOUCH
726         if (fghRegisterTouchWindow == (pRegisterTouchWindow)0xDEADBEEF) 
727                         fghRegisterTouchWindow = (pRegisterTouchWindow)GetProcAddress(GetModuleHandle("user32"),"RegisterTouchWindow");
728                 if (fghRegisterTouchWindow)
729              fghRegisterTouchWindow( window->Window.Handle, TWF_FINETOUCH | TWF_WANTPALM );
730     #endif
731
732 #if defined(_WIN32_WCE)
733     ShowWindow( window->Window.Handle, SW_SHOW );
734 #else
735     ShowWindow( window->Window.Handle,
736                 fgState.ForceIconic ? SW_SHOWMINIMIZED : SW_SHOWNORMAL );
737 #endif /* defined(_WIN32_WCE) */
738
739     ShowCursor( TRUE );
740 }
741
742
743 void fgPlatformDisplayWindow ( SFG_Window *window )
744 {
745     /* This immediately generates a WM_PAINT message upon which we call the display callbacks to redraw the window */
746     RedrawWindow(
747         window->Window.Handle, NULL, NULL,
748         RDW_NOERASE | RDW_INTERNALPAINT | RDW_INVALIDATE | RDW_UPDATENOW
749         );
750 }
751
752
753 void fgPlatformReshapeWindow ( SFG_Window *window, int width, int height )
754 {
755     RECT windowRect;
756
757     /*
758      * HACK HACK HACK:
759      * Before we do anything else, check if this is a newly created window
760      * that did not have its windowStatus/visibility func called yet
761      * we do that on first paint, but because I want to keep the paint
762      * operation as lean as possible, we do it here. The first paint
763      * goes together with a first resize call before the display callback
764      * is called, so this is just in time. Shitty place to do it, but this
765      * is the only reliable way I can think of to call the callback upon
766      * first draw of the window.
767      * More broadly speaking, I know this is an ugly hack, but I'm not sure
768      * what else to do about it.  Depending on WM_ACTIVATE would not work
769      * as not all windows get this when you are opening multiple before the
770      * mainloop starts. WM_SHOWWINDOW looked like an interesting candidate,
771      * but it is generated and processed before glutCreate(Sub)Window
772      * returns, so no callback can yet be set on the window.
773      */
774     /* Check windowStatus/visibility func has been notified that window is visible (deferred from creation time to give user opportunity to register callbacks) */
775     if (!window->State.pWState.WindowFuncCalled)
776     {
777         fghNotifyWindowStatus(window);
778         window->State.pWState.WindowFuncCalled = GL_TRUE;
779     }
780
781     /*
782      * For windowed mode, get the current position of the
783      * window and resize taking the size of the frame
784      * decorations into account.
785      *
786      * Note on maximizing behavior of Windows: the resize borders are off
787      * the screen such that the client area extends all the way from the
788      * leftmost corner to the rightmost corner to maximize screen real
789      * estate. A caption is still shown however to allow interaction with
790      * the window controls. This is default behavior of Windows that
791      * FreeGLUT sticks with. To alter, one would have to check if
792      * WS_MAXIMIZE style is set when a resize event is triggered, and
793      * then manually correct the windowRect to put the borders back on
794      * screen.
795      */
796
797     /* "GetWindowRect" returns the pixel coordinates of the outside of the window */
798     GetWindowRect( window->Window.Handle, &windowRect );
799
800     /* Create rect in FreeGLUT format, (X,Y) topleft outside window, WxH of client area */
801     windowRect.right    = windowRect.left+width;
802     windowRect.bottom   = windowRect.top+height;
803
804     if (window->Parent == NULL)
805         /* get the window rect from this to feed to SetWindowPos, correct for window decorations */
806         fghComputeWindowRectFromClientArea_QueryWindow(&windowRect,window,TRUE);
807     else
808     {
809         /* correct rect for position client area of parent window
810          * (SetWindowPos input for child windows is in coordinates
811          * relative to the parent's client area).
812          * Child windows don't have decoration, so no need to correct
813          * for them.
814          */
815         RECT parentRect;
816         fghGetClientArea( &parentRect, window->Parent );
817         OffsetRect(&windowRect,-parentRect.left,-parentRect.top);
818     }
819     
820     /* Do the actual resizing */
821     SetWindowPos( window->Window.Handle,
822                   HWND_TOP,
823                   windowRect.left, windowRect.top,
824                   windowRect.right - windowRect.left,
825                   windowRect.bottom- windowRect.top,
826                   SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSENDCHANGING |
827                   SWP_NOZORDER
828     );
829
830     /* Set new width and height so we can test for that in WM_SIZE message handler and don't do anything if not needed */
831     window->State.Width  = width;
832     window->State.Height = height;
833 }
834
835
836 /*
837  * Closes a window, destroying the frame and OpenGL context
838  */
839 void fgPlatformCloseWindow( SFG_Window* window )
840 {
841     /* Make sure we don't close a window with current context active */
842     if( fgStructure.CurrentWindow == window )
843         wglMakeCurrent( NULL, NULL );
844
845     /*
846      * Step through the list of windows.  If the rendering context
847      * is not being used by another window, then we delete it.
848      */
849     {
850         int used = FALSE ;
851         SFG_Window *iter ;
852
853         for( iter = (SFG_Window *)fgStructure.Windows.First;
854              iter;
855              iter = (SFG_Window *)iter->Node.Next )
856         {
857             if( ( iter->Window.Context == window->Window.Context ) &&
858                 ( iter != window ) )
859                 used = TRUE;
860         }
861
862         if( ! used )
863             wglDeleteContext( window->Window.Context );
864     }
865
866     DestroyWindow( window->Window.Handle );
867
868     /* clean up copied title text(s) */
869     if (window->State.pWState.WindowTitle)
870         free(window->State.pWState.WindowTitle);
871     if (window->State.pWState.IconTitle)
872         free(window->State.pWState.IconTitle);
873 }
874
875
876
877 /*
878  * This function makes the current window visible
879  */
880 void fgPlatformGlutShowWindow( void )
881 {
882     ShowWindow( fgStructure.CurrentWindow->Window.Handle, SW_SHOW );
883 }
884
885 /*
886  * This function hides the current window
887  */
888 void fgPlatformGlutHideWindow( void )
889 {
890     ShowWindow( fgStructure.CurrentWindow->Window.Handle, SW_HIDE );
891 }
892
893 /*
894  * Iconify the current window (top-level windows only)
895  */
896 void fgPlatformGlutIconifyWindow( void )
897 {
898     SFG_Window *win = fgStructure.CurrentWindow;
899
900     /* Call on parent window */
901     while (win->Parent)
902         win = win->Parent;
903
904     /* Visibility status of window gets updated in the WM_SHOWWINDOW handler */
905     ShowWindow(win->Window.Handle, SW_MINIMIZE);
906 }
907
908 /*
909  * Set the current window's title
910  */
911 void fgPlatformGlutSetWindowTitle( const char* title )
912 {
913 #ifdef _WIN32_WCE
914     {
915         wchar_t* wstr = fghWstrFromStr(title);
916         SetWindowText( fgStructure.CurrentWindow->Window.Handle, wstr );
917         free(wstr);
918     }
919 #else
920     SetWindowText( fgStructure.CurrentWindow->Window.Handle, title );
921 #endif
922
923     /* Make copy of string to refer to later */
924     if (fgStructure.CurrentWindow->State.pWState.WindowTitle)
925         free(fgStructure.CurrentWindow->State.pWState.WindowTitle);
926     fgStructure.CurrentWindow->State.pWState.WindowTitle = strdup(title);
927 }
928
929 /*
930  * Set the current window's iconified title
931  */
932 void fgPlatformGlutSetIconTitle( const char* title )
933 {
934     /* Make copy of string to refer to later */
935     if (fgStructure.CurrentWindow->State.pWState.IconTitle)
936         free(fgStructure.CurrentWindow->State.pWState.IconTitle);
937     fgStructure.CurrentWindow->State.pWState.IconTitle = strdup(title);
938 }
939
940 /*
941  * Change the current window's position
942  */
943 void fgPlatformGlutPositionWindow( int x, int y )
944 {
945     RECT winRect;
946
947     /* "GetWindowRect" returns the pixel coordinates of the outside of the window */
948     GetWindowRect( fgStructure.CurrentWindow->Window.Handle, &winRect );
949     MoveWindow(
950         fgStructure.CurrentWindow->Window.Handle,
951         x,
952         y,
953         winRect.right - winRect.left,
954         winRect.bottom - winRect.top,
955         TRUE
956     );
957 }
958
959 /*
960  * Lowers the current window (by Z order change)
961  */
962 void fgPlatformGlutPushWindow( void )
963 {
964     SetWindowPos(
965         fgStructure.CurrentWindow->Window.Handle,
966         HWND_BOTTOM,
967         0, 0, 0, 0,
968         SWP_NOSIZE | SWP_NOMOVE
969     );
970 }
971
972 /*
973  * Raises the current window (by Z order change)
974  */
975 void fgPlatformGlutPopWindow( void )
976 {
977     SetWindowPos(
978         fgStructure.CurrentWindow->Window.Handle,
979         HWND_TOP,
980         0, 0, 0, 0,
981         SWP_NOSIZE | SWP_NOMOVE
982     );
983 }
984
985 /*
986  * Resize the current window so that it fits the whole screen
987  */
988 void fgPlatformGlutFullScreen( SFG_Window *win )
989 {
990 #if !defined(_WIN32_WCE) /* FIXME: what about WinCE */
991
992     if (glutGet(GLUT_FULL_SCREEN))
993     {
994         /*  Leave full screen state before entering fullscreen again (resizing?) */
995         glutLeaveFullScreen();
996     }
997
998     {
999 #if(WINVER >= 0x0500) /* Windows 2000 or later */
1000         RECT rect;
1001         HMONITOR hMonitor;
1002         MONITORINFO mi;
1003
1004         /* For fullscreen mode, first remove all window decoration
1005          * and set style to popup so it will overlap the taskbar
1006          * then force to maximize on the screen on which it has the most
1007          * overlap.
1008          */
1009
1010         
1011         /* save current window rect, style, exstyle and maximized state */
1012         win->State.pWState.OldMaximized = !!IsZoomed(win->Window.Handle);
1013         if (win->State.pWState.OldMaximized)
1014             /* We force the window into restored mode before going
1015              * fullscreen because Windows doesn't seem to hide the
1016              * taskbar if the window is in the maximized state.
1017              */
1018             SendMessage(win->Window.Handle, WM_SYSCOMMAND, SC_RESTORE, 0);
1019
1020         GetWindowRect( win->Window.Handle, &win->State.pWState.OldRect );
1021         win->State.pWState.OldStyle   = GetWindowLong(win->Window.Handle, GWL_STYLE);
1022         win->State.pWState.OldStyleEx = GetWindowLong(win->Window.Handle, GWL_EXSTYLE);
1023
1024         /* remove decorations from style */
1025         SetWindowLong(win->Window.Handle, GWL_STYLE,
1026                       win->State.pWState.OldStyle & ~(WS_CAPTION | WS_THICKFRAME));
1027         SetWindowLong(win->Window.Handle, GWL_EXSTYLE,
1028                       win->State.pWState.OldStyleEx & ~(WS_EX_DLGMODALFRAME |
1029                       WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE | WS_EX_STATICEDGE));
1030
1031         /* For fullscreen mode, find the monitor that is covered the most
1032          * by the window and get its rect as the resize target.
1033              */
1034         hMonitor= MonitorFromRect(&win->State.pWState.OldRect, MONITOR_DEFAULTTONEAREST);
1035         mi.cbSize = sizeof(mi);
1036         GetMonitorInfo(hMonitor, &mi);
1037         rect = mi.rcMonitor;
1038 #else   /* if (WINVER >= 0x0500) */
1039         RECT rect;
1040
1041         /* For fullscreen mode, force the top-left corner to 0,0
1042          * and adjust the window rectangle so that the client area
1043          * covers the whole screen.
1044          */
1045
1046         rect.left   = 0;
1047         rect.top    = 0;
1048         rect.right  = fgDisplay.ScreenWidth;
1049         rect.bottom = fgDisplay.ScreenHeight;
1050
1051         AdjustWindowRect ( &rect, WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS |
1052                                   WS_CLIPCHILDREN, FALSE );
1053 #endif  /* (WINVER >= 0x0500) */
1054
1055         /*
1056          * then resize window
1057          * SWP_NOACTIVATE     Do not activate the window
1058          * SWP_NOOWNERZORDER  Do not change position in z-order
1059          * SWP_NOSENDCHANGING Suppress WM_WINDOWPOSCHANGING message
1060          * SWP_NOZORDER       Retains the current Z order (ignore 2nd param)
1061          */
1062         SetWindowPos( fgStructure.CurrentWindow->Window.Handle,
1063                       HWND_TOP,
1064                       rect.left,
1065                       rect.top,
1066                       rect.right  - rect.left,
1067                       rect.bottom - rect.top,
1068                       SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSENDCHANGING |
1069                       SWP_NOZORDER
1070                     );
1071
1072         win->State.IsFullscreen = GL_TRUE;
1073     }
1074 #endif
1075 }
1076
1077 /*
1078  * If we are fullscreen, resize the current window back to its original size
1079  */
1080 void fgPlatformGlutLeaveFullScreen( SFG_Window *win )
1081 {
1082 #if !defined(_WIN32_WCE) /* FIXME: what about WinCE */
1083     if (!glutGet(GLUT_FULL_SCREEN))
1084     {
1085         /* nothing to do */
1086         return;
1087     }
1088
1089     /* restore style of window before making it fullscreen */
1090     SetWindowLong(win->Window.Handle, GWL_STYLE, win->State.pWState.OldStyle);
1091     SetWindowLong(win->Window.Handle, GWL_EXSTYLE, win->State.pWState.OldStyleEx);
1092
1093     /* Then resize */
1094     SetWindowPos(win->Window.Handle,
1095         HWND_TOP,
1096         win->State.pWState.OldRect.left,
1097         win->State.pWState.OldRect.top,
1098         win->State.pWState.OldRect.right  - win->State.pWState.OldRect.left,
1099         win->State.pWState.OldRect.bottom - win->State.pWState.OldRect.top,
1100         SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSENDCHANGING |
1101         SWP_NOZORDER
1102         );
1103
1104     if (win->State.pWState.OldMaximized)
1105         SendMessage(win->Window.Handle, WM_SYSCOMMAND, SC_MAXIMIZE, 0);
1106
1107     win->State.IsFullscreen = GL_FALSE;
1108 #endif
1109 }
1110
1111 /*
1112  * Toggle the window's full screen state.
1113  */
1114 void fgPlatformGlutFullScreenToggle( SFG_Window *win )
1115 {
1116     if (!win->State.IsFullscreen)
1117         glutFullScreen();
1118     else
1119         glutLeaveFullScreen();
1120 }
1121
1122
1123 /* -- PLATFORM-SPECIFIC INTERFACE FUNCTION -------------------------------------------------- */
1124
1125 int FGAPIENTRY __glutCreateWindowWithExit( const char *title, void (__cdecl *exit_function)(int) )
1126 {
1127   __glutExitFunc = exit_function;
1128   return glutCreateWindow( title );
1129 }
1130