0025800: Visualization, TKOpenGl - disable GL_DITHER explicitly
[occt.git] / src / OpenGl / OpenGl_Window.cxx
index 14090d6..b7fb9db 100644 (file)
@@ -1,33 +1,33 @@
 // Created on: 2011-09-20
 // Created by: Sergey ZERCHANINOV
-// Copyright (c) 2011-2012 OPEN CASCADE SAS
+// Copyright (c) 2011-2014 OPEN CASCADE SAS
 //
-// The content of this file is subject to the Open CASCADE Technology Public
-// License Version 6.5 (the "License"). You may not use the content of this file
-// except in compliance with the License. Please obtain a copy of the License
-// at http://www.opencascade.org and read it completely before using this file.
+// This file is part of Open CASCADE Technology software library.
 //
-// The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
-// main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
+// This library is free software; you can redistribute it and/or modify it under
+// the terms of the GNU Lesser General Public License version 2.1 as published
+// by the Free Software Foundation, with special exception defined in the file
+// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
+// distribution for complete text of the license and disclaimer of any warranty.
 //
-// The Original Code and all software distributed under the License is
-// distributed on an "AS IS" basis, without warranty of any kind, and the
-// Initial Developer hereby disclaims all such warranties, including without
-// limitation, any warranties of merchantability, fitness for a particular
-// purpose or non-infringement. Please see the License for the specific terms
-// and conditions governing the rights and limitations under the License.
-
-#include <OpenGl_GlCore11.hxx>
+// Alternatively, this file may be used under the terms of Open CASCADE
+// commercial license or contractual agreement.
 
+#include <OpenGl_GlCore12.hxx>
 #include <InterfaceGraphic.hxx>
 
-#include <OpenGl_Window.hxx>
-
 #include <OpenGl_Context.hxx>
-#include <OpenGl_Display.hxx>
+#include <OpenGl_GraphicDriver.hxx>
+#include <OpenGl_Window.hxx>
+#include <OpenGl_Utils.hxx>
 
 #include <Aspect_GraphicDeviceDefinitionError.hxx>
 #include <TCollection_AsciiString.hxx>
+#include <TCollection_ExtendedString.hxx>
+
+#if defined(HAVE_EGL) || defined(__ANDROID__)
+  #include <EGL/egl.h>
+#endif
 
 IMPLEMENT_STANDARD_HANDLE(OpenGl_Window,MMgt_TShared)
 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Window,MMgt_TShared)
