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