5fedea6e847c8742221b3041bb4bd64ef6a45e43
[occt.git] / src / OpenGl / OpenGl_Window.cxx
1 // Created on: 2011-09-20
2 // Created by: Sergey ZERCHANINOV
3 // Copyright (c) 2011-2014 OPEN CASCADE SAS
4 //
5 // This file is part of Open CASCADE Technology software library.
6 //
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
12 //
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
15
16 #include <OpenGl_GlCore12.hxx>
17 #include <InterfaceGraphic.hxx>
18
19 #include <OpenGl_Context.hxx>
20 #include <OpenGl_GraphicDriver.hxx>
21 #include <OpenGl_Window.hxx>
22 #include <OpenGl_Utils.hxx>
23
24 #include <Aspect_GraphicDeviceDefinitionError.hxx>
25 #include <TCollection_AsciiString.hxx>
26 #include <TCollection_ExtendedString.hxx>
27
28 #if defined(HAVE_EGL) || defined(__ANDROID__)
29   #include <EGL/egl.h>
30 #endif
31
32 IMPLEMENT_STANDARD_HANDLE(OpenGl_Window,MMgt_TShared)
33 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Window,MMgt_TShared)
34
35 #if !defined(__APPLE__) || defined(MACOSX_USE_GLX)
36
37 namespace
38 {
39   static const TEL_COLOUR THE_DEFAULT_BG_COLOR = { { 0.F, 0.F, 0.F, 1.F } };
40
41 #if defined(HAVE_EGL) || defined(__ANDROID__)
42   //
43 #elif defined(_WIN32)
44
45   // WGL_ARB_pixel_format
46 #ifndef WGL_NUMBER_PIXEL_FORMATS_ARB
47   #define WGL_NUMBER_PIXEL_FORMATS_ARB            0x2000
48   #define WGL_DRAW_TO_WINDOW_ARB                  0x2001
49   #define WGL_DRAW_TO_BITMAP_ARB                  0x2002
50   #define WGL_ACCELERATION_ARB                    0x2003
51   #define WGL_NEED_PALETTE_ARB                    0x2004
52   #define WGL_NEED_SYSTEM_PALETTE_ARB             0x2005
53   #define WGL_SWAP_LAYER_BUFFERS_ARB              0x2006
54   #define WGL_SWAP_METHOD_ARB                     0x2007
55   #define WGL_NUMBER_OVERLAYS_ARB                 0x2008
56   #define WGL_NUMBER_UNDERLAYS_ARB                0x2009
57   #define WGL_TRANSPARENT_ARB                     0x200A
58   #define WGL_TRANSPARENT_RED_VALUE_ARB           0x2037
59   #define WGL_TRANSPARENT_GREEN_VALUE_ARB         0x2038
60   #define WGL_TRANSPARENT_BLUE_VALUE_ARB          0x2039
61   #define WGL_TRANSPARENT_ALPHA_VALUE_ARB         0x203A
62   #define WGL_TRANSPARENT_INDEX_VALUE_ARB         0x203B
63   #define WGL_SHARE_DEPTH_ARB                     0x200C
64   #define WGL_SHARE_STENCIL_ARB                   0x200D
65   #define WGL_SHARE_ACCUM_ARB                     0x200E
66   #define WGL_SUPPORT_GDI_ARB                     0x200F
67   #define WGL_SUPPORT_OPENGL_ARB                  0x2010
68   #define WGL_DOUBLE_BUFFER_ARB                   0x2011
69   #define WGL_STEREO_ARB                          0x2012
70   #define WGL_PIXEL_TYPE_ARB                      0x2013
71   #define WGL_COLOR_BITS_ARB                      0x2014
72   #define WGL_RED_BITS_ARB                        0x2015
73   #define WGL_RED_SHIFT_ARB                       0x2016
74   #define WGL_GREEN_BITS_ARB                      0x2017
75   #define WGL_GREEN_SHIFT_ARB                     0x2018
76   #define WGL_BLUE_BITS_ARB                       0x2019
77   #define WGL_BLUE_SHIFT_ARB                      0x201A
78   #define WGL_ALPHA_BITS_ARB                      0x201B
79   #define WGL_ALPHA_SHIFT_ARB                     0x201C
80   #define WGL_ACCUM_BITS_ARB                      0x201D
81   #define WGL_ACCUM_RED_BITS_ARB                  0x201E
82   #define WGL_ACCUM_GREEN_BITS_ARB                0x201F
83   #define WGL_ACCUM_BLUE_BITS_ARB                 0x2020
84   #define WGL_ACCUM_ALPHA_BITS_ARB                0x2021
85   #define WGL_DEPTH_BITS_ARB                      0x2022
86   #define WGL_STENCIL_BITS_ARB                    0x2023
87   #define WGL_AUX_BUFFERS_ARB                     0x2024
88
89   #define WGL_NO_ACCELERATION_ARB                 0x2025
90   #define WGL_GENERIC_ACCELERATION_ARB            0x2026
91   #define WGL_FULL_ACCELERATION_ARB               0x2027
92
93   #define WGL_SWAP_EXCHANGE_ARB                   0x2028
94   #define WGL_SWAP_COPY_ARB                       0x2029
95   #define WGL_SWAP_UNDEFINED_ARB                  0x202A
96
97   #define WGL_TYPE_RGBA_ARB                       0x202B
98   #define WGL_TYPE_COLORINDEX_ARB                 0x202C
99 #endif // WGL_NUMBER_PIXEL_FORMATS_ARB
100
101   // WGL_ARB_create_context_profile
102 #ifndef WGL_CONTEXT_MAJOR_VERSION_ARB
103   #define WGL_CONTEXT_MAJOR_VERSION_ARB           0x2091
104   #define WGL_CONTEXT_MINOR_VERSION_ARB           0x2092
105   #define WGL_CONTEXT_LAYER_PLANE_ARB             0x2093
106   #define WGL_CONTEXT_FLAGS_ARB                   0x2094
107   #define WGL_CONTEXT_PROFILE_MASK_ARB            0x9126
108
109   // WGL_CONTEXT_FLAGS bits
110   #define WGL_CONTEXT_DEBUG_BIT_ARB               0x0001
111   #define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB  0x0002
112
113   // WGL_CONTEXT_PROFILE_MASK_ARB bits
114   #define WGL_CONTEXT_CORE_PROFILE_BIT_ARB          0x00000001
115   #define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
116 #endif // WGL_CONTEXT_MAJOR_VERSION_ARB
117
118   static LRESULT CALLBACK wndProcDummy (HWND theWin, UINT theMsg, WPARAM theParamW, LPARAM theParamL)
119   {
120     return DefWindowProcW (theWin, theMsg, theParamW, theParamL);
121   }
122 #else
123   static Bool WaitForNotify (Display* theDisp, XEvent* theEv, char* theArg)
124   {
125     return (theEv->type == MapNotify) && (theEv->xmap.window == (Window )theArg);
126   }
127 #endif
128
129 }
130
131 // =======================================================================
132 // function : OpenGl_Window
133 // purpose  :
134 // =======================================================================
135 OpenGl_Window::OpenGl_Window (const Handle(OpenGl_GraphicDriver)& theDriver,
136                               const CALL_DEF_WINDOW&        theCWindow,
137                               Aspect_RenderingContext       theGContext,
138                               const Handle(OpenGl_Caps)&    theCaps,
139                               const Handle(OpenGl_Context)& theShareCtx)
140 : myGlContext (new OpenGl_Context (theCaps)),
141   myOwnGContext (theGContext == 0),
142   myWidth   (theCWindow.dx),
143   myHeight  (theCWindow.dy),
144   myBgColor (THE_DEFAULT_BG_COLOR)
145 {
146   myBgColor.rgb[0] = theCWindow.Background.r;
147   myBgColor.rgb[1] = theCWindow.Background.g;
148   myBgColor.rgb[2] = theCWindow.Background.b;
149
150   Standard_Boolean isCoreProfile = Standard_False;
151
152 #if defined(HAVE_EGL) || defined(__ANDROID__)
153   EGLDisplay anEglDisplay = (EGLDisplay )theDriver->getRawGlDisplay();
154   EGLContext anEglContext = (EGLContext )theDriver->getRawGlContext();
155   EGLConfig  anEglConfig  = (EGLConfig  )theDriver->getRawGlConfig();
156   if (anEglDisplay == EGL_NO_DISPLAY
157    || anEglContext == EGL_NO_CONTEXT
158    || anEglConfig == NULL)
159   {
160     Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window, EGL does not provide compatible configurations!");
161     return;
162   }
163
164   EGLSurface anEglSurf = EGL_NO_SURFACE;
165   if (theGContext == (EGLContext )EGL_NO_CONTEXT)
166   {
167     // create new surface
168     anEglSurf = eglCreateWindowSurface (anEglDisplay, anEglConfig, (EGLNativeWindowType )theCWindow.XWindow, NULL);
169     if (anEglSurf == EGL_NO_SURFACE)
170     {
171       Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window, EGL is unable to create surface for window!");
172       return;
173     }
174   }
175   else if (theGContext != anEglContext)
176   {
177     Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window, EGL is used in unsupported combination!");
178     return;
179   }
180   else
181   {
182     anEglSurf = eglGetCurrentSurface(EGL_DRAW);
183     if (anEglSurf == EGL_NO_SURFACE)
184     {
185       Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window, EGL is unable to retrieve current surface!");
186       return;
187     }
188   }
189
190   myGlContext->Init ((Aspect_Drawable )anEglSurf, (Aspect_Display )anEglDisplay, (Aspect_RenderingContext )anEglContext, isCoreProfile);
191 #elif defined(_WIN32)
192   (void )theDriver;
193   HWND  aWindow   = (HWND )theCWindow.XWindow;
194   HDC   aWindowDC = GetDC (aWindow);
195   HGLRC aGContext = (HGLRC )theGContext;
196
197   PIXELFORMATDESCRIPTOR aPixelFrmt;
198   memset (&aPixelFrmt, 0, sizeof(aPixelFrmt));
199   aPixelFrmt.nSize        = sizeof(PIXELFORMATDESCRIPTOR);
200   aPixelFrmt.nVersion     = 1;
201   aPixelFrmt.dwFlags      = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
202   aPixelFrmt.iPixelType   = PFD_TYPE_RGBA;
203   aPixelFrmt.cColorBits   = 24;
204   aPixelFrmt.cDepthBits   = 24;
205   aPixelFrmt.cStencilBits = 8;
206   aPixelFrmt.iLayerType   = PFD_MAIN_PLANE;
207   if (theCaps->contextStereo)
208   {
209     aPixelFrmt.dwFlags |= PFD_STEREO;
210   }
211
212   int aPixelFrmtId = ChoosePixelFormat (aWindowDC, &aPixelFrmt);
213
214   // in case of failure try without stereo if any
215   const Standard_Boolean hasStereo = aPixelFrmtId != 0 && theCaps->contextStereo;
216   if (aPixelFrmtId == 0 && theCaps->contextStereo)
217   {
218     TCollection_ExtendedString aMsg ("OpenGl_Window::CreateWindow: "
219                                      "ChoosePixelFormat is unable to find stereo supported pixel format. "
220                                      "Choosing similar non stereo format.");
221     myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
222                               GL_DEBUG_TYPE_OTHER_ARB,
223                               0, GL_DEBUG_SEVERITY_HIGH_ARB, aMsg);
224
225     aPixelFrmt.dwFlags &= ~PFD_STEREO;
226     aPixelFrmtId = ChoosePixelFormat (aWindowDC, &aPixelFrmt);
227   }
228
229   if (aPixelFrmtId == 0)
230   {
231     ReleaseDC (aWindow, aWindowDC);
232
233     TCollection_AsciiString aMsg ("OpenGl_Window::CreateWindow: ChoosePixelFormat failed. Error code: ");
234     aMsg += (int )GetLastError();
235     Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
236     return;
237   }
238
239   DescribePixelFormat (aWindowDC, aPixelFrmtId, sizeof(aPixelFrmt), &aPixelFrmt);
240
241   HGLRC aSlaveCtx = !theShareCtx.IsNull() ? (HGLRC )theShareCtx->myGContext : NULL;
242   if (aGContext == NULL)
243   {
244     // create temporary context to retrieve advanced context creation procedures
245     HMODULE aModule = GetModuleHandleW(NULL);
246     WNDCLASSW aClass; memset (&aClass, 0, sizeof(aClass));
247     aClass.style         = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
248     aClass.lpfnWndProc   = wndProcDummy;
249     aClass.hInstance     = aModule;
250     aClass.lpszClassName = L"OpenGl_WindowTmp";
251     HWND  aWinTmp     = NULL;
252     HDC   aDevCtxTmp  = NULL;
253     HGLRC aRendCtxTmp = NULL;
254     if ((!theCaps->contextDebug && !theCaps->contextNoAccel && theCaps->contextCompatible)
255      || RegisterClassW (&aClass) == 0)
256     {
257       aClass.lpszClassName = NULL;
258     }
259     if (aClass.lpszClassName != NULL)
260     {
261       DWORD anExStyle = WS_EX_TOOLWINDOW | WS_EX_WINDOWEDGE;
262     #if (_WIN32_WINNT >= 0x0500)
263       anExStyle |= WS_EX_NOACTIVATE;
264     #endif
265       aWinTmp = CreateWindowExW(anExStyle,
266                                 aClass.lpszClassName, L"OpenGl_WindowTmp",
267                                 WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_DISABLED,
268                                 2, 2, 4, 4,
269                                 NULL, NULL, aModule, NULL);
270     }
271     if (aWinTmp != NULL)
272     {
273       aDevCtxTmp = GetDC (aWinTmp);
274       SetPixelFormat (aDevCtxTmp, aPixelFrmtId, &aPixelFrmt);
275       aRendCtxTmp = wglCreateContext (aDevCtxTmp);
276     }
277
278     typedef BOOL (WINAPI *wglChoosePixelFormatARB_t)(HDC           theDevCtx,
279                                                      const int*    theIntAttribs,
280                                                      const float*  theFloatAttribs,
281                                                      unsigned int  theMaxFormats,
282                                                      int*          theFormatsOut,
283                                                      unsigned int* theNumFormatsOut);
284     typedef HGLRC (WINAPI *wglCreateContextAttribsARB_t)(HDC        theDevCtx,
285                                                          HGLRC      theShareContext,
286                                                          const int* theAttribs);
287     wglChoosePixelFormatARB_t    aChoosePixProc = NULL;
288     wglCreateContextAttribsARB_t aCreateCtxProc = NULL;
289     if (aRendCtxTmp != NULL)
290     {
291       wglMakeCurrent (aDevCtxTmp, aRendCtxTmp);
292
293       typedef const char* (WINAPI *wglGetExtensionsStringARB_t)(HDC theDeviceContext);
294       wglGetExtensionsStringARB_t aGetExtensions = (wglGetExtensionsStringARB_t  )wglGetProcAddress ("wglGetExtensionsStringARB");
295       const char* aWglExts = (aGetExtensions != NULL) ? aGetExtensions (wglGetCurrentDC()) : NULL;
296       if (OpenGl_Context::CheckExtension (aWglExts, "WGL_ARB_pixel_format"))
297       {
298         aChoosePixProc = (wglChoosePixelFormatARB_t    )wglGetProcAddress ("wglChoosePixelFormatARB");
299       }
300       if (OpenGl_Context::CheckExtension (aWglExts, "WGL_ARB_create_context_profile"))
301       {
302         aCreateCtxProc = (wglCreateContextAttribsARB_t )wglGetProcAddress ("wglCreateContextAttribsARB");
303       }
304     }
305
306     // choose extended pixel format
307     if (aChoosePixProc != NULL)
308     {
309       const int aPixAttribs[] =
310       {
311         WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
312         WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
313         WGL_DOUBLE_BUFFER_ARB,  GL_TRUE,
314         WGL_STEREO_ARB,         hasStereo ? GL_TRUE : GL_FALSE,
315         WGL_PIXEL_TYPE_ARB,     WGL_TYPE_RGBA_ARB,
316         //WGL_SAMPLE_BUFFERS_ARB, 1,
317         //WGL_SAMPLES_ARB,        8,
318         WGL_COLOR_BITS_ARB,     24,
319         WGL_DEPTH_BITS_ARB,     24,
320         WGL_STENCIL_BITS_ARB,   8,
321         WGL_ACCELERATION_ARB,   theCaps->contextNoAccel ? WGL_NO_ACCELERATION_ARB : WGL_FULL_ACCELERATION_ARB,
322         0, 0,
323       };
324       unsigned int aFrmtsNb = 0;
325       aChoosePixProc (aWindowDC, aPixAttribs, NULL, 1, &aPixelFrmtId, &aFrmtsNb);
326     }
327
328     // setup pixel format - may be set only once per window
329     if (!SetPixelFormat (aWindowDC, aPixelFrmtId, &aPixelFrmt))
330     {
331       ReleaseDC (aWindow, aWindowDC);
332
333       TCollection_AsciiString aMsg("OpenGl_Window::CreateWindow: SetPixelFormat failed. Error code: ");
334       aMsg += (int )GetLastError();
335       Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
336       return;
337     }
338
339     // create GL context with extra options
340     if (aCreateCtxProc != NULL)
341     {
342       if (!theCaps->contextCompatible)
343       {
344         int aCoreCtxAttribs[] =
345         {
346           WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
347           WGL_CONTEXT_MINOR_VERSION_ARB, 2,
348           WGL_CONTEXT_PROFILE_MASK_ARB,  WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
349           WGL_CONTEXT_FLAGS_ARB,         theCaps->contextDebug ? WGL_CONTEXT_DEBUG_BIT_ARB : 0,
350           0, 0
351         };
352
353         // Try to create the core profile of highest OpenGL version supported by OCCT
354         // (this will be done automatically by some drivers when requesting 3.2,
355         //  but some will not (e.g. AMD Catalyst) since WGL_ARB_create_context_profile specification allows both implementations).
356         for (int aLowVer4 = 5; aLowVer4 >= 0 && aGContext == NULL; --aLowVer4)
357         {
358           aCoreCtxAttribs[1] = 4;
359           aCoreCtxAttribs[3] = aLowVer4;
360           aGContext = aCreateCtxProc (aWindowDC, aSlaveCtx, aCoreCtxAttribs);
361         }
362         for (int aLowVer3 = 3; aLowVer3 >= 2 && aGContext == NULL; --aLowVer3)
363         {
364           aCoreCtxAttribs[1] = 3;
365           aCoreCtxAttribs[3] = aLowVer3;
366           aGContext = aCreateCtxProc (aWindowDC, aSlaveCtx, aCoreCtxAttribs);
367         }
368         isCoreProfile = aGContext != NULL;
369       }
370
371       if (aGContext == NULL)
372       {
373         int aCtxAttribs[] =
374         {
375           // Beware! NVIDIA drivers reject context creation when WGL_CONTEXT_PROFILE_MASK_ARB are specified
376           // but not WGL_CONTEXT_MAJOR_VERSION_ARB/WGL_CONTEXT_MINOR_VERSION_ARB.
377           //WGL_CONTEXT_PROFILE_MASK_ARB,  WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,
378           WGL_CONTEXT_FLAGS_ARB,         theCaps->contextDebug ? WGL_CONTEXT_DEBUG_BIT_ARB : 0,
379           0, 0
380         };
381         isCoreProfile = Standard_False;
382         aGContext = aCreateCtxProc (aWindowDC, aSlaveCtx, aCtxAttribs);
383
384         if (aGContext != NULL
385         && !theCaps->contextCompatible)
386         {
387           TCollection_ExtendedString aMsg("OpenGl_Window::CreateWindow: core profile creation failed.");
388           myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB, GL_DEBUG_TYPE_PORTABILITY_ARB, 0, GL_DEBUG_SEVERITY_LOW_ARB, aMsg);
389         }
390       }
391
392       if (aGContext != NULL)
393       {
394         aSlaveCtx = NULL;
395       }
396     }
397
398     if (aRendCtxTmp != NULL)
399     {
400       wglDeleteContext (aRendCtxTmp);
401     }
402     if (aDevCtxTmp != NULL)
403     {
404       ReleaseDC (aWinTmp, aDevCtxTmp);
405     }
406     if (aWinTmp != NULL)
407     {
408       DestroyWindow (aWinTmp);
409     }
410     if (aClass.lpszClassName != NULL)
411     {
412       UnregisterClassW (aClass.lpszClassName, aModule);
413     }
414
415     if (aGContext == NULL)
416     {
417       // create context using obsolete functionality
418       aGContext = wglCreateContext (aWindowDC);
419     }
420     if (aGContext == NULL)
421     {
422       ReleaseDC (aWindow, aWindowDC);
423
424       TCollection_AsciiString aMsg ("OpenGl_Window::CreateWindow: wglCreateContext failed. Error code: ");
425       aMsg += (int )GetLastError();
426       Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
427       return;
428     }
429   }
430
431   // all GL context within one OpenGl_GraphicDriver should be shared!
432   if (aSlaveCtx != NULL && wglShareLists (aSlaveCtx, aGContext) != TRUE)
433   {
434     TCollection_AsciiString aMsg ("OpenGl_Window::CreateWindow: wglShareLists failed. Error code: ");
435     aMsg += (int )GetLastError();
436     Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
437     return;
438   }
439
440   myGlContext->Init ((Aspect_Handle )aWindow, (Aspect_Handle )aWindowDC, (Aspect_RenderingContext )aGContext, isCoreProfile);
441 #else
442   Window aParent = (Window )theCWindow.XWindow;
443   Window aWindow = 0;
444
445   Display*   aDisp     = theDriver->GetDisplayConnection()->GetDisplay();
446   GLXContext aGContext = (GLXContext )theGContext;
447
448   XWindowAttributes wattr;
449   XGetWindowAttributes (aDisp, aParent, &wattr);
450   const int scr = DefaultScreen (aDisp);
451
452   XVisualInfo* aVis = NULL;
453   {
454     unsigned long aVisInfoMask = VisualIDMask | VisualScreenMask;
455     XVisualInfo aVisInfo;
456     aVisInfo.visualid = wattr.visual->visualid;
457     aVisInfo.screen   = scr;
458     int aNbItems;
459     aVis = XGetVisualInfo (aDisp, aVisInfoMask, &aVisInfo, &aNbItems);
460   }
461
462   if (!myOwnGContext)
463   {
464     if (aVis != NULL)
465     {
466       Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: XGetVisualInfo failed.");
467       return;
468     }
469
470     aWindow = aParent;
471   }
472   else
473   {
474   #if defined(__linux) || defined(Linux) || defined(__APPLE__)
475     if (aVis != NULL)
476     {
477       // check Visual for OpenGl context's parameters compatibility
478       int isGl = 0, isDoubleBuffer = 0, isRGBA = 0, isStereo = 0;
479       int aDepthSize = 0, aStencilSize = 0;
480
481       if (glXGetConfig (aDisp, aVis, GLX_USE_GL, &isGl) != 0)
482         isGl = 0;
483
484       if (glXGetConfig (aDisp, aVis, GLX_RGBA, &isRGBA) != 0)
485         isRGBA = 0;
486
487       if (glXGetConfig (aDisp, aVis, GLX_DOUBLEBUFFER, &isDoubleBuffer) != 0)
488         isDoubleBuffer = 0;
489
490       if (glXGetConfig (aDisp, aVis, GLX_STEREO, &isStereo) != 0)
491         isStereo = 0;
492
493       if (glXGetConfig (aDisp, aVis, GLX_DEPTH_SIZE, &aDepthSize) != 0)
494         aDepthSize = 0;
495
496       if (glXGetConfig (aDisp, aVis, GLX_STENCIL_SIZE, &aStencilSize) != 0)
497         aStencilSize = 0;
498
499       if (!isGl || !aDepthSize || !isRGBA  || !aStencilSize ||
500           (isDoubleBuffer ? 1 : 0) != 1 ||
501           (isStereo       ? 1 : 0) != (theCaps->contextStereo ? 1 : 0))
502       {
503         XFree (aVis);
504         aVis = NULL;
505       }
506     }
507   #endif
508
509     if (aVis == NULL)
510     {
511       int anIter = 0;
512       int anAttribs[13];
513       anAttribs[anIter++] = GLX_RGBA;
514
515       anAttribs[anIter++] = GLX_DEPTH_SIZE;
516       anAttribs[anIter++] = 1;
517
518       anAttribs[anIter++] = GLX_STENCIL_SIZE;
519       anAttribs[anIter++] = 1;
520
521       anAttribs[anIter++] = GLX_RED_SIZE;
522       anAttribs[anIter++] = (wattr.depth <= 8) ? 0 : 1;
523
524       anAttribs[anIter++] = GLX_GREEN_SIZE;
525       anAttribs[anIter++] = (wattr.depth <= 8) ? 0 : 1;
526
527       anAttribs[anIter++] = GLX_BLUE_SIZE;
528       anAttribs[anIter++] = (wattr.depth <= 8) ? 0 : 1;
529
530       anAttribs[anIter++] = GLX_DOUBLEBUFFER;
531
532       // warning: this flag may be set to None, so it need to be last in anAttribs
533       Standard_Integer aStereoFlagPos = anIter;
534       if (theCaps->contextStereo)
535         anAttribs[anIter++] = GLX_STEREO;
536
537       anAttribs[anIter++] = None;
538
539       aVis = glXChooseVisual (aDisp, scr, anAttribs);
540
541       // in case of failure try without stereo if any
542       if (aVis == NULL && theCaps->contextStereo)
543       {
544         TCollection_ExtendedString aMsg ("OpenGl_Window::CreateWindow: "
545                                          "glXChooseVisual is unable to find stereo supported pixel format. "
546                                          "Choosing similar non stereo format.");
547         myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
548                                   GL_DEBUG_TYPE_OTHER_ARB,
549                                   0, GL_DEBUG_SEVERITY_HIGH_ARB, aMsg);
550
551         anAttribs[aStereoFlagPos] = None;
552         aVis = glXChooseVisual (aDisp, scr, anAttribs);
553       }
554
555       if (aVis == NULL)
556       {
557         Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: glXChooseVisual failed.");
558         return;
559       }
560     }
561
562     if (!theShareCtx.IsNull())
563     {
564       // ctx est une copie du previous
565       aGContext = glXCreateContext (aDisp, aVis, (GLXContext )theShareCtx->myGContext, GL_TRUE);
566     }
567     else
568     {
569       aGContext = glXCreateContext (aDisp, aVis, NULL, GL_TRUE);
570     }
571
572     if (!aGContext)
573     {
574       Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: glXCreateContext failed.");
575       return;
576     }
577
578     Colormap cmap = XCreateColormap (aDisp, aParent, aVis->visual, AllocNone);
579
580     XColor color;
581     color.red   = (unsigned short) (myBgColor.rgb[0] * 0xFFFF);
582     color.green = (unsigned short) (myBgColor.rgb[1] * 0xFFFF);
583     color.blue  = (unsigned short) (myBgColor.rgb[2] * 0xFFFF);
584     color.flags = DoRed | DoGreen | DoBlue;
585     XAllocColor (aDisp, cmap, &color);
586
587     XSetWindowAttributes cwa;
588     cwa.colormap         = cmap;
589     cwa.event_mask       = StructureNotifyMask;
590     cwa.border_pixel     = color.pixel;
591     cwa.background_pixel = color.pixel;
592
593     if (aVis->visualid == wattr.visual->visualid)
594     {
595       aWindow = aParent;
596     }
597     else
598     {
599       unsigned long mask = CWBackPixel | CWColormap | CWBorderPixel | CWEventMask;
600       aWindow = XCreateWindow (aDisp, aParent, 0, 0, myWidth, myHeight, 0/*bw*/, aVis->depth, InputOutput, aVis->visual, mask, &cwa);
601     }
602
603     XSetWindowBackground (aDisp, aWindow, cwa.background_pixel);
604     XClearWindow (aDisp, aWindow);
605
606     if (aWindow != aParent)
607     {
608       XEvent anEvent;
609       XMapWindow (aDisp, aWindow);
610       XIfEvent (aDisp, &anEvent, WaitForNotify, (char* )aWindow);
611     }
612   }
613
614   myGlContext->Init ((Aspect_Drawable )aWindow, (Aspect_Display )aDisp, (Aspect_RenderingContext )aGContext, isCoreProfile);
615 #endif
616   myGlContext->Share (theShareCtx);
617
618   Init();
619 }
620
621 // =======================================================================
622 // function : ~OpenGl_Window
623 // purpose  :
624 // =======================================================================
625 OpenGl_Window::~OpenGl_Window()
626 {
627   if (!myOwnGContext
628    ||  myGlContext.IsNull())
629   {
630     myGlContext.Nullify();
631     return;
632   }
633
634   // release "GL" context if it is owned by window
635   // Mesa implementation can fail to destroy GL context if it set for current thread.
636   // It should be safer to unset thread GL context before its destruction.
637 #if defined(HAVE_EGL) || defined(__ANDROID__)
638   if ((EGLSurface )myGlContext->myWindow != EGL_NO_SURFACE)
639   {
640     eglDestroySurface ((EGLDisplay )myGlContext->myDisplay,
641                        (EGLSurface )myGlContext->myWindow);
642   }
643 #elif defined(_WIN32)
644   HWND  aWindow          = (HWND  )myGlContext->myWindow;
645   HDC   aWindowDC        = (HDC   )myGlContext->myWindowDC;
646   HGLRC aWindowGContext  = (HGLRC )myGlContext->myGContext;
647   HGLRC aThreadGContext  = wglGetCurrentContext();
648   myGlContext.Nullify();
649
650   if (aThreadGContext != NULL)
651   {
652     if (aThreadGContext == aWindowGContext)
653     {
654       wglMakeCurrent (NULL, NULL);
655     }
656
657     wglDeleteContext (aWindowGContext);
658   }
659   ReleaseDC (aWindow, aWindowDC);
660 #else
661   Display*    aDisplay        = (Display*    )myGlContext->myDisplay;
662   GLXContext  aWindowGContext = (GLXContext  )myGlContext->myGContext;
663   GLXContext  aThreadGContext = glXGetCurrentContext();
664   myGlContext.Nullify();
665
666   if (aDisplay != NULL)
667   {
668     if (aThreadGContext == aWindowGContext)
669     {
670       glXMakeCurrent (aDisplay, None, NULL);
671     }
672
673     // FSXXX sync necessary if non-direct rendering
674     glXWaitGL();
675     glXDestroyContext (aDisplay, aWindowGContext);
676   }
677 #endif
678 }
679
680 #endif // !__APPLE__
681
682 // =======================================================================
683 // function : Activate
684 // purpose  :
685 // =======================================================================
686 Standard_Boolean OpenGl_Window::Activate()
687 {
688   return myGlContext->MakeCurrent();
689 }
690
691 #if !defined(__APPLE__) || defined(MACOSX_USE_GLX)
692
693 // =======================================================================
694 // function : Resize
695 // purpose  : call_subr_resize
696 // =======================================================================
697 void OpenGl_Window::Resize (const CALL_DEF_WINDOW& theCWindow)
698 {
699 #if !defined(_WIN32) && !defined(HAVE_EGL) && !defined(__ANDROID__)
700   Display* aDisp = (Display* )myGlContext->myDisplay;
701   if (aDisp == NULL)
702     return;
703 #endif
704
705   // If the size is not changed - do nothing
706   if ((myWidth == theCWindow.dx) && (myHeight == theCWindow.dy))
707     return;
708
709   myWidth  = theCWindow.dx;
710   myHeight = theCWindow.dy;
711
712 #if !defined(_WIN32) && !defined(HAVE_EGL) && !defined(__ANDROID__)
713   XResizeWindow (aDisp, myGlContext->myWindow, (unsigned int )myWidth, (unsigned int )myHeight);
714   XSync (aDisp, False);
715 #endif
716
717   Init();
718 }
719
720 #endif // !__APPLE__
721
722 // =======================================================================
723 // function : ReadDepths
724 // purpose  : TelReadDepths
725 // =======================================================================
726 void OpenGl_Window::ReadDepths (const Standard_Integer theX,     const Standard_Integer theY,
727                                 const Standard_Integer theWidth, const Standard_Integer theHeight,
728                                 float* theDepths)
729 {
730   if (theDepths == NULL || !Activate())
731     return;
732
733   OpenGl_Mat4 aProjectMat;
734   OpenGl_Utils::Ortho2D<Standard_ShortReal> (aProjectMat,
735     0.f, static_cast<GLfloat> (myWidth), 0.f, static_cast<GLfloat> (myHeight));
736
737   myGlContext->WorldViewState.Push();
738   myGlContext->ProjectionState.Push();
739
740   myGlContext->WorldViewState.SetIdentity();
741   myGlContext->ProjectionState.SetCurrent (aProjectMat);
742
743   myGlContext->ApplyProjectionMatrix();
744   myGlContext->ApplyWorldViewMatrix();
745
746 #if !defined(GL_ES_VERSION_2_0)
747   glRasterPos2i (theX, theY);
748   DisableFeatures();
749   glReadPixels (theX, theY, theWidth, theHeight, GL_DEPTH_COMPONENT, GL_FLOAT, theDepths);
750   EnableFeatures();
751 #endif
752
753   myGlContext->WorldViewState.Pop();
754   myGlContext->ProjectionState.Pop();
755
756   myGlContext->ApplyProjectionMatrix();
757 }
758
759 // =======================================================================
760 // function : SetBackgroundColor
761 // purpose  : call_subr_set_background
762 // =======================================================================
763 void OpenGl_Window::SetBackgroundColor (const Standard_ShortReal theR,
764                                         const Standard_ShortReal theG,
765                                         const Standard_ShortReal theB)
766 {
767   myBgColor.rgb[0] = theR;
768   myBgColor.rgb[1] = theG;
769   myBgColor.rgb[2] = theB;
770 }
771
772 #if !defined(__APPLE__) || defined(MACOSX_USE_GLX)
773
774 // =======================================================================
775 // function : Init
776 // purpose  :
777 // =======================================================================
778 void OpenGl_Window::Init()
779 {
780   if (!Activate())
781     return;
782
783 #if defined(HAVE_EGL) || defined(__ANDROID__)
784   eglQuerySurface ((EGLDisplay )myGlContext->myDisplay, (EGLSurface )myGlContext->myWindow, EGL_WIDTH,  &myWidth);
785   eglQuerySurface ((EGLDisplay )myGlContext->myDisplay, (EGLSurface )myGlContext->myWindow, EGL_HEIGHT, &myHeight);
786 #elif defined(_WIN32)
787   RECT cr;
788   GetClientRect ((HWND )myGlContext->myWindow, &cr);
789   myWidth  = cr.right - cr.left;
790   myHeight = cr.bottom - cr.top;
791 #else
792   Window aRootWin;
793   int aDummy;
794   unsigned int aDummyU;
795   unsigned int aNewWidth  = 0;
796   unsigned int aNewHeight = 0;
797   Display* aDisp = (Display* )myGlContext->myDisplay;
798   XGetGeometry (aDisp, myGlContext->myWindow, &aRootWin, &aDummy, &aDummy, &aNewWidth, &aNewHeight, &aDummyU, &aDummyU);
799   myWidth  = aNewWidth;
800   myHeight = aNewHeight;
801 #endif
802
803   glDisable (GL_DITHER);
804   glDisable (GL_SCISSOR_TEST);
805   glViewport (0, 0, myWidth, myHeight);
806 #if !defined(GL_ES_VERSION_2_0)
807   glDrawBuffer (GL_BACK);
808   if (myGlContext->core11 != NULL)
809   {
810     glMatrixMode (GL_MODELVIEW);
811   }
812 #endif
813 }
814
815 #endif // !__APPLE__
816
817 // =======================================================================
818 // function : EnableFeatures
819 // purpose  :
820 // =======================================================================
821 void OpenGl_Window::EnableFeatures() const
822 {
823   //
824 }
825
826 // =======================================================================
827 // function : DisableFeatures
828 // purpose  :
829 // =======================================================================
830 void OpenGl_Window::DisableFeatures() const
831 {
832 #if !defined(GL_ES_VERSION_2_0)
833   glPixelTransferi (GL_MAP_COLOR, GL_FALSE);
834 #endif
835
836   /*
837   * Disable stuff that's likely to slow down glDrawPixels.
838   * (Omit as much of this as possible, when you know in advance
839   * that the OpenGL state will already be set correctly.)
840   */
841   glDisable(GL_DITHER);
842   glDisable(GL_BLEND);
843   glDisable(GL_DEPTH_TEST);
844   glDisable(GL_TEXTURE_2D);
845   glDisable(GL_STENCIL_TEST);
846
847 #if !defined(GL_ES_VERSION_2_0)
848   glDisable(GL_LIGHTING);
849   glDisable(GL_ALPHA_TEST);
850   glDisable(GL_FOG);
851   glDisable(GL_LOGIC_OP);
852   glDisable(GL_TEXTURE_1D);
853
854   glPixelTransferi(GL_MAP_COLOR, GL_FALSE);
855   glPixelTransferi(GL_RED_SCALE, 1);
856   glPixelTransferi(GL_RED_BIAS, 0);
857   glPixelTransferi(GL_GREEN_SCALE, 1);
858   glPixelTransferi(GL_GREEN_BIAS, 0);
859   glPixelTransferi(GL_BLUE_SCALE, 1);
860   glPixelTransferi(GL_BLUE_BIAS, 0);
861   glPixelTransferi(GL_ALPHA_SCALE, 1);
862   glPixelTransferi(GL_ALPHA_BIAS, 0);
863
864   /*
865   * Disable extensions that could slow down glDrawPixels.
866   * (Actually, you should check for the presence of the proper
867   * extension before making these calls.  I've omitted that
868   * code for simplicity.)
869   */
870
871   if ((myGlContext->myGlVerMajor >= 1) && (myGlContext->myGlVerMinor >= 2))
872   {
873 #ifdef GL_EXT_convolution
874     if (myGlContext->CheckExtension ("GL_CONVOLUTION_1D_EXT"))
875       glDisable(GL_CONVOLUTION_1D_EXT);
876
877     if (myGlContext->CheckExtension ("GL_CONVOLUTION_2D_EXT"))
878       glDisable(GL_CONVOLUTION_2D_EXT);
879
880     if (myGlContext->CheckExtension ("GL_SEPARABLE_2D_EXT"))
881       glDisable(GL_SEPARABLE_2D_EXT);
882 #endif
883
884 #ifdef GL_EXT_histogram
885     if (myGlContext->CheckExtension ("GL_SEPARABLE_2D_EXT"))
886       glDisable(GL_HISTOGRAM_EXT);
887
888     if (myGlContext->CheckExtension ("GL_MINMAX_EXT"))
889       glDisable(GL_MINMAX_EXT);
890 #endif
891
892 #ifdef GL_EXT_texture3D
893     if (myGlContext->CheckExtension ("GL_TEXTURE_3D_EXT"))
894       glDisable(GL_TEXTURE_3D_EXT);
895 #endif
896   }
897 #endif
898 }