@@ -38,7 +38,65 @@ namespace
 {
   static const TEL_COLOUR THE_DEFAULT_BG_COLOR = { { 0.F, 0.F, 0.F, 1.F } };
 
-#if defined(_WIN32)
+#if defined(HAVE_EGL) || defined(__ANDROID__)
+  //
+#elif defined(_WIN32)
+
+  // WGL_ARB_pixel_format
+#ifndef WGL_NUMBER_PIXEL_FORMATS_ARB
+  #define WGL_NUMBER_PIXEL_FORMATS_ARB            0x2000
+  #define WGL_DRAW_TO_WINDOW_ARB                  0x2001
+  #define WGL_DRAW_TO_BITMAP_ARB                  0x2002
+  #define WGL_ACCELERATION_ARB                    0x2003
+  #define WGL_NEED_PALETTE_ARB                    0x2004
+  #define WGL_NEED_SYSTEM_PALETTE_ARB             0x2005
+  #define WGL_SWAP_LAYER_BUFFERS_ARB              0x2006
+  #define WGL_SWAP_METHOD_ARB                     0x2007
+  #define WGL_NUMBER_OVERLAYS_ARB                 0x2008
+  #define WGL_NUMBER_UNDERLAYS_ARB                0x2009
+  #define WGL_TRANSPARENT_ARB                     0x200A
+  #define WGL_TRANSPARENT_RED_VALUE_ARB           0x2037
+  #define WGL_TRANSPARENT_GREEN_VALUE_ARB         0x2038
+  #define WGL_TRANSPARENT_BLUE_VALUE_ARB          0x2039
+  #define WGL_TRANSPARENT_ALPHA_VALUE_ARB         0x203A
+  #define WGL_TRANSPARENT_INDEX_VALUE_ARB         0x203B
+  #define WGL_SHARE_DEPTH_ARB                     0x200C
+  #define WGL_SHARE_STENCIL_ARB                   0x200D
+  #define WGL_SHARE_ACCUM_ARB                     0x200E
+  #define WGL_SUPPORT_GDI_ARB                     0x200F
+  #define WGL_SUPPORT_OPENGL_ARB                  0x2010
+  #define WGL_DOUBLE_BUFFER_ARB                   0x2011
+  #define WGL_STEREO_ARB                          0x2012
+  #define WGL_PIXEL_TYPE_ARB                      0x2013
+  #define WGL_COLOR_BITS_ARB                      0x2014
+  #define WGL_RED_BITS_ARB                        0x2015
+  #define WGL_RED_SHIFT_ARB                       0x2016
+  #define WGL_GREEN_BITS_ARB                      0x2017
+  #define WGL_GREEN_SHIFT_ARB                     0x2018
+  #define WGL_BLUE_BITS_ARB                       0x2019
+  #define WGL_BLUE_SHIFT_ARB                      0x201A
+  #define WGL_ALPHA_BITS_ARB                      0x201B
+  #define WGL_ALPHA_SHIFT_ARB                     0x201C
+  #define WGL_ACCUM_BITS_ARB                      0x201D
+  #define WGL_ACCUM_RED_BITS_ARB                  0x201E
+  #define WGL_ACCUM_GREEN_BITS_ARB                0x201F
+  #define WGL_ACCUM_BLUE_BITS_ARB                 0x2020
+  #define WGL_ACCUM_ALPHA_BITS_ARB                0x2021
+  #define WGL_DEPTH_BITS_ARB                      0x2022
+  #define WGL_STENCIL_BITS_ARB                    0x2023
+  #define WGL_AUX_BUFFERS_ARB                     0x2024
+
+  #define WGL_NO_ACCELERATION_ARB                 0x2025
+  #define WGL_GENERIC_ACCELERATION_ARB            0x2026
+  #define WGL_FULL_ACCELERATION_ARB               0x2027
+
+  #define WGL_SWAP_EXCHANGE_ARB                   0x2028
+  #define WGL_SWAP_COPY_ARB                       0x2029
+  #define WGL_SWAP_UNDEFINED_ARB                  0x202A
+
+  #define WGL_TYPE_RGBA_ARB                       0x202B
+  #define WGL_TYPE_COLORINDEX_ARB                 0x202C
+#endif // WGL_NUMBER_PIXEL_FORMATS_ARB
 
   // WGL_ARB_create_context_profile
 #ifndef WGL_CONTEXT_MAJOR_VERSION_ARB
@@ -61,91 +119,6 @@ namespace
   {
     return DefWindowProcW (theWin, theMsg, theParamW, theParamL);
   }
-
-  static int find_pixel_format (HDC                    theDevCtx,
-                                PIXELFORMATDESCRIPTOR& thePixelFrmt,
-                                const Standard_Boolean theIsDoubleBuff)
-  {
-    PIXELFORMATDESCRIPTOR aPixelFrmtTmp;
-    memset (&aPixelFrmtTmp, 0, sizeof (PIXELFORMATDESCRIPTOR));
-    aPixelFrmtTmp.nSize      = sizeof (PIXELFORMATDESCRIPTOR);
-    aPixelFrmtTmp.nVersion   = 1;
-    aPixelFrmtTmp.dwFlags    = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | (theIsDoubleBuff ? PFD_DOUBLEBUFFER : PFD_SUPPORT_GDI);
-    aPixelFrmtTmp.iPixelType = PFD_TYPE_RGBA;
-    aPixelFrmtTmp.iLayerType = PFD_MAIN_PLANE;
-
-    const int BUFF_BITS_STENCIL[] = {  8,  1     };
-    const int BUFF_BITS_COLOR[]   = { 32, 24     };
-    const int BUFF_BITS_DEPTH[]   = { 32, 24, 16 };
-
-    int aGoodBits[] = { 0, 0, 0 };
-    int aPixelFrmtIdLast = 0;
-    int aPixelFrmtIdGood = 0;
-    Standard_Size aStencilIter = 0, aColorIter = 0, aDepthIter = 0;
-    for (aStencilIter = 0; aStencilIter < sizeof(BUFF_BITS_STENCIL) / sizeof(int); ++aStencilIter)
-    {
-      aPixelFrmtTmp.cStencilBits = (BYTE)(BUFF_BITS_STENCIL[aStencilIter]);
-      for (aDepthIter = 0; aDepthIter < sizeof(BUFF_BITS_DEPTH) / sizeof(int); ++aDepthIter)
-      {
-        aPixelFrmtTmp.cDepthBits = (BYTE)(BUFF_BITS_DEPTH[aDepthIter]);
-        aPixelFrmtIdGood = 0;
-        for (aColorIter = 0; aColorIter < sizeof(BUFF_BITS_COLOR) / sizeof(int); ++aColorIter)
-        {
-          aPixelFrmtTmp.cColorBits = (BYTE)(BUFF_BITS_COLOR[aColorIter]);
-          aPixelFrmtIdLast = ChoosePixelFormat (theDevCtx, &aPixelFrmtTmp);
-          if (aPixelFrmtIdLast == 0)
-          {
-            continue;
-          }
-
-          thePixelFrmt.cDepthBits   = 0;
-          thePixelFrmt.cColorBits   = 0;
-          thePixelFrmt.cStencilBits = 0;
-          DescribePixelFormat (theDevCtx, aPixelFrmtIdLast, sizeof(PIXELFORMATDESCRIPTOR), &thePixelFrmt);
-          if (thePixelFrmt.cColorBits   >= BUFF_BITS_COLOR[aColorIter]
-           && thePixelFrmt.cDepthBits   >= BUFF_BITS_DEPTH[aDepthIter]
-           && thePixelFrmt.cStencilBits >= BUFF_BITS_STENCIL[aStencilIter])
-          {
-            break;
-          }
-          if (thePixelFrmt.cColorBits > aGoodBits[0])
-          {
-            aGoodBits[0] = thePixelFrmt.cColorBits;
-            aGoodBits[1] = thePixelFrmt.cDepthBits;
-            aGoodBits[2] = thePixelFrmt.cStencilBits;
-            aPixelFrmtIdGood = aPixelFrmtIdLast;
-          }
-          else if (thePixelFrmt.cColorBits == aGoodBits[0])
-          {
-            if (thePixelFrmt.cDepthBits > aGoodBits[1])
-            {
-              aGoodBits[1] = thePixelFrmt.cDepthBits;
-              aGoodBits[2] = thePixelFrmt.cStencilBits;
-              aPixelFrmtIdGood = aPixelFrmtIdLast;
-            }
-            else if (thePixelFrmt.cDepthBits == aGoodBits[1])
-            {
-              if(thePixelFrmt.cStencilBits > aGoodBits[2])
-              {
-                aGoodBits[2] = thePixelFrmt.cStencilBits;
-                aPixelFrmtIdGood = aPixelFrmtIdLast;
-              }
-            }
-          }
-        }
-        if (aColorIter < sizeof(BUFF_BITS_COLOR) / sizeof(int))
-        {
-          break;
-        }
-      }
-      if (aDepthIter < sizeof(BUFF_BITS_DEPTH) / sizeof(int))
-      {
-        break;
-      }
-    }
-
-    return (aPixelFrmtIdLast == 0) ? aPixelFrmtIdGood : aPixelFrmtIdLast;
-  }
 #else
   static Bool WaitForNotify (Display* theDisp, XEvent* theEv, char* theArg)
   {
@@ -153,78 +126,115 @@ namespace
   }
 #endif
 
-};
+}
 
 // =======================================================================
 // function : OpenGl_Window
 // purpose  :
 // =======================================================================
-OpenGl_Window::OpenGl_Window (const Handle(OpenGl_Display)& theDisplay,
+OpenGl_Window::OpenGl_Window (const Handle(OpenGl_GraphicDriver)& theDriver,
                               const CALL_DEF_WINDOW&        theCWindow,
                               Aspect_RenderingContext       theGContext,
                               const Handle(OpenGl_Caps)&    theCaps,
                               const Handle(OpenGl_Context)& theShareCtx)
-: myDisplay (theDisplay),
-  myGlContext (new OpenGl_Context (theCaps)),
+: myGlContext (new OpenGl_Context (theCaps)),
   myOwnGContext (theGContext == 0),
-#if defined(_WIN32)
-  mySysPalInUse (FALSE),
-#endif
-  myWidth ((Standard_Integer )theCWindow.dx),
-  myHeight ((Standard_Integer )theCWindow.dy),
-  myBgColor (THE_DEFAULT_BG_COLOR),
-  myDither (theDisplay->Dither()),
-  myBackDither (theDisplay->BackDither())
+  myWidth   (theCWindow.dx),
+  myHeight  (theCWindow.dy),
+  myBgColor (THE_DEFAULT_BG_COLOR)
 {
   myBgColor.rgb[0] = theCWindow.Background.r;
   myBgColor.rgb[1] = theCWindow.Background.g;
   myBgColor.rgb[2] = theCWindow.Background.b;
 
-#if defined(_WIN32)
-  HWND  aWindow   = (HWND )theCWindow.XWindow;
-  HDC   aWindowDC = GetDC (aWindow);
-  HGLRC aGContext = (HGLRC )theGContext;
-
-  PIXELFORMATDESCRIPTOR aPixelFrmt;
-  const int aPixelFrmtId = find_pixel_format (aWindowDC, aPixelFrmt, myDisplay->DBuffer());
-  if (aPixelFrmtId == 0)
+#if defined(HAVE_EGL) || defined(__ANDROID__)
+  EGLDisplay anEglDisplay = (EGLDisplay )theDriver->getRawGlDisplay();
+  EGLContext anEglContext = (EGLContext )theDriver->getRawGlContext();
+  EGLConfig  anEglConfig  = (EGLConfig  )theDriver->getRawGlConfig();
+  if (anEglDisplay == EGL_NO_DISPLAY
+   || anEglContext == EGL_NO_CONTEXT
+   || anEglConfig == NULL)
   {
-    ReleaseDC (aWindow, aWindowDC);
-
-    TCollection_AsciiString aMsg ("OpenGl_Window::CreateWindow: ChoosePixelFormat failed. Error code: ");
-    aMsg += (int )GetLastError();
-    Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
+    Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window, EGL does not provide compatible configurations!");
     return;
   }
 
-  if (aPixelFrmt.dwFlags & PFD_NEED_PALETTE)
+  EGLSurface anEglSurf = EGL_NO_SURFACE;
+  if (theGContext == (EGLContext )EGL_NO_CONTEXT)
   {
-    WINDOW_DATA* aWndData = (WINDOW_DATA* )GetWindowLongPtr (aWindow, GWLP_USERDATA);
-
-    mySysPalInUse = (aPixelFrmt.dwFlags & PFD_NEED_SYSTEM_PALETTE) ? TRUE : FALSE;
-    InterfaceGraphic_RealizePalette (aWindowDC, aWndData->hPal, FALSE, mySysPalInUse);
+    // create new surface
+    anEglSurf = eglCreateWindowSurface (anEglDisplay, anEglConfig, (EGLNativeWindowType )theCWindow.XWindow, NULL);
+    if (anEglSurf == EGL_NO_SURFACE)
+    {
+      Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window, EGL is unable to create surface for window!");
+      return;
+    }
+  }
+  else if (theGContext != anEglContext)
+  {
+    Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window, EGL is used in unsupported combination!");
+    return;
+  }
+  else
+  {
+    anEglSurf = eglGetCurrentSurface(EGL_DRAW);
+    if (anEglSurf == EGL_NO_SURFACE)
+    {
+      Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window, EGL is unable to retrieve current surface!");
+      return;
+    }
   }
 
-  if (myDither)
+  myGlContext->Init ((Aspect_Drawable )anEglSurf, (Aspect_Display )anEglDisplay, (Aspect_RenderingContext )anEglContext);
+#elif defined(_WIN32)
+  (void )theDriver;
+  HWND  aWindow   = (HWND )theCWindow.XWindow;
+  HDC   aWindowDC = GetDC (aWindow);
+  HGLRC aGContext = (HGLRC )theGContext;
+
+  PIXELFORMATDESCRIPTOR aPixelFrmt;
+  memset (&aPixelFrmt, 0, sizeof(aPixelFrmt));
+  aPixelFrmt.nSize        = sizeof(PIXELFORMATDESCRIPTOR);
+  aPixelFrmt.nVersion     = 1;
+  aPixelFrmt.dwFlags      = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
+  aPixelFrmt.iPixelType   = PFD_TYPE_RGBA;
+  aPixelFrmt.cColorBits   = 24;
+  aPixelFrmt.cDepthBits   = 24;
+  aPixelFrmt.cStencilBits = 8;
+  aPixelFrmt.iLayerType   = PFD_MAIN_PLANE;
+  if (theCaps->contextStereo)
   {
-    myDither = (aPixelFrmt.cColorBits <= 8);
+    aPixelFrmt.dwFlags |= PFD_STEREO;
   }
 
-  if (myBackDither)
+  int aPixelFrmtId = ChoosePixelFormat (aWindowDC, &aPixelFrmt);
+
+  // in case of failure try without stereo if any
+  if (aPixelFrmtId == 0 && theCaps->contextStereo)
   {
-    myBackDither = (aPixelFrmt.cColorBits <= 8);
+    TCollection_ExtendedString aMsg ("OpenGl_Window::CreateWindow: "
+                                     "ChoosePixelFormat is unable to find stereo supported pixel format. "
+                                     "Choosing similar non stereo format.");
+    myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
+                              GL_DEBUG_TYPE_OTHER_ARB,
+                              0, GL_DEBUG_SEVERITY_HIGH_ARB, aMsg);
+
+    aPixelFrmt.dwFlags &= ~PFD_STEREO;
+    aPixelFrmtId = ChoosePixelFormat (aWindowDC, &aPixelFrmt);
   }
 
-  if (!SetPixelFormat (aWindowDC, aPixelFrmtId, &aPixelFrmt))
+  if (aPixelFrmtId == 0)
   {
     ReleaseDC (aWindow, aWindowDC);
 
-    TCollection_AsciiString aMsg("OpenGl_Window::CreateWindow: SetPixelFormat failed. Error code: ");
+    TCollection_AsciiString aMsg ("OpenGl_Window::CreateWindow: ChoosePixelFormat failed. Error code: ");
     aMsg += (int )GetLastError();
     Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
     return;
   }
 
+  DescribePixelFormat (aWindowDC, aPixelFrmtId, sizeof(aPixelFrmt), &aPixelFrmt);
+
   HGLRC aSlaveCtx = !theShareCtx.IsNull() ? (HGLRC )theShareCtx->myGContext : NULL;
   if (aGContext == NULL)
   {
@@ -238,14 +248,18 @@ OpenGl_Window::OpenGl_Window (const Handle(OpenGl_Display)& theDisplay,
     HWND  aWinTmp     = NULL;
     HDC   aDevCtxTmp  = NULL;
     HGLRC aRendCtxTmp = NULL;
-    if (!theCaps->contextDebug
+    if ((!theCaps->contextDebug && !theCaps->contextNoAccel)
      || RegisterClassW (&aClass) == 0)
     {
       aClass.lpszClassName = NULL;
     }
     if (aClass.lpszClassName != NULL)
     {
-      aWinTmp = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_WINDOWEDGE | WS_EX_NOACTIVATE,
+      DWORD anExStyle = WS_EX_TOOLWINDOW | WS_EX_WINDOWEDGE;
+    #if (_WIN32_WINNT >= 0x0500)
+      anExStyle |= WS_EX_NOACTIVATE;
+    #endif
+      aWinTmp = CreateWindowExW(anExStyle,
                                 aClass.lpszClassName, L"OpenGl_WindowTmp",
                                 WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_DISABLED,
                                 2, 2, 4, 4,
@@ -257,36 +271,86 @@ OpenGl_Window::OpenGl_Window (const Handle(OpenGl_Display)& theDisplay,
       SetPixelFormat (aDevCtxTmp, aPixelFrmtId, &aPixelFrmt);
       aRendCtxTmp = wglCreateContext (aDevCtxTmp);
     }
+
+    typedef BOOL (WINAPI *wglChoosePixelFormatARB_t)(HDC           theDevCtx,
+                                                     const int*    theIntAttribs,
+                                                     const float*  theFloatAttribs,
+                                                     unsigned int  theMaxFormats,
+                                                     int*          theFormatsOut,
+                                                     unsigned int* theNumFormatsOut);
+    typedef HGLRC (WINAPI *wglCreateContextAttribsARB_t)(HDC        theDevCtx,
+                                                         HGLRC      theShareContext,
+                                                         const int* theAttribs);
+    wglChoosePixelFormatARB_t    aChoosePixProc = NULL;
+    wglCreateContextAttribsARB_t aCreateCtxProc = NULL;
     if (aRendCtxTmp != NULL)
     {
       wglMakeCurrent (aDevCtxTmp, aRendCtxTmp);
 
       typedef const char* (WINAPI *wglGetExtensionsStringARB_t)(HDC theDeviceContext);
-      typedef HGLRC (WINAPI *wglCreateContextAttribsARB_t)(HDC        theDevCtx,
-                                                           HGLRC      theShareContext,
-                                                           const int* theAttribs);
-      wglGetExtensionsStringARB_t  aGetExtensions = (wglGetExtensionsStringARB_t  )wglGetProcAddress ("wglGetExtensionsStringARB");
-      wglCreateContextAttribsARB_t aCreateCtxProc = (wglCreateContextAttribsARB_t )wglGetProcAddress ("wglCreateContextAttribsARB");
-      const char* aWglExts = aGetExtensions (wglGetCurrentDC());
-      if (aCreateCtxProc != NULL
-       && OpenGl_Context::CheckExtension (aWglExts, "WGL_ARB_create_context_profile"))
+      wglGetExtensionsStringARB_t aGetExtensions = (wglGetExtensionsStringARB_t  )wglGetProcAddress ("wglGetExtensionsStringARB");
+      const char* aWglExts = (aGetExtensions != NULL) ? aGetExtensions (wglGetCurrentDC()) : NULL;
+      if (OpenGl_Context::CheckExtension (aWglExts, "WGL_ARB_pixel_format"))
+      {
+        aChoosePixProc = (wglChoosePixelFormatARB_t    )wglGetProcAddress ("wglChoosePixelFormatARB");
+      }
+      if (OpenGl_Context::CheckExtension (aWglExts, "WGL_ARB_create_context_profile"))
       {
-        // Beware! NVIDIA drivers reject context creation when WGL_CONTEXT_PROFILE_MASK_ARB are specified
-        // but not WGL_CONTEXT_MAJOR_VERSION_ARB/WGL_CONTEXT_MINOR_VERSION_ARB.
-        int aCtxAttribs[] =
-        {
-          //WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
-          //WGL_CONTEXT_MINOR_VERSION_ARB, 2,
-          //WGL_CONTEXT_PROFILE_MASK_ARB,  WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, //WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
-          WGL_CONTEXT_FLAGS_ARB,         theCaps->contextDebug ? WGL_CONTEXT_DEBUG_BIT_ARB : 0,
-          0, 0
-        };
-
-        aGContext = aCreateCtxProc (aWindowDC, aSlaveCtx, aCtxAttribs);
-        if (aGContext != NULL)
-        {
-          aSlaveCtx = NULL;
-        }
+        aCreateCtxProc = (wglCreateContextAttribsARB_t )wglGetProcAddress ("wglCreateContextAttribsARB");
+      }
+    }
+
+    // choose extended pixel format
+    if (aChoosePixProc != NULL)
+    {
+      const int aPixAttribs[] =
+      {
+        WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
+        WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
+        WGL_DOUBLE_BUFFER_ARB,  GL_TRUE,
+        WGL_STEREO_ARB,         theCaps->contextStereo ? GL_TRUE : GL_FALSE,
+        WGL_PIXEL_TYPE_ARB,     WGL_TYPE_RGBA_ARB,
+        //WGL_SAMPLE_BUFFERS_ARB, 1,
+        //WGL_SAMPLES_ARB,        8,
+        WGL_COLOR_BITS_ARB,     24,
+        WGL_DEPTH_BITS_ARB,     24,
+        WGL_STENCIL_BITS_ARB,   8,
+        WGL_ACCELERATION_ARB,   theCaps->contextNoAccel ? WGL_NO_ACCELERATION_ARB : WGL_FULL_ACCELERATION_ARB,
+        0, 0,
+      };
+      unsigned int aFrmtsNb = 0;
+      aChoosePixProc (aWindowDC, aPixAttribs, NULL, 1, &aPixelFrmtId, &aFrmtsNb);
+    }
+
+    // setup pixel format - may be set only once per window
+    if (!SetPixelFormat (aWindowDC, aPixelFrmtId, &aPixelFrmt))
+    {
+      ReleaseDC (aWindow, aWindowDC);
+
+      TCollection_AsciiString aMsg("OpenGl_Window::CreateWindow: SetPixelFormat failed. Error code: ");
+      aMsg += (int )GetLastError();
+      Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
+      return;
+    }
+
+    // create GL context with extra options
+    if (aCreateCtxProc != NULL)
+    {
+      // Beware! NVIDIA drivers reject context creation when WGL_CONTEXT_PROFILE_MASK_ARB are specified
+      // but not WGL_CONTEXT_MAJOR_VERSION_ARB/WGL_CONTEXT_MINOR_VERSION_ARB.
+      int aCtxAttribs[] =
+      {
+        //WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
+        //WGL_CONTEXT_MINOR_VERSION_ARB, 2,
+        //WGL_CONTEXT_PROFILE_MASK_ARB,  WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, //WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
+        WGL_CONTEXT_FLAGS_ARB,         theCaps->contextDebug ? WGL_CONTEXT_DEBUG_BIT_ARB : 0,
+        0, 0
+      };
+
+      aGContext = aCreateCtxProc (aWindowDC, aSlaveCtx, aCtxAttribs);
+      if (aGContext != NULL)
+      {
+        aSlaveCtx = NULL;
       }
     }
 
@@ -309,6 +373,7 @@ OpenGl_Window::OpenGl_Window (const Handle(OpenGl_Display)& theDisplay,
 
     if (aGContext == NULL)
     {
+      // create context using obsolete functionality
       aGContext = wglCreateContext (aWindowDC);
     }
     if (aGContext == NULL)
@@ -333,9 +398,10 @@ OpenGl_Window::OpenGl_Window (const Handle(OpenGl_Display)& theDisplay,
 
   myGlContext->Init ((Aspect_Handle )aWindow, (Aspect_Handle )aWindowDC, (Aspect_RenderingContext )aGContext);
 #else
-  WINDOW aParent = (WINDOW )theCWindow.XWindow;
-  WINDOW aWindow = 0;
-  DISPLAY* aDisp = (DISPLAY* )myDisplay->GetDisplay();
+  Window aParent = (Window )theCWindow.XWindow;
+  Window aWindow = 0;
+
+  Display*   aDisp     = theDriver->GetDisplayConnection()->GetDisplay();
   GLXContext aGContext = (GLXContext )theGContext;
 
   XWindowAttributes wattr;
@@ -368,7 +434,8 @@ OpenGl_Window::OpenGl_Window (const Handle(OpenGl_Display)& theDisplay,
     if (aVis != NULL)
     {
       // check Visual for OpenGl context's parameters compability
-      int isGl = 0, isDoubleBuffer = 0, isRGBA = 0, aDepthSize = 0, aStencilSize = 0;
+      int isGl = 0, isDoubleBuffer = 0, isRGBA = 0, isStereo = 0;
+      int aDepthSize = 0, aStencilSize = 0;
 
       if (glXGetConfig (aDisp, aVis, GLX_USE_GL, &isGl) != 0)
         isGl = 0;
@@ -379,13 +446,18 @@ OpenGl_Window::OpenGl_Window (const Handle(OpenGl_Display)& theDisplay,
       if (glXGetConfig (aDisp, aVis, GLX_DOUBLEBUFFER, &isDoubleBuffer) != 0)
         isDoubleBuffer = 0;
 
+      if (glXGetConfig (aDisp, aVis, GLX_STEREO, &isStereo) != 0)
+        isStereo = 0;
+
       if (glXGetConfig (aDisp, aVis, GLX_DEPTH_SIZE, &aDepthSize) != 0)
         aDepthSize = 0;
 
       if (glXGetConfig (aDisp, aVis, GLX_STENCIL_SIZE, &aStencilSize) != 0)
         aStencilSize = 0;
 
-      if (!isGl || !aDepthSize || !isRGBA  || (isDoubleBuffer ? 1 : 0) != (myDisplay->DBuffer()? 1 : 0))
+      if (!isGl || !aDepthSize || !isRGBA  || !aStencilSize ||
+          (isDoubleBuffer ? 1 : 0) != 1 ||
+          (isStereo       ? 1 : 0) != (theCaps->contextStereo ? 1 : 0))
       {
         XFree (aVis);
         aVis = NULL;
@@ -414,12 +486,31 @@ OpenGl_Window::OpenGl_Window (const Handle(OpenGl_Display)& theDisplay,
       anAttribs[anIter++] = GLX_BLUE_SIZE;
       anAttribs[anIter++] = (wattr.depth <= 8) ? 0 : 1;
 
-      if (myDisplay->DBuffer())
-        anAttribs[anIter++] = GLX_DOUBLEBUFFER;
+      anAttribs[anIter++] = GLX_DOUBLEBUFFER;
+
+      // warning: this flag may be set to None, so it need to be last in anAttribs
+      Standard_Integer aStereoFlagPos = anIter;
+      if (theCaps->contextStereo)
+        anAttribs[anIter++] = GLX_STEREO;
 
       anAttribs[anIter++] = None;
 
       aVis = glXChooseVisual (aDisp, scr, anAttribs);
+
+      // in case of failure try without stereo if any
+      if (aVis == NULL && theCaps->contextStereo)
+      {
+        TCollection_ExtendedString aMsg ("OpenGl_Window::CreateWindow: "
+                                         "glXChooseVisual is unable to find stereo supported pixel format. "
+                                         "Choosing similar non stereo format.");
+        myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
+                                  GL_DEBUG_TYPE_OTHER_ARB,
+                                  0, GL_DEBUG_SEVERITY_HIGH_ARB, aMsg);
+
+        anAttribs[aStereoFlagPos] = None;
+        aVis = glXChooseVisual (aDisp, scr, anAttribs);
+      }
+
       if (aVis == NULL)
       {
         Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: glXChooseVisual failed.");
@@ -479,31 +570,7 @@ OpenGl_Window::OpenGl_Window (const Handle(OpenGl_Display)& theDisplay,
     }
   }
 
-  /*
-  * Le BackDitherProp est utilise pour le clear du background
-  * Pour eviter une difference de couleurs avec la couleur choisie
-  * par l'application (XWindow) il faut desactiver le dithering
-  * au dessus de 8 plans.
-  *
-  * Pour le DitherProp:
-  * On cherchera a activer le Dithering que si le Visual a au moins
-  * 8 plans pour le GLX_RED_SIZE. Le test est plus sur car on peut
-  * avoir une profondeur superieure a 12 mais avoir besoin du dithering.
-  * (Carte Impact avec GLX_RED_SIZE a 5 par exemple)
-  */
-
-  int aValue;
-  glXGetConfig (aDisp, aVis, GLX_RED_SIZE, &aValue);
-
-  if (myDither)
-    myDither = (aValue < 8);
-
-  if (myBackDither)
-    myBackDither = (aVis->depth <= 8);
-
-  XFree ((char* )aVis);
-
-  myGlContext->Init ((Aspect_Drawable )aWindow, (Aspect_Display )myDisplay->GetDisplay(), (Aspect_RenderingContext )aGContext);
+  myGlContext->Init ((Aspect_Drawable )aWindow, (Aspect_Display )aDisp, (Aspect_RenderingContext )aGContext);
 #endif
   myGlContext->Share (theShareCtx);
 
@@ -516,30 +583,55 @@ OpenGl_Window::OpenGl_Window (const Handle(OpenGl_Display)& theDisplay,
 // =======================================================================
 OpenGl_Window::~OpenGl_Window()
 {
-#if defined(_WIN32)
-  HWND  aWindow   = (HWND  )myGlContext->myWindow;
-  HDC   aWindowDC = (HDC   )myGlContext->myWindowDC;
-  HGLRC aGContext = (HGLRC )myGlContext->myGContext;
+  if (!myOwnGContext
+   ||  myGlContext.IsNull())
+  {
+    myGlContext.Nullify();
+    return;
+  }
+
+  // release "GL" context if it is owned by window
+  // Mesa implementation can fail to destroy GL context if it set for current thread.
+  // It should be safer to unset thread GL context before its destruction.
+#if defined(HAVE_EGL) || defined(__ANDROID__)
+  if ((EGLSurface )myGlContext->myWindow != EGL_NO_SURFACE)
+  {
+    eglDestroySurface ((EGLDisplay )myGlContext->myDisplay,
+                       (EGLSurface )myGlContext->myWindow);
+  }
+#elif defined(_WIN32)
+  HWND  aWindow          = (HWND  )myGlContext->myWindow;
+  HDC   aWindowDC        = (HDC   )myGlContext->myWindowDC;
+  HGLRC aWindowGContext  = (HGLRC )myGlContext->myGContext;
+  HGLRC aThreadGContext  = wglGetCurrentContext();
   myGlContext.Nullify();
 
-  if (myOwnGContext)
+  if (aThreadGContext != NULL)
   {
-    if (wglGetCurrentContext() != NULL)
+    if (aThreadGContext == aWindowGContext)
     {
-      wglDeleteContext (aGContext);
+      wglMakeCurrent (NULL, NULL);
     }
-    ReleaseDC (aWindow, aWindowDC);
+
+    wglDeleteContext (aWindowGContext);
   }
+  ReleaseDC (aWindow, aWindowDC);
 #else
-  Display*    aDisplay  = (Display*    )myGlContext->myDisplay;
-  GLXContext  aGContext = (GLXContext  )myGlContext->myGContext;
+  Display*    aDisplay        = (Display*    )myGlContext->myDisplay;
+  GLXContext  aWindowGContext = (GLXContext  )myGlContext->myGContext;
+  GLXContext  aThreadGContext = glXGetCurrentContext();
   myGlContext.Nullify();
 
-  if (aDisplay != NULL && myOwnGContext)
+  if (aDisplay != NULL)
   {
+    if (aThreadGContext == aWindowGContext)
+    {
+      glXMakeCurrent (aDisplay, None, NULL);
+    }
+
     // FSXXX sync necessary if non-direct rendering
     glXWaitGL();
-    glXDestroyContext (aDisplay, aGContext);
+    glXDestroyContext (aDisplay, aWindowGContext);
   }
 #endif
 }
@@ -563,18 +655,20 @@ Standard_Boolean OpenGl_Window::Activate()
 // =======================================================================
 void OpenGl_Window::Resize (const CALL_DEF_WINDOW& theCWindow)
 {
-  DISPLAY* aDisp = (DISPLAY* )myDisplay->GetDisplay();
+#if !defined(_WIN32) && !defined(HAVE_EGL) && !defined(__ANDROID__)
+  Display* aDisp = (Display* )myGlContext->myDisplay;
   if (aDisp == NULL)
     return;
+#endif
 
   // If the size is not changed - do nothing
   if ((myWidth == theCWindow.dx) && (myHeight == theCWindow.dy))
     return;
 
-  myWidth  = (Standard_Integer )theCWindow.dx;
-  myHeight = (Standard_Integer )theCWindow.dy;
+  myWidth  = theCWindow.dx;
+  myHeight = theCWindow.dy;
 
-#if !defined(_WIN32)
+#if !defined(_WIN32) && !defined(HAVE_EGL) && !defined(__ANDROID__)
   XResizeWindow (aDisp, myGlContext->myWindow, (unsigned int )myWidth, (unsigned int )myHeight);
   XSync (aDisp, False);
 #endif
@@ -595,16 +689,30 @@ void OpenGl_Window::ReadDepths (const Standard_Integer theX,     const Standard_
   if (theDepths == NULL || !Activate())
     return;
 
-  glMatrixMode (GL_PROJECTION);
-  glLoadIdentity();
-  gluOrtho2D (0.0, (GLdouble )myWidth, 0.0, (GLdouble )myHeight);
-  glMatrixMode (GL_MODELVIEW);
-  glLoadIdentity();
+  OpenGl_Mat4 aProjectMat;
+  OpenGl_Utils::Ortho2D<Standard_ShortReal> (aProjectMat,
+    0.f, static_cast<GLfloat> (myWidth), 0.f, static_cast<GLfloat> (myHeight));
+
+  myGlContext->WorldViewState.Push();
+  myGlContext->ProjectionState.Push();
+
+  myGlContext->WorldViewState.SetIdentity();
+  myGlContext->ProjectionState.SetCurrent (aProjectMat);
 
+  myGlContext->ApplyProjectionMatrix();
+  myGlContext->ApplyWorldViewMatrix();
+
+#if !defined(GL_ES_VERSION_2_0)
   glRasterPos2i (theX, theY);
   DisableFeatures();
   glReadPixels (theX, theY, theWidth, theHeight, GL_DEPTH_COMPONENT, GL_FLOAT, theDepths);
   EnableFeatures();
+#endif
+
+  myGlContext->WorldViewState.Pop();
+  myGlContext->ProjectionState.Pop();
+
+  myGlContext->ApplyProjectionMatrix();
 }
 
 // =======================================================================
@@ -631,7 +739,10 @@ void OpenGl_Window::Init()
   if (!Activate())
     return;
 
-#if defined(_WIN32)
+#if defined(HAVE_EGL) || defined(__ANDROID__)
+  eglQuerySurface ((EGLDisplay )myGlContext->myDisplay, (EGLSurface )myGlContext->myWindow, EGL_WIDTH,  &myWidth);
+  eglQuerySurface ((EGLDisplay )myGlContext->myDisplay, (EGLSurface )myGlContext->myWindow, EGL_HEIGHT, &myHeight);
+#elif defined(_WIN32)
   RECT cr;
   GetClientRect ((HWND )myGlContext->myWindow, &cr);
   myWidth  = cr.right - cr.left;
@@ -642,54 +753,30 @@ void OpenGl_Window::Init()
   unsigned int aDummyU;
   unsigned int aNewWidth  = 0;
   unsigned int aNewHeight = 0;
-  DISPLAY* aDisp = (DISPLAY* )myDisplay->GetDisplay();
+  Display* aDisp = (Display* )myGlContext->myDisplay;
   XGetGeometry (aDisp, myGlContext->myWindow, &aRootWin, &aDummy, &aDummy, &aNewWidth, &aNewHeight, &aDummyU, &aDummyU);
   myWidth  = aNewWidth;
   myHeight = aNewHeight;
 #endif
 
-  glMatrixMode (GL_MODELVIEW);
-  glViewport (0, 0, myWidth, myHeight);
-
+  glDisable (GL_DITHER);
   glDisable (GL_SCISSOR_TEST);
+  glViewport (0, 0, myWidth, myHeight);
+#if !defined(GL_ES_VERSION_2_0)
+  glMatrixMode (GL_MODELVIEW);
   glDrawBuffer (GL_BACK);
+#endif
 }
 
 #endif // !__APPLE__
 
-// =======================================================================
-// function : EnablePolygonOffset
-// purpose  : call_subr_enable_polygon_offset
-// =======================================================================
-void OpenGl_Window::EnablePolygonOffset() const
-{
-  Standard_ShortReal aFactor, aUnits;
-  myDisplay->PolygonOffset (aFactor, aUnits);
-  glPolygonOffset (aFactor, aUnits);
-  glEnable (GL_POLYGON_OFFSET_FILL);
-}
-
-// =======================================================================
-// function : DisablePolygonOffset
-// purpose  : call_subr_disable_polygon_offset
-// =======================================================================
-void OpenGl_Window::DisablePolygonOffset() const
-{
-  glDisable (GL_POLYGON_OFFSET_FILL);
-}
-
 // =======================================================================
 // function : EnableFeatures
 // purpose  :
 // =======================================================================
 void OpenGl_Window::EnableFeatures() const
 {
-  /*glPixelTransferi (GL_MAP_COLOR, GL_TRUE);*/
-
-  if (myDither)
-    glEnable (GL_DITHER);
-  else
-    glDisable (GL_DITHER);
+  //
 }
 
 // =======================================================================
@@ -698,24 +785,28 @@ void OpenGl_Window::EnableFeatures() const
 // =======================================================================
 void OpenGl_Window::DisableFeatures() const
 {
-  glDisable (GL_DITHER);
+#if !defined(GL_ES_VERSION_2_0)
   glPixelTransferi (GL_MAP_COLOR, GL_FALSE);
+#endif
 
   /*
   * Disable stuff that's likely to slow down glDrawPixels.
   * (Omit as much of this as possible, when you know in advance
   * that the OpenGL state will already be set correctly.)
   */
-  glDisable(GL_ALPHA_TEST);
+  glDisable(GL_DITHER);
   glDisable(GL_BLEND);
   glDisable(GL_DEPTH_TEST);
-  glDisable(GL_FOG);
-  glDisable(GL_LIGHTING);
+  glDisable(GL_TEXTURE_2D);
+  glDisable(GL_STENCIL_TEST);
 
+#if !defined(GL_ES_VERSION_2_0)
+  glDisable(GL_LIGHTING);
+  glDisable(GL_ALPHA_TEST);
+  glDisable(GL_FOG);
   glDisable(GL_LOGIC_OP);
-  glDisable(GL_STENCIL_TEST);
   glDisable(GL_TEXTURE_1D);
-  glDisable(GL_TEXTURE_2D);
+
   glPixelTransferi(GL_MAP_COLOR, GL_FALSE);
   glPixelTransferi(GL_RED_SCALE, 1);
   glPixelTransferi(GL_RED_BIAS, 0);
@@ -733,19 +824,32 @@ void OpenGl_Window::DisableFeatures() const
   * code for simplicity.)
   */
 
+  if ((myGlContext->myGlVerMajor >= 1) && (myGlContext->myGlVerMinor >= 2))
+  {
 #ifdef GL_EXT_convolution
-  glDisable(GL_CONVOLUTION_1D_EXT);
-  glDisable(GL_CONVOLUTION_2D_EXT);
-  glDisable(GL_SEPARABLE_2D_EXT);
+    if (myGlContext->CheckExtension ("GL_CONVOLUTION_1D_EXT"))
+      glDisable(GL_CONVOLUTION_1D_EXT);
+
+    if (myGlContext->CheckExtension ("GL_CONVOLUTION_2D_EXT"))
+      glDisable(GL_CONVOLUTION_2D_EXT);
+
+    if (myGlContext->CheckExtension ("GL_SEPARABLE_2D_EXT"))
+      glDisable(GL_SEPARABLE_2D_EXT);
 #endif
 
 #ifdef GL_EXT_histogram
-  glDisable(GL_HISTOGRAM_EXT);
-  glDisable(GL_MINMAX_EXT);
+    if (myGlContext->CheckExtension ("GL_SEPARABLE_2D_EXT"))
+      glDisable(GL_HISTOGRAM_EXT);
+
+    if (myGlContext->CheckExtension ("GL_MINMAX_EXT"))
+      glDisable(GL_MINMAX_EXT);
 #endif
 
 #ifdef GL_EXT_texture3D
-  glDisable(GL_TEXTURE_3D_EXT);
+    if (myGlContext->CheckExtension ("GL_TEXTURE_3D_EXT"))
+      glDisable(GL_TEXTURE_3D_EXT);
+#endif
+  }
 #endif
 }
 
@@ -755,7 +859,9 @@ void OpenGl_Window::DisableFeatures() const
 // =======================================================================
 void OpenGl_Window::MakeFrontBufCurrent() const
 {
+#if !defined(GL_ES_VERSION_2_0)
   glDrawBuffer (GL_FRONT);
+#endif
 }
 
 // =======================================================================
@@ -764,23 +870,7 @@ void OpenGl_Window::MakeFrontBufCurrent() const
 // =======================================================================
 void OpenGl_Window::MakeBackBufCurrent() const
 {
+#if !defined(GL_ES_VERSION_2_0)
   glDrawBuffer (GL_BACK);
-}
-
-// =======================================================================
-// function : MakeFrontAndBackBufCurrent
-// purpose  : TelMakeFrontAndBackBufCurrent
-// =======================================================================
-void OpenGl_Window::MakeFrontAndBackBufCurrent() const
-{
-  glDrawBuffer (GL_FRONT_AND_BACK);
-}
-
-// =======================================================================
-// function : GetGContext
-// purpose  :
-// =======================================================================
-GLCONTEXT OpenGl_Window::GetGContext() const
-{
-  return (GLCONTEXT )myGlContext->myGContext;
+#endif
 }